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.

feat(hooks): endpoint failover — a dead pipe falls back to a live server

enes1b1b47d7aefe
diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.ts
index 0ca3bed85..bcb0bcf17 100644
--- a/src/core/agents/hooks/managed-script.test.ts
+++ b/src/core/agents/hooks/managed-script.test.ts
@@ -1,4 +1,8 @@
-import { describe, expect, it } from 'vitest'
+import { spawnSync } from 'node:child_process'
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, describe, expect, it } from 'vitest'
import { buildManagedScript } from './managed-script'
describe('buildManagedScript', () => {
@@ -79,4 +83,78 @@ describe('buildManagedScript', () => {
expect(codex).toContain('/hook/codex')
})
})
+
+ describe('endpoint failover (dead-primary retry against a live sibling endpoint)', () => {
+ it('lists the three known candidate endpoint files', () => {
+ expect(s).toContain('"$HOME/.nodeterm-server/hook-endpoint.env"')
+ expect(s).toContain('"$HOME/.config/node-terminal/hook-endpoint.env"')
+ expect(s).toContain('"$HOME/Library/Application Support/node-terminal/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('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_tried="$1"')
+ expect(s).toContain('[ "$nt_c" = "$nt_tried" ] && continue')
+ })
+ it('only considers readable candidates and returns 1 when there are none', () => {
+ expect(s).toContain('[ -r "$nt_c" ] || continue')
+ expect(s).toContain('[ "$#" -gt 0 ] || 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"')
+ expect(clearSock).toBeGreaterThan(-1)
+ expect(clearPort).toBeGreaterThan(-1)
+ expect(source).toBeGreaterThan(clearSock)
+ expect(source).toBeGreaterThan(clearPort)
+ })
+ 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.
+ expect(s).toContain('nt_request_post && return 0')
+ expect(s).toContain('if nt_pick_fallback "$NODETERM_HOOK_ENDPOINT"; then')
+ // 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.
+ expect(reposts.length).toBe(2)
+ })
+ 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.
+ const send = s.slice(s.indexOf('nt_send_request() {'), s.indexOf('nt_send_request() {') + 200)
+ expect(send).toContain('nt_request_post && return 0')
+ })
+ it('returns curl exit status from nt_request_post (no `|| true` masking) and returns 1 with no transport', () => {
+ // The POST lines end at `>/dev/null 2>&1` (status preserved), NOT `>/dev/null 2>&1 || true`.
+ expect(s).not.toContain('--data-urlencode "payload=${payload}" >/dev/null 2>&1 || true')
+ expect(s).toContain(' else\n return 1\n fi')
+ })
+ it('perm-wait branch advertises the ask in the FOREGROUND (before the poll), non-perm backgrounds it', () => {
+ // Foreground in perm-wait (pendingId reaches primary-or-fallback before the answer poll begins),
+ // backgrounded otherwise so a live session's hot path never blocks.
+ expect(s).toContain('if [ -n "$nt_pending" ]; then\n nt_send_request\nelse\n nt_send_request &\nfi')
+ // The request POST carries nodeterm_pending_id, so the fallback learns the ask too.
+ expect(s).toContain('--data-urlencode "nodeterm_pending_id=${nt_pending}"')
+ })
+ })
+})
+
+describe('buildManagedScript generated shell is syntactically valid', () => {
+ const sh = spawnSync('sh', ['-c', 'exit 0'])
+ const shAvailable = sh.status === 0 && !sh.error
+ const dir = shAvailable ? mkdtempSync(join(tmpdir(), 'nt-managed-script-')) : ''
+ afterAll(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true })
+ })
+ for (const agentId of ['claude', 'codex', 'gemini']) {
+ it.skipIf(!shAvailable)(`passes \`sh -n\` for ${agentId}`, () => {
+ const file = join(dir, `hook-${agentId}.sh`)
+ writeFileSync(file, buildManagedScript(agentId), 'utf8')
+ const res = spawnSync('sh', ['-n', file], { encoding: 'utf8' })
+ expect(res.stderr || '').toBe('')
+ expect(res.status).toBe(0)
+ })
+ }
})
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index 4df59a3ac..8fae7d291 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -3,6 +3,17 @@
// outside nodeterm-spawned sessions (gating via NODETERM_NODE_ID), and posts the
// raw hook payload to the loopback server. Fails open at every step.
//
+// Endpoint failover: a session's env points at ONE
+// endpoint file ($NODETERM_HOOK_ENDPOINT). A Mac-spawned remote session points at the
+// 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 (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).
+//
// Deterministic hook-reply approvals (docs/hook-reply-approvals.md): when
// NODETERM_PERM_WAIT_SECS is set (> 0) in the session env AND the incoming hook is a
// PermissionRequest, the script generates a pendingId, drops the request JSON under
@@ -45,24 +56,76 @@ export function buildManagedScript(agentId: string): string {
' ;;',
' esac',
'fi',
- 'if [ -n "$NODETERM_HOOK_SOCK" ]; then',
- ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1.5 \\',
- ' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
- ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
- ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
- ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true',
- 'elif [ -n "$NODETERM_HOOK_PORT" ]; then',
- ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
- ' --connect-timeout 0.5 --max-time 1.5 \\',
- ' -H "Content-Type: application/x-www-form-urlencoded" \\',
- ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
- ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
- ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
- ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
- ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true',
+ '# --- Endpoint failover helpers --------------------------------------------------',
+ '# Source the freshest EXISTING candidate endpoint file, skipping the already-tried path',
+ '# ($1), into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION}. 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.',
+ 'nt_pick_fallback() {',
+ ' nt_tried="$1"',
+ ' set --',
+ ' for nt_c in \\',
+ ' "$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',
+ ' 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',
+ ' NODETERM_HOOK_SOCK=""',
+ ' NODETERM_HOOK_PORT=""',
+ ' . "$nt_fresh" 2>/dev/null || return 1',
+ ' return 0',
+ '}',
+ '# One request POST against the CURRENT endpoint vars. Returns curl\'s exit status so the',
+ '# caller can fail over; returns 1 when there is no transport at all (unset/unreadable',
+ '# endpoint) so that case also tries a fallback.',
+ 'nt_request_post() {',
+ ' if [ -n "$NODETERM_HOOK_SOCK" ]; then',
+ ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
+ ' --connect-timeout 0.5 --max-time 1.5 \\',
+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',
+ ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
+ ' --data-urlencode "payload=${payload}" >/dev/null 2>&1',
+ ' elif [ -n "$NODETERM_HOOK_PORT" ]; then',
+ ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
+ ' --connect-timeout 0.5 --max-time 1.5 \\',
+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',
+ ' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',
+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
+ ' --data-urlencode "payload=${payload}" >/dev/null 2>&1',
+ ' else',
+ ' 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.',
+ 'nt_send_request() {',
+ ' nt_request_post && return 0',
+ ' if nt_pick_fallback "$NODETERM_HOOK_ENDPOINT"; then',
+ ' nt_request_post',
+ ' fi',
+ '}',
+ '# 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',
+ '# begins — and any fallback it sources persists for the "answered" POST below, which then targets',
+ '# the same live endpoint. Otherwise it is backgrounded so a live session\'s hot path never blocks',
+ '# on the network (fire-and-forget, exactly as before).',
+ 'if [ -n "$nt_pending" ]; then',
+ ' nt_send_request',
+ 'else',
+ ' nt_send_request &',
'fi',
'# Hold the hook open for a phone/canvas answer file, polling every 0.5s up to the armed seconds.',
'if [ -n "$nt_pending" ]; then',