Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(test): give the realtmux suites a socket path that fits sun_path

Uri Bloch8bfa4cbd7d03
diff --git a/src/core/local-send-keys.realtmux.test.ts b/src/core/local-send-keys.realtmux.test.ts
index 59f743554..e80a0bac9 100644
--- a/src/core/local-send-keys.realtmux.test.ts
+++ b/src/core/local-send-keys.realtmux.test.ts
@@ -24,9 +24,9 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { execFileSync } from 'child_process'
import fs from 'fs'
-import os from 'os'
import path from 'path'
import { localTmuxPasteArgs, localTmuxEnterArgs, pasteBufferName } from './tmux-naming'
+import { makeTmuxTmpdir } from './tmux-test-socket'
import { sanitizePasteText } from './paste-injection'
/** A private socket, never `TMUX_SOCKET` — this must not touch a running nodeterm's tmux server. */
@@ -39,6 +39,10 @@ const SESSION = 'nt-probe'
* `kill-server` stops the server but does not unlink the socket file, so a per-pid socket name in
* the shared dir leaves one stale entry behind per run, forever. Pointing `TMUX_TMPDIR` at `work`
* makes `afterAll`'s `rm -rf` the one cleanup path for everything this file created.
+ *
+ * `makeTmuxTmpdir` picks the dir, because private is not the only constraint — the bound socket
+ * path also has to fit `sun_path`, and under the macOS per-user temp root this file's own name
+ * came to 106 of the 103 characters available. See `tmux-test-socket.ts`.
*/
function tmuxEnv(): NodeJS.ProcessEnv {
return { ...process.env, TMUX_TMPDIR: work }
@@ -121,7 +125,7 @@ function freshPane(): void {
beforeAll(() => {
if (!TMUX) return
- work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntsendkeys-'))
+ work = makeTmuxTmpdir('nts-', SOCKET)
})
afterAll(() => {
diff --git a/src/core/session-env.realtmux.test.ts b/src/core/session-env.realtmux.test.ts
index 494326ab3..5f0f6915d 100644
--- a/src/core/session-env.realtmux.test.ts
+++ b/src/core/session-env.realtmux.test.ts
@@ -13,12 +13,18 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { execFileSync } from 'child_process'
import fs from 'fs'
-import os from 'os'
import path from 'path'
import { tmuxConf } from './pty-manager'
import { sessionEnvFileContent } from './remote-ssh/session-env'
+import { makeTmuxTmpdir } from './tmux-test-socket'
-/** A private socket — never the live-session sockets. */
+/**
+ * A private socket — never the live-session sockets, and never the SHARED `/tmp/tmux-<uid>/`
+ * either. `kill-server` does not unlink the socket file, so a per-pid name in the shared dir left
+ * one dead entry behind per run: 14 stale `nt-envtest-*` sockets had accumulated on one dev
+ * machine. `TMUX_TMPDIR` points at this file's own temp dir, so `afterAll`'s `rm -rf` takes the
+ * socket with it — the discipline the other two realtmux suites already had.
+ */
const SOCKET = `nt-envtest-${process.pid}`
let tmp: string
@@ -26,8 +32,10 @@ let conf: string
let tmuxOk = false
function tmux(args: string[], env?: Record<string, string>): string {
+ // TMUX_TMPDIR last: a caller's `env` chooses what the CLIENT carries, never which server it
+ // reaches. Two sockets in one file would be two tmux servers and a test that proves nothing.
return execFileSync('tmux', ['-L', SOCKET, ...args], {
- env: { ...process.env, ...env },
+ env: { ...process.env, ...env, TMUX_TMPDIR: tmp },
stdio: ['ignore', 'pipe', 'pipe']
}).toString()
}
@@ -39,7 +47,7 @@ beforeAll(() => {
} catch {
return // no tmux on this host — every test below self-skips
}
- tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-envtest-'))
+ tmp = makeTmuxTmpdir('ntenv-', SOCKET)
conf = path.join(tmp, 'tmux.conf')
fs.writeFileSync(conf, tmuxConf(2000))
})
@@ -92,7 +100,7 @@ describe('update-environment delivery (the argv-free gateway path)', () => {
execFileSync(
'tmux',
['-L', SOCKET, 'new-session', '-d', '-s', 'plain', `echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}`],
- { env, stdio: ['ignore', 'pipe', 'pipe'] }
+ { env: { ...env, TMUX_TMPDIR: tmp }, stdio: ['ignore', 'pipe', 'pipe'] }
)
expect(await waitFor(out)).toBe('TOKEN=[]\n')
})
@@ -113,7 +121,10 @@ describe('the remote prologue, run through a real /bin/sh', () => {
execFileSync(
'/bin/sh',
['-c', `${prologue} tmux -L ${SOCKET} new-session -d -s remote 'echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}'`],
- { stdio: ['ignore', 'pipe', 'pipe'] }
+ // TMUX_TMPDIR has to reach the tmux INSIDE this shell too. Without it the prologue tests
+ // start a second server for the same socket NAME on the shared dir, which afterAll's
+ // kill-server (aimed at the private one) then leaves running with its socket on disk.
+ { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TMUX_TMPDIR: tmp } }
)
expect(await waitFor(out)).toBe("TOKEN=[vk-remote'; echo pwned]\n")
// Sourced and GONE: nothing at rest on the host after the launch.
@@ -129,7 +140,7 @@ describe('the remote prologue, run through a real /bin/sh', () => {
execFileSync(
'/bin/sh',
['-c', `${prologue} tmux -L ${SOCKET} new-session -d -s ghost 'echo "TOKEN=[$ANTHROPIC_AUTH_TOKEN]" > ${out}'`],
- { stdio: ['ignore', 'pipe', 'pipe'], env: (() => { const e = { ...process.env }; delete e.ANTHROPIC_AUTH_TOKEN; return e })() }
+ { stdio: ['ignore', 'pipe', 'pipe'], env: (() => { const e: NodeJS.ProcessEnv = { ...process.env, TMUX_TMPDIR: tmp }; delete e.ANTHROPIC_AUTH_TOKEN; return e })() }
)
// 6 × 50ms wait budget, then the session still launched — without the env.
expect(Date.now() - t0).toBeGreaterThanOrEqual(250)
diff --git a/src/core/tmux-paste.realtmux.test.ts b/src/core/tmux-paste.realtmux.test.ts
index 6ee472045..ff0df7f18 100644
--- a/src/core/tmux-paste.realtmux.test.ts
+++ b/src/core/tmux-paste.realtmux.test.ts
@@ -21,7 +21,6 @@
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'
import { execFileSync } from 'child_process'
import fs from 'fs'
-import os from 'os'
import path from 'path'
import {
localPasteDelivery,
@@ -31,6 +30,7 @@ import {
type PasteDelivery
} from './tmux-naming'
import { remotePasteDelivery } from './remote-ssh/control-master'
+import { makeTmuxTmpdir } from './tmux-test-socket'
const ESC = '\x1b'
const START = `${ESC}[200~`
@@ -77,7 +77,7 @@ function tryTmux(args: string[], input?: string): void {
beforeAll(() => {
if (!TMUX) return
- work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntpb-'))
+ work = makeTmuxTmpdir('ntpb-', SOCKET)
binDir = path.join(work, 'bin')
fs.mkdirSync(binDir)
// The SSH path's shim. `remoteTmuxPasteArgs` hard-codes `-L nodeterm-rmt`, which on a real host
diff --git a/src/core/tmux-test-socket.test.ts b/src/core/tmux-test-socket.test.ts
new file mode 100644
index 000000000..8a5a56684
--- /dev/null
+++ b/src/core/tmux-test-socket.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from 'vitest'
+import { SUN_PATH_MAX, tmuxSocketPath, pickTmuxTmpdirBase } from './tmux-test-socket'
+
+// The real macOS per-user temp root, measured on the machine where the realtmux suite broke.
+// `os.tmpdir()` reports it without the `/private` prefix; tmux resolves the symlink before it
+// binds, which is where the 8 characters that overflow the sockaddr come from.
+const MAC_TMP = '/private/var/folders/_f/sgpx16sd7z79ycmkyylw5tg40000gn/T'
+
+describe('tmuxSocketPath', () => {
+ it('is where tmux binds for `-L <socket>` under a given TMUX_TMPDIR', () => {
+ expect(tmuxSocketPath('/tmp/nts-abc123', 501, 'sock')).toBe('/tmp/nts-abc123/tmux-501/sock')
+ })
+})
+
+describe('pickTmuxTmpdirBase', () => {
+ it('keeps the first base that fits — the caller orders them by preference', () => {
+ expect(pickTmuxTmpdirBase([MAC_TMP, '/tmp'], 501, 'sock', 'p-')).toBe(MAC_TMP)
+ })
+
+ it('skips a base whose socket path would not fit and takes the next', () => {
+ // This is the regression: the real prefix and socket name from
+ // local-send-keys.realtmux.test.ts, which came to 106 characters under the macOS temp root
+ // and failed as `error connecting to …: File name too long`.
+ const base = pickTmuxTmpdirBase([MAC_TMP, '/tmp'], 501, 'nt-sendkeys-test-38663', 'ntsendkeys-')
+ expect(base).toBe('/tmp')
+ })
+
+ it('accounts for the six random characters mkdtemp appends to the prefix', () => {
+ // A prefix landing EXACTLY on the limit before mkdtemp grows it, so the only thing that can
+ // make this base unusable is the six characters — nothing else in the arithmetic.
+ const uid = 501
+ const socket = 'sock'
+ const overhead = `${MAC_TMP}/`.length + `/tmux-${uid}/${socket}`.length
+ const prefix = 'x'.repeat(SUN_PATH_MAX - overhead)
+ expect(tmuxSocketPath(`${MAC_TMP}/${prefix}`, uid, socket).length).toBe(SUN_PATH_MAX)
+ expect(pickTmuxTmpdirBase([MAC_TMP], uid, socket, prefix)).toBeNull()
+ })
+
+ it('is null when no base fits — a caller must not silently bind a truncated path', () => {
+ expect(pickTmuxTmpdirBase([MAC_TMP], 501, 'x'.repeat(200), 'p-')).toBeNull()
+ })
+})
diff --git a/src/core/tmux-test-socket.ts b/src/core/tmux-test-socket.ts
new file mode 100644
index 000000000..67305eaab
--- /dev/null
+++ b/src/core/tmux-test-socket.ts
@@ -0,0 +1,91 @@
+// TEST-ONLY: choosing a private `TMUX_TMPDIR` for the `*.realtmux.test.ts` suites.
+//
+// Two things a real-tmux test has to get right about its socket, and each has bitten this repo:
+//
+// 1. **It must be private**, so `afterAll`'s `rm -rf` is the one cleanup path. `kill-server` stops
+// the server but never unlinks the socket file, so a per-pid name in the SHARED `/tmp/tmux-<uid>/`
+// leaves one dead entry behind per run, forever — measured at 14 stale `nt-envtest-*` sockets on
+// one dev machine before this module existed.
+// 2. **It must be SHORT.** A unix socket path is bound into a fixed `sockaddr_un.sun_path`, and the
+// macOS per-user temp root is already 56 characters before anything is added to it. This is not
+// theoretical: `local-send-keys.realtmux.test.ts` came to 106 and every test in it failed with
+// `error connecting to …: File name too long`, which reads like a broken test rather than a
+// path-length limit. Its sibling passed at 97 — six characters from the same failure.
+//
+// Production is not exposed to (2): `PtyManager` binds `-L node-terminal` under the default
+// `/tmp/tmux-<uid>/`, which is short on every platform we ship to.
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+
+/**
+ * The longest socket path that can be bound.
+ *
+ * macOS `sys/un.h` declares `sun_path[104]` — 103 characters plus the NUL. Linux allows 107. The
+ * smaller number is the one to hold everywhere: a limit that only bites on a contributor's Mac is
+ * worse than one that bites in CI, because it looks like the test is broken.
+ */
+export const SUN_PATH_MAX = 103
+
+/** `mkdtemp` replaces a trailing `XXXXXX`, so the directory is always six characters longer. */
+export const MKDTEMP_SUFFIX_LEN = 6
+
+/** Where tmux binds for `-L <socket>` under `TMUX_TMPDIR=<dir>`. */
+export function tmuxSocketPath(dir: string, uid: number, socket: string): string {
+ return path.join(dir, `tmux-${uid}`, socket)
+}
+
+/**
+ * The first base directory under which `mkdtemp(<base>/<prefix>XXXXXX)` still leaves room for the
+ * socket, or `null` when none does. Bases are tried in the order given, so the caller states its
+ * preference; `null` is a refusal, never a truncated path that would fail obscurely at bind time.
+ */
+export function pickTmuxTmpdirBase(
+ bases: string[],
+ uid: number,
+ socket: string,
+ prefix: string
+): string | null {
+ const dirName = prefix + 'X'.repeat(MKDTEMP_SUFFIX_LEN)
+ return (
+ bases.find((b) => tmuxSocketPath(path.join(b, dirName), uid, socket).length <= SUN_PATH_MAX) ??
+ null
+ )
+}
+
+/**
+ * Create a private `TMUX_TMPDIR` that `-L <socket>` fits inside, and return it. Prefers the
+ * platform temp dir and falls back to `/tmp`, which is what makes the difference on macOS: the
+ * former resolves to `/private/var/folders/…` (56 characters), the latter to `/private/tmp` (12).
+ *
+ * Both candidates are resolved BEFORE they are measured — tmux resolves the symlink itself before
+ * binding, so measuring the unresolved `/var/folders/…` under-counts by exactly the 8 characters
+ * that overflowed.
+ */
+export function makeTmuxTmpdir(prefix: string, socket: string): string {
+ const uid = process.getuid?.() ?? 0
+ const bases = [...new Set([os.tmpdir(), '/tmp'].map(realpathOrSelf))]
+ const base = pickTmuxTmpdirBase(bases, uid, socket, prefix)
+ if (base === null) {
+ throw new Error(
+ `no temp dir leaves room for a tmux socket: tried ${bases.join(', ')} with prefix ` +
+ `"${prefix}" and socket "${socket}" against ${SUN_PATH_MAX} chars`
+ )
+ }
+ const dir = realpathOrSelf(fs.mkdtempSync(path.join(base, prefix)))
+ const bound = tmuxSocketPath(dir, uid, socket)
+ // Belt and braces: the prediction above and the directory mkdtemp actually made must agree, or
+ // the suite fails here naming the number rather than at bind time naming the errno.
+ if (bound.length > SUN_PATH_MAX) {
+ throw new Error(`tmux socket path is ${bound.length} > ${SUN_PATH_MAX} chars: ${bound}`)
+ }
+ return dir
+}
+
+function realpathOrSelf(p: string): string {
+ try {
+ return fs.realpathSync(p)
+ } catch {
+ return p
+ }
+}