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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(hooks): gate structured answers on the hook script revision
review24883914b408
diff --git a/CLAUDE.md b/CLAUDE.mdindex 995b1d164..0eb6287f7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2188,11 +2188,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile(3) answer content never rides an argv (the answered POST carries the decoded verb; SSH writes go onstdin); (4) a plain `allow` maps to `updatedInput:{}` for a plan and is swallowed (hook keepsholding) for a question — core refuses to write it and the header hides ✓ Approve for that ticket;- (5) these two tools hold 540 s (`PERM_WAIT_SECS_INTERACTIVE`) under the 600 s default command-hook- timeout our installers never override — except a subagent's request, whose dialog awaits the hook.- An old script on an SSH host ignores JSON answers (prints nothing → TUI answers). The renderer gets- `held: {pendingId, toolName}` on the event/store (kept while blocked OR waiting), separate from the- approve/deny `pendingId` the mirror strips from a question. Desktop local + SSH, Server Edition local;+ (5) these two tools hold 540 s (`PERM_WAIT_SECS_INTERACTIVE`) under the explicit `timeout: 600` we+ write on the PermissionRequest handler — except a subagent's request (payload carries `agent_id`),+ whose dialog awaits the hook; (6) structured answers are gated on the SCRIPT REVISION: an old script on+ an SSH host (rewritten only at connect) silently ignores JSON while the write succeeds, so the hook+ server keeps `held` only for `clientRevision >= MIN_STRUCTURED_ANSWER_REVISION` and core refuses a+ structured answer (or a plain plan allow) for a ticket it did not record as capable — never a false+ "answered". The renderer gets `held: {pendingId, toolName}` on the event/store (kept while blocked OR+ waiting), separate from the approve/deny `pendingId` the mirror strips from a question. Desktop local + SSH, Server Edition local;relay unchanged; phone keeps `allow`/`deny` (its plan approve now works via the script mapping).- **Per-node hook identity** (`src/core/agents/node-auth-*.ts`, `node-token-*.ts`,`node-identity-policy.ts` — full write-up in **`docs/node-identity.md`**) — the shared bearer provesdiff --git a/docs/hook-reply-approvals.md b/docs/hook-reply-approvals.mdindex 2f553d035..ed4b83822 100644--- a/docs/hook-reply-approvals.md+++ b/docs/hook-reply-approvals.md@@ -111,19 +111,36 @@ the TUI. Core also refuses to write it (`answerPermission` → `false`) so no sufor an answer that did nothing, and the header hides ✓ Approve for that ticket.**Hold time.** For these two tools the hook holds `PERM_WAIT_SECS_INTERACTIVE` = 540 s instead of 45 s-— people read plans for minutes. Our installers write **no `timeout`** on the PermissionRequest entry,-so Claude's command-hook default of 600 s applies (pinned in `managed-script.answer.test.ts`), leaving a-60 s margin. Because the main-thread dialog is painted concurrently, a long hold blocks nothing. A-**subagent's** request keeps the short hold: its dialog awaits the hook, so 540 s there would hide the-prompt (detected by an `"agent_id":` key in the payload — a false positive only shortens the hold).+— people read plans for minutes. The installer writes an explicit `timeout: 600` on OUR PermissionRequest+handler (`PERMISSION_REQUEST_HOOK_TIMEOUT_SECS`, `CLAUDE_HOOK_EVENTS`; local, managed-account and SSH+installs alike, and an existing install is rewritten with it at the next install), so the bound the hold+is sized against is not a CLI default that could change; 60 s of margin, pinned by tests. The poll counts+half-seconds, and where `sleep 0.5` is unsupported the `sleep 1` fallback counts two, so the hold never+doubles past the timeout. Because the main-thread dialog is painted concurrently, a long hold blocks+nothing. A **subagent's** request keeps the short hold: its dialog awaits the hook, so 540 s there would+hide the prompt. The signal is an `"agent_id":` key in the payload — verified in the claude 2.1.283 bundle,+whose hook base input is `session_id…,permission_mode:r,agent_id:s?.agentId,agent_type:g,…`, so the key is+undefined (and dropped by JSON) on the main thread; a nested false positive only shortens the hold.The tool name is read from the FIRST `"tool_name":` in the payload and trusted only when no`"tool_input"` precedes it, so a nested key inside some tool's input can never make an ordinary tool-look like a plan (an empty/unsafe name degrades to today's default behavior).--**Old script on an SSH host.** The script on a host is rewritten only at connect. An old script reads a-JSON answer as neither `allow` nor `deny`, removes the files and prints nothing, so the TUI dialog still-answers — a safe degrade (verified by running the new sh tests against the previous script). Its plan-`allow` stays the old silent no-op until the project reconnects.+look like a plan (an empty/unsafe name degrades to today's default behavior). The answer file's size is+its BYTE count (`wc -c`) and at most cap+1 bytes are read (`head -c`).++**Old script on an SSH host — gated by revision.** The script on a host is rewritten only at connect,+so a long-connected project can hold a request with an older script. That script reads a JSON answer as+neither `allow` nor `deny`, deletes it and prints nothing (the TUI still answers — verified by running the+new sh tests against the previous script), while the WRITE succeeded; without a gate core would report+success and the optimistic "answered" event would flip NEEDS YOU to working over an agent still waiting+in its TUI. So the script's revision gates it: `MANAGED_SCRIPT_REVISION` is 5, every hook POST already+carries it (`clientRevision`), and the hook server (`labelHeldForRevision`) keeps an event's `held` ticket+— and records the ticket as structured-capable — only for revision >= `MIN_STRUCTURED_ANSWER_REVISION` (5).+`answerHeldPermission` refuses (`false`, nothing written, no synthetic answered event) a structured answer+for a ticket not recorded as capable, and a plain `allow` on a plan held by such a script (it would print a+bare allow Claude drops). **UI consequence:** on an old-script host no plan/question controls are offered+at all (the renderer never receives `held`), and the header ✓ Approve on a plan answers `false` instead of+pretending; Deny and ordinary approvals work exactly as before. Reconnecting the project installs the+current script. The capability record is process-local and bounded, so a ticket from before an app+restart is treated as not capable (the renderer's `held` is gone then too).**Renderer.** A held request's `{pendingId, toolName}` rides the normalized event as `held` and theagent-status store keeps it while the node is `blocked` or `waiting` — separate from `pendingId`, whichdiff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 2fddec6a7..40c1c2bb1 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -1132,6 +1132,18 @@ describe('recordAgentEvent enrichment (returned broadcast event)', () => {expect(out.held).toEqual({ pendingId: 'e9-1-1', toolName: 'AskUserQuestion' })})+ it('a held question with NO PreToolUse stash is classified as an approval and keeps pendingId', () => {+ // Why the header needs its own AskUserQuestion gate (renderer/lib/approveGate.ts).+ const perm = normalizeClaude({+ nodeId: 'e11',+ agentId: 'claude',+ payload: { hook_event_name: 'PermissionRequest', session_id: 's', tool_name: 'AskUserQuestion', tool_input: {}, nodeterm_pending_id: 'e11-1-1' }+ })!+ const out = recordAgentEvent(perm)+ expect(out.pendingId).toBe('e11-1-1')+ expect(out.held).toEqual({ pendingId: 'e11-1-1', toolName: 'AskUserQuestion' })+ })+it('a held PLAN is an approval: keeps pendingId (header Approve works) and names ExitPlanMode', () => {const perm = normalizeClaude({nodeId: 'e10',diff --git a/src/core/agents/hook-server.held.test.ts b/src/core/agents/hook-server.held.test.tsnew file mode 100644index 000000000..150b17f2c--- /dev/null+++ b/src/core/agents/hook-server.held.test.ts@@ -0,0 +1,81 @@+// A held request's `held` ticket (structured answers) must only reach a surface when the POSTING+// script can honor a JSON answer — the hook server is the one place that knows the script revision.+// Real server, real HTTP POST, the exact form fields and header the managed script sends.+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { request } from 'node:http'+import { hookServer } from './hook-server'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'+import { _resetStructuredTicketsForTest, isStructuredTicket, MIN_STRUCTURED_ANSWER_REVISION } from './permission-decision'+import { MANAGED_SCRIPT_REVISION } from './hooks/managed-script'++let dir = ''+const events: NormalizedAgentEvent[] = []++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-hookheld-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setListener((e) => events.push(e))+})+afterAll(() => {+ hookServer.stop()+ fs.rmSync(dir, { recursive: true, force: true })+})+beforeEach(() => {+ events.length = 0+ _resetStructuredTicketsForTest()+})++function post(pendingId: string, rev: number | undefined): Promise<number> {+ const payload = JSON.stringify({ hook_event_name: 'PermissionRequest', session_id: 's', tool_name: 'ExitPlanMode', tool_input: { plan: 'p' } })+ const body = new URLSearchParams({ nodeId: 'held-node', version: '2', nodeterm_pending_id: pendingId, payload }).toString()+ return new Promise((resolve, reject) => {+ const req = request(+ {+ host: '127.0.0.1',+ port: hookServer.getPort(),+ path: '/hook/claude',+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ ...(rev !== undefined ? { 'X-Nodeterm-Hook-Client': String(rev) } : {})+ }+ },+ (res) => {+ res.resume()+ res.on('end', () => resolve(res.statusCode ?? 0))+ }+ )+ req.on('error', reject)+ req.end(body)+ })+}++describe('hook server: held ticket gated on the posting script revision', () => {+ it('the current script revision is structured-answer capable', () => {+ expect(MANAGED_SCRIPT_REVISION).toBeGreaterThanOrEqual(MIN_STRUCTURED_ANSWER_REVISION)+ })+ it('a current script keeps `held` and records the ticket', async () => {+ expect(await post('held-node-1-1', MANAGED_SCRIPT_REVISION)).toBe(204)+ const e = events.at(-1)!+ expect(e.held).toEqual({ pendingId: 'held-node-1-1', toolName: 'ExitPlanMode' })+ expect(isStructuredTicket('held-node-1-1')).toBe(true)+ })+ it('an older or unstamped script loses `held` but keeps its approve/deny pendingId', async () => {+ for (const rev of [4, undefined]) {+ events.length = 0+ expect(await post('held-node-2-2', rev)).toBe(204)+ const e = events.at(-1)!+ expect('held' in e, String(rev)).toBe(false)+ expect(e.pendingId).toBe('held-node-2-2')+ }+ expect(isStructuredTicket('held-node-2-2')).toBe(false)+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex e8df3643d..19fa810d2 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -1,4 +1,5 @@import { sessionContextWindow } from '../model-window'+import { labelHeldForRevision } from './permission-decision'import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'import { randomUUID, timingSafeEqual } from 'crypto'import { readFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'@@ -844,7 +845,10 @@ export class HookServer {// dir for claude alone (codex rollouts and gemini chats live in unrelated trees, and// those agents have their own identity spine).const account = observedClaudeAccount(agentId, payload)- const normalized = normalizeFor(agentId, { nodeId, agentId, payload })+ // A held request keeps its `held` ticket only when the posting script can honor a+ // structured answer (core/agents/permission-decision.ts, MIN_STRUCTURED_ANSWER_REVISION).+ const raw = normalizeFor(agentId, { nodeId, agentId, payload })+ const normalized = raw ? labelHeldForRevision(raw, clientRevision) : rawif (normalized && this.listener)this.listener({ ...normalized, verified, clientRevision, ...(account ? { account } : {}) })}diff --git a/src/core/agents/hooks/install-helper.fs.test.ts b/src/core/agents/hooks/install-helper.fs.test.tsindex 322dd9c69..90c56144f 100644--- a/src/core/agents/hooks/install-helper.fs.test.ts+++ b/src/core/agents/hooks/install-helper.fs.test.ts@@ -15,7 +15,7 @@ vi.mock('os', async (orig) => {})import { installHooksInto, removeHooksFrom } from './install-helper'-import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'+import { CLAUDE_HOOK_EVENTS, managedEventName } from '@shared/agents/hook-events'const WIN_CMD ="if [ -r 'C:\\Users\\u\\.nodeterm\\agent-hooks\\claude.sh' ]; then sh 'C:\\Users\\u\\.nodeterm\\agent-hooks\\claude.sh'; else cat >/dev/null 2>&1 || :; fi"@@ -42,19 +42,19 @@ afterEach(() => rmSync(dir, { recursive: true, force: true }))describe('installHooksInto — heals an already-broken settings.json (issue #558)', () => {it('collapses 9 accumulated duplicates per event to 1 and keeps the user`s own hooks', () => {const hooks: Record<string, unknown[]> = { PreCompact: [FOREIGN] }- for (const ev of CLAUDE_HOOK_EVENTS) {- hooks[ev as string] = [FOREIGN, ...Array.from({ length: 9 }, () => ({ hooks: [{ type: 'command', command: WIN_CMD }] }))]+ for (const ev of CLAUDE_HOOK_EVENTS.map(managedEventName)) {+ hooks[ev] = [FOREIGN, ...Array.from({ length: 9 }, () => ({ hooks: [{ type: 'command', command: WIN_CMD }] }))]}writeFileSync(configPath(), JSON.stringify({ model: 'opus', hooks }, null, 2), 'utf8')install()const after = readConfig()- for (const ev of CLAUDE_HOOK_EVENTS) {- const defs = after.hooks[ev as string]- expect(defs, ev as string).toHaveLength(2)- expect(defs[0], ev as string).toEqual(FOREIGN)- expect(defs[1].hooks[0].command, ev as string).toContain('agent-hooks')+ for (const ev of CLAUDE_HOOK_EVENTS.map(managedEventName)) {+ const defs = after.hooks[ev]+ expect(defs, ev).toHaveLength(2)+ expect(defs[0], ev).toEqual(FOREIGN)+ expect(defs[1].hooks[0].command, ev).toContain('agent-hooks')}// An event we do not manage keeps the foreign hook untouched, and unrelated settings survive.expect(after.hooks.PreCompact).toEqual([FOREIGN])diff --git a/src/core/agents/hooks/install-helper.test.ts b/src/core/agents/hooks/install-helper.test.tsindex 28dea22f4..f0e28ac98 100644--- a/src/core/agents/hooks/install-helper.test.ts+++ b/src/core/agents/hooks/install-helper.test.ts@@ -10,7 +10,7 @@ import {writeManagedHookFileAtomic,type HookSettings} from './install-helper'-import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'+import { CLAUDE_HOOK_EVENTS, managedEventName } from '@shared/agents/hook-events'const cmd = buildManagedHookCommand('/remote/.nodeterm/agent-hooks/claude.sh')@@ -170,6 +170,21 @@ describe('mergeManagedHook — matcher support is opt-in per event', () => {* These run on any OS: the win32-ness that matters is the SEPARATOR inside the stored command,* which `path.win32` gives us without a Windows runner.*/+describe('mergeManagedHook — claude PermissionRequest carries an explicit timeout', () => {+ it('writes timeout: 600 on the held PermissionRequest handler only, and never a matcher', () => {+ const out = mergeManagedHook({}, 'CMD', CLAUDE_HOOK_EVENTS)+ expect(out.hooks!.PermissionRequest).toEqual([{ hooks: [{ type: 'command', command: 'CMD', timeout: 600 }] }])+ expect(out.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command: 'CMD' }] }])+ })+ it('updates an EXISTING install (the old timeout-less entry is replaced, not duplicated)', () => {+ const CMD = buildManagedHookCommand('/home/u/.nodeterm/agent-hooks/claude.sh')+ const old = { hooks: { PermissionRequest: [{ hooks: [{ type: 'command', command: CMD }] }] } }+ const out = mergeManagedHook(old, CMD, CLAUDE_HOOK_EVENTS)+ expect(out.hooks!.PermissionRequest).toEqual([{ hooks: [{ type: 'command', command: CMD, timeout: 600 }] }])+ expect(mergeManagedHook(out, CMD, CLAUDE_HOOK_EVENTS)).toEqual(out) // idempotent+ })+})+describe('mergeManagedHook — Windows path separators (issue #558)', () => {const winScript = path.win32.join('C:\\Users\\u', '.nodeterm', 'agent-hooks', 'claude.sh')const winCmd = buildManagedHookCommand(winScript)@@ -189,10 +204,11 @@ describe('mergeManagedHook — Windows path separators (issue #558)', () => {// The reported state, rebuilt: nine byte-identical definitions on every managed event.const dup = { hooks: [{ type: 'command', command: winCmd }] }const hooks: Record<string, typeof dup[]> = {}- for (const ev of CLAUDE_HOOK_EVENTS) hooks[ev as string] = Array.from({ length: 9 }, () => ({ ...dup }))+ for (const ev of CLAUDE_HOOK_EVENTS.map(managedEventName)) hooks[ev] = Array.from({ length: 9 }, () => ({ ...dup }))const out = mergeManagedHook({ hooks }, winCmd, CLAUDE_HOOK_EVENTS)- for (const ev of CLAUDE_HOOK_EVENTS) {- expect(out.hooks![ev as string], ev as string).toEqual([{ hooks: [{ type: 'command', command: winCmd }] }])+ for (const ev of CLAUDE_HOOK_EVENTS.map(managedEventName)) {+ // One definition, one handler, OUR command (PermissionRequest's also carries its timeout).+ expect(out.hooks![ev]?.map((d) => d.hooks?.map((h) => h.command)), ev).toEqual([[winCmd]])}})diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex 8943063dc..620f7a24c 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -16,11 +16,11 @@ import { updateSettingsFile } from './settings-file'import path from 'path'import { homedir } from 'os'import { readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync } from 'fs'-import type { ManagedHookEvent } from '@shared/agents/hook-events'+import { managedEventName, type ManagedHookEvent } from '@shared/agents/hook-events'import { renameAtomicSync, tempNameFor } from '../../fs-atomic'import { buildManagedScript } from './managed-script'-type HookDef = { matcher?: string; hooks?: { type: string; command: string }[] }+type HookDef = { matcher?: string; hooks?: { type: string; command: string; timeout?: number }[] }type Settings = { hooks?: Record<string, HookDef[]>; [k: string]: unknown }/** Public alias for the hook settings shape, shared by local + remote merge callers. */@@ -175,10 +175,12 @@ function stripManaged(defs: HookDef[], isOurs: (command?: string) => boolean): H}/** A subscription's event name, whichever form it was declared in. */-const eventNameOf = (e: ManagedHookEvent): string => (typeof e === 'string' ? e : e.event)+const eventNameOf = managedEventName/** The matcher to write for it — undefined for the plain string form, so nothing changes for the* agents that never needed one (grok's tool events are the only case; see ManagedHookEvent). */const matcherOf = (e: ManagedHookEvent): string | undefined => (typeof e === 'string' ? undefined : e.matcher)+/** The handler `timeout` (seconds) — only claude's held PermissionRequest declares one. */+const timeoutOf = (e: ManagedHookEvent): number | undefined => (typeof e === 'string' ? undefined : e.timeout)/*** Pure: make the config's managed hooks EXACTLY ours — our command on every event in `events`, and@@ -224,12 +226,16 @@ export function mergeManagedHook(for (const e of events) {const ev = eventNameOf(e)const matcher = matcherOf(e)+ const timeout = timeoutOf(e)const existing = stripManaged(definitionsAt(ev), isOurs)// Spread the matcher CONDITIONALLY: an explicit `matcher: undefined` would serialize as a// missing key here but still change the object shape snapshots compare. The test is// `!== undefined`, not truthiness — the type permits `matcher: ''`, and silently dropping an// empty matcher would emit a subscription that does not say what its declaration said.- existing.push({ ...(matcher !== undefined ? { matcher } : {}), hooks: [{ type: 'command', command }] })+ existing.push({+ ...(matcher !== undefined ? { matcher } : {}),+ hooks: [{ type: 'command', command, ...(timeout !== undefined ? { timeout } : {}) }]+ })next.hooks![ev] = existing}const managedEvents = new Set(events.map(eventNameOf))diff --git a/src/core/agents/hooks/managed-script.answer.test.ts b/src/core/agents/hooks/managed-script.answer.test.tsindex aa3205d17..3546cf366 100644--- a/src/core/agents/hooks/managed-script.answer.test.ts+++ b/src/core/agents/hooks/managed-script.answer.test.ts@@ -11,17 +11,18 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync,import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterAll, beforeEach, describe, expect, it } from 'vitest'-import { buildManagedScript } from './managed-script'+import { buildManagedScript, MANAGED_SCRIPT_REVISION } from './managed-script'import {buildPermissionDecision,parsePendingRequest,PERMISSION_DECISION_MAX_BYTES,PERMISSION_DECISION_PREFIX,PERM_WAIT_SECS_INTERACTIVE,+ MIN_STRUCTURED_ANSWER_REVISION,type PendingRequest} from '../permission-decision'import { mergeManagedHook } from './install-helper'-import { CLAUDE_HOOK_EVENTS } from '../../../shared/agents/hook-events'+import { CLAUDE_HOOK_EVENTS, PERMISSION_REQUEST_HOOK_TIMEOUT_SECS } from '../../../shared/agents/hook-events'const sh = spawnSync('sh', ['-c', 'exit 0'])const shAvailable = sh.status === 0 && !sh.error && process.platform !== 'win32'@@ -85,7 +86,7 @@ describe.skipIf(!shAvailable)('managed hook answer decoding, under /bin/sh', ()* Run claude's hook on `payload` with NODETERM_PERM_WAIT_SECS=1 (a 2-poll default hold).* `answers[k]` is written as the answer file on the k-th poll (1-based).*/- function run(payload: string, answers: Record<number, string> = {}): Run {+ function run(payload: string, answers: Record<number, string> = {}, opts: { noFractionalSleep?: boolean } = {}): Run {const home = join(dir, 'home')const bin = join(dir, 'bin')const answersDir = join(dir, 'answers')@@ -114,6 +115,8 @@ describe.skipIf(!shAvailable)('managed hook answer decoding, under /bin/sh', ()join(bin, 'sleep'),['#!/bin/sh',+ // A sleep that rejects fractions (busybox without FANCY_SLEEP, some old BSDs).+ 'if [ "$1" = 0.5 ] && [ -n "$NT_NO_FRACTION" ]; then exit 1; fi',`c=$(cat ${JSON.stringify(count)} 2>/dev/null || echo 0)`,'c=$((c + 1))',`echo "$c" > ${JSON.stringify(count)}`,@@ -139,7 +142,8 @@ describe.skipIf(!shAvailable)('managed hook answer decoding, under /bin/sh', ()HOME: home,NODETERM_NODE_ID: 'node-1',NODETERM_HOOK_ENDPOINT: endpoint,- NODETERM_PERM_WAIT_SECS: '1'+ NODETERM_PERM_WAIT_SECS: '1',+ ...(opts.noFractionalSleep ? { NT_NO_FRACTION: '1' } : {})}})// The "answered" POST is backgrounded; give it a moment to land before reading the log.@@ -274,6 +278,16 @@ describe.skipIf(!shAvailable)('managed hook answer decoding, under /bin/sh', ()expect(run(envelope('Bash', { command: 'ls' })).sleeps).toBe(2)}, 60_000)+ it('where fractional sleep fails, the 1 s fallback counts double: the hold stays 540 s, not 1080 s', () => {+ const plan = run(envelope('ExitPlanMode', { plan: 'p' }), {}, { noFractionalSleep: true })+ expect(plan.sleeps).toBe(PERM_WAIT_SECS_INTERACTIVE) // 540 one-second sleeps+ fresh()+ expect(run(envelope('Bash', { command: 'ls' }), {}, { noFractionalSleep: true }).sleeps).toBe(1)+ fresh()+ // An answer still lands on the fallback path.+ expect(run(envelope('ExitPlanMode', { plan: 'p' }), { 3: 'allow' }, { noFractionalSleep: true }).stdout).toBe(`${ALLOW_PLAN}\n`)+ }, 60_000)+it('a SUBAGENT\'s plan/question keeps the short hold (its dialog waits for the hook)', () => {const r = run(envelope('ExitPlanMode', { plan: 'p' }, { agent_id: 'a-1', agent_type: 'Plan' }))expect(r.sleeps).toBe(2)@@ -302,15 +316,17 @@ describe.skipIf(!shAvailable)('managed hook answer decoding, under /bin/sh', ()})})-describe('hold time vs Claude\'s command-hook timeout', () => {- it('our installer writes NO timeout on the PermissionRequest entry, so Claude\'s 600 s default applies', () => {+describe('hold time vs the command-hook timeout we write', () => {+ it('our installer writes an explicit timeout on the PermissionRequest entry', () => {const merged = mergeManagedHook({}, "sh '/x/agent-hooks/claude.sh'", CLAUDE_HOOK_EVENTS)const entry = merged.hooks?.PermissionRequest?.[0]?.hooks?.[0] as Record<string, unknown>- expect(entry).toBeDefined()- expect(entry).not.toHaveProperty('timeout')+ expect(entry.timeout).toBe(PERMISSION_REQUEST_HOOK_TIMEOUT_SECS)})- it('the interactive hold leaves at least a minute of margin under 600 s', () => {- expect(PERM_WAIT_SECS_INTERACTIVE).toBeLessThanOrEqual(600 - 60)+ it('the interactive hold leaves at least a minute of margin under that timeout', () => {+ expect(PERM_WAIT_SECS_INTERACTIVE).toBeLessThanOrEqual(PERMISSION_REQUEST_HOOK_TIMEOUT_SECS - 60)expect(PERM_WAIT_SECS_INTERACTIVE).toBeGreaterThan(45)})+ it('the script revision is structured-answer capable', () => {+ expect(MANAGED_SCRIPT_REVISION).toBeGreaterThanOrEqual(MIN_STRUCTURED_ANSWER_REVISION)+ })})diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex c37ef22fe..422fa29b8 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -94,7 +94,11 @@ import {PERMISSION_DECISION_PREFIX,PERM_WAIT_SECS_INTERACTIVE} from '../permission-decision'-import { ASK_USER_QUESTION_TOOL, EXIT_PLAN_MODE_TOOL } from '../../../shared/agents/permission-answer'+import {+ ASK_USER_QUESTION_TOOL,+ EXIT_PLAN_MODE_TOOL,+ INTERACTIVE_HOLD_TOOLS+} from '../../../shared/agents/permission-answer'/*** Bumped by hand whenever this script's CONTRACT with the server changes. Not a git sha and not a@@ -115,13 +119,17 @@ import { ASK_USER_QUESTION_TOOL, EXIT_PLAN_MODE_TOOL } from '../../../shared/age* and any session the PHONE spawns on that host, which runs the host's installed script — stay* `legacy` until the project reconnects.*/-export const MANAGED_SCRIPT_REVISION = 4+export const MANAGED_SCRIPT_REVISION = 5/** The first revision that reads NODETERM_NODE_TOKEN_DIR and sends the node token (PR #195). */export const MIN_TOKEN_AWARE_REVISION = 3/* rev 4 (issue #384): the token read moved to the shared resolver in `node-token-sh.ts`, which* falls back to the standard token dirs when the endpoint file advertises none. The floor stays 3* on purpose — rev 3 CAN read a token, which is the only question `MIN_TOKEN_AWARE_REVISION`- * answers; calling it stale would tell a working session to reconnect for nothing. */+ * answers; calling it stale would tell a working session to reconnect for nothing.+ * rev 5: the answer file may carry a core-built JSON decision (plans/questions), a plain allow on+ * ExitPlanMode maps to `updatedInput:{}`, and those two tools hold 540 s. The server gates+ * structured answers on it (`MIN_STRUCTURED_ANSWER_REVISION`, permission-decision.ts) — an older+ * script would silently ignore them while the write reported success. *//*** Which tool the held PermissionRequest is about, and how long to hold it (claude only; spliced@@ -137,10 +145,14 @@ export const MIN_TOKEN_AWARE_REVISION = 3* identifier and only ever compared against two literals.** `nt_wait`: ExitPlanMode / AskUserQuestion are read by a person for minutes, so they hold- * PERM_WAIT_SECS_INTERACTIVE (< Claude's 600 s default command-hook timeout, which our installers- * never override). EXCEPT for a subagent's request (payload names an `agent_id`): Claude awaits a- * subagent's automated checks BEFORE painting its dialog (research §1), so a long hold there would- * hide the prompt for minutes. A nested `"agent_id":` merely shortens the hold — the safe direction.+ * PERM_WAIT_SECS_INTERACTIVE (< the 600 s command-hook timeout our installers+ * write with an explicit `timeout: 600`, see CLAUDE_HOOK_EVENTS). EXCEPT for a subagent's request+ * (payload names an `agent_id`): Claude awaits a subagent's automated checks BEFORE painting its+ * dialog (research §1), so a long hold there would hide the prompt for minutes. Evidence that the+ * key is the right signal (claude 2.1.283 bundle, verified by the review): the hook base input is+ * `session_id…,permission_mode:r,agent_id:s?.agentId,agent_type:g,…` — `agentId` is undefined on+ * the main thread, so JSON.stringify drops the key there and it appears only for a subagent. A+ * nested `"agent_id":` inside tool_input merely shortens the hold — the safe direction.*/const HELD_TOOL_SH: readonly string[] = [' nt_tool=""',@@ -158,7 +170,7 @@ const HELD_TOOL_SH: readonly string[] = [' case "$nt_tool" in \'\'|*[!A-Za-z0-9_.:-]*) nt_tool="" ;; esac',' nt_wait="$NODETERM_PERM_WAIT_SECS"',' case "$nt_tool" in',- ` ${EXIT_PLAN_MODE_TOOL}|${ASK_USER_QUESTION_TOOL})`,+ ` ${INTERACTIVE_HOLD_TOOLS.join('|')})`,' case "$payload" in',' *\'"agent_id":\'*) ;;',` *) nt_wait=${PERM_WAIT_SECS_INTERACTIVE} ;;`,@@ -201,10 +213,12 @@ const ANSWER_DECODE_SH: readonly string[] = [` '${PERMISSION_DECISION_PREFIX}"allow"'*) nt_verb=allow; nt_out="$nt_decision" ;;`,` '${PERMISSION_DECISION_PREFIX}"deny"'*) nt_verb=deny; nt_out="$nt_decision" ;;`,' esac',- ' # Shape-check a core-built JSON answer before it can reach Claude\'s stdout.',+ ' # Shape-check a core-built JSON answer before it can reach Claude\'s stdout. The size is the',+ ' # FILE\'s byte count (wc -c), not ${#…}: that counts characters under bash, bytes under dash.',' if [ -n "$nt_out" ] && [ "$nt_out" = "$nt_decision" ]; then',' case "$nt_out" in *\'}\') ;; *) nt_out="" ;; esac',- ` if [ "\${#nt_out}" -gt ${PERMISSION_DECISION_MAX_BYTES} ]; then nt_out=""; fi`,+ ' # Fail CLOSED: an empty/odd size (wc failed) makes the test error, which also clears nt_out.',+ ` if ! [ "$nt_size" -le ${PERMISSION_DECISION_MAX_BYTES} ] 2>/dev/null; then nt_out=""; fi`," if [ -n \"$nt_out\" ] && [ \"$(printf '%s' \"$nt_out\" | tr -d '\\000-\\037')\" != \"$nt_out\" ]; then nt_out=\"\"; fi",' [ -n "$nt_out" ] || nt_verb=""',' fi'@@ -465,7 +479,10 @@ export function buildManagedScript(' nt_i=0',' while [ "$nt_i" -lt "$nt_max" ]; do',' if [ -f "$nt_answer" ]; then',- ' nt_decision=$(cat "$nt_answer" 2>/dev/null)',+ // Take the file's BYTE size, then read at most one byte past the cap: a hostile multi-megabyte+ // file is never slurped into the shell, and the size check below rejects anything over it.+ ' nt_size=$(wc -c < "$nt_answer" 2>/dev/null)',+ ` nt_decision=$(head -c ${PERMISSION_DECISION_MAX_BYTES + 1} "$nt_answer" 2>/dev/null)`,...ANSWER_DECODE_SH,' if [ "$nt_verb" = hold ]; then',' # A plain allow on a question: consume it and KEEP HOLDING (see ANSWER_DECODE_SH).',@@ -517,8 +534,9 @@ export function buildManagedScript(' exit 0',' fi',' fi',- ' sleep 0.5 2>/dev/null || sleep 1',- ' nt_i=$((nt_i + 1))',+ // nt_max counts HALF-seconds. Where fractional sleep is unsupported the fallback sleeps a full+ // second, so it must count 2 — else the 540 s hold would run ~1080 s, past the hook timeout.+ ' if sleep 0.5 2>/dev/null; then nt_i=$((nt_i + 1)); else sleep 1; nt_i=$((nt_i + 2)); fi',' done',' # Timed out: clean up the request + payload files and print nothing → Claude shows its normal prompt.',' rm -f "$nt_pending_file" "$nt_payload_file" 2>/dev/null || :',diff --git a/src/core/agents/pending-approvals.test.ts b/src/core/agents/pending-approvals.test.tsindex b8dee6d29..c822955e7 100644--- a/src/core/agents/pending-approvals.test.ts+++ b/src/core/agents/pending-approvals.test.ts@@ -12,7 +12,13 @@ import {readPendingRequestLocal,localHeldPermissionIo} from './pending-approvals'-import { answerHeldPermission, PENDING_REQUEST_MAX_BYTES, PERMISSION_DECISION_PREFIX } from './permission-decision'+import {+ answerHeldPermission,+ labelHeldForRevision,+ MIN_STRUCTURED_ANSWER_REVISION,+ PENDING_REQUEST_MAX_BYTES,+ PERMISSION_DECISION_PREFIX+} from './permission-decision'let home: string@@ -99,7 +105,11 @@ describe('readPendingRequestLocal + localHeldPermissionIo', () => {path.join(pendingDir(home), 'n.json'),JSON.stringify({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode', tool_input: { plan: 'p' } }))- const res = await answerHeldPermission({ answer: { kind: 'plan', mode: 'restore' } }, localHeldPermissionIo('n', home))+ labelHeldForRevision(+ { nodeId: 'x', agentId: 'claude', kind: 'state', state: 'blocked', held: { pendingId: 'n', toolName: 'ExitPlanMode' } },+ MIN_STRUCTURED_ANSWER_REVISION+ )+ const res = await answerHeldPermission('n', { answer: { kind: 'plan', mode: 'restore' } }, localHeldPermissionIo('n', home))expect(res).toEqual({ ok: true, decision: 'allow' })expect(fs.readFileSync(path.join(pendingDir(home), 'n.answer'), 'utf8')).toBe(`${PERMISSION_DECISION_PREFIX}"allow","updatedInput":{}}}}`diff --git a/src/core/agents/permission-decision.test.ts b/src/core/agents/permission-decision.test.tsindex ccfdc7ac8..8ae0a50a1 100644--- a/src/core/agents/permission-decision.test.ts+++ b/src/core/agents/permission-decision.test.ts@@ -1,6 +1,10 @@-import { describe, expect, it } from 'vitest'+import { beforeEach, describe, expect, it } from 'vitest'import {+ _resetStructuredTicketsForTest,answerHeldPermission,+ isStructuredTicket,+ labelHeldForRevision,+ MIN_STRUCTURED_ANSWER_REVISION,buildPermissionDecision,isBoundedAnswerContent,parsePermissionAnswer,@@ -284,6 +288,15 @@ describe('isBoundedAnswerContent — the same bound the hook script applies', ()})describe('answerHeldPermission — the one orchestration both shells call', () => {+ const T = 'node-1-1720-42'+ beforeEach(() => {+ _resetStructuredTicketsForTest()+ // A capable (rev >= 5) script posted this ticket — the hook server's labeler records it.+ labelHeldForRevision(+ { nodeId: 'n', agentId: 'claude', kind: 'state', state: 'blocked', held: { pendingId: T, toolName: 'ExitPlanMode' } },+ MIN_STRUCTURED_ANSWER_REVISION+ )+ })function io(pending: string | null) {const writes: string[] = []return {@@ -297,12 +310,12 @@ describe('answerHeldPermission — the one orchestration both shells call', () =}it('legacy payload (decision only) keeps working', async () => {const x = io(envelope('Bash', { command: 'ls' }))- expect(await answerHeldPermission({ decision: 'allow' }, x)).toEqual({ ok: true, decision: 'allow' })+ expect(await answerHeldPermission(T, { decision: 'allow' }, x)).toEqual({ ok: true, decision: 'allow' })expect(x.writes).toEqual(['allow'])})it('a structured answer wins over decision and is built from the pending file', async () => {const x = io(envelope('ExitPlanMode', { plan: 'p' }))- expect(await answerHeldPermission({ decision: 'deny', answer: { kind: 'plan', mode: 'manual' } }, x)).toEqual({+ expect(await answerHeldPermission(T, { decision: 'deny', answer: { kind: 'plan', mode: 'manual' } }, x)).toEqual({ok: true,decision: 'allow'})@@ -310,22 +323,23 @@ describe('answerHeldPermission — the one orchestration both shells call', () =})it('a structured answer with no pending request (hold expired / already answered) writes NOTHING', async () => {const x = io(null)- expect(await answerHeldPermission({ answer: { kind: 'plan', mode: 'restore' } }, x)).toEqual({ ok: false })+ expect(await answerHeldPermission(T, { answer: { kind: 'plan', mode: 'restore' } }, x)).toEqual({ ok: false })expect(x.writes).toEqual([])})it('an invalid answer or missing decision writes nothing', async () => {const x = io(envelope('AskUserQuestion', { questions: REAL_QUESTIONS }))- expect(await answerHeldPermission({ decision: 'allow' }, x)).toEqual({ ok: false })- expect(await answerHeldPermission({ answer: { kind: 'nope' } }, x)).toEqual({ ok: false })- expect(await answerHeldPermission({}, x)).toEqual({ ok: false })+ expect(await answerHeldPermission(T, { decision: 'allow' }, x)).toEqual({ ok: false })+ expect(await answerHeldPermission(T, { answer: { kind: 'nope' } }, x)).toEqual({ ok: false })+ expect(await answerHeldPermission(T, {}, x)).toEqual({ ok: false })expect(x.writes).toEqual([])})it('a failed write reports false; a throwing reader fails soft', async () => {expect(- await answerHeldPermission({ decision: 'deny' }, { readPending: async () => null, write: async () => false })+ await answerHeldPermission(T, { decision: 'deny' }, { readPending: async () => null, write: async () => false })).toEqual({ ok: false })expect(await answerHeldPermission(+ T,{ decision: 'deny' },{readPending: async () => {@@ -336,4 +350,65 @@ describe('answerHeldPermission — the one orchestration both shells call', () =)).toEqual({ ok: true, decision: 'deny' })})++ describe('a ticket held by an OLDER script (an SSH host keeps its script until reconnect)', () => {+ const OLD = 'node-2-1720-43'+ it('refuses a structured answer before touching the host — no false "answered"', async () => {+ const x = io(envelope('ExitPlanMode', { plan: 'p' }))+ expect(await answerHeldPermission(OLD, { answer: { kind: 'plan', mode: 'restore' } }, x)).toEqual({ ok: false })+ const q = io(envelope('AskUserQuestion', { questions: REAL_QUESTIONS }))+ expect(+ await answerHeldPermission(OLD, { answer: { kind: 'question', answers: { [QUESTION_TEXT]: 'Kim kimi okuyabilir (context)' } } }, q)+ ).toEqual({ ok: false })+ expect(x.writes).toEqual([])+ expect(q.writes).toEqual([])+ })+ it('refuses a plain allow on a PLAN (the old script would print a bare allow Claude drops)', async () => {+ const x = io(envelope('ExitPlanMode', { plan: 'p' }))+ expect(await answerHeldPermission(OLD, { decision: 'allow' }, x)).toEqual({ ok: false })+ expect(x.writes).toEqual([])+ })+ it('keeps the legacy words working everywhere else: deny, an ordinary allow, an unreadable request', async () => {+ const plan = io(envelope('ExitPlanMode', { plan: 'p' }))+ expect(await answerHeldPermission(OLD, { decision: 'deny' }, plan)).toEqual({ ok: true, decision: 'deny' })+ const bash = io(envelope('Bash', { command: 'ls' }))+ expect(await answerHeldPermission(OLD, { decision: 'allow' }, bash)).toEqual({ ok: true, decision: 'allow' })+ const gone = io(null)+ expect(await answerHeldPermission(OLD, { decision: 'allow' }, gone)).toEqual({ ok: true, decision: 'allow' })+ })+ })+})++describe('labelHeldForRevision (the hook server stamps each held ticket)', () => {+ beforeEach(() => _resetStructuredTicketsForTest())+ const blocked = (pendingId: string) => ({+ nodeId: 'n',+ agentId: 'claude',+ kind: 'state' as const,+ state: 'blocked' as const,+ pendingId,+ held: { pendingId, toolName: 'AskUserQuestion' }+ })+ it('keeps `held` and records the ticket for a capable script', () => {+ const out = labelHeldForRevision(blocked('a-1-1'), MIN_STRUCTURED_ANSWER_REVISION)+ expect(out.held).toEqual({ pendingId: 'a-1-1', toolName: 'AskUserQuestion' })+ expect(isStructuredTicket('a-1-1')).toBe(true)+ })+ it('drops `held` (and records nothing) for an older or unstamped script; pendingId is untouched', () => {+ for (const rev of [undefined, 3, 4]) {+ const out = labelHeldForRevision(blocked('b-1-1'), rev)+ expect('held' in out, String(rev)).toBe(false)+ expect(out.pendingId).toBe('b-1-1')+ }+ expect(isStructuredTicket('b-1-1')).toBe(false)+ })+ it('passes an event with no held request through as the same reference', () => {+ const ev = { nodeId: 'n', agentId: 'claude', kind: 'state' as const, state: 'working' as const }+ expect(labelHeldForRevision(ev, 5)).toBe(ev)+ })+ it('stays bounded', () => {+ for (let i = 0; i < 1100; i++) labelHeldForRevision(blocked(`t-${i}`), 5)+ expect(isStructuredTicket('t-0')).toBe(false)+ expect(isStructuredTicket('t-1099')).toBe(true)+ })})diff --git a/src/core/agents/permission-decision.ts b/src/core/agents/permission-decision.tsindex 46579992e..249e3aa95 100644--- a/src/core/agents/permission-decision.ts+++ b/src/core/agents/permission-decision.ts@@ -21,6 +21,7 @@ import {isSafeToolName,type PermissionAnswer} from '../../shared/agents/permission-answer'+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'/*** Every JSON answer core writes starts with exactly these bytes, followed by `"allow"` or `"deny"`.@@ -31,13 +32,16 @@ import {export const PERMISSION_DECISION_PREFIX ='{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":'-/** Largest JSON answer core will write and the script will print. A question echo carries the+/** Largest JSON answer core will write and the script will print, in UTF-8 BYTES (core measures+ * with `Buffer.byteLength`; the script with `wc -c` on the file, never `${#…}`, which counts+ * characters under bash and bytes under dash). A question echo carries the* request's own questions (option descriptions, previews), so it is generous; anything larger is* refused rather than truncated (a truncated decision is invalid JSON). */export const PERMISSION_DECISION_MAX_BYTES = 64 * 1024-/** How much of the pending request file a reader takes. The file is the raw hook payload; a plan- * can be long. Past this the request is treated as unreadable (structured answers refuse). */+/** How much of the pending request file a reader takes, in UTF-8 BYTES. The file is the raw hook+ * payload; a plan can be long. Past this the request is treated as unreadable (structured answers+ * refuse). */export const PENDING_REQUEST_MAX_BYTES = 512 * 1024/**@@ -51,7 +55,8 @@ export const PENDING_REQUEST_MAX_BYTES = 512 * 1024*/export const PERM_WAIT_SECS_INTERACTIVE = 540-/** Caps on user-typed text. Generous for a person, small against the decision budget. */+/** Caps on user-typed text, in UTF-16 code units (`string.length`) — a person-sized limit, not a+ * wire limit; the whole decision's BYTE cap above is what bounds the file. */export const PLAN_REVISE_MAX_CHARS = 8000export const FREE_TEXT_MAX_CHARS = 8000@@ -73,7 +78,7 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {/** Parse the pending request file (the raw PermissionRequest hook payload). Null = not usable. */export function parsePendingRequest(text: string): PendingRequest | null {- if (typeof text !== 'string' || !text || text.length > PENDING_REQUEST_MAX_BYTES) return null+ if (typeof text !== 'string' || !text || Buffer.byteLength(text, 'utf8') > PENDING_REQUEST_MAX_BYTES) return nulllet raw: unknowntry {raw = JSON.parse(text)@@ -266,6 +271,60 @@ export function isBoundedAnswerContent(content: string): boolean {)}+/**+ * The first managed-script revision that understands a JSON answer (and maps a plain `allow` on a+ * plan). `MANAGED_SCRIPT_REVISION` must be >= this — pinned in managed-script.answer.test.ts. It+ * lives HERE rather than in managed-script.ts because that module imports this one.+ *+ * Why a revision gate at all: an SSH host gets a new script only at CONNECT, so a long-connected+ * project can hold a request with an older script. That script reads a JSON answer as neither+ * `allow` nor `deny`, deletes it and prints nothing — the TUI dialog stays — while the write itself+ * succeeded. Without this gate core would report success and the shells would flip NEEDS YOU to+ * "working" over an agent still waiting in its TUI.+ */+export const MIN_STRUCTURED_ANSWER_REVISION = 5++/** Tickets whose PermissionRequest was posted by a script >= MIN_STRUCTURED_ANSWER_REVISION.+ * Process-local and bounded: the only producer is this process's hook server, so a ticket we never+ * heard about (another instance's, or from before a restart) is simply not capable. */+const structuredTickets = new Set<string>()+const STRUCTURED_TICKETS_MAX = 1024++export function isStructuredTicket(pendingId: string): boolean {+ return structuredTickets.has(pendingId)+}++/** Test seam. */+export function _resetStructuredTicketsForTest(): void {+ structuredTickets.clear()+}++/**+ * Label a normalized hook event by the posting script's revision (called by the hook server, the+ * one place `clientRevision` is known, so both shells get it). A held request from a capable+ * script is recorded as a structured ticket and keeps `held`; from an older (or unstamped) script+ * `held` is DROPPED, so no surface offers controls the hook cannot honor. Everything else passes+ * through untouched (same reference).+ */+export function labelHeldForRevision(+ ev: NormalizedAgentEvent,+ clientRevision: number | undefined+): NormalizedAgentEvent {+ if (!ev.held) return ev+ if (typeof clientRevision === 'number' && clientRevision >= MIN_STRUCTURED_ANSWER_REVISION) {+ structuredTickets.delete(ev.held.pendingId)+ structuredTickets.add(ev.held.pendingId)+ while (structuredTickets.size > STRUCTURED_TICKETS_MAX) {+ const oldest = structuredTickets.values().next().value+ if (oldest === undefined) break+ structuredTickets.delete(oldest)+ }+ return ev+ }+ const { held: _dropped, ...rest } = ev+ return rest+}+/** The I/O legs of one answer: read the pending request text (null = missing), write the answer. */export interface HeldPermissionIo {readPending(): Promise<string | null>@@ -279,6 +338,7 @@ export interface HeldPermissionIo {* Resolves `{ok:false}` without writing on any refusal; never throws.*/export async function answerHeldPermission(+ pendingId: string,payload: { decision?: unknown; answer?: unknown },io: HeldPermissionIo): Promise<{ ok: boolean; decision?: 'allow' | 'deny' }> {@@ -289,13 +349,22 @@ export async function answerHeldPermission(? ({ kind: payload.decision } as PermissionAnswer): nullif (!answer) return { ok: false }+ const capable = isStructuredTicket(pendingId)+ // A structured answer to an OLDER script would be written, silently ignored, and reported as+ // success (see MIN_STRUCTURED_ANSWER_REVISION). Refuse before touching the host.+ if (answer.kind !== 'allow' && answer.kind !== 'deny' && !capable) return { ok: false }let text: string | null = nulltry {text = await io.readPending()} catch {text = null}- const built = buildPermissionDecision(text === null ? null : parsePendingRequest(text), answer)+ const pending = text === null ? null : parsePendingRequest(text)+ // Same false success for a plain allow on a plan: an older script prints a BARE allow, which+ // Claude drops. Only refused when we positively know it is a plan held by a non-capable script —+ // an unreadable request keeps the legacy fail-open write.+ if (answer.kind === 'allow' && pending?.toolName === EXIT_PLAN_MODE_TOOL && !capable) return { ok: false }+ const built = buildPermissionDecision(pending, answer)if (!built.ok) return { ok: false }let written = falsetry {diff --git a/src/main/index.ts b/src/main/index.tsindex 0fdfdde67..66bdb4b32 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2802,7 +2802,7 @@ app.whenReady().then(async () => {write: (content) => sshProjectManager!.writePendingAnswer(sshProjectId, pendingId, content)}: localHeldPermissionIo(pendingId, homedir())- const res = await answerHeldPermission({ decision: payload.decision, answer: payload.answer }, io)+ const res = await answerHeldPermission(pendingId, { decision: payload.decision, answer: payload.answer }, io)// Optimistic flip: on a successful write, emit the same synthetic "answered" transition the// held hook's second POST will produce, so the NEEDS YOU badge clears instantly instead of// waiting for that POST to round-trip. The later hook POST is an idempotent duplicate (adiff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 95c858907..d737aca37 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -9,7 +9,7 @@ import { legacyEndpointMigration } from './legacy-hook-endpoint'// simply runs without status). Takes an INJECTED runner so the flow is unit-testable without real// ssh/electron.import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'-import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS } from '@shared/agents/hook-events'+import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, type ManagedHookEvent } from '@shared/agents/hook-events'import { GROK_EVENTS } from '../../core/agents/hooks/grok'import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'@@ -103,7 +103,7 @@ export interface RemoteRunner {// here and had drifted: claude was missing StopFailure/PermissionRequest (an errored remote turn// stuck on "working"), and gemini was subscribed to CLAUDE's event names, which it never fires —// so remote gemini nodes reported nothing at all.-const AGENT_TARGETS: { agentId: string; config: string; events: readonly string[] }[] = [+const AGENT_TARGETS: { agentId: string; config: string; events: readonly ManagedHookEvent[] }[] = [{ agentId: 'claude', config: '.claude/settings.json', events: CLAUDE_HOOK_EVENTS },{ agentId: 'gemini', config: '.gemini/settings.json', events: GEMINI_HOOK_EVENTS }]@@ -440,7 +440,7 @@ export class RemoteHooks {controlPath: string,home: string,remoteDir: string,- target: { agentId: string; config: string; events: readonly string[] }+ target: { agentId: string; config: string; events: readonly ManagedHookEvent[] }): Promise<void> {try {const script = `${remoteDir}/agent-hooks/${target.agentId}.sh`diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 0ef27e261..a89705562 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -1934,7 +1934,7 @@ export class SshProjectManager {const { code, stdout } = await this.r.run(childArgs(c.conn, c.controlPath, cmd)).catch(() => ({ code: 1, stdout: '' }))- if (code !== 0 || typeof stdout !== 'string' || stdout.length > PENDING_REQUEST_MAX_BYTES) return null+ if (code !== 0 || typeof stdout !== 'string' || Buffer.byteLength(stdout, 'utf8') > PENDING_REQUEST_MAX_BYTES) return nullreturn stdout}diff --git a/src/renderer/lib/approveGate.test.ts b/src/renderer/lib/approveGate.test.tsnew file mode 100644index 000000000..71ab48b41--- /dev/null+++ b/src/renderer/lib/approveGate.test.ts@@ -0,0 +1,50 @@+// Behavior test for the header ✓ Approve gate: real hook payloads through the real normalizer into+// the real agent-status store, then the gate. The no-stash question case is the one the gate exists+// for (the mirror then classifies the picker as an APPROVAL and keeps its pendingId — pinned in+// core/agent-status-mirror.test.ts); with a stash the mirror strips pendingId and nothing renders.+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { describe, expect, it } from 'vitest'+import { normalizeClaude } from '@shared/agents/normalize'+import { useAgentStatus } from '../state/agentStatus'+import { canPlainApprove } from './approveGate'++let seq = 0+function held(tool: string, toolInput: unknown): string {+ const id = `gate-${++seq}`+ const e = normalizeClaude({+ nodeId: id,+ agentId: 'claude',+ payload: { hook_event_name: 'PermissionRequest', session_id: 's', tool_name: tool, tool_input: toolInput, nodeterm_pending_id: `${id}-1-1` }+ })!+ useAgentStatus.getState().setState(id, e.state, e.agentId, e.newTurn, e.pendingId, e.verified, e.errored, e.held)+ return id+}+const statusOf = (id: string) => useAgentStatus.getState().byId[id]++describe('canPlainApprove', () => {+ it('a held plan offers Approve (the hook maps a plain allow to updatedInput:{})', () => {+ expect(canPlainApprove(statusOf(held('ExitPlanMode', { plan: 'p' })))).toBe(true)+ })+ it('an ordinary permission offers Approve', () => {+ expect(canPlainApprove(statusOf(held('Bash', { command: 'ls' })))).toBe(true)+ })+ it('a held question whose ticket kept its pendingId does NOT offer Approve', () => {+ const id = held('AskUserQuestion', { questions: [{ question: 'Q?', options: [{ label: 'A' }] }] })+ expect(statusOf(id).pendingId).toBeTruthy() // the case the gate exists for+ expect(canPlainApprove(statusOf(id))).toBe(false)+ })+ it('a concurrent child approval keeps its own Approve while a question is held', () => {+ expect(+ canPlainApprove({ pendingId: 'child-1-1', held: { pendingId: 'parent-2-2', toolName: 'AskUserQuestion' } })+ ).toBe(true)+ })+ it('no ticket, no button', () => {+ expect(canPlainApprove(undefined)).toBe(false)+ expect(canPlainApprove({})).toBe(false)+ })+ it('the node header renders ✓ Approve through this gate', () => {+ const src = readFileSync(resolve(__dirname, '../nodes/TerminalNode.tsx'), 'utf8')+ expect(src).toContain('{canPlainApprove(status) && (')+ })+})diff --git a/src/renderer/lib/approveGate.ts b/src/renderer/lib/approveGate.tsnew file mode 100644index 000000000..f637720fb--- /dev/null+++ b/src/renderer/lib/approveGate.ts@@ -0,0 +1,16 @@+import { ASK_USER_QUESTION_TOOL, type HeldPermission } from '@shared/agents/permission-answer'++/**+ * Whether the node header may offer ✓ Approve (a plain `allow`) for the node's current ticket.+ *+ * A plain allow cannot answer a held AskUserQuestion: Claude drops it, the managed hook consumes it+ * and keeps holding, and core refuses to write it. Normally the mirror strips `pendingId` from a+ * question, so the buttons never render at all — but a picker whose PreToolUse stash is missing+ * (hook lost, stash expired) is classified as an APPROVAL and keeps its `pendingId`. That is the+ * case this gate exists for. It compares the ticket, so a concurrent child approval (a different+ * `pendingId`) keeps its own Approve while a question is held.+ */+export function canPlainApprove(status: { pendingId?: string; held?: HeldPermission } | undefined): boolean {+ if (!status?.pendingId) return false+ return !(status.held?.toolName === ASK_USER_QUESTION_TOOL && status.held.pendingId === status.pendingId)+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 936c3945a..3dddae290 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1,4 +1,5 @@import { useContextEnsure } from '../terminal/useContextEnsure'+import { canPlainApprove } from '../lib/approveGate'import { FIND_DECORATIONS } from '../lib/palette'import { ptyRefusal } from '@shared/pty-refusal'@@ -5691,11 +5692,10 @@ export function TerminalNode({state leaves `blocked` (the store clears pendingId). */}{status?.state === 'blocked' && status?.pendingId && (<span className="term-node__approve nodrag">- {/* A plain allow cannot answer a question (Claude drops it and the hook keeps holding),- so Approve is hidden when THIS ticket is a held AskUserQuestion (a concurrent child- approval keeps its own Approve); Deny still declines it. A held ExitPlanMode keeps Approve: the hook maps a plain allow to "restore the pre-plan- mode" (docs/hook-reply-approvals.md). */}- {!(status.held?.toolName === 'AskUserQuestion' && status.held.pendingId === status.pendingId) && (+ {/* Approve is hidden when THIS ticket is a held AskUserQuestion (lib/approveGate.ts);+ Deny still declines it. A held ExitPlanMode keeps Approve: the hook maps a plain+ allow to "restore the pre-plan mode" (docs/hook-reply-approvals.md). */}+ {canPlainApprove(status) && (<buttonclassName="term-node__approve-btn term-node__approve-btn--allow"title="Approve this permission request"diff --git a/src/renderer/nodes/approve-button-gate.test.ts b/src/renderer/nodes/approve-button-gate.test.tsdeleted file mode 100644index 793b32037..000000000--- a/src/renderer/nodes/approve-button-gate.test.ts+++ /dev/null@@ -1,21 +0,0 @@-// The header ✓ Approve writes a plain `allow`. For a held AskUserQuestion that is not an answer —-// Claude drops a bare allow on that tool, and the managed hook consumes it and keeps holding — so-// the button must not render for that ticket. Source-level pin: the header is a large component-// with no render harness, and the condition is exactly the kind of line a refactor drops silently.-import { readFileSync } from 'node:fs'-import { resolve } from 'node:path'-import { describe, expect, it } from 'vitest'--describe('TerminalNode header Approve gate', () => {- const src = readFileSync(resolve(__dirname, 'TerminalNode.tsx'), 'utf8')- it('hides Approve only when THIS ticket is a held AskUserQuestion', () => {- expect(src).toContain(- "{!(status.held?.toolName === 'AskUserQuestion' && status.held.pendingId === status.pendingId) && ("- )- })- it('Approve and Deny still speak the legacy decision words (the hook maps a plan allow)', () => {- const block = src.slice(src.indexOf('term-node__approve nodrag'), src.indexOf('✕ Deny'))- expect(block).toContain("decision: 'allow'")- expect(block).toContain("decision: 'deny'")- })-})diff --git a/src/server/index.ts b/src/server/index.tsindex 2cf5276cd..78b77c42f 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -515,6 +515,7 @@ export async function startServer(if (workspaceStore.sshProjectIdForNode(nodeId)) return false// Same shared body as the desktop (core/agents/permission-decision.ts), local fs only.const res = await answerHeldPermission(+ pendingId,{ decision: payload.decision, answer: payload.answer },localHeldPermissionIo(pendingId, os.homedir()))diff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.tsindex 2931ddd17..83d5f4d6a 100644--- a/src/shared/agents/hook-events.ts+++ b/src/shared/agents/hook-events.ts@@ -19,7 +19,21 @@* claude/codex/gemini stay plain strings, so their emitted config is byte-identical to what it has* always been.*/-export type ManagedHookEvent = string | { event: string; matcher: string }+export type ManagedHookEvent = string | { event: string; matcher?: string; timeout?: number }++/** A subscription's event name, whichever form it was declared in. */+export function managedEventName(e: ManagedHookEvent): string {+ return typeof e === 'string' ? e : e.event+}++/**+ * The `timeout` (seconds) we write on claude's PermissionRequest handler. Claude's command-hook+ * default is 600 s today, but a held plan/question waits up to `PERM_WAIT_SECS_INTERACTIVE` (540 s,+ * core/agents/permission-decision.ts) — so the bound the hold is sized against is written down in+ * the user's settings instead of borrowed from a CLI default that could change under us. Existing+ * installs pick it up at the next install (the managed entry is always rewritten fresh).+ */+export const PERMISSION_REQUEST_HOOK_TIMEOUT_SECS = 600/** Claude Code hook events. Each maps to a `NormalizedAgentEvent` in shared/agents/normalize.ts. */export const CLAUDE_HOOK_EVENTS = [@@ -30,12 +44,13 @@ export const CLAUDE_HOOK_EVENTS = [// status badge sticks on "working" after any errored turn.'StopFailure','Notification',- // Dedicated permission-prompt signal (→ blocked), more direct than Notification.- 'PermissionRequest',+ // Dedicated permission-prompt signal (→ blocked), more direct than Notification. Carries an+ // explicit timeout because the managed hook HOLDS it (hook-reply approvals, up to 540 s).+ { event: 'PermissionRequest', timeout: PERMISSION_REQUEST_HOOK_TIMEOUT_SECS },'SessionEnd','PreToolUse','PostToolUse'-] as const+] as const satisfies readonly ManagedHookEvent[]/*** Gemini CLI hook events (→ normalizeGemini) — its own names, NOT Claude's.