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): prevent competing macOS account connections (#679)

Dee5f625543af4b
diff --git a/cli/src/cable/__fixtures__/serialClaim.py b/cli/src/cable/__fixtures__/serialClaim.py
new file mode 100644
index 000000000..7dbc3ce7f
--- /dev/null
+++ b/cli/src/cable/__fixtures__/serialClaim.py
@@ -0,0 +1,49 @@
+"""Competing real processes on an owned PTY, including abrupt owner death."""
+import os
+import pty
+import subprocess
+import sys
+
+node, worker = sys.argv[1:]
+master, slave = pty.openpty()
+children = []
+
+def start():
+ child = subprocess.Popen([node, worker, os.ttyname(slave)], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ start_new_session=True)
+ children.append(child)
+ return child
+
+def line(child, expected):
+ actual = child.stdout.readline().strip()
+ assert actual == expected, (actual, child.poll())
+
+try:
+ owner = start()
+ line(owner, 'claimed')
+ contender = start()
+ line(contender, 'busy')
+ assert contender.wait(timeout=3) == 0
+ owner.stdin.write('close\n')
+ owner.stdin.flush()
+ line(owner, 'released')
+ assert owner.wait(timeout=3) == 0
+ replacement = start()
+ line(replacement, 'claimed')
+ replacement.kill()
+ replacement.wait(timeout=3)
+ recovered = start()
+ line(recovered, 'claimed')
+ recovered.stdin.write('close\n')
+ recovered.stdin.flush()
+ line(recovered, 'released')
+ assert recovered.wait(timeout=3) == 0
+ print('exclusive claim, orderly handoff and crash recovery passed')
+finally:
+ for child in children:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=3)
+ os.close(slave)
+ os.close(master)
diff --git a/cli/src/cable/__fixtures__/serialClaim.ts b/cli/src/cable/__fixtures__/serialClaim.ts
new file mode 100644
index 000000000..787433705
--- /dev/null
+++ b/cli/src/cable/__fixtures__/serialClaim.ts
@@ -0,0 +1,15 @@
+import assert from 'node:assert/strict'
+import { SerialLink } from '../serial.js'
+
+const [path] = process.argv.slice(2)
+const deadline = setTimeout(() => { console.error('Serial claim timed out'); process.exit(1) }, 8000)
+try {
+ const link = await SerialLink.open(path, () => {}, () => {})
+ process.stdout.write('claimed\n')
+ await new Promise<void>(resolve => process.stdin.once('data', () => resolve()))
+ await link.close()
+ process.stdout.write('released\n')
+} catch (error) {
+ assert.equal((error as NodeJS.ErrnoException).code, 'EAGAIN')
+ process.stdout.write('busy\n')
+} finally { clearTimeout(deadline); process.stdin.destroy() }
diff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.ts
index 656292a35..9083b6e1f 100644
--- a/cli/src/cable/cableFleet.spec.ts
+++ b/cli/src/cable/cableFleet.spec.ts
@@ -49,6 +49,7 @@ function fixture() {
}
const logs = mkdtempSync(join(tmpdir(), 'usb-fleet-'))
const options = {
+ canUseUsb: vi.fn(() => true),
discover: vi.fn(async () => present), intervalMs: 60_000,
open: vi.fn(async (path: string, onData: (chunk: Buffer) => void, onClosed: (why: string) => void) => {
const port = new Peer(path, onData, onClosed); ports.push(port); return port
@@ -64,6 +65,55 @@ function fixture() {
}
describe('USB dial fleet', () => {
+ it('releases every dial on a macOS user switch and reconnects only when its account returns', async () => {
+ const f = fixture()
+ const scan = () => (f.fleet as unknown as { scan(): Promise<void> }).scan()
+ try {
+ f.options.canUseUsb.mockReturnValue(false)
+ f.fleet.start()
+ await scan()
+ expect(f.options.discover).not.toHaveBeenCalled()
+ expect(f.ports).toHaveLength(0)
+ f.options.canUseUsb.mockReturnValue(true)
+ await scan()
+ await vi.waitFor(() => expect(f.ports).toHaveLength(2))
+ await f.greet(f.ports)
+ expect(f.fleet.isConnected).toBe(true)
+ f.options.canUseUsb.mockReturnValue(false)
+ await scan()
+ expect(f.ports.every(port => !port.isOpen)).toBe(true)
+ expect(f.fleet.isConnected).toBe(false)
+ const discoveries = f.options.discover.mock.calls.length
+ await scan()
+ expect(f.options.discover).toHaveBeenCalledTimes(discoveries)
+ f.options.canUseUsb.mockReturnValue(true)
+ await scan()
+ await vi.waitFor(() => expect(f.ports).toHaveLength(4))
+ await f.greet(f.ports.slice(2))
+ expect(f.fleet.isConnected).toBe(true)
+ } finally { await f.fleet.stop() }
+ })
+
+ it('closes an opening port if the desktop account changes before open finishes', async () => {
+ const f = fixture()
+ f.setPorts([device('/dev/tim', 'AA:01')])
+ let finish!: () => void
+ f.options.open.mockImplementationOnce(async (path, onData, onClosed) => {
+ const peer = new Peer(path, onData, onClosed)
+ f.ports.push(peer)
+ await new Promise<void>(resolve => { finish = resolve })
+ return peer
+ })
+ try {
+ f.fleet.start()
+ await vi.waitFor(() => expect(f.ports).toHaveLength(1))
+ f.options.canUseUsb.mockReturnValue(false)
+ finish()
+ await vi.waitFor(() => expect(f.ports[0].isOpen).toBe(false))
+ expect(f.fleet.isConnected).toBe(false)
+ } finally { finish?.(); await f.fleet.stop() }
+ })
+
it('names every device on the desk, and changes the settings of ONE of them', async () => {
/*
* Before this the fleet picked a row and threw the rest away, so the app drew one robot however
diff --git a/cli/src/cable/cableFleet.ts b/cli/src/cable/cableFleet.ts
index f2b329784..a6478d5de 100644
--- a/cli/src/cable/cableFleet.ts
+++ b/cli/src/cable/cableFleet.ts
@@ -3,6 +3,7 @@
import { join } from 'node:path'
import { DialVerdicts } from './dialPortVerdicts.js'
import { findDialPorts, portInUse, SerialLink, type DialPort } from './serial.js'
+import { isUsbConsoleUser } from './usbConsoleUser.js'
import type { CableSession, CableHost, CablePort, DialStatus, PortOpener } from './cableSession.js'
import type { DialLog } from './dialLog.js'
@@ -20,6 +21,8 @@ export interface CableFleetOptions {
verdicts?: DialVerdicts
/** Does another process have this tty open? A port somebody else is using is not looked at. */
inUse?: (path: string) => Promise<boolean>
+ /** Only the foreground macOS account may automatically own physical USB. */
+ canUseUsb?: () => boolean
/** How often a board ruled out is checked for another program working on it. */
watchEveryMs?: number
}
@@ -34,6 +37,8 @@ export class CableFleet {
private readonly serials: Set<string>
private readonly verdicts: DialVerdicts
private readonly inUse: (path: string) => Promise<boolean>
+ private readonly canUseUsb: () => boolean
+ private waitingForConsole = false
/** 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. */
@@ -48,6 +53,7 @@ export class CableFleet {
this.serials = new Set((options.serials ?? []).map(s => s.toUpperCase()))
this.verdicts = options.verdicts ?? new DialVerdicts()
this.inUse = options.inUse ?? portInUse
+ this.canUseUsb = options.canUseUsb ?? isUsbConsoleUser
this.watchEveryMs = options.watchEveryMs ?? 8_000
}
@@ -101,6 +107,14 @@ export class CableFleet {
}
private async reconcile(): Promise<void> {
+ if (!this.canUseUsb()) {
+ if (!this.waitingForConsole) this.host.log('cable: USB belongs to the active macOS account — 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() }
+ return
+ }
+ this.waitingForConsole = false
const ports = await this.discover()
if (this.stopped) return
const present = new Map<string, DialPort>()
@@ -176,10 +190,10 @@ export class CableFleet {
},
})
const opener: PortOpener = async (onData, onClosed) => {
- if (this.stopped || this.entries.get(id) !== entry) return null
+ if (this.stopped || this.entries.get(id) !== entry || !this.canUseUsb()) return null
const opened = await this.open(port.path, onData, onClosed)
- if (this.stopped || this.entries.get(id) !== entry) {
- await opened.close('USB dial removed while opening')
+ if (this.stopped || this.entries.get(id) !== entry || !this.canUseUsb()) {
+ await opened.close('USB dial ownership changed while opening')
return null
}
return opened
diff --git a/cli/src/cable/serial.real.spec.ts b/cli/src/cable/serial.real.spec.ts
index c7533ee7b..aca5aa9f6 100644
--- a/cli/src/cable/serial.real.spec.ts
+++ b/cli/src/cable/serial.real.spec.ts
@@ -11,6 +11,20 @@ import { expect, it } from 'vitest'
const hasPty = process.platform !== 'win32' && spawnSync('python3', ['-c', 'import pty']).status === 0
+it.skipIf(!hasPty || process.platform !== 'darwin')('arbitrates competing macOS serial owners and releases the claim after a crash', async () => {
+ const scratch = await mkdtemp(join(tmpdir(), 'serial-claim-'))
+ try {
+ const worker = join(scratch, 'serial-claim.mjs')
+ await build({
+ entryPoints: [fileURLToPath(new URL('./__fixtures__/serialClaim.ts', import.meta.url))],
+ outfile: worker, bundle: true, platform: 'node', format: 'esm', target: 'node20',
+ })
+ const driver = fileURLToPath(new URL('./__fixtures__/serialClaim.py', import.meta.url))
+ const { stdout } = await promisify(execFile)('python3', [driver, process.execPath, worker], { timeout: 12000 })
+ expect(stdout).toContain('exclusive claim, orderly handoff and crash recovery passed')
+ } finally { await rm(scratch, { recursive: true, force: true }) }
+}, 15000)
+
it.skipIf(!hasPty)('keeps DNS and file I/O working across repeated silent tty closes with one worker', async () => {
const scratch = await mkdtemp(join(tmpdir(), 'serial-idle-'))
// The master stays open and sends nothing. This exercises the real kernel tty and native reads,
diff --git a/cli/src/cable/serial.spec.ts b/cli/src/cable/serial.spec.ts
index 01f34569c..9ff714244 100644
--- a/cli/src/cable/serial.spec.ts
+++ b/cli/src/cable/serial.spec.ts
@@ -20,11 +20,13 @@ function port(nativeFd = 43) {
return stream
}
const tick = async () => { for (let i = 0; i < 10; i++) await Promise.resolve() }
+const claimsPort = process.platform === 'darwin'
describe('event-driven serial link', () => {
beforeEach(() => {
vi.useFakeTimers()
io.open.mockReturnValue(42)
+ if (claimsPort) io.open.mockReturnValueOnce(41)
io.configure.mockImplementation((_cmd, _args, callback) => callback(null, '', ''))
})
afterEach(() => { vi.useRealTimers(); vi.resetAllMocks() })
@@ -52,28 +54,62 @@ describe('event-driven serial link', () => {
const link = await SerialLink.open('/dev/fake', vi.fn(), vi.fn())
expect(io.close).not.toHaveBeenCalled()
await link.close()
- expect(io.close).not.toHaveBeenCalled()
+ if (claimsPort) expect(io.close).toHaveBeenCalledExactlyOnceWith(41)
+ else expect(io.close).not.toHaveBeenCalled()
expect(stream.destroy).toHaveBeenCalledTimes(1)
})
it('closes the descriptor if native stream construction fails', async () => {
io.stream.mockImplementation(function () { throw new Error('TTY unavailable') })
await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toThrow('TTY unavailable')
- expect(io.close).toHaveBeenCalledExactlyOnceWith(42)
+ expect(io.close.mock.calls).toEqual(claimsPort ? [[42], [41]] : [[42]])
})
it('releases the native stream if closing the original descriptor fails', async () => {
const stream = port()
io.close.mockImplementation(() => { throw new Error('close failed') })
await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toThrow('close failed')
- expect(io.close).toHaveBeenCalledTimes(1)
+ expect(io.close).toHaveBeenCalledTimes(claimsPort ? 2 : 1)
expect(stream.destroy).toHaveBeenCalledTimes(1)
})
it('does not open a port that could not be configured raw', async () => {
io.configure.mockImplementation((_cmd, _args, callback) => callback(new Error('stty failed')))
await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toThrow('stty failed')
- expect(io.open).not.toHaveBeenCalled()
+ if (claimsPort) {
+ expect(io.open).toHaveBeenCalledTimes(1)
+ expect(io.close).toHaveBeenCalledExactlyOnceWith(41)
+ } else expect(io.open).not.toHaveBeenCalled()
+ expect(io.stream).not.toHaveBeenCalled()
+ })
+
+ it.skipIf(!claimsPort)('refuses a competing claim before stty can touch the port', async () => {
+ io.open.mockReset().mockImplementation(() => { throw Object.assign(new Error('busy'), { code: 'EAGAIN' }) })
+ await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toMatchObject({ code: 'EAGAIN' })
+ expect(io.configure).not.toHaveBeenCalled()
+ expect(io.stream).not.toHaveBeenCalled()
+ expect(io.close).not.toHaveBeenCalled()
+ })
+
+ it.skipIf(!claimsPort)('holds the kernel claim until the native stream has actually closed', async () => {
+ const stream = port()
+ stream.destroy.mockImplementation(() => stream)
+ const link = await SerialLink.open('/dev/fake', vi.fn(), vi.fn())
+ expect(io.open.mock.calls[0]).toEqual(['/dev/fake', constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK | 0x20])
+ const closing = link.close()
+ await tick()
+ expect(io.close.mock.calls).toEqual([[42]])
+ stream.emit('close')
+ await closing
+ expect(io.close.mock.calls).toEqual([[42], [41]])
+ await link.close()
+ expect(io.close.mock.calls).toEqual([[42], [41]])
+ })
+
+ it.skipIf(!claimsPort)('releases the claim if opening the stream descriptor fails', async () => {
+ io.open.mockReset().mockReturnValueOnce(41).mockImplementationOnce(() => { throw new Error('port disappeared') })
+ await expect(SerialLink.open('/dev/fake', vi.fn(), vi.fn())).rejects.toThrow('port disappeared')
+ expect(io.close).toHaveBeenCalledExactlyOnceWith(41)
expect(io.stream).not.toHaveBeenCalled()
})
diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.ts
index 77ff56174..c4758e7e3 100644
--- a/cli/src/cable/serial.ts
+++ b/cli/src/cable/serial.ts
@@ -11,6 +11,11 @@ import { promisify } from 'node:util'
const runFile = promisify(execFile)
+// Darwin's O_EXLOCK (sys/fcntl.h). Node accepts it as an open flag but does not
+// expose the constant. The kernel arbitrates competing opens across users;
+// lsof cannot see another macOS account's descriptors and also has a TOCTOU race.
+const DARWIN_O_EXLOCK = 0x20
+
/** The SoC's own USB peripheral. The dial exposes this and nothing else — measured, see findDialPort. */
export const DIAL_VENDOR_ID = 0x303a
export const DIAL_PRODUCT_ID = 0x1001
@@ -189,6 +194,7 @@ export class SerialLink {
private readonly stream: ReadStream,
private readonly onData: (chunk: Buffer) => void,
private readonly onClosed: (why: string) => void,
+ private readonly claimFd?: number,
) {
stream.on('data', (chunk: Buffer) => {
if (this.closed) return
@@ -212,42 +218,55 @@ export class SerialLink {
onData: (chunk: Buffer) => void,
onClosed: (why: string) => void,
): Promise<SerialLink> {
- // Raw mode is not optional. Left in the default line discipline the tty maps CR to NL, strips the
- // eighth bit on some paths and echoes what we write back at us — and a mangled frame is
- // indistinguishable from a bad cable at the far end.
- //
- // `clocal` belongs with it: it tells the line discipline to ignore modem control lines, so losing
- // carrier — which is what unplugging a USB serial device looks like — does not hang the port up
- // underneath us.
- const flag = process.platform === 'darwin' ? '-f' : '-F'
- await runFile('stty', [flag, path, 'raw', 'clocal', '-echo', '-echoe', '-echok', '-echoctl', '-echoke', 'min', '1', 'time', '0'])
+ // Keep the claim on a separate open description: libuv reopens/replaces
+ // the stream's descriptor and would otherwise release this advisory lock.
+ // Acquire it before stty can change a port another Harness is using.
+ const claimFd = process.platform === 'darwin'
+ ? openSync(path, constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK | DARWIN_O_EXLOCK)
+ : undefined
+ let retainedClaim = false
+ try {
+ // Raw mode is not optional. Left in the default line discipline the tty maps CR to NL, strips the
+ // eighth bit on some paths and echoes what we write back at us — and a mangled frame is
+ // indistinguishable from a bad cable at the far end.
+ //
+ // `clocal` belongs with it: it tells the line discipline to ignore modem control lines, so losing
+ // carrier — which is what unplugging a USB serial device looks like — does not hang the port up
+ // underneath us.
+ const flag = process.platform === 'darwin' ? '-f' : '-F'
+ await runFile('stty', [flag, path, 'raw', 'clocal', '-echo', '-echoe', '-echok', '-echoctl', '-echoke', 'min', '1', 'time', '0'])
- // O_NOCTTY IS LOAD-BEARING, AND ITS ABSENCE KILLED THE DAEMON.
- //
- // The daemon is spawned detached, which makes it a session leader. A session leader that opens a tty
- // without this flag ACQUIRES it as its controlling terminal — and when the USB device is unplugged the
- // kernel sends SIGHUP to that terminal's process group. Default disposition for SIGHUP is terminate,
- // so pulling the cable killed the process outright: no exception, no stack, nothing for the
- // unhandledRejection guard to catch, and a log that simply stops mid-second.
- //
- // Measured 2026-08-24: the daemon died at the exact second the cable came out, every time, and the
- // dial then greeted an empty room until it timed out and showed no agents.
- // FileHandle.read either occupies a worker while idle or needs EAGAIN polling. A TTY stream
- // uses libuv readiness instead, including short writes/backpressure, without a polling timer.
- // ReadStream is a net.Socket; opening O_RDWR and enabling both sides makes it full duplex.
- const fd = openSync(path, constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK)
- let stream: ReadStream
- try { stream = new ReadStream(fd, { readable: true, writable: true }) }
- catch (error) { closeSync(fd); throw error }
- // On POSIX libuv normally reopens the tty and owns a duplicate. On its fallback path it owns
- // the supplied fd itself. Check the native handle exactly once so neither path leaks a
- // descriptor or closes it twice. The managed Node runtime's real-PTY tests cover ownership.
- const streamFd = (stream as ReadStream & { _handle: { fd: number } })._handle.fd
- if (streamFd !== fd) {
- try { closeSync(fd) }
- catch (error) { stream.destroy(); throw error }
+ // O_NOCTTY IS LOAD-BEARING, AND ITS ABSENCE KILLED THE DAEMON.
+ //
+ // The daemon is spawned detached, which makes it a session leader. A session leader that opens a tty
+ // without this flag ACQUIRES it as its controlling terminal — and when the USB device is unplugged the
+ // kernel sends SIGHUP to that terminal's process group. Default disposition for SIGHUP is terminate,
+ // so pulling the cable killed the process outright: no exception, no stack, nothing for the
+ // unhandledRejection guard to catch, and a log that simply stops mid-second.
+ //
+ // Measured 2026-08-24: the daemon died at the exact second the cable came out, every time, and the
+ // dial then greeted an empty room until it timed out and showed no agents.
+ // FileHandle.read either occupies a worker while idle or needs EAGAIN polling. A TTY stream
+ // uses libuv readiness instead, including short writes/backpressure, without a polling timer.
+ // ReadStream is a net.Socket; opening O_RDWR and enabling both sides makes it full duplex.
+ const fd = openSync(path, constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK)
+ let stream: ReadStream
+ try { stream = new ReadStream(fd, { readable: true, writable: true }) }
+ catch (error) { closeSync(fd); throw error }
+ // On POSIX libuv normally reopens the tty and owns a duplicate. On its fallback path it owns
+ // the supplied fd itself. Check the native handle exactly once so neither path leaks a
+ // descriptor or closes it twice. The managed Node runtime's real-PTY tests cover ownership.
+ const streamFd = (stream as ReadStream & { _handle: { fd: number } })._handle.fd
+ if (streamFd !== fd) {
+ try { closeSync(fd) }
+ catch (error) { stream.destroy(); throw error }
+ }
+ const link = new SerialLink(path, stream, onData, onClosed, claimFd)
+ retainedClaim = true
+ return link
+ } finally {
+ if (!retainedClaim && claimFd !== undefined) closeSync(claimFd)
}
- return new SerialLink(path, stream, onData, onClosed)
}
/**
@@ -295,7 +314,10 @@ export class SerialLink {
if (this.closePromise) return this.closePromise
this.closed = true
let finish!: () => void
- this.closePromise = new Promise<void>((resolve) => { finish = resolve }).then(() => this.onClosed(why))
+ this.closePromise = new Promise<void>((resolve) => { finish = resolve }).then(() => {
+ try { if (this.claimFd !== undefined) closeSync(this.claimFd) }
+ finally { this.onClosed(why) }
+ })
if (this.streamClosed) finish()
else {
this.stream.once('close', finish)
diff --git a/cli/src/cable/usbConsoleUser.spec.ts b/cli/src/cable/usbConsoleUser.spec.ts
new file mode 100644
index 000000000..3a66ee020
--- /dev/null
+++ b/cli/src/cable/usbConsoleUser.spec.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from 'vitest'
+import { isUsbConsoleUser } from './usbConsoleUser.js'
+
+describe('physical USB ownership', () => {
+ it('allows the active macOS account and excludes a daemon left in another login', () => {
+ const consoleUid = () => 501
+ expect(isUsbConsoleUser({ platform: 'darwin', uid: 501, consoleUid })).toBe(true)
+ expect(isUsbConsoleUser({ platform: 'darwin', uid: 502, consoleUid })).toBe(false)
+ expect(isUsbConsoleUser({ platform: 'darwin', uid: 0, consoleUid })).toBe(false)
+ })
+
+ it('releases the port at the login window or when console ownership cannot be read', () => {
+ expect(isUsbConsoleUser({ platform: 'darwin', uid: 501, consoleUid: () => 0 })).toBe(false)
+ expect(isUsbConsoleUser({ platform: 'darwin', uid: 0, consoleUid: () => 0 })).toBe(false)
+ expect(isUsbConsoleUser({ platform: 'darwin', uid: 501, consoleUid: () => { throw new Error('unavailable') } })).toBe(false)
+ })
+
+ it('does not require a desktop login on Linux', () => {
+ const consoleUid = vi.fn(() => { throw new Error('no macOS console') })
+ expect(isUsbConsoleUser({ platform: 'linux', uid: 1000, consoleUid })).toBe(true)
+ expect(consoleUid).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/cable/usbConsoleUser.ts b/cli/src/cable/usbConsoleUser.ts
new file mode 100644
index 000000000..2053c40d8
--- /dev/null
+++ b/cli/src/cable/usbConsoleUser.ts
@@ -0,0 +1,14 @@
+import { statSync } from 'node:fs'
+
+/** A daemon left running by Fast User Switching must release the physical USB
+ * device. macOS hides other users' descriptors from unprivileged lsof, so its
+ * empty result cannot establish that the current desktop owns the port. */
+export function isUsbConsoleUser({
+ platform = process.platform,
+ uid = process.getuid?.(),
+ consoleUid = () => statSync('/dev/console').uid,
+}: { platform?: NodeJS.Platform; uid?: number; consoleUid?: () => number } = {}): boolean {
+ if (platform !== 'darwin') return true
+ try { return uid !== undefined && uid !== 0 && uid === consoleUid() }
+ catch { return false }
+}
diff --git a/cli/src/orchestrator/service.spec.ts b/cli/src/orchestrator/service.spec.ts
index 48f59507b..60b9e331a 100644
--- a/cli/src/orchestrator/service.spec.ts
+++ b/cli/src/orchestrator/service.spec.ts
@@ -274,10 +274,14 @@ describe('durable orchestrator lifecycle', () => {
expect(launches[0].cwd).toBe(join(realpathSync(root), '.harness-projects', id))
})
it('lists recent projects in order without exposing their full briefs', async () => {
+ // Recency needs distinct timestamps even when CI completes both starts in one millisecond.
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1000)
await start(); await active()
+ clock.mockReturnValue(2000)
const second = 'f'.repeat(32)
await service.start({ id: second, engine: 'claude', prompt: 'A'.repeat(500) })
await vi.waitFor(() => expect(service.snapshot(second).state).toBe('active'))
+ clock.mockReturnValue(3000)
service.chat(second, '1'.repeat(32), 'More detail')
expect(service.list().map(r => r.id)).toEqual([second, id])
expect(String(service.list()[0].prompt)).toHaveLength(160)