Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(codex): review round — await the caps, relay tabs, port-keyed hosts, pre-upgrade recovery
reviewf397edf7470f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4f1001b79..b68ab529d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -785,6 +785,26 @@ Lifecycle, by intent: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 anunprobed, remote-unknown or older CLI gets the line it always got.+ - **Await the answer before building a line — the race is the bug.** After a reboot every Codex+ node cold-restores in the same tick; a node that builds its line before the probe lands launches+ flagless, starts the shared daemon with ITS env, and every other node joins it. On a+ shared-identity machine `codex app-server daemon version` reports such a daemon `running`+ (verified in review), so the managed launcher adopts it too. So TerminalNode's four codex sites+ (cold restore, its fresh fallback, restart, wake) `await ensureCodexLaunchCaps(...)`+ (`renderer/state/codexCli.ts`, 3 s bound, fail open to the old line): local waits for the local+ probe, SSH waits for that host's answer to arrive in `useSshConn`, non-codex agents and relay+ tabs never wait. Pinned at source level by `nodes/codex-launch-caps-wiring.test.ts`.+ `createAgentNode` (a NEW node) is synchronous and still reads the landed answer — a node created+ inside the first ~second after boot can miss it; stated, not fixed.+ - **A relay tab never gets this machine's answer.** Its pane runs the HOST's codex; the guest's+ `true` typed into a host older than 0.156 dies on the unknown option. `codexApprovalCaps(remote,+ projectId)` treats a relay-bound project (checked through `registerCodexRelayProjectCheck`,+ registered by the projects store to avoid an import cycle) or a node's+ `session.source === 'relay'` as remote-with-no-probe: no flag, baseline vocabulary.+ - **One detection rule, two spellings.** `CODEX_NO_DAEMON_HELP_RE` / `_ERE`+ (`shared/agents/codex-daemon.ts`): an option header at indent <= 6 followed by whitespace or end+ of line, so a future `--no-daemon-x` is not this flag. TS reader, launcher and remote probe all+ use it; a test runs the ERE through real `grep -E` beside the regex.- **Never beside `--remote`** — measured: `ERROR: --no-daemon cannot be used with --remote.` Themanaged launcher (`buildCodexLauncherScript`) therefore STRIPS it before its own`codex --remote unix:// resume` and routes every plain-codex fallback through `nt_exec_plain`,@@ -795,24 +815,43 @@ Lifecycle, by intent: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 onemarker-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.+ the claude probe) and publishes `{hostKey, supported}` on a `connected` event and on a reused+ connect's result; the renderer keeps it per host (`useSshConn.codexNoDaemonByHost`). **The key+ is `user@host:port`** (`codexProbeHostKey`), NOT `sshHostKey`: two containers behind one machine+ (`root@localhost:2222` on 0.159, `:2223` on 0.148) are two binaries, and a portless key let the+ last probe answer for both. The SSH mirror slice carries the host's `true` to the phone.- `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`+ TUI clients of the daemon. The phone gets `MirrorSettings.codexNoDaemon`, local and per SSH slice (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.+ - **Residuals, stated:** (1) a `codex` TYPED into a pane rather than launched by us — by hand in a+ plain terminal, or by an agent through `open-terminal --cmd codex` / `write` — carries that+ node's `NODETERM_NODE_ID` and, on 0.157+, can still start the account's daemon with it; 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. (2) A launch-command override or custom `launchCmd`+ that runs a DIFFERENT codex than PATH's (`npx @openai/[email protected]`) is given the flag from+ PATH's probe and dies on it; the fix there is the user's (drop the pin or add the flag to their+ own command) — we cannot probe an arbitrary command line. (3) The Windows argv planner+ (`core/agent-launch.ts`) carries the flag but has no production caller today; Windows native+ Codex is unmeasured.+ - **Machines that ran a pre-fix build keep the mis-attribution until they recycle.** Panes already+ joined to the daemon stay joined across a warm reattach (the TUI process is still the old one); a+ daemon started before the fix keeps its first pane's env, and so does its `pid-update-loop`+ process (verified in review), so managed threads keep using it. We deliberately do NOT kill it:+ every unsupervised plain client attached to it would die with it. Recovery, in order: restart+ each Codex node (node menu → Restart, or close and reopen), then from a shell WITHOUT any+ `NODETERM_*` variables run `codex app-server daemon restart` (one per account: set that+ account's `CODEX_HOME`).- **Device checklist:** (a) macOS desktop, npm codex ≥ 0.157: two Codex nodes, each RUNNING badgeand `nodeterm list` line on its own node; (b) standalone codex with shared identity: a nodewhose 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.+ only if its `--help` lists it; (e) reboot a Mac with 5+ Codex nodes: after cold restore each+ badge is its own (the bounded wait); (f) an upgraded machine: after the recovery steps above,+ `ps eww` on the daemon shows no `NODETERM_NODE_ID`; (g) two SSH projects on one host at+ different ports with different codex versions: only the newer one's lines carry the flag.- **A shared Codex daemon restart is NOT a terminal-session restart.** tmux survives, and the Codexrollout/thread survives, but every `codex --remote unix://` TUI attached to that account's oneapp-server socket exits together. `buildCodexLauncherScript` therefore stays in the pane as adiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aacd2e893..0a2cefebd 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -679,8 +679,11 @@ first node's `NODETERM_NODE_ID` (measured on 0.159.2). Every nodeterm codex line`--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 newcodex 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".+yourself, and AWAIT `ensureCodexLaunchCaps` (bounded) where the site is async — a synchronous+read loses the race when every node cold-restores after a reboot. A relay tab or SSH node must be+passed as remote: the guest's or laptop's answer never applies to another machine's codex. 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 remotecommand string. `/proc/<pid>/cmdline` is mode 444 on a stock Linux, and a remote command line is argvdiff --git a/src/core/codex-cli.ts b/src/core/codex-cli.tsindex d852230f4..53a99821d 100644--- a/src/core/codex-cli.ts+++ b/src/core/codex-cli.ts@@ -30,6 +30,7 @@ import { UNKNOWN_CODEX_CLI_CAPS, type CodexCliCaps } from '../shared/types'import { findInLoginPath } from './pty-manager'import { directExecutableInvocation } from './exec-path'import { platform } from './platform'+import { CODEX_NO_DAEMON_HELP_RE } from '../shared/agents/codex-daemon'const execFileP = promisify(execFile)const PROBE_TIMEOUT_MS = 5000@@ -129,7 +130,7 @@ export function codexApprovalValuesFrom(helpOutput: string | null | undefined):*/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))+ return helpOutput.split(/\r?\n/).some((l) => CODEX_NO_DAEMON_HELP_RE.test(l))}let helpCached: Promise<string | null> | null = nulldiff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.tsindex 55b6dd616..59a73c68c 100644--- a/src/core/codex-identity-proxy.ts+++ b/src/core/codex-identity-proxy.ts@@ -48,6 +48,7 @@ import {writeFileSync} from 'fs'import path from 'path'+import { CODEX_NO_DAEMON_HELP_ERE } from '../shared/agents/codex-daemon'import { createHmac, timingSafeEqual } from 'crypto'import { renameAtomicSync } from './fs-atomic'import { platform } from './platform'@@ -786,6 +787,9 @@ nt_run_shared() {# spell the flag itself (\`withPermissionMode\` then suppresses ours and lets theirs through).# Rebuilt by rotating the positional list, which is the only way sh can edit "$@" without an array.nt_drop_next=0+ # The manual-resume hints below name the flag when the launch line carried it: a human resuming+ # by hand after the shared daemon failed must not start or join ANOTHER one with this pane's env.+ nt_hint_nd=''nt_left=$#while [ "$nt_left" -gt 0 ]; dont_arg=$1@@ -801,7 +805,7 @@ nt_run_shared() {# 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 ;;+ --no-daemon) nt_hint_nd=' --no-daemon'; continue ;;esacset -- "$@" "$nt_arg"done@@ -845,8 +849,8 @@ nt_run_shared() {fint_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+ printf '\\nNodeTerm: Codex daemon kept resetting; automatic resume stopped. Run: codex%s resume %s\\n' \+ "$nt_hint_nd" "$nt_shared_thread" >&2return "$nt_status"fi@@ -857,8 +861,8 @@ nt_run_shared() {nt_app_server_ready && breaknt_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+ printf 'NodeTerm: shared Codex daemon did not recover. Run: codex%s resume %s\\n' \+ "$nt_hint_nd" "$nt_shared_thread" >&2return "$nt_status"fisleep "$nt_start_try"@@ -879,7 +883,7 @@ nt_exec_plain() {for nt_plain_arg in "$@"; docase "$nt_plain_arg" in --no-daemon|--remote|--remote=*) exec codex "$@" ;; esacdone- if codex --help 2>/dev/null | grep -q -e '^[[:space:]]*--no-daemon'; then+ if codex --help 2>/dev/null | grep -q -E '${CODEX_NO_DAEMON_HELP_ERE}'; thenexec codex --no-daemon "$@"fiexec codex "$@"diff --git a/src/core/remote-ssh/codex-no-daemon-probe.ts b/src/core/remote-ssh/codex-no-daemon-probe.tsindex eac69b73a..385e4ecb4 100644--- a/src/core/remote-ssh/codex-no-daemon-probe.ts+++ b/src/core/remote-ssh/codex-no-daemon-probe.ts@@ -11,20 +11,21 @@// 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'+import { CODEX_NO_DAEMON_HELP_ERE } from '../../shared/agents/codex-daemon'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+ * Prints `yes` / `no` between the markers when a `codex` resolves, nothing otherwise. The match is+ * `CODEX_NO_DAEMON_HELP_ERE`, the shell spelling of `codexNoDaemonFrom`'s own rule. 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'; ` ++ `if codex --help 2>/dev/null | grep -q -E '${CODEX_NO_DAEMON_HELP_ERE}'; ` +`then a=yes; else a=no; fi; ` +`printf '${CODEX_NO_DAEMON_START}%s${CODEX_NO_DAEMON_END}' "$a"; }`const q = posixQuote(emit)diff --git a/src/main/index.ts b/src/main/index.tsindex f47b76155..e5b612a1a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2487,11 +2487,15 @@ app.whenReady().then(async () => {claudePermissionMode: s.claudePermissionMode,// The phone launches claude on the REMOTE host — its CLI is the gate, never the local one.autoSupported: sshProjectManager?.remoteAutoPermFor(projectId) === true,- // `codexApprovalValues` is deliberately ABSENT from an SSH slice. Same rule one agent over:- // the session runs the HOST's codex, there is no remote codex probe yet (claude has one, at- // connect), and publishing this machine's vocabulary for another machine's binary is the- // cross-host guess the whole gate exists to prevent. Absent ⇒ the baseline vocabulary ⇒- // Manual degrades honestly instead of a value the host may have removed.+ // `codexApprovalValues` is deliberately ABSENT from an SSH slice: the session runs the HOST's+ // codex, the only remote codex probe asks about `--no-daemon` (not the approval vocabulary),+ // and publishing this machine's vocabulary for another machine's binary is the cross-host+ // guess the whole gate exists to prevent. Absent ⇒ the baseline vocabulary ⇒ Manual+ // degrades honestly instead of a value the host may have removed.+ //+ // `codexNoDaemon` IS the host's own answer (core/remote-ssh/codex-no-daemon-probe.ts), so it+ // may ride — only as a seen `true`.+ ...(sshProjectManager?.remoteCodexNoDaemonFor(projectId) ? { codexNoDaemon: true as const } : {}),...(home && hostKey? {claudeAccounts: (s.claudeAccounts ?? [])diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex 340971099..d8985b62c 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -3285,24 +3285,24 @@ describe('SshProjectManager — remote codex --no-daemon probe', () => {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 () => {+ it('publishes the HOST\'s answer, keyed by user@host:port, 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 }+ remoteCodexNoDaemon: { hostKey: 'u@h:22', 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 })+ expect(again.remoteCodexNoDaemon).toEqual({ hostKey: 'u@h:22', 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 })+ expect(answered(events)?.remoteCodexNoDaemon).toEqual({ hostKey: 'u@h:22', supported: false })})it('no markers (no codex on the host, a failed probe) publishes nothing — the line stays as it was', async () => {diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 33cad0949..719cd2f7f 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -55,6 +55,7 @@ import {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 { codexProbeHostKey } from '../../shared/agents/codex-daemon'import { RemoteHooks } from './remote-hooks'import type { AgentToolsTrigger } from './agent-tools-freshness'import {@@ -1810,6 +1811,11 @@ export class SshProjectManager {/** The connection's cached remote `--permission-mode auto` capability (undefined = not* probed / not connected). Feeds the agent-status settings block the phone reads. */+ /** This connection's host codex takes `--no-daemon` — `true` only when its own probe said so. */+ remoteCodexNoDaemonFor(projectId: string): boolean {+ return this.conns.get(projectId)?.remoteCodexNoDaemon?.supported === true+ }+remoteAutoPermFor(projectId: string): boolean | undefined {return this.conns.get(projectId)?.claudeAutoPermissionMode}@@ -2516,7 +2522,9 @@ export class SshProjectManager {supported = null}if (supported === null || this.conns.get(projectId) !== entry) return- const answer: RemoteCodexNoDaemon = { hostKey: sshHostKey(entry.conn), supported }+ const hostKey = codexProbeHostKey(entry.conn)+ if (!hostKey) return+ const answer: RemoteCodexNoDaemon = { hostKey, supported }entry.remoteCodexNoDaemon = answerthis.emitStatus({ projectId, status: 'connected', remoteCodexNoDaemon: answer })}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 7c00110c6..5322d1e61 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,4 +1,6 @@import { reportTextDelivery } from '../lib/textDelivery'+import { withCodexNoDaemon } from '@shared/agents/codex-daemon'+import { codexApprovalCaps } from '../state/codexCli'import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'import { VisibleMiniMap } from './VisibleMiniMap'import { MinimapDock } from './MinimapDock'@@ -7480,7 +7482,18 @@ export function Canvas() {useAgentStatus.getState().byId[id]?.sessionId,node?.data.agentSessionId)- return agentId && sid ? resumeCommand(agentId, sid) : null+ const line = agentId && sid ? resumeCommand(agentId, sid) : null+ // A hand-typed resume must not start or join Codex's shared daemon either (codex-daemon.ts).+ return line && agentId+ ? withCodexNoDaemon(+ line,+ capabilityAgentId(agentId),+ codexApprovalCaps(+ node?.data.ssh || node?.data.sshRemoteTmux,+ useProjects.getState().activeProjectId ?? undefined+ )+ )+ : line}const targetLabel =targetAgentId == nulldiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 93b63a57f..ffef32f8b 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -232,7 +232,7 @@ import { liveProjectJumpTarget } from '../lib/projectJump'import { pushSessionRename } from '../lib/sessionRename'import { useSettings } from '../state/settings'import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../state/codexIdentity'-import { codexApprovalCaps } from '../state/codexCli'+import { ensureCodexLaunchCaps } from '../state/codexCli'import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'import { useLaunchDelivery } from '../state/launchDelivery'import { erroredDeps, handedOverDeps, holdReason, interruptedDeps, launchTooltip } from '../lib/pendingLaunch'@@ -4092,7 +4092,10 @@ export function TerminalNode({// Which `--ask-for-approval` values the codex that will run this node actually has.// Same remoteness question `shared` just answered: an SSH node runs the HOST's codex,// which this machine's probe never saw.- approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),+ approvalCaps: await ensureCodexLaunchCaps(+ capabilityAgentId(agentId),+ data.ssh || data.sshRemoteTmux || session.source === 'relay'+ ),// The launch-command override rides the relaunch too, so a wrapper user's node comes// back through its wrapper after a reboot — the moment env/account setup matters.// Scoped to the OWNING project (`warmOwningProjectId`) so a project-level wrapper does@@ -4157,7 +4160,10 @@ export function TerminalNode({permissionMode: mode,model: data.agentModel,sharedIdentity: shared,- approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),+ approvalCaps: await ensureCodexLaunchCaps(+ capabilityAgentId(agentId),+ data.ssh || data.sshRemoteTmux || session.source === 'relay'+ ),launchCmdOverride: agentLaunchOverride(agentId, ownerProjectId)},agentEnvSnapshot()@@ -4409,7 +4415,10 @@ export function TerminalNode({customAgent: customTarget,sessionId: agentSessionId,permissionMode: await ensureActivePermissionMode(target),- approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),+ approvalCaps: await ensureCodexLaunchCaps(+ capabilityAgentId(target),+ data.ssh || data.sshRemoteTmux || session.source === 'relay'+ ),model: selectedModel ?? undefined,// The launch-command override rides the restart too (the global layer is undefined for// a custom target, which already owns its launchCmd) — it is a property of how the@@ -4561,7 +4570,10 @@ export function TerminalNode({customAgent,sessionId: agentSessionId,permissionMode: await ensureActivePermissionMode(agentId),- approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),+ approvalCaps: await ensureCodexLaunchCaps(+ capabilityAgentId(agentId),+ data.ssh || data.sshRemoteTmux || session.source === 'relay'+ ),sharedIdentity: false,// The launch-command override lives on the user's own PATH (or is an absolute path),// not in a generated launcher dir, so it rides the wake too — project layer included.diff --git a/src/renderer/nodes/codex-launch-caps-wiring.test.ts b/src/renderer/nodes/codex-launch-caps-wiring.test.tsnew file mode 100644index 000000000..0f3d8d61a--- /dev/null+++ b/src/renderer/nodes/codex-launch-caps-wiring.test.ts@@ -0,0 +1,21 @@+// Every Codex line TerminalNode builds (cold restore, its fresh fallback, restart, wake) must AWAIT+// the bounded caps and say when it is a relay tab. A synchronous read races the probe exactly when+// every node cold-restores at once after a reboot — the first node then launches without+// `--no-daemon` and starts Codex's shared daemon with its own env — and a relay tab would type the+// GUEST's answer into the HOST's pane. Both compile fine, hence a source-level pin.+import { describe, it, expect } from 'vitest'+import fs from 'node:fs'+import path from 'node:path'++const src = fs.readFileSync(path.join(__dirname, 'TerminalNode.tsx'), 'utf8').replace(/\r\n/g, '\n')++describe('TerminalNode codex launch caps', () => {+ it('never reads the caps synchronously', () => {+ expect(src).not.toMatch(/codexApprovalCaps\(/)+ })++ it('awaits the bounded caps at every launch site, relay flag included', () => {+ const sites = src.match(/await ensureCodexLaunchCaps\(\s*capabilityAgentId\(\w+\),\s*data\.ssh \|\| data\.sshRemoteTmux \|\| session\.source === 'relay'\s*\)/g) ?? []+ expect(sites.length).toBe(4)+ })+})diff --git a/src/renderer/state/codexCli.test.ts b/src/renderer/state/codexCli.test.tsindex f1a458bbe..cfd72d1c7 100644--- a/src/renderer/state/codexCli.test.ts+++ b/src/renderer/state/codexCli.test.ts@@ -1,16 +1,24 @@-import { describe, it, expect, beforeEach } from 'vitest'-import { codexApprovalCaps, resetCodexCliCapsForTests } from './codexCli'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import {+ codexApprovalCaps,+ ensureCodexLaunchCaps,+ registerCodexRelayProjectCheck,+ resetCodexCliCapsForTests+} from './codexCli'import { useSshConn } from './sshConn'const server = { host: 'box.example', user: 'dev', port: 22 }+const KEY = '[email protected]:22'beforeEach(() => {resetCodexCliCapsForTests()useSshConn.setState({ codexNoDaemonByHost: {} })+ registerCodexRelayProjectCheck(null)})+afterEach(() => vi.useRealTimers())describe('codexApprovalCaps — --no-daemon', () => {- it('a LOCAL session uses this machine\'s probe', () => {+ it("a LOCAL session uses this machine's probe", () => {resetCodexCliCapsForTests({ approvalValues: null, noDaemon: true })expect(codexApprovalCaps().codexNoDaemon).toBe(true)resetCodexCliCapsForTests({ approvalValues: null, noDaemon: false })@@ -23,24 +31,80 @@ describe('codexApprovalCaps — --no-daemon', () => {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 })+ it("a RELAY tab never gets the guest's answer — its pane runs the HOST's codex", () => {+ resetCodexCliCapsForTests({ approvalValues: ['untrusted', 'on-request', 'never'], noDaemon: true })+ registerCodexRelayProjectCheck((id) => id === 'relay-tab')+ const byProject = codexApprovalCaps(undefined, 'relay-tab')+ expect(byProject).toEqual({ codexApprovalValues: null, codexNoDaemon: null })+ // …and a node that says so itself (`session.source === 'relay'`).+ expect(codexApprovalCaps(true).codexNoDaemon).toBeNull()+ // A local project is untouched.+ expect(codexApprovalCaps(undefined, 'local').codexNoDaemon).toBe(true)+ })++ it("a REMOTE session uses ITS host's probe, from a node connection or a project binding", () => {+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: KEY, 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.+ // Another user on the same host is another answer.expect(codexApprovalCaps({ ...server, user: 'ops' }).codexNoDaemon).toBeNull()})+ it('the PORT is part of the host: two containers on one machine are two binaries', () => {+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: 'root@localhost:2222', supported: true })+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: 'root@localhost:2223', supported: false })+ expect(codexApprovalCaps({ host: 'localhost', user: 'root', port: 2222 }).codexNoDaemon).toBe(true)+ expect(codexApprovalCaps({ host: 'localhost', user: 'root', port: 2223 }).codexNoDaemon).toBeNull()+ // No port = ssh's default, 22 — never "any port".+ expect(codexApprovalCaps({ host: 'localhost', user: 'root' }).codexNoDaemon).toBeNull()+ })+it('a host that answered no stays flagless', () => {- useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: '[email protected]', supported: false })+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: KEY, 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 }+ remoteCodexNoDaemon: { hostKey: KEY, supported: true }})expect(codexApprovalCaps(server).codexNoDaemon).toBe(true)})})++// The cold-restore race: every Codex node relaunches in the same tick after a reboot, and the one+// that builds its line before the probe lands starts the shared daemon with its own env.+describe('ensureCodexLaunchCaps — waits (bounded) for the answer before a codex line is built', () => {+ it('an SSH codex launch waits for its host\'s probe and then carries the flag', async () => {+ const pending = ensureCodexLaunchCaps('codex', server, undefined, 5000)+ let settled = false+ void pending.then(() => (settled = true))+ await Promise.resolve()+ expect(settled).toBe(false)+ useSshConn.getState().setRemoteCodexNoDaemon({ hostKey: KEY, supported: true })+ expect((await pending).codexNoDaemon).toBe(true)+ })++ it('a host that never answers releases the launch at the bound, flagless (fail open)', async () => {+ vi.useFakeTimers()+ const pending = ensureCodexLaunchCaps('codex', server, undefined, 3000)+ await vi.advanceTimersByTimeAsync(3000)+ expect((await pending).codexNoDaemon).toBeNull()+ })++ it('never waits for a non-codex agent, nor for a relay tab', async () => {+ registerCodexRelayProjectCheck((id) => id === 'relay-tab')+ vi.useFakeTimers()+ let done = 0+ void ensureCodexLaunchCaps('claude', server).then(() => done++)+ void ensureCodexLaunchCaps('codex', undefined, 'relay-tab').then(() => done++)+ await vi.advanceTimersByTimeAsync(0)+ expect(done).toBe(2)+ })++ it('a local codex launch reads the landed local probe', async () => {+ resetCodexCliCapsForTests({ approvalValues: null, noDaemon: true })+ expect((await ensureCodexLaunchCaps('codex')).codexNoDaemon).toBe(true)+ })+})diff --git a/src/renderer/state/codexCli.ts b/src/renderer/state/codexCli.tsindex c37663dd6..402193bf1 100644--- a/src/renderer/state/codexCli.ts+++ b/src/renderer/state/codexCli.ts@@ -17,7 +17,7 @@ import {type CodexCliCaps} from '@shared/types'import type { ApprovalCaps } from '@shared/agents/approval-mode'-import { sshHostKey } from '@shared/ssh'+import { codexProbeHostKey } from '@shared/agents/codex-daemon'import { useSshConn } from './sshConn'const CAPS_WAIT_MS = 3000@@ -48,39 +48,103 @@ export function codexCliCapsNow(): CodexCliCaps {}/**- * The approval caps to build a launch line with. `remote` is anything truthy that marks the session- * as running on another machine (`project.ssh`, `data.ssh`, `data.sshRemoteTmux` — the caller- * passes whichever it holds; only its truthiness is read), exactly like `codexSharedIdentity`.+ * Is this project a RELAY tab (a live connection to another machine's core)? Registered by the+ * projects store at module load (`registerCodexRelayProjectCheck`) so this module does not import+ * the store — the store imports `workspace.ts`, which imports this file. Absent = no project is a+ * relay tab, the safe answer for a test that never loads the store.+ */+let relayProjectCheck: ((projectId: string) => boolean) | null = null+export function registerCodexRelayProjectCheck(fn: ((projectId: string) => boolean) | null): void {+ relayProjectCheck = fn+}++/**+ * The caps to build a Codex launch line with.*- * A REMOTE session runs the HOST's codex, which this probe never looked at and whose version is- * unrelated to ours — a host on 0.154 would be handed `untrusted` because the laptop still has- * 0.148, and the node would die on the host with the laptop reporting the mode as supported.- * CLAUDE.md already states the general form of this ("the version that matters is the one on the- * HOST"); claude answers it with a remote probe at connect, codex has none yet, so remote resolves- * to the baseline and the mode degrades honestly instead of guessing across machines.+ * `remote` marks a session that runs on ANOTHER machine: an SSH node (`data.ssh`, a project's+ * `{ server, remoteCwd }`, or a bare `data.sshRemoteTmux` / `true`), or a relay tab (the caller's+ * `session.source === 'relay'`, or `projectId` naming a relay-bound project). A remote session runs+ * the HOST's codex, which this machine's probe never looked at: a host on 0.154 handed `untrusted`+ * because the laptop has 0.148 dies on the host, and a host older than 0.156 handed `--no-daemon`+ * dies the same way. So a remote session gets the baseline vocabulary, and `--no-daemon` only from+ * THAT host's own probe (SSH, `core/remote-ssh/codex-no-daemon-probe.ts`). A relay tab has no probe+ * of its host's codex at all and emits neither.*/-export function codexApprovalCaps(remote?: unknown): ApprovalCaps {- return remote- ? { codexApprovalValues: null, codexNoDaemon: remoteCodexNoDaemon(remote) }- : { codexApprovalValues: caps.approvalValues, codexNoDaemon: caps.noDaemon ?? null }+export function codexApprovalCaps(remote?: unknown, projectId?: string): ApprovalCaps {+ const relay = !!projectId && !!relayProjectCheck?.(projectId)+ if (remote || relay)+ return { codexApprovalValues: null, codexNoDaemon: relay ? null : remoteCodexNoDaemon(remote) }+ return { codexApprovalValues: caps.approvalValues, codexNoDaemon: caps.noDaemon ?? null }}+/** How long a Codex launch waits for its probe before building the line without it. */+export const CODEX_CAPS_LAUNCH_WAIT_MS = 3000+/**- * `--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.+ * `codexApprovalCaps`, but WAITS (bounded) for the probe that answers it, for a codex launch.+ *+ * Why this exists: the synchronous read is a race at exactly the worst moment. After a reboot every+ * Codex node cold-restores in the same tick; if the probe has not landed, the first node launches+ * WITHOUT `--no-daemon`, starts Codex's shared app-server with ITS pane environment, and every other+ * node joins it — the bug the flag exists to prevent. On a shared-identity machine it is worse:+ * `codex app-server daemon version` reports that daemon `running`, so the managed launcher adopts it+ * and every managed thread runs inside it too. Local: `ensureCodexCliCaps` (already bounded). SSH:+ * wait for this host's answer to arrive in `useSshConn`, bounded — a host with no codex never+ * answers, and a launch must never be held hostage by a probe (fail open to the old line).+ * Non-codex agents and relay tabs never wait.*/-function remoteCodexNoDaemon(remote: unknown): boolean | null {- const r = remote as { host?: unknown; user?: unknown; server?: { host?: unknown; user?: unknown } }+export async function ensureCodexLaunchCaps(+ capabilityId: string,+ remote?: unknown,+ projectId?: string,+ waitMs = CODEX_CAPS_LAUNCH_WAIT_MS+): Promise<ApprovalCaps> {+ const relay = !!projectId && !!relayProjectCheck?.(projectId)+ if (capabilityId === 'codex' && !relay) {+ if (!remote) await ensureCodexCliCaps()+ else {+ const key = remoteHostKey(remote)+ if (key) await waitForHostAnswer(key, waitMs)+ }+ }+ return codexApprovalCaps(remote, projectId)+}++function waitForHostAnswer(key: string, waitMs: number): Promise<void> {+ if (key in useSshConn.getState().codexNoDaemonByHost) return Promise.resolve()+ return new Promise((resolve) => {+ let unsub = (): void => {}+ const done = (): void => {+ clearTimeout(timer)+ unsub()+ resolve()+ }+ const timer = setTimeout(done, waitMs)+ unsub = useSshConn.subscribe((s) => {+ if (key in s.codexNoDaemonByHost) done()+ })+ })+}++function remoteHostKey(remote: unknown): string | null {+ const r = remote as { host?: unknown; server?: 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+ return conn && typeof conn === 'object' ? codexProbeHostKey(conn as Record<string, unknown>) : null+}++/**+ * `--no-daemon` for an SSH session comes from that host's own probe, published per+ * `user@host:port` (`codexProbeHostKey`). A bare `true` 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 key = remoteHostKey(remote)+ return key && useSshConn.getState().remoteCodexNoDaemon(key) ? true : null}/** Test seam: drop the memo (and optionally preload a known answer). */export function resetCodexCliCapsForTests(next?: CodexCliCaps): void {caps = next ?? UNKNOWN_CODEX_CLI_CAPS- capsPromise = null+ // A preloaded answer counts as landed, so a launch under test does not wait for a bridge.+ capsPromise = next ? Promise.resolve(caps) : null}diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 7e6501b1a..52ffad799 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -26,6 +26,7 @@ import {import { applyCanvasOp as applyCanvasOpTo, contentOf } from '@shared/canvas-content'import { diffToMutations, type CanvasScene } from '@shared/canvas-mutations'import { applyOwnCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'+import { registerCodexRelayProjectCheck } from './codexCli'import { markWorkspaceDirty } from './workspaceDirty'import { folderName } from '../lib/projectOpen'// One order-independent key for an edge's endpoints — the SAME rule `hiddenLinkIds` uses, so a@@ -1091,3 +1092,8 @@ export const useProjects = create<ProjectsState>((set, get) => ({return { version: 2, activeProjectId, projects: projects.filter((p) => !p.remote) }}}))++// Codex launch caps must know a relay tab when they see one: its sessions run on ANOTHER machine's+// codex, which this machine's probe never saw (see `codexApprovalCaps`). Registered here rather+// than imported there, because this store imports workspace.ts, which imports codexCli.ts.+registerCodexRelayProjectCheck((id) => useProjects.getState().getProject(id)?.remote === true)diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 41eeedbe3..c09a0de3a 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -722,7 +722,7 @@ export function createAgentNode(// Which `--ask-for-approval` values this node's codex actually has. Same `ssh` truthiness as// the line above, and for a related reason: a remote session runs the HOST's codex, so the// local probe must not speak for it (it falls back to the baseline vocabulary instead).- approvalCaps: codexApprovalCaps(ssh),+ approvalCaps: codexApprovalCaps(ssh, projectId),// A model picked at creation (e.g. Transfer-to-agent-with-model). `withAgentModel` appends// `--model <value>` for a switch-capable agent and no-ops otherwise, so the line stays// byte-identical when no model is chosen.diff --git a/src/shared/agents/codex-daemon.test.ts b/src/shared/agents/codex-daemon.test.tsindex a17166477..27683b127 100644--- a/src/shared/agents/codex-daemon.test.ts+++ b/src/shared/agents/codex-daemon.test.ts@@ -93,3 +93,36 @@ describe('every codex launch and resume line carries it (the two assemblers)', (expect(assembleLaunchCommand({ agentId: 'claude', approvalCaps: ON }, {}).command).toBe('claude')})})++describe('one detection rule, two spellings', () => {+ it('the TS regex and the shell ERE agree, and neither reads a future --no-daemon-x', async () => {+ const { CODEX_NO_DAEMON_HELP_RE, CODEX_NO_DAEMON_HELP_ERE } = await import('./codex-daemon')+ const { execFileSync } = await import('node:child_process')+ const cases: Array<[string, boolean]> = [+ [' --no-daemon', true],+ [' --no-daemon Run without the shared background server', true],+ [' --no-daemon', true],+ [' --no-daemon-x', false],+ [' --no-daemons', false],+ [' Unlike --no-daemon this needs an address', false],+ ['--remote --no-daemon', false]+ ]+ for (const [line, want] of cases) {+ expect(CODEX_NO_DAEMON_HELP_RE.test(line), line).toBe(want)+ let sh = true+ try {+ execFileSync('grep', ['-q', '-E', CODEX_NO_DAEMON_HELP_ERE], { input: `${line}\n` })+ } catch {+ sh = false+ }+ expect(sh, `grep -E: ${line}`).toBe(want)+ }+ })++ it('the probe host key carries the port', async () => {+ const { codexProbeHostKey } = await import('./codex-daemon')+ expect(codexProbeHostKey({ user: 'root', host: 'localhost', port: 2222 })).toBe('root@localhost:2222')+ expect(codexProbeHostKey({ user: 'root', host: 'localhost' })).toBe('root@localhost:22')+ expect(codexProbeHostKey({ host: 'localhost' })).toBeNull()+ })+})diff --git a/src/shared/agents/codex-daemon.ts b/src/shared/agents/codex-daemon.tsindex 5bc247527..349321a48 100644--- a/src/shared/agents/codex-daemon.ts+++ b/src/shared/agents/codex-daemon.ts@@ -24,6 +24,27 @@ import type { AgentId } from './config'export const CODEX_NO_DAEMON_FLAG = '--no-daemon'+/**+ * The ONE detection rule, spelled for both readers: an option HEADER line (indent <= 6, which is+ * where clap puts options; descriptions sit at 10), and the flag followed by whitespace or the end+ * of the line — so a future `--no-daemon-x` option is not read as this one. The TS reader+ * (`codexNoDaemonFrom`) and every generated shell reader (`grep -E`, the managed launcher and the+ * remote probe) use these two strings; a test pins that they agree on the same inputs.+ */+export const CODEX_NO_DAEMON_HELP_RE = /^ {0,6}--no-daemon(\s|$)/+export const CODEX_NO_DAEMON_HELP_ERE = '^ {0,6}--no-daemon([[:space:]]|$)'++/**+ * Which host a remote `--no-daemon` answer belongs to: `user@host:port`. The PORT is part of it on+ * purpose — two containers on one machine (`root@localhost:2222`, `:2223`) are two binaries, and a+ * key without the port let the last probe answer for both (a 0.148 container handed the flag dies).+ */+export function codexProbeHostKey(conn: { user?: unknown; host?: unknown; port?: unknown }): string | null {+ if (typeof conn.host !== 'string' || typeof conn.user !== 'string') return null+ const port = typeof conn.port === 'number' && Number.isFinite(conn.port) ? conn.port : 22+ return `${conn.user}@${conn.host}:${port}`+}+/** 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 {