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(hook-server): a confirmation-gated control request must not be killed by the receive-phase timeout

Claude Code71a91a2122d1
diff --git a/src/core/agents/hook-server.slowloris.test.ts b/src/core/agents/hook-server.slowloris.test.ts
new file mode 100644
index 000000000..a34a7074f
--- /dev/null
+++ b/src/core/agents/hook-server.slowloris.test.ts
@@ -0,0 +1,72 @@
+// The slowloris guard is a RECEIVE-phase guard, and this pins that it stays one.
+//
+// A destructive /control/ verb (write, close) parks in the renderer for as long as the user takes
+// to answer the confirmation dialog — by design, up to the desktop's 120s `pendingControl` bound.
+// The 2s guard used to apply to the whole request lifetime, so it destroyed that socket mid-dialog:
+// the sh shim reported "control endpoint unreachable" (curl exit 52 at ~2019ms) while a late
+// confirm STILL delivered the text — the agent was told nothing happened when it had, and may
+// retry, which is a silent duplicate delivery.
+//
+// The guard is raised, not removed: nothing may park forever, so both routes keep a bounded
+// ceiling and the context-link route additionally races its handler. Spins the real hookServer,
+// same harness precedent as context-link.cli.test.ts.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { hookServer } from './hook-server'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform } from '../platform-fake'
+
+// Comfortably past the 2s receive-phase guard, and short enough to keep the suite quick.
+const HANDLER_PARK_MS = 3500
+
+let dir = ''
+
+function post(path: string, body: string): Promise<Response> {
+ return fetch(`http://127.0.0.1:${hookServer.getPort()}${path}`, {
+ method: 'POST',
+ headers: {
+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),
+ 'content-type': 'application/x-www-form-urlencoded',
+ accept: 'text/plain'
+ },
+ body
+ })
+}
+
+beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'hooksrv-slowloris-'))
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ await hookServer.start()
+ // Stands in for the renderer holding the request open on the confirmation dialog.
+ hookServer.setControlHandler(async () => {
+ await new Promise((r) => setTimeout(r, HANDLER_PARK_MS))
+ return { ok: true, message: 'sent' }
+ })
+ // Stands in for a linked-transcript read whose remote leg is slow (but not wedged).
+ hookServer.setContextLinkHandler(async () => {
+ await new Promise((r) => setTimeout(r, HANDLER_PARK_MS))
+ return 'linked transcript'
+ })
+})
+
+afterAll(() => {
+ hookServer.stop()
+ rmSync(dir, { recursive: true, force: true })
+})
+
+describe('hook server: the slowloris guard is receive-phase only', () => {
+ it('/control/ survives a handler that parks longer than the guard', async () => {
+ const res = await post('/control/write', 'nodeId=n1&arg.node=n2&arg.text=hi')
+ expect(res.status).toBe(200)
+ expect((await res.text()).trim()).toBe('sent')
+ }, 15000)
+
+ it('/context-link/ survives a read that takes longer than the guard', async () => {
+ const res = await post('/context-link/transcript', 'nodeId=n1&arg.node=n2')
+ expect(res.status).toBe(200)
+ expect((await res.text()).trim()).toBe('linked transcript')
+ }, 15000)
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index d4d78ab6e..e04d3bd2b 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -9,6 +9,23 @@ import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/nor
export const NODETERM_HOOK_PROTOCOL_VERSION = '1'
const SLOWLORIS_MS = 2000
+// Once the body is fully read the slowloris guard has done its job — it exists for the RECEIVE
+// phase (a client that dribbles bytes to pin a socket), not for the handler. But it is replaced
+// with a HIGHER ceiling, never removed: a confirmation-gated control verb legitimately parks
+// while the renderer waits for the user's answer, yet nothing may park forever. The desktop shell
+// bounds a control request at 120s (`pendingControl` in src/main/index.ts) — a bound that lives
+// OUTSIDE core, so a future core-side handler with no bound of its own would inherit an unbounded
+// socket if this were `setTimeout(0)`. 130s sits comfortably above that, so in the desktop the
+// handler's own timeout always wins and this only ever fires as a backstop.
+const CONTROL_CEILING_MS = 130_000
+
+// The context-link handler has no timeout of its own, and its remote leg reads over an SSH
+// ControlMaster that can wedge (ConnectTimeout only covers the connect). Race it so the agent
+// gets the same prose failure it would get from any other read error, instead of a session that
+// blocks indefinitely — pre-fix the 2s destroy at least unblocked the agent's curl.
+const CONTEXT_LINK_READ_MS = 30_000
+const CONTEXT_LINK_TIMEOUT_TEXT = 'Could not read linked context.'
+
// Default seconds the managed permission hook holds for a phone/canvas answer before falling
// through to Claude's interactive prompt (must stay under Claude's own hook timeout). Injected
// into a claude session's env as NODETERM_PERM_WAIT_SECS when hook-reply approvals are enabled.
@@ -32,6 +49,24 @@ function readBody(req: IncomingMessage): Promise<string> {
})
}
+/**
+ * Resolve to `fallback` if `p` has not settled within `ms`. The timer is always cleared, so a
+ * losing race never holds the process open. There is nothing to cancel in a read already in
+ * flight, so a rejection must be swallowed either way — otherwise it surfaces as an unhandled
+ * rejection once the timeout has already answered. A rejection that loses no race therefore also
+ * yields `fallback`, which for the context-link route means the caller reads the same prose
+ * failure it gets from any other read error instead of a bare 204.
+ */
+function withTimeout<T>(p: Promise<T>, ms: number, fallback: T): Promise<T> {
+ let timer: NodeJS.Timeout
+ return Promise.race([
+ p.catch(() => fallback),
+ new Promise<T>((resolve) => {
+ timer = setTimeout(() => resolve(fallback), ms)
+ })
+ ]).finally(() => clearTimeout(timer))
+}
+
// Parses application/x-www-form-urlencoded bodies (what the managed script posts).
function parseForm(body: string): Record<string, string> {
const out: Record<string, string> = {}
@@ -149,6 +184,12 @@ class HookServer {
await readBody(req),
String(req.headers['content-type'] ?? '')
)
+ // Body fully received: hand the socket from the receive-phase guard to the much larger
+ // handler ceiling. A destructive control verb parks here for as long as the user takes
+ // to answer the confirmation dialog, and the 2s guard used to destroy the socket mid-
+ // dialog — the caller saw "endpoint unreachable" while the dialog was still up, and a
+ // late confirm still delivered, so the agent was told nothing happened when it had.
+ req.setTimeout(CONTROL_CEILING_MS, () => req.destroy())
const result = this.controlHandler
? await this.controlHandler({ verb, nodeId, args })
: { ok: false, error: 'control unavailable' }
@@ -172,10 +213,18 @@ class HookServer {
await readBody(req),
String(req.headers['content-type'] ?? '')
)
+ // Same hand-off as /control/: the receive phase is over, so raise the guard to the
+ // handler ceiling rather than dropping it. The effective bound here is the race below;
+ // the socket ceiling is only the backstop behind it.
+ req.setTimeout(CONTROL_CEILING_MS, () => req.destroy())
// Always text: the caller is the sh shim, and the payload IS prose (a rendered
// transcript). The handler owns the authorization — see context-link.ts.
const text = this.contextLinkHandler
- ? await this.contextLinkHandler({ verb, nodeId, args })
+ ? await withTimeout(
+ this.contextLinkHandler({ verb, nodeId, args }),
+ CONTEXT_LINK_READ_MS,
+ CONTEXT_LINK_TIMEOUT_TEXT
+ )
: 'Context link is unavailable in this session.'
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
res.end(`${text}\n`)