Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(codex): shared per-account identity for codex nodes, with a plain-codex fallback
enes0d5a6a6c11d5
diff --git a/src/core/agent-session-name.test.ts b/src/core/agent-session-name.test.tsindex df24930fa..ee71b612d 100644--- a/src/core/agent-session-name.test.ts+++ b/src/core/agent-session-name.test.ts@@ -28,10 +28,20 @@ describe('readAgentSessionName', () => {rememberGrokSessionDir('shared-id', path.join(root, 'gs1'))expect(await readAgentSessionName('shared-id', undefined, 'claude')).toBeNull()expect(await readAgentSessionName('shared-id')).toBeNull()- expect(await readAgentSessionName('shared-id', undefined, 'codex')).toBeNull()forgetGrokSession('shared-id')})+ it("routes codex to its app-server reader, never to claude's transcript scan", async () => {+ // codex's name lives in the shared app-server's Thread.name — there is no file to find. With+ // no server listening the honest answer is null; what matters is that it did not fall through+ // to claude's resolver, which SCANS ~/.claude/projects on a cache miss (once a minute, per+ // node, for a guaranteed miss) and can hand back a stranger's session name via its cwd leg.+ process.env.CODEX_HOME = path.join(root, 'no-such-codex-home')+ expect(await readAgentSessionName('thread-1', undefined, 'codex')).toBeNull()+ expect(await readAgentSessionName('thread-1', 'acct-2', 'codex')).toBeNull()+ delete process.env.CODEX_HOME+ })+it('answers null for an empty session id without asking either reader', async () => {expect(await readAgentSessionName('', undefined, 'grok')).toBeNull()expect(await readAgentSessionName('')).toBeNull()diff --git a/src/core/agent-session-name.ts b/src/core/agent-session-name.tsindex c9e0e24ed..461f276ea 100644--- a/src/core/agent-session-name.ts+++ b/src/core/agent-session-name.ts@@ -11,11 +11,15 @@// grok → `summary.json` in the session directory a hook told us about (core/grok-session.ts)// gemini → its own transcript `.jsonl`, at the path the context tail already tracks, read for the// `update_topic` tool call that carries the name (core/gemini-session.ts)+// codex → `Thread.name`, read over the shared app-server's own socket (core/codex-session-name.ts).+// There is no file to read: with the shared server the name lives in the server, and the+// node's session id IS the thread id.// Anything else has no readable session name; the claude reader answers null for it, which is what// every pre-grok caller already got.import { readSessionName, readSmallTail, TITLE_TAIL_BYTES } from './transcript-reader'import { readGrokSessionName } from './grok-session'import { pickGeminiTitle } from './gemini-session'+import { readCodexSessionName } from './codex-session-name'/*** Per-agent associations this router cannot own itself, injected by the shell.@@ -69,5 +73,8 @@ export function readAgentSessionName(if (!sessionId) return Promise.resolve(null)if (agentId === 'grok') return readGrokSessionName(sessionId)if (agentId === 'gemini') return readGeminiSessionName(sessionId, deps?.geminiPathFor)+ // Never falls through to claude's reader: that one SCANS ~/.claude/projects on a cache miss, so+ // an unrouted codex node would pay that scan once a minute for a guaranteed null.+ if (agentId === 'codex') return readCodexSessionName(sessionId)return readSessionName(sessionId, accountId)}diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex e04d3bd2b..41f3841d8 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -1,10 +1,11 @@import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'-import { randomUUID, timingSafeEqual } from 'crypto'+import { createHmac, randomUUID, timingSafeEqual } from 'crypto'import { writeFileSync, mkdirSync } from 'fs'import path from 'path'import { platform } from '../platform'-import { canControlCanvas, type AgentId } from '../../shared/agents/config'+import { canControlCanvas, hasSharedIdentity, type AgentId } from '../../shared/agents/config'import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'+import type { CodexIdentityEvent } from '../../shared/types'export const NODETERM_HOOK_PROTOCOL_VERSION = '1'const SLOWLORIS_MS = 2000@@ -125,7 +126,20 @@ class HookServer {private contextLinkHandler:| ((req: { verb: string; nodeId: string; args: Record<string, string> }) => Promise<string>)| null = null+ /**+ * The shared-identity spine's handlers (see core/codex-identity-proxy.ts). Both are injected by+ * the shell, and BOTH routes below additionally require a per-node capability — see+ * `codexNodeAuthToken`.+ */+ private codexThreadStartHandler:+ | ((req: { nodeId: string; cwd: string; hookEndpoint: string }) => Promise<string>)+ | null = null+ private codexThreadBindHandler:+ | ((req: { nodeId: string; threadId: string; hookEndpoint: string }) => Promise<void>)+ | null = null+ private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = nullprivate endpointPath = ''+ private codexNodeAuthSecret: Buffer | null = nullendpointFilePath(): string {if (!this.endpointPath) this.endpointPath = path.join(platform().userDataDir, 'hook-endpoint.env')@@ -160,6 +174,48 @@ class HookServer {this.contextLinkHandler = cb}+ setCodexThreadStartHandler(cb: NonNullable<HookServer['codexThreadStartHandler']>): void {+ this.codexThreadStartHandler = cb+ }++ setCodexThreadBindHandler(cb: NonNullable<HookServer['codexThreadBindHandler']>): void {+ this.codexThreadBindHandler = cb+ }++ /** Where a node's identity mode goes on its way to the UI (both shells forward it). */+ setCodexIdentityListener(cb: (e: CodexIdentityEvent) => void): void {+ this.codexIdentityListener = cb+ }++ /**+ * Mint the capability a Codex process must present for node-scoped identity operations.+ *+ * THIS IS THE SECURITY FIX. The global hook bearer proves only "this request came from some+ * NodeTerm-spawned session"; it cannot prove WHICH session. Every identity route takes a+ * caller-supplied `nodeId`, so with the shared bearer alone any agent session could bind ITS+ * OWN codex thread to a SIBLING node — reparenting another node's status, and (through the hook+ * prelude, which re-exports the recorded node id and endpoint) aiming that node's hook traffic.+ * This token is HMAC(secret, nodeId): stable across app restarts, scoped to one node, injected+ * only into that node's session env, and never written to the shared endpoint file that every+ * session can read.+ */+ codexNodeAuthToken(nodeId: string): string {+ if (!/^[A-Za-z0-9._-]+$/.test(nodeId)) return ''+ if (!this.codexNodeAuthSecret)+ throw new Error('NodeTerm Codex node authentication is unavailable')+ return createHmac('sha256', this.codexNodeAuthSecret).update(nodeId).digest('base64url')+ }++ /** The shell injects a keychain-backed, restart-stable secret before any Codex PTY is created. */+ setCodexNodeAuthSecret(secret: Uint8Array): void {+ if (secret.byteLength < 32) throw new Error('Invalid NodeTerm Codex node-auth secret')+ this.codexNodeAuthSecret = Buffer.from(secret)+ }++ hasCodexNodeAuth(): boolean {+ return !!this.codexNodeAuthSecret+ }+async start(): Promise<void> {if (this.server) returnthis.token = randomUUID()@@ -178,6 +234,10 @@ class HookServer {}req.setTimeout(SLOWLORIS_MS, () => req.destroy())const reqUrl = new URL(req.url ?? '/', 'http://127.0.0.1')+ if (reqUrl.pathname.startsWith('/codex-thread/')) {+ await this.handleCodexThread(reqUrl.pathname, req, res)+ return+ }if (reqUrl.pathname.startsWith('/control/')) {const verb = decodeURIComponent(reqUrl.pathname.replace(/^\/control\//, ''))const { nodeId, args } = parseControlBody(@@ -289,6 +349,105 @@ class HookServer {return a.length === b.length && timingSafeEqual(a, b)}+ private codexNodeTokenMatches(nodeId: string, provided: string | string[] | undefined): boolean {+ if (typeof provided !== 'string') return false+ let expected = ''+ try {+ expected = this.codexNodeAuthToken(nodeId)+ } catch {+ return false+ }+ if (!expected) return false+ const a = Buffer.from(provided)+ const b = Buffer.from(expected)+ return a.length === b.length && timingSafeEqual(a, b)+ }++ /**+ * `/codex-thread/{start,bind,fallback}`.+ *+ * start/bind are the identity spine and require the per-node capability on top of the shared+ * bearer. `fallback` deliberately does NOT: it is the launcher telling us it gave up and is+ * running plain codex, it grants nothing, and requiring a token there would silence the report+ * in exactly the case (no token) it exists to surface.+ */+ private async handleCodexThread(+ pathname: string,+ req: IncomingMessage,+ res: ServerResponse+ ): Promise<void> {+ const verb = pathname.replace(/^\/codex-thread\//, '')+ const form = parseForm(await readBody(req))+ const nodeId = form.nodeId ?? ''+ if (!/^[A-Za-z0-9._-]+$/.test(nodeId)) {+ res.writeHead(400)+ res.end()+ return+ }+ if (verb === 'fallback') {+ // 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 })+ res.writeHead(204)+ res.end()+ return+ }+ if (verb !== 'start' && verb !== 'bind') {+ res.writeHead(404)+ res.end()+ return+ }+ if (!this.codexNodeTokenMatches(nodeId, req.headers['x-nodeterm-node-token'])) {+ res.writeHead(403)+ res.end()+ return+ }+ if (verb === 'start') {+ const cwd = form.cwd ?? ''+ if (!path.isAbsolute(cwd)) {+ res.writeHead(400)+ res.end()+ return+ }+ try {+ if (!this.codexThreadStartHandler) throw new Error('start handler unavailable')+ const threadId = await this.codexThreadStartHandler({+ nodeId,+ cwd,+ hookEndpoint: this.endpointFilePath()+ })+ if (!/^[A-Za-z0-9._-]+$/.test(threadId)) throw new Error('invalid thread id')+ this.codexIdentityListener?.({ nodeId, mode: 'shared' })+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })+ res.end(`${threadId}\n`)+ } catch {+ res.writeHead(503)+ res.end()+ }+ return+ }+ const threadId = form.threadId ?? ''+ if (!/^[A-Za-z0-9._-]+$/.test(threadId)) {+ res.writeHead(400)+ res.end()+ return+ }+ try {+ if (!this.codexThreadBindHandler) throw new Error('bind handler unavailable')+ await this.codexThreadBindHandler({+ nodeId,+ threadId,+ hookEndpoint: this.endpointFilePath()+ })+ this.codexIdentityListener?.({ nodeId, mode: 'shared' })+ res.writeHead(204)+ res.end()+ } catch {+ res.writeHead(409)+ res.end()+ }+ }+// The managed script sources this file at invocation to get the LIVE port/token.// tmux sessions outlive the app, so env-baked coords go stale after a restart.private writeEndpointFile(): void {@@ -321,7 +480,12 @@ class HookServer {NODETERM_NODE_ID: nodeId,NODETERM_AGENT_ID: agentId,...(permWaitSecs > 0 ? { NODETERM_PERM_WAIT_SECS: String(permWaitSecs) } : {}),- ...(canControlCanvas(agentId) ? { NODETERM_CANVAS_CONTROL: '1' } : {})+ ...(canControlCanvas(agentId) ? { NODETERM_CANVAS_CONTROL: '1' } : {}),+ // The per-node capability for the identity routes. Gated by the CAPABILITY LIST, never by+ // `agentId === 'codex'`. No secret ⇒ no token ⇒ the launcher falls back to plain codex.+ ...(hasSharedIdentity(agentId) && this.codexNodeAuthSecret+ ? { NODETERM_CODEX_NODE_TOKEN: this.codexNodeAuthToken(nodeId) }+ : {})}}diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex 594c49a25..c87dc0858 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -92,6 +92,26 @@ describe('buildManagedScript', () => {})})+ describe('the Codex thread-identity prelude', () => {+ // It is prepended for EVERY agent, not just codex — the generated scripts all change. That is+ // intended: the block is inert without CODEX_THREAD_ID, which no other agent's tool shell+ // sets, and one builder beats a codex-only fork of it. (Its behavior is exercised for real+ // under /bin/sh in core/codex-thread-identity-sh.test.ts.)+ it('is present in every agent script when an identity root is known', () => {+ for (const agent of ['claude', 'codex', 'gemini', 'grok', 'opencode']) {+ expect(buildManagedScript(agent, '/data/codex-thread-nodes')).toContain(+ "nt_codex_map='/data/codex-thread-nodes'/\"$CODEX_THREAD_ID\""+ )+ }+ })++ it('is omitted entirely when there is no identity root, leaving the legacy script', () => {+ const legacy = buildManagedScript('claude', null as unknown as string)+ expect(legacy).not.toContain('CODEX_THREAD_ID')+ expect(legacy.split('\n')[1]).toBe('if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then')+ })+ })+describe('endpoint failover (dead-primary retry against a live sibling endpoint)', () => {it('lists the three known candidate endpoint files', () => {expect(s).toContain('"$HOME/.nodeterm-server/hook-endpoint.env"')diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 138df6347..04840b26e 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -47,9 +47,30 @@// NEEDS YOU badge flips to working immediately rather than lingering until the agent's next hook. The// whole branch is a NO-OP when the env var is absent (a user's own terminals, older// nodeterm, non-claude agents), so behavior is bit-for-bit legacy there.-export function buildManagedScript(agentId: string): string {+/**+ * `identityRoot` is where the Codex thread → node records live (`codexThreadIdentityRoot()`).+ * It is a PARAMETER because this builder is also called from tests that never boot a platform,+ * and because the prelude has to bake the path in — the shell it runs in has no idea where the+ * app's data dir is. Undefined (no platform yet) ⇒ no prelude, i.e. today's script exactly.+ *+ * The prelude is prepended for EVERY agent, not just codex. 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.+ */+import { codexThreadIdentityResolverSh } from '../../codex-thread-identity-sh'+import { codexThreadIdentityRoot } from '../../codex-identity-proxy'++function safeIdentityRoot(): string | null {+ try {+ return codexThreadIdentityRoot()+ } catch {+ return null+ }+}++export function buildManagedScript(agentId: string, identityRoot = safeIdentityRoot()): string {return ['#!/bin/sh',+ ...(identityRoot ? [codexThreadIdentityResolverSh(identityRoot)] : []),'if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then',' . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :','fi',diff --git a/src/core/codex-identity-caps.ts b/src/core/codex-identity-caps.tsnew file mode 100644index 000000000..452d1ddc1--- /dev/null+++ b/src/core/codex-identity-caps.ts@@ -0,0 +1,45 @@+/**+ * "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.+ *+ * 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+ * launcher would fall back anyway, one process later), and+ * 2. the generated launcher could actually be written (a read-only or full data dir is a real+ * failure mode, and it is the one the renderer cannot see at all).+ *+ * SERVER EDITION: `src/server` deliberately registers this and answers `false` — see the comment+ * at its registration site. That is what makes "Server Edition runs plain codex" a decision rather+ * than an accident.+ */+import { IPC } from '../shared/ipc'+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++/** Recompute now. Called at wiring time and again whenever the launcher is (re)installed. */+export function refreshCodexIdentityCaps(): CodexIdentityCaps {+ const launcher = codexThreadIdentityAvailable() ? installCodexLauncher() : null+ cached = { shared: !!launcher, launcherPath: launcher }+ return cached+}++export function codexIdentityCaps(): CodexIdentityCaps {+ return cached ?? UNKNOWN_CODEX_IDENTITY_CAPS+}++/** Wire the answer onto the platform's RPC surface (Electron ipcMain / server WS-RPC alike). */+export function registerCodexIdentityIpc(answer: () => CodexIdentityCaps = codexIdentityCaps): void {+ platform().handle(IPC.codexIdentityCaps, () => answer())+}++export function resetCodexIdentityCapsForTests(): void {+ cached = null+}diff --git a/src/core/codex-identity-proxy.test.ts b/src/core/codex-identity-proxy.test.tsnew file mode 100644index 000000000..8c4c08e15--- /dev/null+++ b/src/core/codex-identity-proxy.test.ts@@ -0,0 +1,119 @@+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 {+ bindCodexThreadIdentity,+ codexLauncherDir,+ codexThreadIdentityRoot,+ installCodexLauncher,+ readCodexThreadIdentity,+ resetCodexThreadIdentityAuthSecret,+ resolveCodexThreadNodeIdentity,+ setCodexThreadIdentityAuthSecret,+ writeCodexThreadIdentity+} from './codex-identity-proxy'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++let dir = ''+const live = (ids: string[]) => (id: string) => ids.includes(id)++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-identity-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ setCodexThreadIdentityAuthSecret(randomBytes(32))+})++afterEach(() => {+ resetCodexThreadIdentityAuthSecret()+ resetPlatformForTests()+ fs.rmSync(dir, { recursive: true, force: true })+})++describe('codex thread identity store', () => {+ it('lives under the platform data dir, not $HOME', () => {+ // The wrong seam is why the Server Edition had no story at all: `homedir()` is not where a+ // server keeps its state, and nothing behind CorePlatform can be swapped for it.+ expect(codexThreadIdentityRoot()).toBe(path.join(dir, 'codex-thread-nodes'))+ expect(codexLauncherDir()).toBe(path.join(dir, 'codex-bin'))+ })++ it('round-trips a record and resolves its owning node', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/hook-endpoint.env')+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBe('node-1')+ })++ it('ignores a record whose node id was rewritten (the signature no longer matches)', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/hook-endpoint.env')+ const file = path.join(codexThreadIdentityRoot(), 'thread-1')+ fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('node-1', 'node-evil'))+ // Not repaired, not trusted: the prelude re-exports both fields into an agent's environment,+ // so an attacker-writable record is an attacker-chosen hook target.+ expect(readCodexThreadIdentity('thread-1')).toBeUndefined()+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBeUndefined()+ })++ it('ignores an unsigned record', () => {+ fs.mkdirSync(codexThreadIdentityRoot(), { recursive: true })+ fs.writeFileSync(+ path.join(codexThreadIdentityRoot(), 'thread-1'),+ 'nodeId=node-1\nendpoint=/data/hook-endpoint.env\n'+ )+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBeUndefined()+ })++ it('refuses ids and endpoints that are not shaped like ids and endpoints', () => {+ expect(() => writeCodexThreadIdentity('../escape', 'node-1', '/data/e')).toThrow()+ expect(() => writeCodexThreadIdentity('thread-1', 'node 1; rm -rf /', '/data/e')).toThrow()+ expect(() => writeCodexThreadIdentity('thread-1', 'node-1', 'relative/e')).toThrow()+ })++ it('writes nothing at all without the auth secret', () => {+ resetCodexThreadIdentityAuthSecret()+ expect(() => writeCodexThreadIdentity('thread-1', 'node-1', '/data/e')).toThrow()+ expect(fs.existsSync(path.join(codexThreadIdentityRoot(), 'thread-1'))).toBe(false)+ })+})++describe('binding a thread to a node', () => {+ it('refuses to take a thread away from a node that is still live', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e')+ expect(() =>+ bindCodexThreadIdentity('thread-1', 'node-2', '/data/e', live(['node-1']))+ ).toThrow()+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBe('node-1')+ })++ it('re-claims a thread whose owner is gone', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e')+ bindCodexThreadIdentity('thread-1', 'node-2', '/data/e', live([]))+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBe('node-2')+ })++ it('is idempotent for the node that already owns it (a restart re-binds its own thread)', () => {+ writeCodexThreadIdentity('thread-1', 'node-1', '/data/e')+ bindCodexThreadIdentity('thread-1', 'node-1', '/data/e', live(['node-1']))+ expect(resolveCodexThreadNodeIdentity('thread-1')).toBe('node-1')+ })+})++describe('installCodexLauncher', () => {+ it('writes an executable launcher and answers with its path', () => {+ const file = installCodexLauncher()+ expect(file).toBe(path.join(codexLauncherDir(), 'nodeterm-codex'))+ expect(fs.statSync(file as string).mode & 0o777).toBe(0o700)+ })++ it('answers null instead of throwing when it cannot be written', () => {+ // A read-only data dir is a real failure mode, and null is what makes the caps probe say "no+ // shared identity" — which keeps every launch line on the bare `codex` instead of naming a+ // launcher that is not there.+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: path.join(dir, 'file-not-a-dir') }))+ fs.writeFileSync(path.join(dir, 'file-not-a-dir'), 'x')+ expect(installCodexLauncher()).toBeNull()+ })+})diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.tsnew file mode 100644index 000000000..c40323bae--- /dev/null+++ b/src/core/codex-identity-proxy.ts@@ -0,0 +1,352 @@+/**+ * Shared-identity spine for Codex canvas nodes.+ *+ * WHY: a Codex terminal node used to spawn a full `codex` process tree per node — one app-server+ * each. A canvas with a dozen Codex nodes paid a dozen servers' worth of RAM for one account. With+ * this, every node on a machine talks to ONE `codex app-server` and owns one THREAD inside it, and+ * the node ↔ thread mapping is what survives resumes, in-pane restarts and app restarts.+ *+ * The mapping is a tiny file per thread under `<userDataDir>/codex-thread-nodes/`. It is read by+ * generated POSIX sh (the hook prelude in `codex-thread-identity-sh.ts`), so it is a flat+ * `key=value` text file — parsed as DATA, never sourced.+ *+ * WHY IT IS SIGNED: the records name a node id and a hook endpoint, and the hook prelude+ * re-exports both into the agent's environment. An attacker who could write one of these files+ * could aim a session's hook traffic at a node (or an endpoint) of their choosing. Every record+ * therefore carries an HMAC over (threadId, nodeId, endpoint) keyed by the same restart-stable+ * secret the hook server uses to mint per-node capabilities (`src/main/codex-node-auth-secret.ts`).+ * Unsigned/mis-signed records are ignored, not repaired.+ *+ * ACCOUNT SCOPING is deliberately absent here: managed Codex accounts are a later slice. The+ * 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 path from 'path'+import { createHmac, timingSafeEqual } from 'crypto'+import { platform } from './platform'+import { posixQuote } from '../shared/ssh'++const SAFE_NODE_ID = /^[A-Za-z0-9._-]+$/+const SAFE_ENDPOINT = /^\/[A-Za-z0-9._/ -]+$/+const SAFE_THREAD_ID = /^[A-Za-z0-9._-]+$/++let identityAuthSecret: Buffer | null = null++/** Injected by the shell once, from the same keychain-backed secret the hook server signs with. */+export function setCodexThreadIdentityAuthSecret(secret: Uint8Array): void {+ if (secret.byteLength < 32) throw new Error('Invalid NodeTerm Codex identity-auth secret')+ identityAuthSecret = Buffer.from(secret)+}++/** Test-only: forget the injected secret so a suite can assert the unavailable path. */+export function resetCodexThreadIdentityAuthSecret(): void {+ identityAuthSecret = null+}++export function codexThreadIdentityAvailable(): boolean {+ return !!identityAuthSecret+}++/**+ * Where the thread → node records live. Through `CorePlatform`, NOT `homedir()`: this is state the+ * app owns, and the Server Edition's data dir is not `~`. The generated sh gets this exact path+ * baked in (quoted), so the two never disagree.+ */+export function codexThreadIdentityRoot(): string {+ return path.join(platform().userDataDir, 'codex-thread-nodes')+}++function identitySignature(threadId: string, nodeId: string, hookEndpoint: string): string {+ if (!identityAuthSecret) throw new Error('NodeTerm Codex identity authentication is unavailable')+ return createHmac('sha256', identityAuthSecret)+ .update(`${threadId}\0${nodeId}\0${hookEndpoint}`)+ .digest('base64url')+}++function signatureMatches(threadId: string, identity: CodexThreadIdentity): boolean {+ if (!identity.signature || !identityAuthSecret) return false+ let expected = ''+ try {+ expected = identitySignature(threadId, identity.nodeId, identity.hookEndpoint)+ } catch {+ return false+ }+ const actual = Buffer.from(identity.signature)+ const wanted = Buffer.from(expected)+ return actual.length === wanted.length && timingSafeEqual(actual, wanted)+}++export interface CodexThreadIdentity {+ nodeId: string+ hookEndpoint: string+ signature: string+}++export function validCodexIdentity(nodeId: string, hookEndpoint: string): boolean {+ return SAFE_NODE_ID.test(nodeId) && SAFE_ENDPOINT.test(hookEndpoint)+}++function identityFile(threadId: string, root = codexThreadIdentityRoot()): string {+ if (!SAFE_THREAD_ID.test(threadId)) throw new Error('Invalid NodeTerm Codex thread identity')+ return path.join(root, threadId)+}++function parseCodexThreadIdentity(raw: string): CodexThreadIdentity {+ const values: Record<string, string> = {}+ for (const line of raw.split('\n')) {+ const separator = line.indexOf('=')+ if (separator < 1) continue+ values[line.slice(0, separator)] = line.slice(separator + 1)+ }+ return {+ nodeId: values.nodeId ?? '',+ hookEndpoint: values.endpoint ?? '',+ signature: values.signature ?? ''+ }+}++/** The record for a thread, or undefined when it is absent, malformed or badly signed. */+export function readCodexThreadIdentity(+ threadId: string,+ root = codexThreadIdentityRoot()+): CodexThreadIdentity | undefined {+ if (!SAFE_THREAD_ID.test(threadId)) return undefined+ let raw: string+ try {+ raw = readFileSync(path.join(root, threadId), 'utf8')+ } catch {+ return undefined+ }+ const identity = parseCodexThreadIdentity(raw)+ if (!validCodexIdentity(identity.nodeId, identity.hookEndpoint)) return undefined+ if (!signatureMatches(threadId, identity)) return undefined+ return identity+}++/**+ * Recover a thread's owning node after the app restarts. tmux sessions outlive the app, so a+ * running Codex client can outlive every in-memory map we hold; the file is the only thing that+ * still knows which node it belongs to.+ */+export function resolveCodexThreadNodeIdentity(+ threadId: string,+ root = codexThreadIdentityRoot()+): string | undefined {+ return readCodexThreadIdentity(threadId, root)?.nodeId+}++/** Write (or replace) the record for `threadId`, atomically. */+export function writeCodexThreadIdentity(+ threadId: string,+ nodeId: string,+ hookEndpoint: string,+ root = codexThreadIdentityRoot()+): void {+ if (!SAFE_THREAD_ID.test(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {+ throw new Error('Invalid NodeTerm Codex thread identity')+ }+ const signature = identitySignature(threadId, nodeId, hookEndpoint)+ const file = identityFile(threadId, root)+ const tmp = path.join(root, `.${threadId}.${process.pid}.${Date.now()}`)+ mkdirSync(root, { recursive: true, mode: 0o700 })+ let renamed = false+ try {+ writeFileSync(tmp, `nodeId=${nodeId}\nendpoint=${hookEndpoint}\nsignature=${signature}\n`, {+ encoding: 'utf8',+ mode: 0o600+ })+ renameSync(tmp, file)+ renamed = true+ } finally {+ if (!renamed) {+ try {+ unlinkSync(tmp)+ } catch {+ /* best effort */+ }+ }+ }+}++/**+ * One canvas node owns one Codex conversation, and one conversation belongs to one node. A resume+ * that would steal a thread from a node that is still LIVE is refused — the caller (the launcher)+ * then falls back to a plain `codex`, which is a working session rather than two clients fighting+ * over one thread. A STALE owner (node deleted, app restarted without it) is simply replaced.+ */+export function bindCodexThreadIdentity(+ threadId: string,+ nodeId: string,+ hookEndpoint: string,+ isNodeLive: (nodeId: string) => boolean,+ root = codexThreadIdentityRoot()+): void {+ if (!SAFE_THREAD_ID.test(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {+ throw new Error('Invalid NodeTerm Codex thread identity')+ }+ const existing = readCodexThreadIdentity(threadId, root)+ if (existing && existing.nodeId !== nodeId && isNodeLive(existing.nodeId)) {+ throw new Error('Codex thread is already bound to another live node')+ }+ if (existing && existing.nodeId === nodeId && existing.hookEndpoint === hookEndpoint) return+ 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+ try {+ unlinkSync(path.join(root, threadId))+ } catch {+ /* nothing to forget */+ }+}++export function codexLauncherDir(): string {+ return path.join(platform().userDataDir, 'codex-bin')+}++export const CODEX_LAUNCHER_NAME = 'nodeterm-codex'++export function codexLauncherPath(): string {+ return path.join(codexLauncherDir(), CODEX_LAUNCHER_NAME)+}++/**+ * The generated launcher.+ *+ * EVERY failure path here ends in `exec codex "$@"` — the caller's arguments untouched. That is+ * the owner's decision and it follows the repo's own precedent (`gatePermissionMode`: an unknown+ * or failed probe degrades to the bare command, never to a blocked launch). The upstream version+ * of this script exited 69 "identity unavailable", which turns a missing app-server, an older+ * `codex`, a stale tmux session or a locked-down `$HOME` into a DEAD node.+ *+ * The fallback is not silent: before exec'ing plain codex the script POSTs `/codex-thread/fallback`+ * with a machine-readable reason, and the desktop marks the node. Nothing is ever written into the+ * pane — text injected into an agent's terminal is prompt injection, which this repo forbids.+ *+ * `appServerStartCommand` is injected so the test suite can run this script for real under+ * `/bin/sh` (the discipline `canvas-control-shim.test.ts` and `remote-claude-usage.test.ts` set).+ */+export function buildCodexLauncherScript(+ appServerStartCommand = 'codex app-server daemon start >/dev/null 2>&1'+): string {+ return `#!/bin/sh+# Generated by NodeTerm. Do not edit — it is rewritten on every launch.+# Runs a Codex session against the ONE shared app-server, bound to this canvas node's thread.+# Anything missing => plain 'codex' with the same arguments. A node that cannot get a managed+# identity must still be a working node.++nt_reason=''+nt_fail() { nt_reason=$1; return 1; }++nt_hook_curl() { curl "$@"; }+if [ -n "\${NODETERM_HOOK_SOCK-}" ]; then+ case "$NODETERM_HOOK_SOCK" in+ /*) nt_hook_curl() { curl --unix-socket "$NODETERM_HOOK_SOCK" "$@"; } ;;+ *) nt_reason=broker-unreachable ;;+ esac+fi++# A path we are willing to source. Written with tr rather than a case bracket class because the+# endpoint lives under the app's data dir, which on macOS contains a space ("Application Support")+# — escaping a space inside a case pattern's bracket expression is exactly the kind of quoting+# that reads fine and matches nothing.+nt_safe_path() {+ case "\${1-}" in /*) ;; *) return 1 ;; esac+ [ "$(printf %s "$1" | tr -cd 'A-Za-z0-9._/ -')" = "$1" ]+}++# Runs in THIS shell, never a command substitution: it sources the endpoint file, and that file is+# what carries the live hook port/token. Sourcing it in a subshell would leave both unset here and+# every launch would "fall back" for the wrong reason.+nt_preflight() {+ case "\${NODETERM_NODE_ID-}" in ''|*[!A-Za-z0-9._-]*) nt_fail node-id-unavailable; return ;; esac+ nt_safe_path "\${NODETERM_HOOK_ENDPOINT-}" || { nt_fail hook-endpoint-unavailable; return; }+ [ -r "$NODETERM_HOOK_ENDPOINT" ] || { nt_fail hook-endpoint-unavailable; return; }+ . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || { nt_fail broker-unreachable; return; }+ case "\${NODETERM_HOOK_PORT-}" in ''|*[!0-9]*) nt_fail broker-unreachable; return ;; esac+ case "\${NODETERM_HOOK_TOKEN-}" in ''|*[!A-Za-z0-9-]*) nt_fail broker-unreachable; return ;; esac+ # The per-node capability. Absent => this build/shell has no managed identity to give.+ case "\${NODETERM_CODEX_NODE_TOKEN-}" in+ ''|*[!A-Za-z0-9_-]*) nt_fail node-token-unavailable; return ;;+ esac+ if [ "\${1-}" = resume ]; then+ case "\${2-}" in ''|*[!A-Za-z0-9._-]*) nt_fail thread-id-unavailable; return ;; esac+ fi+ ${appServerStartCommand} || { nt_fail app-server-unavailable; return; }+ return 0+}++# 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.+nt_report_fallback() {+ [ -n "\${NODETERM_HOOK_PORT-}" ] || return 0+ [ -n "\${NODETERM_HOOK_TOKEN-}" ] || return 0+ [ -n "\${NODETERM_NODE_ID-}" ] || return 0+ printf 'header = "X-NodeTerm-Hook-Token: %s"\\n' "$NODETERM_HOOK_TOKEN" |+ nt_hook_curl --silent --show-error --fail --max-time 3 --config - --request POST \\+ --data-urlencode "nodeId=$NODETERM_NODE_ID" \\+ --data-urlencode "reason=$1" \\+ "http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/fallback" >/dev/null 2>&1 || :+}++[ -n "$nt_reason" ] || nt_preflight "$@" || :+if [ -n "$nt_reason" ]; then+ nt_report_fallback "$nt_reason"+ exec codex "$@"+fi++nt_post() {+ printf '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 "$@"+}++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-}" \\+ "http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/bind" >/dev/null; then+ exec codex --remote unix:// "$@"+ fi+ nt_report_fallback thread-bind-refused+ exec codex "$@"+fi++nt_thread=$(nt_post --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+ ''|*[!A-Za-z0-9._-]*)+ nt_report_fallback thread-start-failed+ exec codex "$@"+ ;;+esac+exec codex --remote unix:// resume "$nt_thread" "$@"+`+}++/**+ * Write the launcher and return its path, or null when it could not be installed (read-only home,+ * no permission). Null is a first-class answer: it is what makes `codexIdentityCaps()` say "no"+ * and every launch line stay the bare `codex` it has always been.+ */+export function installCodexLauncher(): string | null {+ try {+ const dir = codexLauncherDir()+ const file = path.join(dir, CODEX_LAUNCHER_NAME)+ mkdirSync(dir, { recursive: true, mode: 0o700 })+ writeFileSync(file, buildCodexLauncherScript(), { encoding: 'utf8', mode: 0o700 })+ chmodSync(file, 0o700)+ return file+ } catch {+ 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.tsnew file mode 100644index 000000000..8e91d1933--- /dev/null+++ b/src/core/codex-launcher-sh.test.ts@@ -0,0 +1,216 @@+// The generated Codex launcher, run by the real /bin/sh against the real hook server.+//+// This script is source no compiler checks, it is the ONLY thing standing between a Codex node and+// a shell, and its most important job is the one that is hardest to assert on paper: FALLING BACK.+// Every branch below therefore runs for real, with a fake `codex` on PATH that records the argv it+// was exec'd with — because "did it fall back with the arguments intact?" is exactly the question+// a string assertion cannot answer. Same discipline as canvas-control-shim.test.ts and+// remote-claude-usage.test.ts.+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { execFile } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'+import { randomBytes } from 'node:crypto'+import { buildCodexLauncherScript } from './codex-identity-proxy'+import { hookServer } from './agents/hook-server'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++const run = promisify(execFile)++let dir = ''+let launcher = ''+let binDir = ''+let argvLog = ''+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 bindAnswer: (() => void) | null = null++/** A stand-in for the real `codex`, which records how it was invoked and exits 0. */+function writeFakeCodex(): void {+ fs.writeFileSync(+ path.join(binDir, 'codex'),+ `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}\nexit 0\n`,+ { mode: 0o755 }+ )+}++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-launcher-'))+ binDir = path.join(dir, 'bin')+ fs.mkdirSync(binDir)+ argvLog = path.join(dir, 'codex-argv.log')+ writeFakeCodex()+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ launcher = path.join(dir, 'nodeterm-codex')+ // `true` stands in for `codex app-server daemon start`; the "no app-server" case overrides it.+ fs.writeFileSync(launcher, buildCodexLauncherScript('true'), { mode: 0o755 })+ await hookServer.start()+ hookServer.setCodexNodeAuthSecret(randomBytes(32))+ hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd }) => {+ started.push({ nodeId, cwd })+ if (!startAnswer) throw new Error('start refused')+ return startAnswer()+ })+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId }) => {+ bound.push({ nodeId, threadId })+ if (!bindAnswer) throw new Error('bind refused')+ bindAnswer()+ })+ hookServer.setCodexIdentityListener((e) => {+ if (e.mode === 'plain') fallbacks.push({ nodeId: e.nodeId, reason: e.reason })+ })+})++afterAll(() => {+ hookServer.stop()+ resetPlatformForTests()+ fs.rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ started = []+ bound = []+ fallbacks = []+ startAnswer = () => 'thread-abc'+ bindAnswer = () => {}+ fs.writeFileSync(argvLog, '')+})++function baseEnv(): Record<string, string> {+ return {+ PATH: `${binDir}:${process.env.PATH ?? ''}`,+ HOME: dir,+ NODETERM_NODE_ID: 'node-1',+ NODETERM_HOOK_ENDPOINT: hookServer.endpointFilePath(),+ // buildPtyEnv injects these at spawn too. The endpoint FILE is still required (it carries the+ // live coordinates after an app restart), but their presence is why a node whose endpoint file+ // vanished can still report that it fell back.+ NODETERM_HOOK_PORT: String(hookServer.getPort()),+ NODETERM_HOOK_TOKEN: hookServer.getToken(),+ NODETERM_CODEX_NODE_TOKEN: hookServer.codexNodeAuthToken('node-1')+ }+}++function callLauncher(+ args: string[],+ env: Record<string, string> = {},+ script = launcher+): Promise<{ stdout: string; stderr: string }> {+ const merged = { ...baseEnv(), ...env }+ for (const [k, v] of Object.entries(merged)) if (v === '') delete (merged as any)[k]+ return run('/bin/sh', [script, ...args], { env: merged, cwd: dir })+}++/** What the fake `codex` was exec'd with, one line per invocation. */+function codexArgv(): string[] {+ return fs.readFileSync(argvLog, 'utf8').split('\n').slice(0, -1)+}++describe('generated Codex launcher', () => {+ it('is valid POSIX sh', async () => {+ await expect(run('/bin/sh', ['-n', launcher])).resolves.toBeTruthy()+ })++ it('starts a thread for a fresh node and resumes it on the shared app-server', async () => {+ await callLauncher([])+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-abc'])+ expect(fallbacks).toEqual([])+ })++ it('keeps the caller arguments after the thread it resolved', async () => {+ await callLauncher(['--ask-for-approval', 'never', 'fix the bug'])+ expect(codexArgv()).toEqual([+ '--remote unix:// resume thread-abc --ask-for-approval never fix the bug'+ ])+ })++ it('binds a caller-supplied thread on resume instead of starting a new one', async () => {+ await callLauncher(['resume', 'thread-xyz'])+ expect(bound).toEqual([{ nodeId: 'node-1', threadId: 'thread-xyz' }])+ expect(started).toEqual([])+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-xyz'])+ })+})++// Each case below is a way the managed identity can be unavailable on a real machine. The+// assertion is always the same pair: plain `codex` ran WITH THE ORIGINAL ARGUMENTS, and the+// desktop was told why. Upstream, every one of these exited 69 — a dead node.+describe('falls back to plain codex', () => {+ const cases: Array<[string, Record<string, string>, string]> = [+ ['no node id (a session nodeterm did not spawn)', { NODETERM_NODE_ID: '' }, 'node-id-unavailable'],+ [+ 'no hook endpoint',+ { NODETERM_HOOK_ENDPOINT: '' },+ 'hook-endpoint-unavailable'+ ],+ [+ 'hook endpoint points at nothing (app restarted, tmux session outlived it)',+ { NODETERM_HOOK_ENDPOINT: '/nonexistent/hook-endpoint.env' },+ 'hook-endpoint-unavailable'+ ],+ [+ 'no per-node capability token (secure storage unavailable)',+ { NODETERM_CODEX_NODE_TOKEN: '' },+ 'node-token-unavailable'+ ]+ ]++ for (const [name, env, reason] of cases) {+ it(`${name} → exec codex with the same args`, async () => {+ await callLauncher(['--ask-for-approval', 'never', 'do the thing'], env)+ expect(codexArgv()).toEqual(['--ask-for-approval never do the thing'])+ expect(started).toEqual([])+ // A node id is the ONLY thing the fallback report cannot be made without.+ if (env.NODETERM_NODE_ID === '') expect(fallbacks).toEqual([])+ else expect(fallbacks).toEqual([{ nodeId: 'node-1', reason }])+ })+ }++ it('an older codex with no app-server → plain codex, not a dead node', async () => {+ const noServer = path.join(dir, 'nodeterm-codex-no-server')+ fs.writeFileSync(noServer, buildCodexLauncherScript('false'), { mode: 0o755 })+ await callLauncher(['hello'], {}, noServer)+ expect(codexArgv()).toEqual(['hello'])+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'app-server-unavailable' }])+ })++ it('a thread owned by another live node → plain codex, never two clients on one thread', async () => {+ bindAnswer = null+ await callLauncher(['resume', 'thread-xyz'])+ expect(codexArgv()).toEqual(['resume thread-xyz'])+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'thread-bind-refused' }])+ })++ it('the app-server refusing to start a thread → plain codex', async () => {+ startAnswer = null+ await callLauncher([])+ expect(codexArgv()).toEqual([''])+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'thread-start-failed' }])+ })++ it('a resume with an unusable session id → plain codex, id left alone', async () => {+ await callLauncher(['resume', 'not a; thread'])+ expect(codexArgv()).toEqual(['resume not a; thread'])+ expect(bound).toEqual([])+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'thread-id-unavailable' }])+ })+})++describe('per-node capability (the authorization the shared bearer cannot give)', () => {+ 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')+ })+ // The route rejected it before the handler ran: no binding was recorded for node-1.+ expect(bound).toEqual([])+ expect(codexArgv()).toEqual(['resume thread-xyz'])+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'thread-bind-refused' }])+ })+})diff --git a/src/core/codex-session-name.ts b/src/core/codex-session-name.tsnew file mode 100644index 000000000..014c07f17--- /dev/null+++ b/src/core/codex-session-name.ts@@ -0,0 +1,337 @@+/**+ * The desktop's client for the ONE shared `codex app-server`.+ *+ * Two jobs, both of which the sh launcher cannot do itself:+ * - `startCodexThreadAt` — mint the thread a fresh Codex node will own.+ * - `readCodexSessionName` — the READ leg of codex's session name (`TITLE_READ_CAPABLE`).+ *+ * The name lives in the app-server's `Thread.name`, not in a file on disk, so this is the only+ * place it can be read from. There is no WRITE leg: codex has no rename command NodeTerm can+ * drive, which is exactly the gemini situation `TITLE_READ_CAPABLE` was split out for.+ *+ * Everything here fails to `null`/reject rather than throwing into a caller's poll loop: a name we+ * cannot read means the node keeps its own title, and a thread we cannot start means the launcher+ * falls back to plain codex.+ */+import { homedir } from 'os'+import path from 'path'+import { WebSocket } from 'ws'++const SAFE_THREAD_ID = /^[A-Za-z0-9._-]+$/+const CACHE_MS = 3_000+const 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_000++const names = new Map<string, { name: string | null; at: number }>()+const inflight = new Map<string, Promise<string | null>>()++/** The app-server's control socket, under the CLI's own `CODEX_HOME` (default `~/.codex`). */+export function defaultCodexAppServerSocket(): string {+ const configured = process.env.CODEX_HOME+ const codexHome =+ configured && path.isAbsolute(configured) ? configured : path.join(homedir(), '.codex')+ return path.join(codexHome, 'app-server-control', 'app-server-control.sock')+}++export function codexUnixWebSocketUrl(socketPath: string): string {+ if (!path.isAbsolute(socketPath) || /[\s:%?#]/.test(socketPath)) {+ throw new Error('Unsupported Codex app-server socket path')+ }+ return `ws+unix://${socketPath}:/rpc`+}++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,+ timeoutMs = REQUEST_TIMEOUT_MS+): Promise<string | null> {+ if (!SAFE_THREAD_ID.test(threadId)) return Promise.resolve(null)+ return new Promise((resolve) => {+ let settled = false+ let ws: WebSocket+ const finish = (name: string | null): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ try {+ ws.close()+ } catch {+ /* the connection may never have opened */+ }+ resolve(name)+ }+ const timer = setTimeout(() => finish(null), timeoutMs)+ timer.unref?.()+ try {+ ws = connectCodexAppServer(socketPath)+ } catch {+ clearTimeout(timer)+ resolve(null)+ 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(null)+ ws.send(JSON.stringify({ method: 'initialized' }))+ ws.send(+ JSON.stringify({+ id: 2,+ method: 'thread/read',+ params: { threadId, includeTurns: false }+ })+ )+ } else if (message.id === 2) {+ const name = message.result?.thread?.name+ finish(typeof name === 'string' && name.trim() ? name.trim() : null)+ }+ })+ ws.once('error', () => finish(null))+ ws.once('close', () => finish(null))+ })+}++/**+ * Create one new, immediately RESUMABLE thread on the shared app-server and return its id.+ *+ * `thread/start` alone only creates app-server metadata: it deliberately does not materialize the+ * rollout file, and a second client's `thread/resume` then fails with "no rollout found" — which+ * is precisely what the launcher does one line later. So the rollout is materialized by running+ * one empty turn, interrupting it the moment the server announces it, forking immediately BEFORE+ * that turn, and deleting the seed. The result is a thread with zero user turns and a valid+ * rollout, without the deprecated rollback API.+ */+export function startCodexThreadAt(+ socketPath: string,+ cwd: string,+ timeoutMs = START_TIMEOUT_MS+): Promise<string> {+ if (!path.isAbsolute(cwd) || cwd.includes('\0')) {+ return Promise.reject(new Error('Unsupported Codex thread cwd'))+ }+ return new Promise((resolve, reject) => {+ let settled = false+ let ws: WebSocket+ const finish = (error: Error | null, threadId?: string): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ try {+ ws.close()+ } catch {+ /* the connection may never have opened */+ }+ if (error) reject(error)+ else resolve(threadId as string)+ }+ const timer = setTimeout(+ () => finish(new Error('Codex app-server thread start timed out')),+ timeoutMs+ )+ timer.unref?.()+ try {+ ws = connectCodexAppServer(socketPath)+ } catch {+ clearTimeout(timer)+ reject(new Error('Codex app-server is unavailable'))+ return+ }+ ws.once('open', () => {+ ws.send(+ JSON.stringify({+ id: 1,+ method: 'initialize',+ params: {+ clientInfo: { name: 'nodeterm', version: '1' },+ capabilities: { experimentalApi: true }+ }+ })+ )+ })+ let threadId = ''+ let bootstrapTurnId = ''+ let announcedBootstrapTurnId = ''+ let announcedCompletedTurnId = ''+ let bootstrapStarted = false+ let interruptSent = false+ let interruptAcknowledged = false+ let bootstrapCompleted = false+ let cleanupForkSent = false+ const maybeInterrupt = (): void => {+ if (!bootstrapTurnId || !bootstrapStarted || bootstrapCompleted || interruptSent) return+ interruptSent = true+ ws.send(+ JSON.stringify({+ id: 4,+ method: 'turn/interrupt',+ params: { threadId, turnId: bootstrapTurnId }+ })+ )+ }+ const maybeCreateCleanThread = (): void => {+ if (!bootstrapCompleted || cleanupForkSent) return+ if (interruptSent && !interruptAcknowledged) return+ cleanupForkSent = true+ ws.send(+ JSON.stringify({+ id: 5,+ method: 'thread/fork',+ params: { threadId, beforeTurnId: bootstrapTurnId, cwd, ephemeral: false }+ })+ )+ }+ ws.on('message', (raw) => {+ let message: Record<string, any>+ try {+ message = JSON.parse(raw.toString())+ } catch {+ return+ }+ if (message.id === 1) {+ if (message.error) {+ finish(new Error('Codex app-server initialization failed'))+ return+ }+ ws.send(JSON.stringify({ method: 'initialized' }))+ ws.send(JSON.stringify({ id: 2, method: 'thread/start', params: { cwd } }))+ } else if (message.id === 2) {+ const startedThreadId = message.result?.thread?.id+ if (+ message.error ||+ typeof startedThreadId !== 'string' ||+ !SAFE_THREAD_ID.test(startedThreadId)+ ) {+ finish(new Error('Codex app-server returned no valid thread identity'))+ return+ }+ threadId = startedThreadId+ ws.send(JSON.stringify({ id: 3, method: 'turn/start', params: { threadId, input: [] } }))+ } else if (message.id === 3) {+ const turnId = message.result?.turn?.id+ if (message.error || typeof turnId !== 'string' || !SAFE_THREAD_ID.test(turnId)) {+ finish(new Error('Codex app-server could not materialize the new thread'))+ return+ }+ bootstrapTurnId = turnId+ if (announcedBootstrapTurnId === turnId) bootstrapStarted = true+ if (announcedCompletedTurnId === turnId) bootstrapCompleted = true+ maybeInterrupt()+ maybeCreateCleanThread()+ } else if (message.method === 'turn/started') {+ const turnId = message.params?.turn?.id+ if (typeof turnId === 'string') {+ announcedBootstrapTurnId = turnId+ if (turnId === bootstrapTurnId) {+ bootstrapStarted = true+ maybeInterrupt()+ }+ }+ } else if (message.id === 4) {+ if (message.error) {+ finish(new Error('Codex app-server could not interrupt thread materialization'))+ return+ }+ interruptAcknowledged = true+ maybeCreateCleanThread()+ } else if (message.method === 'turn/completed') {+ const turnId = message.params?.turn?.id+ if (typeof turnId === 'string') {+ announcedCompletedTurnId = turnId+ if (turnId === bootstrapTurnId) {+ bootstrapCompleted = true+ maybeCreateCleanThread()+ }+ }+ } else if (message.id === 5) {+ const readyThreadId = message.result?.thread?.id+ if (+ message.error ||+ typeof readyThreadId !== 'string' ||+ !SAFE_THREAD_ID.test(readyThreadId)+ ) {+ finish(new Error('Codex app-server could not clean up thread materialization'))+ return+ }+ const seedThreadId = threadId+ threadId = readyThreadId+ ws.send(JSON.stringify({ id: 6, method: 'thread/delete', params: { threadId: seedThreadId } }))+ } else if (message.id === 6) {+ if (message.error) {+ finish(new Error('Codex app-server could not remove thread materialization seed'))+ return+ }+ finish(null, threadId)+ }+ })+ ws.once('error', () => finish(new Error('Codex app-server is unavailable')))+ ws.once('close', () => finish(new Error('Codex app-server closed before thread start')))+ })+}++export function startCodexThread(cwd: string): Promise<string> {+ return startCodexThreadAt(defaultCodexAppServerSocket(), cwd)+}++/**+ * The READ leg for `TITLE_READ_CAPABLE`. Memoized for `CACHE_MS` and coalesced, because the+ * session-name sweep asks once a minute PER NODE and every ask is a socket connect.+ */+export function readCodexSessionName(+ threadId: string,+ socketPath = defaultCodexAppServerSocket()+): Promise<string | null> {+ if (!SAFE_THREAD_ID.test(threadId)) return Promise.resolve(null)+ const key = `${socketPath}\0${threadId}`+ const cached = names.get(key)+ if (cached && Date.now() - cached.at < CACHE_MS) return Promise.resolve(cached.name)+ const running = inflight.get(key)+ if (running) return running+ const request = readCodexSessionNameAt(socketPath, threadId).then(+ (name) => {+ names.set(key, { name, at: Date.now() })+ inflight.delete(key)+ return name+ },+ () => {+ inflight.delete(key)+ return null+ }+ )+ inflight.set(key, request)+ return request+}++export function forgetCodexSessionNames(): void {+ names.clear()+ inflight.clear()+}diff --git a/src/core/codex-thread-identity-sh.test.ts b/src/core/codex-thread-identity-sh.test.tsnew file mode 100644index 000000000..20006d3b1--- /dev/null+++ b/src/core/codex-thread-identity-sh.test.ts@@ -0,0 +1,82 @@+// The hook prelude, run by the real /bin/sh. It is prepended to every managed hook script, so a+// quoting slip here does not break "codex identity recovery" — it breaks every agent's hooks on+// every machine. It is also the one place where a data file's contents become environment+// variables, which is why the negative cases below matter as much as the positive one.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFile } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'+import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'++const run = promisify(execFile)++let dir = ''+let root = ''+let script = ''++beforeAll(() => {+ // A space in the path on purpose: the real one is macOS's "Application Support".+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm codex prelude '))+ root = path.join(dir, 'codex-thread-nodes')+ fs.mkdirSync(root, { recursive: true })+ script = path.join(dir, 'prelude.sh')+ fs.writeFileSync(+ script,+ `#!/bin/sh\n${codexThreadIdentityResolverSh(root)}\n` ++ `printf '%s|%s|%s\\n' "\${NODETERM_NODE_ID-}" "\${NODETERM_HOOK_ENDPOINT-}" "\${NODETERM_CANVAS_CONTROL-}"\n`,+ { mode: 0o755 }+ )+})++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))++function record(threadId: string, body: string): void {+ fs.writeFileSync(path.join(root, threadId), body)+}++async function resolve(env: Record<string, string>): Promise<string> {+ const { stdout } = await run('/bin/sh', [script], {+ env: { PATH: process.env.PATH ?? '', HOME: dir, ...env }+ })+ return stdout.trim()+}++describe('codex thread identity prelude', () => {+ it('is valid POSIX sh', async () => {+ await expect(run('/bin/sh', ['-n', script])).resolves.toBeTruthy()+ })++ it('recovers the node binding a tool shell never inherited', async () => {+ record('thread-1', `nodeId=node-7\nendpoint=${dir}/hook-endpoint.env\nsignature=x\n`)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-1' })).toBe(+ `node-7|${dir}/hook-endpoint.env|1`+ )+ })++ it('changes nothing when the session already knows its node', async () => {+ record('thread-1', `nodeId=node-7\nendpoint=${dir}/hook-endpoint.env\nsignature=x\n`)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-1', NODETERM_NODE_ID: 'node-own' })).toBe(+ 'node-own||'+ )+ })++ it('is inert for every other agent (no CODEX_THREAD_ID, no record)', async () => {+ expect(await resolve({})).toBe('||')+ expect(await resolve({ CODEX_THREAD_ID: 'unknown-thread' })).toBe('||')+ })++ it('refuses a thread id that could escape the record directory', async () => {+ expect(await resolve({ CODEX_THREAD_ID: '../../etc/passwd' })).toBe('||')+ })++ it('exports nothing when a record carries a node id or endpoint it should not', async () => {+ record('thread-bad-node', `nodeId=node 7; rm -rf /\nendpoint=${dir}/e\n`)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-bad-node' })).toBe('||')+ record('thread-bad-ep', 'nodeId=node-7\nendpoint=relative/e\n')+ expect(await resolve({ CODEX_THREAD_ID: 'thread-bad-ep' })).toBe('||')+ record('thread-bad-ep2', 'nodeId=node-7\nendpoint=/etc/$(id)\n')+ expect(await resolve({ CODEX_THREAD_ID: 'thread-bad-ep2' })).toBe('||')+ })+})diff --git a/src/core/codex-thread-identity-sh.ts b/src/core/codex-thread-identity-sh.tsnew file mode 100644index 000000000..ad3984ce6--- /dev/null+++ b/src/core/codex-thread-identity-sh.ts@@ -0,0 +1,58 @@+/**+ * POSIX-sh prelude prepended to every managed hook script.+ *+ * WHY IT EXISTS: with the shared app-server, the shell a Codex TOOL runs in is spawned by that+ * server, not by the TUI client NodeTerm launched. It therefore inherits `CODEX_THREAD_ID` but+ * none of the `NODETERM_*` env we set on the pane — so the hook it runs has no idea which canvas+ * node it belongs to, and the node's badge/status would simply never move. This recovers the node+ * binding from the thread id.+ *+ * The mapping file is parsed as DATA (`sed`), never sourced as shell code, and both recovered+ * fields are re-validated before they are exported. The record itself is HMAC-signed by+ * `codex-identity-proxy.ts`; this prelude cannot verify that signature (no key in an agent's+ * shell), which is why the charset re-validation below is not redundant.+ *+ * Inert for every other agent: without `CODEX_THREAD_ID` the whole block is skipped, and the+ * generated script is otherwise byte-identical to what it was. That is intentional — the prelude+ * is prepended once in `buildManagedScript`, so it lands in claude/gemini/codex/grok/opencode+ * scripts alike rather than in a codex-only fork of the builder.+ *+ * Deliberately free of Node/Electron imports beyond the path it is given: the generated-script+ * cores are shared by the desktop and the Server Edition.+ */+import { posixQuote } from '../shared/ssh'++/**+ * @param identityRoot absolute path of the thread → node record directory+ * (`codexThreadIdentityRoot()`, i.e. under `CorePlatform.userDataDir` — NOT `~`).+ */+export function codexThreadIdentityResolverSh(identityRoot: string): string {+ return `# A shared-app-server Codex tool shell inherits CODEX_THREAD_ID, not the TUI client's+# NODETERM_* env. Recover this thread's exact node binding, or change nothing at all.+if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then+ case "$CODEX_THREAD_ID" in+ ''|*[!A-Za-z0-9._-]*) ;;+ *)+ nt_codex_map=${posixQuote(identityRoot)}/"$CODEX_THREAD_ID"+ if [ -r "$nt_codex_map" ]; then+ nt_codex_node=$(sed -n 's/^nodeId=//p' "$nt_codex_map" | head -n 1)+ nt_codex_endpoint=$(sed -n 's/^endpoint=//p' "$nt_codex_map" | head -n 1)+ case "$nt_codex_node" in ''|*[!A-Za-z0-9._-]*) nt_codex_node='' ;; esac+ case "$nt_codex_endpoint" in /*) ;; *) nt_codex_endpoint='' ;; esac+ if [ -n "$nt_codex_endpoint" ] &&+ [ "$(printf %s "$nt_codex_endpoint" | tr -cd 'A-Za-z0-9._/ -')" != "$nt_codex_endpoint" ]+ then+ nt_codex_endpoint=''+ fi+ if [ -n "$nt_codex_node" ] && [ -n "$nt_codex_endpoint" ]; then+ NODETERM_NODE_ID="$nt_codex_node"+ NODETERM_HOOK_ENDPOINT="$nt_codex_endpoint"+ NODETERM_AGENT_ID=codex+ NODETERM_CANVAS_CONTROL=1+ export NODETERM_NODE_ID NODETERM_HOOK_ENDPOINT NODETERM_AGENT_ID NODETERM_CANVAS_CONTROL+ fi+ fi+ ;;+ esac+fi`+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 04bcf5966..7cd350453 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -53,6 +53,8 @@ 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 { hasSharedIdentity, type AgentId } from '../shared/agents/config'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which// kills the tmux server) can still replay recent output on cold restart. A final snapshot also@@ -1574,6 +1576,12 @@ export class PtyManager {// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)// so the session env below picks it up — awaiting keeps the event loop free either way.await resolveShellPath()+ // Rewrite the launcher on every create: it is generated, so an app upgrade must not leave an+ // old copy behind. Failure is not fatal — `installCodexLauncher` answers null, the caps probe+ // says "no shared identity", and the launch line the renderer already chose is the bare CLI.+ if (hasSharedIdentity((options.agentId ?? 'claude') as AgentId) && !options.sshRemote) {+ installCodexLauncher()+ }const sessionId = this.spawnSession(options, clientId, undefined)const spawned = this.sessions.get(sessionId)// Surface a missing-account-dir fallback so the renderer can flag the node's account chip.@@ -1887,6 +1895,14 @@ export class PtyManager {: {}for (const [k, v] of Object.entries(hookEnv)) env[k] = v+ // Shared-identity agents (SHARED_IDENTITY_CAPABLE — never `agentId === 'codex'`) reach their+ // managed launcher by NAME, so its directory goes first on THIS session's PATH only. A plain+ // terminal, and every other agent, sees the PATH it always saw. The launcher itself falls back+ // to the bare CLI, so a session that gets the PATH but no identity is still a working session.+ if (hasSharedIdentity((options.agentId ?? 'claude') as AgentId) && !options.sshRemote) {+ env.PATH = `${codexLauncherDir()}${path.delimiter}${env.PATH ?? ''}`+ }+// Managed Claude account: the whole session runs under the account's private config// dir. The claude CLI then reads/writes credentials + transcripts there. Also strip// env auth vars that would silently shadow the account's OAuth login (an inheriteddiff --git a/src/core/session-name-sweep.test.ts b/src/core/session-name-sweep.test.tsindex aacf1f063..2de76200c 100644--- a/src/core/session-name-sweep.test.ts+++ b/src/core/session-name-sweep.test.ts@@ -150,22 +150,25 @@ describe('the default supports gate (TITLE_READ_CAPABLE)', () => {const { published, asked } = await sweepWithDefaultGate([{ nodeId: 'c', sessionId: 'cs', agentId: 'claude' },{ nodeId: 'g', sessionId: 'gs', agentId: 'grok' },- { nodeId: 'm', sessionId: 'ms', agentId: 'gemini' }+ { nodeId: 'm', sessionId: 'ms', agentId: 'gemini' },+ // codex joined the same way: with the shared app-server its node owns a thread, and that+ // thread's `Thread.name` is readable over the server's socket. Read-only, like gemini.+ { nodeId: 'x', sessionId: 'xs', agentId: 'codex' }])- expect(asked).toEqual(['cs', 'gs', 'ms'])+ expect(asked).toEqual(['cs', 'gs', 'ms', 'xs'])expect(published).toEqual([['c', 'name of cs'],['g', 'name of gs'],- ['m', 'name of ms']+ ['m', 'name of ms'],+ ['x', 'name of xs']])})it('never asks about an agent whose name we cannot read', async () => {- // codex is in neither list (its command set was not enumerable, so neither leg has a measured- // basis) and a custom agent has no reader at all. Asking anyway would send them through- // claude's resolver, which SCANS ~/.claude/projects for an id that can never be there.+ // A custom agent has no reader at all, and an entry with no agentId cannot be routed. Asking+ // anyway would send them through claude's resolver, which SCANS ~/.claude/projects for an id+ // that can never be there — once a minute, per node, forever.const { published, asked } = await sweepWithDefaultGate([- { nodeId: 'x', sessionId: 'xs', agentId: 'codex' },{ nodeId: 'y', sessionId: 'ys', agentId: 'custom:mine' },{ nodeId: 'z', sessionId: 'zs' }])diff --git a/src/main/codex-node-auth-secret.test.ts b/src/main/codex-node-auth-secret.test.tsnew file mode 100644index 000000000..de3a28cf4--- /dev/null+++ b/src/main/codex-node-auth-secret.test.ts@@ -0,0 +1,58 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'++let userData = ''+let encryptionAvailable = true+const flip = (value: Buffer) => Buffer.from(value.map((byte) => byte ^ 0xff))++vi.mock('electron', () => ({+ app: { getPath: () => userData },+ safeStorage: {+ isEncryptionAvailable: () => encryptionAvailable,+ encryptString: (value: string) => flip(Buffer.from(value, 'utf8')),+ decryptString: (value: Buffer) => flip(value).toString('utf8')+ }+}))++import { loadOrCreateCodexNodeAuthSecret, resetCodexNodeAuthSecretForTests } from './codex-node-auth-secret'++const file = () => path.join(userData, 'codex-node-auth-key.json')++describe('Codex node-auth secret', () => {+ beforeEach(async () => {+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-codex-node-auth-'))+ encryptionAvailable = true+ resetCodexNodeAuthSecretForTests()+ })++ afterEach(async () => {+ await fs.rm(userData, { recursive: true, force: true })+ })++ it('persists only keychain ciphertext and restores the same secret after restart', async () => {+ const first = await loadOrCreateCodexNodeAuthSecret()+ const stored = JSON.parse(await fs.readFile(file(), 'utf8')) as Record<string, unknown>+ expect(first).toHaveLength(32)+ expect(stored).toEqual({ version: 1, secretKeyEnc: expect.any(String) })+ expect(JSON.stringify(stored)).not.toContain(first.toString('base64'))+ expect((await fs.stat(file())).mode & 0o777).toBe(0o600)+ resetCodexNodeAuthSecretForTests()+ expect(await loadOrCreateCodexNodeAuthSecret()).toEqual(first)+ })++ it('fails closed without an OS keychain and writes no plaintext fallback', async () => {+ encryptionAvailable = false+ await expect(loadOrCreateCodexNodeAuthSecret()).rejects.toThrow('OS keychain is unavailable')+ await expect(fs.access(file())).rejects.toThrow()+ })++ it('fails closed on malformed persisted state instead of rotating ownership', async () => {+ await fs.writeFile(file(), '{"version":1,"secretKeyEnc":"broken"}\n', {+ mode: 0o600+ })+ await expect(loadOrCreateCodexNodeAuthSecret()).rejects.toThrow()+ expect(await fs.readFile(file(), 'utf8')).toBe('{"version":1,"secretKeyEnc":"broken"}\n')+ })+})diff --git a/src/main/codex-node-auth-secret.ts b/src/main/codex-node-auth-secret.tsnew file mode 100644index 000000000..62639854b--- /dev/null+++ b/src/main/codex-node-auth-secret.ts@@ -0,0 +1,84 @@+import { randomBytes } from 'crypto'+import { promises as fs } from 'fs'+import path from 'path'+import { app, safeStorage } from 'electron'++type StoredSecret = { version: 1; secretKeyEnc: string }++let cached: Promise<Buffer> | null = null+let cachedFile = ''++function secretFile(): string {+ return path.join(app.getPath('userData'), 'codex-node-auth-key.json')+}++function decode(raw: string): Buffer {+ if (!safeStorage.isEncryptionAvailable()) {+ throw new Error('OS keychain is unavailable')+ }+ let stored: StoredSecret+ try {+ stored = JSON.parse(raw) as StoredSecret+ } catch {+ throw new Error('Codex node-auth key is malformed')+ }+ if (stored?.version !== 1 || typeof stored.secretKeyEnc !== 'string') {+ throw new Error('Codex node-auth key is malformed')+ }+ const secret = Buffer.from(safeStorage.decryptString(Buffer.from(stored.secretKeyEnc, 'base64')), 'base64')+ if (secret.byteLength !== 32) throw new Error('Codex node-auth key is invalid')+ return secret+}++async function persist(file: string, secret: Buffer): Promise<void> {+ if (!safeStorage.isEncryptionAvailable()) throw new Error('OS keychain is unavailable')+ const body: StoredSecret = {+ version: 1,+ secretKeyEnc: safeStorage.encryptString(secret.toString('base64')).toString('base64')+ }+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`+ await fs.mkdir(path.dirname(file), { recursive: true })+ try {+ await fs.writeFile(tmp, `${JSON.stringify(body)}\n`, {+ encoding: 'utf8',+ mode: 0o600,+ flag: 'wx'+ })+ await fs.rename(tmp, file)+ await fs.chmod(file, 0o600)+ } finally {+ await fs.unlink(tmp).catch(() => {})+ }+}++async function load(file: string): Promise<Buffer> {+ try {+ return decode(await fs.readFile(file, 'utf8'))+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ }+ const secret = randomBytes(32)+ await persist(file, secret)+ return secret+}++/** Restart-stable node-capability key. Ciphertext only at rest; no plaintext fallback. */+export function loadOrCreateCodexNodeAuthSecret(): Promise<Buffer> {+ const file = secretFile()+ if (cached && cachedFile === file) return cached+ const pending = load(file)+ cached = pending+ cachedFile = file+ pending.catch(() => {+ if (cached === pending) {+ cached = null+ cachedFile = ''+ }+ })+ return pending+}++export function resetCodexNodeAuthSecretForTests(): void {+ cached = null+ cachedFile = ''+}diff --git a/src/main/index.ts b/src/main/index.tsindex 5f41257fb..7e7b6eb21 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -124,6 +124,14 @@ import { SpeechService } from '../core/speech/speech-service'import { registerSpeechIpc } from '../core/speech/register-ipc'import { initClaudeAccounts } from './claude-accounts'import { claudeCliCaps, registerClaudeCliIpc, type ClaudeCliCaps } from '../core/claude-cli'+import { refreshCodexIdentityCaps, registerCodexIdentityIpc } from '../core/codex-identity-caps'+import {+ bindCodexThreadIdentity,+ setCodexThreadIdentityAuthSecret,+ writeCodexThreadIdentity+} from '../core/codex-identity-proxy'+import { startCodexThread } from '../core/codex-session-name'+import { loadOrCreateCodexNodeAuthSecret } from './codex-node-auth-secret'import { claudeConfigDirFor } from '../core/claude-config-dir'import {isSafeLocalTranscriptPath,@@ -548,6 +556,7 @@ app.whenReady().then(async () => {process.platform === 'darwin' ? systemPreferences.askForMediaAccess('microphone') : true)registerClaudeCliIpc()+ registerCodexIdentityIpc()// Warm the `claude --version` probe now (it spawns a login shell + node, ~sub-second) so the// renderer's first `claude.cliCaps()` — awaited on the launch path of a cold-restored agent// node — resolves from cache instead of racing the probe into a conservative "no auto".@@ -894,6 +903,34 @@ app.whenReady().then(async () => {// listeners (setListener/setRawListener/setControlHandler) attach later, which the server// tolerates — early hook POSTs are simply dropped, never mis-routed.await hookServer.start()+ // ---- Codex shared identity (src/core/codex-identity-proxy.ts) -------------------------------+ // One keychain-backed secret does two jobs: it mints the per-node capability the identity routes+ // require (closing the "shared bearer can name any sibling node" hole) and it signs the thread →+ // node records the hook prelude reads back. If secure storage is unavailable the whole feature+ // stays OFF — `codexIdentityCaps()` then answers `shared: false`, every launch line stays the+ // bare `codex`, and nothing is half-armed.+ try {+ const codexNodeAuthSecret = await loadOrCreateCodexNodeAuthSecret()+ hookServer.setCodexNodeAuthSecret(codexNodeAuthSecret)+ setCodexThreadIdentityAuthSecret(codexNodeAuthSecret)+ } catch (error) {+ console.error('[codex-identity] unavailable; Codex nodes run plain codex:', error)+ }+ // Installs the launcher and answers the renderer's construction-time question.+ 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+ // workspace that no longer holds it) is free to be re-claimed; one whose owner is still there is+ // not, and the launcher then falls back rather than putting two clients on one conversation.+ const codexNodeIsLive = (nodeId: string): boolean => !!workspaceStore.getNode(nodeId)+ hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, hookEndpoint }) => {+ const threadId = await startCodexThread(cwd)+ writeCodexThreadIdentity(threadId, nodeId, hookEndpoint)+ return threadId+ })+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, hookEndpoint }) => {+ bindCodexThreadIdentity(threadId, nodeId, hookEndpoint, codexNodeIsLive)+ })// SSH_ASKPASS relay (ssh-project.ts): lets the ControlMaster, which has no tty, route a// passphrase-protected identity file's prompt back through the app instead of failing auth.// MUST NOT be fatal: binding a unix socket under ~/.nodeterm can fail for filesystem reasonsdiff --git a/src/preload/index.ts b/src/preload/index.tsindex 22fabf38d..35c51b88d 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -422,6 +422,14 @@ const api: NodeTerminalApi = {return () => ipcRenderer.removeListener(IPC.canvasMut, handler)}},+ codex: {+ identityCaps: () => ipcRenderer.invoke(IPC.codexIdentityCaps),+ onIdentity: (listener) => {+ const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)+ ipcRenderer.on(IPC.codexIdentity, handler)+ return () => ipcRenderer.removeListener(IPC.codexIdentity, handler)+ }+ },claude: {cliCaps: () => ipcRenderer.invoke(IPC.claudeCliCaps),readTranscript: (sessionId, cwd, accountId, nodeId) =>diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex 97f43f778..d83edb06f 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -2,6 +2,7 @@ import React from 'react'import ReactDOM from 'react-dom/client'import App from './App'import { ensureClaudeCliCaps } from './state/permissionMode'+import { ensureCodexIdentityCaps } from './state/codexIdentity'import './styles.css'import './tailwind.css'@@ -11,6 +12,11 @@ import './tailwind.css'// resolves immediately.void ensureClaudeCliCaps()+// Same shape, same reason: a Codex launch line names the managed shared-identity launcher only if+// this machine has one installed and armed. Unprobed ⇒ plain `codex`, which is what every Codex+// node ran before this feature — never a launcher path that might not resolve.+void ensureCodexIdentityCaps()+// Note: StrictMode is intentionally not used — its double mount in dev would open// two PTY sessions per terminal node.ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<App />)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 6cd9d82a0..31df8ad10 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -16,6 +16,7 @@import {UNKNOWN_CLAUDE_CLI_CAPS,+ UNKNOWN_CODEX_IDENTITY_CAPS,type ClaudeUsage,type NodeTerminalApi,type NotifyPayload,@@ -257,6 +258,13 @@ export function buildStubApi(): Omit<read: () => Promise.resolve({ ok: false, rows: [], mem: null }),host: () => Promise.resolve(null)},+ codex: {+ // Overridden by the real WS-backed namespace in ws-bridge. The stub's answer is the same+ // one the Server Edition gives on purpose (see server/handlers/index.ts): no shared+ // identity, so every Codex launch line stays the bare `codex`.+ identityCaps: () => Promise.resolve(UNKNOWN_CODEX_IDENTITY_CAPS),+ onIdentity: noopUnsub+ },claude: {// Overridden by the real WS-backed namespace in ws-bridge; the stub still answers with the// fail-open caps (never rejects) because the permission-mode gate reads it on the boot path.diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 1e619ce25..50066c796 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -22,6 +22,9 @@ import {type ChatTranscriptResult,type ClaudeApi,type ClaudeCliCaps,+ type CodexApi,+ type CodexIdentityCaps,+ UNKNOWN_CODEX_IDENTITY_CAPS,type ContextApi,type DownloadTicket,type FilesApi,@@ -659,6 +662,22 @@ export function buildSessionMemoryApi(client: RpcClient): Pick<NodeTerminalApi,* only real member is a capability probe — the Server Edition gets the real reader from* `buildTranscriptApi` below instead, which the relay does not use.*/+/**+ * The `codex` namespace over an RpcClient — a REAL implementation, not a stub, because the answer+ * has to come from the machine the pty runs on. Today the Server Edition's handler deliberately+ * answers `{ shared: false }` (see server/handlers/index.ts); wiring that side later needs nothing+ * here. A failed request degrades to the same conservative answer: the launch path reads it.+ */+export function buildCodexApi(client: RpcClient): CodexApi {+ return {+ identityCaps: () =>+ (client.request(IPC.codexIdentityCaps) as Promise<CodexIdentityCaps>).catch(+ () => UNKNOWN_CODEX_IDENTITY_CAPS+ ),+ onIdentity: (listener) => client.subscribe(IPC.codexIdentity, listener as Listener)+ }+}+export function buildClaudeApi(client: RpcClient, stub: ClaudeApi): ClaudeApi {return {...stub,@@ -819,6 +838,7 @@ export async function installWsBridge(): Promise<boolean> {...buildUsageApi(client),...buildSessionMemoryApi(client),...buildGitHubApi(client),+ codex: buildCodexApi(client),// `claude` is assembled from two builders: `cliCaps` from the relay-shared one, and the// transcript reader from the Server-Edition-only one (which also supplies `chat`)....(() => {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 353c1ffc1..ba7c6b77d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -190,6 +190,7 @@ import { opensInEditor } from '../lib/openTarget'import { newEntryPath, parentDir } from '../lib/explorerCreate'import { useProjects } from '../state/projects'import { useAgentStatus } from '../state/agentStatus'+import { useCodexIdentity, codexFallbackText } from '../state/codexIdentity'import { useTeamAccessEvents } from '../state/teamAccess'import { useAgentNodes } from '../state/agentNodes'import { SubagentNode } from '../nodes/SubagentNode'@@ -691,9 +692,10 @@ export function Canvas() {// told here rather than being left with a note their teammates never see. Dismissible; re-armed// by the next refused cast (the publisher keeps retrying that node, so it syncs once trimmed).const [syncNote, setSyncNote] = useState<string | null>(null)- // Copy-to-clipboard failure (browser build only): the bridge clipboard stub dispatches- // `nodeterm:toast` when neither the Clipboard API nor execCommand can copy — typically a- // non-secure context (plain http over a LAN). It must be seen, not swallowed.+ // A transient warning banner. Two producers, both of which must be SEEN rather than swallowed:+ // a copy-to-clipboard failure (browser build only — the bridge clipboard stub dispatches+ // `nodeterm:toast` when neither the Clipboard API nor execCommand can copy, typically a+ // non-secure context over a LAN), and a Codex node reporting that it fell back to plain codex.const [copyError, setCopyError] = useState<string | null>(null)// Cmd+V only drops an image on the canvas when the LAST pointer press was on the pane itself —// otherwise a paste aimed at a panel or a dialog would spawn a node behind it. See@@ -949,6 +951,20 @@ export function Canvas() {window.addEventListener('nodeterm:toast', onToast)return () => window.removeEventListener('nodeterm:toast', onToast)}, [])+ // A Codex node's launcher reporting what it actually got. The 'plain' case is the fallback, and+ // this is what stops it being silent: the node keeps a chip (see TerminalNode's header) and the+ // FIRST fallback per node also raises a toast, because a chip on a node you are not looking at+ // teaches nothing. Deliberately NOT written into the pane — text pushed into an agent's terminal+ // is prompt injection, which this repo forbids.+ useEffect(() => {+ const seen = new Set<string>()+ return window.nodeTerminal.codex.onIdentity((e) => {+ useCodexIdentity.getState().setMode(e.nodeId, e.mode, e.reason)+ if (e.mode !== 'plain' || seen.has(e.nodeId)) return+ seen.add(e.nodeId)+ setCopyError(codexFallbackText(e.reason))+ })+ }, [])// Terminal node id awaiting confirmation to move into its group's worktree.const [moveTarget, setMoveTargetState] = useState<string | null>(null)// Group awaiting confirmation to remove its worktree (drives the ask-first safety dialog).diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f3c8176b6..56c1d4c8f 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -126,6 +126,7 @@ import { isHidden } from '../lib/ui-visibility'import { readsClaudeTranscript } from '../lib/transcriptGates'import { liveProjectJumpTarget } from '../lib/projectJump'import { useSettings } from '../state/settings'+import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../state/codexIdentity'import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'import type { AgentState } from '@shared/agents/normalize'import type { ClientId } from '@shared/presence'@@ -138,7 +139,7 @@ import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'import { useSession, useActiveSessionPresence } from '../session/session'import { accountChipLabel, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'-import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, canReadTitle, createdAgentId, reportsOwnCopy, resumeCommand, agentConfig } from '@shared/agents/config'+import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, canReadTitle, createdAgentId, reportsOwnCopy, resumeCommand, agentConfig, agentLaunchProgram } from '@shared/agents/config'import { withPermissionMode } from '@shared/agents/approval-mode'import { ensureActivePermissionMode } from '../state/permissionMode'import { buildSshArgs, type SshConnection } from '@shared/ssh'@@ -1221,6 +1222,9 @@ export function TerminalNode({!remoteSession &&(data.cwd as string | undefined) !== parentWtPathconst status = useAgentStatus((s) => s.byId[id])+ // Transient, per-launch: what this node's Codex launcher reported it actually got. Undefined for+ // every non-codex node and for a codex node whose launcher never spoke.+ const codexIdentity = useCodexIdentity((s) => s.byId[id])// --- Eco / hibernation wake (see terminal/hibernation-policy.ts) ---// A hibernated node's CLI was asked to `/exit` while nobody was looking; its tmux session, pane// and scrollback are untouched, and the conversation comes back with the provider's own@@ -2681,7 +2685,14 @@ export function TerminalNode({// relaunched empty while their transcripts sat on disk, unreachable.const st = useAgentStatus.getState().byId[id]const priorId = st?.sessionId || data.agentSessionId- const base = (priorId && resumeCommand(agentId, priorId)) || agentConfig(agentId)?.launchCmd+ // Shared-identity agents resume THROUGH their launcher, so the cold-restored node+ // re-claims its own thread instead of joining as an anonymous client. `data.ssh` is what+ // keeps a remote node on the bare command (no launcher on the host).+ const shared = codexSharedIdentity(data.ssh || data.sshRemoteTmux)+ const base =+ (priorId && resumeCommand(agentId, priorId, shared)) ||+ (agentConfig(agentId) &&+ agentLaunchProgram(agentId, agentConfig(agentId)!.launchCmd, shared))// Re-resolve the mode at relaunch: it's a property of how a session is launched, not// a persisted property of the node, so the current setting wins after a reboot. `base`// is always freshly built here — never a command string read back from node data — so@@ -2847,6 +2858,11 @@ export function TerminalNode({// Same funnel, same await, same reasoning as the restart closure above: the permission// mode is a property of how a session is LAUNCHED, so it is re-resolved now (a wake can be// hours after the exit, and days after the node was created).+ // Deliberately the BARE command, with no shared-identity launcher: this types into a pane+ // that already exists, and a tmux session created before the launcher was installed does+ // not carry its directory on PATH — naming it there would be `command not found` where a+ // plain `codex resume` works. A restarted codex node therefore rejoins as a plain client+ // until its next cold start. Fail open, same rule as everywhere else in this feature.const base = resumeCommand(agentId, agentSessionId)// Refused BEFORE anything is written. `performResumePhase` gates on this same bare command// and would refuse too — but the KILL_LINE below is ours, so leaving this check to it@@ -3962,6 +3978,18 @@ export function TerminalNode({{status.session}</span>)}+ {/* The fallback, made visible. A Codex node that could not get a managed shared identity+ runs a perfectly good plain `codex` — but the user has to be able to SEE that it did,+ without reading a log, so the chip states it and its tooltip says why. Absent (and the+ node byte-identical to before this feature) whenever identity is shared or unknown. */}+ {codexIdentity?.mode === 'plain' && (+ <span+ className="node-account-chip node-account-chip--warning"+ title={codexFallbackText(codexIdentity.reason)}+ >+ plain codex+ </span>+ )}{accountChip && (<spanclassName={`node-account-chip${accountFallback ? ' node-account-chip--warning' : ''}`}diff --git a/src/renderer/state/codexIdentity.ts b/src/renderer/state/codexIdentity.tsnew file mode 100644index 000000000..6584958ca--- /dev/null+++ b/src/renderer/state/codexIdentity.ts@@ -0,0 +1,105 @@+/**+ * The renderer's half of the Codex shared-identity fallback.+ *+ * TWO questions, and they are not the same one:+ *+ * 1. "Should this launch line name the managed launcher?" — answered BEFORE the node exists, by+ * `codexSharedIdentity(ssh)` below. Same shape as the `--permission-mode auto` gate: a+ * memoized shell probe whose unknown answer is the conservative one, so an unprobed or failed+ * machine emits the bare `codex` it always did rather than a launcher path that may not+ * resolve. That is the difference between "no shared identity" and "a dead node".+ *+ * 2. "What did this node ACTUALLY get?" — answered AFTER it launched, by the node's own launcher+ * (`codex-identity:event`). Only the launcher can see the pane's env, whether the endpoint+ * file was readable, or whether the installed `codex` even has an app-server, so the script+ * is the authority and question 1 is only an optimistic gate in front of it.+ *+ * The mode is TRANSIENT — never persisted. It describes one launch of one process; a node reloaded+ * from disk has not launched anything yet, and a stale "plain" badge on it would be a lie.+ */+import { create } from 'zustand'+import { UNKNOWN_CODEX_IDENTITY_CAPS, type CodexIdentityCaps } from '@shared/types'++const CAPS_WAIT_MS = 3000++let caps: CodexIdentityCaps = UNKNOWN_CODEX_IDENTITY_CAPS+let capsPromise: Promise<CodexIdentityCaps> | null = null++/** Probe once per app run. Never rejects; a slow bridge resolves to what we have so far. */+export function ensureCodexIdentityCaps(): Promise<CodexIdentityCaps> {+ if (!capsPromise) {+ const probe = Promise.resolve()+ .then(() => window.nodeTerminal.codex.identityCaps())+ .then((c) => (caps = c ?? UNKNOWN_CODEX_IDENTITY_CAPS))+ .catch(() => UNKNOWN_CODEX_IDENTITY_CAPS)+ const timeout = new Promise<CodexIdentityCaps>((resolve) =>+ setTimeout(() => resolve(caps), CAPS_WAIT_MS)+ )+ capsPromise = Promise.race([probe, timeout])+ }+ return capsPromise+}++export function codexIdentityCapsNow(): CodexIdentityCaps {+ return caps+}++/**+ * Should a node use the shared-identity launcher? `remote` is anything truthy that marks the+ * session as running on another machine (`project.ssh`, `data.ssh`, `data.sshRemoteTmux` — the+ * caller passes whichever it holds; only its truthiness is read).+ *+ * An SSH project's session runs on the HOST, which has no launcher installed (that is a later+ * slice), so a launcher-named launch line there would be `command not found` — a dead node, the+ * exact failure this whole fallback exists to prevent. Remote ⇒ plain codex.+ */+export function codexSharedIdentity(remote?: unknown): boolean {+ return !remote && codexIdentityCapsNow().shared+}++export function resetCodexIdentityCapsForTests(next?: CodexIdentityCaps): void {+ caps = next ?? UNKNOWN_CODEX_IDENTITY_CAPS+ capsPromise = null+}++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) => ({+ byId: {},+ setMode: (nodeId, mode, reason) =>+ set((s) => {+ const prev = s.byId[nodeId]+ if (prev?.mode === mode && prev.reason === reason) return s+ return { 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 }+ })+}))++/** Human copy for the reasons the generated launcher can report. */+export const CODEX_FALLBACK_REASONS: Record<string, string> = {+ 'node-id-unavailable': 'this session was not started by nodeterm',+ 'hook-endpoint-unavailable': "nodeterm's hook endpoint was unreadable",+ 'broker-unreachable': "nodeterm's hook server was unreachable",+ 'node-token-unavailable': 'this build could not mint a node identity key',+ 'thread-id-unavailable': 'the session id to resume was not usable',+ 'app-server-unavailable': 'this codex CLI has no shared app-server',+ 'thread-bind-refused': 'another live node already owns that conversation',+ 'thread-start-failed': 'the shared app-server would not start a conversation'+}++export function codexFallbackText(reason?: string): string {+ const why = (reason && CODEX_FALLBACK_REASONS[reason]) || 'the managed identity was unavailable'+ return `Running plain codex — ${why}.`+}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex ad07b1bd5..ff454223a 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1,10 +1,11 @@import type { Node } from '@xyflow/react'import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, PendingLaunch, Project } from '@shared/types'import type { AgentId, AgentPermissionMode } from '@shared/agents/config'-import { agentConfig, mintsSessionId, withSessionId } from '@shared/agents/config'+import { agentConfig, agentLaunchProgram, mintsSessionId, withSessionId } from '@shared/agents/config'import { withPermissionMode } from '@shared/agents/approval-mode'import { uuid } from '@renderer/lib/uuid'import { claudeCliCapsNow } from './permissionMode'+import { codexSharedIdentity } from './codexIdentity'import { sshHostKey } from '@shared/ssh'import { useSettings } from './settings'@@ -338,7 +339,14 @@ export function createAgentNode(permissionMode?: AgentPermissionMode): CanvasNode {const { label, color, launchCmd } = resolveAgent(agentId)- const baseCmd = agentId === 'claude' ? claudeLaunchCommand() : launchCmd+ // A SHARED_IDENTITY_CAPABLE agent (codex) launches through its managed launcher when this+ // machine actually has one — otherwise the bare CLI, byte-identical to before. Asked through the+ // capability helper, never `agentId === 'codex'`; `codexSharedIdentity` folds in the SSH answer+ // (a host has no launcher installed yet, so a remote node must stay on the bare command).+ const baseCmd =+ agentId === 'claude'+ ? claudeLaunchCommand()+ : agentLaunchProgram(agentId, launchCmd, codexSharedIdentity(ssh))// A flag-prompt agent (opencode) takes the initial prompt via its flag — a bare positional// would be misread (opencode treats it as a project path). Everything else keeps the// historical argv append, INCLUDING stdin-after-start agents (gemini has always launcheddiff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex 911cd103c..8e3051f1a 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -7,6 +7,8 @@ import { GitService } from '../../core/git-service'import { generateCommitMessage } from '../../core/commit-message'import { registerFsHandlers } from '../../core/fs-handlers'import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'+import { registerCodexIdentityIpc } from '../../core/codex-identity-caps'+import { UNKNOWN_CODEX_IDENTITY_CAPS } from '@shared/types'import { startUsageService } from '../../core/usage/usage-service'import {setMirrorUsageProvider,@@ -68,6 +70,22 @@ export function registerCoreHandlers(registerClaudeCliIpc()void claudeCliCaps()+ // ---- Codex shared identity: a DELIBERATE degrade, not an omission ----------------------------+ // The Server Edition answers "no shared identity", so every Codex node here launches the bare+ // `codex` it always did — a working node with its own app-server, just without the shared one.+ //+ // The blocker is the secret, not the plumbing: the per-node capability that closes the identity+ // routes' authorization hole is keychain-backed on the desktop (Electron `safeStorage`, see+ // src/main/codex-node-auth-secret.ts) and there is no equivalent on a headless Linux host. The+ // only way to arm this here is a secret at rest in the data dir, which is a security decision+ // this slice is not entitled to make quietly. Wiring it up is exactly three calls at this spot —+ // `hookServer.setCodexNodeAuthSecret(secret)`, `setCodexThreadIdentityAuthSecret(secret)`,+ // `refreshCodexIdentityCaps()` — plus the same two `setCodexThread*Handler` registrations+ // src/main/index.ts makes; everything they call already lives in src/core and boots from+ // CorePlatform. Until that secret question is answered, saying "no" here is what keeps the+ // browser's Codex nodes identical to what they are today rather than half-armed.+ registerCodexIdentityIpc(() => UNKNOWN_CODEX_IDENTITY_CAPS)+// Claude subscription usage. Previously desktop-only — the browser bridge answered `null`, so// the pill never rendered in the Server Edition. The poll runs UNGATED here (the default), not// browser-gated: the phone reads this host's agent-status mirror over plain SSH with no browserdiff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex f94b22263..16408a7d6 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -17,7 +17,10 @@ import {hasPermissionMode,hasUsage,reportsOwnCopy,- RENAME_CAPABLE+ RENAME_CAPABLE,+ hasSharedIdentity,+ agentLaunchProgram,+ resumeCommand} from './config'describe('CONTEXT_LINK_CAPABLE', () => {@@ -178,12 +181,35 @@ describe('title read vs rename write', () => {for (const id of RENAME_CAPABLE) expect(canReadTitle(id), id).toBe(true)})- it('codex claims neither, for want of evidence', () => {- // Its slash-command set was not enumerable from the CLI, so neither leg has a measured basis.- expect(canReadTitle('codex')).toBe(false)+ it('codex reads but does not write — the same split gemini forced', () => {+ // With the shared app-server a codex node owns a THREAD, and that thread has a `Thread.name`+ // we can read over the server's own socket (core/codex-session-name.ts). There is still no+ // measured rename command, and one list for both legs would light the rename UI on a node+ // where the write silently does nothing.+ expect(canReadTitle('codex')).toBe(true)expect(canRename('codex')).toBe(false)})+ it('only codex has a shared identity, and it is asked through the helper', () => {+ expect(hasSharedIdentity('codex')).toBe(true)+ for (const id of ['claude', 'gemini', 'grok', 'opencode', 'custom:abc'] as const) {+ expect(hasSharedIdentity(id), id).toBe(false)+ }+ })++ it('the launch program is the bare CLI unless the caller says shared identity is available', () => {+ // The default is the pre-feature command, byte for byte: an unprobed machine, an SSH project,+ // a test, a call site that never opted in — all emit `codex`. Same shape as gatePermissionMode.+ expect(agentLaunchProgram('codex', 'codex')).toBe('codex')+ expect(agentLaunchProgram('codex', 'codex', false)).toBe('codex')+ expect(agentLaunchProgram('codex', 'codex', true)).toBe('nodeterm-codex')+ // A non-member never gets rerouted, whatever the caller claims.+ expect(agentLaunchProgram('claude', 'claude', true)).toBe('claude')+ expect(resumeCommand('codex', 'thread-1')).toBe('codex resume thread-1')+ expect(resumeCommand('codex', 'thread-1', true)).toBe('nodeterm-codex resume thread-1')+ expect(resumeCommand('claude', 'abc', true)).toBe('claude --resume abc')+ })+it('a custom agent claims neither', () => {expect(canReadTitle('custom:abc')).toBe(false)expect(canRename('custom:abc')).toBe(false)diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 155f9991b..1d07a66c0 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -145,9 +145,22 @@ export const RENAME_CAPABLE = ['claude', 'grok'] as const// INVARIANT (pinned in config.capabilities.test.ts): every RENAME_CAPABLE agent is also here. The// write leg pushes a name and the read leg is what confirms it settled.//-// codex is in NEITHER: its slash-command set could not be enumerated from the CLI, so neither leg-// has a measured basis — and a guess here costs a wrong node title, not a missing one.-export const TITLE_READ_CAPABLE = ['claude', 'grok', 'gemini'] as const+// codex joined the READ leg only, and for the same reason gemini did: with the shared app-server+// (SHARED_IDENTITY_CAPABLE below) a node owns a THREAD, and that thread carries a `Thread.name` we+// can read over the server's own socket (core/codex-session-name.ts). There is still no measured+// rename command, so it stays out of RENAME_CAPABLE — the read⊇write invariant holds either way.+export const TITLE_READ_CAPABLE = ['claude', 'codex', 'grok', 'gemini'] as const+// Agents whose canvas nodes share ONE managed CLI server per machine and keep a stable per-node+// identity inside it, instead of each node owning a whole process tree.+//+// Membership is what makes `buildPtyEnv` mint the per-node capability token, what makes+// `pty-manager` install + PATH-expose the generated launcher, and what lets a launch line address+// that launcher at all. Everything downstream asks `hasSharedIdentity(agentId)`; nothing may ask+// `agentId === 'codex'`, which is how this started and is what CLAUDE.md forbids.+//+// Only codex today: it is the only builtin with an app-server mode NodeTerm can attach many+// clients to. A second agent joins by being added here and writing its own launcher body.+export const SHARED_IDENTITY_CAPABLE = ['codex'] as const// Agents allowed to drive the canvas via the `nodeterm` CLI (open/show/write/close).// Discovery differs per agent: claude gets the manage-nodeterm-canvas skill; codex/gemini/// opencode a marker block in ~/.codex/AGENTS.md / ~/.gemini/GEMINI.md /@@ -207,6 +220,26 @@ export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)export const canReadTitle = (id: AgentId): boolean => includes(TITLE_READ_CAPABLE, id)export const canControlCanvas = (id: AgentId): boolean => includes(CANVAS_CONTROL_CAPABLE, id)export const hasPermissionMode = (id: AgentId): boolean => includes(PERMISSION_MODE_CAPABLE, id)+export const hasSharedIdentity = (id: AgentId): boolean => includes(SHARED_IDENTITY_CAPABLE, id)++/**+ * The program a launch line should name for `id`.+ *+ * `sharedIdentity` is the caller's answer to "will the managed launcher actually be there?", and+ * it is FALSE by default on purpose: every call site that has not opted in emits the bare CLI+ * command it always did, byte for byte. This is the same shape as `gatePermissionMode` — an+ * unknown or failed probe degrades to the bare command, never to a launch that cannot run.+ *+ * The launcher is addressed by NAME, not by path: `pty-manager` puts its directory first on the+ * session's PATH for exactly the agents in SHARED_IDENTITY_CAPABLE, so the pane shows a readable+ * command and a plain terminal's PATH is untouched.+ */+export const SHARED_IDENTITY_LAUNCHERS: Partial<Record<AgentId, string>> = { codex: 'nodeterm-codex' }++export function agentLaunchProgram(id: AgentId, base: string, sharedIdentity = false): string {+ if (!sharedIdentity || !hasSharedIdentity(id)) return base+ return SHARED_IDENTITY_LAUNCHERS[id] ?? base+}/** Does this agent's CLI report its own copies? Undefined (a plain terminal, a custom agent) is* `false` — nobody speaks for those, so nodeterm's own feedback is the only feedback there is. */export const reportsOwnCopy = (id: AgentId | undefined): boolean =>@@ -268,14 +301,18 @@ export function withSessionId(cmd: string, id: AgentId, sessionId: string): stri* Used on a cold restart (machine reboot) where the tmux session — and the live agent — are* gone, so the conversation must be reconstructed via the agent CLI's own `--resume`.* Returns null for non-resumable/custom agents or an unsafe/empty session id.+ *+ * `sharedIdentity` routes a SHARED_IDENTITY_CAPABLE agent's resume through the managed launcher,+ * so the resumed session re-claims the node's own thread instead of opening it as an anonymous+ * client. Default false = the bare command this has always emitted (see `agentLaunchProgram`).*/-export function resumeCommand(id: AgentId, sessionId: string): string | null {+export function resumeCommand(id: AgentId, sessionId: string, sharedIdentity = false): string | null {if (!canResume(id)) return nullconst sid = sessionId.trim()if (!sid || !SAFE_SESSION_ID.test(sid)) return nullswitch (id) {case 'codex':- return `codex resume ${sid}`+ return `${agentLaunchProgram('codex', 'codex', sharedIdentity)} resume ${sid}`case 'opencode':return `opencode --session ${sid}`case 'claude':diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 28cad05eb..b28d14e2d 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -39,6 +39,11 @@ export const IPC = {claudeAccountsCancelWait: 'claude-accounts:cancel-wait',claudeAccountsRemove: 'claude-accounts:remove',claudeCliCaps: 'claude-cli:caps',+ /** Can a node on this machine get a managed Codex identity? See core/codex-identity-caps.ts. */+ codexIdentityCaps: 'codex-identity:caps',+ /** main/server → renderer: a Codex node's identity mode changed ('shared' | 'plain'). The+ * 'plain' events are what make the launcher's fallback visible instead of silent. */+ codexIdentity: 'codex-identity:event',transcriptSearch: 'transcript:search',appToggleMarkdown: 'app:toggle-markdown',appCloseNode: 'app:close-node',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 1fc74435d..0ada113fe 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1873,6 +1873,36 @@ export const UNKNOWN_CLAUDE_CLI_CAPS: ClaudeCliCaps = {sessionIdFlag: false}+/** Whether a Codex node launched on this machine right now would get a managed shared identity.+ * Fed by core/codex-identity-caps.ts; the unknown answer is `false`, i.e. plain `codex`. */+export interface CodexIdentityCaps {+ shared: boolean+ /** Absolute path of the installed launcher, or null when it could not be written. */+ launcherPath: string | null+}++/** The answer before the probe has run, and the one the Server Edition gives on purpose. */+export const UNKNOWN_CODEX_IDENTITY_CAPS: CodexIdentityCaps = { shared: false, launcherPath: null }++/** A Codex node's identity mode, as reported by the node's own launcher at spawn time.+ * `plain` carries the machine-readable reason the managed identity was unavailable. */+export interface CodexIdentityEvent {+ nodeId: string+ mode: 'shared' | 'plain'+ reason?: string+}++/** The Codex-specific surface. Small on purpose: everything else a Codex node needs already goes+ * through the shared agent/pty APIs. */+export interface CodexApi {+ /** Would a Codex node launched right now get a managed shared identity on this machine?+ * Never rejects — the unknown answer is `{ shared: false }`, i.e. plain `codex`. */+ identityCaps(): Promise<CodexIdentityCaps>+ /** Fires when a Codex node's launcher reports its identity mode. `plain` is the fallback, and+ * this event is what stops that fallback being silent. Returns unsubscribe. */+ onIdentity(listener: (e: CodexIdentityEvent) => void): () => void+}+export interface ClaudeApi {/** Capabilities of the local Claude CLI (memoized in the shell; safe to call repeatedly).* Never rejects — an unknown version resolves to the fail-open caps. */@@ -2146,6 +2176,7 @@ export interface NodeTerminalApi {sessionMemory: SessionMemoryApicontext: ContextApicanvas: CanvasApi+ codex: CodexApiclaude: ClaudeApichat: ChatApiclaudeAccounts: ClaudeAccountsApi