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): only the pane's foreground claude speaks for a node (#1112, #1153) (#1236)
eneskirca26e34cb3cdf7
diff --git a/CLAUDE.md b/CLAUDE.mdindex b453ff670..b2fd7ff8f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3406,6 +3406,36 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile`questions` (a held AskUserQuestion's exact question texts, from the one `readQuestions`) is whatthe ⌘M answer controls match their card by — absent = unreadable input = no controls. Desktop local + SSH, Server Edition local;relay unchanged; phone keeps `allow`/`deny` (its plan approve now works via the script mapping).+- **A hook event's node id is INHERITED, so only the pane's foreground claude speaks for a node**+ (issues #1112, #1153; `core/agents/claude-pane-origin.ts`). `NODETERM_NODE_ID` (and the per-node+ token, looked up by that id) reaches every process the node's claude starts: a background script's+ `claude -p` took over the node's session id, model, meter and context-link transcript (#1112), and+ Claude's daemon (`claude daemon run` → `--bg-pty-host` → the `--fork-session` claude) posted a+ fork's hooks as the node that spawned it, so `/rename` retitled the wrong node (#1153). The rule is+ keyed on the PROCESS, not the session: the managed claude script runs one+ `ps -o stat= -o tty= -p $CLAUDE_PID` WHILE claude waits on the hook and posts+ `nodeterm_claude_{pid,fg,tty}`; the hook server sends every claude event through a per-node+ ordered gate BEFORE either listener, and drops it when the claude is not in the foreground group+ of any terminal, or is foreground on a tty that is not the node's pane tty (`PtyManager.paneOwner`,+ wired in BOTH shells by `wireClaudePaneOrigin`, cached 5 min, re-read on disagreement at most every+ 10 s, forgotten on destroy/recycle). MEASURED on Claude Code 2.1.301 in a private tmux server:+ `CLAUDE_PID` is in every hook's env (and in the binary from at least 2.1.220, absent from 2.1.200);+ the pane's interactive claude has `+` on the pane tty; a `claude -p` run from claude's Bash tool+ (a setsid'd shell) has tty `?`; a `&` job of the pane shell has no `+`. Every legitimate change —+ `/clear`, `/resume`, `/compact`, Branch, cold-restore resume, in-place restart, a new `claude`+ after the old one quit — happens in the pane's foreground and needs no rule of its own; a claude+ that died without `SessionEnd` blocks nothing (there is no binding to release). Rejected:+ session-source allowlists (a detached `claude -p --resume` also says `resume`; a missing+ `SessionEnd` locks the next session out — both found in the #1112 prototype) and "first session+ wins until its pid dies" (needs a remote liveness probe, and a daemon fork outliving its spawner+ would take the node over). **Fails OPEN** wherever a fact is missing — no `CLAUDE_PID` (older+ claude), Git Bash / BusyBox `ps`, a pane tty this core cannot read (Zellij, plain-shell fallback,+ an SSH node with no live client here), a probe over 2 s — because dropping the pane's OWN events+ strands a node on RUNNING. The script also never arms the approval wait for a non-foreground+ claude. Known residuals: a claude wrapped in its own pty inside the pane (`script`, `unbuffer`) is+ foreground on that pty and reads as foreign; a node whose TUI attaches to a daemon-hosted session+ gets no hook events at all (they were never posted under its id). Mobile: N/A (the mirror simply+ stops receiving foreign events).- **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 proves"a session on this machine", never *which* session, so every node also gets a capability deriveddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8dd19c98b..dc549d160 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -321,6 +321,14 @@ anything else. Board-level fields survive every transform — `pullLinks` is onemust pass `isBoundedAnswerContent` or it is silently ignored. Answer content never goes on an argv.See `docs/hook-reply-approvals.md`.+- **`NODETERM_NODE_ID` is inherited, so a hook event's node id is not proof it is that node's+ session.** A detached `claude -p` started from a node, or Claude's own daemon hosting a fork,+ posts hooks under the node's id (and its token). Claude events pass `core/agents/claude-pane-origin.ts`+ in the hook server before ANY listener: the managed script reports `$CLAUDE_PID`'s foreground+ flag and tty, and only the pane's foreground claude speaks for the node. Do not add a listener+ that runs before that gate, and do not "fix" a stuck node by loosening it: missing facts already+ fail open. Both shells call `wireClaudePaneOrigin` (pinned by `hook-verified-parity.test.ts`).+- **Never call the user's machine a Mac in user-visible copy.** Use `thisMachine()` /`thisMachineCap()` / `machineNoun()` from `src/renderer/lib/machineName.ts` — "this Mac" onmacOS, "this PC" on Windows, "this computer" elsewhere and in any Server Edition browser tabdiff --git a/src/core/agents/claude-pane-origin.test.ts b/src/core/agents/claude-pane-origin.test.tsnew file mode 100644index 000000000..74568e67b--- /dev/null+++ b/src/core/agents/claude-pane-origin.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it, vi } from 'vitest'+import {+ classifyClaudeOrigin,+ createPaneOriginGate,+ normalizeTty,+ parseClaudeHookOrigin,+ PANE_TTY_RECHECK_MS,+ PANE_TTY_TTL_MS,+ wireClaudePaneOrigin+} from './claude-pane-origin'++describe('parseClaudeHookOrigin', () => {+ it('reads the three fields the claude script posts', () => {+ expect(parseClaudeHookOrigin({ nodeterm_claude_pid: '42', nodeterm_claude_fg: '1', nodeterm_claude_tty: 'pts/3' }))+ .toEqual({ pid: 42, foreground: true, tty: 'pts/3' })+ expect(parseClaudeHookOrigin({ nodeterm_claude_pid: '42', nodeterm_claude_fg: '0', nodeterm_claude_tty: '' }))+ .toEqual({ pid: 42, foreground: false })+ })+ it('no (or a malformed) fg field is no origin at all: an older script, a ps that could not answer', () => {+ expect(parseClaudeHookOrigin({})).toBeUndefined()+ expect(parseClaudeHookOrigin({ nodeterm_claude_fg: '' })).toBeUndefined()+ expect(parseClaudeHookOrigin({ nodeterm_claude_fg: 'yes' })).toBeUndefined()+ })+ it('drops a hostile pid or tty rather than carrying it', () => {+ expect(parseClaudeHookOrigin({ nodeterm_claude_pid: '1;id', nodeterm_claude_fg: '1', nodeterm_claude_tty: '../../x' }))+ .toEqual({ foreground: true })+ })+})++describe('classifyClaudeOrigin', () => {+ it('the pane\'s own foreground claude is the node\'s', () => {+ expect(classifyClaudeOrigin({ foreground: true, tty: 'pts/3' }, '/dev/pts/3')).toBe('own')+ expect(classifyClaudeOrigin({ foreground: true, tty: 'ttys003' }, '/dev/ttys003')).toBe('own')+ })+ it('#1112: a claude that is not the foreground of any terminal is not', () => {+ expect(classifyClaudeOrigin({ foreground: false }, '/dev/pts/3')).toBe('foreign')+ expect(classifyClaudeOrigin({ foreground: false }, null)).toBe('foreign')+ })+ it('#1153: a claude in the foreground of ANOTHER terminal (Claude\'s daemon pty) is not', () => {+ expect(classifyClaudeOrigin({ foreground: true, tty: 'pts/9' }, '/dev/pts/3')).toBe('foreign')+ })+ it('anything this core cannot judge is unknown, never foreign', () => {+ expect(classifyClaudeOrigin(undefined, '/dev/pts/3')).toBe('unknown')+ expect(classifyClaudeOrigin({ foreground: true }, '/dev/pts/3')).toBe('unknown')+ expect(classifyClaudeOrigin({ foreground: true, tty: 'pts/3' }, null)).toBe('unknown')+ })+ it('normalizeTty', () => {+ expect(normalizeTty('/dev/pts/3')).toBe('pts/3')+ expect(normalizeTty('?')).toBeNull()+ expect(normalizeTty('')).toBeNull()+ })+})++describe('createPaneOriginGate', () => {+ it('admits own, drops foreign, admits unknown — and reads the pane tty once while it agrees', async () => {+ const paneTty = vi.fn(async () => '/dev/pts/3')+ const gate = createPaneOriginGate({ paneTty, log: () => {} })+ expect(await gate.admit('n', { foreground: true, tty: 'pts/3', pid: 1 })).toBe(true)+ expect(await gate.admit('n', { foreground: true, tty: 'pts/3', pid: 1 })).toBe(true)+ expect(paneTty).toHaveBeenCalledTimes(1)+ expect(await gate.admit('n', { foreground: false, pid: 2 })).toBe(false)+ expect(await gate.admit('n', undefined)).toBe(true)+ expect(paneTty).toHaveBeenCalledTimes(1)+ })++ it('without a resolver only the no-terminal half applies', async () => {+ const gate = createPaneOriginGate({ log: () => {} })+ expect(await gate.admit('n', { foreground: false })).toBe(false)+ expect(await gate.admit('n', { foreground: true, tty: 'pts/9' })).toBe(true)+ })++ it('a disagreeing tty is re-read before it is called foreign, so a recreated pane never locks its own claude out', async () => {+ let t = 0+ let tty = '/dev/pts/3'+ const paneTty = vi.fn(async () => tty)+ const gate = createPaneOriginGate({ paneTty, now: () => t, log: () => {} })+ expect(await gate.admit('n', { foreground: true, tty: 'pts/3' })).toBe(true)+ // The pane is recreated under a new tty; past the recheck window the new tty is read.+ tty = '/dev/pts/7'+ t += PANE_TTY_RECHECK_MS+ expect(await gate.admit('n', { foreground: true, tty: 'pts/7' })).toBe(true)+ expect(paneTty).toHaveBeenCalledTimes(2)+ })++ it('a foreign process posting steadily costs one pane read per recheck window, not one per event', async () => {+ let t = 0+ const paneTty = vi.fn(async () => '/dev/pts/3')+ const gate = createPaneOriginGate({ paneTty, now: () => t, log: () => {} })+ await gate.admit('n', { foreground: true, tty: 'pts/3' })+ for (let i = 0; i < 5; i++) expect(await gate.admit('n', { foreground: true, tty: 'pts/9' })).toBe(false)+ expect(paneTty).toHaveBeenCalledTimes(1)+ t += PANE_TTY_TTL_MS+ expect(await gate.admit('n', { foreground: true, tty: 'pts/9' })).toBe(false)+ expect(paneTty).toHaveBeenCalledTimes(2)+ })++ it('forgetNode drops the cached tty (a recycle/destroy hands the node a new pane)', async () => {+ let tty = '/dev/pts/3'+ const paneTty = vi.fn(async () => tty)+ const gate = createPaneOriginGate({ paneTty, log: () => {} })+ await gate.admit('n', { foreground: true, tty: 'pts/3' })+ tty = '/dev/pts/7'+ gate.forgetNode('n')+ expect(await gate.admit('n', { foreground: true, tty: 'pts/7' })).toBe(true)+ })++ it('a pane that cannot be read is unknown (admitted) and is not re-read on every event', async () => {+ const paneTty = vi.fn(async () => null)+ const gate = createPaneOriginGate({ paneTty, log: () => {} })+ expect(await gate.admit('n', { foreground: true, tty: 'pts/9' })).toBe(true)+ expect(await gate.admit('n', { foreground: true, tty: 'pts/9' })).toBe(true)+ expect(paneTty).toHaveBeenCalledTimes(1)+ })++ it('a resolver that throws or hangs is unknown, never foreign', async () => {+ vi.useFakeTimers()+ try {+ const gate = createPaneOriginGate({ paneTty: () => new Promise(() => {}), log: () => {} })+ const p = gate.admit('n', { foreground: true, tty: 'pts/9' })+ await vi.advanceTimersByTimeAsync(2_500)+ expect(await p).toBe(true)+ } finally {+ vi.useRealTimers()+ }+ const gate2 = createPaneOriginGate({ paneTty: async () => { throw new Error('x') }, log: () => {} })+ expect(await gate2.admit('n', { foreground: true, tty: 'pts/9' })).toBe(true)+ })++ it('keeps each node\'s events in arrival order while a pane read is pending', async () => {+ let release: (v: string) => void = () => {}+ const paneTty = vi.fn(() => new Promise<string>((r) => { release = r }))+ const gate = createPaneOriginGate({ paneTty, log: () => {} })+ const order: string[] = []+ const a = gate.admit('n', { foreground: true, tty: 'pts/3' }).then((ok) => order.push(`a:${ok}`))+ const b = gate.admit('n', undefined).then((ok) => order.push(`b:${ok}`))+ const other = gate.admit('m', undefined).then((ok) => order.push(`m:${ok}`))+ await other+ expect(order).toEqual(['m:true'])+ release('/dev/pts/3')+ await Promise.all([a, b])+ expect(order).toEqual(['m:true', 'a:true', 'b:true'])+ })+})++describe('wireClaudePaneOrigin', () => {+ it('reads the pane tty from paneOwner, and never for a node it cannot read honestly', async () => {+ let resolver: ((id: string) => Promise<string | null>) | undefined+ const forgotten: string[] = []+ const handlers = new Map<string, (id: string) => void>()+ const paneOwner = vi.fn(async () => ({ tty: '/dev/pts/3' }))+ wireClaudePaneOrigin({+ hooks: { setPaneTtyResolver: (fn) => { resolver = fn }, forgetPaneOrigin: (id) => forgotten.push(id) },+ paneOwner,+ // An SSH-project node with no live client: paneOwner would read the LOCAL socket.+ cannotRead: (id) => id === 'remote-idle',+ on: (ch, cb) => handlers.set(ch, cb),+ destroyChannel: 'destroy',+ recycleChannel: 'recycle'+ })+ expect(await resolver!('local')).toBe('/dev/pts/3')+ expect(await resolver!('remote-idle')).toBeNull()+ expect(paneOwner).toHaveBeenCalledTimes(1)+ handlers.get('destroy')!('a')+ handlers.get('recycle')!('b')+ expect(forgotten).toEqual(['a', 'b'])+ })+})diff --git a/src/core/agents/claude-pane-origin.ts b/src/core/agents/claude-pane-origin.tsnew file mode 100644index 000000000..0f4ed4aa5--- /dev/null+++ b/src/core/agents/claude-pane-origin.ts@@ -0,0 +1,246 @@+/**+ * WHICH CLAUDE IS ALLOWED TO SPEAK FOR A NODE (issues #1112, #1153).+ *+ * A hook event names its node by `NODETERM_NODE_ID`, and that is an ENVIRONMENT variable: every+ * process the node's claude starts inherits it. Two field reports, one mechanism:+ *+ * - #1112: a background script started from a node ran `claude --model … -p …` every so often.+ * Each run fired the managed hooks as that node, so its session took over the node's session+ * id, model and context meter (and, through `setNodeTranscript`, what a context link reads).+ * - #1153: a Claude fork is hosted by Claude's own daemon (`claude daemon run` →+ * `claude --bg-pty-host` → `claude --session-id <fork> --fork-session …`), spawned by node A's+ * claude and carrying A's env. Every hook of the fork was posted as A, so `/rename` in the node+ * that resumed the fork renamed A.+ *+ * Nothing on the nodeterm side could tell those events from the node's own: the session id is+ * new, the node token is looked up by the same inherited id (so the events even verify), and a+ * new session id on an ordinary event is also what a legitimate `/clear` or a cold-restore resume+ * looks like. Rules keyed on the SESSION (bind to the first one, switch only on `SessionStart`+ * with source clear/resume/compact) fail both ways — a detached `claude -p --resume` sends+ * `source: resume`, and a claude that died without `SessionEnd` locks the next one out+ * (both found in the contributor's prototype on #1112).+ *+ * The rule here is keyed on the PROCESS, and on the one fact about it the kernel keeps: is it the+ * foreground process group of the node's pane? MEASURED on Claude Code 2.1.301 (2026-10-16,+ * Linux, private tmux socket, capture hook via --settings; the hook's own env lists `CLAUDE_PID`):+ *+ * interactive claude in the pane: CLAUDE_PID's stat has `+`, tty = the pane's pts+ * `claude -p` run from claude's Bash tool (setsid'd tool shell): tty `?`, no `+`+ * a `cmd &` job of the pane's shell: same tty, no `+` (not the foreground group)+ *+ * and, by construction, the daemon-hosted fork of #1153 is foreground on the bg-pty-host's OWN+ * pty, never on the pane's. `CLAUDE_PID` is in the claude binary from at least 2.1.220 (it is+ * absent from 2.1.200; npm `@anthropic-ai/claude-code-linux-x64` checked). The managed claude+ * script (managed-script.ts) reads `ps -o stat= -o tty= -p $CLAUDE_PID` WHILE claude waits on the+ * hook — so the process is alive for the read even on `SessionEnd` — and posts the two facts.+ *+ * Every legitimate session change in a node happens in the pane's foreground: `/clear`,+ * `/resume`, `/compact` (same process), Branch (the source keeps its pane; the branch resumes in+ * its own node), cold-restore resume, the in-place restart, a new `claude` typed after the old one+ * quit. None of them needs a rule of its own, and a claude that dies without `SessionEnd` blocks+ * nothing — there is no binding to release.+ *+ * Fail OPEN wherever a fact is missing: an older script or claude (no pid), a `ps` that cannot+ * answer (Windows / Git Bash, BusyBox), a pane whose tty this core cannot read (Zellij, plain-shell+ * fallback, an SSH node with no live client here). Those events behave exactly as before — the+ * cost of wrongly dropping the pane's OWN events (a node stuck on RUNNING, a meter that never+ * fills) is worse than the bug this closes.+ */++/** What the managed claude hook script reports about the claude process that ran it. */+export interface ClaudeHookOrigin {+ pid?: number+ /** `true`: in the foreground process group of its terminal; `false`: not (or no terminal). */+ foreground?: boolean+ /** The controlling terminal, `ps`'s spelling (`pts/3`, `ttys003`). Absent when there is none. */+ tty?: string+}++export type ClaudeOriginVerdict = 'own' | 'foreign' | 'unknown'++/** Strip a leading `/dev/` so tmux's `#{pane_tty}` and `ps -o tty=` compare as one spelling. */+export function normalizeTty(tty: string | null | undefined): string | null {+ if (!tty) return null+ const t = tty.trim().replace(/^\/dev\//, '')+ if (!t || t.length > 64 || !/^[A-Za-z0-9][A-Za-z0-9/._-]*$/.test(t) || t.includes('..')) return null+ return t+}++/**+ * Read the origin out of the hook POST's form fields. Anything malformed is simply absent — the+ * fields are written by a script, but the endpoint takes any bearer holder's POST, so they are+ * parsed, never trusted beyond what `classifyClaudeOrigin` does with them.+ */+export function parseClaudeHookOrigin(form: Record<string, string | undefined>): ClaudeHookOrigin | undefined {+ const fg = form.nodeterm_claude_fg+ const foreground = fg === '1' ? true : fg === '0' ? false : undefined+ if (foreground === undefined) return undefined+ const rawPid = form.nodeterm_claude_pid+ const pid = rawPid && /^\d{1,10}$/.test(rawPid) ? Number(rawPid) : undefined+ const tty = normalizeTty(form.nodeterm_claude_tty) ?? undefined+ return {+ foreground,+ ...(pid !== undefined && pid > 0 ? { pid } : {}),+ ...(tty ? { tty } : {})+ }+}++/**+ * The decision, pure. `paneTty` is the node's pane tty as this core reads it (`null` = could not+ * read it). Only two answers are ever `foreign`: the reporting claude is not in the foreground of+ * any terminal, or it is in the foreground of a terminal that is not the node's pane.+ */+export function classifyClaudeOrigin(+ origin: ClaudeHookOrigin | undefined,+ paneTty: string | null | undefined+): ClaudeOriginVerdict {+ if (!origin || origin.foreground === undefined) return 'unknown'+ if (origin.foreground === false) return 'foreign'+ const own = normalizeTty(origin.tty)+ const pane = normalizeTty(paneTty)+ if (!own || !pane) return 'unknown'+ return own === pane ? 'own' : 'foreign'+}++/** How long a pane tty read is trusted. A tty only changes when the node's session is recreated,+ * and a mismatch re-reads anyway; the TTL bounds the one case a re-read cannot catch (a recycled+ * pane whose OLD tty number was handed to some other terminal). */+export const PANE_TTY_TTL_MS = 5 * 60_000+/** A failed read is retried, but not on every event (a Zellij node answers null every time). */+export const PANE_TTY_MISS_TTL_MS = 30_000+/** A tty that DISAGREES with the cached one is re-read at most this often, so a foreign process+ * posting steadily (the #1153 fork) costs one pane read per window, not one per event. */+export const PANE_TTY_RECHECK_MS = 10_000+/** The probe has no deadline of its own (PtyManager.paneOwner); events wait at most this long. */+export const PANE_TTY_PROBE_MS = 2_000++export interface PaneOriginGateDeps {+ /** The node's pane tty, or null when it cannot be read. Injected by each shell. */+ paneTty?: (nodeId: string) => Promise<string | null>+ now?: () => number+ log?: (line: string) => void+}++export interface PaneOriginGate {+ /**+ * Should this event be delivered as the node's? Resolves in arrival order PER NODE, so an event+ * that waits for a tty read never overtakes or is overtaken by the node's next one.+ */+ admit(nodeId: string, origin: ClaudeHookOrigin | undefined): Promise<boolean>+ setPaneTtyResolver(fn: ((nodeId: string) => Promise<string | null>) | undefined): void+ forgetNode(nodeId: string): void+}++export function createPaneOriginGate(deps: PaneOriginGateDeps = {}): PaneOriginGate {+ let resolver = deps.paneTty+ const now = deps.now ?? Date.now+ const log = deps.log ?? ((line: string) => console.warn(line))+ const cache = new Map<string, { tty: string | null; at: number }>()+ const chains = new Map<string, Promise<unknown>>()+ const logged = new Set<string>()++ const probe = async (nodeId: string): Promise<string | null> => {+ const fn = resolver+ if (!fn) return null+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ const tty = await Promise.race([+ fn(nodeId).catch(() => null),+ new Promise<null>((r) => {+ timer = setTimeout(() => r(null), PANE_TTY_PROBE_MS)+ ;(timer as { unref?: () => void }).unref?.()+ })+ ])+ const t = normalizeTty(tty)+ cache.set(nodeId, { tty: t, at: now() })+ return t+ } finally {+ if (timer) clearTimeout(timer)+ }+ }++ const paneTty = async (nodeId: string, reported: string | null): Promise<string | null> => {+ const hit = cache.get(nodeId)+ const age = hit ? now() - hit.at : Infinity+ if (hit && hit.tty === null && age < PANE_TTY_MISS_TTL_MS) return null+ // A cached tty is used only while it AGREES; a disagreement is re-read before anything is+ // called foreign, so a pane recreated under a new tty can never lock its own claude out.+ if (hit && hit.tty !== null && age < PANE_TTY_TTL_MS) {+ if (hit.tty === reported || age < PANE_TTY_RECHECK_MS) return hit.tty+ }+ return probe(nodeId)+ }++ const decide = async (nodeId: string, origin: ClaudeHookOrigin | undefined): Promise<boolean> => {+ let verdict: ClaudeOriginVerdict+ if (!origin || origin.foreground !== true) verdict = classifyClaudeOrigin(origin, null)+ else {+ const reported = normalizeTty(origin.tty)+ verdict = reported ? classifyClaudeOrigin(origin, await paneTty(nodeId, reported)) : 'unknown'+ }+ if (verdict !== 'foreign') return true+ const key = `${nodeId}\u0000${origin?.pid ?? '?'}`+ if (!logged.has(key)) {+ if (logged.size > 1000) logged.clear()+ logged.add(key)+ log(+ `[agent-hooks] ignoring claude hook events for node ${nodeId} from pid ${origin?.pid ?? '?'}: ` ++ `${origin?.foreground ? `foreground on ${origin.tty}, not the node's pane` : 'not the foreground of a terminal'} ` ++ '(a process that inherited NODETERM_NODE_ID; issue #1112)'+ )+ }+ return false+ }++ return {+ admit(nodeId, origin) {+ const prev = chains.get(nodeId) ?? Promise.resolve()+ const next = prev.then(() => decide(nodeId, origin))+ const tail = next.catch(() => true)+ chains.set(nodeId, tail)+ void tail.then(() => {+ if (chains.get(nodeId) === tail) chains.delete(nodeId)+ })+ return next.catch(() => true)+ },+ setPaneTtyResolver(fn) {+ resolver = fn+ cache.clear()+ },+ forgetNode(nodeId) {+ cache.delete(nodeId)+ }+ }+}++/**+ * The ONE wiring both shells call (desktop `src/main/index.ts`, Server Edition+ * `src/server/index.ts`; pinned by hook-verified-parity.test.ts): the pane tty comes from the+ * shell's own PtyManager (`paneOwner` — local tmux, the SSH ControlMaster for a live remote node,+ * the Windows session host), and a destroyed or recycled node forgets it (its next pane has a new+ * tty). A shell that skipped this would still drop a claude with no terminal, but would deliver a+ * daemon-hosted fork's events (#1153) as the node's.+ */+export function wireClaudePaneOrigin(deps: {+ hooks: {+ setPaneTtyResolver(fn: ((nodeId: string) => Promise<string | null>) | undefined): void+ forgetPaneOrigin(nodeId: string): void+ }+ paneOwner: (nodeId: string) => Promise<{ tty?: string } | null>+ /**+ * A node whose pane this core cannot read HONESTLY: an SSH-project node with no live client in+ * this process. `paneOwner` would fall through to the LOCAL tmux socket for it, and a stray local+ * `nt-<id>` (CLAUDE.md, the relay attach section) would answer with a tty from the wrong machine+ * — every event of the real remote claude would then read as foreign. Such a node is "unknown".+ */+ cannotRead?: (nodeId: string) => boolean+ on: (channel: string, cb: (nodeId: string) => void) => void+ destroyChannel: string+ recycleChannel: string+}): void {+ deps.hooks.setPaneTtyResolver(async (nodeId) =>+ deps.cannotRead?.(nodeId) ? null : ((await deps.paneOwner(nodeId))?.tty ?? null)+ )+ deps.on(deps.destroyChannel, (nodeId) => deps.hooks.forgetPaneOrigin(nodeId))+ deps.on(deps.recycleChannel, (nodeId) => deps.hooks.forgetPaneOrigin(nodeId))+}diff --git a/src/core/agents/hook-server.claude-origin.test.ts b/src/core/agents/hook-server.claude-origin.test.tsnew file mode 100644index 000000000..d7bda0664--- /dev/null+++ b/src/core/agents/hook-server.claude-origin.test.ts@@ -0,0 +1,107 @@+// The /hook route drops a claude event that came from a process which merely INHERITED the node's+// id (issues #1112, #1153) — before EITHER listener sees it, because the raw listener rebinds the+// node's session/meter/context-link transcript and the normalized one the mirror's session id,+// title and badge. The rule itself is claude-pane-origin.ts; this pins the wiring.+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { hookServer } from './hook-server'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { testTmpDir } from '../test-tmp'+import type { NormalizedAgentEvent } from '@shared/agents/normalize'++let events: NormalizedAgentEvent[] = []+let raws: { agent: string; payload: Record<string, unknown> }[] = []+let paneTty: string | null = '/dev/pts/3'++function post(agent: string, fields: Record<string, string>): Promise<Response> {+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/${agent}`, {+ method: 'POST',+ headers: {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'content-type': 'application/x-www-form-urlencoded'+ },+ body: new URLSearchParams(fields).toString()+ })+}++const start = (sessionId: string) => JSON.stringify({+ hook_event_name: 'SessionStart',+ source: 'startup',+ session_id: sessionId,+ model: 'claude-haiku-4-5'+})++beforeAll(async () => {+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: testTmpDir('hooksrv-origin-') }))+ await hookServer.start()+ hookServer.setListener((e) => { events.push(e) })+ hookServer.setRawListener((agent, _node, payload) => { raws.push({ agent, payload }) })+ hookServer.setPaneTtyResolver(async () => paneTty)+})++afterAll(() => {+ hookServer.setPaneTtyResolver(undefined)+ hookServer.stop()+})++beforeEach(() => {+ events = []+ raws = []+ paneTty = '/dev/pts/3'+ hookServer.forgetPaneOrigin('term-a')+})++describe('claude hook events from a process that inherited the node id', () => {+ it('#1112: a claude with no controlling terminal (a detached `claude -p`) reaches no listener', async () => {+ const res = await post('claude', {+ nodeId: 'term-a', nodeterm_claude_pid: '777', nodeterm_claude_fg: '0', nodeterm_claude_tty: '',+ payload: start('foreign-session')+ })+ expect(res.status).toBe(204)+ expect(raws).toHaveLength(0)+ expect(events).toHaveLength(0)+ })++ it('#1153: a claude in the foreground of ANOTHER terminal (Claude\'s daemon-hosted fork) reaches no listener', async () => {+ await post('claude', {+ nodeId: 'term-a', nodeterm_claude_pid: '778', nodeterm_claude_fg: '1', nodeterm_claude_tty: 'pts/9',+ payload: start('fork-session')+ })+ expect(raws).toHaveLength(0)+ expect(events).toHaveLength(0)+ })++ it('the pane\'s own foreground claude is delivered, a new session id included (/clear, resume, restart)', async () => {+ await post('claude', {+ nodeId: 'term-a', nodeterm_claude_pid: '100', nodeterm_claude_fg: '1', nodeterm_claude_tty: 'pts/3',+ payload: start('own-session')+ })+ expect(raws).toHaveLength(1)+ expect(events).toHaveLength(1)+ expect(events[0].sessionId).toBe('own-session')+ })++ it('an event with no origin (older script or claude, Windows) behaves exactly as before', async () => {+ await post('claude', { nodeId: 'term-a', payload: start('legacy-session') })+ expect(raws).toHaveLength(1)+ expect(events).toHaveLength(1)+ })++ it('a pane this core cannot read (Zellij, no live client) is unknown and delivered', async () => {+ paneTty = null+ await post('claude', {+ nodeId: 'term-a', nodeterm_claude_pid: '100', nodeterm_claude_fg: '1', nodeterm_claude_tty: 'pts/9',+ payload: start('unknown-session')+ })+ expect(events).toHaveLength(1)+ })++ it('other agents are not gated by claude fields', async () => {+ await post('codex', {+ nodeId: 'term-a', nodeterm_claude_fg: '0',+ payload: JSON.stringify({ hook_event_name: 'SessionStart', session_id: 'c1' })+ })+ expect(raws).toHaveLength(1)+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex ff6968368..79a9fcdd7 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -60,6 +60,7 @@ import {type PersistedLedgerRow} from '../control-request-ledger'import { DurableFactFile } from '../durable-state'+import { createPaneOriginGate, parseClaudeHookOrigin, type PaneOriginGate } from './claude-pane-origin'// v2 advertises NODETERM_NODE_TOKEN_DIR so clients read their per-node capability from a file// rather than receiving it in argv. Nothing consumes the posted version server-side, so the bump@@ -550,6 +551,24 @@ export class HookServer {return this.codexPermissionGate}+ /**+ * Which claude may speak for a node (issues #1112, #1153 — claude-pane-origin.ts). Created+ * eagerly: the "not the foreground of any terminal" half needs no shell at all, so a shell that+ * never wires a resolver still drops a detached `claude -p`. The pane-tty half needs+ * `setPaneTtyResolver`, which BOTH shells call (hook-verified-parity.test.ts pins it).+ */+ private readonly paneOrigin: PaneOriginGate = createPaneOriginGate()++ /** The node's pane tty, read by each shell from its own PtyManager (`paneOwner(...).tty`). */+ setPaneTtyResolver(fn: ((nodeId: string) => Promise<string | null>) | undefined): void {+ this.paneOrigin.setPaneTtyResolver(fn)+ }++ /** Drop the cached pane tty of a node whose session ended or was recycled (new pane, new tty). */+ forgetPaneOrigin(nodeId: string): void {+ this.paneOrigin.forgetNode(nodeId)+ }+// Raw payload listener: receives the parsed (un-normalized) hook JSON. Drives the// contextTail/subagentTail features, which need transcript_path (not in NormalizedAgentEvent).// `meta` carries what the transport knows about the caller (see HookEventMeta).@@ -1114,6 +1133,18 @@ export class HookServer {if (form.nodeterm_hook_event) payload.nodeterm_hook_event = form.nodeterm_hook_eventelse delete payload.nodeterm_hook_event}+ // A claude event from a process that merely INHERITED this node's id — a detached+ // `claude -p`, Claude's own daemon hosting a fork — is not the node's, and must reach+ // NEITHER listener: the raw one rebinds the node's session, meter and context-link+ // transcript, the normalized one the mirror's session id, title and badge (#1112,+ // #1153). Decided per node in arrival order; see claude-pane-origin.ts for the rule and+ // the measurement behind it. Every claude event goes through the gate, with or without+ // an origin, so an event waiting for a pane read is never overtaken by the next one.+ if (agentId === 'claude' && !(await this.paneOrigin.admit(nodeId, parseClaudeHookOrigin(form)))) {+ res.writeHead(204)+ res.end()+ return+ }// 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, {diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.tsindex fc1a53480..bbe99ea1c 100644--- a/src/core/agents/hook-verified-parity.test.ts+++ b/src/core/agents/hook-verified-parity.test.ts@@ -303,6 +303,19 @@ describe('both shells register a 4-arg raw listener', () => {})+describe('which claude may speak for a node (#1112, #1153)', () => {+ const root = resolve(__dirname, '../../..')+ // Both shell ENTRYPOINTS wire the pane-tty half of the origin gate (claude-pane-origin.ts). A+ // shell that forgets it compiles, passes every unit test and still drops a detached `claude -p`+ // — but delivers a daemon-hosted fork's events as the node's, which is #1153 in that shell only.+ for (const rel of ['src/main/index.ts', 'src/server/index.ts']) {+ it(`${rel} wires the pane tty from its own PtyManager`, () => {+ const src = readFileSync(join(root, rel), 'utf8').replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '')+ expect(src).toMatch(/wireClaudePaneOrigin\(\{[\s\S]*?hooks:\s*hookServer[\s\S]*?ptyManager\.paneOwner\(/)+ })+ }+})+describe('session window metadata', () => {it('accepts validated configuration only from this node identity', async () => {await post(NODE, nodeAuthToken(SECRET, NODE), '1048576')diff --git a/src/core/agents/hooks/antigravity-script.test.ts b/src/core/agents/hooks/antigravity-script.test.tsindex 127e3b420..5c874672c 100644--- a/src/core/agents/hooks/antigravity-script.test.ts+++ b/src/core/agents/hooks/antigravity-script.test.ts@@ -192,9 +192,12 @@ describe('the managed script for antigravity', () => {// IDENTITY-ROOT variant (the second hash of each pair) moved — codex's most, since it reads its// payload first. The no-root (remote) variants did not.const expected: Record<string, [string, string]> = {+ // claude changed DELIBERATELY (issues #1112/#1153): it now reports which process ran the+ // hook (`$CLAUDE_PID`, foreground, tty — claude-pane-origin.ts). Recomputed from this+ // branch's builder; the other five are untouched, which is what this test still proves.claude: [- '0c160e0081608c44e327bb22f394aa51e17e852bc277523d0edee9c6d867711d',- '57fb9ccb0731a2baa5042741309c7bd52cc559db45738d0742d651fda668e2a5'+ '0e3e1e0d89e7b3ca269effe57067047f9321897c79bf53a3edeadf2bb30ca992',+ '84a8fc82dede3cf252138376b209e6469a22bfdc9b72f953eb35cb94ccd4fbe3'],codex: ['592fe88ee069db002c9f5c385a2e0465f9659bade3f0bd18c86b5b51f7644e59',diff --git a/src/core/agents/hooks/managed-script.claude-origin.test.ts b/src/core/agents/hooks/managed-script.claude-origin.test.tsnew file mode 100644index 000000000..f08965c93--- /dev/null+++ b/src/core/agents/hooks/managed-script.claude-origin.test.ts@@ -0,0 +1,142 @@+// The claude hook script's ORIGIN report (issues #1112, #1153; rule in claude-pane-origin.ts),+// executed for real: the generated script runs under `/bin/sh` inside a pane of a PRIVATE tmux+// server, reads the real `ps` about `$CLAUDE_PID`, and posts to a fake curl that records its argv.+// The three cases are the three shapes measured on Claude Code 2.1.301: the pane's own foreground+// process, a job of the pane's shell that is NOT the foreground group, and a process with no+// controlling terminal at all (what claude's Bash tool and Claude's daemon give a child).+import { spawnSync } from 'node:child_process'+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { buildManagedScript } from './managed-script'+import { testTmpDir } from '../../test-tmp'+import { makeTmuxTmpdir } from '../../tmux-test-socket'++const SOCKET = 'nt-test-claude-origin'+const tmuxOk = process.platform !== 'win32' && spawnSync('tmux', ['-V']).status === 0+const psOk = process.platform !== 'win32' && spawnSync('ps', ['-o', 'stat=', '-o', 'tty=', '-p', String(process.pid)]).status === 0++// `setsid(1)` is util-linux; macOS has none, so the no-terminal cases run where it exists.+const setsidOk = process.platform !== 'win32' && spawnSync('setsid', ['true']).status === 0++let dir = ''+let tmuxDir = ''+let env: NodeJS.ProcessEnv = {}++function tmux(...args: string[]): string {+ const r = spawnSync('tmux', ['-L', SOCKET, '-f', '/dev/null', ...args], { env, encoding: 'utf8' })+ return r.stdout ?? ''+}++function fakeCurl(log: string): string {+ return ['#!/bin/sh', `printf 'ARGV %s\\n' "$*" >> ${JSON.stringify(log)}`, 'cat >/dev/null', 'exit 0', ''].join('\n')+}++async function waitFor(file: string, ms = 8000): Promise<string> {+ const end = Date.now() + ms+ while (Date.now() < end) {+ if (existsSync(file)) {+ const s = readFileSync(file, 'utf8')+ if (s.includes('ARGV')) return s+ }+ await new Promise((r) => setTimeout(r, 50))+ }+ throw new Error(`no curl call recorded in ${file}`)+}++/** Runs `prelude; <hook>` as a pane's command and returns the fake curl's recorded argv. */+async function runInPane(name: string, prelude: string, payload = '{"hook_event_name":"Stop"}'): Promise<string> {+ const log = join(dir, `${name}.log`)+ const script = join(dir, 'claude.sh')+ const hook = `printf '%s' '${payload}' | sh ${script}`+ const cmd = `${prelude}; ${hook}; sleep 30`+ tmux('new-session', '-d', '-s', name, '-x', '80', '-y', '20', 'sh', '-c', cmd)+ // The pane's env is the tmux server's; the script reads these.+ const out = await waitFor(log.replace(`${name}.log`, 'curl.log'))+ rmSync(join(dir, 'curl.log'), { force: true })+ return out+}++beforeAll(() => {+ if (!tmuxOk || !psOk) return+ dir = testTmpDir('claude-origin-')+ tmuxDir = makeTmuxTmpdir('nt-co-', SOCKET)+ const bin = join(dir, 'bin')+ mkdirSync(bin)+ writeFileSync(join(bin, 'curl'), fakeCurl(join(dir, 'curl.log')), { mode: 0o755 })+ writeFileSync(join(dir, 'claude.sh'), buildManagedScript('claude', null))+ env = {+ PATH: `${bin}:${process.env.PATH ?? ''}`,+ HOME: dir,+ TMUX_TMPDIR: tmuxDir,+ NODETERM_NODE_ID: 'fixture',+ NODETERM_HOOK_PORT: '1',+ NODETERM_PERM_WAIT_SECS: '1',+ TERM: 'xterm'+ }+ tmux('start-server', ';', 'set', '-g', 'exit-empty', 'off')+})++afterAll(() => {+ if (!tmuxOk || !psOk) return+ tmux('kill-server')+ rmSync(tmuxDir, { recursive: true, force: true })+})++describe.skipIf(!tmuxOk || !psOk)('the claude hook script reports which process ran it', () => {+ it('the pane\'s foreground process: fg=1 and the pane tty', async () => {+ const argv = await runInPane('own', 'export CLAUDE_PID=$$')+ const paneTty = tmux('display-message', '-p', '-t', 'own', '#{pane_tty}').trim().replace(/^\/dev\//, '')+ expect(paneTty).toMatch(/\S/)+ expect(argv).toMatch(/nodeterm_claude_pid=\d+ /)+ expect(argv).toContain('nodeterm_claude_fg=1 ')+ expect(argv).toContain(`nodeterm_claude_tty=${paneTty} `)+ })++ it('a job of the pane\'s shell that is not the foreground group: fg=0', async () => {+ // `set -m`: job control, so the `&` job gets its own process group, as in an interactive shell.+ const argv = await runInPane('bgjob', 'set -m; sleep 30 & export CLAUDE_PID=$!; sleep 0.2')+ expect(argv).toContain('nodeterm_claude_fg=0 ')+ })++ it.skipIf(!setsidOk)('a process with no controlling terminal (setsid, like claude\'s tool shell or its daemon): fg=0, no tty', async () => {+ const argv = await runInPane('detached', 'setsid sleep 30 & export CLAUDE_PID=$!; sleep 0.2')+ expect(argv).toContain('nodeterm_claude_fg=0 ')+ expect(argv).toContain('nodeterm_claude_tty= ')+ })++ it.skipIf(!setsidOk)('never arms the approval wait for a non-foreground claude', async () => {+ const argv = await runInPane(+ 'perm',+ 'setsid sleep 30 & export CLAUDE_PID=$!; sleep 0.2',+ '{"hook_event_name":"PermissionRequest","tool_name":"Bash"}'+ )+ expect(argv).toContain('nodeterm_pending_id= ')+ const pending = join(dir, '.nodeterm', 'pending')+ expect(existsSync(pending) ? readdirSync(pending).filter((f) => f.endsWith('.json')) : []).toEqual([])+ })++ it('no CLAUDE_PID (an older claude) or a non-numeric one: every field empty, i.e. unknown', async () => {+ for (const [name, prelude] of [+ ['nopid', 'unset CLAUDE_PID'],+ ['badpid', "export CLAUDE_PID='1;id'"],+ ['gone', 'export CLAUDE_PID=999999999']+ ]) {+ const argv = await runInPane(name, prelude)+ expect(argv, name).toContain('nodeterm_claude_pid= ')+ expect(argv, name).toContain('nodeterm_claude_fg= ')+ expect(argv, name).toContain('nodeterm_claude_tty= ')+ }+ })+})++describe('the origin report is claude-only', () => {+ it('no other agent\'s script carries it', () => {+ for (const agent of ['codex', 'gemini', 'grok', 'copilot', 'opencode']) {+ const s = buildManagedScript(agent, null)+ expect(s, agent).not.toContain('nodeterm_claude_')+ expect(s, agent).not.toContain('CLAUDE_PID')+ expect(s, agent).not.toContain('nt_msys')+ }+ })+})diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 7e8291787..37d5acc3a 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -225,6 +225,42 @@ const ANSWER_DECODE_SH: readonly string[] = [' fi']+/**+ * CLAUDE ONLY: which claude process ran this hook, and is it the foreground of its terminal+ * (issues #1112, #1153 — the rule and the measurement are in core/agents/claude-pane-origin.ts).+ *+ * Read HERE, synchronously, before the POST is backgrounded: claude waits on its hook, so+ * `$CLAUDE_PID` is alive for this one `ps` even on `SessionEnd`; a read in the server could land+ * after the process exited. `$CLAUDE_PID` is exported to hooks by Claude Code itself (measured on+ * 2.1.301; present in the binary from at least 2.1.220). One `ps`, BSD- and procps-compatible:+ * `stat`'s `+` means "in the foreground process group of its controlling terminal" on both, and+ * one `-o` per keyword for the reason PS_FOREGROUND_FLAGS gives. Every way this can fail — no+ * `$CLAUDE_PID` (an older claude), a `ps` without `-o`/`-p` (Git Bash, BusyBox), a process already+ * gone — leaves all three EMPTY, which the server reads as "unknown" and delivers as before. Git+ * Bash is skipped outright: its `ps` cannot answer and a fork there is expensive.+ */+const CLAUDE_ORIGIN_SH: readonly string[] = [+ 'nt_claude_pid=""',+ 'nt_claude_fg=""',+ 'nt_claude_tty=""',+ 'if [ -z "$nt_msys" ]; then',+ ' case "$CLAUDE_PID" in',+ " ''|*[!0-9]*) ;;",+ ' *)',+ ' nt_ps=$(ps -o stat= -o tty= -p "$CLAUDE_PID" 2>/dev/null) || nt_ps=""',+ ' set -f',+ ' set -- $nt_ps',+ ' set +f',+ ' if [ "$#" -ge 1 ]; then',+ ' nt_claude_pid="$CLAUDE_PID"',+ ` case "$1" in *+*) nt_claude_fg=1 ;; *) nt_claude_fg=0 ;; esac`,+ ` case "$2" in ''|'?'|'??'|-|*[!A-Za-z0-9/._-]*) ;; *) nt_claude_tty="$2" ;; esac`,+ ' fi',+ ' ;;',+ ' esac',+ 'fi'+]+function safeIdentityRoot(): string | null {try {return codexThreadIdentityRoot()@@ -266,6 +302,15 @@ export function buildManagedScript(// only thread id a hook under the shared app-server has (#1150/#1175, codex-thread-identity-sh.ts).const codexPayloadFirst = agentId === 'codex' && !!identityRoot// The event name rides the POST for antigravity only — its payload never carries one.+ // Which claude ran this hook (claude-pane-origin.ts) — claude only, like the event field above.+ const originFields =+ agentId === 'claude'+ ? [+ ' --data-urlencode "nodeterm_claude_pid=${nt_claude_pid}" \\',+ ' --data-urlencode "nodeterm_claude_fg=${nt_claude_fg}" \\',+ ' --data-urlencode "nodeterm_claude_tty=${nt_claude_tty}" \\'+ ]+ : []const eventField = antigravity? [` --data-urlencode "nodeterm_hook_event=\${${ANTIGRAVITY_EVENT_ENV}}" \\`]: []@@ -389,15 +434,18 @@ export function buildManagedScript('# environment itself rather than inherited, so it still holds when a caller replaces the env','# (which is exactly what the hook tests in this repo do). CYGWIN* is deliberately outside the','# gate: Cygwin ships its own curl, and that one takes POSIX paths.',+ ...(agentId === 'claude' ? ['nt_msys=""'] : []),'nt_payload_arg="$nt_payload_file"','case "$(uname -s 2>/dev/null)" in',' MINGW*|MSYS*)',+ ...(agentId === 'claude' ? [' nt_msys=1'] : []),' if command -v cygpath >/dev/null 2>&1; then',' nt_payload_arg=$(cygpath -w "$nt_payload_file" 2>/dev/null) || nt_payload_arg="$nt_payload_file"',' [ -n "$nt_payload_arg" ] || nt_payload_arg="$nt_payload_file"',' fi',' ;;','esac',+ ...(agentId === 'claude' ? CLAUDE_ORIGIN_SH : []),'# 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=""',@@ -416,7 +464,9 @@ export function buildManagedScript(// not depend on the env at all....(agentId === 'claude'? [- 'if [ -n "$NODETERM_PERM_WAIT_SECS" ] && [ "$NODETERM_PERM_WAIT_SECS" -gt 0 ] 2>/dev/null; then',+ '# Never arm for a claude that is not the foreground of a terminal (claude-pane-origin.ts):',+ '# its events are not delivered as this node\'s, so nobody could ever answer the hold.',+ 'if [ "$nt_claude_fg" != 0 ] && [ -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_-\' \'_\')',@@ -458,6 +508,7 @@ export function buildManagedScript(' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',...eventField,+ ...originFields,' --data-urlencode "payload@${nt_payload_arg}" 2>/dev/null) || return 1',' elif [ -n "$NODETERM_HOOK_PORT" ]; then',' nt_code=$(nt_hook_headers |',@@ -469,6 +520,7 @@ export function buildManagedScript(' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',...eventField,+ ...originFields,' --data-urlencode "payload@${nt_payload_arg}" 2>/dev/null) || return 1',' else',' return 1',@@ -574,6 +626,9 @@ export function buildManagedScript(' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',' --data-urlencode "nodeterm_answered=${nt_verb}" \\',+ ' --data-urlencode "nodeterm_claude_pid=${nt_claude_pid}" \\',+ ' --data-urlencode "nodeterm_claude_fg=${nt_claude_fg}" \\',+ ' --data-urlencode "nodeterm_claude_tty=${nt_claude_tty}" \\',' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',' nt_payload_owned=1',' elif [ -n "$NODETERM_HOOK_PORT" ]; then',@@ -586,6 +641,9 @@ export function buildManagedScript(' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',' --data-urlencode "nodeterm_answered=${nt_verb}" \\',+ ' --data-urlencode "nodeterm_claude_pid=${nt_claude_pid}" \\',+ ' --data-urlencode "nodeterm_claude_fg=${nt_claude_fg}" \\',+ ' --data-urlencode "nodeterm_claude_tty=${nt_claude_tty}" \\',' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',' nt_payload_owned=1',' fi',diff --git a/src/main/index.ts b/src/main/index.tsindex 37f744755..80ffde8be 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -339,6 +339,7 @@ import { sessionName } from '../core/tmux-naming'import { posixQuote, sshHostKey, type SshConnection } from '../shared/ssh'import { buildHandoff, type HandoffRemote } from './handoff'import { contextLinkShimPath, initContextLink, setNodeTranscript } from '../core/context-link'+import { wireClaudePaneOrigin } from '../core/agents/claude-pane-origin'import { transcriptPathOf } from '../core/context-link-core'import { initCanvasControl, canvasControlShimPath } from './canvas-control'import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control-verbs'@@ -4086,6 +4087,17 @@ app.whenReady().then(async () => {// host's tails too, instead of leaking them.corePlatform.on(IPC.ptyDestroy, (nodeId: string) => releaseNodeTails(nodeId))corePlatform.on(IPC.ptyRecycle, (nodeId: string) => releaseNodeTails(nodeId))+ // Which claude may speak for a node (#1112, #1153): the pane tty from THIS shell's PtyManager.+ // Same call as the Server Edition's (hook-verified-parity.test.ts).+ wireClaudePaneOrigin({+ hooks: hookServer,+ paneOwner: (nodeId) => ptyManager.paneOwner(nodeId),+ cannotRead: (nodeId) =>+ !ptyManager.sshRemoteForNode(nodeId) && !!workspaceStore.sshProjectIdForNode(nodeId),+ on: (channel, cb) => corePlatform.on(channel, cb),+ destroyChannel: IPC.ptyDestroy,+ recycleChannel: IPC.ptyRecycle+ })// Agent canvas control: the spawned agent's `nodeterm` CLI POSTs a verb to the hook server,// which we forward to the renderer and await a reply. A pending-request map (keyed by a random// requestId) bridges the two async hops; both the reply and the timeout below clear the entry.diff --git a/src/server/index.ts b/src/server/index.tsindex e2d3e14b3..dada1c2fc 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -50,6 +50,7 @@ import { installLogSink } from '../core/log-sink'import { registerLogHandlers } from '../core/log-handlers'import os from 'os'import { hookServer } from '../core/agents/hook-server'+import { wireClaudePaneOrigin } from '../core/agents/claude-pane-origin'import { serverEditionControlHandler } from './control-unsupported'import { initServerCanvasControl, serverCanvasShimPath, type ServerCanvasControl } from './canvas-control'import { registerStationNoticeIpc } from '../core/agents/station-notice'@@ -562,6 +563,17 @@ export async function startServer(const { contextTail, geminiContextTail, codexContextTail } = wireAgentStatus(platform, {onEvent: (event) => canvasControl?.onAgentEvent(event)})+ // Which claude may speak for a node (#1112, #1153): the pane tty from THIS shell's PtyManager.+ // Same call as the desktop's (hook-verified-parity.test.ts).+ wireClaudePaneOrigin({+ hooks: hookServer,+ paneOwner: (nodeId) => ptyManager.paneOwner(nodeId),+ // No SSH-project manager here: such a node's pane is on another machine, never readable.+ cannotRead: (nodeId) => !!workspaceStore.sshProjectIdForNode(nodeId),+ on: (channel, cb) => platform.on(channel, cb),+ destroyChannel: IPC.ptyDestroy,+ recycleChannel: IPC.ptyRecycle+ })// The ⌘M chat view + the find-bar's transcript index. Registered HERE rather than with the rest// of the handlers because the hook-fed path authority is the tail created just above. No remote// leg: the Server Edition runs ON the host whose transcripts it reads, so local resolution is