Skip to content

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.

fix(codex): resume sessions after daemon reset

freshjuicezfcd5ac546783
diff --git a/CLAUDE.md b/CLAUDE.md
index cbc7ca07c..ed5aef7d9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -395,6 +395,24 @@ Lifecycle, by intent:
The refusal is **only** in `spawnNew` — a co-attach JOIN to a live session for that node id is
still correct. An offline node reports itself to `SshReconnector`, so the canvas heals itself;
`retryNow` (banner Reconnect / node Reconnect) skips the backoff and clears the refuse window.
+- **A shared Codex daemon restart is NOT a terminal-session restart.** tmux survives, and the Codex
+ rollout/thread survives, but every `codex --remote unix://` TUI attached to that account's one
+ app-server socket exits together. `buildCodexLauncherScript` therefore stays in the pane as a
+ bounded transport supervisor after binding a thread instead of `exec`ing the remote TUI. On an
+ abnormal client exit it resumes that exact thread only when `app-server daemon version` no longer
+ reports `status: running` or the known control-socket inode changed; the same healthy generation
+ returns the original status so a deterministic CLI error cannot relaunch forever. A reconnect
+ never replays the launch prompt/options (that would duplicate the user's turn), and three rapid
+ resets stop with a manual `codex resume <thread>` receipt. Preflight probes live protocol health
+ before lifecycle start: Codex's PID ownership record can go stale while the shared process remains
+ responsive, and killing that "orphan" would fan one bookkeeping failure out across every node.
+ The generated-shell tests run the replaced-socket, missing-daemon, healthy-client-error, and
+ responsive-orphan cases under real `/bin/sh`; the healthy-error case is the mutation guard.
+ **Both shells wire this spine.** Electron and Server Edition arm the same signed record secret,
+ thread start/bind handlers, capability refresh, and UI identity events; the server composition is
+ isolated in `server/codex-shared-identity.ts` and behavior-tested. The old Server Edition
+ "deliberate plain Codex" answer bypassed the launcher entirely, so a reconnect implementation in
+ the launcher could be perfectly green while every headless pane still fell back to its shell.
- **"Restart agent (resume)"** → deliberately NOT a session lifecycle event: `terminal/
agent-restart.ts` restarts the agent CLI *inside* the pane and leaves the PTY, the tmux session
and its scrollback untouched. It exists for **new-model pickup** — a freshly released model only
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e63c9a0a3..dac6ab5d9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -114,6 +114,14 @@ come from git-shared JSON and can end up interpolated into a shell command line.
`/bin/sh` against a fixture tree. A composed fixture will not tell you that `echo ##MEM` prints an
empty line because `#` starts a comment.
+**A shared agent daemon is live-session infrastructure.** Codex's app-server control socket is
+shared by every `--remote` TUI in an account scope, so stopping or replacing one daemon disconnects
+every attached canvas node. A managed launcher must keep the already-bound thread under a bounded
+supervisor: resume only when protocol health failed or the known socket generation changed, never
+loop an unrelated client error, and never replay the original prompt after reconnect. Probe a
+responsive daemon before invoking lifecycle repair; stale PID bookkeeping is not permission to kill
+working sessions. See `docs/shared-codex-node-identity.md`.
+
**Credentials never ride argv — local or SSH.** Not a tmux `-e` pair, not `curl -H`, not a remote
command string. `/proc/<pid>/cmdline` is mode 444 on a stock Linux, and a remote command line is argv
on the host too: we shipped the hook bearer that way and any other account on the machine could read
diff --git a/docs/shared-codex-node-identity.md b/docs/shared-codex-node-identity.md
index 954f21d10..0a9483bc1 100644
--- a/docs/shared-codex-node-identity.md
+++ b/docs/shared-codex-node-identity.md
@@ -53,6 +53,39 @@ collide; a remote host has one home root, so the remote digest is over `accountI
pre-migration long home (`<userData>/codex-accounts/<id>`) is moved to its short home at boot,
fail-closed (no-op if absent, if the target exists, or on an invalid id).
+## Shared-daemon restart continuity
+
+The control socket is not one process per canvas node. Every `codex --remote unix://` TUI for an
+account scope rides one persistent app-server, so an app-server upgrade, repair, or crash severs all
+of them at once. Their tmux panes and Codex rollouts remain intact, but without a client supervisor
+each pane drops back to its shell and looks like a reset.
+
+The generated launcher therefore owns the remote client for the lifetime of the bound thread:
+
+1. It records the app-server control socket's inode before launching the TUI.
+2. A normal exit or terminal signal returns unchanged.
+3. After any other exit, it retries only when `codex app-server daemon version` does not report
+ `status: running`, or when a known pre-launch socket inode changed. A failed inode read alone is
+ unknown, not proof of a reset; an unrelated Codex failure against the same healthy generation
+ returns its original status.
+4. It starts a missing daemon through the same scrubbed environment used at preflight, then resumes
+ the exact already-bound thread. Only the first launch receives the caller's prompt/options;
+ recovery never replays them because that could submit the same user turn twice.
+5. Three rapid resets stop the loop and print the exact manual `codex resume <thread>` command.
+
+Protocol health is checked before lifecycle start. Codex's PID ownership record can become stale
+while the socket remains responsive; that bookkeeping failure must not trigger a kill of live,
+shared infrastructure. The behavior is failure-injection tested under real `/bin/sh` in
+`src/core/codex-launcher-sh.test.ts`, including a mutation guard proving that a healthy
+same-generation client error is not relaunched.
+
+Desktop and Server Edition both wire this same core spine. The headless shell arms the
+restart-stable record secret, registers thread start/bind handlers against its persisted canvas,
+refreshes the launcher capability, and broadcasts identity mode through its normal browser RPC.
+Mobile needs no separate implementation: it attaches to the Server Edition's existing tmux
+session. Managed Codex account administration remains desktop-only; that is separate from
+supervising the system account's shared app-server on the server host.
+
## The signing secret (both shells — Decision 1)
Every ownership record is HMAC-signed by the **one** restart-stable 32-byte node-auth secret
diff --git a/src/core/codex-identity-caps.ts b/src/core/codex-identity-caps.ts
index a70c75432..26116c811 100644
--- a/src/core/codex-identity-caps.ts
+++ b/src/core/codex-identity-caps.ts
@@ -37,9 +37,9 @@
* `--remote` dies on a clap usage error after that exec, where there is no fallback left. So
* it is answered here, once per app run, entirely off the launch path.
*
- * 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.
+ * SERVER EDITION: `src/server` registers the same async answer after arming its raw-0600 node
+ * secret. The shared identity is core-owned and local on that host; no Electron primitive is
+ * required.
*/
import { execFile } from 'child_process'
import { accessSync, constants } from 'fs'
diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.ts
index fcd10558e..492901e41 100644
--- a/src/core/codex-identity-proxy.ts
+++ b/src/core/codex-identity-proxy.ts
@@ -505,21 +505,27 @@ export function codexLauncherPath(): string {
/**
* 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.
+ * Every identity-setup 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. Once a shared thread is bound, the launcher remains as its transport supervisor.
*
* 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.
+ * with a machine-readable reason, and the desktop marks the node. Nothing is injected into a live
+ * agent TUI — text injected into an agent's terminal is prompt injection, which this repo forbids.
+ * The supervisor may print a transport status only after the TUI has exited.
*
- * `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).
+ * `appServerStartCommand` and `appServerProbeCommand` are 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'
+ appServerStartCommand = 'codex app-server daemon start >/dev/null 2>&1',
+ appServerProbeCommand =
+ `codex app-server daemon version 2>/dev/null | ` +
+ `grep -q '"status"[[:space:]]*:[[:space:]]*"running"'`
): string {
return `#!/bin/sh
# Generated by NodeTerm. Do not edit — it is rewritten on every launch.
@@ -531,6 +537,100 @@ nt_reason=''
nt_node_token=''
nt_fail() { nt_reason=$1; return 1; }
+# The app-server is shared by every Codex node in this account scope. Keep ALL lifecycle starts in
+# one scrubbed subshell: starting it with a pane's NODETERM_NODE_ID leaks that one node into every
+# tool shell the persistent daemon later creates (#350). The account id is deliberately retained —
+# one daemon serves one account scope.
+nt_start_app_server() (
+ unset NODETERM_NODE_ID NODETERM_HOOK_ENDPOINT NODETERM_HOOK_PORT NODETERM_HOOK_TOKEN \
+ NODETERM_HOOK_SOCK NODETERM_AGENT_ID NODETERM_CANVAS_CONTROL NODETERM_NODE_TOKEN_DIR \
+ NODETERM_PERM_WAIT_SECS
+ ${appServerStartCommand}
+)
+
+nt_app_server_ready() (
+ ${appServerProbeCommand}
+)
+
+# A successful remote TUI can still be severed later when the shared daemon is upgraded, repaired,
+# or restarted. The Unix socket inode is the daemon generation we can observe without intercepting
+# the TUI's terminal streams. A failed read is UNKNOWN, not evidence of a restart; it is useful only
+# when a known pre-launch inode changes or the authoritative daemon probe fails.
+nt_app_server_generation() {
+ nt_socket="\${CODEX_HOME:-$HOME/.codex}/app-server-control/app-server-control.sock"
+ [ -e "$nt_socket" ] || return 1
+ ls -di "$nt_socket" 2>/dev/null | awk 'NR == 1 { print $1 }'
+}
+
+nt_epoch() {
+ date +%s 2>/dev/null || printf '0\\n'
+}
+
+# Run a known thread under supervision. Normal exits and terminal signals return unchanged. An
+# abnormal exit is resumed ONLY when the daemon probe failed or the known socket generation
+# changed; a Codex crash against the same healthy daemon must not become a relaunch loop. The
+# caller's prompt/options are one-shot and run only on the first launch — replaying an initial
+# prompt after transport recovery would duplicate the user's turn.
+nt_run_shared() {
+ nt_shared_thread=$1
+ shift
+ nt_first_launch=1
+ nt_rapid_resets=0
+
+ while :; do
+ nt_generation_before=$(nt_app_server_generation) || nt_generation_before=''
+ nt_run_started=$(nt_epoch)
+
+ if [ "$nt_first_launch" -eq 1 ]; then
+ codex --remote unix:// resume "$nt_shared_thread" "$@"
+ else
+ codex --remote unix:// resume "$nt_shared_thread"
+ fi
+ nt_status=$?
+
+ case "$nt_status" in
+ 0|129|130|131|143) return "$nt_status" ;;
+ esac
+
+ nt_generation_after=$(nt_app_server_generation) || nt_generation_after=''
+ nt_daemon_reset=0
+ if ! nt_app_server_ready; then
+ nt_daemon_reset=1
+ elif [ -n "$nt_generation_before" ] && \
+ [ "$nt_generation_before" != "$nt_generation_after" ]; then
+ nt_daemon_reset=1
+ fi
+ [ "$nt_daemon_reset" -eq 1 ] || return "$nt_status"
+
+ nt_run_ended=$(nt_epoch)
+ if [ "$nt_run_started" -gt 0 ] && [ "$nt_run_ended" -ge "$nt_run_started" ] && \
+ [ $((nt_run_ended - nt_run_started)) -ge 10 ]; then
+ nt_rapid_resets=0
+ fi
+ nt_rapid_resets=$((nt_rapid_resets + 1))
+ if [ "$nt_rapid_resets" -gt 3 ]; then
+ printf '\\nNodeTerm: Codex daemon kept resetting; automatic resume stopped. Run: codex resume %s\\n' \
+ "$nt_shared_thread" >&2
+ return "$nt_status"
+ fi
+
+ printf '\\nNodeTerm: shared Codex connection reset; restoring this session...\\n' >&2
+ nt_start_try=0
+ while ! nt_app_server_ready; do
+ nt_start_app_server || :
+ nt_app_server_ready && break
+ nt_start_try=$((nt_start_try + 1))
+ if [ "$nt_start_try" -ge 3 ]; then
+ printf 'NodeTerm: shared Codex daemon did not recover. Run: codex resume %s\\n' \
+ "$nt_shared_thread" >&2
+ return "$nt_status"
+ fi
+ sleep "$nt_start_try"
+ done
+ nt_first_launch=0
+ done
+}
+
nt_hook_curl() { curl "$@"; }
if [ -n "\${NODETERM_HOOK_SOCK-}" ]; then
case "$NODETERM_HOOK_SOCK" in
@@ -603,19 +703,12 @@ nt_preflight() {
# here entirely, but the pane resolves CODEX_HOME from its OWN environment (§8.5) and an install
# can be removed after boot, so the launcher still has to be able to say which it hit.
#
- # The app-server is a PERSISTENT DAEMON: the FIRST codex node to reach here starts it and every
- # later node reuses it. Start it in a SUBSHELL with THIS node's per-pane NODETERM_* scrubbed, or
- # the daemon — and every tool shell it later spawns for EVERY node — would inherit this one node's
- # NODETERM_NODE_ID. The thread → node resolver (codex-thread-identity-sh.ts) only recovers the
- # right node when a tool shell has NO NODETERM_NODE_ID; a leaked value makes its guard no-op and
- # silently collapses every codex node's identity onto whichever node started the daemon, so
- # Project B's codex lists Project A's links and routes to A (#350). NODETERM_CODEX_ACCOUNT_ID is
- # the ONE var deliberately KEPT: one daemon serves one account, and the resolver reads it from the
- # daemon's env to pick the record scope. The unset runs BEFORE the (test-injected) start command.
- if ( unset NODETERM_NODE_ID NODETERM_HOOK_ENDPOINT NODETERM_HOOK_PORT NODETERM_HOOK_TOKEN \\
- NODETERM_HOOK_SOCK NODETERM_AGENT_ID NODETERM_CANVAS_CONTROL NODETERM_NODE_TOKEN_DIR \\
- NODETERM_PERM_WAIT_SECS
- ${appServerStartCommand} ); then
+ # A responsive app-server is authoritative even when Codex's PID ownership record has gone stale.
+ # Calling the lifecycle start first can reject that harmless orphan and degrade this node to plain
+ # codex — or tempt a repair to kill infrastructure shared by every pane. Probe first; start only
+ # when the protocol itself is not running. nt_start_app_server owns the environment scrub as well
+ # as the later recovery path, so duplicating its unset list here would let one path drift into #350.
+ if nt_app_server_ready || nt_start_app_server; then
return 0
fi
if [ -x "\${CODEX_HOME:-$HOME/.codex}/packages/standalone/current/codex" ]; then
@@ -665,7 +758,10 @@ if [ "\${1-}" = resume ]; then
if nt_post 20 --data-urlencode "nodeId=$NODETERM_NODE_ID" --data-urlencode "threadId=\${2-}" \\
--data-urlencode "accountId=\${NODETERM_CODEX_ACCOUNT_ID-}" \\
"http://localhost:\${NODETERM_HOOK_PORT-0}/codex-thread/bind" >/dev/null; then
- exec codex --remote unix:// "$@"
+ nt_bound_thread=$2
+ shift 2
+ nt_run_shared "$nt_bound_thread" "$@"
+ exit $?
fi
nt_report_fallback thread-bind-refused
exec codex "$@"
@@ -681,7 +777,8 @@ case "$nt_thread" in
exec codex "$@"
;;
esac
-exec codex --remote unix:// resume "$nt_thread" "$@"
+nt_run_shared "$nt_thread" "$@"
+exit $?
`
}
diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.ts
index a8c204dcd..ef221df16 100644
--- a/src/core/codex-launcher-sh.test.ts
+++ b/src/core/codex-launcher-sh.test.ts
@@ -43,11 +43,11 @@ let startAnswer: (() => string) | null = null
let startDelayMs = 0
let bindAnswer: (() => void) | null = null
-/** A stand-in for the real `codex`, which records how it was invoked and exits 0. */
-function writeFakeCodex(): void {
+/** A stand-in for the real `codex`, which records how it was invoked before the injected body. */
+function writeFakeCodex(body = 'exit 0'): void {
fs.writeFileSync(
path.join(binDir, 'codex'),
- `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}\nexit 0\n`,
+ `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}\n${body}\n`,
{ mode: 0o755 }
)
}
@@ -61,8 +61,9 @@ beforeAll(async () => {
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 })
+ // `true` stands in for `codex app-server daemon start`; `false` makes preflight exercise that
+ // start rather than calling the fake client as a health probe. Health-specific cases override it.
+ fs.writeFileSync(launcher, buildCodexLauncherScript('true', 'false'), { mode: 0o755 })
await hookServer.start()
hookServer.setNodeAuthSecret(SECRET)
hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, accountId }) => {
@@ -206,7 +207,9 @@ describe('generated Codex launcher', () => {
{ mode: 0o755 }
)
const script2 = path.join(dir, 'nodeterm-codex-envdump')
- fs.writeFileSync(script2, buildCodexLauncherScript(JSON.stringify(dumpScript)), { mode: 0o755 })
+ fs.writeFileSync(script2, buildCodexLauncherScript(JSON.stringify(dumpScript), 'false'), {
+ mode: 0o755
+ })
await callLauncher([], { NODETERM_CODEX_ACCOUNT_ID: 'acct-A' }, script2)
@@ -228,7 +231,9 @@ describe('generated Codex launcher', () => {
const dumpScript = path.join(dir, 'dump-daemon-env-endpointfail.sh')
fs.writeFileSync(dumpScript, `#!/bin/sh\n: > ${JSON.stringify(envDump)}\n`, { mode: 0o755 })
const script2 = path.join(dir, 'nodeterm-codex-endpointfail')
- fs.writeFileSync(script2, buildCodexLauncherScript(JSON.stringify(dumpScript)), { mode: 0o755 })
+ fs.writeFileSync(script2, buildCodexLauncherScript(JSON.stringify(dumpScript), 'false'), {
+ mode: 0o755
+ })
await callLauncher(['do', 'work'], { NODETERM_HOOK_ENDPOINT: '/nonexistent/hook-endpoint.env' }, script2)
@@ -252,6 +257,120 @@ describe('generated Codex launcher', () => {
expect(codexArgv()).toEqual(['--remote unix:// resume thread-xyz'])
})
+ // A daemon update/restart closes every attached `--remote` TUI at once. The launcher used to
+ // `exec` the client, so the surviving tmux pane fell back to a shell even though the rollout was
+ // intact. Run the generated shell for real and replace the socket inode while the first fake
+ // client fails: the same thread must come back automatically, and the one-shot prompt MUST NOT be
+ // replayed (that would duplicate the user's turn after a transport-only failure).
+ it('resumes the same thread after the shared daemon socket is replaced, without replaying args', async () => {
+ const codexHome = path.join(dir, 'daemon-replaced-home')
+ const socketDir = path.join(codexHome, 'app-server-control')
+ const socket = path.join(socketDir, 'app-server-control.sock')
+ const failedOnce = path.join(dir, 'daemon-replaced-once')
+ fs.mkdirSync(socketDir, { recursive: true })
+ fs.writeFileSync(socket, 'generation-one')
+ fs.rmSync(failedOnce, { force: true })
+ writeFakeCodex(
+ `case "$*" in\n` +
+ ` --remote*)\n` +
+ ` if [ ! -e ${JSON.stringify(failedOnce)} ]; then\n` +
+ ` : > ${JSON.stringify(failedOnce)}\n` +
+ // Rename a second inode over the marker; unlink+create may immediately reuse one inode.
+ ` printf next > ${JSON.stringify(`${socket}.next`)}\n` +
+ ` mv ${JSON.stringify(`${socket}.next`)} ${JSON.stringify(socket)}\n` +
+ ` exit 1\n` +
+ ` fi\n` +
+ ` ;;\n` +
+ `esac\n` +
+ `exit 0`
+ )
+ const recovering = path.join(dir, 'nodeterm-codex-replaced-daemon')
+ fs.writeFileSync(recovering, buildCodexLauncherScript('true', 'true'), { mode: 0o755 })
+
+ const result = await callLauncher(
+ ['--ask-for-approval', 'never', 'fix the bug'],
+ { CODEX_HOME: codexHome },
+ recovering
+ )
+
+ expect(codexArgv()).toEqual([
+ '--remote unix:// resume thread-abc --ask-for-approval never fix the bug',
+ '--remote unix:// resume thread-abc'
+ ])
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])
+ expect(result.stderr).toContain('shared Codex connection reset; restoring this session')
+ })
+
+ // Mutation guard for the generation/health condition above: an unrelated Codex client failure
+ // against the SAME healthy daemon returns to the shell once. Removing that condition makes this
+ // test log four launches (and turns every deterministic CLI error into a restart loop).
+ it('does not relaunch an unrelated client failure against the same healthy daemon', async () => {
+ const codexHome = path.join(dir, 'daemon-healthy-home')
+ const socketDir = path.join(codexHome, 'app-server-control')
+ fs.mkdirSync(socketDir, { recursive: true })
+ fs.writeFileSync(path.join(socketDir, 'app-server-control.sock'), 'same-generation')
+ writeFakeCodex('case "$*" in --remote*) exit 7 ;; esac\nexit 0')
+ const guarded = path.join(dir, 'nodeterm-codex-healthy-daemon')
+ fs.writeFileSync(guarded, buildCodexLauncherScript('true', 'true'), { mode: 0o755 })
+
+ await expect(callLauncher([], { CODEX_HOME: codexHome }, guarded)).rejects.toMatchObject({
+ code: 7
+ })
+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-abc'])
+ })
+
+ it('starts a missing daemon and then resumes the same thread', async () => {
+ const codexHome = path.join(dir, 'daemon-missing-home')
+ const socketDir = path.join(codexHome, 'app-server-control')
+ const socket = path.join(socketDir, 'app-server-control.sock')
+ const failedOnce = path.join(dir, 'daemon-missing-once')
+ const starts = path.join(dir, 'daemon-starts.log')
+ fs.mkdirSync(socketDir, { recursive: true })
+ fs.rmSync(socket, { force: true })
+ fs.rmSync(failedOnce, { force: true })
+ fs.writeFileSync(starts, '')
+ writeFakeCodex(
+ `case "$*" in\n` +
+ ` --remote*)\n` +
+ ` if [ ! -e ${JSON.stringify(failedOnce)} ]; then\n` +
+ ` : > ${JSON.stringify(failedOnce)}\n` +
+ ` rm -f ${JSON.stringify(socket)}\n` +
+ ` exit 1\n` +
+ ` fi\n` +
+ ` ;;\n` +
+ `esac\n` +
+ `exit 0`
+ )
+ const startCommand =
+ `printf 'start\\n' >> ${JSON.stringify(starts)}; ` +
+ `mkdir -p ${JSON.stringify(socketDir)}; : > ${JSON.stringify(socket)}`
+ const probeCommand = `[ -e ${JSON.stringify(socket)} ]`
+ const recovering = path.join(dir, 'nodeterm-codex-missing-daemon')
+ fs.writeFileSync(recovering, buildCodexLauncherScript(startCommand, probeCommand), {
+ mode: 0o755
+ })
+
+ await callLauncher(['resume', 'thread-xyz'], { CODEX_HOME: codexHome }, recovering)
+
+ expect(codexArgv()).toEqual([
+ '--remote unix:// resume thread-xyz',
+ '--remote unix:// resume thread-xyz'
+ ])
+ // Once during preflight, once after the fake transport failure removed the socket.
+ expect(fs.readFileSync(starts, 'utf8').trim().split('\n')).toEqual(['start', 'start'])
+ })
+
+ it('uses a responsive orphaned daemon without invoking its refusing lifecycle start', async () => {
+ const running = path.join(dir, 'nodeterm-codex-running-orphan')
+ fs.writeFileSync(running, buildCodexLauncherScript('false', 'true'), { mode: 0o755 })
+
+ await callLauncher([], {}, running)
+
+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-abc'])
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])
+ expect(fallbacks).toEqual([])
+ })
+
// S6: the account scope travels in the POST body, never on argv (Constraint 6), so the record is
// filed under the right account. An empty id (the system account) reaches the handler as undefined.
it('threads the managed account id through start (in the body, not on argv)', async () => {
@@ -337,7 +456,7 @@ describe('falls back to plain codex', () => {
fs.writeFileSync(path.join(runtime, 'codex'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
try {
const noServer = path.join(dir, 'nodeterm-codex-no-server')
- fs.writeFileSync(noServer, buildCodexLauncherScript('false'), { mode: 0o755 })
+ fs.writeFileSync(noServer, buildCodexLauncherScript('false', 'false'), { mode: 0o755 })
await callLauncher(['hello'], {}, noServer)
expect(codexArgv()).toEqual(['hello'])
expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'app-server-unavailable' }])
@@ -352,7 +471,7 @@ describe('falls back to plain codex', () => {
// The caps probe normally keeps this case away from the launcher entirely — but the pane
// resolves CODEX_HOME from its OWN environment (§8.5) and an install can be removed after boot.
const noServer = path.join(dir, 'nodeterm-codex-no-standalone')
- fs.writeFileSync(noServer, buildCodexLauncherScript('false'), { mode: 0o755 })
+ fs.writeFileSync(noServer, buildCodexLauncherScript('false', 'false'), { mode: 0o755 })
await callLauncher(['hello'], {}, noServer)
expect(codexArgv()).toEqual(['hello'])
expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'codex-standalone-missing' }])
@@ -364,7 +483,7 @@ describe('falls back to plain codex', () => {
fs.mkdirSync(runtime, { recursive: true })
fs.writeFileSync(path.join(runtime, 'codex'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
const noServer = path.join(dir, 'nodeterm-codex-relocated')
- fs.writeFileSync(noServer, buildCodexLauncherScript('false'), { mode: 0o755 })
+ fs.writeFileSync(noServer, buildCodexLauncherScript('false', 'false'), { mode: 0o755 })
await callLauncher(['hello'], { CODEX_HOME: home }, noServer)
expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'app-server-unavailable' }])
})
diff --git a/src/server/codex-shared-identity.test.ts b/src/server/codex-shared-identity.test.ts
new file mode 100644
index 000000000..a9d2bb35d
--- /dev/null
+++ b/src/server/codex-shared-identity.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest'
+import { IPC } from '../shared/ipc'
+import type { CodexIdentityEvent } from '../shared/types'
+import type { ServerCodexIdentityDeps } from './codex-shared-identity'
+import { wireServerCodexSharedIdentity } from './codex-shared-identity'
+
+describe('Server Edition shared Codex identity wiring', () => {
+ it('wires start, bind, liveness, UI broadcast, and the capability refresh', async () => {
+ let identityListener: ((event: CodexIdentityEvent) => void) | undefined
+ let startHandler: ((request: any) => Promise<string>) | undefined
+ let bindHandler: ((request: any) => Promise<void>) | undefined
+ const hooks = {
+ setCodexIdentityListener: (listener: typeof identityListener) => (identityListener = listener),
+ setCodexThreadStartHandler: (handler: typeof startHandler) => (startHandler = handler),
+ setCodexThreadBindHandler: (handler: typeof bindHandler) => (bindHandler = handler)
+ }
+ const liveNodes = new Set(['node-live'])
+ const broadcast = vi.fn()
+ const refresh = vi.fn(async () => undefined)
+ const start = vi.fn(async () => 'thread-new')
+ const exists = vi.fn(async (threadId: string) => threadId === 'thread-known')
+ const write = vi.fn()
+ const bind = vi.fn()
+ const deps: ServerCodexIdentityDeps = { refresh, start, exists, write, bind }
+
+ await wireServerCodexSharedIdentity(
+ hooks,
+ { getNode: (nodeId) => (liveNodes.has(nodeId) ? { id: nodeId } : undefined) },
+ broadcast,
+ deps
+ )
+
+ expect(refresh).toHaveBeenCalledOnce()
+ const event: CodexIdentityEvent = { nodeId: 'node-new', mode: 'shared' }
+ identityListener?.(event)
+ expect(broadcast).toHaveBeenCalledWith(IPC.codexIdentity, event)
+
+ await expect(
+ startHandler?.({
+ nodeId: 'node-new',
+ cwd: '/repo',
+ hookEndpoint: '/data/hook',
+ accountId: 'acct-A'
+ })
+ ).resolves.toBe('thread-new')
+ expect(write).toHaveBeenCalledWith(
+ 'thread-new',
+ 'node-new',
+ '/data/hook',
+ undefined,
+ 'acct-A'
+ )
+
+ await expect(
+ bindHandler?.({
+ nodeId: 'node-new',
+ threadId: 'thread-missing',
+ hookEndpoint: '/data/hook'
+ })
+ ).rejects.toThrow('unknown to the shared app-server')
+ expect(bind).not.toHaveBeenCalled()
+
+ await bindHandler?.({
+ nodeId: 'node-new',
+ threadId: 'thread-known',
+ hookEndpoint: '/data/hook',
+ accountId: 'acct-A'
+ })
+ expect(bind).toHaveBeenCalledOnce()
+ const nodeIsLive = bind.mock.calls[0][3] as (nodeId: string) => boolean
+ expect(nodeIsLive('node-live')).toBe(true)
+ expect(nodeIsLive('node-gone')).toBe(false)
+ expect(bind).toHaveBeenCalledWith(
+ 'thread-known',
+ 'node-new',
+ '/data/hook',
+ nodeIsLive,
+ undefined,
+ 'acct-A'
+ )
+ })
+})
diff --git a/src/server/codex-shared-identity.ts b/src/server/codex-shared-identity.ts
new file mode 100644
index 000000000..d87e502ae
--- /dev/null
+++ b/src/server/codex-shared-identity.ts
@@ -0,0 +1,85 @@
+/**
+ * Server Edition wiring for the same shared Codex identity spine the Electron shell uses.
+ *
+ * Core owns the launcher, thread RPC, signed ownership records, and capability probe. The server
+ * shell contributes only its live-node lookup and broadcast channel. Keeping this composition in
+ * one function makes the headless production path behavior-testable without booting an HTTP server.
+ */
+import { IPC } from '../shared/ipc'
+import type { CodexIdentityEvent } from '../shared/types'
+import { hookServer } from '../core/agents/hook-server'
+import {
+ bindCodexThreadIdentity,
+ writeCodexThreadIdentity
+} from '../core/codex-identity-proxy'
+import { refreshCodexIdentityCaps } from '../core/codex-identity-caps'
+import { codexThreadExists, startCodexThread } from '../core/codex-session-name'
+
+type SharedIdentityHook = Pick<
+ typeof hookServer,
+ 'setCodexIdentityListener' | 'setCodexThreadStartHandler' | 'setCodexThreadBindHandler'
+>
+
+type NodeLookup = { getNode(nodeId: string): unknown }
+
+export interface ServerCodexIdentityDeps {
+ refresh(): Promise<unknown>
+ start(cwd: string): Promise<string>
+ exists(threadId: string): Promise<boolean>
+ write(
+ threadId: string,
+ nodeId: string,
+ hookEndpoint: string,
+ root?: string,
+ accountId?: string
+ ): void
+ bind(
+ threadId: string,
+ nodeId: string,
+ hookEndpoint: string,
+ nodeIsLive: (nodeId: string) => boolean,
+ root?: string,
+ accountId?: string
+ ): void
+}
+
+const defaultDeps: ServerCodexIdentityDeps = {
+ refresh: refreshCodexIdentityCaps,
+ start: startCodexThread,
+ exists: codexThreadExists,
+ write: writeCodexThreadIdentity,
+ bind: bindCodexThreadIdentity
+}
+
+/** Arm shared-thread launch/bind behavior and publish identity-mode changes to browser clients. */
+export async function wireServerCodexSharedIdentity(
+ hooks: SharedIdentityHook,
+ nodes: NodeLookup,
+ broadcast: (channel: string, event: CodexIdentityEvent) => void,
+ deps: ServerCodexIdentityDeps = defaultDeps
+): Promise<void> {
+ hooks.setCodexIdentityListener((event) => broadcast(IPC.codexIdentity, event))
+ hooks.setCodexThreadStartHandler(async ({ nodeId, cwd, hookEndpoint, accountId }) => {
+ const threadId = await deps.start(cwd)
+ deps.write(threadId, nodeId, hookEndpoint, undefined, accountId)
+ return threadId
+ })
+ hooks.setCodexThreadBindHandler(
+ async ({ nodeId, threadId, hookEndpoint, accountId }) => {
+ // Never write an ownership record for a rollout the shared app-server cannot resume. The
+ // launcher interprets this refusal as its safe plain-Codex fallback.
+ if (!(await deps.exists(threadId))) {
+ throw new Error('Codex thread is unknown to the shared app-server')
+ }
+ deps.bind(
+ threadId,
+ nodeId,
+ hookEndpoint,
+ (ownerId) => !!nodes.getNode(ownerId),
+ undefined,
+ accountId
+ )
+ }
+ )
+ await deps.refresh()
+}
diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.ts
index 23e33956b..6f2055422 100644
--- a/src/server/handlers/index.ts
+++ b/src/server/handlers/index.ts
@@ -8,7 +8,6 @@ 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 { registerClaudeAccountsIpc } from '../../core/claude-accounts-service'
import { codexUsageAccounts } from '../../core/codex-accounts-core'
@@ -73,23 +72,9 @@ 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 secret question that used to block this is ANSWERED: src/server/index.ts arms
- // `hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())` at boot, which on a headless
- // host is raw 0600 bytes in the data dir — a decision taken explicitly, not quietly (see
- // src/core/agents/node-auth-secret.ts). As of S6 PR 5 the same boot path also calls
- // `setCodexThreadIdentityAuthSecret(secret)`, so a MANAGED Codex account's thread→node→account
- // ownership records sign and verify on this headless host instead of throwing "identity
- // authentication is unavailable" (the carried PR-2 obligation). What stays deliberately absent
- // here is the shared-app-server plumbing (`refreshCodexIdentityCaps()` + the two
- // `setCodexThread*Handler` registrations src/main/index.ts makes): the Server Edition answers "no
- // shared identity" so its Codex nodes launch the bare `codex` — a working node with its own
- // app-server, just without the shared one. Arming the record secret is orthogonal to that
- // degrade: it never launches an app-server, it only lets the record layer sign.
- registerCodexIdentityIpc(() => UNKNOWN_CODEX_IDENTITY_CAPS)
+ // The answer is populated after server node identity is armed. Early browser callers wait for
+ // that refresh instead of being pinned to a false "plain Codex" answer for the whole app run.
+ registerCodexIdentityIpc()
// Managed CLAUDE accounts (issue #313). The lifecycle is core, so a browser-only deployment can
// create, log into and remove them exactly as the desktop does — env injection, the transcript
diff --git a/src/server/index.ts b/src/server/index.ts
index b83b224d7..b34c8e2f8 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -50,6 +50,7 @@ import { hookServer } from '../core/agents/hook-server'
import { serverEditionControlHandler } from './control-unsupported'
import { refreshNodeTokens } from '../core/agents/node-token-service'
import { armServerNodeIdentity } from './node-identity-arm'
+import { wireServerCodexSharedIdentity } from './codex-shared-identity'
import {
writePendingAnswerLocal,
startPendingSweep,
@@ -548,6 +549,15 @@ export async function startServer(
console.warn('[node-identity] no secret — hook identity unavailable, running legacy', error)
}
+ // The Server Edition has the same local app-server, signed node tokens, and persistent canvas
+ // store as Electron. Wire the shared-thread spine after those secrets exist, so its Codex panes
+ // get the same daemon-reset supervisor instead of bypassing it through bare `codex`.
+ void wireServerCodexSharedIdentity(
+ hookServer,
+ workspaceStore,
+ (channel, event) => platform.broadcast(channel, event)
+ ).catch((error) => console.warn('[codex-identity] shared identity unavailable:', error))
+
// Context Link: core owns the whole feature (read handler, shim, skill, instruction blocks) and
// writes everything under `dataDir`; what it needs from a shell is the link map. The desktop's
// renderer pushes it from the live canvas — headless there may be no browser attached at all, so