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: recover Codex node identity in local shims
freshjuicez587caab24e73
diff --git a/CLAUDE.md b/CLAUDE.mdindex d55f2e114..125d7c969 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1076,6 +1076,14 @@ else, and its context links must keep classifying across restarts).layout by construction on all three surfaces) and then the well-known data dirs; it is monotone— advertised dir first, keyed by node-id filename in every candidate, and a foreign instance'sdir yields a foreign `kid` = `legacy` = exactly what presenting nothing already gave.+ - **Every LOCAL generated sh client recovers shared-Codex identity before its env gate.** A tool+ shell forked by the account-scoped app-server carries `CODEX_THREAD_ID`, not the pane's+ `NODETERM_*`. Managed hooks, local `nodeterm.sh`, and local `context.sh` therefore prepend+ `codexThreadIdentityResolverSh(codexThreadIdentityRoot())` before testing+ `NODETERM_NODE_ID`/`NODETERM_CANVAS_CONTROL`. Before this was shared, status hooks recovered the+ node while both user-facing shims declared that same first-class Codex session outside+ nodeterm. The SSH constants remain machine-neutral: the local record root is not valid on a+ remote host and must never be baked into its copy.- **Every generated sh client walks the SAME endpoint failover** (`nt_candidates`/`nt_adopt`,`core/agents/hook-endpoint-failover-sh.ts`) — issue #445, the endpoint-level twin of #384: asession is pinned for life to the endpoint PATH it got at tmux creation, so an appdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e63c9a0a3..2ca7fee44 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -163,6 +163,13 @@ that file advertises presents nothing forever when the file is old or unreadablehook script alone could heal itself, the same node proved itself through one client and was refusedthrough another for the life of the session.+**Local generated sh clients recover shared-Codex identity before their env gate.** A Codex tool+shell is forked by the account-scoped app-server, so it has `CODEX_THREAD_ID` but not the pane's+`NODETERM_*`. Managed hooks, local `nodeterm.sh`, and local `context.sh` must prepend+`codexThreadIdentityResolverSh(codexThreadIdentityRoot())` before checking `NODETERM_NODE_ID` or+`NODETERM_CANVAS_CONTROL`. Keep the SSH shim constants machine-neutral: baking the desktop/server+record path into a remote host is both wrong and a local-layout leak.+**A stream error is not a throw you can catch.** When a write to `process.stdout`/`stderr` fails —`EPIPE` down a closed pipe, `EIO` after macOS revokes a closed terminal's tty — node reports it byemitting `'error'` on the stream a tick later, and the default for an unhandled `'error'` event isdiff --git a/docs/shared-codex-node-identity.md b/docs/shared-codex-node-identity.mdindex 954f21d10..46d3d7e44 100644--- a/docs/shared-codex-node-identity.md+++ b/docs/shared-codex-node-identity.md@@ -119,9 +119,16 @@ Ownership resolution reuses the merged fail-closed posture (`pane-ownership.ts`,## The POSIX-sh resolver-`codexThreadIdentityResolverSh(root)` is prepended to every managed hook script. A shared-app-server-tool shell inherits `CODEX_THREAD_ID` but not the pane's `NODETERM_*` (see probe U5,-`docs/superpowers/probes/2026-08-codex-tool-shell-env.md`), so this prelude recovers the binding:+`codexThreadIdentityResolverSh(root)` is prepended to every managed hook script and to both LOCAL+agent shims (`nodeterm.sh` and `context.sh`) before their early environment gates. A+shared-app-server tool shell inherits `CODEX_THREAD_ID` but not the pane's `NODETERM_*` (see probe+U5, `docs/superpowers/probes/2026-08-codex-tool-shell-env.md`), so this prelude recovers the binding.+Without it, Codex hook status worked while canvas control and linked-context reads misdiagnosed the+same first-class node as being outside nodeterm. The machine-neutral shim constants copied to SSH+hosts deliberately omit the local record path; local desktop and Server Edition installers build+their copies with their own `codexThreadIdentityRoot()`.++The resolver:- reads `NODETERM_CODEX_ACCOUNT_ID` from the daemon env to pick the scope;- a known safe account id ⇒ reads **only** that account's record, and requires the record'sdiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 267c06d78..9205e0978 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -12,6 +12,7 @@ import { FANOUT_PER_TURN, PAIR_MIN_INTERVAL_MS } from './agents/agent-message-flimport { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from './browser-outcomes'import { BROWSER_KEYS, BROWSER_TIMEOUT_DEFAULT_MS, BROWSER_TIMEOUT_MAX_MS } from './browser-verb'import { NODE_COLORS } from '@shared/node-colors'+import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'/*** The messaging verbs' retry guidance, RENDERED from `RETRYABLE` — the table is the source, and@@ -421,8 +422,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {* verbatim and the parity test holds the two ends together (issue #367). */export const CONTROL_UNREACHABLE_MSG = 'Could not reach nodeterm (control endpoint unreachable).'-export const CONTROL_SHIM_SCRIPT = `#!/bin/sh-# nodeterm canvas-control CLI (auto-generated — do not edit).+const CONTROL_SHIM_BODY = `# nodeterm canvas-control CLI (auto-generated — do not edit).if [ -z "$NODETERM_CANVAS_CONTROL" ]; thenecho "Canvas control is not available in this session (not a nodeterm agent node)." >&2@@ -590,6 +590,23 @@ fiexit 1`+/**+ * Build the local canvas-control shim. A Codex tool shell is forked by the account-scoped shared+ * app-server, not by its pane, so it carries CODEX_THREAD_ID but none of the NODETERM_* identity+ * variables. The signed thread-ownership record is the only safe way to recover that identity,+ * and the resolver must run before the shim's early NODETERM_CANVAS_CONTROL gate.+ *+ * `identityRoot` stays optional because the same machine-neutral script is copied to SSH hosts;+ * the desktop's local ownership-record path must never be baked into a remote client.+ */+export function buildControlShimScript(identityRoot?: string): string {+ const identityPrelude = identityRoot ? `${codexThreadIdentityResolverSh(identityRoot)}\n` : ''+ return `#!/bin/sh\n${identityPrelude}${CONTROL_SHIM_BODY}`+}++/** Machine-neutral variant used by SSH installation and legacy tests. */+export const CONTROL_SHIM_SCRIPT = buildControlShimScript()+/** The manage-nodeterm-canvas SKILL.md body, pointing at the shim at `shimPath`.* Parameterized because the same skill is installed twice with different paths: into the* desktop's config dirs, and onto an SSH host for remote agent nodes. */diff --git a/src/core/codex-shim-identity.integration.test.ts b/src/core/codex-shim-identity.integration.test.tsnew file mode 100644index 000000000..e3a53a686--- /dev/null+++ b/src/core/codex-shim-identity.integration.test.ts@@ -0,0 +1,82 @@+// A shared Codex app-server forks tool shells without the pane's NODETERM_* environment. These+// tests run both generated local shims under real /bin/sh with only CODEX_THREAD_ID, proving that+// the signed ownership-record prelude executes before either shim's "not a nodeterm node" gate.+import { afterEach, describe, expect, it } from 'vitest'+import { execFile } from 'node:child_process'+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'++import { buildControlShimScript } from './canvas-control-core'+import { buildContextShimScript } from './context-link-core'++const run = promisify(execFile)+const cleanup: string[] = []++afterEach(() => {+ for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true })+})++describe('local Codex tool-shell identity recovery', () => {+ for (const [name, build] of [+ ['canvas control', buildControlShimScript],+ ['linked context', buildContextShimScript]+ ] as const) {+ it(`${name} resolves CODEX_THREAD_ID before its NODETERM_* gate`, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'nodeterm-codex-local-shim-'))+ cleanup.push(dir)+ const root = join(dir, 'codex-thread-nodes')+ const built = build(root)++ const bin = join(dir, 'bin')+ const endpoint = join(dir, 'hook-endpoint.env')+ const tokens = join(dir, 'node-tokens')+ const capture = join(dir, 'curl-args')+ const script = join(dir, 'shim.sh')+ mkdirSync(root)+ mkdirSync(bin)+ mkdirSync(tokens)+ writeFileSync(+ join(root, 'thread-1'),+ `accountId=\nnodeId=node-1\nendpoint=${endpoint}\nsignature=test-fixture\n`,+ { mode: 0o600 }+ )+ writeFileSync(+ endpoint,+ `NODETERM_HOOK_PORT=54321\nNODETERM_HOOK_TOKEN=test-hook\n` ++ `NODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokens}\n`,+ { mode: 0o600 }+ )+ writeFileSync(join(tokens, 'node-1'), 'test-node-token\n', { mode: 0o600 })+ writeFileSync(script, built, { mode: 0o755 })+ writeFileSync(+ join(bin, 'curl'),+ `#!/bin/sh+nt_out=''+while [ "$#" -gt 0 ]; do+ case "$1" in+ -o) shift; nt_out="$1" ;;+ --data-urlencode) shift; printf '%s\n' "$1" >> "$NT_CAPTURE" ;;+ esac+ shift+done+[ -n "$nt_out" ] && printf 'ok\n' > "$nt_out"+printf '200'+`,+ { mode: 0o755 }+ )++ const result = await run('/bin/sh', [script, 'list'], {+ env: {+ PATH: `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}`,+ CODEX_THREAD_ID: 'thread-1',+ NT_CAPTURE: capture+ }+ })++ expect(result.stdout.trim()).toBe('ok')+ expect(readFileSync(capture, 'utf8').split('\n')).toContain('nodeId=node-1')+ })+ }+})diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex 823a650ea..ed3abc456 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -7,6 +7,7 @@ import { HOOK_CURL_HEADERS_SH } from './agents/hook-curl-config-sh'import { CODEX_SANDBOX_BLOCKED_LINE, CODEX_SANDBOX_HINT_SH } from './agents/hook-sandbox-hint-sh'import { HOOK_ENDPOINT_FALLBACK_SH, STALE_ENDPOINT_HINT } from './agents/hook-endpoint-failover-sh'import { NODE_TOKEN_READ_SH } from './agents/node-token-sh'+import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'/** The shim's generic transport-failure sentence — exported so the agent-facing docs below can* quote it verbatim and the parity test holds the two ends together. */@@ -171,8 +172,7 @@ export function buildLinkDoc(// desktop (context-link-render.ts) behind the hook server's /context-link/ route, and this shim is// the thin client that reaches it — over the reverse tunnel's unix socket for a remote node, over// loopback for a local one. Same script either way; sh + curl only.-export const CONTEXT_SHIM_SCRIPT = `#!/bin/sh-# nodeterm context-link CLI (auto-generated — do not edit).+const CONTEXT_SHIM_BODY = `# nodeterm context-link CLI (auto-generated — do not edit).if [ -z "$NODETERM_NODE_ID" ]; thenecho "Not a nodeterm session (NODETERM_NODE_ID unset) — nothing to read."@@ -304,6 +304,21 @@ fiexit 1`+/**+ * Build the local context-link shim with the same shared-Codex identity recovery used by managed+ * hooks and canvas control. The resolver has to precede the NODETERM_NODE_ID early return or a+ * legitimate app-server tool shell is misdiagnosed as being outside nodeterm.+ *+ * Omit `identityRoot` for the machine-neutral script copied to SSH hosts.+ */+export function buildContextShimScript(identityRoot?: string): string {+ const identityPrelude = identityRoot ? `${codexThreadIdentityResolverSh(identityRoot)}\n` : ''+ return `#!/bin/sh\n${identityPrelude}${CONTEXT_SHIM_BODY}`+}++/** Machine-neutral variant used by SSH installation and legacy tests. */+export const CONTEXT_SHIM_SCRIPT = buildContextShimScript()+/** The get-linked-context SKILL.md body, pointing at the shim at `shimPath`. Parameterized* because the same skill is installed twice with different paths: into the desktop's config* dirs, and onto an SSH host for remote agent nodes. */diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex 1b51240c0..ea2bcd071 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -5,7 +5,9 @@// document per node (linked nodes' titles, transcript paths learned from hooks, cwds, tmux// session names) and answers reads over the hook server's /context-link/ route. A POSIX-sh shim// (context.sh) is the client; a globally-installed Claude skill (plus instruction blocks for the-// agents that have no skill system) tells the agent how + when to call it.+// agents that have no skill system) tells the agent how + when to call it. The local shim is built+// with the shared-Codex thread resolver before its node-id gate; the SSH installer keeps the+// machine-neutral body because this machine's ownership-record path is meaningless on the host.//// The reading and parsing happen HERE, on the desktop, not in the CLI. That is what lets an SSH// project's remote agent use the feature at all: its transcripts live on the host, reachable over@@ -21,7 +23,7 @@ import type { ContextLinkMap } from '../shared/types'import { type PtyManager } from './pty-manager'import { TMUX_SOCKET } from './tmux-naming'import {- CONTEXT_SHIM_SCRIPT,+ buildContextShimScript,buildContextLinkSkillBody,buildLinkDoc,buildLinkedContextInstructions,@@ -31,6 +33,7 @@ import {type LinkDoc,type LinkDocEntry} from './context-link-core'+import { codexThreadIdentityRoot } from './codex-identity-proxy'import {CONTEXT_LINK_VERBS,renderContextLink,@@ -58,7 +61,7 @@ function skillPath(): string {function writeCliFiles(): void {const d = contextLinkDir()fs.mkdirSync(d, { recursive: true })- fs.writeFileSync(cliShimPath(), CONTEXT_SHIM_SCRIPT)+ fs.writeFileSync(cliShimPath(), buildContextShimScript(codexThreadIdentityRoot()))try {fs.chmodSync(cliShimPath(), 0o755)} catch {diff --git a/src/main/canvas-control.ts b/src/main/canvas-control.tsindex dc3fb8f25..ec9fbe777 100644--- a/src/main/canvas-control.ts+++ b/src/main/canvas-control.ts@@ -3,19 +3,20 @@// /control/* routes; a Claude skill / codex-gemini instruction blocks tell the agent how +// when to call it. The CLI no-ops unless NODETERM_CANVAS_CONTROL is set.//-// The SSH counterpart of this file is RemoteHooks.installCanvasControl, which writes the very-// same shim + skill onto the remote host — the shim carries no machine-specific paths, so one-// script serves both sides.+// The SSH counterpart is RemoteHooks.installCanvasControl. Both use the same machine-neutral+// body, but the LOCAL installer prepends the shared-Codex thread resolver with this machine's+// ownership-record path; a desktop path must never be baked into the remote copy.import fs from 'fs'import os from 'os'import path from 'path'import { app } from 'electron'import {- CONTROL_SHIM_SCRIPT,+ buildControlShimScript,buildCanvasControlInstructions,buildCanvasSkillBody,mergeCanvasControlBlock} from '../core/canvas-control-core'+import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'import { opencodeConfigDir } from '../core/agents/hooks/opencode'import { copilotHomeDir } from '../core/agents/hooks/copilot'@@ -35,7 +36,7 @@ function skillBody(): string {function writeCliFiles(): void {const d = dir()fs.mkdirSync(d, { recursive: true })- fs.writeFileSync(shimPath(), CONTROL_SHIM_SCRIPT)+ fs.writeFileSync(shimPath(), buildControlShimScript(codexThreadIdentityRoot()))try {fs.chmodSync(shimPath(), 0o755)} catch {diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.tsindex adab27939..0027ddccb 100644--- a/src/server/canvas-control.test.ts+++ b/src/server/canvas-control.test.ts@@ -120,7 +120,10 @@ describe('initServerCanvasControl', () => {})const shim = path.join(dataDir, 'canvas-control', 'nodeterm.sh')- expect(fs.readFileSync(shim, 'utf8')).toContain('NODETERM_CANVAS_CONTROL')+ const shimBody = fs.readFileSync(shim, 'utf8')+ expect(shimBody).toContain('NODETERM_CANVAS_CONTROL')+ expect(shimBody).toContain('CODEX_THREAD_ID')+ expect(shimBody).toContain(path.join(dataDir, 'codex-thread-nodes'))expect(fs.statSync(shim).mode & 0o111).not.toBe(0)const accountDir = path.join(dataDir, 'test-account')runtime.installSkillInto(accountDir)diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 7ed151dea..dba6b884a 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -16,11 +16,12 @@ import {} from '../core/agent-status-mirror'import type { BoardLogHandlers } from '../core/board-log-handlers'import {- CONTROL_SHIM_SCRIPT,+ buildControlShimScript,buildCanvasControlInstructions,buildCanvasSkillBody,mergeCanvasControlBlock} from '../core/canvas-control-core'+import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'import { platform } from '../core/platform'@@ -68,7 +69,7 @@ function skillPathIn(configDir: string): string {function writeShim(): void {const dir = canvasControlDir()fs.mkdirSync(dir, { recursive: true })- fs.writeFileSync(shimPath(), CONTROL_SHIM_SCRIPT, 'utf8')+ fs.writeFileSync(shimPath(), buildControlShimScript(codexThreadIdentityRoot()), 'utf8')try {fs.chmodSync(shimPath(), 0o755)} catch {diff --git a/src/server/context-link.test.ts b/src/server/context-link.test.tsindex c83c4e4bc..b8e3ab7f8 100644--- a/src/server/context-link.test.ts+++ b/src/server/context-link.test.ts@@ -3,7 +3,14 @@// parsing, the local/remote split) are core's and are covered by src/core/context-link.handler.test.ts —// what is tested here is the wiring that was missing server-side.import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest'-import { existsSync, mkdtempSync, promises as fsPromises, rmSync, writeFileSync } from 'node:fs'+import {+ existsSync,+ mkdtempSync,+ promises as fsPromises,+ readFileSync,+ rmSync,+ writeFileSync+} from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { deriveLinkMap, initServerContextLink } from './context-link'@@ -150,6 +157,9 @@ describe('initServerContextLink', () => {// Without this registration the hook server answers every read with// "Context link is unavailable in this session." — the whole desktop-only symptom.expect(registered).toBe(true)+ const shimBody = readFileSync(join(dir, 'context-links', 'context.sh'), 'utf8')+ expect(shimBody).toContain('CODEX_THREAD_ID')+ expect(shimBody).toContain(join(dir, 'codex-thread-nodes'))await link.refresh()const out = await handler({ verb: 'list', nodeId: 'term-a', args: {} })expect(out).toContain('Beta')