Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cable): reset a silent Harness Pro once, then ask for a replug; bundle the Pro's own logs (#1713)

0xdiego25c84d2bc2e7ab
diff --git a/cli/src/cable/boardReset.spec.ts b/cli/src/cable/boardReset.spec.ts
new file mode 100644
index 000000000..0544db51d
--- /dev/null
+++ b/cli/src/cable/boardReset.spec.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { resetBoard } from './boardReset.js'
+
+describe('resetting a board over its cable', () => {
+ it('holds RTS with DTR low for 200 ms, then lets go: the pulse esptool calls a hard reset', async () => {
+ const run = vi.fn(async () => ({ stdout: '', stderr: '' }))
+ expect(await resetBoard('/dev/cu.usbmodem143101', { platform: 'darwin', run })).toBe(true)
+ // TIOCMSET is _IOW('t', 109, int) on macOS; TIOCM_RTS = 0x004.
+ expect(run).toHaveBeenCalledWith('perl', ['-e', expect.any(String), '/dev/cu.usbmodem143101', '0x8004746d', '4:200', '0:200'], { timeout: 5000 })
+ run.mockClear()
+ expect(await resetBoard('/dev/ttyACM0', { platform: 'linux', run })).toBe(true)
+ expect(run).toHaveBeenCalledWith('perl', ['-e', expect.any(String), '/dev/ttyACM0', '0x5418', '4:200', '0:200'], { timeout: 5000 })
+ })
+
+ it('says it could not, and runs nothing, where there is no way to set the lines', async () => {
+ const run = vi.fn(async () => ({ stdout: '', stderr: '' }))
+ expect(await resetBoard('COM3', { platform: 'win32', run })).toBe(false)
+ expect(run).not.toHaveBeenCalled()
+ // No perl on the PATH: the failed spawn is a "no", never a throw.
+ const missing = vi.fn(async () => { throw Object.assign(new Error('spawn perl ENOENT'), { code: 'ENOENT' }) })
+ expect(await resetBoard('/dev/cu.usbmodem1', { platform: 'darwin', run: missing })).toBe(false)
+ })
+
+ // Windows has no /dev/null tty to refuse the lines, and the reset is never attempted there (the case above).
+ it.skipIf(process.platform === 'win32')('is a script the real perl runs, and a port that refuses the lines is a "no"', async () => {
+ // /dev/null opens but is no tty, so the ioctl fails: exit 3 says the script parsed and got as far as the
+ // first TIOCMSET (a syntax error would be 255, a failed open 2), and it still comes back as a plain "no".
+ let code: unknown
+ const run = async (file: string, args: string[], options: { timeout: number }) => {
+ try { return await promisify(execFile)(file, args, options) } catch (error) { code = (error as { code?: unknown }).code; throw error }
+ }
+ expect(await resetBoard('/dev/null', { platform: process.platform, run })).toBe(false)
+ expect(code).toBe(3)
+ })
+})
diff --git a/cli/src/cable/boardReset.ts b/cli/src/cable/boardReset.ts
new file mode 100644
index 000000000..df228b6de
--- /dev/null
+++ b/cli/src/cable/boardReset.ts
@@ -0,0 +1,33 @@
+// Reset a board over its USB cable, the way esptool's hard reset does.
+//
+// A user's Harness Pro started beside a booting Mac sent nothing for days at a time (20-26 Oct): no greeting, no
+// console text, and a reopen of the port did not bring it back, only a replug did. The USB-Serial/JTAG peripheral
+// resets the chip when the host raises RTS while DTR is low, which a person cannot do but the daemon can.
+//
+// Node cannot set a tty's modem lines (no ioctl), and macOS ships perl, so a few lines of it do the TIOCMSET calls.
+// Windows has neither the ioctl nor perl here; it is told "no" and the caller falls back to asking the person.
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+
+type Run = (file: string, args: string[], options: { timeout: number }) => Promise<unknown>
+
+/** TIOCMSET: _IOW('t', 109, int) on macOS, 0x5418 on Linux. */
+const TIOCMSET: Partial<Record<NodeJS.Platform, string>> = { darwin: '0x8004746d', linux: '0x5418' }
+/** RTS high with DTR low holds the chip in reset; both low lets it boot normally (DTR high would ask for the ROM's download mode). */
+const PULSE = ['4:200', '0:200']
+// Path, request, then `bits:ms` steps. The port is opened without blocking on carrier and without becoming the
+// daemon's controlling terminal (serial.ts says why that matters).
+const SCRIPT = 'use Fcntl;sysopen(my $f,shift,O_RDWR|O_NONBLOCK|O_NOCTTY) or exit 2;my $r=hex shift;'
+ + 'for(@ARGV){my($b,$ms)=split /:/;ioctl($f,$r,pack("i",$b)) or exit 3;select(undef,undef,undef,$ms/1000)}'
+
+/** True when the pulse was sent. Never throws: a board that cannot be reset is an ordinary answer. */
+export async function resetBoard(path: string, deps: { platform?: NodeJS.Platform; run?: Run } = {}): Promise<boolean> {
+ const request = TIOCMSET[deps.platform ?? process.platform]
+ if (!request) return false
+ try {
+ await (deps.run ?? promisify(execFile))('perl', ['-e', SCRIPT, path, request, ...PULSE], { timeout: 5000 })
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.ts
index 84e0461d0..499e41381 100644
--- a/cli/src/cable/cableFleet.spec.ts
+++ b/cli/src/cable/cableFleet.spec.ts
@@ -1,5 +1,5 @@
import { spawn } from 'node:child_process'
-import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
@@ -743,3 +743,176 @@ describe('macOS USB inventory', () => {
})
})
})
+
+describe('a Harness Pro that is silent from the moment its port opens', () => {
+ // A user's Pro, started beside a booting Mac, sent nothing at all on 20-26 Oct: the daemon wrote it off as
+ // "not a Harness dial" and the Pro sat on its Home screen until it was replugged. This session stands in for
+ // CableSession's 20 s silence (tested there) so each step is one call.
+ class Quiet {
+ static made: Quiet[] = []
+ isConnected = false
+ wantsStats = false
+ constructor(readonly host: CableHost) { Quiet.made.push(this) }
+ start() {}
+ async stop() {}
+ petDial() { return { supported: false, held: [], sending: null, errors: {} } }
+ silent() { this.host.onForeignPort?.('/dev/pro', 'silent') }
+ }
+ const PRO = 'E8:F6:0A:E7:63:7D'
+ const NOTICE = 'Not answering — unplug and replug'
+ function setup(opts: { verdicts?: DialVerdicts; session?: string; serial?: string } = {}) {
+ Quiet.made = []
+ const f = fixture()
+ const port = { ...device('/dev/pro', opts.serial ?? PRO), session: opts.session ?? '7' }
+ f.setPorts([port])
+ const reset = vi.fn(async () => true)
+ const verdicts = opts.verdicts ?? new DialVerdicts()
+ const fleet = new CableFleet(Quiet as unknown as typeof CableSession, f.host, f.logs, DialLog, { ...f.options, verdicts, watchEveryMs: 0, reset })
+ const scan = async () => { await (fleet as unknown as { scan(): Promise<void> }).scan(); await new Promise(r => setTimeout(r, 5)) }
+ const rows = () => (vi.mocked(f.host.onDialStatus!).mock.calls.at(-1)?.[0].devices ?? [])
+ return { f, fleet, port, reset, verdicts, scan, rows }
+ }
+
+ it('is reset over the cable once, watched again, and only then is the person told', async () => {
+ const s = setup()
+ s.verdicts.markDial(s.port, 'pro')
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ Quiet.made[0].silent()
+ await vi.waitFor(() => expect(s.reset).toHaveBeenCalledWith('/dev/pro'))
+ // Looked at again, by a fresh session, after the reset.
+ await vi.waitFor(async () => { await s.scan(); expect(Quiet.made).toHaveLength(2) })
+ expect(s.rows()).toEqual([])
+ Quiet.made[1].silent()
+ await vi.waitFor(() => expect(s.rows()).toEqual([{ id: PRO, attached: false, board: 'pro', problem: NOTICE }]))
+ // Exactly one reset, and the port is then left alone for this attachment.
+ for (let i = 0; i < 3; i++) await s.scan()
+ expect(s.reset).toHaveBeenCalledTimes(1)
+ expect(Quiet.made).toHaveLength(2)
+ expect(s.verdicts.isForeign(s.port)).toBe(false)
+ // Replugged: a new attachment is looked at again, and the notice goes.
+ s.f.setPorts([{ ...s.port, session: '8' }])
+ await vi.waitFor(async () => { await s.scan(); expect(Quiet.made).toHaveLength(3) })
+ expect(s.rows()).toEqual([])
+ } finally { await s.fleet.stop() }
+ })
+
+ it('is told to the person at once where the board cannot be reset', async () => {
+ const s = setup()
+ s.verdicts.markDial(s.port, 'pro')
+ s.reset.mockResolvedValue(false)
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ Quiet.made[0].silent()
+ await vi.waitFor(() => expect(s.rows()).toEqual([{ id: PRO, attached: false, board: 'pro', problem: NOTICE }]))
+ for (let i = 0; i < 3; i++) await s.scan()
+ expect(Quiet.made).toHaveLength(1)
+ } finally { await s.fleet.stop() }
+ })
+
+ it('is never reset when its port has no USB serial, since only a serial says which board it is: notice only', async () => {
+ const s = setup()
+ const nameless = { path: '/dev/pro', vendorId: 0x303a, productId: 0x1001, session: '7' }
+ s.f.setPorts([nameless])
+ s.verdicts.markDial(nameless, 'pro')
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ Quiet.made[0].silent()
+ await vi.waitFor(() => expect(s.rows()).toEqual([{ id: '/dev/pro', attached: false, board: 'pro', problem: NOTICE }]))
+ expect(s.reset).not.toHaveBeenCalled()
+ } finally { await s.fleet.stop() }
+ })
+
+ it('is not reset when the daemon stops or USB passes to another account just before the reset', async () => {
+ for (const change of ['usb', 'stop'] as const) {
+ const s = setup()
+ s.verdicts.markDial(s.port, 'pro')
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ // The change lands while the silent session is being stopped, after the decision to reset.
+ Quiet.made[0].stop = async () => {
+ if (change === 'usb') s.f.options.canUseUsb.mockReturnValue(false)
+ else void s.fleet.stop()
+ }
+ Quiet.made[0].silent()
+ await new Promise(r => setTimeout(r, 50))
+ expect(s.reset).not.toHaveBeenCalled()
+ } finally { await s.fleet.stop() }
+ }
+ })
+
+ it('withdraws a notice it has shown when the second silent round is given up, and says so to the window', async () => {
+ const s = setup()
+ s.verdicts.markDial(s.port, 'pro')
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ Quiet.made[0].silent()
+ await vi.waitFor(async () => { await s.scan(); expect(Quiet.made).toHaveLength(2) })
+ // Stopping the second, still silent, session reports it gone, which publishes the notice; then USB passes
+ // to another account before the notice is settled.
+ Quiet.made[1].stop = async () => {
+ Quiet.made[1].host.onDialStatus?.({ attached: false })
+ s.f.options.canUseUsb.mockReturnValue(false)
+ }
+ Quiet.made[1].silent()
+ await vi.waitFor(() => expect(vi.mocked(s.f.host.onDialStatus!).mock.calls.some(([st]) => st.devices?.some(d => d.problem))).toBe(true))
+ await new Promise(r => setTimeout(r, 50))
+ expect(s.rows()).toEqual([])
+ } finally { await s.fleet.stop() }
+ })
+
+ it('withdraws its notice when USB passes to another account at this computer', async () => {
+ const s = setup()
+ s.verdicts.markDial(s.port, 'pro')
+ s.reset.mockResolvedValue(false)
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ Quiet.made[0].silent()
+ await vi.waitFor(() => expect(s.rows()).toEqual([{ id: PRO, attached: false, board: 'pro', problem: NOTICE }]))
+ s.f.options.canUseUsb.mockReturnValue(false)
+ await s.scan()
+ expect(s.rows()).toEqual([])
+ } finally { await s.fleet.stop() }
+ })
+
+ it('never resets a silent board this computer has not seen greet as a Harness Pro', async () => {
+ for (const known of ['nothing', 'round dial'] as const) {
+ const s = setup({ serial: 'CC:03' })
+ if (known === 'round dial') s.verdicts.markDial(s.port)
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ Quiet.made[0].silent()
+ await vi.waitFor(() => expect(s.f.host.log).toHaveBeenCalledWith(expect.stringContaining('is not a Harness dial (silent)')))
+ await s.scan()
+ expect(s.reset).not.toHaveBeenCalled()
+ expect(s.rows().some(r => r.problem)).toBe(false)
+ } finally { await s.fleet.stop() }
+ }
+ })
+
+ it('is known from its own dial log when it greeted before the record kept the board, so a verdict does not pin it', async () => {
+ // This user's Pro: last greeted a daemon older than the board record, then judged foreign on this very
+ // attachment, which held for 6 h and across every restart.
+ const file = join(mkdtempSync(join(tmpdir(), 'fleet-verdicts-')), 'dial-ports.json')
+ const pinned = new DialVerdicts(file)
+ const s = setup({ verdicts: pinned })
+ pinned.markForeign(s.port)
+ const folder = join(s.f.logs, 'usb-E8-F6-0A-E7-63-7D')
+ mkdirSync(folder)
+ writeFileSync(join(folder, 'dial-20261022.log'), '2026-10-22T09:49:09.860Z [daemon] dial E8:F6:0A:E7:63:7D on fw 0.1.13 proto 3 hw harness-pro board pro caps swarms\n')
+ try {
+ s.fleet.start()
+ await vi.waitFor(() => expect(Quiet.made).toHaveLength(1))
+ expect(new DialVerdicts(file).isPro(s.port)).toBe(true)
+ Quiet.made[0].silent()
+ await vi.waitFor(() => expect(s.reset).toHaveBeenCalledTimes(1))
+ } finally { await s.fleet.stop() }
+ })
+})
diff --git a/cli/src/cable/cableFleet.ts b/cli/src/cable/cableFleet.ts
index 3d3c13ad2..083bb50b9 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 { readFileSync } from 'node:fs'
+import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
+import { resetBoard } from './boardReset.js'
import { DialVerdicts } from './dialPortVerdicts.js'
import { findDialPorts, portInUse, SerialLink, type DialPort } from './serial.js'
import { isUsbConsoleUser } from './usbConsoleUser.js'
@@ -12,6 +13,8 @@ type Surface = Pick<CableSession, keyof CableSession>
type SessionConstructor = new (host: CableHost, log: DialLog, open: PortOpener) => Surface
type Entry = { port: DialPort; session: Surface; attached: boolean; status: DialStatus; faults: number[] }
type OpenPort = (path: string, onData: (chunk: Buffer) => void, onClosed: (why: string) => void) => Promise<CablePort>
+/** A known Harness Pro that has been silent since its port opened: being reset, reset and looked at again, or the person told. */
+type Unanswered = { port: DialPort; stage: 'resetting' | 'reset' | 'told' }
export interface CableFleetOptions {
discover?: () => Promise<DialPort[]>
open?: OpenPort
@@ -31,6 +34,8 @@ export interface CableFleetOptions {
faults?: ReadonlySet<string>
/** The first wait before a dropped dial's port is looked at again (tests shorten it). */
dropBackoffMs?: number
+ /** Reset a board over its cable; false when it cannot be done here (boardReset.ts). */
+ reset?: (path: string) => Promise<boolean>
}
/** Faults within a minute that drop one dial; a hostile stream drops it at once. */
@@ -40,6 +45,20 @@ const FAULTS_TO_DROP = 5
const DROP_BACKOFF_MS = 5_000
const DROP_BACKOFF_MAX_MS = 60_000
const DROP_FORGIVEN_MS = 300_000
+/** Shown on a silent Harness Pro's row once a reset has not brought it back: short, the card gives it about two lines. */
+const UNANSWERED_NOTICE = 'Not answering — unplug and replug'
+/** A Harness Pro's greeting as the daemon writes it into that device's dial log (cableSession.ts, dialLog.ts). */
+const PRO_GREETING = /\] dial \S+ (?:back )?on fw \S+ .*\bboard pro\b/
+
+/** The folder of one device's dial logs, under the logs directory. */
+const logFolder = (id: string) => `usb-${id.replace(/[^a-zA-Z0-9_-]/g, '-')}`
+
+// ponytail: reads the whole of each kept day (at most 7 x 20 MB) once per board per process; a greeting index if that ever shows up.
+function greetedAsPro(folder: string): boolean {
+ try {
+ return readdirSync(folder).filter(name => /^dial-\d{8}\.log$/.test(name)).some(name => PRO_GREETING.test(readFileSync(join(folder, name), 'utf8')))
+ } catch { return false }
+}
/**
* Discovery for the end-to-end suite's dials, pseudo-terminals (e2e/harness/fakeDial.ts) named by
@@ -81,6 +100,11 @@ export class CableFleet {
private readonly watchEveryMs: number
/** Dials dropped for their faults, by id: when their port is looked at again, and the wait after that. */
private readonly dropped = new Map<string, { until: number; backoffMs: number; at: number }>()
+ private readonly reset: (path: string) => Promise<boolean>
+ /** Known Harness Pros silent since their port opened, by id, for as long as that USB attachment lasts. */
+ private readonly unanswered = new Map<string, Unanswered>()
+ /** Whether a board's own dial logs show it greeting as a Harness Pro, read once per board. */
+ private readonly proInLogs = new Map<string, boolean>()
constructor(private readonly Session: SessionConstructor, private readonly host: CableHost,
private readonly logs: string, private readonly Log: typeof DialLog,
@@ -92,6 +116,7 @@ export class CableFleet {
this.inUse = options.inUse ?? portInUse
this.canUseUsb = options.canUseUsb ?? isUsbConsoleUser
this.watchEveryMs = options.watchEveryMs ?? 8_000
+ this.reset = options.reset ?? resetBoard
}
get isConnected(): boolean { return [...this.entries.values()].some(e => e.session.isConnected) }
@@ -151,7 +176,8 @@ export class CableFleet {
if (!this.waitingForConsole) this.host.log('cable: USB belongs to the account at this computer\'s screen — releasing this connection')
this.waitingForConsole = true
await Promise.allSettled([...this.entries.values()].map(entry => entry.session.stop()))
- if (this.entries.size) { this.entries.clear(); this.publish() }
+ // A silent Pro's notice is this account's to see, and its board no longer ours to reset.
+ if (this.entries.size || this.unanswered.size) { this.entries.clear(); this.unanswered.clear(); this.publish() }
return
}
this.waitingForConsole = false
@@ -162,7 +188,7 @@ export class CableFleet {
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))) continue
+ if (this.verdicts.isForeign(port) && !this.knownPro(port) && !(await this.workedOn(port))) continue
present.set(serial || port.path, port)
}
let removed = false
@@ -172,12 +198,22 @@ export class CableFleet {
this.entries.delete(id)
removed = true
}
+ // A silent Pro is left alone for as long as its USB attachment lasts: unplugged, or plugged back in, it is
+ // a new attachment and looked at afresh.
+ for (const [id, held] of this.unanswered) {
+ const now = present.get(id)
+ if (now?.path === held.port.path && now.session === held.port.session) continue
+ this.unanswered.delete(id)
+ removed = true
+ }
// After the deletes, not inside them: a publish mid-loop would name a device this computer has
// already stopped talking to.
if (removed) this.publish()
if (this.stopped) return
for (const [id, port] of present) {
if (this.entries.has(id)) continue
+ // Being reset, or the person has been asked to replug it: not opened. Once reset, it is looked at again.
+ if (this.unanswered.has(id) && this.unanswered.get(id)?.stage !== 'reset') continue
// Dropped for its faults a moment ago: its port is left alone until its wait is over.
if ((this.dropped.get(id)?.until ?? 0) > Date.now()) continue
// A board somebody else has open is somebody's work in progress (a flash, a monitor, a console).
@@ -191,7 +227,8 @@ export class CableFleet {
if (this.stopped) return
const entry: Entry = { port, attached: false, status: { attached: false }, session: undefined!, faults: [] }
const attached = () => {
- this.verdicts.markDial(port)
+ this.verdicts.markDial(port, entry.status.board)
+ this.unanswered.delete(id)
if (entry.attached) return
const first = ![...this.entries.values()].some(e => e.attached)
entry.attached = true
@@ -214,6 +251,7 @@ export class CableFleet {
if (key === 'onDialAttached') return attached
if (key === 'onDialGone') return gone
if (key === 'onForeignPort') return (path: string, why: string) => {
+ if (why === 'silent' && this.knownPro(port)) return this.silentPro(id, entry)
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.
@@ -244,12 +282,64 @@ export class CableFleet {
}
return opened
}
- entry.session = new this.Session(host, new this.Log(join(this.logs, `usb-${id.replace(/[^a-zA-Z0-9_-]/g, '-')}`)), opener)
+ entry.session = new this.Session(host, new this.Log(join(this.logs, logFolder(id))), opener)
this.entries.set(id, entry)
entry.session.start()
}
}
+ /**
+ * Did this board greet as a Harness Pro? Its port record says so, or, for a Pro that last greeted a daemon older
+ * than the record's board (a user's Pro, 20-26 Oct), its own dial log does; that is then recorded. Nothing else is
+ * ever reset: every ESP32 shares one USB id, and its serial is only the chip's MAC.
+ */
+ private knownPro(port: DialPort): boolean {
+ if (this.verdicts.isPro(port)) return true
+ const id = port.serialNumber?.toUpperCase() || port.path
+ if (!this.proInLogs.has(id)) this.proInLogs.set(id, greetedAsPro(join(this.logs, logFolder(id))))
+ if (!this.proInLogs.get(id)) return false
+ this.verdicts.markDial(port, 'pro')
+ return true
+ }
+
+ /**
+ * A known Harness Pro silent since its port opened. Measured on a user's Pro started beside a booting Mac: nothing
+ * came out at all, a reopen did not help and a replug did. So it is reset over the cable once and looked at again
+ * by a fresh session; silent again, or where it cannot be reset, the person is asked to replug it, on its row, and
+ * the port is left alone until they do. Never written off as foreign: a 6 h verdict is what stranded that Pro.
+ */
+ private silentPro(id: string, entry: Entry): void {
+ const again = this.unanswered.get(id)?.stage === 'reset'
+ const held: Unanswered = { port: entry.port, stage: again ? 'told' : 'resetting' }
+ this.unanswered.set(id, held)
+ // Off this call stack, as onForeignPort's own stop: the session is in the middle of deciding this.
+ // Given up when the port has gone, the daemon is stopping or USB has passed to another account in the meantime:
+ // the next look at the port starts over.
+ // A second round's notice may already be on screen (a stopping session publishes), so withdrawing it is said too.
+ const forget = () => {
+ if (this.unanswered.get(id) !== held) return
+ this.unanswered.delete(id)
+ if (held.stage === 'told') this.publish()
+ }
+ setTimeout(() => void (async () => {
+ if (this.entries.get(id) !== entry) return forget()
+ this.entries.delete(id)
+ await entry.session.stop()
+ if (this.unanswered.get(id) !== held) return
+ if (this.stopped || !this.canUseUsb()) return forget()
+ // Only a USB serial says which board this is; a port without one is told, never reset.
+ if (!again && entry.port.serialNumber && await this.reset(entry.port.path)) {
+ this.host.log(`cable: Harness Pro on ${entry.port.path} is silent — reset it over the cable, looking again [usb ${id}]`)
+ if (this.unanswered.get(id) === held) held.stage = 'reset'
+ return
+ }
+ this.host.log(`cable: Harness Pro on ${entry.port.path} is still silent${again ? ' after a reset' : ' and cannot be reset here'} — asking for a replug [usb ${id}]`)
+ if (this.unanswered.get(id) !== held) return
+ held.stage = 'told'
+ this.publish()
+ })(), 0)
+ }
+
/**
* One dial's session failed, or its far end is flooding the port. The dial alone is dropped — its
* session stopped and its port let go — once it has failed five times in a minute, or at once for a
@@ -283,7 +373,7 @@ export class CableFleet {
* fleet picked one row and discarded the rest.
*/
private publish(): void {
- const devices = [...this.entries.values()].map(e => e.status).filter(s => s.attached || s.settings)
+ const devices = this.devices()
const live = devices.filter(s => s.attached)
const primary = live.find(s => s.updating) ?? live[0]
this.host.onDialStatus?.({ ...(primary ?? { attached: false }), devices })
@@ -291,7 +381,9 @@ export class CableFleet {
/** Every device this computer can see, newest reading. Ordered as they were discovered. */
devices(): DialStatus[] {
- return [...this.entries.values()].map(e => e.status).filter(s => s.attached || s.settings)
+ const told = [...this.unanswered].filter(([, held]) => held.stage === 'told')
+ .map(([id]): DialStatus => ({ id, attached: false, board: 'pro', problem: UNANSWERED_NOTICE }))
+ return [...[...this.entries.values()].map(e => e.status).filter(s => s.attached || s.settings), ...told]
}
/**
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 828f1a8b9..efb04ab5d 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -529,6 +529,8 @@ export interface DialStatus {
/** `hello.board`; "pro" is the square Harness Pro. Absent = a round dial. */
board?: string
updating?: string
+ /** Something the person has to do about this device, in words shown as they are (cableFleet.ts: a silent Harness Pro). */
+ problem?: string
/**
* Every device on this computer, when a fleet is reporting. Present only on the primary status, and
* the primary is one of these rows — the flat fields above repeat it so a window that predates this
diff --git a/cli/src/cable/dialPortVerdicts.spec.ts b/cli/src/cable/dialPortVerdicts.spec.ts
index a173c4625..77fbddb06 100644
--- a/cli/src/cable/dialPortVerdicts.spec.ts
+++ b/cli/src/cable/dialPortVerdicts.spec.ts
@@ -69,4 +69,23 @@ describe('verdicts on USB boards', () => {
next.markForeign(board('2', 'BB:02'))
expect(next.isForeign(board('2', 'BB:02'))).toBe(true)
})
+
+ it('remembers which board greeted, across restarts, so only a known Harness Pro is ever reset', () => {
+ const file = join(mkdtempSync(join(tmpdir(), 'verdicts-')), 'dial-ports.json')
+ const verdicts = new DialVerdicts(file)
+ expect(verdicts.isPro(board('1'))).toBe(false)
+ // A round dial (no board) is a dial, not a Pro.
+ verdicts.markDial(board('1', 'RD:01'))
+ expect(verdicts.isPro(board('1', 'RD:01'))).toBe(false)
+ // A dial recorded before the board was kept learns it on its next greeting.
+ verdicts.markDial(board('1'))
+ verdicts.markDial(board('1'), 'pro')
+ expect(new DialVerdicts(file).isPro(board('2'))).toBe(true)
+ // A later greeting that names no board keeps what is known.
+ new DialVerdicts(file).markDial(board('2'))
+ expect(new DialVerdicts(file).isPro(board('3'))).toBe(true)
+ // A foreign board is never a Pro.
+ verdicts.markForeign(board('1', 'BB:02'))
+ expect(verdicts.isPro(board('1', 'BB:02'))).toBe(false)
+ })
})
diff --git a/cli/src/cable/dialPortVerdicts.ts b/cli/src/cable/dialPortVerdicts.ts
index 0facadcc0..3a4cea9a2 100644
--- a/cli/src/cable/dialPortVerdicts.ts
+++ b/cli/src/cable/dialPortVerdicts.ts
@@ -18,7 +18,8 @@ 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; dial?: true }
+/** `board`: what a dial's greeting named it (`hello.board`), "pro" for a Harness Pro; absent for a round dial. */
+interface Verdict { session?: string; at: number; dial?: true; board?: string }
const keyOf = (port: DialPort) => (port.serialNumber ?? port.path).toUpperCase()
@@ -31,7 +32,7 @@ export class DialVerdicts {
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 } : {}), ...(v.dial === true ? { dial: true as const } : {}) })
+ if (v && typeof v.at === 'number') this.foreign.set(key, { at: v.at, ...(typeof v.session === 'string' ? { session: v.session } : {}), ...(v.dial === true ? { dial: true as const } : {}), ...(typeof v.board === 'string' ? { board: v.board } : {}) })
}
} catch { /* unreadable: start with no opinions, and rewrite it on the next verdict */ }
}
@@ -51,13 +52,21 @@ export class DialVerdicts {
if (this.foreign.delete(keyOf(port))) this.save()
}
- /** This board greeted as a dial: it is one, whatever a later silence looks like. */
- markDial(port: DialPort): void {
- if (this.foreign.get(keyOf(port))?.dial) return
- this.foreign.set(keyOf(port), { at: this.now(), dial: true })
+ /** This board greeted as a dial: it is one, whatever a later silence looks like. `board` is its hello's. */
+ markDial(port: DialPort, board?: string): void {
+ const known = this.foreign.get(keyOf(port))
+ if (known?.dial && (!board || known.board === board)) return
+ const kept = board ?? known?.board
+ this.foreign.set(keyOf(port), { at: this.now(), dial: true, ...(kept ? { board: kept } : {}) })
this.save()
}
+ /** Did this board greet as a Harness Pro? The one board the fleet may reset over the cable (cableFleet.ts). */
+ isPro(port: DialPort): boolean {
+ const known = this.foreign.get(keyOf(port))
+ return known?.dial === true && known.board === 'pro'
+ }
+
markForeign(port: DialPort): void {
if (this.foreign.get(keyOf(port))?.dial) return
this.foreign.set(keyOf(port), { at: this.now(), ...(port.session ? { session: port.session } : {}) })
diff --git a/cli/src/lib/logBundle.spec.ts b/cli/src/lib/logBundle.spec.ts
index 3e6d020d5..d3f331edb 100644
--- a/cli/src/lib/logBundle.spec.ts
+++ b/cli/src/lib/logBundle.spec.ts
@@ -68,6 +68,59 @@ describe('buildLogBundle', () => {
expect(bundleFileName(now)).toBe('harness-logs-20260915-1030.zip')
})
+ it('takes each device\'s own dial logs from its usb-<serial> folder, redacted, within the same week', () => {
+ // The fleet writes one folder per device (cableFleet.ts); a bundle without them left out the Pro's own
+ // console on 20-26 Oct, the one log that says whether it rebooted.
+ const root = mkdtempSync(join(tmpdir(), 'bundle-'))
+ const logs = join(root, 'logs'), pro = join(logs, 'usb-E8-F6-0A-E7-63-7D'), other = join(logs, 'notes')
+ mkdirSync(pro, { recursive: true }); mkdirSync(other)
+ writeFileSync(join(pro, 'dial-20260915.log'), '[daemon] dial E8 on fw 0.1.13 board pro\nsession_token: abcdefgh12345\n')
+ writeFileSync(join(pro, 'dial-20260901.log'), 'too old\n')
+ writeFileSync(join(pro, 'notes.txt'), 'no\n')
+ writeFileSync(join(other, 'dial-20260915.log'), 'not a device folder\n')
+ const { zip, included } = buildLogBundle({ logsDir: logs, dataDir: root, now: new Date(2026, 8, 15, 10, 30), version: '0', redact: redactSecretsInText })
+ const files = readZip(zip)
+ expect([...files.keys()]).toEqual(['README.txt', 'logs/usb-E8-F6-0A-E7-63-7D/dial-20260915.log'])
+ expect(files.get('logs/usb-E8-F6-0A-E7-63-7D/dial-20260915.log')?.toString()).toBe('[daemon] dial E8 on fw 0.1.13 board pro\nsession_token: <redacted>\n')
+ expect(included).toEqual(['usb-E8-F6-0A-E7-63-7D/dial-20260915.log'])
+ })
+
+ it('caps the devices\' dial logs, newest first, so a desk of devices cannot make the bundle huge', () => {
+ const root = mkdtempSync(join(tmpdir(), 'bundle-'))
+ const logs = join(root, 'logs'), a = join(logs, 'usb-AA'), b = join(logs, 'usb-BB')
+ mkdirSync(a, { recursive: true }); mkdirSync(b)
+ writeFileSync(join(a, 'dial-20260915.log'), 'a'.repeat(40))
+ writeFileSync(join(b, 'dial-20260914.log'), 'b'.repeat(40))
+ writeFileSync(join(a, 'dial-20260913.log'), 'c'.repeat(40))
+ writeFileSync(join(logs, 'app-20260913.log'), 'the app log is not capped\n')
+ const { zip, included } = buildLogBundle({ logsDir: logs, dataDir: root, now: new Date(2026, 8, 15, 10, 30), version: '0', redact: (t) => t, deviceLogCapBytes: 100 })
+ expect([...readZip(zip).keys()]).toEqual(['README.txt', 'logs/app-20260913.log', 'logs/usb-AA/dial-20260915.log', 'logs/usb-BB/dial-20260914.log'])
+ expect(included).toContain('usb-AA/dial-20260913.log (left out to keep the bundle small)')
+ })
+
+ it('keeps every device\'s newest day, as its tail when that day alone is over the cap, then older days while there is room', () => {
+ // The reviewer's case: dialLog caps a day at 20 MB and then writes one more line, so a newest day can be 20 MB + 90 B.
+ // Counting whole files left that day out, and every older day after it.
+ const root = mkdtempSync(join(tmpdir(), 'bundle-'))
+ const logs = join(root, 'logs'), big = join(logs, 'usb-AA'), small = join(logs, 'usb-BB')
+ mkdirSync(big, { recursive: true }); mkdirSync(small)
+ const cap = 20 * 1024 * 1024
+ writeFileSync(join(big, 'dial-20260915.log'), 'x'.repeat(cap) + 'y'.repeat(89) + '\n')
+ writeFileSync(join(big, 'dial-20260914.log'), 'o'.repeat(1024))
+ writeFileSync(join(small, 'dial-20260913.log'), 'the other device\n')
+ const { zip, included } = buildLogBundle({ logsDir: logs, dataDir: root, now: new Date(2026, 8, 15, 10, 30), version: '0', redact: (t) => t })
+ const files = readZip(zip)
+ expect([...files.keys()]).toEqual(['README.txt', 'logs/usb-AA/dial-20260915.log', 'logs/usb-BB/dial-20260913.log'])
+ const newest = files.get('logs/usb-AA/dial-20260915.log')!
+ expect(newest.length).toBe(cap - 17)
+ expect(newest.toString().endsWith('y'.repeat(89) + '\n')).toBe(true)
+ expect(files.get('logs/usb-BB/dial-20260913.log')?.toString()).toBe('the other device\n')
+ expect(included).toEqual(expect.arrayContaining([
+ `usb-AA/dial-20260915.log (last ${Math.round((cap - 17) / 1024)} KB)`,
+ 'usb-AA/dial-20260914.log (left out to keep the bundle small)',
+ ]))
+ })
+
it('still produces a bundle with a README when there is nothing to include', () => {
const root = mkdtempSync(join(tmpdir(), 'bundle-'))
const { zip, included } = buildLogBundle({ logsDir: join(root, 'none'), dataDir: root, version: '0', redact: (s) => s })
diff --git a/cli/src/lib/logBundle.ts b/cli/src/lib/logBundle.ts
index 2737b5704..62c412cdf 100644
--- a/cli/src/lib/logBundle.ts
+++ b/cli/src/lib/logBundle.ts
@@ -1,5 +1,5 @@
import { readdirSync, readFileSync, statSync, openSync, readSync, closeSync } from 'node:fs'
-import { join } from 'node:path'
+import { basename, join } from 'node:path'
import { writeZip, type ZipEntry } from './zipWriter.js'
/**
@@ -7,7 +7,8 @@ import { writeZip, type ZipEntry } from './zipWriter.js'
* one zip, secrets blanked.
*
* app-YYYYMMDD.log, cli-YYYYMMDD.log the desktop app's own log and its CLI transcript
- * dial-YYYYMMDD.log the dial's console + the daemon's cable events (dialLog.ts)
+ * dial-YYYYMMDD.log the dial's console + the daemon's cable events (dialLog.ts),
+ * and usb-<serial>/dial-YYYYMMDD.log, one folder per device
* harness.log (tail) the daemon's console — the last few MB, which is where today is
* README.txt when, which version, what was included
*
@@ -23,6 +24,8 @@ export interface LogBundleOptions {
days?: number
/** How much of the end of `harness.log` to take. Default 5 MB. */
harnessLogTailBytes?: number
+ /** Most bytes of devices' dial logs, newest day first across every device. Default 20 MB. */
+ deviceLogCapBytes?: number
now?: Date
version: string
/** Free text for the README — `harness status` output, the app's version, anything else known. */
@@ -32,6 +35,7 @@ export interface LogBundleOptions {
}
const DATED = /^(app|cli|dial)-(\d{8})\.log$/
+const DEVICE_DIR = /^usb-[A-Za-z0-9_-]+$/
function ymd(d: Date): string {
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`
@@ -65,14 +69,46 @@ export function buildLogBundle(opts: LogBundleOptions): { zip: Buffer; included:
let names: string[] = []
try { names = readdirSync(opts.logsDir).sort() } catch { /* no logs directory yet */ }
+ // Each device's dial logs are in a folder of their own, `usb-<serial>/` (cableFleet.ts). Reading only the top
+ // level left a user's Harness Pro console out of the bundle sent about it stuck silent (20-26 Oct).
+ names = names.flatMap((name) => {
+ if (!DEVICE_DIR.test(name)) return [name]
+ try { return readdirSync(join(opts.logsDir, name)).sort().filter((f) => f.startsWith('dial-')).map((f) => `${name}/${f}`) } catch { return [] }
+ })
+ // A device's day may be 20 MB (dialLog.ts) and a desk may hold several, so their logs share one cap. Every device keeps
+ // its newest day, as its tail when that does not fit: counting whole files once left out every device's logs when one
+ // day was 20 MB and the line that says so. Older days follow, newest first, while there is room.
+ const cap = opts.deviceLogCapBytes ?? 20 * 1024 * 1024
+ const dayOf = (name: string) => DATED.exec(basename(name))?.[2] ?? ''
+ const sizeOf = (name: string) => { try { return statSync(join(opts.logsDir, name)).size } catch { return 0 } }
+ const deviceDays = names.filter((n) => n.includes('/') && dayOf(n) >= cutoff).sort((x, y) => dayOf(y).localeCompare(dayOf(x)))
+ // deviceDays is newest first; reversed, each folder's newest day is the last one written into the map.
+ const newestPerDevice = [...new Map([...deviceDays].reverse().map((n) => [n.split('/')[0], n])).values()]
+ /** Bytes to take from the end of each device log; 0 leaves it out. */
+ const take = new Map<string, number>()
+ let room = cap
+ newestPerDevice.sort((x, y) => sizeOf(x) - sizeOf(y)).forEach((name, i, all) => {
+ const share = Math.min(sizeOf(name), Math.floor(room / (all.length - i)))
+ take.set(name, share)
+ room -= share
+ })
+ for (const name of deviceDays) {
+ if (take.has(name)) continue
+ const size = sizeOf(name)
+ take.set(name, size <= room ? size : 0)
+ if (size <= room) room -= size
+ }
for (const name of names) {
- const m = DATED.exec(name)
+ const m = DATED.exec(basename(name))
if (!m || m[2] < cutoff) continue
+ const bytes = take.get(name)
+ if (bytes === 0) { included.push(`${name} (left out to keep the bundle small)`); continue }
const path = join(opts.logsDir, name)
try {
- const text = readFileSync(path, 'utf8')
+ const whole = bytes === undefined || bytes >= statSync(path).size
+ const text = whole ? readFileSync(path, 'utf8') : readTail(path, bytes).toString('utf8')
entries.push({ name: `logs/${name}`, data: Buffer.from(opts.redact(text)), mtime: statSync(path).mtime })
- included.push(name)
+ included.push(whole ? name : `${name} (last ${Math.round(bytes / 1024)} KB)`)
} catch { /* unreadable: skipped, said in the README below */ }
}
diff --git a/desktop/lib/devices/devices_controller.dart b/desktop/lib/devices/devices_controller.dart
index ef1045c17..f5da5a9b4 100644
--- a/desktop/lib/devices/devices_controller.dart
+++ b/desktop/lib/devices/devices_controller.dart
@@ -58,7 +58,7 @@ class HarnessDevice {
? 'Updating'
: status.attached
? 'Connected'
- : 'Disconnected';
+ : status.problem ?? 'Disconnected';
HarnessDevice copyWith({
String? name,
@@ -282,6 +282,7 @@ class DevicesController extends ChangeNotifier {
hw: live.hw ?? known?.status.hw,
board: live.board ?? known?.status.board,
updating: live.updating,
+ problem: live.problem,
// A disconnect frame may omit readings. Preserve them for reference,
// but require fresh settings when a connected device greets us again.
settings:
diff --git a/desktop/lib/state/dial_status.dart b/desktop/lib/state/dial_status.dart
index 477e4ecf8..977a99f91 100644
--- a/desktop/lib/state/dial_status.dart
+++ b/desktop/lib/state/dial_status.dart
@@ -169,6 +169,7 @@ class DialStatus {
this.hw,
this.board,
this.updating,
+ this.problem,
});
static const none = DialStatus(attached: false);
@@ -210,6 +211,10 @@ class DialStatus {
/// window, because it is the minute in which people unplug the thing.
final String? updating;
+ /// Something the person has to do about this device, in the daemon's words, shown as they are: a Harness
+ /// Pro that stayed silent after a reset over its cable is asked to be unplugged and plugged back in.
+ final String? problem;
+
/// What to call this robot on screen.
///
/// `hw` is what the firmware detected itself as at boot — `cst816s`, `cst9217+axp2101` — which is a
@@ -246,6 +251,9 @@ class DialStatus {
json['updating'] is String && (json['updating'] as String).isNotEmpty
? json['updating'] as String
: null,
+ problem: json['problem'] is String && (json['problem'] as String).isNotEmpty
+ ? json['problem'] as String
+ : null,
);
}
diff --git a/desktop/test/devices_controller_test.dart b/desktop/test/devices_controller_test.dart
index ece5358b7..2d7d8c2c1 100644
--- a/desktop/test/devices_controller_test.dart
+++ b/desktop/test/devices_controller_test.dart
@@ -60,6 +60,37 @@ void main() {
},
);
+ test('a Harness Pro the daemon could not bring back says what to do on its row, until it answers again', () async {
+ final dial = DialState();
+ final controller = DevicesController(
+ dial: dial,
+ accountId: 'a',
+ sendSettings: (_, _) async => true,
+ );
+ await controller.load();
+ report(dial, [deviceStatus('E8:F6', mac: 'e8:f6')]);
+ final key = controller.devices.single.key;
+ // The daemon's row for a Pro silent since its port opened, after one reset over the cable.
+ report(dial, [
+ DialStatus.fromJson({
+ 'id': 'E8:F6',
+ 'attached': false,
+ 'board': 'pro',
+ 'problem':
+ 'Not answering — unplug and replug',
+ }),
+ ]);
+ expect(controller.devices, hasLength(1));
+ expect(
+ controller.device(key)!.connectionLabel,
+ 'Not answering — unplug and replug',
+ );
+ report(dial, [deviceStatus('E8:F6', mac: 'e8:f6')]);
+ expect(controller.device(key)!.connectionLabel, 'Connected');
+ controller.dispose();
+ dial.dispose();
+ });
+
test('a failed library read cannot overwrite saved devices; retry merges new arrivals', () async {
final storage = _ReadFailureStore();
final dial = DialState();