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(agent-hooks): gate before sourcing, drain stdin on bail, swallow sourced stdout

enesc498ac6d89f9
diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.ts
index 075515c07..bde586ced 100644
--- a/src/core/agents/hooks/managed-script.test.ts
+++ b/src/core/agents/hooks/managed-script.test.ts
@@ -1,5 +1,5 @@
import { spawn, spawnSync } from 'node:child_process'
-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync, utimesSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync, utimesSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
@@ -27,7 +27,8 @@ describe('buildManagedScript', () => {
// (its baked NODETERM_HOOK_ENDPOINT resolved empty). The gate must exit on a MISSING NODE ID,
// NOT on a missing token — otherwise the failover in nt_send_request never runs and the session
// stays dark until it is recreated. See buildManagedScript's "Empty-endpoint self-heal" note.
- expect(s).toContain('if [ -z "$NODETERM_NODE_ID" ]; then\n exit 0\nfi')
+ // The bail drains stdin first (#187) — see the executed bail-path tests at the end of the file.
+ expect(s).toContain('if [ -z "$NODETERM_NODE_ID" ]; then\n cat >/dev/null 2>&1 || :\n exit 0\nfi')
expect(s).not.toContain('if [ -z "$NODETERM_HOOK_TOKEN" ] || [ -z "$NODETERM_NODE_ID" ]; then')
})
@@ -136,7 +137,15 @@ describe('buildManagedScript', () => {
it('is omitted entirely when there is no identity root, leaving the legacy script', () => {
const legacy = buildManagedScript('claude', null as unknown as string)
expect(legacy).not.toContain('CODEX_THREAD_ID')
- expect(legacy.split('\n')[1]).toBe('if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then')
+ // The gate PRECEDES the endpoint sourcing (#186): a non-nodeterm session bails before any
+ // foreign-env file is executed. Order asserted, not a line index — comments may grow.
+ const lines = legacy.split('\n')
+ const gate = lines.indexOf('if [ -z "$NODETERM_NODE_ID" ]; then')
+ const sourcing = lines.indexOf(
+ 'if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then'
+ )
+ expect(gate).toBeGreaterThan(0)
+ expect(sourcing).toBeGreaterThan(gate)
})
})
@@ -653,3 +662,83 @@ describe('buildManagedScript generated shell is syntactically valid', () => {
})
}
})
+
+/**
+ * The bail path, executed under a real /bin/sh — the two failure modes of issues #186/#187, each
+ * pinned by the issue's own repro shape. String assertions above say the lines exist; these prove
+ * the behavior: no EPIPE for a big writer, and not one byte of endpoint stdout reaching the agent.
+ */
+describe('the managed script bail path (issues #186/#187), under /bin/sh', () => {
+ const sh = spawnSync('sh', ['-c', 'exit 0'])
+ const shAvailable = sh.status === 0 && !sh.error
+ const dir = shAvailable ? mkdtempSync(join(tmpdir(), 'nt-bail-path-')) : ''
+ const script = dir ? join(dir, 'claude.sh') : ''
+ const home = dir ? join(dir, 'home') : ''
+ beforeAll(() => {
+ if (!dir) return
+ mkdirSync(home, { recursive: true })
+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
+ })
+ afterAll(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true })
+ })
+ // HOME points at an empty temp dir in every run: the endpoint failover globs $HOME for candidate
+ // files, and a test that let it see the real ~/.nodeterm would depend on this machine's state.
+ const baseEnv = { PATH: process.env.PATH ?? '' }
+
+ it.skipIf(!shAvailable)(
+ 'drains stdin before bailing — a >64KB payload never EPIPEs the writer (#187)',
+ async () => {
+ // The issue's repro: raw writes (subprocess.communicate-style helpers swallow EPIPE and hide
+ // this). 2MB is ~32 pipe buffers, so an un-drained bail fails on the second write at latest.
+ const payload = Buffer.alloc(2_000_000, 0x41)
+ const child = spawn('sh', [script], {
+ env: { ...baseEnv, HOME: home },
+ stdio: ['pipe', 'pipe', 'pipe']
+ })
+ const writeError = new Promise<Error | null>((resolve) => {
+ child.stdin.on('error', (e) => resolve(e))
+ child.stdin.end(payload, () => resolve(null))
+ })
+ const exit = new Promise<number | null>((resolve) => child.on('close', (c) => resolve(c)))
+ expect(await writeError).toBeNull()
+ expect(await exit).toBe(0)
+ }
+ )
+
+ it.skipIf(!shAvailable)(
+ 'a no-node-id session never executes the endpoint file, let alone leaks its stdout (#186)',
+ () => {
+ // The issue's canary, plus a side-effect marker: executed-at-all and leaked-to-stdout are
+ // different failures, and the marker file catches the first even if output were swallowed.
+ const canary = join(dir, 'canary.env')
+ writeFileSync(canary, `echo "LEAKED"\n: > '${join(dir, 'executed.marker')}'\n`, 'utf8')
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"UserPromptSubmit"}',
+ env: { ...baseEnv, HOME: home, NODETERM_HOOK_ENDPOINT: canary }
+ })
+ expect(res.status).toBe(0)
+ expect(res.stdout).toBe('')
+ expect(existsSync(join(dir, 'executed.marker'))).toBe(false)
+ }
+ )
+
+ it.skipIf(!shAvailable)(
+ 'a nodeterm session sources the endpoint file but swallows its stdout (#186 point 2)',
+ () => {
+ // SessionStart/UserPromptSubmit stdout is ADDED TO THE AGENT'S CONTEXT, so even the legit
+ // sourcing path must print nothing. No SOCK/PORT and an empty HOME → the backgrounded POST
+ // finds no transport and no fallback candidates; the script still owes a silent exit 0.
+ const canary = join(dir, 'canary-live.env')
+ writeFileSync(canary, 'echo "LEAKED"\n', 'utf8')
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"UserPromptSubmit"}',
+ env: { ...baseEnv, HOME: home, NODETERM_NODE_ID: 'node-1', NODETERM_HOOK_ENDPOINT: canary }
+ })
+ expect(res.status).toBe(0)
+ expect(res.stdout).toBe('')
+ }
+ )
+})
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index 3e5252e00..d028b1382 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -98,8 +98,35 @@ export function buildManagedScript(
return [
'#!/bin/sh',
...(identityRoot ? [codexThreadIdentityResolverSh(identityRoot)] : []),
+ '# GATE FIRST, and drain stdin before bailing (issues #186/#187). Order is load-bearing twice:',
+ '# - The codex thread-identity prelude above may DERIVE the node id (and endpoint) from its',
+ '# thread id, so the gate cannot move above it — but nothing below needs to run for a',
+ '# non-nodeterm session, and',
+ '# sourcing the endpoint file before the gate executed foreign-env file contents in sessions',
+ '# this script promises a "bit-for-bit legacy no-op" for (#186).',
+ '# - The drain: claude writes the hook payload into our stdin, and PreToolUse/PostToolUse bodies',
+ '# exceed one 64KB pipe buffer on any large Read or diff. A bail that exits without reading',
+ '# EPIPEs the writer mid-payload (#187) — silent, because we still exit 0. The installed',
+ '# missing-script fallback in settings.json already drains (`else cat >/dev/null`); this makes',
+ '# the script\'s own bail path keep the same promise.',
+ '# Gate on the NODE ID only — it is what marks a nodeterm-spawned session (a user\'s own',
+ '# terminal has neither var and exits here, bit-for-bit legacy no-op). The token is NOT',
+ '# required at this point: a phone-spawned session whose endpoint was empty/dead at spawn',
+ '# (NODETERM_HOOK_ENDPOINT="" because no host process existed yet) carries a node id but no',
+ '# token, and nt_send_request below sources a live sibling endpoint (e.g. a headless Server',
+ '# Edition that came up AFTER the session) to heal it. Gating on the token here instead would',
+ '# exit before that failover ever ran, leaving such a session dark until it was recreated.',
+ 'if [ -z "$NODETERM_NODE_ID" ]; then',
+ ' cat >/dev/null 2>&1 || :',
+ ' exit 0',
+ 'fi',
+ '# Sourced with stdout swallowed, not only stderr: SessionStart and UserPromptSubmit are two of',
+ '# the events where Claude ADDS hook stdout to the agent\'s context (#186). The endpoint files',
+ '# nodeterm writes print nothing today — this guards the day one of the four candidate paths',
+ '# grows a stray echo or an unsilenced warning, which would otherwise be injected into every',
+ '# prompt silently.',
'if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then',
- ' . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :',
+ ' . "$NODETERM_HOOK_ENDPOINT" >/dev/null 2>&1 || :',
'fi',
'# THIS SCRIPT\'s revision, stamped on every POST (X-Nodeterm-Hook-Client) so the server can tell',
'# a session running a pre-identity script from one whose token file is merely missing — they',
@@ -126,16 +153,6 @@ export function buildManagedScript(
'}',
'nt_read_node_token',
HOOK_CURL_HEADERS_SH,
- '# Gate on the NODE ID only — it is what marks a nodeterm-spawned session (a user\'s own',
- '# terminal has neither var and exits here, bit-for-bit legacy no-op). The token is NOT',
- '# required at this point: a phone-spawned session whose endpoint was empty/dead at spawn',
- '# (NODETERM_HOOK_ENDPOINT="" because no host process existed yet) carries a node id but no',
- '# token, and nt_send_request below sources a live sibling endpoint (e.g. a headless Server',
- '# Edition that came up AFTER the session) to heal it. Gating on the token here instead would',
- '# exit before that failover ever ran, leaving such a session dark until it was recreated.',
- 'if [ -z "$NODETERM_NODE_ID" ]; then',
- ' exit 0',
- 'fi',
'payload=$(cat)',
'if [ -z "$payload" ]; then',
' exit 0',
@@ -188,7 +205,9 @@ export function buildManagedScript(
' NODETERM_HOOK_SOCK=""',
' NODETERM_HOOK_PORT=""',
' NODETERM_NODE_TOKEN_DIR=""',
- ' . "$nt_fresh" 2>/dev/null || return 1',
+ // stdout swallowed for the same reason as the primary source above (#186): in the perm-wait
+ // branch this runs in the FOREGROUND of a hook whose stdout reaches the agent's context.
+ ' . "$nt_fresh" >/dev/null 2>&1 || return 1',
' return 0',
'}',
'# One request POST against the CURRENT endpoint vars. Returns curl\'s exit status so the',