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(hooks): the fallback walks past dead sibling tunnels to a live local endpoint

enese8fcbec68075
diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.ts
index cc9d7a378..444aa2261 100644
--- a/src/core/agents/hooks/managed-script.test.ts
+++ b/src/core/agents/hooks/managed-script.test.ts
@@ -189,36 +189,73 @@ describe('buildManagedScript', () => {
expect(s).toContain('"$HOME"/.nodeterm/hook-endpoint-*.env')
expect(s).not.toContain('"$HOME/.nodeterm/hook-endpoint-*.env"')
})
- it('picks the FRESHEST existing candidate (ls -t | head -n 1)', () => {
- expect(s).toContain('nt_fresh=$(ls -t "$@" 2>/dev/null | head -n 1)')
+ it('emits the LOCAL endpoints before the tunnel glob (failure-domain order, not mtime)', () => {
+ // The ordering IS the fix. Every hook-endpoint-*.env tunnel on a host terminates at the same
+ // desktop, so they share one fate; a local endpoint (the host's own Server Edition, or a
+ // desktop installed here) fails independently. Sorting the whole list by mtime buried the one
+ // live endpoint under N dead siblings — see the measured table in managed-script.ts.
+ const list = s.slice(s.indexOf('nt_candidates() {'), s.indexOf('nt_adopt() {'))
+ const server = list.indexOf('"$HOME/.nodeterm-server/hook-endpoint.env"')
+ const appSupport = list.indexOf('"$HOME/Library/Application Support/node-terminal/hook-endpoint.env"')
+ const glob = list.indexOf('"$HOME"/.nodeterm/hook-endpoint-*.env')
+ expect(server).toBeGreaterThan(-1)
+ expect(glob).toBeGreaterThan(appSupport)
+ expect(appSupport).toBeGreaterThan(server)
+ })
+ it('keeps mtime as the tie-break WITHIN the tunnel group only (ls -t over the glob matches)', () => {
+ // The live project's endpoint is rewritten and VERIFIED on every connect, so freshest-first is
+ // still the right order among tunnels — it is only wrong when applied across failure domains.
+ expect(s).toContain('ls -t "$@" 2>/dev/null')
+ // The whole-list, single-winner rule is gone: no `head -n 1` anywhere in the candidate scan.
+ expect(s).not.toContain('ls -t "$@" 2>/dev/null | head -n 1')
})
it('SKIPS the endpoint file already tried (compares each candidate to the tried path)', () => {
- expect(s).toContain('nt_pick_fallback "$NODETERM_HOOK_ENDPOINT"')
+ expect(s).toContain('nt_candidates "$NODETERM_HOOK_ENDPOINT"')
expect(s).toContain('nt_tried="$1"')
expect(s).toContain('[ "$nt_c" = "$nt_tried" ] && continue')
})
- it('only considers readable candidates and returns 1 when there are none', () => {
+ it('only considers readable candidates and returns nothing when there are none', () => {
expect(s).toContain('[ -r "$nt_c" ] || continue')
- expect(s).toContain('[ "$#" -gt 0 ] || return 1')
+ expect(s).toContain('[ "$#" -gt 0 ] || return 0')
+ expect(s).toContain('[ -n "$nt_list" ] || return 1')
})
- it('clears SOCK/PORT before sourcing the fallback so a transport switch takes effect', () => {
- const clearSock = s.indexOf('NODETERM_HOOK_SOCK=""')
- const clearPort = s.indexOf('NODETERM_HOOK_PORT=""')
- const source = s.indexOf('. "$nt_fresh"')
+ it('clears SOCK/PORT before sourcing EACH adopted candidate so no transport leaks across', () => {
+ const adopt = s.slice(s.indexOf('nt_adopt() {'), s.indexOf('nt_request_post() {'))
+ const clearSock = adopt.indexOf('NODETERM_HOOK_SOCK=""')
+ const clearPort = adopt.indexOf('NODETERM_HOOK_PORT=""')
+ const clearDir = adopt.indexOf('NODETERM_NODE_TOKEN_DIR=""')
+ const source = adopt.indexOf('. "$1"')
expect(clearSock).toBeGreaterThan(-1)
expect(clearPort).toBeGreaterThan(-1)
+ expect(clearDir).toBeGreaterThan(-1)
expect(source).toBeGreaterThan(clearSock)
expect(source).toBeGreaterThan(clearPort)
+ expect(source).toBeGreaterThan(clearDir)
})
- it('re-POSTs against the fallback exactly ONCE on a failed primary POST', () => {
- // nt_send_request: primary attempt short-circuits on success (`&& return 0`), else a single
- // fallback source + one re-POST. No loop → at most one retry.
+ it('walks SEVERAL candidates after a failed primary POST, capped by nt_fallback_max', () => {
+ // One retry could not get past a single stale sibling — which is exactly what the measured
+ // host had. The walk is bounded because a dead reverse-tunnel socket is not cheap to fail:
+ // sshd accepts and never answers, so each attempt can burn the full --max-time.
expect(s).toContain('nt_request_post && return 0')
- expect(s).toContain('if nt_pick_fallback "$NODETERM_HOOK_ENDPOINT"; then')
+ expect(s).toContain('nt_fallback_max=3')
+ expect(s).toContain('[ "$nt_n" -le "$nt_fallback_max" ] || break')
// Count CALLS (followed by whitespace/EOL), not the `nt_request_post() {` definition (`(`).
const reposts = s.match(/\n *nt_request_post(?=\s|$)/g) ?? []
- // Two textual calls: the primary attempt and the single fallback retry.
+ // Two textual calls: the primary attempt and the ONE inside the bounded loop.
expect(reposts.length).toBe(2)
+ // The token is re-read per adopted candidate, inside the loop — not once before it.
+ const loop = s.slice(s.indexOf('for nt_ep in "$@"; do'), s.indexOf(' return 1\n}'))
+ expect(loop).toContain('nt_read_node_token')
+ expect(loop).toContain('nt_adopt "$nt_ep" || continue')
+ })
+ it('splits the candidate list on NEWLINES with globbing off (paths contain spaces)', () => {
+ // "Application Support" has a space in it. Default IFS would split it into two bogus paths;
+ // an unquoted expansion without `set -f` would re-glob a path containing a glob character.
+ expect(s).toContain('IFS="\n"')
+ expect(s).toContain(' set -f\n')
+ expect(s).toContain(' set +f\n')
+ expect(s).toContain('nt_ifs="$IFS"')
+ expect(s).toContain('IFS="$nt_ifs"')
})
it('leaves the happy path untouched: a successful primary POST does no fallback work', () => {
// `&& return 0` guarantees nt_pick_fallback / the candidate scan never run when curl exits 0.
@@ -393,6 +430,261 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {
}
)
+ /**
+ * The measured outage, reproduced. On the live host (Mac closed, 8 agents running):
+ *
+ * hook-endpoint-project-mrkigsjp-4.env 13:25 the primary — excluded as already tried
+ * hook-endpoint-project-msq9marh-4.env 12:52 another project's tunnel to the SAME Mac, dead
+ * .nodeterm-server/hook-endpoint.env 00:26 the host's own Server Edition — ALIVE
+ *
+ * A freshest-by-mtime single retry lands on the dead sibling and gives up; that host's mirror
+ * held 0 nodes and 0 events while every session worked. Ordering by FAILURE DOMAIN (locals before
+ * tunnels) is what reaches the live endpoint — and it reaches it FIRST, so the dead sibling is
+ * never even dialled.
+ */
+ it.skipIf(!shAvailable)(
+ 'reaches the host-local Server Edition even though a fresher sibling tunnel outranks it by mtime',
+ () => {
+ const home = join(dir, 'home-local-first')
+ const bin = join(dir, 'bin-local-first')
+ const log = join(dir, 'curl-local-first.log')
+ mkdirSync(join(home, '.nodeterm'), { recursive: true })
+ mkdirSync(join(home, '.nodeterm-server'), { recursive: true })
+ mkdirSync(bin, { recursive: true })
+ // The primary: this session's own reverse tunnel, dead with the laptop closed.
+ const primary = join(home, '.nodeterm', 'hook-endpoint-project-mrkigsjp-4.env')
+ writeFileSync(
+ primary,
+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'hook-mrkigsjp.sock')}\nNODETERM_HOOK_TOKEN=primary-token\nNODETERM_HOOK_VERSION=2\n`,
+ 'utf8'
+ )
+ // Another project's tunnel to the SAME Mac. Also dead — they share one fate.
+ const sibling = join(home, '.nodeterm', 'hook-endpoint-project-msq9marh-4.env')
+ writeFileSync(
+ sibling,
+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'hook-msq9marh.sock')}\nNODETERM_HOOK_TOKEN=sibling-token\nNODETERM_HOOK_VERSION=2\n`,
+ 'utf8'
+ )
+ // The always-on Server Edition on THIS host: oldest file on disk, and the only live endpoint.
+ const local = join(home, '.nodeterm-server', 'hook-endpoint.env')
+ writeFileSync(
+ local,
+ 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=local-token\nNODETERM_HOOK_VERSION=2\n',
+ 'utf8'
+ )
+ // Exactly the measured mtime ranking: primary newest, sibling next, local oldest by hours.
+ const now = Date.now() / 1000
+ utimesSync(primary, now, now)
+ utimesSync(sibling, now - 1800, now - 1800)
+ utimesSync(local, now - 46_000, now - 46_000)
+ // Every tunnel socket is dead; only the local TCP port answers.
+ writeFileSync(
+ join(bin, 'curl'),
+ fakeCurlScript(log, 'case "$*" in *127.0.0.1:45999*) : ;; *) exit 7 ;; esac'),
+ { encoding: 'utf8', mode: 0o755 }
+ )
+ const script = join(dir, 'claude-local-first.sh')
+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"PermissionRequest"}',
+ env: {
+ PATH: `${bin}:${process.env.PATH ?? ''}`,
+ HOME: home,
+ NODETERM_NODE_ID: 'node-1',
+ NODETERM_HOOK_ENDPOINT: primary,
+ NODETERM_PERM_WAIT_SECS: '1'
+ }
+ })
+ expect(res.status).toBe(0)
+ const calls = curlCalls(log)
+ // Two calls: the dead primary, then the LOCAL endpoint. The dead sibling tunnel — freshest of
+ // the remaining candidates, and the only one the old single retry ever tried — is skipped
+ // entirely, because it belongs to the failure domain that just proved itself dead.
+ expect(calls).toHaveLength(2)
+ expect(calls[0].argv).toContain('--unix-socket')
+ expect(calls[0].argv).toContain('hook-mrkigsjp.sock')
+ expect(calls[1].argv).toContain('http://127.0.0.1:45999/hook/claude')
+ expect(calls[1].argv).not.toContain('--unix-socket')
+ expect(calls[1].cfg).toContain('header = "X-Nodeterm-Hook-Token: local-token"')
+ for (const c of calls) expect(c.argv).not.toContain('hook-msq9marh.sock')
+ }
+ )
+
+ // Locals are ordered too, and one of them has a SPACE in its path. A dead local must not end the
+ // walk (an exited Server Edition leaves its endpoint file behind), and default IFS would have
+ // split "Application Support" into two paths that exist nowhere.
+ it.skipIf(!shAvailable)('walks past a dead local to one whose path contains a space', () => {
+ const home = join(dir, 'home-space')
+ const bin = join(dir, 'bin-space')
+ const log = join(dir, 'curl-space.log')
+ const appSupportDir = join(home, 'Library', 'Application Support', 'node-terminal')
+ mkdirSync(join(home, '.nodeterm'), { recursive: true })
+ mkdirSync(join(home, '.nodeterm-server'), { recursive: true })
+ mkdirSync(appSupportDir, { recursive: true })
+ mkdirSync(bin, { recursive: true })
+ const primary = join(home, '.nodeterm', 'hook-endpoint-project-a.env')
+ writeFileSync(
+ primary,
+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'a.sock')}\nNODETERM_HOOK_TOKEN=primary-token\nNODETERM_HOOK_VERSION=2\n`,
+ 'utf8'
+ )
+ // A Server Edition that is no longer running: its endpoint file outlived it.
+ writeFileSync(
+ join(home, '.nodeterm-server', 'hook-endpoint.env'),
+ 'NODETERM_HOOK_PORT=46000\nNODETERM_HOOK_TOKEN=stale-server-token\nNODETERM_HOOK_VERSION=2\n',
+ 'utf8'
+ )
+ // The live desktop installed on this same host.
+ writeFileSync(
+ join(appSupportDir, 'hook-endpoint.env'),
+ 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=desktop-token\nNODETERM_HOOK_VERSION=2\n',
+ 'utf8'
+ )
+ writeFileSync(
+ join(bin, 'curl'),
+ fakeCurlScript(log, 'case "$*" in *127.0.0.1:45999*) : ;; *) exit 7 ;; esac'),
+ { encoding: 'utf8', mode: 0o755 }
+ )
+ const script = join(dir, 'claude-space.sh')
+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"PermissionRequest"}',
+ env: {
+ PATH: `${bin}:${process.env.PATH ?? ''}`,
+ HOME: home,
+ NODETERM_NODE_ID: 'node-1',
+ NODETERM_HOOK_ENDPOINT: primary,
+ NODETERM_PERM_WAIT_SECS: '1'
+ }
+ })
+ expect(res.status).toBe(0)
+ const calls = curlCalls(log)
+ // primary (dead socket) → stale Server Edition (dead port) → the desktop under the spaced path.
+ expect(calls).toHaveLength(3)
+ expect(calls[0].argv).toContain('--unix-socket')
+ expect(calls[1].argv).toContain('http://127.0.0.1:46000/hook/claude')
+ expect(calls[2].argv).toContain('http://127.0.0.1:45999/hook/claude')
+ expect(calls[2].cfg).toContain('header = "X-Nodeterm-Hook-Token: desktop-token"')
+ })
+
+ // The bound. A dead reverse-tunnel socket is NOT cheap to fail — sshd accepts the connection and
+ // then never answers, so each attempt can burn the full --max-time. A host with a dozen stale
+ // project endpoints must not turn every hook event into a dozen hanging curls.
+ it.skipIf(!shAvailable)('stops after nt_fallback_max fallback POSTs, however many candidates exist', () => {
+ const home = join(dir, 'home-bound')
+ const bin = join(dir, 'bin-bound')
+ const log = join(dir, 'curl-bound.log')
+ mkdirSync(join(home, '.nodeterm'), { recursive: true })
+ mkdirSync(bin, { recursive: true })
+ const primary = join(home, '.nodeterm', 'hook-endpoint-project-0.env')
+ writeFileSync(primary, 'NODETERM_HOOK_PORT=46000\nNODETERM_HOOK_VERSION=2\n', 'utf8')
+ // Eight more dead tunnels to the same (closed) desktop.
+ const now = Date.now() / 1000
+ for (let i = 1; i <= 8; i++) {
+ const f = join(home, '.nodeterm', `hook-endpoint-project-${i}.env`)
+ writeFileSync(f, `NODETERM_HOOK_PORT=${46000 + i}\nNODETERM_HOOK_VERSION=2\n`, 'utf8')
+ utimesSync(f, now - i, now - i)
+ }
+ utimesSync(primary, now, now)
+ // Nothing anywhere answers.
+ writeFileSync(join(bin, 'curl'), fakeCurlScript(log, 'exit 7'), {
+ encoding: 'utf8',
+ mode: 0o755
+ })
+ const script = join(dir, 'claude-bound.sh')
+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"PermissionRequest"}',
+ env: {
+ PATH: `${bin}:${process.env.PATH ?? ''}`,
+ HOME: home,
+ NODETERM_NODE_ID: 'node-1',
+ NODETERM_HOOK_ENDPOINT: primary,
+ NODETERM_PERM_WAIT_SECS: '1'
+ }
+ })
+ expect(res.status).toBe(0)
+ const calls = curlCalls(log)
+ // 1 primary + 3 fallbacks, never 1 + 8.
+ expect(calls).toHaveLength(4)
+ // And they are the FRESHEST three tunnels, in order — mtime is still the tie-break within the
+ // tunnel group (this host has no local endpoint at all).
+ expect(calls[1].argv).toContain('127.0.0.1:46001')
+ expect(calls[2].argv).toContain('127.0.0.1:46002')
+ expect(calls[3].argv).toContain('127.0.0.1:46003')
+ })
+
+ // Requirement 4, pinned: the overwhelmingly common host is one project, one tunnel, no Server
+ // Edition. Its only candidate is the endpoint it already tried, so the walk must find nothing and
+ // fire nothing — exactly as before this change.
+ it.skipIf(!shAvailable)('a single-tunnel host with no local endpoint does no fallback work', () => {
+ const home = join(dir, 'home-single')
+ const bin = join(dir, 'bin-single')
+ const log = join(dir, 'curl-single.log')
+ mkdirSync(join(home, '.nodeterm'), { recursive: true })
+ mkdirSync(bin, { recursive: true })
+ const primary = join(home, '.nodeterm', 'hook-endpoint-project-only.env')
+ writeFileSync(
+ primary,
+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'only.sock')}\nNODETERM_HOOK_TOKEN=only-token\nNODETERM_HOOK_VERSION=2\n`,
+ 'utf8'
+ )
+ writeFileSync(join(bin, 'curl'), fakeCurlScript(log, 'exit 7'), { encoding: 'utf8', mode: 0o755 })
+ const script = join(dir, 'claude-single.sh')
+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"PermissionRequest"}',
+ env: {
+ PATH: `${bin}:${process.env.PATH ?? ''}`,
+ HOME: home,
+ NODETERM_NODE_ID: 'node-1',
+ NODETERM_HOOK_ENDPOINT: primary,
+ NODETERM_PERM_WAIT_SECS: '1'
+ }
+ })
+ expect(res.status).toBe(0)
+ expect(curlCalls(log)).toHaveLength(1)
+ })
+
+ // The happy path pays for none of this: a primary POST that SUCCEEDS must produce exactly one
+ // curl and never touch the candidate scan, even on a host stuffed with live-looking endpoints.
+ it.skipIf(!shAvailable)('a successful primary POST fires exactly one curl and scans nothing', () => {
+ const home = join(dir, 'home-happy')
+ const bin = join(dir, 'bin-happy')
+ const log = join(dir, 'curl-happy.log')
+ mkdirSync(join(home, '.nodeterm'), { recursive: true })
+ mkdirSync(join(home, '.nodeterm-server'), { recursive: true })
+ mkdirSync(bin, { recursive: true })
+ const primary = join(home, '.nodeterm', 'hook-endpoint-project-a.env')
+ writeFileSync(primary, 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_VERSION=2\n', 'utf8')
+ for (const other of [
+ join(home, '.nodeterm', 'hook-endpoint-project-b.env'),
+ join(home, '.nodeterm-server', 'hook-endpoint.env')
+ ]) {
+ writeFileSync(other, 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_VERSION=2\n', 'utf8')
+ }
+ writeFileSync(join(bin, 'curl'), fakeCurlScript(log), { encoding: 'utf8', mode: 0o755 })
+ const script = join(dir, 'claude-happy.sh')
+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })
+ const res = spawnSync('sh', [script], {
+ encoding: 'utf8',
+ input: '{"hook_event_name":"PermissionRequest"}',
+ env: {
+ PATH: `${bin}:${process.env.PATH ?? ''}`,
+ HOME: home,
+ NODETERM_NODE_ID: 'node-1',
+ NODETERM_HOOK_ENDPOINT: primary,
+ NODETERM_PERM_WAIT_SECS: '1'
+ }
+ })
+ expect(res.status).toBe(0)
+ expect(curlCalls(log)).toHaveLength(1)
+ })
+
// The other half of the same subtlety: an OLDER instance's endpoint file carries no
// NODETERM_NODE_TOKEN_DIR line at all. Sourcing it must leave the dir EMPTY (nt_pick_fallback
// clears it first), not silently keep ours — otherwise the retry reads OUR token dir and hands
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index 3fa6b55c1..bbbbe4b9e 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -8,12 +8,40 @@
// reverse-tunnel endpoint the Mac's RemoteHooks wrote; when the Mac is offline that pipe
// is dead and the POST fails silently, so the session goes dark — even when the SAME host
// runs an always-on headless Server Edition whose endpoint file is alive right next to it.
-// So the request POST captures curl's exit status and, on failure, retries ONCE against the
-// freshest OTHER endpoint file among the known candidates (the SSH reverse-tunnel endpoints
-// `~/.nodeterm/hook-endpoint-*.env` + the server-edition dataDir + the desktop userData dirs),
-// sourcing its sock/port/token. The happy path (primary alive) is
-// unchanged — curl succeeds, no candidate scan, no re-POST. A host with no candidate files
-// behaves exactly as before (nothing posts).
+// So the request POST captures curl's exit status and, on failure, walks the OTHER known endpoint
+// files (the SSH reverse-tunnel endpoints `~/.nodeterm/hook-endpoint-*.env` + the server-edition
+// dataDir + the desktop userData dirs), sourcing each one's sock/port/token, until one POST
+// succeeds. The happy path (primary alive) is unchanged — curl succeeds, no candidate scan, no
+// re-POST. A host with no candidate files behaves exactly as before (nothing posts).
+//
+// FALLBACK ORDERING AND BOUND — both were wrong, and the failure was total.
+// v1 picked ONE candidate, the freshest by mtime, and retried exactly once. Measured on a live
+// host with the Mac closed and 8 agents running:
+// hook-endpoint-project-mrkigsjp-4.env 13:25 the primary — excluded as already tried
+// hook-endpoint-project-msq9marh-4.env 12:52 another project's tunnel to the SAME Mac, dead
+// .nodeterm-server/hook-endpoint.env 00:26 the host's own Server Edition — ALIVE
+// The single retry landed on the dead sibling and gave up; the live local endpoint was never
+// tried, and that host's mirror held 0 nodes and 0 events while 8 sessions worked. Two fixes:
+// 1. ORDER BY FAILURE DOMAIN, NOT BY MTIME. Every `hook-endpoint-*.env` tunnel on a host
+// terminates at the SAME desktop, so they share one fate — mtime ranks a dead sibling above a
+// listening local server, and the more projects a host has, the deeper the live endpoint is
+// buried. A LOCAL endpoint (the host's own Server Edition, then a desktop installed on this
+// host) is written by a process running HERE and fails independently, so locals go first;
+// tunnels follow, freshest-first among themselves (the live project's endpoint is rewritten
+// and VERIFIED on every connect, so mtime is a good tie-break WITHIN that group). The cost of
+// being wrong is asymmetric: preferring a local when a sibling tunnel was in fact alive still
+// delivers the event (the local instance pushes it) and only loses the desktop's own badge;
+// preferring tunnels when they are all dead loses the event entirely.
+// 2. TRY SEVERAL, BUT BOUND IT (`nt_fallback_max`, 3). One retry cannot get past even a single
+// stale sibling. The bound is what keeps the cure from being its own outage: a dead
+// reverse-tunnel socket is not cheap to fail — sshd ACCEPTS the connection and then never
+// answers, so each attempt can burn the full `--max-time 1.5`. 3 is chosen against the
+// candidate list, not picked round: at most 3 local slots exist and the two desktop userData
+// paths are per-OS (mutually exclusive), so a real host has at most 2 locals — 3 attempts
+// therefore always reaches a live local endpoint AND still leaves at least one tunnel slot,
+// while capping the added latency at ~4.5s on a path that has already failed.
+// A single-desktop host — one project, one tunnel, no Server Edition — is untouched: the only
+// candidate is the tried one, the list comes back empty, and nothing else runs.
//
// Stale-project self-heal (the glob candidate): a remote session's `NODETERM_HOOK_ENDPOINT` is
// baked into its tmux session at CREATION (`new-session -A -e …`, which tmux ignores when the
@@ -186,38 +214,63 @@ export function buildManagedScript(
' esac',
'fi',
'# --- Endpoint failover helpers --------------------------------------------------',
- '# Source the freshest EXISTING candidate endpoint file, skipping the already-tried path',
- '# ($1), into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION} + NODETERM_NODE_TOKEN_DIR. Returns 0 if one',
- '# was sourced, else 1.',
- '# SOCK/PORT are cleared first so a primary-vs-fallback transport switch (e.g. dead SOCK →',
- '# live PORT) never leaves the stale transport winning in the re-POST below. NODE_TOKEN_DIR is',
- '# cleared for the same reason and one more: our token belongs to the instance that MINTED it, so',
- '# carrying our dir into someone else\'s endpoint would point the read at a directory that server',
- '# cannot verify. Cleared, the newly sourced file sets its own — we then present THAT instance\'s',
- '# token for this node, or (if it has none) nothing at all, which is honest `legacy`.',
- 'nt_pick_fallback() {',
+ // How many endpoints we may POST to AFTER the primary failed. See the "Fallback ordering and
+ // bound" block comment above buildManagedScript for the full reasoning; the short version:
+ // the ordered list is (at most 3) LOCAL endpoints followed by the reverse tunnels, only one or
+ // two locals can exist on a real host (the two desktop userData paths are per-OS and mutually
+ // exclusive), so 3 attempts always reaches a live local endpoint AND still leaves a tunnel slot.
+ // The cost ceiling is what bounds it: each dead attempt can burn --max-time 1.5s, because an
+ // sshd-held reverse-tunnel socket ACCEPTS and then never answers.
+ 'nt_fallback_max=3',
+ '# Print the candidate endpoint files, ONE PER LINE, most-likely-alive first, skipping the',
+ '# already-tried path ($1) and anything unreadable. Ordering, and why it is not mtime:',
+ '# 1. LOCAL endpoints — the host\'s own Server Edition, then a desktop installed on this host.',
+ '# They are written by a process running HERE, a different failure domain from the tunnels.',
+ '# 2. The per-project SSH reverse tunnels, freshest first (the old whole-list rule, kept as the',
+ '# tie-break within this group, because the live project\'s endpoint is rewritten and VERIFIED',
+ '# on every connect).',
+ '# The tunnels all terminate at the SAME desktop, so they share one fate: when the primary tunnel',
+ '# is dead (closed laptop) its siblings are almost always dead too, and mtime happily ranks those',
+ '# siblings above a local endpoint that is actually listening. That is the whole bug — a host with',
+ '# an always-on Server Edition sat silent while every one of its agents ran.',
+ 'nt_candidates() {',
' nt_tried="$1"',
- ' set --',
' for nt_c in \\',
- // Unquoted glob (with $HOME itself still quoted): the per-project SSH reverse-tunnel
- // endpoints. On no match the pattern stays literal and the `-r` test below drops it.
- ' "$HOME"/.nodeterm/hook-endpoint-*.env \\',
' "$HOME/.nodeterm-server/hook-endpoint.env" \\',
' "$HOME/.config/node-terminal/hook-endpoint.env" \\',
' "$HOME/Library/Application Support/node-terminal/hook-endpoint.env"; do',
' [ "$nt_c" = "$nt_tried" ] && continue',
' [ -r "$nt_c" ] || continue',
+ ' printf \'%s\\n\' "$nt_c"',
+ ' done',
+ ' set --',
+ // Unquoted glob (with $HOME itself still quoted): the per-project SSH reverse-tunnel
+ // endpoints. On no match the pattern stays literal and the `-r` test below drops it.
+ ' for nt_c in "$HOME"/.nodeterm/hook-endpoint-*.env; do',
+ ' [ "$nt_c" = "$nt_tried" ] && continue',
+ ' [ -r "$nt_c" ] || continue',
' set -- "$@" "$nt_c"',
' done',
- ' [ "$#" -gt 0 ] || return 1',
- ' nt_fresh=$(ls -t "$@" 2>/dev/null | head -n 1)',
- ' [ -n "$nt_fresh" ] && [ -r "$nt_fresh" ] || return 1',
+ ' [ "$#" -gt 0 ] || return 0',
+ ' ls -t "$@" 2>/dev/null',
+ '}',
+ '# Adopt one candidate endpoint file ($1): source it into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION}',
+ '# + NODETERM_NODE_TOKEN_DIR. Returns 0 if it was sourced, else 1.',
+ '# SOCK/PORT are cleared first so a primary-vs-fallback transport switch (e.g. dead SOCK →',
+ '# live PORT) never leaves the stale transport winning in the re-POST below — and, now that we',
+ '# may walk several candidates, so one candidate\'s transport never leaks into the next one.',
+ '# NODE_TOKEN_DIR is cleared for the same reason and one more: our token belongs to the instance',
+ '# that MINTED it, so carrying our dir into someone else\'s endpoint would point the read at a',
+ '# directory that server cannot verify. Cleared, the newly sourced file sets its own — we then',
+ '# present THAT instance\'s token for this node, or (if it has none) nothing at all, which is',
+ '# honest `legacy`.',
+ 'nt_adopt() {',
' NODETERM_HOOK_SOCK=""',
' NODETERM_HOOK_PORT=""',
' NODETERM_NODE_TOKEN_DIR=""',
// 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',
+ ' . "$1" >/dev/null 2>&1 || return 1',
' return 0',
'}',
'# One request POST against the CURRENT endpoint vars. Returns curl\'s exit status so the',
@@ -248,20 +301,42 @@ export function buildManagedScript(
' return 1',
' fi',
'}',
- '# Request POST with a single fallback retry. On a failed primary POST, source the freshest',
- '# OTHER endpoint file (nt_pick_fallback) and re-POST with its sock/port/token — so a session',
- '# whose primary endpoint is dead (offline Mac reverse-tunnel) still reaches an alive server',
- '# (e.g. the headless Server Edition) sitting right next to it. In the perm-wait branch this',
- '# also carries nodeterm_pending_id to the fallback, so the phone/canvas still learns the ask.',
+ '# Request POST with a BOUNDED fallback walk. On a failed primary POST, try the OTHER endpoint',
+ '# files in most-likely-alive order (nt_candidates) — at most $nt_fallback_max of them — and stop',
+ '# at the first POST that succeeds. So a session whose primary endpoint is dead (offline Mac',
+ '# reverse-tunnel) still reaches an alive server (e.g. the headless Server Edition) sitting right',
+ '# next to it, EVEN when several equally-dead sibling tunnels are listed ahead of it by mtime —',
+ '# which is what a single freshest-only retry could never get past. In the perm-wait branch this',
+ '# also carries nodeterm_pending_id to whichever endpoint answers, so the phone/canvas still',
+ '# learns the ask.',
+ '# The happy path is untouched: `&& return 0` means a successful primary POST runs no glob, no',
+ '# subshell and no second curl, exactly as before.',
'nt_send_request() {',
' nt_request_post && return 0',
- ' if nt_pick_fallback "$NODETERM_HOOK_ENDPOINT"; then',
- ' # The token is re-read HERE, not once at the top: it must come from the dir the endpoint we',
- ' # just adopted advertises. Reusing the primary\'s would send our kid to a server that cannot',
- ' # judge it — harmless, but also pointless, and it would hide a real identity behind a legacy.',
+ ' nt_list=$(nt_candidates "$NODETERM_HOOK_ENDPOINT")',
+ ' [ -n "$nt_list" ] || return 1',
+ ' # Split the list on NEWLINES only, so a candidate path containing spaces survives (the macOS',
+ ' # "Application Support" entry already has one). `set -f` for the same span, so a path with a',
+ ' # glob character in it is not re-expanded by the unquoted $nt_list.',
+ ' nt_ifs="$IFS"',
+ ' set -f',
+ ' IFS="\n"',
+ ' set -- $nt_list',
+ ' set +f',
+ ' IFS="$nt_ifs"',
+ ' nt_n=0',
+ ' for nt_ep in "$@"; do',
+ ' nt_n=$((nt_n + 1))',
+ ' [ "$nt_n" -le "$nt_fallback_max" ] || break',
+ ' nt_adopt "$nt_ep" || continue',
+ ' # The token is re-read HERE, per candidate, not once at the top: it must come from the dir',
+ ' # the endpoint we just adopted advertises. Reusing the primary\'s (or the previous',
+ ' # candidate\'s) would send our kid to a server that cannot judge it — harmless, but also',
+ ' # pointless, and it would hide a real identity behind a legacy.',
' nt_read_node_token',
- ' nt_request_post',
- ' fi',
+ ' nt_request_post && return 0',
+ ' done',
+ ' return 1',
'}',
'# Advertise status (+ pendingId in the perm-wait branch). In the perm-wait branch this runs in',
'# the FOREGROUND so the ask reaches the (primary or fallback) server before the answer-file poll',