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(codex): let the start route outlive the slowloris guard, and verify a thread before binding it
enes10e8564825f5
diff --git a/docs/codex-shared-identity.md b/docs/codex-shared-identity.mdnew file mode 100644index 000000000..682f65869--- /dev/null+++ b/docs/codex-shared-identity.md@@ -0,0 +1,302 @@+# Codex shared identity++How many Codex canvas nodes share one `codex app-server`, how each node keeps a stable identity+inside it, and — the part that matters most in practice — what happens when none of that is+available.++Companion to `docs/grok-agent.md` and `docs/gemini-agent.md`; §9 is the device checklist those+files' §9 sets the format for. Sliced from external PR #112 by **Corvin**+(`[email protected]`).++---++## 1. What it buys++A Codex terminal node used to spawn a full `codex` process tree — an app-server each. A canvas with+a dozen Codex nodes paid for a dozen servers against one account. Now every node on a machine talks+to **one** `codex app-server` and owns one **thread** inside it.++The node ↔ thread mapping is what makes that survivable. It has to outlive the app, because tmux+sessions do: a running Codex client can outlive the Electron process that started it, and after a+restart nothing in memory knows whose conversation is whose.++## 2. The pieces++| File | Job |+| --- | --- |+| `src/core/codex-identity-proxy.ts` | The thread → node record store (signed), and the generated launcher. |+| `src/core/codex-thread-identity-sh.ts` | The POSIX-sh prelude prepended to every managed hook script. |+| `src/core/codex-session-name.ts` | The app-server protocol client: mint a thread, check one exists, read its name. |+| `src/core/codex-identity-caps.ts` | "Can a node on this machine get a managed identity?" — the construction-time gate. |+| `src/core/agents/hook-server.ts` | The `/codex-thread/{start,bind,fallback}` routes and the per-node capability. |+| `src/main/codex-node-auth-secret.ts` | The keychain-backed secret both of the above are keyed on. |+| `src/renderer/state/codexIdentity.ts` | The renderer's gate + the transient per-node mode the UI shows. |++### The records++One file per thread under `<userDataDir>/codex-thread-nodes/<threadId>`:++```+nodeId=term-17+endpoint=/Users/x/Library/Application Support/nodeterm/hook-endpoint.env+signature=<base64url HMAC-SHA256>+```++Through `CorePlatform.userDataDir`, **not** `homedir()` — that was the original shape and it is why+the Server Edition had no story at all. The generated sh gets the same path baked in, POSIX-quoted+(the real one contains a space on macOS), so the two cannot disagree.++Account scoping is deliberately absent: managed Codex accounts are a later slice, and scoping adds+a directory level above this without changing anything the format promises.++### Why the records are signed++The hook prelude reads a record and **re-exports both fields into an agent's environment**. An+attacker who could write one would be choosing a session's node id and hook endpoint. So each+record carries an HMAC over `(threadId, nodeId, endpoint)`; a record that does not verify is+ignored, never repaired, and never deleted by the pruner either.++The sh side cannot verify that HMAC — there is no key in an agent's shell — so the prelude+re-validates the *shape* of both fields (`L1` in the review: the signature is a desktop-side+guarantee, and the prelude's charset checks are the second layer, not a redundancy).++### The per-node capability — the security fix++The hook server's bearer token proves only *"this request came from some nodeterm-spawned+session"*. It cannot prove **which**. Every identity route takes a caller-supplied `nodeId`, so with+the shared bearer alone any agent session could bind **its own** thread to a **sibling** node —+reparenting that node's status, and (via the prelude) aiming its hook traffic.++Each `/codex-thread/*` route therefore also requires `X-NodeTerm-Node-Token` =+`HMAC(secret, nodeId)`: restart-stable, scoped to one node, injected only into that node's session+env by `buildPtyEnv`, and never written to the shared endpoint file every session can read. The+same secret signs the records.++`/codex-thread/fallback` is the one exemption, and it is as narrow as it can be made: the commonest+thing it reports is *"there was no capability to present"*, so requiring one would silence it in+exactly the case it exists for. A report that **does** carry a token must carry the right one, so+only a tokenless caller is trusted on the node id it names.++If secure storage is unavailable the whole feature stays off — `codexIdentityCaps()` answers+`shared: false`, every launch line stays the bare `codex`, and nothing is half-armed.++### The routes++| Route | Token | Handler |+| --- | --- | --- |+| `POST /codex-thread/start` | required | mint a thread on the app-server, write its record, return the id |+| `POST /codex-thread/bind` | required | verify the thread exists, then record that this node owns it |+| `POST /codex-thread/fallback` | tokenless, or matching | mark the node as running plain codex |++`start` mints through a five-step conversation (`initialize`, `thread/start`, an empty+`turn/start`, `turn/interrupt`, `thread/fork` before that turn, `thread/delete` of the seed).+`thread/start` alone creates only app-server metadata and does **not** materialize the rollout file+— a second client's `thread/resume` then fails with "no rollout found", which is precisely what the+launcher does one line later. The fork-and-delete dance produces a thread with zero user turns and+a valid rollout without the deprecated rollback API.++That conversation runs against a server that is typically **cold** (the first Codex node after+boot). Three budgets have to stay ordered, and the ordering is the whole point:++```+launcher curl (30 s) > server handler (CODEX_THREAD_START_TIMEOUT_MS, 20 s) < socket guard (CONTROL_CEILING_MS, 130 s)+```++Get the first comparison backwards and curl quits while the server carries on to create a thread+and write a record nothing will ever resume — an orphan pair per attempt. Get the second wrong and+the route inherits the 2 s **slowloris** guard, which is a RECEIVE-phase guard: it destroys the+socket while the handler is still working, on the most common launch there is. `handleCodexThread`+hands off to `CONTROL_CEILING_MS` after `readBody`, exactly as `/control/` and `/context-link/` do,+and `codex-launcher-sh.test.ts` pins it with a start handler that sleeps.++---++## 3. The fallback++**Every failure path ends in `exec codex "$@"`, arguments intact.** Upstream exited 69 "identity+unavailable", which turns a missing app-server, an older `codex`, a stale tmux session or a+locked-down data dir into a **dead node**. The repo's own precedent is `gatePermissionMode`: an+unknown or failed probe degrades to the bare command, never to a blocked launch.++The decision lives in two places at different granularity, and **the script is the authority**.++**1. Construction time** — `codexIdentityCaps()`. `AGENT_CONFIG.codex.launchCmd` stays `'codex'`,+byte-identical; `agentLaunchProgram(id, base, sharedIdentity = false)` names the launcher only when+the caller opts in, and `codexSharedIdentity(remote)` says yes only when the probe reports an+installed + armed launcher **and** the session is local. (An SSH host has no launcher installed —+that is a later slice — so a launcher-named line there would be `command not found`, i.e. the exact+dead node this exists to prevent.) The default `false` means every call site that has not opted in+emits today's command.++Unlike claude's, this probe cannot compute anything until the shell hands the hook server its+secret, so the shell **pushes** the answer in and an early caller **waits**. A sync getter would+answer "no" to anything that asked first, and a "no" pins the feature off for the whole run with no+chip, no toast and no log line — one boot-chain reordering away, invisibly.++**2. Runtime** — the launcher. Only the script can see the pane's env, whether the endpoint file is+readable, whether the broker answers, or whether the installed `codex` even has an app-server. It+preflights all of that and, on any miss, execs plain codex.++### Where it surfaces++Not silent, and **never in the pane** — text pushed into an agent's terminal is prompt injection,+which this repo forbids.++- the launcher POSTs `/codex-thread/fallback` with a machine-readable reason before exec'ing;+- the node header shows a muted **`plain codex`** chip whose tooltip says why;+- the **first** fallback per node also raises the warning banner, because a chip on a node you are+ not looking at teaches nothing.++The mode is **transient**, never persisted: it describes one launch of one process, and a stale+"plain" badge on a reloaded node would be a lie.++### The reasons++| Reason | Means |+| --- | --- |+| `node-id-unavailable` | not a nodeterm-spawned session (the launcher was run by hand) |+| `hook-endpoint-unavailable` | the endpoint file is missing or unreadable |+| `broker-unreachable` | the hook server's coordinates are unusable |+| `node-token-unavailable` | no per-node capability — usually no secure storage |+| `thread-id-unavailable` | the session id to resume is not shaped like one |+| `app-server-unavailable` | `codex app-server daemon start` failed — an older CLI |+| `thread-bind-refused` | the thread is unknown to the server, or a live node already owns it |+| `thread-start-failed` | the server would not mint a thread |++### What the fallback does NOT cover++**Everything after `exec` is unrecoverable.** Once the launcher runs+`codex --remote unix:// resume "$thread" "$@"`, a clap usage error or a "no rollout found" is a dead+node — the outcome this whole design exists to prevent, arrived at by a different door.++One class of that is closed defensively: **bind verifies the thread exists** on the app-server+before writing a record. The id reaching us is whatever the node persisted, and it can be stale or+left over from a session that ran under plain codex; binding it anyway wrote a record and then+exec'd a resume that died where nothing could catch it. Refusing here *is* the fallback. A server we+cannot reach answers "does not exist", which is the safe direction: refusing costs a plain codex+session, accepting costs the node.++The rest needs a real machine — §9.1-9.3.++### One deliberate non-use++**"Restart agent (resume)" keeps emitting the bare `codex resume <id>`.** It types into a pane that+already exists, and a tmux session created before the launcher was installed does not carry its+directory on PATH. A restarted node rejoins as a plain client until its next cold start.++---++## 4. The hook prelude++A shared app-server spawns a Codex **tool**'s shell itself, so that shell inherits `CODEX_THREAD_ID`+but none of the `NODETERM_*` env we set on the pane — the hook it runs would have no idea which+canvas node it belongs to, and the node's badge would simply never move. The prelude recovers the+binding from the thread id.++It is prepended to **every** agent's managed hook script, not just codex's. That is intentional: it+is inert without `CODEX_THREAD_ID` (which no other agent's tool shell sets), and one builder beats a+codex-only fork of it. It does change every agent's generated script, which is why+`managed-script.test.ts` asserts both its presence for all five builtins and that a missing identity+root yields the legacy script unchanged. **Remote (SSH) hosts get `null`** — the default root is+this machine's data dir, and baking it into a script on someone else's host leaks the desktop's+layout for no benefit.++---++## 5. Session names++`TITLE_READ_CAPABLE` gained `codex`; `RENAME_CAPABLE` did not. With the shared server a node owns a+thread, and that thread carries a `Thread.name` readable over the server's own socket — but there is+no measured rename command, so the read and write legs split exactly as they did for gemini. One+list for both would light the rename UI on a node where the write silently does nothing.++`readAgentSessionName` routes codex to its own reader **before** claude's: claude's resolver SCANS+`~/.claude/projects` on a cache miss, and its cwd fallback can hand back a stranger's session name.+Both shells' session-name sweeps take core's `supportsTitleRead` default, so codex is enrolled in+both without either shell being edited (the two drifted once before — see CLAUDE.md rule 10).++---++## 6. Three surfaces++- **Desktop** — full support.+- **Server Edition** — a deliberate, documented degrade to plain `codex`. The blocker is the+ *secret*, not the plumbing: the per-node capability is keychain-backed on desktop (Electron+ `safeStorage`) and there is no equivalent on a headless Linux host, so arming it means a secret at+ rest in the data dir — a security decision this slice is not entitled to make quietly. Everything+ it would need already lives in `src/core` and boots from `CorePlatform`; the wiring is three calls+ plus the two handler registrations, at the marked spot in `src/server/handlers/index.ts`. The+ renderer bridge already has a **real** `codex` namespace, so that side needs no change.+- **Mobile companion** (`~/projects/nodeterm-ios`) — N/A. It attaches to tmux sessions over the+ transport protocol; which app-server a Codex session talks to is invisible to it, and the+ `plain codex` chip is a canvas-node affordance the phone has no slot for. No protocol change owed.+- **Kanban** — the mode lives in a store the card modal could read; the chip is on the canvas node+ header only. Adding it to the card's expanded detail row is a small follow-up.++---++## 7. Not in this slice++The relay daemon, managed Codex accounts (including account-scoped record directories, which the+flat layout extends into cleanly), SSH hosts, browser control, and the mailbox/loop work — all from+PR #112, all still to be sliced.++---++## 8. Known gaps++1. **Post-`exec` failures are unrecoverable** (§3, and §9.1-9.3).+2. **The launcher requires a hook PORT**, not a unix socket — it POSTs to+ `http://localhost:$NODETERM_HOOK_PORT`. Fine today (the desktop's hook server is a loopback TCP+ listener), but the Server Edition wiring will have to revisit it alongside `NODETERM_HOOK_SOCK`,+ which the launcher already reads for curl but not for the URL.+3. **The node token rides tmux `-e` on the local path**, i.e. it is in the tmux session env like+ every other `NODETERM_*` value. Same exposure as the hook bearer already has; noted rather than+ changed, because changing it means changing how all of them are delivered.+4. **`CODEX_HOME` is resolved twice**: the desktop resolves the app-server socket from the Electron+ process's environment, the pane resolves `--remote unix://` from its own. Identical unless a user+ sets `CODEX_HOME` in a shell rc only, in which case start succeeds and resume misses. Managed+ accounts make this explicit; until then it is a narrow, real mismatch.++---++## 9. Device checklist++Everything below needs a machine with a logged-in `codex`. Items 1-3 are the assumptions the+implementation could not verify; a failure in any of them is a **dead node**, not a degrade, so they+come first. Items 1, 2 and 5 fall out of a single capture run on one fresh node.++1. **`codex --remote unix://` exists on the installed CLI.** The preflight only proves+ `codex app-server daemon start` exits 0 — it says nothing about the `--remote` flag. Run+ `codex --help` and confirm `--remote` and its argument form; then open a fresh Codex node and+ confirm the pane shows a working session rather than a clap usage error. If the flag differs,+ the launcher's two `exec` lines are what change.+2. **`codex resume <id> <prompt> --ask-for-approval never` accepts a positional prompt AND a global+ flag after the subcommand.** This is the composed line `createAgentNode` builds, and it is+ CLAUDE.md rule 5's grok-`--` lesson exactly: a `withPermissionMode` unit test passes while the+ composed line is wrong. Create a Codex node with an initial prompt while the permission mode is+ anything but `manual`, and confirm the prompt reaches the model and the flag is honored (not+ swallowed into the prompt text, not a usage error).+3. **The session id nodeterm persists from hooks is the id the app-server accepts as a thread.**+ Let a Codex node run a turn, note `agentStatus.sessionId`, restart the app, and confirm the cold+ restore resumes the same conversation rather than falling back. If they are different+ namespaces, `bind` will refuse every resume and every restored node quietly runs plain codex.+4. **RAM, the thing this is for.** Open six Codex nodes; confirm `ps` shows ONE `codex app-server`+ and six thin clients, and compare RSS against six independent `codex` processes.+5. **The chip and the toast.** Force a fallback (rename `~/.nodeterm`… no — simplest: launch a node+ with `CODEX_HOME` pointed at a directory with no app-server, or use a CLI without+ `app-server`), and confirm the node shows `plain codex`, the tooltip names the reason, the+ banner appears once, and **nothing is written into the pane**.+6. **The session name.** Let codex name a thread, confirm the node title adopts it within a poll+ cycle, and confirm a hand-renamed node (`titleAuto` false) is left alone.+7. **Restart and reboot.** Restart the app with Codex nodes running: the tmux clients survive, the+ records are still trusted, and hooks from a Codex TOOL shell (which has only `CODEX_THREAD_ID`)+ still move the right node's badge — that last one is the prelude, and it is only exercised by a+ tool call, not by a plain turn.+8. **Deletion prunes.** Delete a Codex node permanently and confirm its records are gone from+ `<userDataDir>/codex-thread-nodes/` while other nodes' remain.+9. **Two nodes, one thread.** Point a second node at a thread the first still owns (a `resume` with+ a copied id) and confirm it falls back to plain codex instead of both clients attaching.+10. **A cold app-server.** Kill the app-server, then open a Codex node. This is the H1 case: confirm+ it waits for the mint (which can take seconds) and comes up shared, rather than falling back+ with `thread-start-failed` while an orphan thread is created behind it.diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 41f3841d8..cf5d018ec 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -378,6 +378,18 @@ class HookServer {): Promise<void> {const verb = pathname.replace(/^\/codex-thread\//, '')const form = parseForm(await readBody(req))+ // SAME HAND-OFF as /control/ and /context-link/, and for the same reason — this route needs it+ // MOST. The receive phase is over, so the 2s slowloris guard has done its job; leaving it armed+ // destroys the socket while the HANDLER is still working. `/codex-thread/start` mints a thread+ // through a five-step conversation with the app-server (initialize, start, a turn, an+ // interrupt, a fork, a delete) against a server that is typically COLD — the first codex node+ // after boot is the common case, not the edge one. At 2s that fails every time, and it fails in+ // the worst possible way: curl gives up, the launcher falls back to plain codex, and main goes+ // on to create the thread and write a record for it — an orphan thread plus an orphan record+ // per attempt. The client budget is deliberately set ABOVE the server's own (see+ // CODEX_THREAD_START_TIMEOUT_MS / the launcher's --max-time) so the server is always the one+ // that gives up first and can clean up after itself.+ req.setTimeout(CONTROL_CEILING_MS, () => req.destroy())const nodeId = form.nodeId ?? ''if (!/^[A-Za-z0-9._-]+$/.test(nodeId)) {res.writeHead(400)@@ -385,6 +397,19 @@ class HookServer {return}if (verb === 'fallback') {+ // This is the ONE route that may be called without the per-node capability, because the+ // commonest thing it reports is "there was no capability to present" — requiring one would+ // silence it in exactly the case it exists for. That exemption is as narrow as it can be+ // made: a report that DOES carry a token must have the right one, so only a tokenless caller+ // is trusted on the nodeId it names. Without this a session holding the shared bearer could+ // flag a sibling node as fallen back. Cosmetic (the flag is transient and downgrade-only),+ // but a claim in a comment has to be true.+ const token = req.headers['x-nodeterm-node-token']+ if (token !== undefined && !this.codexNodeTokenMatches(nodeId, token)) {+ res.writeHead(403)+ res.end()+ return+ }// A reason is free text from a generated script we wrote; bound it and let the UI show it.const reason = (form.reason ?? '').slice(0, 64).replace(/[^A-Za-z0-9._-]/g, '') || 'unknown'this.codexIdentityListener?.({ nodeId, mode: 'plain', reason })diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 04840b26e..fd3b4cab4 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -67,7 +67,10 @@ function safeIdentityRoot(): string | null {}}-export function buildManagedScript(agentId: string, identityRoot = safeIdentityRoot()): string {+export function buildManagedScript(+ agentId: string,+ identityRoot: string | null = safeIdentityRoot()+): string {return ['#!/bin/sh',...(identityRoot ? [codexThreadIdentityResolverSh(identityRoot)] : []),diff --git a/src/core/codex-identity-caps.test.ts b/src/core/codex-identity-caps.test.tsnew file mode 100644index 000000000..94f0a5ead--- /dev/null+++ b/src/core/codex-identity-caps.test.ts@@ -0,0 +1,69 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { randomBytes } from 'node:crypto'+import {+ codexIdentityCaps,+ refreshCodexIdentityCaps,+ resetCodexIdentityCapsForTests+} from './codex-identity-caps'+import {+ resetCodexThreadIdentityAuthSecret,+ setCodexThreadIdentityAuthSecret+} from './codex-identity-proxy'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++let dir = ''++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-caps-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ resetCodexIdentityCapsForTests()+ resetCodexThreadIdentityAuthSecret()+})++afterEach(() => {+ resetCodexThreadIdentityAuthSecret()+ resetCodexIdentityCapsForTests()+ resetPlatformForTests()+ fs.rmSync(dir, { recursive: true, force: true })+})++describe('codexIdentityCaps', () => {+ it('says yes, and installs the launcher, once the secret is in', () => {+ setCodexThreadIdentityAuthSecret(randomBytes(32))+ const caps = refreshCodexIdentityCaps()+ expect(caps.shared).toBe(true)+ expect(fs.existsSync(caps.launcherPath as string)).toBe(true)+ })++ it('says no without the secret, and installs nothing', () => {+ // Half-armed is the state to avoid: a launcher on PATH with no capability to present would+ // reach the routes, be refused, and fall back one process later. Better to never name it.+ const caps = refreshCodexIdentityCaps()+ expect(caps).toEqual({ shared: false, launcherPath: null })+ expect(fs.existsSync(path.join(dir, 'codex-bin', 'nodeterm-codex'))).toBe(false)+ })++ it('makes an early caller WAIT rather than answering no', async () => {+ // The ordering trap this exists for: a sync getter would answer `false` to anything that asked+ // before the shell refreshed, and a `false` pins the feature off for the whole run — with no+ // launcher run there is no chip, no toast and no log line to say it happened.+ const asked = codexIdentityCaps()+ let settled = false+ void asked.then(() => (settled = true))+ await Promise.resolve()+ expect(settled).toBe(false)+ setCodexThreadIdentityAuthSecret(randomBytes(32))+ refreshCodexIdentityCaps()+ expect((await asked).shared).toBe(true)+ })++ it('answers immediately once refreshed', async () => {+ refreshCodexIdentityCaps()+ expect(await codexIdentityCaps()).toEqual({ shared: false, launcherPath: null })+ })+})diff --git a/src/core/codex-identity-caps.ts b/src/core/codex-identity-caps.tsindex 452d1ddc1..83527cb2f 100644--- a/src/core/codex-identity-caps.ts+++ b/src/core/codex-identity-caps.ts@@ -2,10 +2,17 @@* "Can a node on THIS machine get a managed Codex identity?" — the construction-time half of the* fallback.*- * Shaped exactly like `core/claude-cli.ts`: a memoized probe behind one CorePlatform RPC channel,- * registered by BOTH shells, whose unknown answer is the conservative one. The renderer asks it- * before it writes a launch line, and a `false` means the line stays the bare `codex` it has- * always been — never a launcher path that might not resolve, which would be a dead node.+ * Modelled on `core/claude-cli.ts`: one answer behind one CorePlatform RPC channel, registered by+ * BOTH shells, whose unknown answer is the conservative one. The renderer asks it before it writes+ * a launch line, and a `false` means the line stays the bare `codex` it has always been — never a+ * launcher path that might not resolve, which would be a dead node.+ *+ * It differs from claude's in WHERE the work happens: claude's probe is lazy and self-starting+ * (`claude --version` can run whenever someone first asks), while this one cannot compute anything+ * until the shell has handed the hook server its node-auth secret. So the shell PUSHES the answer+ * in (`refreshCodexIdentityCaps`) and a caller that arrives first WAITS for it — see+ * `codexIdentityCaps` below for why waiting, rather than answering "no", is the only safe default+ * here.** Two things have to be true, and neither is knowable from the renderer:* 1. the hook server holds the per-node auth secret (no secret ⇒ no capability token ⇒ the@@ -22,24 +29,51 @@ import { platform } from './platform'import { UNKNOWN_CODEX_IDENTITY_CAPS, type CodexIdentityCaps } from '../shared/types'import { installCodexLauncher, codexThreadIdentityAvailable } from './codex-identity-proxy'-let cached: CodexIdentityCaps | null = null+let latest: CodexIdentityCaps | null = null+let ready: Promise<CodexIdentityCaps> | null = null+let announce: ((c: CodexIdentityCaps) => void) | null = null-/** Recompute now. Called at wiring time and again whenever the launcher is (re)installed. */+/**+ * Compute the answer and publish it. Called once by the shell, AFTER the node-auth secret has been+ * set (or has definitively failed), because the secret is half of what "shared" means.+ */export function refreshCodexIdentityCaps(): CodexIdentityCaps {const launcher = codexThreadIdentityAvailable() ? installCodexLauncher() : null- cached = { shared: !!launcher, launcherPath: launcher }- return cached+ latest = { shared: !!launcher, launcherPath: launcher }+ if (announce) {+ announce(latest)+ announce = null+ } else if (!ready) {+ ready = Promise.resolve(latest)+ }+ return latest}-export function codexIdentityCaps(): CodexIdentityCaps {- return cached ?? UNKNOWN_CODEX_IDENTITY_CAPS+/**+ * The answer, ASYNC — like `claudeCliCaps()`, and for the same reason.+ *+ * An early caller must WAIT rather than be told "no". A sync getter would answer `false` to+ * anything that asked before `refreshCodexIdentityCaps()` ran, and since a `false` means no+ * launcher ever runs, it would pin the feature off for the whole session with no chip, no toast+ * and no log line to say so — one reordering of the boot chain away, invisibly. Waiting makes the+ * ordering a latency question instead of a correctness one. The renderer races this against its+ * own bounded timeout, so a shell that never refreshes costs a plain-codex session, not a hang.+ */+export function codexIdentityCaps(): Promise<CodexIdentityCaps> {+ if (latest) return Promise.resolve(latest)+ if (!ready) ready = new Promise((resolve) => (announce = resolve))+ return ready}/** Wire the answer onto the platform's RPC surface (Electron ipcMain / server WS-RPC alike). */-export function registerCodexIdentityIpc(answer: () => CodexIdentityCaps = codexIdentityCaps): void {+export function registerCodexIdentityIpc(+ answer: () => CodexIdentityCaps | Promise<CodexIdentityCaps> = codexIdentityCaps+): void {platform().handle(IPC.codexIdentityCaps, () => answer())}export function resetCodexIdentityCapsForTests(): void {- cached = null+ latest = null+ ready = null+ announce = null}diff --git a/src/core/codex-identity-proxy.test.ts b/src/core/codex-identity-proxy.test.tsindex 8c4c08e15..b50ad9a16 100644--- a/src/core/codex-identity-proxy.test.ts+++ b/src/core/codex-identity-proxy.test.ts@@ -6,6 +6,7 @@ import { randomBytes } from 'node:crypto'import {bindCodexThreadIdentity,codexLauncherDir,+ forgetCodexThreadIdentitiesForNode,codexThreadIdentityRoot,installCodexLauncher,readCodexThreadIdentity,@@ -117,3 +118,28 @@ describe('installCodexLauncher', () => {expect(installCodexLauncher()).toBeNull()})})++describe('forgetting a permanently deleted node', () => {+ it('removes every record naming it, and leaves the others alone', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e')+ writeCodexThreadIdentity('thread-2', 'node-1', '/data/e')+ writeCodexThreadIdentity('thread-3', 'node-2', '/data/e')+ forgetCodexThreadIdentitiesForNode('node-1')+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBeUndefined()+ expect(resolveCodexThreadNodeIdentity('thread-2')).toBeUndefined()+ // Without this the directory grows a file per thread forever, AND a dead node's record keeps+ // re-exporting its node id into any tool shell still carrying that thread id.+ expect(resolveCodexThreadNodeIdentity('thread-3')).toBe('node-2')+ })++ it('never deletes a record it does not trust, and never throws', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e')+ const file = path.join(codexThreadIdentityRoot(), 'thread-1')+ fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('node-1', 'node-2'))+ forgetCodexThreadIdentitiesForNode('node-2')+ expect(fs.existsSync(file)).toBe(true)+ // A node deletion must never fail on this: no directory at all is simply nothing to forget.+ fs.rmSync(codexThreadIdentityRoot(), { recursive: true, force: true })+ expect(() => forgetCodexThreadIdentitiesForNode('node-1')).not.toThrow()+ })+})diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.tsindex c40323bae..c0605a688 100644--- a/src/core/codex-identity-proxy.ts+++ b/src/core/codex-identity-proxy.ts@@ -21,11 +21,30 @@* storage shape is one file per thread id; scoping adds a directory level above it without* changing anything this file promises.*/-import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs'+import {+ chmodSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ renameSync,+ unlinkSync,+ writeFileSync+} from 'fs'import path from 'path'import { createHmac, timingSafeEqual } from 'crypto'import { platform } from './platform'-import { posixQuote } from '../shared/ssh'++/**+ * How long the SERVER gives itself to mint a thread (`startCodexThreadAt`'s default).+ *+ * The launcher's own curl budget is derived from this and is deliberately LARGER+ * (`CODEX_THREAD_START_CLIENT_MAX_S`), so the server is always the side that gives up first.+ * Get that ordering backwards and a slow app-server produces the worst outcome available: curl+ * quits, the launcher falls back to plain codex, and the server carries on to create a thread and+ * write a record for it that nothing will ever resume.+ */+export const CODEX_THREAD_START_TIMEOUT_MS = 20_000+const CODEX_THREAD_START_CLIENT_MAX_S = CODEX_THREAD_START_TIMEOUT_MS / 1000 + 10const SAFE_NODE_ID = /^[A-Za-z0-9._-]+$/const SAFE_ENDPOINT = /^\/[A-Za-z0-9._/ -]+$/@@ -193,13 +212,37 @@ export function bindCodexThreadIdentity(writeCodexThreadIdentity(threadId, nodeId, hookEndpoint, root)}-/** Drop a node's record when the node is permanently deleted. Best effort. */-export function forgetCodexThreadIdentity(threadId: string, root = codexThreadIdentityRoot()): void {- if (!SAFE_THREAD_ID.test(threadId)) return+/**+ * Drop every record naming `nodeId`, when that node is permanently deleted.+ *+ * Two reasons this is not just housekeeping. The directory would otherwise grow one file per+ * thread forever, and — worse — a dead node's record keeps re-exporting its node id and hook+ * endpoint into any tool shell that still carries the thread id, so a deleted node's identity+ * outlives it. Keyed by node, not by thread, because the caller (`destroySession`) knows the node+ * id and nothing else; the directory is one flat level, so the scan is a single readdir.+ *+ * Best effort throughout: a record we cannot read or remove must never fail a node deletion.+ */+export function forgetCodexThreadIdentitiesForNode(+ nodeId: string,+ root = codexThreadIdentityRoot()+): void {+ if (!SAFE_NODE_ID.test(nodeId)) return+ let entries: string[]try {- unlinkSync(path.join(root, threadId))+ entries = readdirSync(root)} catch {- /* nothing to forget */+ return+ }+ for (const threadId of entries) {+ if (!SAFE_THREAD_ID.test(threadId)) continue+ // Reads through the signature check, so a record we do not trust is also one we do not delete.+ if (readCodexThreadIdentity(threadId, root)?.nodeId !== nodeId) continue+ try {+ unlinkSync(path.join(root, threadId))+ } catch {+ /* nothing to forget */+ }}}@@ -280,7 +323,10 @@ nt_preflight() {}# Best effort, and never fatal: tell the desktop this node is running plain codex, so the UI can-# say so without the user reading a log. Requires only the shared bearer — it names no sibling.+# say so without the user reading a log. Sent WITHOUT the per-node capability on purpose — the+# commonest thing it reports is that there was no capability to present. The server only trusts a+# TOKENLESS report on the node it names (see handleCodexThread), so a session that does hold a+# token cannot use this route to flag a sibling.nt_report_fallback() {[ -n "\${NODETERM_HOOK_PORT-}" ] || return 0[ -n "\${NODETERM_HOOK_TOKEN-}" ] || return 0@@ -298,16 +344,21 @@ if [ -n "$nt_reason" ]; thenexec codex "$@"fi+# $1 is the client budget in seconds; the rest is curl's. Start gets a budget LARGER than the+# server's own (CODEX_THREAD_START_TIMEOUT_MS) so the server, not curl, is what times out — a curl+# that quits first leaves behind a thread and a record nothing will ever resume.nt_post() {+ nt_budget=$1+ shiftprintf 'header = "X-NodeTerm-Hook-Token: %s"\\nheader = "X-NodeTerm-Node-Token: %s"\\n' \\"$NODETERM_HOOK_TOKEN" "$NODETERM_CODEX_NODE_TOKEN" |- nt_hook_curl --silent --show-error --fail --max-time 10 --config - --request POST "$@"+ nt_hook_curl --silent --show-error --fail --max-time "$nt_budget" --config - --request POST "$@"}if [ "\${1-}" = resume ]; then# Claim the caller-supplied thread for THIS node before Codex opens it. A refusal means another# live node owns it; two clients on one thread is worse than one plain session, so we fall back.- if nt_post --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "threadId=\${2-}" \\+ if nt_post 20 --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "threadId=\${2-}" \\"http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/bind" >/dev/null; thenexec codex --remote unix:// "$@"fi@@ -315,7 +366,7 @@ if [ "\${1-}" = resume ]; thenexec codex "$@"fi-nt_thread=$(nt_post --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "cwd=$PWD" \\+nt_thread=$(nt_post ${CODEX_THREAD_START_CLIENT_MAX_S} --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "cwd=$PWD" \\"http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/start") || nt_thread=''nt_thread=$(printf %s "$nt_thread" | tr -d '\\r\\n')case "$nt_thread" in@@ -345,8 +396,3 @@ export function installCodexLauncher(): string | null {return null}}--/** The launcher directory as a single POSIX-sh token, for embedding in generated scripts. */-export function quotedCodexLauncherDir(): string {- return posixQuote(codexLauncherDir())-}diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.tsindex 8e91d1933..1951f5f35 100644--- a/src/core/codex-launcher-sh.test.ts+++ b/src/core/codex-launcher-sh.test.ts@@ -28,6 +28,7 @@ let started: Array<{ nodeId: string; cwd: string }> = []let bound: Array<{ nodeId: string; threadId: string }> = []let fallbacks: Array<{ nodeId: string; reason?: string }> = []let startAnswer: (() => string) | null = null+let startDelayMs = 0let bindAnswer: (() => void) | null = null/** A stand-in for the real `codex`, which records how it was invoked and exits 0. */@@ -54,6 +55,7 @@ beforeAll(async () => {hookServer.setCodexNodeAuthSecret(randomBytes(32))hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd }) => {started.push({ nodeId, cwd })+ if (startDelayMs) await new Promise((r) => setTimeout(r, startDelayMs))if (!startAnswer) throw new Error('start refused')return startAnswer()})@@ -78,6 +80,7 @@ beforeEach(() => {bound = []fallbacks = []startAnswer = () => 'thread-abc'+ startDelayMs = 0bindAnswer = () => {}fs.writeFileSync(argvLog, '')})@@ -203,7 +206,52 @@ describe('falls back to plain codex', () => {})})+describe('a start handler that takes real time', () => {+ // REGRESSION. `/codex-thread/start` mints a thread through a five-step conversation with an+ // app-server that is typically COLD — the first codex node after boot. The route inherited the+ // 2s slowloris guard (a RECEIVE-phase guard), so the socket was destroyed while the handler was+ // still working: curl failed, the launcher fell back to plain codex, and the server went on to+ // create the thread and write a record for it. An orphan thread and an orphan record, per+ // attempt, in the most common case there is. A handler that resolves synchronously — which is+ // what this suite used to have — cannot see any of that.+ it('is waited for, and its thread is the one codex resumes', async () => {+ startDelayMs = 3000+ await callLauncher([])+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-abc'])+ expect(fallbacks).toEqual([])+ }, 20_000)+})+describe('per-node capability (the authorization the shared bearer cannot give)', () => {+ it('the fallback report is trusted only when it presents no token at all', async () => {+ // The one route the capability is not required on — because the commonest thing it reports is+ // that there was no capability to present. The exemption is exactly that narrow: a report that+ // DOES carry a token must carry the right one, or a session holding only the shared bearer+ // could flag a sibling node as fallen back.+ const post = (nodeId: string, headers: Record<string, string>) =>+ fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/fallback`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/x-www-form-urlencoded',+ 'x-nodeterm-hook-token': hookServer.getToken(),+ ...headers+ },+ body: `nodeId=${nodeId}&reason=broker-unreachable`+ })+ expect((await post('node-1', {})).status).toBe(204)+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'broker-unreachable' }])+ const wrong = await post('node-1', {+ 'x-nodeterm-node-token': hookServer.codexNodeAuthToken('node-2')+ })+ expect(wrong.status).toBe(403)+ expect(fallbacks).toHaveLength(1)+ const right = await post('node-1', {+ 'x-nodeterm-node-token': hookServer.codexNodeAuthToken('node-1')+ })+ expect(right.status).toBe(204)+ expect(fallbacks).toHaveLength(2)+ })+it("refuses a token minted for a SIBLING node, and falls back rather than binding it", async () => {await callLauncher(['resume', 'thread-xyz'], {NODETERM_CODEX_NODE_TOKEN: hookServer.codexNodeAuthToken('node-2')diff --git a/src/core/codex-session-name.test.ts b/src/core/codex-session-name.test.tsnew file mode 100644index 000000000..89cad2e1e--- /dev/null+++ b/src/core/codex-session-name.test.ts@@ -0,0 +1,118 @@+// The app-server protocol client, against a real WebSocket server on a real unix socket.+//+// Two of its answers are load-bearing in ways a mocked test would not show: `codexThreadExistsAt`+// is what stands between a stale session id and a node that dies AFTER exec (where no fallback is+// left), and both readers must answer the conservative thing when the server is simply not there —+// which, for a CLI whose app-server starts on demand, is a completely ordinary state.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import http from 'node:http'+import path from 'node:path'+import { WebSocketServer, type WebSocket } from 'ws'+import {+ codexThreadExistsAt,+ codexUnixWebSocketUrl,+ readCodexSessionNameAt+} from './codex-session-name'++let dir = ''+let sock = ''+let server: http.Server+let wss: WebSocketServer+/** Threads the fake app-server knows about, id → name. */+const threads = new Map<string, string | null>([+ ['thread-known', 'Named by codex'],+ ['thread-nameless', null]+])+let initializeFails = false++function handle(ws: WebSocket): void {+ ws.on('message', (raw) => {+ const msg = JSON.parse(raw.toString()) as Record<string, any>+ if (msg.method === 'initialize') {+ ws.send(+ JSON.stringify(+ initializeFails+ ? { id: msg.id, error: { message: 'not authenticated' } }+ : { id: msg.id, result: {} }+ )+ )+ return+ }+ if (msg.method === 'thread/read') {+ const id = msg.params?.threadId as string+ if (!threads.has(id)) {+ ws.send(JSON.stringify({ id: msg.id, error: { message: 'no rollout found' } }))+ return+ }+ ws.send(JSON.stringify({ id: msg.id, result: { thread: { id, name: threads.get(id) } } }))+ }+ })+}++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-appserver-'))+ sock = path.join(dir, 'app-server-control.sock')+ server = http.createServer()+ wss = new WebSocketServer({ server })+ wss.on('connection', handle)+ await new Promise<void>((resolve) => server.listen(sock, resolve))+})++afterAll(async () => {+ await new Promise<void>((resolve) => wss.close(() => resolve()))+ await new Promise<void>((resolve) => server.close(() => resolve()))+ fs.rmSync(dir, { recursive: true, force: true })+})++describe('codexThreadExistsAt', () => {+ it('confirms a thread the app-server knows', async () => {+ expect(await codexThreadExistsAt(sock, 'thread-known')).toBe(true)+ expect(await codexThreadExistsAt(sock, 'thread-nameless')).toBe(true)+ })++ it('refuses an id the app-server never heard of (the stale-session-id case)', async () => {+ // This is the whole point: the launcher's bind falls back to plain codex instead of exec'ing+ // a resume that dies with "no rollout found" where nothing can catch it.+ expect(await codexThreadExistsAt(sock, 'thread-from-a-past-life')).toBe(false)+ })++ it('refuses when the app-server is not running at all', async () => {+ expect(await codexThreadExistsAt(path.join(dir, 'nope.sock'), 'thread-known', 500)).toBe(false)+ })++ it('refuses an id that is not shaped like one, without opening a socket', async () => {+ expect(await codexThreadExistsAt(sock, '../../etc/passwd')).toBe(false)+ })++ it('refuses when the server will not initialize (a logged-out CLI)', async () => {+ initializeFails = true+ try {+ expect(await codexThreadExistsAt(sock, 'thread-known')).toBe(false)+ } finally {+ initializeFails = false+ }+ })+})++describe('readCodexSessionNameAt', () => {+ it("reads the thread's own name", async () => {+ expect(await readCodexSessionNameAt(sock, 'thread-known')).toBe('Named by codex')+ })++ it('answers null for a nameless or unknown thread, and for a dead server', async () => {+ // Null means "the node keeps its own title" — never a wrong one.+ expect(await readCodexSessionNameAt(sock, 'thread-nameless')).toBeNull()+ expect(await readCodexSessionNameAt(sock, 'thread-from-a-past-life')).toBeNull()+ expect(await readCodexSessionNameAt(path.join(dir, 'nope.sock'), 'thread-known', 500)).toBeNull()+ })+})++describe('codexUnixWebSocketUrl', () => {+ it('refuses a socket path that could not survive being put in a URL', () => {+ expect(() => codexUnixWebSocketUrl('relative/app-server.sock')).toThrow()+ expect(() => codexUnixWebSocketUrl('/tmp/with space/app.sock')).toThrow()+ expect(() => codexUnixWebSocketUrl('/tmp/a?b/app.sock')).toThrow()+ })+})diff --git a/src/core/codex-session-name.ts b/src/core/codex-session-name.tsindex 014c07f17..4610d9b21 100644--- a/src/core/codex-session-name.ts+++ b/src/core/codex-session-name.ts@@ -16,12 +16,14 @@import { homedir } from 'os'import path from 'path'import { WebSocket } from 'ws'+// Minting a thread is a multi-step conversation with a typically COLD server, so it needs a real+// budget — and the hook route serving it must raise its socket guard to match (handleCodexThread).+// Shared with the launcher's client budget so the two cannot drift apart.+import { CODEX_THREAD_START_TIMEOUT_MS } from './codex-identity-proxy'const SAFE_THREAD_ID = /^[A-Za-z0-9._-]+$/const CACHE_MS = 3_000const REQUEST_TIMEOUT_MS = 2_000-/** Minting a thread is a multi-step conversation with a cold server; it needs a real budget. */-const START_TIMEOUT_MS = 20_000const names = new Map<string, { name: string | null; at: number }>()const inflight = new Map<string, Promise<string | null>>()@@ -45,17 +47,6 @@ function connectCodexAppServer(socketPath: string): WebSocket {return new WebSocket(codexUnixWebSocketUrl(socketPath), { perMessageDeflate: false })}-/** Seed the name cache from a name we were handed out of band (a hook, a bind). */-export function rememberCodexSessionName(- threadId: string,- name: unknown,- socketPath = defaultCodexAppServerSocket()-): void {- if (!threadId) return- const value = typeof name === 'string' && name.trim() ? name.trim() : null- names.set(`${socketPath}\0${threadId}`, { name: value, at: Date.now() })-}-export function readCodexSessionNameAt(socketPath: string,threadId: string,@@ -121,6 +112,84 @@ export function readCodexSessionNameAt(})}+/**+ * Does the shared app-server actually know this thread?+ *+ * The bind route writes a record claiming a node owns a conversation. Without this check ANY+ * id the caller hands us binds happily — a stale session id, or one persisted from a+ * plain-codex-era session that the app-server has never heard of — and the launcher then execs+ * `codex --remote unix:// resume <id>`, which dies with "no rollout found" AFTER exec, where+ * there is no fallback left. Asking first turns that dead node into an ordinary fallback.+ *+ * A server we cannot reach answers `false`, which is the safe direction here: refusing costs a+ * plain codex session, accepting costs the node.+ */+export function codexThreadExistsAt(+ socketPath: string,+ threadId: string,+ timeoutMs = REQUEST_TIMEOUT_MS+): Promise<boolean> {+ if (!SAFE_THREAD_ID.test(threadId)) return Promise.resolve(false)+ return new Promise((resolve) => {+ let settled = false+ let ws: WebSocket+ const finish = (exists: boolean): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ try {+ ws.close()+ } catch {+ /* the connection may never have opened */+ }+ resolve(exists)+ }+ const timer = setTimeout(() => finish(false), timeoutMs)+ timer.unref?.()+ try {+ ws = connectCodexAppServer(socketPath)+ } catch {+ clearTimeout(timer)+ resolve(false)+ return+ }+ ws.once('open', () => {+ ws.send(+ JSON.stringify({+ id: 1,+ method: 'initialize',+ params: { clientInfo: { name: 'nodeterm', version: '1' } }+ })+ )+ })+ ws.on('message', (raw) => {+ let message: Record<string, any>+ try {+ message = JSON.parse(raw.toString())+ } catch {+ return+ }+ if (message.id === 1) {+ if (message.error) return finish(false)+ ws.send(JSON.stringify({ method: 'initialized' }))+ ws.send(+ JSON.stringify({ id: 2, method: 'thread/read', params: { threadId, includeTurns: false } })+ )+ } else if (message.id === 2) {+ // The id must come back UNCHANGED: a server that answers with some other thread has not+ // confirmed the one we asked about.+ finish(!message.error && message.result?.thread?.id === threadId)+ }+ })+ ws.once('error', () => finish(false))+ ws.once('close', () => finish(false))+ })+}++export function codexThreadExists(threadId: string): Promise<boolean> {+ return codexThreadExistsAt(defaultCodexAppServerSocket(), threadId)+}+/*** Create one new, immediately RESUMABLE thread on the shared app-server and return its id.*@@ -134,7 +203,7 @@ export function readCodexSessionNameAt(export function startCodexThreadAt(socketPath: string,cwd: string,- timeoutMs = START_TIMEOUT_MS+ timeoutMs = CODEX_THREAD_START_TIMEOUT_MS): Promise<string> {if (!path.isAbsolute(cwd) || cwd.includes('\0')) {return Promise.reject(new Error('Unsupported Codex thread cwd'))@@ -330,8 +399,3 @@ export function readCodexSessionName(inflight.set(key, request)return request}--export function forgetCodexSessionNames(): void {- names.clear()- inflight.clear()-}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 7cd350453..1e3041bde 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -53,7 +53,11 @@ import { claudeConfigDirFor } from './claude-config-dir'import { findExecutableSync, findInPathString, resolveShellPath, shellPathNow } from './exec-path'import { AUTH_ENV_STRIP, accountTmuxEnvArgs, remoteAccountConfigDirAbs } from './claude-accounts-core'import { presenceHub } from './presence/hub'-import { codexLauncherDir, installCodexLauncher } from './codex-identity-proxy'+import {+ codexLauncherDir,+ forgetCodexThreadIdentitiesForNode,+ installCodexLauncher+} from './codex-identity-proxy'import { hasSharedIdentity, type AgentId } from '../shared/agents/config'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which@@ -3014,6 +3018,10 @@ export class PtyManager {// OLD cwd's session, and the respawn is a cold start (`fresh`), so replaying it would paint the// pre-move terminal into the new one.await deleteScrollback(persistKey)+ // Same hook, same reason: a permanently deleted node's Codex thread records must go with it.+ // Left behind they accumulate one file per thread forever, and the hook prelude keeps+ // re-exporting a dead node's id into any tool shell that still carries that thread id.+ forgetCodexThreadIdentitiesForNode(persistKey)if (sshRemote) {// Remote (ssh-project) node: end the REMOTE session.const ssh = findSsh()diff --git a/src/main/index.ts b/src/main/index.tsindex 7e7b6eb21..f6a5bfbc6 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -130,7 +130,7 @@ import {setCodexThreadIdentityAuthSecret,writeCodexThreadIdentity} from '../core/codex-identity-proxy'-import { startCodexThread } from '../core/codex-session-name'+import { codexThreadExists, startCodexThread } from '../core/codex-session-name'import { loadOrCreateCodexNodeAuthSecret } from './codex-node-auth-secret'import { claudeConfigDirFor } from '../core/claude-config-dir'import {@@ -916,7 +916,11 @@ app.whenReady().then(async () => {} catch (error) {console.error('[codex-identity] unavailable; Codex nodes run plain codex:', error)}- // Installs the launcher and answers the renderer's construction-time question.+ // Installs the launcher and publishes the construction-time answer. MUST stay after the secret+ // above and before the window: it is what unblocks `codexIdentityCaps()`, which the renderer's+ // first Codex launch line waits on. Reordering it later only delays that answer now (callers+ // wait rather than being told "no"), but leaving it out entirely would stall them until their+ // own timeout, so it is not optional.refreshCodexIdentityCaps()hookServer.setCodexIdentityListener((ev) => sendToMain(IPC.codexIdentity, ev))// A node still on a canvas is "live". A thread whose recorded owner is gone (node deleted, or a@@ -929,6 +933,14 @@ app.whenReady().then(async () => {return threadId})hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, hookEndpoint }) => {+ // Ask the app-server whether this conversation exists BEFORE recording that a node owns it.+ // The id reaching us is whatever the node persisted — it can be stale, or from a session that+ // ran under plain codex and the shared server has never heard of. Binding it anyway writes a+ // record and then execs `codex --remote unix:// resume <id>`, which dies with "no rollout+ // found" AFTER exec, where nothing can fall back any more. Refusing here IS the fallback.+ if (!(await codexThreadExists(threadId))) {+ throw new Error('Codex thread is unknown to the shared app-server')+ }bindCodexThreadIdentity(threadId, nodeId, hookEndpoint, codexNodeIsLive)})// SSH_ASKPASS relay (ssh-project.ts): lets the ControlMaster, which has no tty, route adiff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 4bf0cfb90..85ee29943 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -9,6 +9,16 @@ import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileCoimport { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@shared/agents/hook-events'import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'import { buildManagedScript } from '../../core/agents/hooks/managed-script'++/**+ * Remote hook scripts get NO Codex thread-identity root.+ *+ * The default root is THIS machine's data dir, and baking it into a script written to someone+ * else's host puts a path like `/Users/<you>/Library/Application Support/…` on that host — inert+ * (nothing there can read it) but a needless leak of the desktop's layout. Shared identity for SSH+ * hosts is a later slice; when it lands, this becomes the REMOTE host's root, not null.+ */+const REMOTE_IDENTITY_ROOT = nullimport { buildManagedHookCommand, mergeManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'import {buildCodexHooksAndTrust,@@ -131,7 +141,7 @@ export class RemoteHooks {const config = `${home}/${t.config}`await this.r.run(childArgs(conn, controlPath, `mkdir -p ${remoteDir}/agent-hooks && cat > ${script} && chmod 755 ${script}`),- buildManagedScript(t.agentId)+ buildManagedScript(t.agentId, REMOTE_IDENTITY_ROOT))const { stdout: cfgRaw } = await this.r.run(childArgs(conn, controlPath, `cat ${config} 2>/dev/null || echo '{}'`))let cfg: HookSettings = {}@@ -187,7 +197,7 @@ export class RemoteHooks {controlPath,`mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`),- buildManagedScript('codex')+ buildManagedScript('codex', REMOTE_IDENTITY_ROOT))const command = buildCodexManagedCommand(script)const codexHome = `${home}/.codex`@@ -286,7 +296,7 @@ export class RemoteHooks {controlPath,`mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`),- buildManagedScript('grok')+ buildManagedScript('grok', REMOTE_IDENTITY_ROOT))// `|| echo '{}'` fires ONLY when the file is missing — still the read that distinguishes a// missing file from an unreadable one. An unreadable one is then HEALED, not preserved: this@@ -337,7 +347,7 @@ export class RemoteHooks {// Idempotently (re)write the shared hook script — setup() may not have run (fail-open) yet.await this.r.run(childArgs(conn, controlPath, `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`),- buildManagedScript('claude')+ buildManagedScript('claude', REMOTE_IDENTITY_ROOT))const { stdout: cfgRaw } = await this.r.run(childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)diff --git a/src/renderer/state/codexIdentity.ts b/src/renderer/state/codexIdentity.tsindex 6584958ca..df97e5705 100644--- a/src/renderer/state/codexIdentity.ts+++ b/src/renderer/state/codexIdentity.ts@@ -67,7 +67,6 @@ export type CodexIdentityMode = 'shared' | 'plain'interface CodexIdentityState {byId: Record<string, { mode: CodexIdentityMode; reason?: string }>setMode(nodeId: string, mode: CodexIdentityMode, reason?: string): void- clear(nodeId: string): void}export const useCodexIdentity = create<CodexIdentityState>((set) => ({@@ -77,13 +76,6 @@ export const useCodexIdentity = create<CodexIdentityState>((set) => ({const prev = s.byId[nodeId]if (prev?.mode === mode && prev.reason === reason) return sreturn { byId: { ...s.byId, [nodeId]: { mode, reason } } }- }),- clear: (nodeId) =>- set((s) => {- if (!(nodeId in s.byId)) return s- const byId = { ...s.byId }- delete byId[nodeId]- return { byId }})}))