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): keep every nodeterm Codex TUI out of Codex's auto-started shared daemon

reviewc88c8d46e075
diff --git a/CLAUDE.md b/CLAUDE.md
index a81a8d718..4f1001b79 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -765,6 +765,54 @@ 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.
+- **Codex's auto-started shared daemon: every nodeterm Codex TUI runs `--no-daemon`** (2026-09-30).
+ From codex-cli **0.157.0** the `daemon_auto_start` feature is `stable, true` (0.156.1:
+ `experimental, false`; 0.148.0: no such feature): a plain `codex` TUI no longer runs in-process
+ but starts, or JOINS, ONE background `app-server` per `CODEX_HOME`, and that daemon keeps the
+ environment of the pane that STARTED it and outlives it. The daemon is what spawns tool shells and
+ hook processes, and nodeterm tells a node apart by environment (`buildPtyEnv`). MEASURED on
+ 0.159.2 (private `CODEX_HOME`, private tmux socket, `env -i`): pane A (`NODETERM_NODE_ID=node-A`)
+ started the daemon; in pane B (`node-B`) the tool shell printed `node-A` and every hook process
+ logged `node-A` — pane B's status, canvas-control verbs and context-link reads were pane A's.
+ `--no-daemon` put pane C back on `node-C` in both; `-c features.daemon_auto_start=false` did NOT
+ (it still joins a RUNNING daemon); there is no environment switch. Transcript and the three help
+ pages: `src/core/__fixtures__/codex-daemon/`. Rules a refactor must not undo:
+ - **Feature-detected, fail open.** `core/codex-cli.ts` `codexNoDaemonFrom` reads the flag off the
+ option-header lines of the same memoized `codex --help` the approval vocabulary uses;
+ `CodexCliCaps.noDaemon` rides the existing `ApprovalCaps` bag (`codexNoDaemon`) that every launch
+ site already threads, and `withCodexNoDaemon` (`shared/agents/codex-daemon.ts`) appends it in
+ BOTH assemblers — fresh launch and resume (cold restore, restart, restart-with-model, account
+ switch, transfer, headless Server opens, custom agents whose `baseAgent` is codex, a launch-
+ command override). Only a literal `true` emits it: clap exits on an unknown option, so an
+ unprobed, remote-unknown or older CLI gets the line it always got.
+ - **Never beside `--remote`** — measured: `ERROR: --no-daemon cannot be used with --remote.` The
+ managed launcher (`buildCodexLauncherScript`) therefore STRIPS it before its own
+ `codex --remote unix:// resume` and routes every plain-codex fallback through `nt_exec_plain`,
+ which keeps it, or ADDS it when the codex about to run advertises it (the SSH launcher's host was
+ never probed from here). This matters beyond the fallback node itself: a daemon started by a
+ plain pane carries that pane's `NODETERM_NODE_ID`, and the thread-identity prelude only resolves
+ a tool shell whose `NODETERM_NODE_ID` is EMPTY — so one plain launch used to poison every managed
+ thread of that account too. Our own start stays the scrubbed `nt_start_app_server` (#350).
+ - **SSH: the HOST's binary is asked.** `core/remote-ssh/codex-no-daemon-probe.ts` runs one
+ marker-delimited `codex --help` through the login shell after connect (off the connect path, like
+ the claude probe) and publishes `{hostKey: user@host, supported}` on a `connected` event and on a
+ reused connect's result; the renderer keeps it per host (`useSshConn.codexNoDaemonByHost`) and
+ `codexApprovalCaps(remote)` reads it. Before it lands a remote line carries nothing.
+ - `codex exec` (commit messages), `login`, `mcp` and `app-server` take no such flag and are not
+ TUI clients of the daemon. The phone gets `MirrorSettings.codexNoDaemon` (iOS reader: follow-up,
+ @eneskirca). opencode was checked the same way: no published release has `serve --service`
+ (latest 1.18.33 and the `dev` channel), and a plain TUI leaves no process behind.
+ - **Residual, stated:** a `codex` the user TYPES by hand in a nodeterm plain terminal carries that
+ node's `NODETERM_NODE_ID` and, on 0.157+, can still start the account's daemon with it — until
+ that daemon restarts, managed threads' tool shells then keep the leaked id (the prelude skips a
+ set one). Changing the prelude to prefer the thread record over a set id was rejected: a
+ bind-refused fallback pane legitimately runs a thread another node's record names.
+ - **Device checklist:** (a) macOS desktop, npm codex ≥ 0.157: two Codex nodes, each RUNNING badge
+ and `nodeterm list` line on its own node; (b) standalone codex with shared identity: a node
+ whose launcher fell back still reports as itself; (c) SSH project on a host with codex ≥ 0.157:
+ the second remote Codex node's badge is its own after the probe landed (and flagless before);
+ (d) Windows native codex: whether the daemon exists there at all is unmeasured — the flag rides
+ only if its `--help` lists it.
- **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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index aab67070c..aacd2e893 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -672,6 +672,16 @@ loop an unrelated client error, and never replay the original prompt after recon
responsive daemon before invoking lifecycle repair; stale PID bookkeeping is not permission to kill
working sessions. See `docs/shared-codex-node-identity.md`.
+**A plain Codex TUI must not join Codex's own auto-started daemon.** From codex-cli 0.157.0 a
+plain `codex` starts (or joins) ONE background app-server per `CODEX_HOME` that keeps the
+environment of the pane that STARTED it, so every later node's hooks and tool shells run with the
+first node's `NODETERM_NODE_ID` (measured on 0.159.2). Every nodeterm codex line therefore ends in
+`--no-daemon` when the CLI that will run it advertised the flag — added in the two assemblers
+(`shared/agents/launch.ts` via `withCodexNoDaemon`), fed by `ApprovalCaps.codexNoDaemon`. A new
+codex launch site goes through those assemblers and threads the caps; never type a bare `codex` line
+yourself. The flag must never meet `--remote` (codex refuses the pair), which is why the managed
+launcher strips it. See CLAUDE.md "Codex's auto-started shared daemon".
+
**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/src/core/__fixtures__/codex-daemon/README.md b/src/core/__fixtures__/codex-daemon/README.md
new file mode 100644
index 000000000..4bd0648c2
--- /dev/null
+++ b/src/core/__fixtures__/codex-daemon/README.md
@@ -0,0 +1,50 @@
+# Codex's auto-started shared app-server (`daemon_auto_start`)
+
+`help-<version>.txt` are the verbatim `codex --help` pages of three published npm builds, read by
+`codexNoDaemonFrom` (`src/core/codex-cli.ts`) and by the remote probe's real-shell test.
+
+| build | `codex features list` → `daemon_auto_start` | `--no-daemon` in `--help` |
+|---------|---------------------------------------------|---------------------------|
+| 0.148.0 | (no such feature) | no |
+| 0.156.1 | `experimental false` | yes |
+| 0.157.0 | `stable true` | yes |
+| 0.159.2 | `stable true` | yes |
+
+## The measurement (2026-09-30, Linux x86_64, codex-cli 0.159.2 from npm)
+
+Private `CODEX_HOME` (only `auth.json` copied in, 0600, the whole directory deleted afterwards), a
+fake `HOME`, a private tmux socket, and `env -i` so the only `NODETERM_*` variable in each pane is
+the `NODETERM_NODE_ID` set deliberately. A `hooks.json` in that home (trusted through
+`codex-trust.ts`) appended `NODETERM_NODE_ID` of every SessionStart / UserPromptSubmit /
+PreToolUse hook process to a log. Paths below are shortened.
+
+```
+pane A: env -i … NODETERM_NODE_ID=node-A codex -a never -s danger-full-access
+ → CODEX_HOME/app-server-daemon/daemon.pid, app-server-control/app-server-control.sock
+ → process: …/packages/app-server-daemon/releases/0.159.2-…/bin/codex app-server --listen unix:// --managed-daemon
+ /proc/<daemon>/environ: CODEX_HOME=… HOME=… NODETERM_NODE_ID=node-A …
+ (the daemon outlives pane A's TUI)
+
+pane B: … NODETERM_NODE_ID=node-B codex -a never -s danger-full-access
+ → no second daemon: B joined A's
+ prompt: run `echo "NODE=$NODETERM_NODE_ID PANE=$PROBE_PANE"`
+ └ NODE=node-A PANE=node-A
+ hook log: hook NODETERM_NODE_ID=node-A (×3)
+
+pane C: … NODETERM_NODE_ID=node-C codex --no-daemon -a never -s danger-full-access
+ └ NODE=node-C PANE=node-C
+ hook log: hook NODETERM_NODE_ID=node-C (×3)
+
+pane D: … NODETERM_NODE_ID=node-D codex -c features.daemon_auto_start=false -a never …
+ └ NODE=node-A PANE=node-A ← the feature switch does NOT leave a RUNNING daemon
+
+codex --remote unix:// --no-daemon
+ ERROR: --no-daemon cannot be used with --remote.
+codex --no-daemon resume <id> / codex resume <id> --no-daemon / codex --no-daemon fork <id>
+ all parse (answer: "No saved session found with ID …")
+codex exec | review | login | mcp | app-server --help: no `--no-daemon` (not TUI clients)
+```
+
+The daemon is keyed by `CODEX_HOME`: every managed Codex account (its own `CODEX_HOME`) gets its
+own, and every node on one account shares one. There is no environment-variable switch (the
+binary's `CODEX_*` names were checked).
diff --git a/src/core/__fixtures__/codex-daemon/help-0.148.0.txt b/src/core/__fixtures__/codex-daemon/help-0.148.0.txt
new file mode 100644
index 000000000..843883eba
--- /dev/null
+++ b/src/core/__fixtures__/codex-daemon/help-0.148.0.txt
@@ -0,0 +1,132 @@
+Codex CLI
+
+If no subcommand is specified, options will be forwarded to the interactive CLI.
+
+Usage: codex [OPTIONS] [PROMPT]
+ codex [OPTIONS] <COMMAND> [ARGS]
+
+Commands:
+ exec Run Codex non-interactively [aliases: e]
+ review Run a code review non-interactively
+ login Manage login
+ logout Remove stored authentication credentials
+ mcp Manage external MCP servers for Codex
+ plugin Manage Codex plugins
+ mcp-server Start Codex as an MCP server (stdio)
+ app-server [experimental] Run the app server or related tooling
+ remote-control [experimental] Manage the app-server daemon with remote control enabled
+ completion Generate shell completion scripts
+ update Update Codex to the latest version
+ doctor Diagnose local Codex installation, config, auth, and runtime health
+ sandbox Run commands within a Codex-provided sandbox
+ debug Debugging tools
+ apply Apply the latest diff produced by Codex agent as a `git apply` to your local
+ working tree [aliases: a]
+ resume Resume a previous interactive session (picker by default; use --last to continue
+ the most recent)
+ archive Archive a saved session by id or session name
+ delete Permanently delete a saved session by id or session name
+ migrate-rollouts Inspect or migrate legacy local sessions to paginated thread history
+ unarchive Unarchive a saved session by id or session name
+ fork Fork a previous interactive session (picker by default; use --last to fork the
+ most recent)
+ cloud [EXPERIMENTAL] Browse tasks from Codex Cloud and apply changes locally
+ exec-server [EXPERIMENTAL] Run the standalone exec-server service
+ features Inspect feature flags
+ help Print this message or the help of the given subcommand(s)
+
+Arguments:
+ [PROMPT]
+ Optional user prompt to start the session
+
+Options:
+ -c, --config <key=value>
+ Override a configuration value that would otherwise be loaded from `~/.codex/config.toml`.
+ Use a dotted path (`foo.bar.baz`) to override nested values. The `value` portion is parsed
+ as TOML. If it fails to parse as TOML, the raw string is used as a literal.
+
+ Examples: - `-c model="o3"` - `-c 'sandbox_permissions=["disk-full-read-access"]'` - `-c
+ shell_environment_policy.inherit=all`
+
+ --enable <FEATURE>
+ Enable a feature (repeatable). Equivalent to `-c features.<name>=true`
+
+ --disable <FEATURE>
+ Disable a feature (repeatable). Equivalent to `-c features.<name>=false`
+
+ --remote <ADDR>
+ Connect the TUI to a remote app server endpoint.
+
+ Accepted forms: `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`.
+
+ --remote-auth-token-env <ENV_VAR>
+ Name of the environment variable containing the bearer token to send to a remote app
+ server websocket
+
+ --strict-config
+ Error out when config.toml contains fields that are not recognized by this version of
+ Codex
+
+ -i, --image <FILE>...
+ Optional image(s) to attach to the initial prompt
+
+ -m, --model <MODEL>
+ Model the agent should use
+
+ --oss
+ Use open-source provider
+
+ --local-provider <OSS_PROVIDER>
+ Specify which local provider to use (lmstudio or ollama). If not specified with --oss,
+ will use config default or show selection
+
+ -p, --profile <CONFIG_PROFILE_V2>
+ Layer $CODEX_HOME/<name>.config.toml on top of the base user config
+
+ -s, --sandbox <SANDBOX_MODE>
+ Select the sandbox policy to use when executing model-generated shell commands
+
+ [possible values: read-only, workspace-write, danger-full-access]
+
+ --approve-for-me
+ Route approval requests through automatic review using the workspace-write sandbox
+
+ --dangerously-bypass-approvals-and-sandbox
+ Skip all confirmation prompts and execute commands without sandboxing. EXTREMELY
+ DANGEROUS. Intended solely for running in environments that are externally sandboxed
+
+ --dangerously-bypass-hook-trust
+ Run enabled hooks without requiring persisted hook trust for this invocation. DANGEROUS.
+ Intended only for automation that already vets hook sources
+
+ -C, --cd <DIR>
+ Tell the agent to use the specified directory as its working root
+
+ --add-dir <DIR>
+ Additional directories that should be writable alongside the primary workspace
+
+ -a, --ask-for-approval <APPROVAL_POLICY>
+ Configure when the model requires human approval before executing a command
+
+ Possible values:
+ - untrusted: Only run "trusted" commands (e.g. ls, cat, sed) without asking for user
+ approval. Will escalate to the user if the model proposes a command that is not in the
+ "trusted" set
+ - on-request: The model decides when to ask the user for approval
+ - never: Never ask for user approval Execution failures are immediately returned to
+ the model
+
+ --search
+ Enable live web search. When enabled, the native Responses `web_search` tool is available
+ to the model (no per‑call approval)
+
+ --no-alt-screen
+ Disable alternate screen mode
+
+ Runs the TUI in inline mode, preserving terminal scrollback history.
+
+ -h, --help
+ Print help (see a summary with '-h')
+
+ -V, --version
+ Print version
diff --git a/src/core/__fixtures__/codex-daemon/help-0.156.1.txt b/src/core/__fixtures__/codex-daemon/help-0.156.1.txt
new file mode 100644
index 000000000..76d34fdb6
--- /dev/null
+++ b/src/core/__fixtures__/codex-daemon/help-0.156.1.txt
@@ -0,0 +1,136 @@
+Codex CLI
+
+If no subcommand is specified, options will be forwarded to the interactive CLI.
+
+Usage: codex [OPTIONS] [PROMPT]
+ codex [OPTIONS] <COMMAND> [ARGS]
+
+Commands:
+ agents Browse all agent sessions on the shared local app-server daemon
+ exec Run Codex non-interactively [aliases: e]
+ review Run a code review non-interactively
+ login Manage login
+ logout Remove stored authentication credentials
+ mcp Manage external MCP servers for Codex
+ plugin Manage Codex plugins
+ app-server [experimental] Run the app server or related tooling
+ remote-control [experimental] Manage the app-server daemon with remote control enabled
+ completion Generate shell completion scripts
+ update Update Codex to the latest version
+ doctor Diagnose local Codex installation, config, auth, and runtime health
+ sandbox Run commands within a Codex-provided sandbox
+ debug Debugging tools
+ apply Apply the latest diff produced by Codex agent as a `git apply` to your local
+ working tree [aliases: a]
+ resume Resume a previous interactive session (picker by default; use --last to continue
+ the most recent)
+ queue Queue a message for an existing session
+ archive Archive a saved session by id or session name
+ delete Permanently delete a saved session by id or session name
+ migrate-rollouts Inspect or migrate legacy local sessions to paginated thread history
+ unarchive Unarchive a saved session by id or session name
+ fork Fork a previous interactive session (picker by default; use --last to fork the
+ most recent)
+ cloud [EXPERIMENTAL] Browse tasks from Codex Cloud and apply changes locally
+ exec-server [EXPERIMENTAL] Run the standalone exec-server service
+ features Inspect feature flags
+ help Print this message or the help of the given subcommand(s)
+
+Arguments:
+ [PROMPT]
+ Optional user prompt to start the session
+
+Options:
+ -c, --config <key=value>
+ Override a configuration value that would otherwise be loaded from `~/.codex/config.toml`.
+ Use a dotted path (`foo.bar.baz`) to override nested values. The `value` portion is parsed
+ as TOML. If it fails to parse as TOML, the raw string is used as a literal.
+
+ Examples: - `-c model="o3"` - `-c 'sandbox_permissions=["disk-full-read-access"]'` - `-c
+ shell_environment_policy.inherit=all`
+
+ --enable <FEATURE>
+ Enable a feature (repeatable). Equivalent to `-c features.<name>=true`
+
+ --disable <FEATURE>
+ Disable a feature (repeatable). Equivalent to `-c features.<name>=false`
+
+ --remote <ADDR>
+ Connect the TUI to a remote app server endpoint.
+
+ Accepted forms: `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`.
+
+ --remote-auth-token-env <ENV_VAR>
+ Name of the environment variable containing the bearer token to send to a remote app
+ server websocket
+
+ --strict-config
+ Error out when config.toml contains fields that are not recognized by this version of
+ Codex
+
+ -i, --image <FILE>...
+ Optional image(s) to attach to the initial prompt
+
+ -m, --model <MODEL>
+ Model the agent should use
+
+ --oss
+ Use open-source provider
+
+ --local-provider <OSS_PROVIDER>
+ Specify which local provider to use (lmstudio or ollama). If not specified with --oss,
+ will use config default or show selection
+
+ -p, --profile <CONFIG_PROFILE_V2>
+ Layer $CODEX_HOME/<name>.config.toml on top of the base user config
+
+ -s, --sandbox <SANDBOX_MODE>
+ Select the sandbox policy to use when executing model-generated shell commands
+
+ [possible values: read-only, workspace-write, danger-full-access]
+
+ --approve-for-me
+ Route approval requests through automatic review using the workspace-write sandbox
+
+ --dangerously-bypass-approvals-and-sandbox
+ Skip all confirmation prompts and execute commands without sandboxing. EXTREMELY
+ DANGEROUS. Intended solely for running in environments that are externally sandboxed
+
+ --dangerously-bypass-hook-trust
+ Run enabled hooks without requiring persisted hook trust for this invocation. DANGEROUS.
+ Intended only for automation that already vets hook sources
+
+ -C, --cd <DIR>
+ Tell the agent to use the specified directory as its working root
+
+ --worktree
+ Run the session in a new managed Git worktree
+
+ --add-dir <DIR>
+ Additional directories that should be writable alongside the primary workspace
+
+ -a, --ask-for-approval <APPROVAL_POLICY>
+ Configure when the model requires human approval before executing a command
+
+ Possible values:
+ - on-request: The model decides when to ask the user for approval
+ - never: Never ask for user approval Execution failures are immediately returned to
+ the model
+
+ --search
+ Enable live web search. When enabled, the native Responses `web_search` tool is available
+ to the model (no per‑call approval)
+
+ --no-alt-screen
+ Disable alternate screen mode
+
+ Runs the TUI in inline mode, preserving terminal scrollback history.
+
+ --no-daemon
+ Run without the shared background server, even if it is already running
+
+ -h, --help
+ Print help (see a summary with '-h')
+
+ -V, --version
+ Print version
diff --git a/src/core/__fixtures__/codex-daemon/help-0.159.2.txt b/src/core/__fixtures__/codex-daemon/help-0.159.2.txt
new file mode 100644
index 000000000..76d34fdb6
--- /dev/null
+++ b/src/core/__fixtures__/codex-daemon/help-0.159.2.txt
@@ -0,0 +1,136 @@
+Codex CLI
+
+If no subcommand is specified, options will be forwarded to the interactive CLI.
+
+Usage: codex [OPTIONS] [PROMPT]
+ codex [OPTIONS] <COMMAND> [ARGS]
+
+Commands:
+ agents Browse all agent sessions on the shared local app-server daemon
+ exec Run Codex non-interactively [aliases: e]
+ review Run a code review non-interactively
+ login Manage login
+ logout Remove stored authentication credentials
+ mcp Manage external MCP servers for Codex
+ plugin Manage Codex plugins
+ app-server [experimental] Run the app server or related tooling
+ remote-control [experimental] Manage the app-server daemon with remote control enabled
+ completion Generate shell completion scripts
+ update Update Codex to the latest version
+ doctor Diagnose local Codex installation, config, auth, and runtime health
+ sandbox Run commands within a Codex-provided sandbox
+ debug Debugging tools
+ apply Apply the latest diff produced by Codex agent as a `git apply` to your local
+ working tree [aliases: a]
+ resume Resume a previous interactive session (picker by default; use --last to continue
+ the most recent)
+ queue Queue a message for an existing session
+ archive Archive a saved session by id or session name
+ delete Permanently delete a saved session by id or session name
+ migrate-rollouts Inspect or migrate legacy local sessions to paginated thread history
+ unarchive Unarchive a saved session by id or session name
+ fork Fork a previous interactive session (picker by default; use --last to fork the
+ most recent)
+ cloud [EXPERIMENTAL] Browse tasks from Codex Cloud and apply changes locally
+ exec-server [EXPERIMENTAL] Run the standalone exec-server service
+ features Inspect feature flags
+ help Print this message or the help of the given subcommand(s)
+
+Arguments:
+ [PROMPT]
+ Optional user prompt to start the session
+
+Options:
+ -c, --config <key=value>
+ Override a configuration value that would otherwise be loaded from `~/.codex/config.toml`.
+ Use a dotted path (`foo.bar.baz`) to override nested values. The `value` portion is parsed
+ as TOML. If it fails to parse as TOML, the raw string is used as a literal.
+
+ Examples: - `-c model="o3"` - `-c 'sandbox_permissions=["disk-full-read-access"]'` - `-c
+ shell_environment_policy.inherit=all`
+
+ --enable <FEATURE>
+ Enable a feature (repeatable). Equivalent to `-c features.<name>=true`
+
+ --disable <FEATURE>
+ Disable a feature (repeatable). Equivalent to `-c features.<name>=false`
+
+ --remote <ADDR>
+ Connect the TUI to a remote app server endpoint.
+
+ Accepted forms: `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`.
+
+ --remote-auth-token-env <ENV_VAR>
+ Name of the environment variable containing the bearer token to send to a remote app
+ server websocket
+
+ --strict-config
+ Error out when config.toml contains fields that are not recognized by this version of
+ Codex
+
+ -i, --image <FILE>...
+ Optional image(s) to attach to the initial prompt
+
+ -m, --model <MODEL>
+ Model the agent should use
+
+ --oss
+ Use open-source provider
+
+ --local-provider <OSS_PROVIDER>
+ Specify which local provider to use (lmstudio or ollama). If not specified with --oss,
+ will use config default or show selection
+
+ -p, --profile <CONFIG_PROFILE_V2>
+ Layer $CODEX_HOME/<name>.config.toml on top of the base user config
+
+ -s, --sandbox <SANDBOX_MODE>
+ Select the sandbox policy to use when executing model-generated shell commands
+
+ [possible values: read-only, workspace-write, danger-full-access]
+
+ --approve-for-me
+ Route approval requests through automatic review using the workspace-write sandbox
+
+ --dangerously-bypass-approvals-and-sandbox
+ Skip all confirmation prompts and execute commands without sandboxing. EXTREMELY
+ DANGEROUS. Intended solely for running in environments that are externally sandboxed
+
+ --dangerously-bypass-hook-trust
+ Run enabled hooks without requiring persisted hook trust for this invocation. DANGEROUS.
+ Intended only for automation that already vets hook sources
+
+ -C, --cd <DIR>
+ Tell the agent to use the specified directory as its working root
+
+ --worktree
+ Run the session in a new managed Git worktree
+
+ --add-dir <DIR>
+ Additional directories that should be writable alongside the primary workspace
+
+ -a, --ask-for-approval <APPROVAL_POLICY>
+ Configure when the model requires human approval before executing a command
+
+ Possible values:
+ - on-request: The model decides when to ask the user for approval
+ - never: Never ask for user approval Execution failures are immediately returned to
+ the model
+
+ --search
+ Enable live web search. When enabled, the native Responses `web_search` tool is available
+ to the model (no per‑call approval)
+
+ --no-alt-screen
+ Disable alternate screen mode
+
+ Runs the TUI in inline mode, preserving terminal scrollback history.
+
+ --no-daemon
+ Run without the shared background server, even if it is already running
+
+ -h, --help
+ Print help (see a summary with '-h')
+
+ -V, --version
+ Print version
diff --git a/src/core/agent-launch.test.ts b/src/core/agent-launch.test.ts
index 6f401aafb..b2b996a1e 100644
--- a/src/core/agent-launch.test.ts
+++ b/src/core/agent-launch.test.ts
@@ -877,3 +877,23 @@ describe.runIf(!WINDOWS)("real POSIX shell argv behavior", () => {
},
);
});
+
+describe("--no-daemon (codex >= 0.157 auto-starts a shared app-server that keeps the first pane's env)", () => {
+ it("rides a codex argv only when the host's codex was seen to accept it", async () => {
+ await expect(
+ prepareAgentLaunch(
+ resume("codex", "thread-1", { permissionMode: "auto" }),
+ "posix",
+ builtinContext("codex", { codexNoDaemon: true }),
+ ),
+ ).resolves.toEqual({
+ command: "'codex' 'resume' 'thread-1' '--ask-for-approval' 'on-request' '--no-daemon'",
+ });
+ await expect(
+ prepareAgentLaunch(start("codex"), "posix", builtinContext("codex", { codexNoDaemon: null })),
+ ).resolves.toEqual({ command: "'codex'" });
+ await expect(
+ prepareAgentLaunch(start("claude"), "posix", builtinContext("claude", { codexNoDaemon: true })),
+ ).resolves.toEqual({ command: "'claude'" });
+ });
+});
diff --git a/src/core/agent-launch.ts b/src/core/agent-launch.ts
index b0157539e..298760fa9 100644
--- a/src/core/agent-launch.ts
+++ b/src/core/agent-launch.ts
@@ -13,6 +13,7 @@ import {
type PromptInjectionMode,
} from "../shared/agents/config";
import { approvalFlags } from "../shared/agents/approval-mode";
+import { CODEX_NO_DAEMON_FLAG } from "../shared/agents/codex-daemon";
import { SAFE_SESSION_ID } from "../shared/session-id";
/** The parser that owns a live local Windows-profile terminal. */
@@ -66,6 +67,12 @@ export interface AgentLaunchTrustedContext {
* not know, so emitting it blind is a dead session, not a degraded one.
*/
codexApprovalValues?: readonly string[] | null;
+ /**
+ * Does the host's `codex` accept `--no-daemon`? Same probe, same provenance. Only a literal
+ * `true` adds the flag — see `withCodexNoDaemon` (shared/agents/codex-daemon.ts) for why every
+ * plain Codex TUI nodeterm starts needs it from codex-cli 0.157.0 on.
+ */
+ codexNoDaemon?: boolean | null;
}
/** Core-private launch material. It must never cross the renderer/preload/relay boundary. */
@@ -352,11 +359,22 @@ function logicalLaunch(
if (intent.permissionMode !== undefined && !hasPermissionMode(config.id))
fail("invalid-intent");
- const modeFlags = intent.permissionMode
+ const approval = intent.permissionMode
? approvalFlags(config.id, intent.permissionMode, {
codexApprovalValues: context.codexApprovalValues,
})
: [];
+ // Same rule as `withCodexNoDaemon`, applied to argv instead of a typed line.
+ const noDaemon =
+ config.id === "codex" &&
+ context.codexNoDaemon === true &&
+ !baseArgs.some(
+ (a) =>
+ a === CODEX_NO_DAEMON_FLAG || a === "--remote" || a.startsWith("--remote="),
+ )
+ ? [CODEX_NO_DAEMON_FLAG]
+ : [];
+ const modeFlags = [...approval, ...noDaemon];
if (intent.action === "resume") {
if (!config.builtin || !canResume(config.id)) fail("agent-unavailable");
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 53bc07057..c606fc7ce 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -230,6 +230,15 @@ export interface MirrorSettings {
* *this* host and generalizes to neither another agent nor another machine.
*/
codexApprovalValues?: string[]
+ /**
+ * THIS host's `codex` accepts `--no-daemon` — present only as `true`, when its own `--help` said
+ * so. A reader launching a plain Codex TUI must then add the flag: from codex-cli 0.157.0 the TUI
+ * otherwise starts or joins ONE shared app-server per CODEX_HOME that keeps the environment of the
+ * pane that started it, so the new session's hooks and tool shells run as another node (measured on
+ * 0.159.2; see shared/agents/codex-daemon.ts). Never together with `--remote` (codex refuses).
+ * Absent = unknown = emit nothing: clap exits on an unknown option.
+ */
+ codexNoDaemon?: true
/**
* The user's custom agents (Settings → Agents), reduced to what a phone needs to chat with one:
* which builtin harness it inherits (the chat capability follows `baseAgent`) and which binary
diff --git a/src/core/codex-cli.ts b/src/core/codex-cli.ts
index 18c5f9513..d852230f4 100644
--- a/src/core/codex-cli.ts
+++ b/src/core/codex-cli.ts
@@ -7,9 +7,9 @@
* codex would downgrade codex sessions on a machine whose *claude* is old or missing, and reading
* codex's vocabulary off claude's probe would be the same mistake with the arrow reversed.
*
- * Today it answers exactly one question — which values does this `codex` accept for
- * `--ask-for-approval`? — but it is shaped as a caps bag so the next codex fact lands here instead
- * of growing a third probe.
+ * It answers two questions read off the same `--help` page — which values does this `codex` accept
+ * for `--ask-for-approval`, and does it take `--no-daemon` (see `codexNoDaemonFrom`)? — shaped as a
+ * caps bag so the next codex fact lands here instead of growing another probe.
*
* WHY THE VALUES AND NOT A VERSION NUMBER. The vocabulary is not stable across releases: measured
* on real binaries, 0.146.0–0.148.0 advertise `untrusted, on-request, never` and 0.149.0 onwards
@@ -108,6 +108,30 @@ export function codexApprovalValuesFrom(helpOutput: string | null | undefined):
return clean.length ? Array.from(new Set(clean)) : null
}
+/**
+ * Pure: `codex --help` output → does this CLI accept `--no-daemon`? `null` when there is no page to
+ * read (no codex, a timeout) — the caller then emits nothing, i.e. today's command line.
+ *
+ * WHY THIS FLAG MATTERS. From 0.157.0 the `daemon_auto_start` feature is `stable, true` (0.156.1:
+ * `experimental, false`): a plain `codex` TUI no longer runs in-process but starts — or JOINS — ONE
+ * background `app-server` per `CODEX_HOME`, and that daemon keeps the environment of the pane that
+ * started it. MEASURED on 0.159.2 (private CODEX_HOME, private tmux socket): pane A started with
+ * `NODETERM_NODE_ID=node-A`, pane B with `node-B`; in pane B both the tool shell (`echo
+ * $NODETERM_NODE_ID` printed `node-A`) and every hook process (`node-A` in the hook log) ran as
+ * pane A. Every nodeterm hook POST, canvas-control verb and context-link read from pane B was
+ * attributed to another node. `--no-daemon` ("Run without the shared background server, even if it
+ * is already running") put pane C's tool shell and hooks back on `node-C`;
+ * `-c features.daemon_auto_start=false` did NOT — it still joined the running daemon. There is no
+ * environment-variable switch.
+ *
+ * Anchored on an option HEADER line, never on prose: a description mentioning the flag inside
+ * another option must not read as the option itself.
+ */
+export function codexNoDaemonFrom(helpOutput: string | null | undefined): boolean | null {
+ if (!helpOutput) return null
+ return helpOutput.split(/\r?\n/).some((l) => /^ {0,6}--no-daemon\b/.test(l))
+}
+
let helpCached: Promise<string | null> | null = null
/**
@@ -163,7 +187,10 @@ let cached: Promise<CodexCliCaps> | null = null
export function codexCliCaps(): Promise<CodexCliCaps> {
if (!cached) {
cached = codexHelpText()
- .then((help) => ({ approvalValues: codexApprovalValuesFrom(help) }))
+ .then((help) => ({
+ approvalValues: codexApprovalValuesFrom(help),
+ noDaemon: codexNoDaemonFrom(help)
+ }))
.catch(() => UNKNOWN_CODEX_CLI_CAPS)
}
return cached
diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.ts
index 2aae87539..55b6dd616 100644
--- a/src/core/codex-identity-proxy.ts
+++ b/src/core/codex-identity-proxy.ts
@@ -666,8 +666,8 @@ export function codexLauncherPath(): string {
/**
* The generated launcher.
*
- * 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
+ * Every identity-setup failure path here ends in plain codex (`nt_exec_plain`) — the caller's
+ * arguments untouched, plus `--no-daemon` when that codex advertises it (see the function). 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
@@ -798,6 +798,10 @@ nt_run_shared() {
case "$nt_arg" in
--ask-for-approval|-a) nt_drop_next=1; continue ;;
--ask-for-approval=*|-a=*) continue ;;
+ # Measured on 0.159.2: "ERROR: --no-daemon cannot be used with --remote." The launch line
+ # carries it for the plain-codex exits below (nt_exec_plain); the managed thread IS a remote
+ # client of the scrubbed shared daemon, so it must not.
+ --no-daemon) continue ;;
esac
set -- "$@" "$nt_arg"
done
@@ -863,6 +867,24 @@ nt_run_shared() {
done
}
+# Every plain-codex exit of this script goes through here. From codex-cli 0.157.0 a plain TUI
+# starts — or joins — ONE auto-started app-server per CODEX_HOME, and that daemon keeps the
+# environment of the pane that started it: every hook process and tool shell of a LATER node then
+# runs with the first node's NODETERM_NODE_ID (measured on 0.159.2), and a daemon started from
+# here would also be the one our managed threads connect to. '--no-daemon' keeps the TUI
+# in-process. The launch line normally carries it already (the desktop probed its own codex); on a
+# host nobody probed (an SSH launcher) this asks the binary about to run, and a codex that does not
+# advertise the flag gets the caller's arguments untouched — clap exits on an unknown option.
+nt_exec_plain() {
+ for nt_plain_arg in "$@"; do
+ case "$nt_plain_arg" in --no-daemon|--remote|--remote=*) exec codex "$@" ;; esac
+ done
+ if codex --help 2>/dev/null | grep -q -e '^[[:space:]]*--no-daemon'; then
+ exec codex --no-daemon "$@"
+ fi
+ exec codex "$@"
+}
+
nt_hook_curl() { curl "$@"; }
if [ -n "\${NODETERM_HOOK_SOCK-}" ]; then
case "$NODETERM_HOOK_SOCK" in
@@ -970,7 +992,7 @@ nt_report_fallback() {
[ -n "$nt_reason" ] || nt_preflight "$@" || :
if [ -n "$nt_reason" ]; then
nt_report_fallback "$nt_reason"
- exec codex "$@"
+ nt_exec_plain "$@"
fi
# $1 is the client budget in seconds; the rest is curl's. Start gets a budget LARGER than the
@@ -997,7 +1019,7 @@ if [ "\${1-}" = resume ]; then
exit $?
fi
nt_report_fallback thread-bind-refused
- exec codex "$@"
+ nt_exec_plain "$@"
fi
# THIS PANE'S OWN LABEL travels with both calls, and the pane is the only durable holder of it:
@@ -1013,7 +1035,7 @@ 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 "$@"
+ nt_exec_plain "$@"
;;
esac
nt_run_shared "$nt_thread" "$@"
diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.ts
index 28c2ef208..d65c45d7d 100644
--- a/src/core/codex-launcher-sh.test.ts
+++ b/src/core/codex-launcher-sh.test.ts
@@ -43,11 +43,17 @@ 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 before the injected body. */
+/** A stand-in for the real `codex`, which records how it was invoked before the injected body.
+ * `codex --help` is answered (and NOT logged): the plain-codex exits ask it whether `--no-daemon`
+ * exists. By default the page does not advertise it — an older CLI, i.e. arguments untouched. */
+let fakeHelpNoDaemon = false
function writeFakeCodex(body = 'exit 0'): void {
+ const help = fakeHelpNoDaemon
+ ? "printf '%s\\n' 'Options:' ' --no-daemon' ' Run without the shared background server, even if it is already running'"
+ : "printf '%s\\n' 'Options:' ' --no-alt-screen'"
fs.writeFileSync(
path.join(binDir, 'codex'),
- `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}\n${body}\n`,
+ `#!/bin/sh\nif [ "$1" = --help ]; then ${help}; exit 0; fi\nprintf '%s\\n' "$*" >> ${JSON.stringify(argvLog)}\n${body}\n`,
{ mode: 0o755 }
)
}
@@ -97,6 +103,8 @@ beforeEach(() => {
startAnswer = () => 'thread-abc'
startDelayMs = 0
bindAnswer = () => {}
+ fakeHelpNoDaemon = false
+ writeFakeCodex()
fs.writeFileSync(argvLog, '')
// The capability arrives through the FILE channel now (0600 under nodeTokenDir(), advertised as
// NODETERM_NODE_TOKEN_DIR in the endpoint file) — never through the tmux argv. Re-materialised
@@ -774,3 +782,55 @@ describe('the approval override never rides a remote resume (#811)', () => {
expect(fallbacks.map((f) => f.reason)).toContain('hook-endpoint-unavailable')
})
})
+
+// From codex-cli 0.157.0 a plain Codex TUI starts — or joins — ONE auto-started app-server per
+// CODEX_HOME that keeps the environment of the pane that started it (`daemon_auto_start`, stable
+// and on). MEASURED on 0.159.2: a second pane's tool shell and hooks ran with the FIRST pane's
+// NODETERM_NODE_ID. The launch line therefore carries `--no-daemon` (shared/agents/codex-daemon.ts),
+// and this launcher has two exits that treat it oppositely:
+// - the managed thread is `codex --remote unix:// resume …`, and codex REFUSES the pair
+// ("ERROR: --no-daemon cannot be used with --remote.", measured) — so it is stripped there;
+// - every plain-codex fallback must keep it, and on a host nobody probed (an SSH launcher) must ADD
+// it when the codex about to run advertises it.
+describe('--no-daemon: stripped from the managed thread, kept or added on plain codex', () => {
+ it('never reaches the --remote resume (codex refuses the pair)', async () => {
+ await callLauncher(['fix the bug', '--ask-for-approval', 'never', '--no-daemon'])
+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-abc fix the bug'])
+ })
+
+ it('never reaches a caller-supplied --remote resume either', async () => {
+ await callLauncher(['resume', 'thread-xyz', '--no-daemon'])
+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-xyz'])
+ })
+
+ it('is kept on the plain-codex fallback, exactly once', async () => {
+ fakeHelpNoDaemon = true
+ writeFakeCodex()
+ await callLauncher(['fix the bug', '--no-daemon'], {
+ NODETERM_HOOK_ENDPOINT: '/nonexistent/hook-endpoint.env'
+ })
+ expect(codexArgv()).toEqual(['fix the bug --no-daemon'])
+ })
+
+ it('is ADDED on a fallback when the codex about to run advertises it', async () => {
+ fakeHelpNoDaemon = true
+ writeFakeCodex()
+ await callLauncher(['resume', 'thread-xyz'], { NODETERM_HOOK_ENDPOINT: '' })
+ expect(codexArgv()).toEqual(['--no-daemon resume thread-xyz'])
+ })
+
+ it('is added on every fallback exit, not only the preflight one', async () => {
+ fakeHelpNoDaemon = true
+ writeFakeCodex()
+ bindAnswer = null
+ await callLauncher(['resume', 'thread-xyz'])
+ startAnswer = () => 'not a thread id!'
+ await callLauncher(['hello'])
+ expect(codexArgv()).toEqual(['--no-daemon resume thread-xyz', '--no-daemon hello'])
+ })
+
+ it('is NOT added when the codex does not advertise it (clap exits on an unknown option)', async () => {
+ await callLauncher(['hello'], { NODETERM_HOOK_ENDPOINT: '' })
+ expect(codexArgv()).toEqual(['hello'])
+ })
+})
diff --git a/src/core/codex-no-daemon.test.ts b/src/core/codex-no-daemon.test.ts
new file mode 100644
index 000000000..f516293b6
--- /dev/null
+++ b/src/core/codex-no-daemon.test.ts
@@ -0,0 +1,37 @@
+// `--no-daemon` detection, read off REAL `codex --help` pages captured for this change
+// (src/core/__fixtures__/codex-daemon/, see its README for the measurement they came from).
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { codexNoDaemonFrom } from './codex-cli'
+
+const fixture = (name: string): string =>
+ fs.readFileSync(path.join(__dirname, '__fixtures__', 'codex-daemon', name), 'utf8').replace(/\r\n/g, '\n')
+
+describe('codexNoDaemonFrom', () => {
+ it('reads the flag off 0.159.2 (daemon_auto_start stable, on)', () => {
+ expect(codexNoDaemonFrom(fixture('help-0.159.2.txt'))).toBe(true)
+ })
+
+ it('reads the flag off 0.156.1 too (the feature existed, off by default, and so did the flag)', () => {
+ expect(codexNoDaemonFrom(fixture('help-0.156.1.txt'))).toBe(true)
+ })
+
+ it('answers false for 0.148.0, which has neither — clap would EXIT on the unknown option', () => {
+ expect(codexNoDaemonFrom(fixture('help-0.148.0.txt'))).toBe(false)
+ })
+
+ it('answers null when there is no page at all (no codex, a timeout): emit nothing', () => {
+ expect(codexNoDaemonFrom(null)).toBeNull()
+ expect(codexNoDaemonFrom('')).toBeNull()
+ })
+
+ it('reads an option HEADER, never prose that mentions the flag', () => {
+ const prose = [
+ 'Options:',
+ ' --remote <ADDR>',
+ ' Connect to a remote server; unlike --no-daemon this needs an address'
+ ].join('\n')
+ expect(codexNoDaemonFrom(prose)).toBe(false)
+ })
+})
diff --git a/src/core/remote-ssh/codex-no-daemon-probe.test.ts b/src/core/remote-ssh/codex-no-daemon-probe.test.ts
new file mode 100644
index 000000000..b071a6ce3
--- /dev/null
+++ b/src/core/remote-ssh/codex-no-daemon-probe.test.ts
@@ -0,0 +1,85 @@
+// The remote "does this host's codex take --no-daemon?" probe, run for real under /bin/sh against a
+// fake host: the command is generated shell that no compiler checks.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { testTmpDir } from '../test-tmp'
+import {
+ CODEX_NO_DAEMON_END,
+ CODEX_NO_DAEMON_START,
+ codexNoDaemonProbeCommand,
+ parseCodexNoDaemonProbe
+} from './codex-no-daemon-probe'
+
+const run = promisify(execFile)
+const fixture = (name: string): string =>
+ path.join(__dirname, '..', '__fixtures__', 'codex-daemon', name)
+
+let root = ''
+beforeAll(() => {
+ root = testTmpDir('nt-codex-nd-probe-')
+})
+afterAll(() => fs.rmSync(root, { recursive: true, force: true }))
+
+/** A host whose `codex --help` prints `helpFile`, and whose login profile is noisy. */
+function host(helpFile: string | null): Record<string, string> {
+ const home = fs.mkdtempSync(path.join(root, 'h-'))
+ const bin = path.join(home, 'bin')
+ fs.mkdirSync(bin)
+ if (helpFile)
+ fs.writeFileSync(path.join(bin, 'codex'), `#!/bin/sh\n[ "$1" = --help ] && cat '${helpFile}'\n`, {
+ mode: 0o755
+ })
+ // A login-profile banner that must never read as an answer.
+ fs.writeFileSync(path.join(home, '.profile'), 'echo "Welcome — --no-daemon yes"\n')
+ // Only the tools the probe needs — never the system bin dirs, where a REAL codex may live.
+ const tools = path.join(home, 'tools')
+ fs.mkdirSync(tools)
+ for (const t of ['grep', 'cat']) {
+ const real = ['/usr/bin', '/bin'].map((d) => path.join(d, t)).find((f) => fs.existsSync(f))
+ if (real) fs.symlinkSync(real, path.join(tools, t))
+ }
+ fs.symlinkSync('/bin/sh', path.join(tools, 'sh'))
+ // The "login shell": this machine's /etc/profile would re-add the system dirs (and its real
+ // codex). A host's own login PATH is exactly what the probe wants; the TEST wants only ours.
+ const login = path.join(tools, 'login-sh')
+ fs.writeFileSync(login, '#!/bin/sh\n[ "$1" = -lc ] && shift\n. "$HOME/.profile"\nexec /bin/sh -c "$1"\n', {
+ mode: 0o755
+ })
+ return { HOME: home, SHELL: login, PATH: `${bin}:${tools}` }
+}
+
+async function probe(env: Record<string, string>): Promise<boolean | null> {
+ const { stdout } = await run('/bin/sh', ['-c', codexNoDaemonProbeCommand()], { env }).catch(
+ (e: { stdout?: string }) => ({ stdout: e.stdout ?? '' })
+ )
+ return parseCodexNoDaemonProbe(stdout)
+}
+
+describe('codexNoDaemonProbeCommand under a real /bin/sh', () => {
+ it('answers true for a host whose codex is 0.159.2', async () => {
+ expect(await probe(host(fixture('help-0.159.2.txt')))).toBe(true)
+ })
+
+ it('answers false for a host whose codex is 0.148.0 (no such option)', async () => {
+ expect(await probe(host(fixture('help-0.148.0.txt')))).toBe(false)
+ })
+
+ it('answers unknown when the host has no codex at all', async () => {
+ expect(await probe(host(null))).toBeNull()
+ })
+})
+
+describe('parseCodexNoDaemonProbe', () => {
+ it('reads only what sits between the markers', () => {
+ const wrap = (v: string): string => `banner yes\n${CODEX_NO_DAEMON_START}${v}${CODEX_NO_DAEMON_END}\nno`
+ expect(parseCodexNoDaemonProbe(wrap('yes'))).toBe(true)
+ expect(parseCodexNoDaemonProbe(wrap('no'))).toBe(false)
+ expect(parseCodexNoDaemonProbe(wrap('maybe'))).toBeNull()
+ expect(parseCodexNoDaemonProbe('yes')).toBeNull()
+ expect(parseCodexNoDaemonProbe(`${CODEX_NO_DAEMON_START}yes`)).toBeNull()
+ expect(parseCodexNoDaemonProbe(null)).toBeNull()
+ })
+})
diff --git a/src/core/remote-ssh/codex-no-daemon-probe.ts b/src/core/remote-ssh/codex-no-daemon-probe.ts
new file mode 100644
index 000000000..eac69b73a
--- /dev/null
+++ b/src/core/remote-ssh/codex-no-daemon-probe.ts
@@ -0,0 +1,44 @@
+// Pure shell command + parser for the REMOTE "does this host's `codex` take `--no-daemon`?" probe.
+//
+// Why a host needs asking at all: from codex-cli 0.157.0 a plain Codex TUI starts (or joins) ONE
+// auto-started app-server per CODEX_HOME that keeps the environment of the pane that started it, so
+// on an SSH host every later Codex node's hooks and tool shells run with the FIRST node's
+// NODETERM_NODE_ID (measured on 0.159.2 — see shared/agents/codex-daemon.ts). The fix is the flag,
+// and clap EXITS on an option it does not know, so it may ride a remote launch line only when THAT
+// host's codex advertised it. The laptop's probe says nothing about the host's binary.
+//
+// Same discipline as `claude-version-probe.ts`: through the LOGIN shell (an exec channel's shell
+// usually never sees an nvm/npm-global PATH), with the answer DELIMITED so a profile banner can
+// never be read as one. No marker ⇒ unknown ⇒ no flag.
+import { posixQuote } from '../../shared/ssh'
+
+export const CODEX_NO_DAEMON_START = '__NT_CODEX_ND__'
+export const CODEX_NO_DAEMON_END = '__NT_CODEX_ND_END__'
+
+/**
+ * Prints `yes` / `no` between the markers when a `codex` resolves, nothing otherwise. Anchored on
+ * an option HEADER line (`codexNoDaemonFrom`'s rule), never on prose. A `codex --help` that fails
+ * answers `no` — the conservative reading (no flag), and the one a CLI that cannot print its own
+ * help page deserves.
+ */
+export function codexNoDaemonProbeCommand(): string {
+ const emit =
+ `command -v codex >/dev/null 2>&1 && { ` +
+ `if codex --help 2>/dev/null | grep -q -e '^[[:space:]]*--no-daemon'; ` +
+ `then a=yes; else a=no; fi; ` +
+ `printf '${CODEX_NO_DAEMON_START}%s${CODEX_NO_DAEMON_END}' "$a"; }`
+ const q = posixQuote(emit)
+ return `$SHELL -lc ${q} 2>/dev/null || sh -c ${q} 2>/dev/null`
+}
+
+/** `true` / `false` from the markers, `null` when they are absent (no codex, a failed probe). */
+export function parseCodexNoDaemonProbe(stdout: string | null | undefined): boolean | null {
+ if (!stdout) return null
+ const start = stdout.indexOf(CODEX_NO_DAEMON_START)
+ if (start < 0) return null
+ const from = start + CODEX_NO_DAEMON_START.length
+ const end = stdout.indexOf(CODEX_NO_DAEMON_END, from)
+ if (end < 0) return null
+ const v = stdout.slice(from, end).trim()
+ return v === 'yes' ? true : v === 'no' ? false : null
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index de78adbea..f47b76155 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -2279,6 +2279,9 @@ app.whenReady().then(async () => {
...(localCodexCaps?.approvalValues
? { codexApprovalValues: localCodexCaps.approvalValues }
: {}), // unprobed ⇒ absent ⇒ the reader uses the baseline vocabulary
+ // Only a SEEN `true`: a phone-launched plain Codex TUI must carry `--no-daemon` too, or it
+ // joins the auto-started shared app-server and runs as another node (shared/agents/codex-daemon).
+ ...(localCodexCaps?.noDaemon === true ? { codexNoDaemon: true } : {}),
claudeAccounts: (s.claudeAccounts ?? [])
.filter((a) => !a.host && !a.pending)
.map((a) => ({ id: a.id, dir: claudeConfigDirFor(a.id) })),
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index e354287fc..340971099 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -3258,3 +3258,57 @@ describe('SshProjectManager — atomic remote import (Task 6.2, Property 2 + 11)
expect(seen.some((c) => /rm -f '[^']*rollout-x\.jsonl'/.test(c))).toBe(true)
})
})
+
+// From codex-cli 0.157.0 a plain Codex TUI joins ONE auto-started app-server per CODEX_HOME that
+// keeps the first pane's NODETERM_* env; on an SSH host that means every later remote Codex node
+// runs as the first one. The fix is `--no-daemon`, which may ride a REMOTE line only when that
+// host's own `codex --help` advertised it — the laptop's probe says nothing about the host.
+describe('SshProjectManager — remote codex --no-daemon probe', () => {
+ function mgrWithCodexHelp(answer: string) {
+ const events: { status: string; remoteCodexNoDaemon?: unknown }[] = []
+ const run = vi.fn(async (args: string[]) => {
+ const cmd = args.join(' ')
+ if (cmd.includes('__NT_CODEX_ND__')) return { code: 0, stdout: `Welcome yes\n${answer}` }
+ if (cmd.includes('printf %s')) return { code: 0, stdout: '/home/u' }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: (e) => events.push({ status: e.status, remoteCodexNoDaemon: e.remoteCodexNoDaemon })
+ })
+ return { mgr, events }
+ }
+ const answered = (events: { remoteCodexNoDaemon?: unknown }[]) =>
+ events.find((e) => e.remoteCodexNoDaemon !== undefined)
+
+ it('publishes the HOST\'s answer, keyed by user@host, on a connected event', async () => {
+ const { mgr, events } = mgrWithCodexHelp('__NT_CODEX_ND__yes__NT_CODEX_ND_END__')
+ await mgr.connect('p1', conn)
+ await vi.waitFor(() => expect(answered(events)).toBeDefined())
+ expect(answered(events)).toEqual({
+ status: 'connected',
+ remoteCodexNoDaemon: { hostKey: 'u@h', supported: true }
+ })
+ // A reused connection hands the same answer back with the connect result.
+ const again = await mgr.connect('p1', conn)
+ expect(again.remoteCodexNoDaemon).toEqual({ hostKey: 'u@h', supported: true })
+ })
+
+ it('an older host codex answers false', async () => {
+ const { mgr, events } = mgrWithCodexHelp('__NT_CODEX_ND__no__NT_CODEX_ND_END__')
+ await mgr.connect('p1', conn)
+ await vi.waitFor(() => expect(answered(events)).toBeDefined())
+ expect(answered(events)?.remoteCodexNoDaemon).toEqual({ hostKey: 'u@h', supported: false })
+ })
+
+ it('no markers (no codex on the host, a failed probe) publishes nothing — the line stays as it was', async () => {
+ const { mgr, events } = mgrWithCodexHelp('')
+ await mgr.connect('p1', conn)
+ await new Promise((r) => setTimeout(r, 20))
+ expect(answered(events)).toBeUndefined()
+ })
+})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 34167f7dd..33cad0949 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -18,7 +18,8 @@ import type {
ClaudeSessionCopyResult,
DownloadResult,
SshPassphraseRequest,
- SshProjectStatusEvent
+ SshProjectStatusEvent,
+ RemoteCodexNoDaemon
} from '../../shared/types'
import {
parseRemoteSessionCopy,
@@ -53,6 +54,7 @@ import {
} from '../../core/remote-ssh/control-master'
import { SshChildGate } from '../../core/remote-ssh/ssh-child-gate'
import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'
+import { codexNoDaemonProbeCommand, parseCodexNoDaemonProbe } from '../../core/remote-ssh/codex-no-daemon-probe'
import { RemoteHooks } from './remote-hooks'
import type { AgentToolsTrigger } from './agent-tools-freshness'
import {
@@ -305,6 +307,7 @@ export interface ConnectResult {
codexCliPath?: string
claudeAutoPermissionMode?: boolean
remoteClaudeVersion?: string | null
+ remoteCodexNoDaemon?: RemoteCodexNoDaemon
}
/**
@@ -405,6 +408,8 @@ interface Conn {
/** The probed remote `claude --version` output. `null` = the probe ran and found no claude
* (feeds the tab-menu hint); undefined = not probed yet. */
remoteClaudeVersion?: string | null
+ /** This host's `codex` takes `--no-daemon` (probed after connect); undefined = not probed. */
+ remoteCodexNoDaemon?: RemoteCodexNoDaemon
}
/**
@@ -811,7 +816,8 @@ export class SshProjectManager {
codexRelayRuntimePath: existing.codexRelayRuntimePath,
codexCliPath: existing.codexCliPath,
claudeAutoPermissionMode: existing.claudeAutoPermissionMode,
- remoteClaudeVersion: existing.remoteClaudeVersion
+ remoteClaudeVersion: existing.remoteClaudeVersion,
+ remoteCodexNoDaemon: existing.remoteCodexNoDaemon
}
}
this.emitStatus({ projectId, status: 'reconnecting' })
@@ -1099,6 +1105,11 @@ export class SshProjectManager {
// log line. Internals are already try/catch-guarded, but `this.r.onStatus` (IPC send) can
// still throw if the window is torn down mid-probe, that must never surface here.
if (entry) void this.probeClaudeAutoPermissionMode(projectId, entry).catch(() => {})
+ // Same shape for the host's codex: may a remote Codex TUI carry `--no-daemon`? (From
+ // 0.157.0 it otherwise joins an auto-started shared app-server that runs every later node
+ // as the first one — shared/agents/codex-daemon.ts.) Unawaited and swallowed for the same
+ // reasons; until it lands, remote Codex lines stay exactly as they were.
+ if (entry) void this.probeRemoteCodexNoDaemon(projectId, entry).catch(() => {})
return {
controlPath,
hookEndpointPath,
@@ -1109,7 +1120,8 @@ export class SshProjectManager {
codexRelayRuntimePath: entry?.codexRelayRuntimePath,
codexCliPath: entry?.codexCliPath,
claudeAutoPermissionMode: entry?.claudeAutoPermissionMode,
- remoteClaudeVersion: entry?.remoteClaudeVersion
+ remoteClaudeVersion: entry?.remoteClaudeVersion,
+ remoteCodexNoDaemon: entry?.remoteCodexNoDaemon
}
}
const alive = master.exited ? !master.exited() : undefined
@@ -2490,6 +2502,25 @@ export class SshProjectManager {
}
}
+ /**
+ * One remote `codex --help` (login shell, marker-delimited — `codex-no-daemon-probe.ts`), pushed
+ * as a `connected` event once it lands. No retries: an unknown answer only means the remote line
+ * stays as it has always been (no `--no-daemon`), and the next connect asks again.
+ */
+ private async probeRemoteCodexNoDaemon(projectId: string, entry: Conn): Promise<void> {
+ let supported: boolean | null = null
+ try {
+ const { stdout } = await this.r.run(childArgs(entry.conn, entry.controlPath, codexNoDaemonProbeCommand()))
+ supported = parseCodexNoDaemonProbe(stdout)
+ } catch {
+ supported = null
+ }
+ if (supported === null || this.conns.get(projectId) !== entry) return
+ const answer: RemoteCodexNoDaemon = { hostKey: sshHostKey(entry.conn), supported }
+ entry.remoteCodexNoDaemon = answer
+ this.emitStatus({ projectId, status: 'connected', remoteCodexNoDaemon: answer })
+ }
+
/**
* Probe the remote CLI's `--permission-mode auto` support AFTER the connect resolves, then push
* the answer into the live conn + the renderer (a `connected` status event carrying it).
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a082383c3..7c00110c6 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -16163,6 +16163,8 @@ export function Canvas() {
// The remote claude probe runs AFTER connect (its login shell is slow) and pushes its answer
// on a later `connected` event — record it so this project's next Claude launch can use
// `--permission-mode auto`. Absent = nothing new to record (keep omitting the flag).
+ // The host's `codex --help` answer: may a remote Codex TUI carry `--no-daemon`?
+ if (e.remoteCodexNoDaemon) useSshConn.getState().setRemoteCodexNoDaemon(e.remoteCodexNoDaemon)
if (e.claudeAutoPermissionMode !== undefined) {
useSshConn
.getState()
diff --git a/src/renderer/state/codexCli.test.ts b/src/renderer/state/codexCli.test.ts
new file mode 100644
index 000000000..f1a458bbe
--- /dev/null
+++ b/src/renderer/state/codexCli.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { codexApprovalCaps, resetCodexCliCapsForTests } from './codexCli'
+import { useSshConn } from './sshConn'
+
+const server = { host: 'box.example', user: 'dev', port: 22 }
+
+beforeEach(() => {
+ resetCodexCliCapsForTests()
+ useSshConn.setState({ codexNoDaemonByHost: {} })
+})
+
+describe('codexApprovalCaps — --no-daemon', () => {
+ it('a LOCAL session uses this machine\'s probe', () => {
+ resetCodexCliCapsForTests({ approvalValues: null, noDaemon: true })
+ expect(codexApprovalCaps().codexNoDaemon).toBe(true)
+ resetCodexCliCapsForTests({ approvalValues: null, noDaemon: false })
+ expect(codexApprovalCaps().codexNoDaemon).toBe(false)
+ })
+
+ it('a REMOTE session never borrows the local answer', () => {
+ resetCodexCliCapsForTests({ approvalValues: null, noDaemon: true })
+ expect(codexApprovalCaps(server).codexNoDaemon).toBeNull()
+ expect(codexApprovalCaps(true).codexNoDaemon).toBeNull()
+ })
+
+ it('a REMOTE session uses ITS host\'s probe, from a node connection or a project binding', () => {
+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: '[email protected]', supported: true })
+ expect(codexApprovalCaps(server).codexNoDaemon).toBe(true)
+ expect(codexApprovalCaps({ server, remoteCwd: '~' }).codexNoDaemon).toBe(true)
+ // Another host (or another user on the same host) is another binary.
+ expect(codexApprovalCaps({ ...server, user: 'ops' }).codexNoDaemon).toBeNull()
+ })
+
+ it('a host that answered no stays flagless', () => {
+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: '[email protected]', supported: false })
+ expect(codexApprovalCaps(server).codexNoDaemon).toBeNull()
+ })
+
+ it('a reused connection carries the answer in its connect result', () => {
+ useSshConn.getState().setConn('p1', {
+ controlPath: '/tmp/cm',
+ remoteCodexNoDaemon: { hostKey: '[email protected]', supported: true }
+ })
+ expect(codexApprovalCaps(server).codexNoDaemon).toBe(true)
+ })
+})
diff --git a/src/renderer/state/codexCli.ts b/src/renderer/state/codexCli.ts
index d19d9352f..c37663dd6 100644
--- a/src/renderer/state/codexCli.ts
+++ b/src/renderer/state/codexCli.ts
@@ -17,6 +17,8 @@ import {
type CodexCliCaps
} from '@shared/types'
import type { ApprovalCaps } from '@shared/agents/approval-mode'
+import { sshHostKey } from '@shared/ssh'
+import { useSshConn } from './sshConn'
const CAPS_WAIT_MS = 3000
@@ -58,7 +60,23 @@ export function codexCliCapsNow(): CodexCliCaps {
* to the baseline and the mode degrades honestly instead of guessing across machines.
*/
export function codexApprovalCaps(remote?: unknown): ApprovalCaps {
- return { codexApprovalValues: remote ? null : caps.approvalValues }
+ return remote
+ ? { codexApprovalValues: null, codexNoDaemon: remoteCodexNoDaemon(remote) }
+ : { codexApprovalValues: caps.approvalValues, codexNoDaemon: caps.noDaemon ?? null }
+}
+
+/**
+ * `--no-daemon` for a REMOTE session is the one codex fact we DO ask the host for: the SSH connect
+ * probes the host's own `codex --help` (core/remote-ssh/codex-no-daemon-probe.ts) and publishes the
+ * answer per `user@host`. `remote` is whatever the caller holds — an `SshConnection` (`data.ssh`) or
+ * a project's `{ server, remoteCwd }`; a bare `true` (or no probe yet) cannot name a host and
+ * answers unknown, i.e. no flag, i.e. the line this has always sent.
+ */
+function remoteCodexNoDaemon(remote: unknown): boolean | null {
+ const r = remote as { host?: unknown; user?: unknown; server?: { host?: unknown; user?: unknown } }
+ const conn = typeof r?.host === 'string' ? r : r?.server
+ if (!conn || typeof conn.host !== 'string' || typeof conn.user !== 'string') return null
+ return useSshConn.getState().remoteCodexNoDaemon(sshHostKey({ host: conn.host, user: conn.user })) || null
}
/** Test seam: drop the memo (and optionally preload a known answer). */
diff --git a/src/renderer/state/sshConn.ts b/src/renderer/state/sshConn.ts
index 5214c138e..13194f5e0 100644
--- a/src/renderer/state/sshConn.ts
+++ b/src/renderer/state/sshConn.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import type { SshConnection } from '@shared/ssh'
+import type { RemoteCodexNoDaemon } from '@shared/types'
/** Live connection coordinates for one connection scope, returned by `sshProject.connect`.
* A scope is an SSH PROJECT's id, or a host ATTACHMENT id — see `sshConnectionIdForProject`. */
@@ -24,6 +25,8 @@ export interface SshConnInfo {
/** The probed remote `claude --version` output (`null` = probe ran, claude not found). Feeds
* the tab menu's Auto hint; only present on a reused (already probed) connection. */
remoteClaudeVersion?: string | null
+ /** The host's `--no-daemon` answer, when the connection had already probed it (reused conns). */
+ remoteCodexNoDaemon?: RemoteCodexNoDaemon
/** Absolute remote path of the uploaded `nodeterm-codex` launcher (`chmod 700`). Present only
* when `installRemoteCodexRuntime` found node+codex+curl and staged the runtime. Absent ⇒ this
* host cannot host managed Codex accounts (the renderer keeps Codex nodes on the system login). */
@@ -99,6 +102,14 @@ interface SshConnState {
/** project id → the probed remote `claude --version` output (`null` = claude not found). Kept
* beside `autoPermByProject` (same lifecycle) so the tab-menu hint can name the version. */
remoteClaudeVersionByProject: Record<string, string | null>
+ /** `user@host` → that host's `codex` accepts `--no-daemon`. Keyed by HOST, not scope: it is a
+ * fact about the binary on that machine, shared by every project and attachment pointed at it,
+ * and a repointed project changes its key rather than inheriting a stale answer. */
+ codexNoDaemonByHost: Record<string, boolean>
+ /** Record a host's `--no-daemon` answer (a `connected` status event, or a reused connect). */
+ setRemoteCodexNoDaemon(answer: RemoteCodexNoDaemon): void
+ /** True ONLY when that host's codex was probed and advertised `--no-daemon`. */
+ remoteCodexNoDaemon(hostKey: string): boolean
setConn(projectId: string, info: SshConnInfo): void
/** Record the early (pre-setup) ControlMaster path for a scope. Ignored once the full info for
* that scope has landed — the full entry is strictly better and must not be walked back. */
@@ -170,7 +181,19 @@ export const useSshConn = create<SshConnState>((set, get) => ({
attachments: {},
autoPermByProject: {},
remoteClaudeVersionByProject: {},
+ codexNoDaemonByHost: {},
+ setRemoteCodexNoDaemon({ hostKey, supported }) {
+ set((s) =>
+ s.codexNoDaemonByHost[hostKey] === supported
+ ? s
+ : { codexNoDaemonByHost: { ...s.codexNoDaemonByHost, [hostKey]: supported } }
+ )
+ },
+ remoteCodexNoDaemon(hostKey) {
+ return get().codexNoDaemonByHost[hostKey] === true
+ },
setConn(projectId, info) {
+ if (info.remoteCodexNoDaemon) get().setRemoteCodexNoDaemon(info.remoteCodexNoDaemon)
set((s) => ({
byProject: { ...s.byProject, [projectId]: info },
// The full info supersedes the early path — keeping both would leave a stale socket string
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index aa97973b6..5ab9ec870 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -1601,7 +1601,10 @@ export class HeadlessNodeFactory {
sessionIdFlagSupported,
launchCmdOverride: settings.agentLaunchCommands?.[agentId as BuiltinAgentId],
sharedIdentity: codexSharedIdentity,
- approvalCaps: { codexApprovalValues: codexCaps.approvalValues },
+ approvalCaps: {
+ codexApprovalValues: codexCaps.approvalValues,
+ codexNoDaemon: codexCaps.noDaemon ?? null
+ },
model: args.model
},
this.deps.env ?? process.env
diff --git a/src/server/index.ts b/src/server/index.ts
index 4087c1443..0708589fb 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -485,6 +485,9 @@ export async function startServer(
...(localCodexCaps?.approvalValues
? { codexApprovalValues: localCodexCaps.approvalValues }
: {}), // unprobed ⇒ absent ⇒ the reader uses the baseline vocabulary
+ // Only a SEEN `true`: a phone-launched plain Codex TUI must carry `--no-daemon` too, or it
+ // joins the auto-started shared app-server and runs as another node (shared/agents/codex-daemon).
+ ...(localCodexCaps?.noDaemon === true ? { codexNoDaemon: true } : {}),
claudeAccounts: (s.claudeAccounts ?? [])
.filter((a) => !a.host && !a.pending)
.map((a) => ({ id: a.id, dir: claudeConfigDirFor(a.id) })),
diff --git a/src/shared/agents/approval-mode.ts b/src/shared/agents/approval-mode.ts
index e02a2d9fa..19719a0e0 100644
--- a/src/shared/agents/approval-mode.ts
+++ b/src/shared/agents/approval-mode.ts
@@ -47,6 +47,11 @@ export interface ApprovalCaps {
* from its own `--help` — see `core/codex-cli.ts`. `null`/absent = not probed, not probeable
* (a remote host, a relay tab), or the probe failed. */
codexApprovalValues?: readonly string[] | null
+ /** Does the `codex` that will RUN this session accept `--no-daemon`? Read by
+ * `withCodexNoDaemon` (`./codex-daemon`), not by anything in this file: the caps bag is simply
+ * what every launch site already threads to the two command assemblers. Anything but a literal
+ * `true` (a remote host, a relay tab, an unprobed or older CLI) emits nothing. */
+ codexNoDaemon?: boolean | null
}
/**
diff --git a/src/shared/agents/codex-daemon.test.ts b/src/shared/agents/codex-daemon.test.ts
new file mode 100644
index 000000000..a17166477
--- /dev/null
+++ b/src/shared/agents/codex-daemon.test.ts
@@ -0,0 +1,95 @@
+import { describe, it, expect, afterEach } from 'vitest'
+import { withCodexNoDaemon } from './codex-daemon'
+import { assembleLaunchCommand, assembleResumeCommand } from './launch'
+import type { CustomAgent } from '../types'
+import { setCustomAgentBaseResolver } from './config'
+
+afterEach(() => setCustomAgentBaseResolver(null))
+
+const ON = { codexNoDaemon: true }
+
+describe('withCodexNoDaemon', () => {
+ it('appends the flag to a codex line only when the CLI was SEEN to accept it', () => {
+ expect(withCodexNoDaemon('codex', 'codex', ON)).toBe('codex --no-daemon')
+ expect(withCodexNoDaemon('codex', 'codex', {})).toBe('codex')
+ expect(withCodexNoDaemon('codex', 'codex', { codexNoDaemon: null })).toBe('codex')
+ expect(withCodexNoDaemon('codex', 'codex', { codexNoDaemon: false })).toBe('codex')
+ })
+
+ it('never touches another agent', () => {
+ expect(withCodexNoDaemon('claude', 'claude', ON)).toBe('claude')
+ expect(withCodexNoDaemon('gemini', 'gemini', ON)).toBe('gemini')
+ })
+
+ it('is idempotent, and never pairs the flag with --remote (codex refuses the pair)', () => {
+ expect(withCodexNoDaemon('codex --no-daemon', 'codex', ON)).toBe('codex --no-daemon')
+ expect(withCodexNoDaemon('codex --remote ws://h:1', 'codex', ON)).toBe('codex --remote ws://h:1')
+ expect(withCodexNoDaemon('codex --remote=unix://', 'codex', ON)).toBe('codex --remote=unix://')
+ })
+
+ it('reads a quoted prompt as data, not as the flag', () => {
+ expect(withCodexNoDaemon("codex 'mention --no-daemon'", 'codex', ON)).toBe(
+ "codex 'mention --no-daemon' --no-daemon"
+ )
+ })
+})
+
+describe('every codex launch and resume line carries it (the two assemblers)', () => {
+ it('fresh launch with a prompt and a permission mode', () => {
+ const { command } = assembleLaunchCommand(
+ { agentId: 'codex', initialPrompt: 'fix it', permissionMode: 'auto', approvalCaps: ON },
+ {}
+ )
+ expect(command).toBe("codex 'fix it' --ask-for-approval on-request --no-daemon")
+ })
+
+ it('cold-restore / restart resume', () => {
+ const { command } = assembleResumeCommand(
+ { agentId: 'codex', sessionId: 'abc-123', permissionMode: 'auto', approvalCaps: ON },
+ {}
+ )
+ expect(command).toBe('codex resume abc-123 --ask-for-approval on-request --no-daemon')
+ })
+
+ it('a resume with no known session (a fresh relaunch)', () => {
+ const { command } = assembleResumeCommand({ agentId: 'codex', approvalCaps: ON }, {})
+ expect(command).toBe('codex --no-daemon')
+ })
+
+ it('the managed launcher line too — the launcher strips it before its own --remote', () => {
+ const { command } = assembleLaunchCommand(
+ { agentId: 'codex', sharedIdentity: true, approvalCaps: ON },
+ {}
+ )
+ expect(command).toBe('nodeterm-codex --no-daemon')
+ })
+
+ it('a custom agent whose baseAgent is codex (its own launch command)', () => {
+ const custom = {
+ id: 'custom:x',
+ label: 'My codex',
+ launchCmd: 'codex -m o4',
+ baseAgent: 'codex'
+ } as unknown as CustomAgent
+ setCustomAgentBaseResolver((id) => (id === 'custom:x' ? 'codex' : undefined))
+ const { command } = assembleLaunchCommand({ agentId: 'custom:x', customAgent: custom, approvalCaps: ON }, {})
+ expect(command).toBe('codex -m o4 --no-daemon')
+ })
+
+ it('a launch-command override (the user wrapper) keeps it too', () => {
+ const { command } = assembleLaunchCommand(
+ { agentId: 'codex', launchCmdOverride: 'my-codex-wrapper', approvalCaps: ON },
+ {}
+ )
+ expect(command).toBe('my-codex-wrapper --no-daemon')
+ })
+
+ it('unknown caps (a remote host nobody probed, an older CLI) leave every line byte-identical', () => {
+ expect(assembleLaunchCommand({ agentId: 'codex', initialPrompt: 'x' }, {}).command).toBe("codex 'x'")
+ expect(assembleResumeCommand({ agentId: 'codex', sessionId: 's1' }, {}).command).toBe('codex resume s1')
+ })
+
+ it('never lands on a non-codex agent even with the caps set', () => {
+ expect(assembleLaunchCommand({ agentId: 'claude', approvalCaps: ON }, {}).command).toBe('claude')
+ })
+})
diff --git a/src/shared/agents/codex-daemon.ts b/src/shared/agents/codex-daemon.ts
new file mode 100644
index 000000000..5bc247527
--- /dev/null
+++ b/src/shared/agents/codex-daemon.ts
@@ -0,0 +1,33 @@
+/**
+ * Keep every nodeterm-launched Codex TUI out of Codex's auto-started shared app-server.
+ *
+ * From codex-cli 0.157.0 the `daemon_auto_start` feature is `stable, true`: a plain `codex` TUI
+ * starts (or joins) ONE background app-server per `CODEX_HOME`, and that daemon keeps the
+ * environment of the pane that STARTED it. nodeterm tells a node apart by environment
+ * (`NODETERM_NODE_ID`, the hook endpoint — `buildPtyEnv`), and the daemon is what spawns tool
+ * shells and hook processes, so every later Codex node's hooks, canvas-control verbs and
+ * context-link reads were attributed to the first pane's node. Measured on 0.159.2 (see
+ * `codexNoDaemonFrom` in core/codex-cli.ts): `--no-daemon` fixes it, `-c
+ * features.daemon_auto_start=false` does not (it still joins a running daemon), and there is no
+ * environment switch.
+ *
+ * The flag goes on the line only when the CLI that will run it has been SEEN to accept it
+ * (`caps.codexNoDaemon === true`): clap exits on an unknown option, so an unprobed or remote CLI
+ * gets today's command line byte for byte. Never next to `--remote` — measured, codex refuses the
+ * pair ("--no-daemon cannot be used with --remote") — which is also why the managed launcher strips
+ * it again before its own `codex --remote unix:// resume` (core/codex-identity-proxy.ts) and keeps
+ * it for its plain-codex fallbacks.
+ */
+import { argvHasFlag } from '../shell-quote'
+import type { ApprovalCaps } from './approval-mode'
+import type { AgentId } from './config'
+
+export const CODEX_NO_DAEMON_FLAG = '--no-daemon'
+
+/** Append `--no-daemon` to a codex launch/resume line. `agentId` is the CAPABILITY id (a custom
+ * agent whose `baseAgent` is codex passes `codex`, exactly as `withPermissionMode` is called). */
+export function withCodexNoDaemon(cmd: string, agentId: AgentId, caps: ApprovalCaps = {}): string {
+ if (agentId !== 'codex' || caps.codexNoDaemon !== true) return cmd
+ if (argvHasFlag(cmd, CODEX_NO_DAEMON_FLAG) || argvHasFlag(cmd, '--remote')) return cmd
+ return `${cmd} ${CODEX_NO_DAEMON_FLAG}`
+}
diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.ts
index 3b3950977..0d19a57ad 100644
--- a/src/shared/agents/launch.ts
+++ b/src/shared/agents/launch.ts
@@ -28,6 +28,7 @@ import {
import { withPermissionMode, type ApprovalCaps } from './approval-mode'
import { resolveAgentConfig } from './custom-agent'
import { withAgentModel } from './model-gateway'
+import { withCodexNoDaemon } from './codex-daemon'
export interface LaunchInputs {
agentId: AgentId
@@ -236,7 +237,9 @@ export function assembleLaunchCommand(
return withAgentModel(withMode, capId, inputs.model)
}
- const command = usesSep ? `${flagged(baseCmd)} ${sep} ${promptArg}` : flagged(withPrompt)
+ const composed = usesSep ? `${flagged(baseCmd)} ${sep} ${promptArg}` : flagged(withPrompt)
+ // Codex has no prompt separator, so the flag lands last like its approval flag. See codex-daemon.
+ const command = withCodexNoDaemon(composed, capId, inputs.approvalCaps ?? {})
return { command, missingEnv: [...m1, ...m2] }
}
@@ -271,6 +274,10 @@ export function assembleResumeCommand(
const withMode = inputs.permissionMode
? withPermissionMode(base, capId, inputs.permissionMode, inputs.approvalCaps ?? {})
: base
- const command = withAgentModel(withMode, capId, inputs.model)
+ const command = withCodexNoDaemon(
+ withAgentModel(withMode, capId, inputs.model),
+ capId,
+ inputs.approvalCaps ?? {}
+ )
return { command, missingEnv: [...m1, ...m2] }
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 2e32a6b2e..9ecd651a5 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2381,6 +2381,17 @@ export interface SshProjectStatusEvent {
* `claudeAutoPermissionMode`. `null` = the probe ran but found no claude (distinguishable from
* "old CLI" in the tab-menu hint); absent = nothing new. */
remoteClaudeVersion?: string | null
+ /** Does THIS HOST's `codex` accept `--no-daemon` (probed after connect, `codex --help` through
+ * the login shell)? Keyed by `sshHostKey` because it is a fact about the host's binary, not the
+ * project. Only `supported: true` puts the flag on a remote Codex launch — see
+ * shared/agents/codex-daemon.ts. Absent = nothing new. */
+ remoteCodexNoDaemon?: RemoteCodexNoDaemon
+}
+
+/** A host's answer to "does its `codex` accept `--no-daemon`?" — see `SshProjectStatusEvent`. */
+export interface RemoteCodexNoDaemon {
+ hostKey: string
+ supported: boolean
}
/** main → renderer: this SSH identity file needs its passphrase (the ssh-agent doesn't hold the
@@ -2411,6 +2422,8 @@ export interface SshProjectApi {
claudeAutoPermissionMode?: boolean
/** The probed remote `claude --version` output (`null` = probe failed; only on reused conns). */
remoteClaudeVersion?: string | null
+ /** The host's `--no-daemon` answer, when a probe already ran on this connection (reused conns). */
+ remoteCodexNoDaemon?: RemoteCodexNoDaemon
}>
/** Tear down the master (remote tmux is unaffected). */
disconnect(projectId: string): Promise<void>
@@ -3474,11 +3487,17 @@ export interface CodexCliCaps {
* "this CLI accepts nothing". Measured: 0.146.0–0.148.0 list `untrusted, on-request, never`;
* 0.149.0+ list `on-request, never`. */
approvalValues: string[] | null
+ /** Does this `codex` accept `--no-daemon`? `null` = unknown (not probed, no codex). Every
+ * nodeterm-launched plain Codex TUI carries the flag when this is `true`: from 0.157.0 a plain
+ * TUI otherwise runs inside ONE shared background app-server per CODEX_HOME that keeps the FIRST
+ * pane's `NODETERM_*` environment, attributing every later node's hooks and tool shells to that
+ * first node (see `codexNoDaemonFrom`). Optional so an older core's answer still type-checks. */
+ noDaemon?: boolean | null
}
/** The answer before the probe has run, and for any surface that cannot speak for the CLI that will
* actually run the session (a relay tab, an SSH host). */
-export const UNKNOWN_CODEX_CLI_CAPS: CodexCliCaps = { approvalValues: null }
+export const UNKNOWN_CODEX_CLI_CAPS: CodexCliCaps = { approvalValues: null, noDaemon: null }
/** 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`. */