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
feat(approvals): hook-reply Approve/Deny — the decision IS the hook's answer
enes7380308675ac
diff --git a/docs/hook-reply-approvals.md b/docs/hook-reply-approvals.mdnew file mode 100644index 000000000..11edfedcd--- /dev/null+++ b/docs/hook-reply-approvals.md@@ -0,0 +1,67 @@+# Hook-reply approvals — deterministic Approve/Deny (v1 contract)++Inspired by claude-island's EventServer: its permission hook holds the HTTP request open and+the UI's Allow/Deny **is the hook's reply** — no keystrokes, no prompt-layout coupling. This+doc adapts that to nodeterm's architecture, where the answerer may be a **phone reaching the+host over SSH** (no route to the desktop's loopback server), so the reply channel is a+**file on the host the agent runs on** — reachable by every answerer we have.++## Why replace send-keys++The phone's quick-approve today types `1`/Escape into tmux. It depends on the permission+prompt being on screen, focused, and numbered the way we assume. Hook-reply is deterministic:+Claude Code applies the decision before ever painting the prompt; on timeout it falls through+to the normal interactive prompt (fail-open, bit-for-bit legacy).++## Mechanism++**Request** — the managed hook script's `PermissionRequest` branch (env-gated like everything+else in `managed-script.ts`), only when `NODETERM_PERM_WAIT_SECS` is set (> 0) in the session+env:+1. Generate `pendingId` = `<nodeId>-<epoch-ms>-$$`.+2. Write the incoming hook JSON to `~/.nodeterm/pending/<pendingId>.json` (mkdir -p, umask 077).+3. POST to the loopback hook server as today (fire-and-forget status flow — this is how the+ mirror/inbox learns `pendingId`).+4. Poll `~/.nodeterm/pending/<pendingId>.answer` every 0.5 s up to `NODETERM_PERM_WAIT_SECS`+ (default injected: 45; hook must stay under Claude's own hook timeout).+5. Answer file appears: read it (`allow` | `deny`), `rm -f` both files, print the decision+ JSON to stdout:+ `{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}`+ (deny adds a short `"message"`). Exit 0.+6. Timeout: `rm -f` the request file, print **nothing**, exit 0 → Claude shows its normal+ prompt; legacy send-keys still works as the fallback.++POSIX sh only, no deps — same constraints as the existing managed script. The wait branch+must be a **no-op** when the env var is absent (user's own terminals, older nodeterm).++**Answerers** (all write the same one-line answer file, atomically `printf > tmp && mv`):+- **Phone (SSH)** — `InboxApproval` writes it over the connection when the approval event+ carries `pendingId`; else falls back to send-keys. Digit `2`/"Always allow" keeps using+ send-keys in v1 (hook `updatedPermissions` is out of scope).+- **Desktop canvas** — the NEEDS-YOU badge gains Approve/Deny buttons (approval events with+ `pendingId` only), routed over IPC to a main-side writer: local project → local fs; SSH+ project → write via the project's ControlMaster. So desktop users are not left staring at+ a held prompt — they get one-click approval the moment the badge pulses.++**Event plumbing** — the hook server's raw `PermissionRequest` payload now carries+`nodeterm_pending_id` (added by the script to its POST body); the mirror's approval+`InboxEvent` gains `pendingId?: string`, riding the mirror (phone) and dropped from the+push-notify POST body (the APNs payload doesn't need it — the phone re-reads the mirror+before acting anyway).++**Env injection** — `buildPtyEnv` adds `NODETERM_PERM_WAIT_SECS=<n>` when the new setting+`hookReplyApprovals` (default **on**) is enabled AND the agent is claude (the only CLI whose+PermissionRequest hook decision contract we've verified). Setting lives beside the mobile-push+settings; off ⇒ env absent ⇒ script branch inert ⇒ exact legacy behavior.++**Cleanup** — the hook server sweeps `~/.nodeterm/pending/` for files older than 10 min on+boot and hourly (orphans from killed sessions). The phone/desktop never create answer files+for pendingIds they didn't read from a live approval event, and re-check the event is still+unresolved before writing.++## Out of scope (v1)++- Questions (AskUserQuestion) — a hook cannot inject an answer value; digits remain.+- "Always allow" via hook `updatedPermissions`.+- codex/gemini permission hooks (unverified decision contracts).+- The desktop notch/HUD overlay (separate feature).diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex c5bb9cb88..d70e91d3f 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -9,6 +9,12 @@ import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/norexport const NODETERM_HOOK_PROTOCOL_VERSION = '1'const SLOWLORIS_MS = 2000+// 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.+// See docs/hook-reply-approvals.md.+export const PERM_WAIT_SECS_DEFAULT = 45+function readBody(req: IncomingMessage): Promise<string> {return new Promise((resolve) => {// Collect Buffers and decode ONCE at the end: `data += chunk` coerced every chunk through@@ -129,6 +135,11 @@ class HookServer {} catch {payload = {}}+ // Deterministic-approval ticket: the managed permission hook adds `nodeterm_pending_id`+ // as a separate form field (it can't edit the agent's JSON payload in POSIX sh). Merge it+ // into the payload object so both the raw listener and the normalizers see it as if it+ // rode inside the hook JSON. See docs/hook-reply-approvals.md.+ if (form.nodeterm_pending_id) payload.nodeterm_pending_id = form.nodeterm_pending_id// Raw listener first: it drives the transcript-tailing features (which need// transcript_path). Inside the try so a throwing raw listener still ends 204.this.rawListener?.(agentId, nodeId, payload)@@ -186,7 +197,11 @@ class HookServer {}}- buildPtyEnv(nodeId: string, agentId: AgentId): Record<string, string> {+ // `permWaitSecs > 0` opts this session into the deterministic hook-reply approval flow: the+ // managed permission hook holds for that many seconds for a phone/canvas answer file before+ // falling through to Claude's interactive prompt. 0/undefined ⇒ NODETERM_PERM_WAIT_SECS absent ⇒+ // the hook's wait-branch is inert (exact legacy behavior). See docs/hook-reply-approvals.md.+ buildPtyEnv(nodeId: string, agentId: AgentId, permWaitSecs = 0): Record<string, string> {if (this.port <= 0 || !this.token) return {}return {NODETERM_HOOK_PORT: String(this.port),@@ -195,6 +210,7 @@ class HookServer {NODETERM_HOOK_ENDPOINT: this.endpointFilePath(),NODETERM_NODE_ID: nodeId,NODETERM_AGENT_ID: agentId,+ ...(permWaitSecs > 0 ? { NODETERM_PERM_WAIT_SECS: String(permWaitSecs) } : {}),...(canControlCanvas(agentId) ? { NODETERM_CANVAS_CONTROL: '1' } : {})}}diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex ffd07467b..01669ea6d 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -14,4 +14,48 @@ describe('buildManagedScript', () => {it('still no-ops without node id / endpoint', () => {expect(s).toContain('NODETERM_NODE_ID')})++ describe('deterministic hook-reply approvals (PermissionRequest wait branch)', () => {+ it('gates the wait branch on NODETERM_PERM_WAIT_SECS > 0', () => {+ expect(s).toContain('[ -n "$NODETERM_PERM_WAIT_SECS" ] && [ "$NODETERM_PERM_WAIT_SECS" -gt 0 ]')+ })+ it('only arms on a PermissionRequest hook', () => {+ expect(s).toContain('"hook_event_name":"PermissionRequest"')+ })+ it('generates a pendingId and writes the request file under ~/.nodeterm/pending with umask 077', () => {+ expect(s).toContain('nt_pending="${nt_node}-${nt_ms}-$$"')+ expect(s).toContain('$HOME/.nodeterm/pending')+ expect(s).toContain('(umask 077; mkdir -p "$nt_dir")')+ expect(s).toContain('(umask 077; printf %s "$payload" > "$nt_pending_file")')+ })+ it('sanitizes the node id to the safe filename charset', () => {+ expect(s).toContain("tr -c 'A-Za-z0-9_-' '_'")+ })+ it('tags the POST body with nodeterm_pending_id on both transports', () => {+ // Two POST blocks (unix-socket + TCP) — both carry the tag.+ const matches = s.match(/--data-urlencode "nodeterm_pending_id=\$\{nt_pending\}"/g) ?? []+ expect(matches.length).toBe(2)+ })+ it('polls the answer file every 0.5s up to the armed seconds', () => {+ expect(s).toContain('nt_answer="$HOME/.nodeterm/pending/$nt_pending.answer"')+ expect(s).toContain('nt_max=$((NODETERM_PERM_WAIT_SECS * 2))')+ expect(s).toContain('sleep 0.5')+ })+ it('prints the exact allow / deny decision JSON', () => {+ expect(s).toContain(+ '{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}'+ )+ expect(s).toContain('"behavior":"deny"')+ expect(s).toContain('"message":"Denied from nodeterm."')+ })+ it('cleans up request + answer files and, on timeout, removes the request file', () => {+ expect(s).toContain('rm -f "$nt_answer" "$nt_pending_file"')+ expect(s).toContain('rm -f "$nt_pending_file"')+ })+ it('is a no-op branch for a non-claude agent script too (env-gated, present but inert)', () => {+ const codex = buildManagedScript('codex')+ expect(codex).toContain('NODETERM_PERM_WAIT_SECS')+ expect(codex).toContain('/hook/codex')+ })+ })})diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 858265996..587e2ff38 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -2,6 +2,16 @@// It sources the endpoint file for the LIVE port/token (restart handoff), no-ops// outside nodeterm-spawned sessions (gating via NODETERM_NODE_ID), and posts the// raw hook payload to the loopback server. Fails open at every step.+//+// 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+// ~/.nodeterm/pending/, tags the POST body with nodeterm_pending_id (so the mirror/inbox+// learns it), then polls for ~/.nodeterm/pending/<pendingId>.answer for up to that many+// seconds. An answer ('allow' | 'deny') is echoed back as the hook's decision JSON; a+// timeout prints nothing and Claude falls through to its normal interactive prompt. The+// whole branch is a NO-OP when the env var is absent (a user's own terminals, older+// nodeterm, non-claude agents), so behavior is bit-for-bit legacy there.export function buildManagedScript(agentId: string): string {return ['#!/bin/sh',@@ -15,6 +25,24 @@ export function buildManagedScript(agentId: string): string {'if [ -z "$payload" ]; then',' exit 0','fi',+ '# Deterministic-approval request: only for a PermissionRequest hook while the wait is armed.',+ '# `nt_pending` stays empty otherwise, so the POST tag and the poll loop below are both inert.',+ 'nt_pending=""',+ 'nt_pending_file=""',+ 'if [ -n "$NODETERM_PERM_WAIT_SECS" ] && [ "$NODETERM_PERM_WAIT_SECS" -gt 0 ] 2>/dev/null; then',+ ' case "$payload" in',+ ' *\'"hook_event_name":"PermissionRequest"\'*|*\'"hook_event_name": "PermissionRequest"\'*)',+ ' nt_node=$(printf %s "$NODETERM_NODE_ID" | tr -c \'A-Za-z0-9_-\' \'_\')',+ ' nt_ms=$(date +%s%3N 2>/dev/null)',+ ' case "$nt_ms" in \'\'|*[!0-9]*) nt_ms=$(date +%s) ;; esac',+ ' nt_pending="${nt_node}-${nt_ms}-$$"',+ ' nt_dir="$HOME/.nodeterm/pending"',+ ' (umask 077; mkdir -p "$nt_dir") 2>/dev/null || :',+ ' nt_pending_file="$nt_dir/$nt_pending.json"',+ ' (umask 077; printf %s "$payload" > "$nt_pending_file") 2>/dev/null || :',+ ' ;;',+ ' 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 \\',@@ -22,6 +50,7 @@ export function buildManagedScript(agentId: string): string {' -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}" \\`,@@ -30,8 +59,31 @@ export function buildManagedScript(agentId: string): string {' -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','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',+ ' nt_answer="$HOME/.nodeterm/pending/$nt_pending.answer"',+ ' nt_max=$((NODETERM_PERM_WAIT_SECS * 2))',+ ' nt_i=0',+ ' while [ "$nt_i" -lt "$nt_max" ]; do',+ ' if [ -f "$nt_answer" ]; then',+ ' nt_decision=$(cat "$nt_answer" 2>/dev/null)',+ ' rm -f "$nt_answer" "$nt_pending_file" 2>/dev/null || :',+ ' if [ "$nt_decision" = "allow" ]; then',+ ' printf \'%s\\n\' \'{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}\'',+ ' elif [ "$nt_decision" = "deny" ]; then',+ ' printf \'%s\\n\' \'{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"Denied from nodeterm."}}}\'',+ ' fi',+ ' exit 0',+ ' fi',+ ' sleep 0.5 2>/dev/null || sleep 1',+ ' nt_i=$((nt_i + 1))',+ ' done',+ ' # Timed out: clean up the request file and print nothing → Claude shows its normal prompt.',+ ' rm -f "$nt_pending_file" 2>/dev/null || :',+ 'fi','exit 0',''].join('\n')diff --git a/src/core/agents/pending-approvals.test.ts b/src/core/agents/pending-approvals.test.tsnew file mode 100644index 000000000..fecabf6b4--- /dev/null+++ b/src/core/agents/pending-approvals.test.ts@@ -0,0 +1,108 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ isValidPendingId,+ pendingDir,+ writePendingAnswerLocal,+ sweepPendingDir,+ PENDING_MAX_AGE_MS+} from './pending-approvals'++let home: string++beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-pending-'))+})+afterEach(() => {+ fs.rmSync(home, { recursive: true, force: true })+})++describe('isValidPendingId', () => {+ it('accepts the script charset', () => {+ expect(isValidPendingId('nt_node-1720000000000-12345')).toBe(true)+ expect(isValidPendingId('abcXYZ_09-')).toBe(true)+ })+ it('rejects traversal / injection / empty', () => {+ expect(isValidPendingId('')).toBe(false)+ expect(isValidPendingId('../etc/passwd')).toBe(false)+ expect(isValidPendingId('a/b')).toBe(false)+ expect(isValidPendingId('a b')).toBe(false)+ expect(isValidPendingId('a;rm -rf')).toBe(false)+ expect(isValidPendingId('a.answer')).toBe(false)+ expect(isValidPendingId('a'.repeat(257))).toBe(false)+ })+})++describe('writePendingAnswerLocal', () => {+ it('writes the one-line answer file for a valid id + decision', async () => {+ const ok = await writePendingAnswerLocal('node-1-2', 'allow', home)+ expect(ok).toBe(true)+ const file = path.join(pendingDir(home), 'node-1-2.answer')+ expect(fs.readFileSync(file, 'utf8')).toBe('allow')+ })++ it('writes deny too', async () => {+ expect(await writePendingAnswerLocal('n', 'deny', home)).toBe(true)+ expect(fs.readFileSync(path.join(pendingDir(home), 'n.answer'), 'utf8')).toBe('deny')+ })++ it('leaves no .tmp behind (atomic rename)', async () => {+ await writePendingAnswerLocal('n', 'allow', home)+ const entries = fs.readdirSync(pendingDir(home))+ expect(entries).toEqual(['n.answer'])+ })++ it('refuses an invalid pendingId and writes nothing', async () => {+ expect(await writePendingAnswerLocal('../evil', 'allow', home)).toBe(false)+ expect(fs.existsSync(pendingDir(home))).toBe(false)+ })++ it('refuses an out-of-contract decision', async () => {+ // @ts-expect-error — exercising the runtime guard against a bad value+ expect(await writePendingAnswerLocal('n', 'always', home)).toBe(false)+ })+})++describe('sweepPendingDir', () => {+ it('removes files older than the max age, keeps fresh ones', async () => {+ const dir = pendingDir(home)+ fs.mkdirSync(dir, { recursive: true })+ const stale = path.join(dir, 'old-1.json')+ const fresh = path.join(dir, 'new-1.json')+ fs.writeFileSync(stale, '{}')+ fs.writeFileSync(fresh, '{}')+ const now = Date.now()+ // Backdate the stale file well past the window.+ const old = new Date(now - PENDING_MAX_AGE_MS - 60_000)+ fs.utimesSync(stale, old, old)++ const removed = await sweepPendingDir(now, PENDING_MAX_AGE_MS, home)+ expect(removed).toBe(1)+ expect(fs.existsSync(stale)).toBe(false)+ expect(fs.existsSync(fresh)).toBe(true)+ })++ it('also sweeps stale .answer orphans and ignores unrelated files', async () => {+ const dir = pendingDir(home)+ fs.mkdirSync(dir, { recursive: true })+ const ans = path.join(dir, 'x.answer')+ const other = path.join(dir, 'notes.txt')+ fs.writeFileSync(ans, 'allow')+ fs.writeFileSync(other, 'keep')+ const now = Date.now()+ const old = new Date(now - PENDING_MAX_AGE_MS - 1000)+ fs.utimesSync(ans, old, old)+ fs.utimesSync(other, old, old)++ const removed = await sweepPendingDir(now, PENDING_MAX_AGE_MS, home)+ expect(removed).toBe(1)+ expect(fs.existsSync(ans)).toBe(false)+ expect(fs.existsSync(other)).toBe(true) // non-pending file untouched+ })++ it('returns 0 (no throw) when the dir does not exist', async () => {+ expect(await sweepPendingDir(Date.now(), PENDING_MAX_AGE_MS, home)).toBe(0)+ })+})diff --git a/src/core/agents/pending-approvals.ts b/src/core/agents/pending-approvals.tsnew file mode 100644index 000000000..70b32bafa--- /dev/null+++ b/src/core/agents/pending-approvals.ts@@ -0,0 +1,113 @@+// Deterministic hook-reply approvals — the answer-file side (docs/hook-reply-approvals.md).+//+// The managed permission hook (managed-script.ts) holds an incoming PermissionRequest open and+// polls `<home>/.nodeterm/pending/<pendingId>.answer` for a one-line `allow` | `deny`. This module+// writes that answer file (LOCAL fs — the host the agent runs on for a local project) and sweeps+// stale request files left by killed/timed-out sessions.+//+// Electron-free (fs/path/os only), so both shells boot it. Every function fails soft: an invalid+// pendingId or an fs error resolves false / logs, never throws.++import fs from 'fs'+import os from 'os'+import path from 'path'++/** pendingId shape the script generates (`<node>-<ms>-<pid>`) and the ONLY thing we interpolate+ * into a filename. Validated everywhere a pendingId becomes a path so a forged value can't+ * traverse (`../`) or inject. Keep in sync with the managed script's `tr -c 'A-Za-z0-9_-'`. */+export const PENDING_ID_RE = /^[A-Za-z0-9_-]+$/++/** How old a request (`.json`) / answer (`.answer`) file may get before the sweeper removes it. */+export const PENDING_MAX_AGE_MS = 10 * 60_000+/** Sweep cadence (boot + this interval). */+export const PENDING_SWEEP_INTERVAL_MS = 60 * 60_000++export function isValidPendingId(pendingId: string): boolean {+ return typeof pendingId === 'string' && pendingId.length > 0 && pendingId.length <= 256 && PENDING_ID_RE.test(pendingId)+}++/** `<home>/.nodeterm/pending`. `homeDir` is injected so tests never touch the real home. */+export function pendingDir(homeDir: string = os.homedir()): string {+ return path.join(homeDir, '.nodeterm', 'pending')+}++/**+ * Write the one-line answer file for a held permission hook, atomically (tmp + rename, mode 0600).+ * Resolves true on success, false on an invalid pendingId or any fs error (fail-open — the hook+ * simply times out to the interactive prompt). The `decision` is written verbatim as the hook+ * script compares it against the literals `allow` / `deny`.+ */+export async function writePendingAnswerLocal(+ pendingId: string,+ decision: 'allow' | 'deny',+ homeDir: string = os.homedir()+): Promise<boolean> {+ if (!isValidPendingId(pendingId)) return false+ if (decision !== 'allow' && decision !== 'deny') return false+ const dir = pendingDir(homeDir)+ const file = path.join(dir, `${pendingId}.answer`)+ const tmp = `${file}.${process.pid}.tmp`+ try {+ await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 })+ await fs.promises.writeFile(tmp, decision, { mode: 0o600 })+ await fs.promises.rename(tmp, file)+ return true+ } catch {+ await fs.promises.rm(tmp, { force: true }).catch(() => {})+ return false+ }+}++/**+ * Remove `.json` / `.answer` files under the pending dir older than `maxAgeMs` (orphans from killed+ * or timed-out sessions). Returns the count removed. Best-effort — a missing dir or unreadable+ * entry is silently skipped. Pure w.r.t. its `now`/`homeDir` inputs for testing.+ */+export async function sweepPendingDir(+ now: number = Date.now(),+ maxAgeMs: number = PENDING_MAX_AGE_MS,+ homeDir: string = os.homedir()+): Promise<number> {+ const dir = pendingDir(homeDir)+ let removed = 0+ let names: string[]+ try {+ names = await fs.promises.readdir(dir)+ } catch {+ return 0 // no dir yet / unreadable+ }+ for (const name of names) {+ if (!name.endsWith('.json') && !name.endsWith('.answer')) continue+ const p = path.join(dir, name)+ try {+ const st = await fs.promises.stat(p)+ if (now - st.mtimeMs > maxAgeMs) {+ await fs.promises.rm(p, { force: true })+ removed+++ }+ } catch {+ // Raced deletion / stat error: skip.+ }+ }+ return removed+}++export interface PendingSweeperHandle {+ stop(): void+}++/**+ * Start the pending-dir sweeper: one sweep now, then every `intervalMs`. The interval is unref'd so+ * it never keeps the process alive. Wired once per shell on boot.+ */+export function startPendingSweep(+ homeDir: string = os.homedir(),+ intervalMs: number = PENDING_SWEEP_INTERVAL_MS+): PendingSweeperHandle {+ void sweepPendingDir(Date.now(), PENDING_MAX_AGE_MS, homeDir).catch(() => {})+ const timer = setInterval(() => {+ void sweepPendingDir(Date.now(), PENDING_MAX_AGE_MS, homeDir).catch(() => {})+ }, intervalMs)+ timer.unref?.()+ return { stop: () => clearInterval(timer) }+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 027550600..62f5a9ece 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -16,7 +16,7 @@ import {type TmuxStatus} from '../shared/types'import { findCommand, tmuxInstall } from './tmux-hint'-import { hookServer } from './agents/hook-server'+import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'import {probeSaysAbsent,remoteHookEnvArgs,@@ -1110,9 +1110,16 @@ export class PtyManager {// 127.0.0.1:<localPort>, which is useless (and misleading) on the remote host. The remote// session's hook env is injected via the remote tmux `-e` below (from the reverse-tunnel// endpoint file), so leave the local hook env out entirely here.+ // Deterministic hook-reply approvals (docs/hook-reply-approvals.md): arm the permission hook's+ // wait-branch for claude sessions when the setting is on. `permWaitSecs > 0` injects+ // NODETERM_PERM_WAIT_SECS; off / non-claude ⇒ 0 ⇒ absent ⇒ legacy behavior.+ const permWaitSecs =+ this.getSettings().hookReplyApprovals && (options.agentId ?? 'claude') === 'claude'+ ? PERM_WAIT_SECS_DEFAULT+ : 0const hookEnv =options.persistKey && !options.sshRemote- ? hookServer.buildPtyEnv(options.persistKey, options.agentId ?? 'claude')+ ? hookServer.buildPtyEnv(options.persistKey, options.agentId ?? 'claude', permWaitSecs): {}for (const [k, v] of Object.entries(hookEnv)) env[k] = v@@ -1173,11 +1180,17 @@ export class PtyManager {// selection off that raw id with no `nt-` stripping. Passing the session name here would// emit events under `nt-<id>` that match no node → no badge/notification/session/loop.const hookExtraEnv = options.sshRemote.hookEndpointPath- ? remoteHookEnvArgs(- options.sshRemote.hookEndpointPath,- options.persistKey,- hookServer.getVersion()- )+ ? [+ ...remoteHookEnvArgs(+ options.sshRemote.hookEndpointPath,+ options.persistKey,+ hookServer.getVersion()+ ),+ // Arm the remote permission hook's wait-branch too (deterministic approvals over SSH):+ // the request/answer files live on the REMOTE host; the desktop answers over the+ // ControlMaster. Only when the hook endpoint is set (else no POST → nothing learns the id).+ ...(permWaitSecs > 0 ? ['-e', `NODETERM_PERM_WAIT_SECS=${permWaitSecs}`] : [])+ ]: []// Managed REMOTE Claude account (Task 12): inject CLAUDE_CONFIG_DIR into the remote tmux// session via `-e`, pointing at the account's config dir on the remote host. The path must bediff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex aaec252ff..61299a663 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -383,6 +383,19 @@ export class WorkspaceStore {return new Set((e?.cache?.nodes ?? []).map((n) => n.id))}+ /** The SSH project id a node belongs to, or undefined for a local/inline node (deterministic+ * approvals: a match routes the answer-file write to the REMOTE host over that project's+ * ControlMaster; undefined ⇒ write on the LOCAL fs). Scans the ssh entries' cached node lists;+ * a not-yet-cached remote node resolves undefined (fail-open to a local write that harmlessly+ * never matches a remote poll). */+ sshProjectIdForNode(nodeId: string): string | undefined {+ for (const e of this.index?.entries ?? []) {+ if (!e.ssh) continue+ if ((e.cache?.nodes ?? []).some((n) => n.id === nodeId)) return e.id+ }+ return undefined+ }+/*** Resolve a node's human display title (what the canvas header / sessions sidebar shows) from the* last-persisted workspace, across all three entry kinds: inline canvases (`e.project.nodes`), sshdiff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex 52075eb03..12286e785 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -60,6 +60,34 @@ describe('SshProjectManager', () => {expect(mgr.refForRemoteCwd('/nope')).toBeUndefined()})+ it('writePendingAnswer writes the answer file over the master (atomic tmp+mv, decision on stdin)', async () => {+ const { mgr, run } = makeMgr()+ await mgr.connect('p1', conn)+ const ok = await mgr.writePendingAnswer('p1', 'node-1-2', 'allow')+ expect(ok).toBe(true)+ const call = run.mock.calls.find((c) => (c[0] as string[]).join(' ').includes('.answer'))+ expect(call).toBeTruthy()+ const cmd = (call![0] as string[]).join(' ')+ expect(cmd).toContain('umask 077')+ expect(cmd).toContain('.nodeterm/pending')+ // atomic tmp+mv: write to <id>.answer.tmp then rename onto <id>.answer.+ expect(cmd).toMatch(/cat > [\s\S]*\.answer\.tmp/)+ expect(cmd).toMatch(/mv -f [\s\S]*\.answer\.tmp[\s\S]*\.answer/)+ expect(call![1]).toBe('allow') // decision written on stdin+ })++ it('writePendingAnswer refuses an invalid pendingId and a disconnected project (no run)', async () => {+ const { mgr, run } = makeMgr()+ // Not connected → false, no ssh command issued.+ expect(await mgr.writePendingAnswer('p1', 'ok-id', 'allow')).toBe(false)+ await mgr.connect('p1', conn)+ const before = run.mock.calls.length+ expect(await mgr.writePendingAnswer('p1', '../evil', 'allow')).toBe(false)+ // @ts-expect-error — runtime guard against a bad decision value+ expect(await mgr.writePendingAnswer('p1', 'ok-id', 'always')).toBe(false)+ expect(run.mock.calls.length).toBe(before) // neither refusal touched ssh+ })+it('uploadFile uploads via scp under <remoteHome>/.nodeterm/uploads/<token> and returns the abs path', async () => {const scpCalls: string[][] = []const run = vi.fn(async (args: string[]) =>diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex e2b35f84c..8f27fd6d3 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -536,6 +536,41 @@ export class SshProjectManager {.catch(() => {})}+ /**+ * Deterministic hook-reply approvals (docs/hook-reply-approvals.md): write the one-line answer+ * file for a held REMOTE permission hook, on the project's host over its ControlMaster (atomic+ * tmp+mv, 0600 via umask). The hook is polling `~/.nodeterm/pending/<pendingId>.answer` on that+ * host. `pendingId` is validated by the caller (main) before it reaches here; this method also+ * refuses anything but the safe charset as defense-in-depth, since it interpolates into a remote+ * shell command. No-ops (false) when the project isn't connected or the write fails.+ */+ async writePendingAnswer(+ projectId: string,+ pendingId: string,+ decision: 'allow' | 'deny'+ ): Promise<boolean> {+ const c = this.conns.get(projectId)+ if (!c) return false+ if (!/^[A-Za-z0-9_-]+$/.test(pendingId)) return false+ if (decision !== 'allow' && decision !== 'deny') return false+ const dir = c.remoteHome ? `${c.remoteHome}/.nodeterm/pending` : '~/.nodeterm/pending'+ const file = `${dir}/${pendingId}.answer`+ const q = quoteRemotePath(file)+ const qTmp = quoteRemotePath(`${file}.tmp`)+ const qDir = quoteRemotePath(dir)+ const { code } = await this.r+ .run(+ childArgs(+ c.conn,+ c.controlPath,+ `umask 077; mkdir -p ${qDir} && cat > ${qTmp} && mv -f ${qTmp} ${q}`+ ),+ decision+ )+ .catch(() => ({ code: 1, stdout: '' }))+ return code === 0+ }+/*** The resolved remote `$HOME` for the project owning this `controlPath`, if known. The hook* raw-listener only has the node's `{ controlPath, conn }` (from `sshRemoteForNode`), so itdiff --git a/src/preload/index.ts b/src/preload/index.tsindex 0d05bd13e..51513e19b 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -500,6 +500,7 @@ const api: NodeTerminalApi = {ipcRenderer.on(IPC.appFocusNode, handler)return () => ipcRenderer.removeListener(IPC.appFocusNode, handler)},+ answerPermission: (payload) => ipcRenderer.invoke(IPC.agentAnswerPermission, payload),onAgentStatus: (listener) => {const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)ipcRenderer.on(IPC.agentStatus, handler)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 0e1487ed7..d78a46a40 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -115,6 +115,7 @@ export function buildStubApi(): Omit<| 'dialog'| 'onAgentStatus'| 'onSubagentActivity'+ | 'answerPermission'// Real over the bridge (IPC.appUserDataDir): the worktree dialog's default path is derived from// it, and a '' stub would propose `/worktrees/…` at the filesystem root.| 'userDataDir'@@ -330,6 +331,7 @@ export function buildStubApi(): Omit<| 'dialog'| 'onAgentStatus'| 'onSubagentActivity'+ | 'answerPermission'| 'userDataDir'| 'presence'| 'speech'diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 615a4a2b0..6085e315c 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -415,11 +415,16 @@ export function buildFilesApi(*/export function buildAgentApi(client: RpcClient-): Pick<NodeTerminalApi, 'onAgentStatus' | 'onSubagentActivity'> {+): Pick<NodeTerminalApi, 'onAgentStatus' | 'onSubagentActivity' | 'answerPermission'> {return {onAgentStatus: (listener) => client.subscribe(IPC.agentStatus, listener as Listener),onSubagentActivity: (listener) =>- client.subscribe(IPC.agentSubagentActivity, listener as Listener)+ client.subscribe(IPC.agentSubagentActivity, listener as Listener),+ // Deterministic hook-reply approvals: a real request over the bridge — the Server Edition runs+ // ON the host, so a local project's answer file is written right there (SSH-from-server is v1+ // unsupported and the handler returns false). See docs/hook-reply-approvals.md.+ answerPermission: (payload) =>+ client.request(IPC.agentAnswerPermission, payload) as Promise<boolean>}}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex ce30bcb2c..46c9aafd0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -5183,7 +5183,9 @@ export function Canvas() {const an = useAgentNodes.getState()switch (e.kind) {case 'state':- if (e.state) cs.setState(e.nodeId, e.state, e.agentId, e.newTurn)+ // `pendingId` (deterministic approvals) rides a `blocked` event; the store keeps it only+ // while blocked so the header's Approve/Deny buttons appear + vanish with the state.+ if (e.state) cs.setState(e.nodeId, e.state, e.agentId, e.newTurn, e.pendingId)if (e.newTurn) an.clearForParent(e.nodeId) // genuine new turn → drop the previous fan-outif (e.newTurn && e.task) {// Prompt-prefix fallback for /loop|/schedule|/cron when the natural-languagediff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex dcf69ae41..7b16243f5 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -21,6 +21,7 @@ import { hintLabel } from '@shared/platform-utils'import { SegmentedPill } from '@renderer/ui/SegmentedPill'import { Button } from '@renderer/ui/Button'import { Select } from '@renderer/ui/Select'+import { Switch } from '@renderer/ui/Switch'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'@@ -46,6 +47,10 @@ const ROWS = {'shift tab']},+ hookReplyApprovals: {+ title: 'One-click approvals',+ keywords: ['approve', 'deny', 'approval', 'permission', 'hook', 'phone', 'canvas', 'one click', 'claude']+ },}const ENTRIES = Object.values(ROWS)@@ -142,6 +147,19 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El}/></SearchableRow>+ <SearchableRow {...ROWS.hookReplyApprovals}>+ <FieldRow+ label="One-click approvals"+ description="Phone/canvas Approve & Deny answer Claude's permission hook directly; the interactive prompt appears after 45s if unanswered. Claude terminal sessions only."+ control={+ <Switch+ checked={settings.hookReplyApprovals}+ ariaLabel="One-click hook-reply approvals"+ onChange={(on) => update({ hookReplyApprovals: on })}+ />+ }+ />+ </SearchableRow></SettingsSection>)}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 3d222846f..943be16be 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1705,6 +1705,40 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNNEEDS YOU</span>)}+ {/* Deterministic hook-reply approvals (docs/hook-reply-approvals.md): when the node is+ blocked on a Claude permission request whose managed hook is holding open (pendingId+ known), answer it in one click — no keystrokes into the prompt. Vanishes the moment the+ state leaves `blocked` (the store clears pendingId). */}+ {status?.state === 'blocked' && status?.pendingId && (+ <span className="term-node__approve nodrag">+ <button+ className="term-node__approve-btn term-node__approve-btn--allow"+ title="Approve this permission request"+ onClick={() =>+ void window.nodeTerminal.answerPermission({+ nodeId: id,+ pendingId: status.pendingId!,+ decision: 'allow'+ })+ }+ >+ ✓ Approve+ </button>+ <button+ className="term-node__approve-btn term-node__approve-btn--deny"+ title="Deny this permission request"+ onClick={() =>+ void window.nodeTerminal.answerPermission({+ nodeId: id,+ pendingId: status.pendingId!,+ decision: 'deny'+ })+ }+ >+ ✕ Deny+ </button>+ </span>+ )}{isUnread && (<spanclassName="term-node__status term-node__status--unread"diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 1d1de16d5..784e5c88d 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -45,6 +45,13 @@ export interface AgentNodeStatus {session?: string/** Claude session id (from hooks) — used to resume/branch the conversation. */sessionId?: string+ /**+ * Deterministic hook-reply approval ticket (docs/hook-reply-approvals.md). Set while the node is+ * `blocked` on a Claude permission request whose managed hook is holding open; the header's+ * Approve/Deny buttons answer it. TRANSIENT — never persisted, and cleared the moment the node+ * leaves `blocked` (so the buttons vanish once the decision lands). Absent = legacy prompt path.+ */+ pendingId?: string/** Set when running /loop, /schedule or /cron (heuristic); shown as a connected node. */loop?: {count: number@@ -63,8 +70,16 @@ export interface AgentStatusStore {/** The terminal node the user is currently focused in (for unread decisions). */activeId: string | nullsetActive(id: string, active: boolean): void- /** `newTurn` marks a genuine UserPromptSubmit — the only working that may follow a fresh done. */- setState(id: string, state: AgentState | undefined, agentId?: AgentId, newTurn?: boolean): void+ /** `newTurn` marks a genuine UserPromptSubmit — the only working that may follow a fresh done.+ * `pendingId` (deterministic approvals) is retained only while `state === 'blocked'`; any other+ * state clears it, so the header's Approve/Deny buttons disappear as soon as the node moves on. */+ setState(+ id: string,+ state: AgentState | undefined,+ agentId?: AgentId,+ newTurn?: boolean,+ pendingId?: string+ ): void/** Clear `working` entries whose last event is older than `staleMs` (lost-Stop safety net). */sweepStaleWorking(staleMs?: number): voidsetSession(id: string, session: string): void@@ -190,7 +205,7 @@ export function createAgentStatusSession(persistKey?: string): AgentStatusSessioreturn s.activeId === id ? { activeId: null } : s}),- setState: (id, state, agentId, newTurn) =>+ setState: (id, state, agentId, newTurn, pendingId) =>set((s) => {const prev = s.byId[id] ?? EMPTYconst now = Date.now()@@ -205,7 +220,16 @@ export function createAgentStatusSession(persistKey?: string): AgentStatusSessio) {return s}- if (prev.state === state && (agentId === undefined || prev.agentId === agentId)) {+ // A re-asserted `blocked` carrying a NEW pendingId (Claude re-asks) must break the fast+ // path so the header buttons retarget the new answer file — otherwise treat same-state as+ // a freshness-only refresh.+ const samePendingWhileBlocked =+ state !== 'blocked' || (pendingId ?? prev.pendingId) === prev.pendingId+ if (+ prev.state === state &&+ (agentId === undefined || prev.agentId === agentId) &&+ samePendingWhileBlocked+ ) {// Same-state event: refresh freshness in place — stateAt is never rendered, and a// new object here would re-render every node header on each tool event.if (s.byId[id]) s.byId[id].stateAt = now@@ -213,6 +237,8 @@ export function createAgentStatusSession(persistKey?: string): AgentStatusSessio}const next = { ...prev, state, stateAt: now }if (agentId !== undefined) next.agentId = agentId+ // Retain the approval ticket only while blocked; any other state clears it (transient).+ next.pendingId = state === 'blocked' ? (pendingId ?? prev.pendingId) : undefinedreturn { byId: { ...s.byId, [id]: next } }}),diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 301508eda..92c51aaa9 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1138,6 +1138,39 @@ body,color: var(--accent);}+/* Deterministic hook-reply approvals: compact Approve/Deny buttons beside the NEEDS YOU badge. */+.term-node__approve {+ display: inline-flex;+ gap: 4px;+ align-items: center;+}+.term-node__approve-btn {+ font-size: 10px;+ font-weight: 600;+ line-height: 1;+ padding: 3px 7px;+ border-radius: 6px;+ border: 1px solid transparent;+ cursor: pointer;+ white-space: nowrap;+}+.term-node__approve-btn--allow {+ color: #30d158;+ border-color: rgba(48, 209, 88, 0.5);+ background: rgba(48, 209, 88, 0.12);+}+.term-node__approve-btn--allow:hover {+ background: rgba(48, 209, 88, 0.22);+}+.term-node__approve-btn--deny {+ color: #ff453a;+ border-color: rgba(255, 69, 58, 0.5);+ background: rgba(255, 69, 58, 0.12);+}+.term-node__approve-btn--deny:hover {+ background: rgba(255, 69, 58, 0.22);+}+@keyframes nt-pulse {0%,100% {diff --git a/src/server/index.ts b/src/server/index.tsindex a2277520a..3814c2b33 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -14,7 +14,9 @@ import { WorkspaceStore } from '../core/workspace-store'import { PtyManager } from '../core/pty-manager'import { registerCoreHandlers } from './handlers'import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'+import os from 'os'import { hookServer } from '../core/agents/hook-server'+import { writePendingAnswerLocal, startPendingSweep, isValidPendingId } from '../core/agents/pending-approvals'import { installManagedAgentHooks } from '../core/agents/hooks'import {initAgentStatusMirror,@@ -188,6 +190,24 @@ export async function startServer(}})wireAgentStatus(platform)+ // Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the browser canvas answers a+ // held Claude permission hook here. The Server Edition runs ON the host, so a local project's+ // answer file is written right there (under os.homedir(), which the hook uses as $HOME). SSH+ // projects are v1-unsupported server-side (no ControlMaster manager here) → false, a documented+ // three-surfaces degrade. pendingId is validated before it becomes a path.+ platform.handle(+ IPC.agentAnswerPermission,+ async (payload: { nodeId: string; pendingId: string; decision: 'allow' | 'deny' }) => {+ const { nodeId, pendingId, decision } = payload ?? ({} as typeof payload)+ if (!isValidPendingId(pendingId)) return false+ if (decision !== 'allow' && decision !== 'deny') return false+ // An SSH-project node has no reachable ControlMaster here (v1): answer only local nodes.+ if (workspaceStore.sshProjectIdForNode(nodeId)) return false+ return writePendingAnswerLocal(pendingId, decision, os.homedir())+ }+ )+ // Sweep stale ~/.nodeterm/pending files on boot + hourly (orphans from killed sessions).+ startPendingSweep(os.homedir())// Desktop → paired-phone APNs push (spec: apns-push) is DELIBERATELY not wired here. The push// service (`src/core/push-notify.ts`) fans actionable inbox events out to a host's relay-PAIRED// phones, keyed by the standing relay host's identity (public key + hostDeviceId) and thediff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsindex 445e3d537..3e4e0acc1 100644--- a/src/shared/agents/normalize.test.ts+++ b/src/shared/agents/normalize.test.ts@@ -25,6 +25,26 @@ describe('normalizeClaude — turn-end signals', () => {})})+describe('normalizeClaude — PermissionRequest (deterministic approvals)', () => {+ it('PermissionRequest → blocked, threading the merged nodeterm_pending_id', () => {+ const e = normalizeClaude(+ env({+ hook_event_name: 'PermissionRequest',+ session_id: 's1',+ last_assistant_message: 'Approve write',+ nodeterm_pending_id: 'n1-1720-42'+ })+ )+ expect(e).toMatchObject({ kind: 'state', state: 'blocked', pendingId: 'n1-1720-42' })+ })++ it('omits pendingId when the hook did not arm the wait branch (legacy prompt path)', () => {+ const e = normalizeClaude(env({ hook_event_name: 'PermissionRequest', session_id: 's1' }))+ expect(e).toMatchObject({ kind: 'state', state: 'blocked' })+ expect(e && 'pendingId' in e).toBe(false)+ })+})+describe('normalizeClaude — async subagents', () => {it('PostToolUse for a sync subagent → subagent-end with stats', () => {const e = normalizeClaude(diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 9deb63eb2..3f56a8422 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -17,6 +17,11 @@ export interface NormalizedAgentEvent {newTurn?: booleansessionId?: stringlastMessage?: string+ // blocked (Claude PermissionRequest) only: the deterministic-approval ticket the managed hook+ // generated and is polling for an answer file. Rides from the raw POST body's+ // `nodeterm_pending_id` (merged into the payload by the hook server) so the phone/canvas can+ // answer the held hook. Absent = no held hook (legacy prompt path). See docs/hook-reply-approvals.md.+ pendingId?: string// sessionsessionTitle?: string// session lifecycle phase: 'start' resets to idle, 'end' resets + clears loop/fan-out@@ -51,6 +56,9 @@ const RECURRING_TOOLS = new Set(['Skill', 'CronCreate', 'ScheduleWakeup'])interface ClaudePayload {hook_event_name?: stringsession_id?: string+ /** Deterministic-approval ticket the managed hook script added to its POST body and the hook+ * server merged into this payload (PermissionRequest only). */+ nodeterm_pending_id?: stringnotification_type?: stringis_interrupt?: booleanlast_assistant_message?: string@@ -167,7 +175,14 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu}// The dedicated permission hook (more direct than Notification's permission_prompt).if (ev === 'PermissionRequest') {- return { ...base, kind: 'state', state: 'blocked', lastMessage: p.last_assistant_message }+ return {+ ...base,+ kind: 'state',+ state: 'blocked',+ lastMessage: p.last_assistant_message,+ // Deterministic-approval ticket (present only when the wait-branch of the managed hook ran).+ ...(p.nodeterm_pending_id ? { pendingId: p.nodeterm_pending_id } : {})+ }}if (ev === 'Notification') {// Only the types that genuinely need the user flip the state. Everything else —diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 81a2bb974..7b583c61a 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -35,6 +35,10 @@ export const IPC = {appFocusNode: 'app:focus-node',appSetBadge: 'app:set-badge',agentStatus: 'agent:status',+ /** Renderer → main/server: answer a held Claude permission hook (deterministic approvals).+ * Payload: `{ nodeId, pendingId, decision: 'allow'|'deny' }`; resolves boolean. See+ * docs/hook-reply-approvals.md. */+ agentAnswerPermission: 'agent:answer-permission',agentSubagentActivity: 'agent:subagent-activity',agentControl: 'agent:control',agentControlResult: 'agent:control-result',