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
A dial unplugged as its port opens no longer hangs the devices' process: the port is never reopened by name (#953)
Dee42982b26e508
diff --git a/cli/src/cable/__fixtures__/serialGone.py b/cli/src/cable/__fixtures__/serialGone.pyindex 897f43f86..0bfe70682 100644--- a/cli/src/cable/__fixtures__/serialGone.py+++ b/cli/src/cable/__fixtures__/serialGone.py@@ -2,6 +2,8 @@`gone`: the slave is held open here (as a daemon still holding its port would), the master closed, and thenthe worker opens the slave: it must refuse at once, not wait in open() for a master that is not coming.+`raced`: the same, with the worker's probe read told "nothing yet", as when the master goes just after it:+the port must open without waiting, and close on the far end's end.`early`: the master writes before the worker opens the slave, and then more: the worker gets both, in order."""import os@@ -13,7 +15,7 @@ import timenode, worker, mode = sys.argv[1:]master, slave = pty.openpty()path = os.ttyname(slave)-if mode == 'gone':+if mode in ('gone', 'raced'):os.close(master)else:os.write(master, b'before ')diff --git a/cli/src/cable/__fixtures__/serialGone.ts b/cli/src/cable/__fixtures__/serialGone.tsindex 16c837d8c..619e53faa 100644--- a/cli/src/cable/__fixtures__/serialGone.ts+++ b/cli/src/cable/__fixtures__/serialGone.ts@@ -1,16 +1,25 @@// Paired with serialGone.py: only that driver's disposable PTY is opened.+import fs from 'node:fs'+import { syncBuiltinESMExports } from 'node:module'import { SerialLink } from '../serial.js'const [path, mode] = process.argv.slice(2)+// `raced`: the far end goes just after the probe read, which is told "nothing yet" here, as it was then.+if (mode === 'raced') {+ fs.readSync = (() => { throw Object.assign(new Error('EAGAIN'), { code: 'EAGAIN' }) }) as typeof fs.readSync+ syncBuiltinESMExports()+}const timeout = setTimeout(() => { console.log(JSON.stringify({ mode, hung: true })); process.exit(1) }, 5_000)const started = Date.now()try {const received: Buffer[] = []- const link = await SerialLink.open(path, (chunk) => { received.push(chunk) }, () => {})+ let closed: string | null = null+ const link = await SerialLink.open(path, (chunk) => { received.push(chunk) }, (why) => { closed ??= why })+ const openMs = Date.now() - started// What the dial sent before the port was opened arrives first, and nothing is lost after it.await new Promise((resolve) => setTimeout(resolve, 300))await link.close('done')- console.log(JSON.stringify({ mode, opened: true, received: Buffer.concat(received).toString('utf8') }))+ console.log(JSON.stringify({ mode, opened: true, received: Buffer.concat(received).toString('utf8'), closed, openMs }))} catch (error) {console.log(JSON.stringify({ mode, opened: false, code: (error as NodeJS.ErrnoException).code ?? null, ms: Date.now() - started }))}diff --git a/cli/src/cable/portStream.spec.ts b/cli/src/cable/portStream.spec.tsnew file mode 100644index 000000000..0de704e2a--- /dev/null+++ b/cli/src/cable/portStream.spec.ts@@ -0,0 +1,57 @@+import { execFileSync } from 'node:child_process'+import { closeSync, mkdtempSync, openSync, rmSync, constants } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'++const tty = vi.hoisted(() => ({ ReadStream: vi.fn() }))+vi.mock('node:tty', () => tty)++import { nodePipes, portStream, type PipeWrap } from './portStream.js'++describe('a stream over a dial\'s port', () => {+ const dirs: string[] = []+ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })++ /** A descriptor libuv can watch as it watches a port: a FIFO, opened both ways, never blocking. */+ const fifo = (): number => {+ const dir = mkdtempSync(join(tmpdir(), 'port-stream-'))+ dirs.push(dir)+ execFileSync('mkfifo', [join(dir, 'port')])+ return openSync(join(dir, 'port'), constants.O_RDWR | constants.O_NONBLOCK)+ }++ it('reads and writes the descriptor it is given, through Node\'s pipe handle, and owns it', async () => {+ const fd = fifo()+ const stream = portStream(fd)+ expect((stream as unknown as { _handle: { fd: number } })._handle.fd).toBe(fd)+ const heard = new Promise<string>((resolve) => stream.once('data', (chunk: Buffer) => resolve(chunk.toString('utf8'))))+ stream.write('hello')+ expect(await heard).toBe('hello')+ await new Promise<void>((resolve) => { stream.once('close', () => resolve()); stream.destroy() })+ // Closed with the stream: the descriptor is no longer this process's.+ expect(() => closeSync(fd)).toThrow()+ expect(tty.ReadStream).not.toHaveBeenCalled()+ })++ it('says why a descriptor it cannot use is refused, and lets go of the handle', () => {+ const close = vi.fn()+ const pipes: PipeWrap = { Pipe: class { open() { return -9 } close() { close() } } as unknown as PipeWrap['Pipe'], constants: { SOCKET: 0 } }+ expect(() => portStream(7, pipes)).toThrow(expect.objectContaining({ code: 'EBADF', message: 'the port cannot be read: EBADF' }))+ expect(close).toHaveBeenCalledOnce()+ })++ it('is a terminal stream, as before, on a Node without the pipe handle', () => {+ const terminal = { terminal: true }+ tty.ReadStream.mockImplementationOnce(function () { return terminal })+ expect(portStream(7, null)).toBe(terminal)+ expect(tty.ReadStream).toHaveBeenCalledWith(7, { readable: true, writable: true })+ })++ it('finds Node\'s pipe handle, and none where it is missing, half there or refused', () => {+ expect(nodePipes()).toMatchObject({ Pipe: expect.any(Function), constants: { SOCKET: expect.any(Number) } })+ expect(nodePipes(() => undefined)).toBeNull()+ expect(nodePipes(() => ({ Pipe: class {} }))).toBeNull()+ expect(nodePipes(() => { throw new Error('No such module: pipe_wrap') })).toBeNull()+ })+})diff --git a/cli/src/cable/portStream.ts b/cli/src/cable/portStream.tsnew file mode 100644index 000000000..68418908e--- /dev/null+++ b/cli/src/cable/portStream.ts@@ -0,0 +1,56 @@+// A stream over a dial's port that never opens the port again, by its name or any other way.+//+// `tty.ReadStream` hands its descriptor to libuv's uv_tty_init, which reopens a terminal by name with a+// plain, blocking open() so as to set non-blocking mode on a description of its own. A pseudo-terminal+// whose far end has gone blocks that open until something opens the far end again, which nothing will.+// SerialLink.open refuses a port that is already gone (its probe), but the far end can go between the+// probe and the reopen: measured 2026-10-06, a fake dial unplugged within 150 ms of its plug held the+// devices' process in that open for 40 s, 2 times in 22 daemons under load, until the master killed the+// process as hung and the other dial with it (sampled: TTYWrap::New → uv_tty_init → uv__open_cloexec →+// open). The probe cannot close that window: the far end is another process, or the USB bus.+//+// A pipe handle opened on the descriptor (uv_pipe_open) takes it as it is, with the same readiness as a+// terminal's (kqueue, or on macOS libuv's select thread when kqueue cannot watch it, uv__stream_try_select,+// which uv_tty_init uses too), and opens nothing. The descriptor is SerialLink's own, opened non-blocking for+// this, so the reason libuv reopens a terminal, not to change the mode of one it shares with another+// process, does not apply here.+//+// The pipe handle's constructor is Node's own (`process.binding('pipe_wrap')`, the one net.Socket uses; its+// deprecation, DEP0111, is documentation-only). A Node without it gets the terminal stream, as before.+import { Socket } from 'node:net'+import { ReadStream } from 'node:tty'+import { getSystemErrorName } from 'node:util'++interface PipeHandle {+ open(fd: number): number+ close(): void+}++/** Node's pipe handle constructor, as net.Socket reaches it. */+export interface PipeWrap {+ Pipe: new (type: number) => PipeHandle+ constants: { SOCKET: number }+}++/** Node's pipe handle constructor, or null when this Node does not offer it. */+export function nodePipes(binding: (name: string) => unknown = (name) => (process as unknown as { binding(name: string): unknown }).binding(name)): PipeWrap | null {+ try {+ const wrap = binding('pipe_wrap') as Partial<PipeWrap> | undefined+ return typeof wrap?.Pipe === 'function' && typeof wrap.constants?.SOCKET === 'number' ? wrap as PipeWrap : null+ } catch {+ return null+ }+}++/** A duplex stream over `fd`, which it takes ownership of: closed when the stream is destroyed. */+export function portStream(fd: number, pipes: PipeWrap | null = nodePipes()): Socket {+ if (!pipes) return new ReadStream(fd, { readable: true, writable: true })+ const handle = new pipes.Pipe(pipes.constants.SOCKET)+ const failed = handle.open(fd)+ if (failed) {+ handle.close()+ const code = getSystemErrorName(failed)+ throw Object.assign(new Error(`the port cannot be read: ${code}`), { code })+ }+ return new Socket({ handle, readable: true, writable: true } as ConstructorParameters<typeof Socket>[0])+}diff --git a/cli/src/cable/serial.real.spec.ts b/cli/src/cable/serial.real.spec.tsindex c05d57dc7..825a3c521 100644--- a/cli/src/cable/serial.real.spec.ts+++ b/cli/src/cable/serial.real.spec.ts@@ -69,7 +69,7 @@ it.skipIf(!hasPty).each(['duplex', 'disconnect', 'close'])(}, 15_000,)-it.skipIf(!hasPty).each(['gone', 'early'])('opens a port whose far end is %s without waiting in open()', async (mode) => {+it.skipIf(!hasPty).each(['gone', 'early', 'raced'])('opens a port whose far end is %s without waiting in open()', async (mode) => {const scratch = await mkdtemp(join(tmpdir(), 'serial-gone-'))try {const worker = join(scratch, 'serial-gone.mjs')@@ -81,7 +81,19 @@ it.skipIf(!hasPty).each(['gone', 'early'])('opens a port whose far end is %s witconst { stdout } = await promisify(execFile)('python3', [driver, process.execPath, worker, mode], { timeout: 12_000 })const result = JSON.parse(stdout)if (mode === 'gone') expect(result).toMatchObject({ mode, opened: false })- else expect(result).toEqual({ mode, opened: true, received: 'before after' })+ // Opened over the descriptor it has, never again by name: a terminal stream reopened it and waited there+ // for the far end, in open(), the process's event loop with it (measured 2026-10-06, 40 s).+ // Never waits, and either opens or is refused at once, as each kernel has it. macOS lets a terminal whose+ // master has gone be configured and opened without waiting: it opens, with nothing to read, and waits for+ // the dial's greeting as for any dial, its first write (EIO) or its silence ending it (cableSession.ts).+ // Linux hangs such a terminal up: `stty` on it fails (EIO), so it is refused before anything is opened.+ else if (mode === 'raced' && process.platform === 'darwin') {+ expect(result).toMatchObject({ mode, opened: true, received: '' })+ expect(result.openMs).toBeLessThan(2_000)+ } else if (mode === 'raced') {+ expect(result).toMatchObject({ mode, opened: false })+ expect(result.ms).toBeLessThan(2_000)+ } else expect(result).toMatchObject({ mode, opened: true, received: 'before after', closed: 'done' })} finally {await rm(scratch, { recursive: true, force: true })}diff --git a/cli/src/cable/serial.spec.ts b/cli/src/cable/serial.spec.tsindex 7421928ee..2f92ff197 100644--- a/cli/src/cable/serial.spec.ts+++ b/cli/src/cable/serial.spec.ts@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const io = vi.hoisted(() => ({ open: vi.fn(), close: vi.fn(), configure: vi.fn(), stream: vi.fn(), readdir: vi.fn(), lstat: vi.fn(), read: vi.fn() }))vi.mock('node:fs', async (original) => ({ ...await original<typeof import('node:fs')>(), openSync: io.open, closeSync: io.close, readdirSync: io.readdir, lstatSync: io.lstat, readSync: io.read }))-vi.mock('node:tty', () => ({ ReadStream: io.stream }))+vi.mock('./portStream.js', () => ({ portStream: io.stream }))vi.mock('node:child_process', () => ({ execFile: io.configure }))import { SerialLink, findDialPorts } from './serial.js'@@ -59,7 +59,7 @@ describe('event-driven serial link', () => {const link = await SerialLink.open('/dev/fake', received, closed)expect(io.open).toHaveBeenCalledWith('/dev/fake', constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK)expect(io.close).toHaveBeenCalledExactlyOnceWith(42)- expect(io.stream).toHaveBeenCalledWith(42, { readable: true, writable: true })+ expect(io.stream).toHaveBeenCalledWith(42)expect(vi.getTimerCount()).toBe(0)await vi.advanceTimersByTimeAsync(60_000)expect(received).not.toHaveBeenCalled()diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.tsindex 21cd69922..31b75fe24 100644--- a/cli/src/cable/serial.ts+++ b/cli/src/cable/serial.ts@@ -7,8 +7,9 @@import { execFile } from 'node:child_process'import { closeSync, constants, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync } from 'node:fs'import { basename } from 'node:path'-import { ReadStream } from 'node:tty'+import type { Socket } from 'node:net'import { promisify } from 'node:util'+import { portStream } from './portStream.js'const runFile = promisify(execFile)@@ -222,7 +223,7 @@ function findLinux(): DialPort[] {export class SerialLink {private constructor(readonly path: string,- private readonly stream: ReadStream,+ private readonly stream: Socket,private readonly onData: (chunk: Buffer) => void,private readonly onClosed: (why: string) => void,private readonly claimFd?: number,@@ -277,18 +278,15 @@ export class SerialLink {//// 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.+ // FileHandle.read either occupies a worker while idle or needs EAGAIN polling. A stream on libuv's+ // readiness does neither, short writes and backpressure included, without a polling timer+ // (portStream.ts); opening O_RDWR and enabling both sides makes it full duplex.const fd = openSync(path, constants.O_RDWR | constants.O_NOCTTY | constants.O_NONBLOCK)- // THE FAR END MUST STILL BE THERE, OR THE NEXT LINE NEVER RETURNS. libuv reopens a tty by its name- // with a plain, blocking open() (uv_tty_init), and a terminal whose other end has closed blocks such an- // open until something opens that end again: measured 2026-10-06, a fake dial on a pseudo-terminal- // unplugged while its port was being opened (during `stty` above) held the devices' process in that- // open for 40 s, until the master killed it as hung, and the other dial with it. A dial on USB is a- // callout device (cu.*) that does not wait, but nothing here should rest on that. So one read first,- // without waiting: it ends (0) or fails, other than with "nothing yet", when the far end is gone, and- // what it read is the dial's and is handed to the stream ahead of the rest.+ // A port whose far end is already gone is refused here, plainly: one read first, without waiting, ends+ // (0) or fails, other than with "nothing yet", and what it read is the dial's and is handed to the+ // stream ahead of the rest. It once stood between the stream and a reopen that waited forever for a+ // far end that had gone (measured 2026-10-06, 40 s); the stream opens nothing now (portStream.ts),+ // since the far end can also go just after this read.let early: Buffer | null = nulltry {const probe = Buffer.alloc(4096)@@ -298,14 +296,14 @@ export class SerialLink {} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'EAGAIN') { closeSync(fd); throw error }}- let stream: ReadStream- try { stream = new ReadStream(fd, { readable: true, writable: true }) }+ let stream: Socket+ try { stream = portStream(fd) }catch (error) { closeSync(fd); throw error }if (early) stream.unshift(early)- // 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+ // The stream owns the descriptor it was given, unless it is a terminal stream (a Node without the+ // pipe handle), which reopens the tty and owns a duplicate. Check the native handle exactly once so+ // neither path leaks a descriptor or closes it twice. The real-PTY tests cover ownership.+ const streamFd = (stream as Socket & { _handle: { fd: number } })._handle.fdif (streamFd !== fd) {try { closeSync(fd) }catch (error) { stream.destroy(); throw error }