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): gate the approval mapping on the CLI's own vocabulary (#785)
enesdf1f57199ead
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a8b723fe2..8bb7a4597 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,4 +71,4 @@ jobs:run: npm run host:build- name: Windows-relevant tests- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsx+ run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/codex-cli.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsxdiff --git a/CLAUDE.md b/CLAUDE.mdindex 9558131f7..f108819c7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1660,7 +1660,8 @@ else, and its context links must keep classifying across restarts).`src/shared/agents/approval-mode.ts`** (`approvalFlags` / `modeSupported`), which is also where`withPermissionMode` now lives — it moved one layer up out of `config.ts` to break a cycle.gemini = `--approval-mode default|auto_edit|yolo|plan`, codex = `--ask-for-approval- untrusted|on-request|never`. Two rules the mapping exists to enforce: a mode the CLI **cannot+ on-request|never` (and `untrusted` too, but only on a codex that still has it — see the next+ paragraph). Two rules the mapping exists to enforce: a mode the CLI **cannotexpress emits NO flag**, never a substituted nearest match (codex has no `plan` and noedit-specific mode; **gemini has no `auto`** — nothing in its vocabulary means "approve most thingsbut not edits", and since `auto` is the DEFAULT mode, mapping it to `auto_edit` would have switched@@ -1671,10 +1672,40 @@ else, and its context links must keep classifying across restarts).ask" under an "Ask each time" label. **codex is the first agent where `manual` emits a flag.** TheUI copy is DERIVED from the mapping (`permissionModeAgentIds` / `permissionModeAgentsLabel` /`unsupportedModesNote` / `bypassSandboxCaveat`) so a sentence cannot drift from what the table- does — so the note now reads "Auto has no Gemini equivalent…" beside codex's two gaps, and the+ does — so the note now reads "Auto has no Gemini equivalent…" beside codex's gaps, and theresidual wart is only that `auto` and `manual` land on the same gemini policy (the *prompting* one).`--sandbox` is a separate axis and deliberately untouched (`--ask-for-approval never`still sandboxes).+ **AN AGENT'S VOCABULARY IS NOT A CONSTANT — codex's moved, and the table is gated on a probe of+ the binary in front of us (#785).** Measured release by release on the published linux-x64+ binaries: 0.146.0 / 0.147.0 / 0.148.0 advertise `untrusted, on-request, never`; **0.149.0**+ through 0.154.0 advertise `on-request, never`. clap does not ignore a value it does not know, it+ prints `error: invalid value 'untrusted'` and **exits**, so a Manual-mode Codex node launched from+ the pinned table died at the prompt and left the pane at a bare shell. The gate is codex's OWN and+ sits beside claude's, never inside it (a gate fed by `claude --version` belongs to claude):+ **`core/codex-cli.ts`** reads `codex --help` once per app run — FEATURE-detected, not+ version-compared, because a floor guesses about builds that are not on npm — parses the option's+ own slice with `codexApprovalValuesFrom` (the neighbouring `-s, --sandbox` carries its own+ `[possible values: …]` two lines up, and a page-wide scan emits `--ask-for-approval read-only`),+ and publishes `CodexCliCaps` over `codex.cliCaps()`, registered by **both** shells. Every emitter+ threads it as `ApprovalCaps` — `approvalFlags` / `modeSupported` / `withPermissionMode` /+ `unsupportedModesNote` all take an optional trailing `caps`, and the **omitted** form resolves to+ the BASELINE `['on-request','never']`, the two values every measured codex accepts. That default+ is the design: a call site that forgets to thread its probe result loses a mode, never a launch.+ On 0.149.0+ `modeSupported('codex','manual')` is **false** and the derived note says so —+ measured before concluding it: `-a unless-trusted` is refused, `-c approval_policy=untrusted`+ fails config load, and `--approve-for-me` routes approvals through *automatic* review. **Remote is+ unknown, never guessed**: an SSH node runs the HOST's codex and there is no remote codex probe yet+ (claude has one, at connect), so `codexApprovalCaps(ssh)` and the mirror's SSH slice publish+ nothing and fall to the baseline. Same for a relay tab (the guest's machine) — its stub answers+ unknown on purpose. Three surfaces: **Desktop** and **Server Edition** both probe their own+ machine (the server's `registerCodexCliIpc` is REAL, unlike its deliberately-false+ `registerCodexIdentityIpc`); **Mobile** gets the vocabulary as `MirrorSettings.codexApprovalValues`+ — the desktop/server now publish it, the iOS reader is the follow-up. The app-server **usage+ tier** (`usage/codex-usage.ts`) carried the same dead `-a untrusted` and silently returned null on+ every current CLI; it is now `-a never` with **no probe**, because `never` is in both vocabularies+ (measured against 0.148.0 / 0.151.0 / 0.154.0) and `-s read-only` is what actually guards the+ user's files.`settings.claudePermissionMode` (global, default **`auto`** — a behavior change for existingusers, who previously got a prompt per action) is overridden per project by`project.defaultPermissionMode` (persisted to `.nodeterm/project.json`, so a `bypassPermissions`diff --git a/src/core/__fixtures__/codex/help-0.148.0.txt b/src/core/__fixtures__/codex/help-0.148.0.txtnew file mode 100644index 000000000..843883eba--- /dev/null+++ b/src/core/__fixtures__/codex/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 versiondiff --git a/src/core/__fixtures__/codex/help-0.151.0.txt b/src/core/__fixtures__/codex/help-0.151.0.txtnew file mode 100644index 000000000..e43ab5993--- /dev/null+++ b/src/core/__fixtures__/codex/help-0.151.0.txt@@ -0,0 +1,131 @@+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+ 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)+ 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++ --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.++ -h, --help+ Print help (see a summary with '-h')++ -V, --version+ Print versiondiff --git a/src/core/__fixtures__/codex/help-short-0.148.0.txt b/src/core/__fixtures__/codex/help-short-0.148.0.txtnew file mode 100644index 000000000..88b8c45dc--- /dev/null+++ b/src/core/__fixtures__/codex/help-short-0.148.0.txt@@ -0,0 +1,93 @@+Codex 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+ --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+ --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, on-request, never]+ --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+ -h, --help+ Print help (see more with '--help')+ -V, --version+ Print versiondiff --git a/src/core/__fixtures__/codex/help-short-0.151.0.txt b/src/core/__fixtures__/codex/help-short-0.151.0.txtnew file mode 100644index 000000000..f5e00967b--- /dev/null+++ b/src/core/__fixtures__/codex/help-short-0.151.0.txt@@ -0,0 +1,95 @@+Codex 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+ 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)+ 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+ --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+ --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: on-request, never]+ --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+ -h, --help+ Print help (see more with '--help')+ -V, --version+ Print versiondiff --git a/src/core/agent-launch.ts b/src/core/agent-launch.tsindex 262616cf2..16d99abf8 100644--- a/src/core/agent-launch.ts+++ b/src/core/agent-launch.ts@@ -54,6 +54,17 @@ export interface AgentLaunchTrustedContext {resolveExecutableKind?: AgentLaunchExecutableKindResolver;/** Trusted absolute Windows PowerShell executable used only as cmd's ASCII-safe wrapper. */windowsPowerShellPath?: string;+ /**+ * What the host's `codex` accepts for `--ask-for-approval`, from `core/codex-cli.ts`'s probe of+ * the binary this plan will exec. Host-authoritative like everything else here, and injected+ * rather than read inline so this planner stays pure and testable.+ *+ * Absent = unknown = the baseline vocabulary, which is the safe degrade everywhere: the launch+ * still happens, at worst `manual` falls back to codex's own default. The value that makes this+ * field necessary is `untrusted`, which codex removed in 0.149.0 — clap EXITS on a value it does+ * not know, so emitting it blind is a dead session, not a degraded one.+ */+ codexApprovalValues?: readonly string[] | null;}/** Core-private launch material. It must never cross the renderer/preload/relay boundary. */@@ -342,7 +353,9 @@ function logicalLaunch(if (intent.permissionMode !== undefined && !hasPermissionMode(config.id))fail("invalid-intent");const modeFlags = intent.permissionMode- ? approvalFlags(config.id, intent.permissionMode)+ ? approvalFlags(config.id, intent.permissionMode, {+ codexApprovalValues: context.codexApprovalValues,+ }): [];if (intent.action === "resume") {diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex 95dcb5755..c052e9c38 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -168,6 +168,18 @@ export interface MirrorSettings {autoSupported?: boolean/** Managed accounts usable on THIS host; dirs are absolute on that host. */claudeAccounts?: { id: string; dir: string }[]+ /**+ * Which values THIS host's `codex` accepts for `--ask-for-approval`, read from its own `--help`.+ * Absent = not probed / not knowable for this host, which means "use `on-request` and `never`+ * only" — the two values every codex from 0.146.0 to 0.154.0 takes.+ *+ * A reader must not emit a value that is not in this list. `untrusted` was removed in codex+ * 0.149.0 and clap EXITS on an unknown value, so a phone that launches Manual-mode Codex from a+ * hardcoded table gets a dead pane with the CLI's usage error in it (issue #785). It is a+ * per-agent, per-host fact for the same reason `autoSupported` is: it answers for *codex* on+ * *this* host and generalizes to neither another agent nor another machine.+ */+ codexApprovalValues?: string[]}export interface MirrorFile {diff --git a/src/core/codex-cli.test.ts b/src/core/codex-cli.test.tsnew file mode 100644index 000000000..1440513e0--- /dev/null+++ b/src/core/codex-cli.test.ts@@ -0,0 +1,149 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { codexApprovalValuesFrom } from './codex-cli'+import { CODEX_APP_SERVER_ARGS } from './usage/codex-usage'++/**+ * The four fixtures are REAL `codex --help` / `codex -h` output, captured by running the published+ * linux-x64 binaries (`npm pack @openai/codex@<v>-linux-x64`) rather than transcribed from an+ * issue. That distinction is the point of this file: #785 reported the removal as a 0.154 change,+ * and running the releases one at a time showed `untrusted` was already gone in **0.149.0** — five+ * releases earlier, so the "Manual kills the launch" window had been open far longer than the+ * report implied.+ */+const fixture = (name: string): string =>+ readFileSync(path.join(__dirname, '__fixtures__', 'codex', name), 'utf8')++describe('codexApprovalValuesFrom — real help pages', () => {+ it('reads the pre-removal vocabulary from codex 0.148.0 (long --help)', () => {+ expect(codexApprovalValuesFrom(fixture('help-0.148.0.txt'))).toEqual([+ 'untrusted',+ 'on-request',+ 'never'+ ])+ })++ it('reads the post-removal vocabulary from codex 0.151.0 (long --help)', () => {+ expect(codexApprovalValuesFrom(fixture('help-0.151.0.txt'))).toEqual(['on-request', 'never'])+ })++ // `-h` renders the same fact inline and WRAPS IT mid-phrase ("… [possible" / "values: on-request,+ // never]"), which a line-by-line parser reads as no values at all.+ it('reads the inline `[possible values: …]` form from `-h`, wrapping included', () => {+ expect(codexApprovalValuesFrom(fixture('help-short-0.148.0.txt'))).toEqual([+ 'untrusted',+ 'on-request',+ 'never'+ ])+ expect(codexApprovalValuesFrom(fixture('help-short-0.151.0.txt'))).toEqual([+ 'on-request',+ 'never'+ ])+ })++ /**+ * THE trap this parser was written around. `-s, --sandbox` carries its own `[possible values:+ * read-only, workspace-write, danger-full-access]` a few lines above `--ask-for-approval` on+ * every one of these pages, so a scan for "possible values" answers with the SANDBOX vocabulary+ * — and the launch line then says `--ask-for-approval read-only`, which is a dead node wearing a+ * valid-looking flag.+ */+ it('never returns the neighbouring --sandbox vocabulary', () => {+ for (const name of [+ 'help-0.148.0.txt',+ 'help-0.151.0.txt',+ 'help-short-0.148.0.txt',+ 'help-short-0.151.0.txt'+ ]) {+ const values = codexApprovalValuesFrom(fixture(name))+ // Asserted non-null FIRST and deliberately: `?? []` would let a parser that found nothing at+ // all pass this as vacuously clean, which is the one way a "never returns the wrong+ // vocabulary" test can be green while the parser is broken in both directions at once.+ expect(values, name).not.toBeNull()+ expect(values, name).toContain('never')+ for (const sandbox of ['read-only', 'workspace-write', 'danger-full-access'])+ expect(values, `${name} / ${sandbox}`).not.toContain(sandbox)+ }+ })+})++describe('codexApprovalValuesFrom — unknown is null, not empty', () => {+ // `null` and `[]` mean different things one layer up: null falls back to the baseline vocabulary+ // (today's command line), an empty list would forbid every value including the two that have+ // worked on every release. A probe that cannot read the page must say so.+ it.each([+ ['no output', null],+ ['undefined', undefined],+ ['empty string', ''],+ ['a help page without the option', 'Usage: codex [OPTIONS]\n -m, --model <MODEL>\n'],+ ['the option with no values at all', ' -a, --ask-for-approval <POLICY>\n Configure it\n -h, --help\n']+ ])('answers null for %s', (_label, input) => {+ expect(codexApprovalValuesFrom(input as string | null | undefined)).toBeNull()+ })++ it('drops tokens that are not plain flag values, and answers null if none survive', () => {+ // The help page is untrusted input at an interpolation site: these strings are appended to a+ // command typed into a tmux pane.+ const forged = [+ ' -a, --ask-for-approval <APPROVAL_POLICY>',+ ' Configure when the model requires human approval [possible values: $(id), `id`, a b, ok-1]',+ ' -h, --help'+ ].join('\n')+ expect(codexApprovalValuesFrom(forged)).toEqual(['ok-1'])++ const allForged = [+ ' -a, --ask-for-approval <APPROVAL_POLICY>',+ ' Configure it [possible values: ; rm -rf ~]',+ ' -h, --help'+ ].join('\n')+ expect(codexApprovalValuesFrom(allForged)).toBeNull()+ })+})++/**+ * The two facts that are NOT read off a probe, pinned at source level because the failure mode of+ * each is silence.+ */+describe('the codex vocabulary reaches every surface it has to', () => {+ const read = (rel: string): string =>+ readFileSync(path.join(__dirname, '..', ...rel.split('/')), 'utf8')++ /**+ * CLAUDE.md invariant: a probe registered in one shell and forgotten in the other gives the+ * Server Edition the feature's silence, and the boundary tests cannot tell you a handler is+ * MISSING. `registerGrokCliIpc`'s own comment in the server shell states this rule; this asserts+ * it for all three CLI probes rather than leaving it as a comment.+ */+ it('registers every CLI capability probe in BOTH shells', () => {+ const main = read('main/index.ts')+ const server = read('server/handlers/index.ts')+ for (const fn of ['registerClaudeCliIpc', 'registerGrokCliIpc', 'registerCodexCliIpc']) {+ expect(main, `main: ${fn}`).toContain(`${fn}()`)+ expect(server, `server: ${fn}`).toContain(`${fn}()`)+ }+ })++ /**+ * The app-server usage tier (issue #785's second half). It spawns `codex` directly, so the argv+ * is exported to be assertable rather than buried in the spawn — it was `-a untrusted` and on+ * every codex >= 0.149.0 clap refused the whole invocation, which made this tier return null+ * forever with nothing on screen to say why.+ *+ * MEASURED: `-s read-only -a never app-server` gets past clap on 0.148.0, 0.151.0 and 0.154.0+ * (all three then fail only on this container's missing sandbox helper, which is an environment+ * fact, not a flag one), while `-a untrusted` exits at the parser on 0.151.0 and 0.154.0.+ */+ it('asks the app-server for an approval policy both vocabularies contain', () => {+ const value = CODEX_APP_SERVER_ARGS[CODEX_APP_SERVER_ARGS.indexOf('-a') + 1]+ for (const vocabulary of [+ ['untrusted', 'on-request', 'never'], // codex <= 0.148.0+ ['on-request', 'never'] // codex >= 0.149.0+ ]) {+ expect(vocabulary, value).toContain(value)+ }+ // The sandbox is the guard that keeps a quota refresh away from the user's files, and it is a+ // separate axis from the approval policy — it must not be traded away for one.+ expect(CODEX_APP_SERVER_ARGS).toContain('read-only')+ })+})diff --git a/src/core/codex-cli.ts b/src/core/codex-cli.tsnew file mode 100644index 000000000..18c5f9513--- /dev/null+++ b/src/core/codex-cli.ts@@ -0,0 +1,180 @@+/**+ * Capability probe for the LOCAL Codex CLI — the codex analogue of `core/claude-cli.ts`, and+ * deliberately a SECOND probe rather than a reuse of claude's.+ *+ * CLAUDE.md states the rule this file exists to obey: a capability gate fed by a version probe+ * belongs to the agent it probes. Claude's `auto` gate is fed by `claude --version`; applying it to+ * 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.+ *+ * 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+ * advertise `on-request, never`. A version floor would work today and would be wrong the next time+ * OpenAI moves the set, and it cannot answer for a build that is not on npm at all. Reading the+ * CLI's own `--help` asks the binary in front of us what it actually takes — the same choice+ * `codexCliSupportsRemote` and claude's `--session-id` detection already made.+ *+ * Lives in core (not main) so the Server Edition boots it through the same CorePlatform seam: the+ * server's own machine is the one that runs its Codex sessions, so it needs the real answer, not a+ * stub. The remote (SSH) host's codex is a different binary and is NOT covered here — a remote+ * launch falls back to the baseline vocabulary, see `ApprovalCaps` in shared/agents/approval-mode.+ */+import { execFile } from 'child_process'+import { promisify } from 'util'+import { IPC } from '../shared/ipc'+import { UNKNOWN_CODEX_CLI_CAPS, type CodexCliCaps } from '../shared/types'+import { findInLoginPath } from './pty-manager'+import { directExecutableInvocation } from './exec-path'+import { platform } from './platform'++const execFileP = promisify(execFile)+const PROBE_TIMEOUT_MS = 5000++/**+ * Only the option we are reading, never the one next to it.+ *+ * `--help` lists `-s, --sandbox <SANDBOX_MODE>` with its own `[possible values: read-only,+ * workspace-write, danger-full-access]` two lines above `--ask-for-approval`, so a parser that+ * scanned the page for "possible values" would confidently return the SANDBOX vocabulary and then+ * emit `--ask-for-approval read-only`. The slice below is anchored on the option's own header line+ * and ends at the next one.+ */+const ASK_FOR_APPROVAL = /--ask-for-approval\b/+/** An option header: indented at most 6 and starting with a dash. Value/description lines inside an+ * option are indented 10, so this cannot cut a block short. */+const OPTION_HEADER = /^ {0,6}-{1,2}[A-Za-z]/++/**+ * Pure: `codex --help` output → the `--ask-for-approval` values it advertises, or `null` when the+ * page did not say (absent output, an option we could not find, a shape we do not recognise).+ *+ * `null` is a first-class answer and NOT an empty list: "the CLI accepts nothing" and "we could not+ * read the page" lead to different decisions one layer up, where `null` resolves to the baseline+ * vocabulary and an empty list would forbid every value including the two that have always worked.+ *+ * BOTH of clap's renderings are handled, because both are real. Long `--help` prints a block:+ *+ * -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+ *+ * short `-h` prints it inline and wraps it mid-phrase:+ *+ * -a, --ask-for-approval <APPROVAL_POLICY>+ * Configure when the model requires human approval ... [possible+ * values: on-request, never]+ *+ * — which is why the inline branch joins the slice before matching rather than working line by+ * line. The probe below asks for the long form; the short form is handled so a caller that has+ * `-h` output lying around gets the same answer instead of a silent `null`.+ *+ * Every token is validated against `[a-z][a-z0-9-]*`. These strings are appended to a launch+ * command that is typed into a tmux pane, so the help page is untrusted input at an interpolation+ * site like any other — a token we would not recognise is dropped rather than quoted and hoped+ * for, and if nothing survives the answer is `null`.+ */+export function codexApprovalValuesFrom(helpOutput: string | null | undefined): string[] | null {+ if (!helpOutput) return null+ const lines = helpOutput.split(/\r?\n/)+ const start = lines.findIndex((l) => ASK_FOR_APPROVAL.test(l))+ if (start < 0) return null+ let end = start + 1+ while (end < lines.length && !OPTION_HEADER.test(lines[end])) end+++ const slice = lines.slice(start, end)++ const values: string[] = []+ const inline = slice.join(' ').match(/\[possible\s+values:\s*([^\]]*)\]/i)+ if (inline) {+ values.push(...inline[1].split(','))+ } else {+ // The block form. Anchored on the `Possible values:` marker so a bullet inside the option's+ // prose description can never be mistaken for a value.+ const marker = slice.findIndex((l) => /^\s*possible\s+values:\s*$/i.test(l))+ if (marker < 0) return null+ for (const line of slice.slice(marker + 1)) {+ const m = line.match(/^\s*-\s+([^\s:]+)\s*:/)+ if (m) values.push(m[1])+ }+ }+ const clean = values.map((v) => v.trim()).filter((v) => /^[a-z][a-z0-9-]*$/.test(v))+ return clean.length ? Array.from(new Set(clean)) : null+}++let helpCached: Promise<string | null> | null = null++/**+ * `codex --help`, memoized for the process lifetime. Exported because two capability answers are+ * read off the same page — this file's approval vocabulary and `codex-identity-caps`'s `--remote`+ * detection — and paying for the page twice per boot to answer two questions about one binary is+ * the kind of duplication that turns into two different answers.+ *+ * Never rejects: a missing CLI, a timeout or a non-zero exit all resolve to `null`, which every+ * reader treats as "we do not know".+ *+ * `codex-identity-caps.ts` spawns the same page for its own `--remote` detection and deliberately+ * keeps doing so: its probe is handed an already-resolved `bin` (and falls through to `resume+ * --help`, which this file has no use for), and it only runs on an install that has the standalone+ * runtime. The two read DIFFERENT facts off the page with different parsers, so there is no shared+ * rule here to drift — only, on that one install shape, one extra boot-time spawn.+ */+export function codexHelpText(): Promise<string | null> {+ if (!helpCached) {+ helpCached = (async () => {+ try {+ // GUI apps don't inherit the shell PATH — resolve through the login shell like every other+ // CLI lookup in the app (pty-manager, claude-cli, commit-message).+ const bin = await findInLoginPath('codex')+ if (!bin) return null+ // Through the same wrapper the `--remote` probe uses (`codex-identity-caps.ts`): on+ // Windows the resolved `codex` is routinely a `.cmd` shim, which `execFile` cannot spawn+ // directly, and a probe that silently fails there would report "unknown vocabulary" on+ // every Windows machine.+ const invocation = directExecutableInvocation(bin, ['--help'])+ if (!invocation) return null+ const { stdout } = await execFileP(invocation.executable, invocation.args, {+ ...invocation.options,+ timeout: PROBE_TIMEOUT_MS+ })+ return stdout+ } catch {+ return null+ }+ })()+ }+ return helpCached+}++let cached: Promise<CodexCliCaps> | null = null++/**+ * The local Codex CLI's capabilities. Memoized for the process lifetime: the answer only changes+ * when the user upgrades the CLI, which a relaunch picks up. Never rejects — unknown resolves to+ * `UNKNOWN_CODEX_CLI_CAPS`, i.e. the baseline vocabulary, i.e. the command line nodeterm has always+ * sent for the modes that never depended on this.+ */+export function codexCliCaps(): Promise<CodexCliCaps> {+ if (!cached) {+ cached = codexHelpText()+ .then((help) => ({ approvalValues: codexApprovalValuesFrom(help) }))+ .catch(() => UNKNOWN_CODEX_CLI_CAPS)+ }+ return cached+}++/** Wire the probe onto the platform's RPC surface (Electron ipcMain / server WS-RPC alike). */+export function registerCodexCliIpc(): void {+ platform().handle(IPC.codexCliCaps, () => codexCliCaps())+}++export function resetCodexCliCapsForTests(): void {+ cached = null+ helpCached = null+}diff --git a/src/core/usage/codex-usage.ts b/src/core/usage/codex-usage.tsindex 20bb7e4b4..b1e3a9fac 100644--- a/src/core/usage/codex-usage.ts+++ b/src/core/usage/codex-usage.ts@@ -148,20 +148,29 @@ async function fetchViaBackend(home: string): Promise<ProviderUsage | null> {/*** Tier 2: `codex app-server` speaks JSON-RPC over stdio. Costs a subprocess, so it runs only- * when the backend tier declined. Sandboxed read-only/untrusted — this must never be a way for- * a quota refresh to touch the user's files.+ * when the backend tier declined. Sandboxed read-only — this must never be a way for a quota+ * refresh to touch the user's files.+ *+ * The approval policy is `never`, and it used to be `untrusted`. That value was removed from+ * codex's vocabulary in 0.149.0 and clap refuses the whole invocation rather than ignoring it:+ *+ * error: invalid value 'untrusted' for '--ask-for-approval <APPROVAL_POLICY>'+ *+ * so on every current CLI this tier exited 2 before it spoke a word of JSON-RPC and silently+ * returned null forever (issue #785). Unlike the launch path there is nothing to probe for here:+ * `never` is accepted by EVERY codex we have measured, 0.146.0 through 0.154.0 (checked by running+ * `-s read-only -a never app-server` against each binary), so one value serves both vocabularies.+ * It is also the right value on its own terms — this is a non-interactive read with no user to+ * prompt, and `-s read-only` is what actually keeps it away from the user's files; an approval+ * policy that escalates would only have hung it.*/+export const CODEX_APP_SERVER_ARGS = ['-s', 'read-only', '-a', 'never', 'app-server'] as const+export async function fetchCodexUsageViaAppServerAt(bin: string,home: string): Promise<ProviderUsage | null> {- const invocation = directExecutableInvocation(bin, [- '-s',- 'read-only',- '-a',- 'untrusted',- 'app-server'- ])+ const invocation = directExecutableInvocation(bin, [...CODEX_APP_SERVER_ARGS])if (!invocation) return nullreturn new Promise<ProviderUsage | null>((resolve) => {let child: ReturnType<typeof spawn>diff --git a/src/main/index.ts b/src/main/index.tsindex 5d8a5bc1f..6e451993a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -255,8 +255,10 @@ import { registerSpeechIpc } from '../core/speech/register-ipc'import { initClaudeAccounts } from './claude-accounts'import { initCodexAccounts } from './codex-accounts'import { claudeCliCaps, registerClaudeCliIpc, type ClaudeCliCaps } from '../core/claude-cli'+import type { CodexCliCaps } from '../shared/types'import { registerGrokCliIpc } from '../core/grok-cli'import { refreshCodexIdentityCaps, registerCodexIdentityIpc } from '../core/codex-identity-caps'+import { codexCliCaps, registerCodexCliIpc } from '../core/codex-cli'import {bindCodexThreadIdentity,setCodexThreadIdentityAuthSecret,@@ -1385,6 +1387,9 @@ app.whenReady().then(async () => {// the desktop and not in the browser, with nothing to say which.registerGrokCliIpc()registerCodexIdentityIpc()+ // What THIS machine's codex accepts for `--ask-for-approval`. Lazy + memoized inside the probe,+ // so registering it costs nothing until the first Codex launch line asks.+ registerCodexCliIpc()// Warm the `claude --version` probe now (it spawns a login shell + node, ~sub-second) so the// renderer's first `claude.cliCaps()` — awaited on the launch path of a cold-restored agent// node — resolves from cache instead of racing the probe into a conservative "no auto".@@ -2066,11 +2071,25 @@ app.whenReady().then(async () => {void flushAgentStatusMirror()}).catch(() => {})+ // codex's own probe, on the same re-flush plumbing and for the reason CLAUDE.md gives: a gate fed+ // by a version probe belongs to the agent it probes. This one publishes the host's+ // `--ask-for-approval` vocabulary so a phone-launched Codex node cannot send a value this CLI+ // removed (issue #785).+ let localCodexCaps: CodexCliCaps | undefined+ void codexCliCaps()+ .then((c) => {+ localCodexCaps = c+ void flushAgentStatusMirror()+ })+ .catch(() => {})setMirrorSettingsProvider((): MirrorSettings => {const s = settingsStore.get()return {claudePermissionMode: s.claudePermissionMode,autoSupported: localClaudeCaps?.autoPermissionMode === true,+ ...(localCodexCaps?.approvalValues+ ? { codexApprovalValues: localCodexCaps.approvalValues }+ : {}), // unprobed ⇒ absent ⇒ the reader uses the baseline vocabularyclaudeAccounts: (s.claudeAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => ({ id: a.id, dir: claudeConfigDirFor(a.id) }))@@ -2270,6 +2289,11 @@ 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....(home && hostKey? {claudeAccounts: (s.claudeAccounts ?? [])diff --git a/src/preload/index.ts b/src/preload/index.tsindex a946f750f..ce50c6fd6 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -523,6 +523,7 @@ const api: NodeTerminalApi = {},codex: {identityCaps: () => ipcRenderer.invoke(IPC.codexIdentityCaps),+ cliCaps: () => ipcRenderer.invoke(IPC.codexCliCaps),onIdentity: (listener) => {const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)ipcRenderer.on(IPC.codexIdentity, handler)diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex 4bc82c59b..8866d249f 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom/client'import App from './App'import { ensureClaudeCliCaps, ensureGrokCliCaps } from './state/permissionMode'import { ensureCodexIdentityCaps } from './state/codexIdentity'+import { ensureCodexCliCaps } from './state/codexCli'import { initAgentResolver } from './state/agent-resolver'import { refreshAgentEnv } from './lib/agentEnv'import { applyWindowChrome } from './lib/windowChrome'@@ -32,6 +33,11 @@ void ensureGrokCliCaps()// this machine has one installed and armed. Unprobed ⇒ plain `codex`, which is what every Codex// node ran before this feature — never a launcher path that might not resolve.void ensureCodexIdentityCaps()+// What this machine's codex accepts for `--ask-for-approval`. Warmed here for the same reason as+// the probes above it: every Codex launch line reads it synchronously, so the answer must be in+// hand before the user can create a node. Unprobed degrades to the baseline vocabulary, never to a+// blocked launch.+void ensureCodexCliCaps()// One env snapshot for `${env:VAR}` expansion, fetched up front and cached (src/renderer/lib/// agentEnv.ts): the Settings preview and every launch path expand against the same object, so thediff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 30ba698dd..cc48eb0aa 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -18,6 +18,7 @@ import {UNKNOWN_CLAUDE_CLI_CAPS,UNKNOWN_GROK_CLI_CAPS,UNKNOWN_CODEX_IDENTITY_CAPS,+ UNKNOWN_CODEX_CLI_CAPS,type ClaudeUsage,type NodeTerminalApi,type NotifyPayload,@@ -298,6 +299,13 @@ export function buildStubApi(): Omit<// one the Server Edition gives on purpose (see server/handlers/index.ts): no shared// identity, so every Codex launch line stays the bare `codex`.identityCaps: () => Promise.resolve(UNKNOWN_CODEX_IDENTITY_CAPS),+ // A RELAY tab keeps this stub: its sessions run on the GUEST's machine, whose codex is a+ // different binary from the one this probe could reach, and applying our vocabulary to their+ // launch line is precisely the cross-machine guess this gate exists to stop. Unknown ⇒ the+ // baseline vocabulary ⇒ the two values every measured codex accepts; "Ask each time" is+ // reported as unsupported there rather than gambling `untrusted` on someone else's CLI.+ // Overridden by the real WS-backed namespace in ws-bridge for the Server Edition.+ cliCaps: () => Promise.resolve(UNKNOWN_CODEX_CLI_CAPS),onIdentity: noopUnsub},claude: {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 5501c1dc6..bc8a799ea 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -32,6 +32,8 @@ import {type CodexApi,type CodexIdentityCaps,UNKNOWN_CODEX_IDENTITY_CAPS,+ type CodexCliCaps,+ UNKNOWN_CODEX_CLI_CAPS,type ContextApi,type DownloadTicket,type FilesApi,@@ -869,6 +871,14 @@ export function buildCodexApi(client: RpcClient): CodexApi {(client.request(IPC.codexIdentityCaps) as Promise<CodexIdentityCaps>).catch(() => UNKNOWN_CODEX_IDENTITY_CAPS),+ // A REAL handler server-side, unlike `identityCaps` right above it — `registerCodexCliIpc`+ // runs in that shell for the reason spelled out there: the Server Edition's Codex sessions run+ // on the server's own `codex`, so the browser needs that binary's real approval vocabulary.+ // Rejection degrades to the unknown caps, i.e. the baseline vocabulary.+ cliCaps: () =>+ (client.request(IPC.codexCliCaps) as Promise<CodexCliCaps>).catch(+ () => UNKNOWN_CODEX_CLI_CAPS+ ),onIdentity: (listener) => client.subscribe(IPC.codexIdentity, listener as Listener)}}diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsxindex e11f38e6e..0fe629956 100644--- a/src/renderer/components/TabBar.tsx+++ b/src/renderer/components/TabBar.tsx@@ -20,6 +20,7 @@ import {type AgentPermissionMode} from '@shared/agents/config'import { bypassSandboxCaveat, permissionModeAgentsLabel } from '@shared/agents/approval-mode'+import { codexApprovalCaps } from '@renderer/state/codexCli'interface TabBarProps {onSwitch: (id: string) => void@@ -580,7 +581,7 @@ export function TabBar({// for codex the mode skips APPROVALS only: `--ask-for-approval never` does// not touch `--sandbox`, which we deliberately leave alone, so "no// permission checks" must not be read as "no sandbox either".- `Skips every permission prompt. This override is saved in the project file (.nodeterm/project.json), so if you commit it, everyone who clones the repo runs their ${permissionModeAgentsLabel({ mode: 'bypassPermissions' })} sessions without permission checks too. ${bypassSandboxCaveat()}`.trim()+ `Skips every permission prompt. This override is saved in the project file (.nodeterm/project.json), so if you commit it, everyone who clones the repo runs their ${permissionModeAgentsLabel({ mode: 'bypassPermissions', caps: codexApprovalCaps() })} sessions without permission checks too. ${bypassSandboxCaveat(codexApprovalCaps())}`.trim(): m === 'auto'? (menuAutoHint ?? undefined): undefineddiff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex edb182450..f36e20f8d 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -39,6 +39,7 @@ import {permissionModeAgentsLabel,unsupportedModesNote} from '@shared/agents/approval-mode'+import { codexApprovalCaps } from '@renderer/state/codexCli'import { AgentIcon } from '../../../lib/agentIcons'import { chipFor } from '../../../lib/keybindingOverrides'import { NODE_IDENTITY_STRICT_DATE } from '@shared/node-identity'@@ -246,9 +247,15 @@ const ENTRIES = [* space) the day every capable agent expresses every mode.*/function permissionModeDescription(): string {+ // The gaps are not a constant: codex's `--ask-for-approval` vocabulary changes between releases+ // (it lost `untrusted`, and with it "Ask each time", in 0.149.0), so the sentence is derived+ // against the codex ON THIS MACHINE rather than a table pinned to one release. Read at render;+ // the probe is warmed at boot, so by the time Settings can be opened this is the real answer,+ // and an unprobed read degrades to the baseline vocabulary like every other consumer.+ const caps = codexApprovalCaps()return [`The mode ${permissionModeAgentsLabel()} terminal sessions start in; other agents ignore it.`,- unsupportedModesNote(),+ unsupportedModesNote(caps),'Shift+Tab still switches modes at any time. Projects can override this from the tab ⌄ menu.'].filter(Boolean)diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex ffb0ff4cc..d7c01531f 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -172,6 +172,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 { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'import { useLaunchDelivery } from '../state/launchDelivery'import { erroredDeps, launchTooltip } from '../lib/pendingLaunch'@@ -3606,6 +3607,10 @@ export function TerminalNode({permissionMode: mode,model: data.agentModel,sharedIdentity: shared,+ // 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),// 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@@ -3670,6 +3675,7 @@ export function TerminalNode({permissionMode: mode,model: data.agentModel,sharedIdentity: shared,+ approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),launchCmdOverride: agentLaunchOverride(agentId, ownerProjectId)},agentEnvSnapshot()@@ -3903,6 +3909,7 @@ export function TerminalNode({customAgent: customTarget,sessionId: agentSessionId,permissionMode: await ensureActivePermissionMode(target),+ approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),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@@ -4054,6 +4061,7 @@ export function TerminalNode({customAgent,sessionId: agentSessionId,permissionMode: await ensureActivePermissionMode(agentId),+ approvalCaps: codexApprovalCaps(data.ssh || data.sshRemoteTmux),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/state/codexCli.ts b/src/renderer/state/codexCli.tsnew file mode 100644index 000000000..d19d9352f--- /dev/null+++ b/src/renderer/state/codexCli.ts@@ -0,0 +1,68 @@+/**+ * The renderer's half of the Codex approval-vocabulary gate.+ *+ * Same shape as `codexIdentity.ts` and as claude's `--permission-mode auto` gate: a memoized probe+ * whose unknown answer is the conservative one, read at the moment a launch command is built and+ * never rendered from — so it is a module memo, not a store.+ *+ * WHAT THE CONSERVATIVE ANSWER IS HERE, because it is not "emit nothing". An unprobed launch falls+ * back to the BASELINE vocabulary (`on-request`, `never` — every codex from 0.146.0 to 0.154.0+ * takes both), so Auto and Bypass keep the exact command line they have always had. The one value+ * that moved is `untrusted`, removed in 0.149.0, and that one is emitted only when a probe has+ * actually SEEN this binary advertise it. Unknown therefore costs at most "Ask each time"+ * degrading to Codex's own default — never a launch that dies on a value clap does not know.+ */+import {+ UNKNOWN_CODEX_CLI_CAPS,+ type CodexCliCaps+} from '@shared/types'+import type { ApprovalCaps } from '@shared/agents/approval-mode'++const CAPS_WAIT_MS = 3000++let caps: CodexCliCaps = UNKNOWN_CODEX_CLI_CAPS+let capsPromise: Promise<CodexCliCaps> | null = null++/** Probe once per app run. Never rejects; a slow bridge resolves to what we have so far. The+ * timeout is what makes "a launch is never blocked on the probe" true by construction — in the+ * Server Edition this call goes over WS-RPC, which does not reject pending requests when the+ * socket drops. */+export function ensureCodexCliCaps(): Promise<CodexCliCaps> {+ if (!capsPromise) {+ const probe = Promise.resolve()+ .then(() => window.nodeTerminal.codex.cliCaps())+ .then((c) => (caps = c ?? UNKNOWN_CODEX_CLI_CAPS))+ .catch(() => UNKNOWN_CODEX_CLI_CAPS)+ const timeout = new Promise<CodexCliCaps>((resolve) =>+ setTimeout(() => resolve(caps), CAPS_WAIT_MS)+ )+ capsPromise = Promise.race([probe, timeout])+ }+ return capsPromise+}++export function codexCliCapsNow(): CodexCliCaps {+ return caps+}++/**+ * 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`.+ *+ * 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.+ */+export function codexApprovalCaps(remote?: unknown): ApprovalCaps {+ return { codexApprovalValues: remote ? null : caps.approvalValues }+}++/** 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+}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 8b6bab265..414845aff 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -28,6 +28,7 @@ import { mintFreeGrokSessionId } from '@shared/agents/grok-session-mint'import { projectLaunchInfoNow } from './projectLaunchInfo'import { isAgentEnabled, launchableDefaultAgent } from './agentAvailability'import { codexSharedIdentity } from './codexIdentity'+import { codexApprovalCaps } from './codexCli'import { folderTitle } from '../lib/explorerCreate'import { sshHostKey } from '@shared/ssh'import { normalizeNodeIcon } from '@shared/node-icon'@@ -708,6 +709,10 @@ export function createAgentNode(// machine actually has one — otherwise the bare CLI, byte-identical to before. `codexSharedIdentity`// folds in the SSH answer (a host has no launcher installed yet, so a remote node stays bare).sharedIdentity: codexSharedIdentity(ssh),+ // 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),// 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/server/canvas-control.ts b/src/server/canvas-control.tsindex 82735cfa3..efe539a72 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -25,7 +25,8 @@ import { codexIdentityCaps } from '../core/codex-identity-caps'import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'import { grokCliCaps } from '../core/grok-cli'-import type { GrokCliCaps } from '../shared/types'+import { codexCliCaps } from '../core/codex-cli'+import type { CodexCliCaps, GrokCliCaps } from '../shared/types'import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'import { platform } from '../core/platform'import type { PtyManager } from '../core/pty-manager'@@ -49,6 +50,7 @@ export interface ServerCanvasControlDeps {cliCaps?: () => Promise<ClaudeCliCaps>/** grok's own `--session-id` probe; defaults to the real one. See HeadlessNodeFactoryDeps. */grokCaps?: () => Promise<GrokCliCaps>+ codexCaps?: () => Promise<CodexCliCaps>/** Test seam for the boot-populated shared Codex capability answer. */codexSharedIdentity?: () => Promise<boolean>/**@@ -172,6 +174,10 @@ export async function initServerCanvasControl(cliCaps: deps.cliCaps ?? claudeCliCaps,// grok answers with its own probe — see HeadlessNodeFactoryDeps.grokCaps.grokCaps: deps.grokCaps ?? grokCliCaps,+ // …and so does codex, for the same reason: its `--ask-for-approval` vocabulary is its own and+ // it MOVED (see HeadlessNodeFactoryDeps.codexCaps). The Server Edition runs its Codex sessions+ // on this host's `codex`, so this probe is the right authority for them.+ codexCaps: deps.codexCaps ?? codexCliCaps,codexSharedIdentity:deps.codexSharedIdentity ?? (() => codexIdentityCaps().then((caps) => caps.shared)),stateOf: nodeState,diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex c87ac2584..9235be14c 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -9,6 +9,7 @@ import { registerFsHandlers } from '../../core/fs-handlers'import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'import { registerGrokCliIpc } from '../../core/grok-cli'import { registerCodexIdentityIpc } from '../../core/codex-identity-caps'+import { registerCodexCliIpc } from '../../core/codex-cli'import { startUsageService } from '../../core/usage/usage-service'import { registerClaudeAccountsIpc } from '../../core/claude-accounts-service'import { codexUsageAccounts } from '../../core/codex-accounts-core'@@ -74,6 +75,14 @@ export function registerCoreHandlers(// Invariant 11 for probes: registered in BOTH shells, or session-id minting silently works on// the desktop and not in the browser, with nothing to say which.registerGrokCliIpc()+ // The codex CLI's own approval vocabulary, and this one is registered FOR REAL rather than+ // stubbed. `registerCodexIdentityIpc` below declines a shared app-server on purpose; this is the+ // opposite case, and the distinction matters — the Server Edition's Codex sessions run on THIS+ // machine, on THIS `codex`, so the browser must be told what that binary accepts. A constant+ // here would silently drop "Ask each time" for a Server Edition user on codex <= 0.148.0 and+ // hand a later codex a value it removed: exactly the "a stub compiles fine while doing nothing"+ // failure the three-surfaces rule warns about.+ registerCodexCliIpc()void claudeCliCaps()// The answer is populated after server node identity is armed. Early browser callers wait fordiff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex 09e33e622..55768d6bf 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -95,6 +95,7 @@ describe('HeadlessNodeFactory', () => {let factory: HeadlessNodeFactorylet ownership: HeadlessNodeOwnershiplet codexSharedIdentity: boolean+ let codexApprovalValues: { approvalValues: string[] | null }const settings = (): Settings => ({...DEFAULT_SETTINGS,@@ -115,6 +116,7 @@ describe('HeadlessNodeFactory', () => {removed = []publishedProjects = []codexSharedIdentity = false+ codexApprovalValues = { approvalValues: ['on-request', 'never'] }ownership = createHeadlessNodeOwnership()ownership.record('term-upstream', {sourceNodeId: 'term-source',@@ -159,6 +161,10 @@ describe('HeadlessNodeFactory', () => {// `models: []` is grok's own "no catalogue" answer (a failed/absent `grok models`), which is// the pre-feature behaviour: no model switching offered, never a partial list.grokCaps: async () => ({ sessionIdFlag: false, models: [] }),+ // Likewise stated. The default is the CURRENT codex vocabulary (0.149.0 dropped `untrusted`),+ // so the assembled lines below are the ones a Server Edition on a current CLI really sends;+ // the old vocabulary gets its own case rather than being the silent default.+ codexCaps: async () => codexApprovalValues,codexSharedIdentity: async () => codexSharedIdentity,ownership,stateOf: (id) => states[id],@@ -892,7 +898,10 @@ describe('HeadlessNodeFactory', () => {it.each([['claude', "claude 'do work'"],- ['codex', "codex 'do work' --ask-for-approval untrusted"],+ // Manual is the resolved mode in this fixture, and on a current codex it has NO expressible+ // value — `untrusted` was removed in 0.149.0 and clap exits on it (issue #785). The honest+ // line is the bare one; the case below pins the old CLI, which still gets the flag.+ ['codex', "codex 'do work'"],['gemini', "gemini 'do work'"]] as const)('assembles the %s launch through the shared command builder', async (agent, command) => {const reply = await factory.openAgent(@@ -982,7 +991,26 @@ describe('HeadlessNodeFactory', () => {const id = (reply.result as { id: string }).idexpect(pty.sends.at(-1)).toEqual({nodeId: id,- text: "nodeterm-codex 'do work' --ask-for-approval untrusted"+ text: "nodeterm-codex 'do work'"+ })+ })++ /**+ * The Server Edition's Codex sessions run on THIS host's `codex`, so the host's own probe is the+ * authority for them — not a constant, and not the desktop's. A host still on <= 0.148.0 keeps+ * "Ask each time" working; the case above shows the same factory dropping it on a host that+ * cannot express it. Both come out of one probe, which is the whole point of #785's fix.+ */+ it('keeps `untrusted` for a host whose codex still advertises it', async () => {+ codexApprovalValues = { approvalValues: ['untrusted', 'on-request', 'never'] }++ const reply = await factory.openAgent('term-source', { agent: 'codex', prompt: 'do work' }, true)++ expect(reply.ok).toBe(true)+ const id = (reply.result as { id: string }).id+ expect(pty.sends.at(-1)).toEqual({+ nodeId: id,+ text: "codex 'do work' --ask-for-approval untrusted"})})diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex 4b936922b..8bfb8454c 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -26,10 +26,12 @@ import {import { assembleLaunchCommand } from '../shared/agents/launch'import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'import { oneLine } from '../shared/one-line'+import { UNKNOWN_CODEX_CLI_CAPS } from '../shared/types'import type {BridgeLink,CanvasNodeState,ClaudeCliCaps,+ CodexCliCaps,GrokCliCaps,Project,PtyCreateOptions,@@ -75,6 +77,14 @@ export interface HeadlessNodeFactoryDeps {* be that forgotten probe, waiting for the day grok joins the set.*/grokCaps(): Promise<GrokCliCaps>+ /**+ * codex's OWN `--help` probe, and separate from `cliCaps`/`grokCaps` for the same reason they are+ * separate from each other. It answers which values this host's `codex` accepts for+ * `--ask-for-approval`: the set changed between releases (`untrusted` was removed in 0.149.0) and+ * clap EXITS on a value it does not know, so a launch line built from a table rather than from+ * the binary is a dead session, not a degraded one — issue #785.+ */+ codexCaps(): Promise<CodexCliCaps>/** Whether this host's Codex launcher + shared app-server identity spine are ready. */codexSharedIdentity(): Promise<boolean>/** Hook-mirror lookups. A stored agentId wins; these cover a plain terminal running an agent. */@@ -1100,6 +1110,14 @@ export class HeadlessNodeFactory {verb === 'open-agent' && agentId === 'codex'? await this.deps.codexSharedIdentity().catch(() => false): false+ // Which `--ask-for-approval` values this host's codex has. Asked only where it can matter,+ // right beside the other codex question. Every failure answers `null` = unknown = the+ // baseline vocabulary, which is the launch line this factory has always produced for Auto+ // and Bypass; only `untrusted` (gone since 0.149.0) depends on a real answer.+ const codexCaps =+ verb === 'open-agent' && agentId === 'codex'+ ? await this.deps.codexCaps().catch(() => UNKNOWN_CODEX_CLI_CAPS)+ : UNKNOWN_CODEX_CLI_CAPSconst count = parseCount(args.count, verb === 'open-terminal' ? TERMINAL_LIMIT : AGENT_LIMIT)const created: CanvasNodeState[] = []@@ -1151,6 +1169,7 @@ export class HeadlessNodeFactory {sessionIdFlagSupported,launchCmdOverride: settings.agentLaunchCommands?.[agentId as BuiltinAgentId],sharedIdentity: codexSharedIdentity,+ approvalCaps: { codexApprovalValues: codexCaps.approvalValues },model: args.model},this.deps.env ?? process.envdiff --git a/src/server/index.ts b/src/server/index.tsindex f7358e583..15ead1c4b 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -86,6 +86,8 @@ import { startSessionMemoryService, sshScopePredicate } from '../core/session-meimport { createMemoryPressureMonitor } from '../core/memory-pressure'import { createPtyPressureMonitor } from '../core/pty-pressure'import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'+import { codexCliCaps } from '../core/codex-cli'+import type { CodexCliCaps } from '../shared/types'import { claudeConfigDirFor, registerClaudeAccountsSource } from '../core/claude-config-dir'import { presenceHub } from '../core/presence/hub'import { initCanvasSync } from '../core/canvas-sync'@@ -434,11 +436,25 @@ export async function startServer(void flushAgentStatusMirror()}).catch(() => {})+ // Same, for codex — its `--ask-for-approval` vocabulary is its own and it changed between+ // releases (see MirrorSettings.codexApprovalValues). Registered in BOTH shells: a probe published+ // on the desktop and missing here would leave a phone paired to a Server Edition host building+ // Codex launch lines from a table instead of from the binary.+ let localCodexCaps: CodexCliCaps | undefined+ void codexCliCaps()+ .then((c) => {+ localCodexCaps = c+ void flushAgentStatusMirror()+ })+ .catch(() => {})setMirrorSettingsProvider((): MirrorSettings => {const s = settingsStore.get()return {claudePermissionMode: s.claudePermissionMode,autoSupported: localClaudeCaps?.autoPermissionMode === true,+ ...(localCodexCaps?.approvalValues+ ? { codexApprovalValues: localCodexCaps.approvalValues }+ : {}), // unprobed ⇒ absent ⇒ the reader uses the baseline vocabularyclaudeAccounts: (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.test.ts b/src/shared/agents/approval-mode.test.tsindex ff17a5021..2cdc29804 100644--- a/src/shared/agents/approval-mode.test.ts+++ b/src/shared/agents/approval-mode.test.ts@@ -14,11 +14,22 @@ import {type AgentPermissionMode} from './config'+/** What codex <= 0.148.0 advertises. Passing it is what a machine with that CLI does. */+const OLD_CODEX = { codexApprovalValues: ['untrusted', 'on-request', 'never'] }+/** What codex >= 0.149.0 advertises — and, value for value, the baseline an UNPROBED launch uses. */+const NEW_CODEX = { codexApprovalValues: ['on-request', 'never'] }+/*** Measured flag vocabularies:* claude / grok : --permission-mode auto|acceptEdits|plan|bypassPermissions (manual = no flag)* gemini 0.54.4 : --approval-mode default|auto_edit|yolo|plan (gemini --help)* codex 0.146.0 : --ask-for-approval untrusted|on-request|never (codex --help)+ * codex 0.149.0+: --ask-for-approval on-request|never (codex --help)+ *+ * codex's vocabulary MOVED — `untrusted` was removed in 0.149.0, measured release by release+ * against the published binaries (see core/codex-cli.test.ts). clap exits on a value it does not+ * know, so the table is gated on what the CLI in front of us advertises, and the two constants+ * below are the two vocabularies that gate has to serve.*/describe('approvalFlags — claude and grok are untouched', () => {it('emits the historical --permission-mode spelling', () => {@@ -85,20 +96,85 @@ describe('approvalFlags — codex REFUSES what it cannot express', () => {})/**- * codex is the only agent where `manual` emits a flag, and it MUST. Measured on 0.146.0:- * `codex doctor` reports `approval policy OnRequest` with no `approval` key in- * ~/.codex/config.toml, so codex's built-in default is "the model decides when to ask" — not "ask- * each time". Unflagged, `manual` and `auto` would be the SAME runtime policy: two dropdown- * entries collapsed onto one behaviour, under a label promising something else. `untrusted` is the- * documented equivalent ("only run trusted commands without asking; escalate anything else").+ * codex is the only agent where `manual` emits a flag, and on a CLI that still HAS the value it+ * must. Measured on 0.146.0 and re-measured on 0.151.0: `codex doctor` reports `approval policy+ * OnRequest` with no `approval` key in ~/.codex/config.toml, so codex's built-in default is "the+ * model decides when to ask" — not "ask each time". Unflagged, `manual` and `auto` are the SAME+ * runtime policy: two dropdown entries collapsed onto one behaviour, under a label promising+ * something else. `untrusted` is the documented equivalent ("only run trusted commands without+ * asking; escalate anything else").*/- it('emits `untrusted` for manual, because codex’s own default is not "ask each time"', () => {- expect(approvalFlags('codex', 'manual')).toEqual(['--ask-for-approval', 'untrusted'])+ it('emits `untrusted` for manual on a CLI that has it, and says so', () => {+ expect(approvalFlags('codex', 'manual', OLD_CODEX)).toEqual([+ '--ask-for-approval',+ 'untrusted'+ ])// ...and it is therefore a DIFFERENT policy from auto, which is the whole point.- expect(approvalFlags('codex', 'manual')).not.toEqual(approvalFlags('codex', 'auto'))- // codex has an equivalent, so the derived copy must NOT claim otherwise.- expect(modeSupported('codex', 'manual')).toBe(true)- expect(unsupportedModesNote()).not.toContain(PERMISSION_MODE_LABELS.manual)+ expect(approvalFlags('codex', 'manual', OLD_CODEX)).not.toEqual(+ approvalFlags('codex', 'auto', OLD_CODEX)+ )+ // That codex has an equivalent, so the derived copy must NOT claim otherwise.+ expect(modeSupported('codex', 'manual', OLD_CODEX)).toBe(true)+ expect(unsupportedModesNote(OLD_CODEX)).not.toContain(PERMISSION_MODE_LABELS.manual)+ })++ /**+ * ISSUE #785, and the regression this whole gate exists for. codex 0.149.0 removed `untrusted`;+ * clap does not ignore an unknown value, it prints+ *+ * error: invalid value 'untrusted' for '--ask-for-approval <APPROVAL_POLICY>'+ *+ * and exits — so a Manual-mode Codex node launched with the old table died at the prompt and left+ * the pane at a bare shell. Emitting NOTHING is the only honest answer left: there is no value in+ * 0.149.0's vocabulary that means "ask every time" (`-c approval_policy=untrusted` is refused+ * too, and `--approve-for-me` routes approvals through AUTOMATIC review), so the mode is reported+ * as unsupported rather than silently answered with `on-request`.+ */+ it('emits NOTHING for manual on codex >= 0.149.0, rather than a value clap rejects', () => {+ expect(approvalFlags('codex', 'manual', NEW_CODEX)).toEqual([])+ expect(modeSupported('codex', 'manual', NEW_CODEX)).toBe(false)+ // The other two modes are untouched by the removal — the command line they produce is the one+ // nodeterm has always sent.+ expect(approvalFlags('codex', 'auto', NEW_CODEX)).toEqual(['--ask-for-approval', 'on-request'])+ expect(approvalFlags('codex', 'bypassPermissions', NEW_CODEX)).toEqual([+ '--ask-for-approval',+ 'never'+ ])+ })++ /**+ * FAIL OPEN, in the direction that cannot kill a launch. An unprobed / unreadable / remote CLI+ * resolves to the baseline vocabulary, which is `on-request|never`: the two values every measured+ * codex accepts. So an unknown CLI keeps Auto and Bypass exactly as they were and loses only+ * Manual — never the reverse, and never a launch.+ */+ it('treats an unknown vocabulary as the baseline: no `untrusted`, but Auto and Bypass intact', () => {+ for (const caps of [{}, { codexApprovalValues: null }, { codexApprovalValues: [] }]) {+ expect(approvalFlags('codex', 'manual', caps)).toEqual([])+ expect(modeSupported('codex', 'manual', caps)).toBe(false)+ expect(approvalFlags('codex', 'auto', caps)).toEqual(['--ask-for-approval', 'on-request'])+ expect(approvalFlags('codex', 'bypassPermissions', caps)).toEqual([+ '--ask-for-approval',+ 'never'+ ])+ }+ // The zero-argument form is the one every caller that forgets to thread its probe result gets,+ // so it has to BE the safe answer rather than merely be documented as one.+ expect(approvalFlags('codex', 'manual')).toEqual([])+ expect(withPermissionMode('codex', 'codex', 'manual')).toBe('codex')+ })++ it('never emits a value the CLI in front of it did not advertise', () => {+ // The general rule, stated against the mechanism rather than against today's table: whatever+ // the vocabulary says, every value we emit is in it.+ for (const caps of [OLD_CODEX, NEW_CODEX, { codexApprovalValues: ['never'] }]) {+ for (const m of ALL_PERMISSION_MODES) {+ const flags = approvalFlags('codex', m, caps)+ if (!flags.length) continue+ expect(flags[0], m).toBe('--ask-for-approval')+ expect(caps.codexApprovalValues, m).toContain(flags[1])+ }+ }})it('leaves every other agent’s manual unflagged — their own default already prompts', () => {@@ -109,13 +185,15 @@ describe('approvalFlags — codex REFUSES what it cannot express', () => {}})- it('emits NO flag for a mode codex has no equivalent of', () => {+ it('emits NO flag for a mode codex has no equivalent of, on either vocabulary', () => {// Silently substituting a nearest match would tell the user "Plan" while codex ran in// on-request. No flag = codex's own default, which is the honest degrade.- expect(approvalFlags('codex', 'plan')).toEqual([])- expect(approvalFlags('codex', 'acceptEdits')).toEqual([])- expect(modeSupported('codex', 'plan')).toBe(false)- expect(modeSupported('codex', 'acceptEdits')).toBe(false)+ for (const caps of [OLD_CODEX, NEW_CODEX]) {+ expect(approvalFlags('codex', 'plan', caps)).toEqual([])+ expect(approvalFlags('codex', 'acceptEdits', caps)).toEqual([])+ expect(modeSupported('codex', 'plan', caps)).toBe(false)+ expect(modeSupported('codex', 'acceptEdits', caps)).toBe(false)+ }})it('does NOT touch the sandbox flag', () => {@@ -125,16 +203,7 @@ describe('approvalFlags — codex REFUSES what it cannot express', () => {expect(approvalFlags('codex', m).join(' ')).not.toContain('sandbox')})- it('only ever emits a value codex --help lists', () => {- // The vocabulary read off `codex --help` on 0.146.0. There is no `on-failure` and no plan mode.- const CHOICES = ['untrusted', 'on-request', 'never']- for (const m of ALL_PERMISSION_MODES) {- const flags = approvalFlags('codex', m)- if (!flags.length) continue- expect(flags[0], m).toBe('--ask-for-approval')- expect(CHOICES, m).toContain(flags[1])- }- })+})describe('approvalFlags — an agent with no permission mode', () => {@@ -179,8 +248,8 @@ describe('UI copy derived from the mapping', () => {})it('admits each gap once, with number agreement, and names no agent that has none', () => {- const note = unsupportedModesNote()- // codex: two gaps → plural verb.+ const note = unsupportedModesNote(OLD_CODEX)+ // codex on a CLI that still has `untrusted`: two gaps → plural verb.expect(note).toContain('Accept edits and Plan have no Codex equivalent')// gemini: one gap → singular verb. Both sentences in one string, one per agent.expect(note).toContain('Auto has no Gemini equivalent')@@ -197,9 +266,38 @@ describe('UI copy derived from the mapping', () => {// The sentence has to vanish by itself the day a CLI grows the missing mode — otherwise it// becomes a stale claim nobody thinks to delete. Proven by the shape: the note is a join over// agents WITH gaps, so an empty gap set is an empty string.- const gapCount = ALL_PERMISSION_MODES.filter((m) => !modeSupported('codex', m)).length- expect(gapCount).toBe(2)- expect(unsupportedModesNote().endsWith('own default.')).toBe(true)+ const gaps = (caps: object): number =>+ ALL_PERMISSION_MODES.filter((m) => !modeSupported('codex', m, caps)).length+ expect(gaps(OLD_CODEX)).toBe(2)+ expect(unsupportedModesNote(OLD_CODEX).endsWith('own default.')).toBe(true)+ })++ /**+ * THE copy half of #785. The removal of `untrusted` has to reach the SENTENCE, not only the+ * command line — "Ask each time" silently becoming codex's own on-request policy is the exact+ * dishonesty this module was written to prevent, and a dropdown entry that quietly does+ * something else is worse than one that admits it cannot.+ */+ it('admits the Manual gap on codex >= 0.149.0, and explains what happens instead', () => {+ const note = unsupportedModesNote(NEW_CODEX)+ expect(note).toContain('Ask each time, Accept edits and Plan have no Codex equivalent')+ // …and says what Codex's own default actually does, because "starts in its own default" is not+ // enough when the promise the user picked was about every single action.+ expect(note).toContain('only when the model chooses to')+ expect(note).toContain('0.149.0')+ // The same sentence must NOT appear for the CLI that can express it.+ expect(unsupportedModesNote(OLD_CODEX)).not.toContain('Ask each time')+ expect(unsupportedModesNote(OLD_CODEX)).not.toContain('0.149.0')+ // Gemini's gap is a different agent's fact and is unmoved by codex's vocabulary.+ for (const caps of [OLD_CODEX, NEW_CODEX])+ expect(unsupportedModesNote(caps)).toContain('Auto has no Gemini equivalent')+ })++ it('keeps the Bypass-all sandbox caveat on both vocabularies', () => {+ // `bypassPermissions` maps to `never`, which is in every measured vocabulary — so the codex+ // sandbox warning must not disappear just because the CLI dropped a DIFFERENT value.+ for (const caps of [OLD_CODEX, NEW_CODEX, {}])+ expect(bypassSandboxCaveat(caps)).toContain('Codex')})})@@ -268,7 +366,9 @@ describe('withPermissionMode — a flag the command already carries (issue #601)// The regression guard for everyone who has not set an override: nodeterm builds those lines// and never puts the flag in twice, so the new branch is unreachable for them.expect(withPermissionMode('claude', 'claude', 'auto')).toBe('claude --permission-mode auto')- expect(withPermissionMode('codex', 'codex', 'manual')).toBe('codex --ask-for-approval untrusted')+ expect(withPermissionMode('codex', 'codex', 'manual', OLD_CODEX)).toBe(+ 'codex --ask-for-approval untrusted'+ )expect(withPermissionMode('claude', 'claude', 'manual')).toBe('claude')})})diff --git a/src/shared/agents/approval-mode.ts b/src/shared/agents/approval-mode.tsindex 937e8f7c2..e02a2d9fa 100644--- a/src/shared/agents/approval-mode.ts+++ b/src/shared/agents/approval-mode.ts@@ -7,10 +7,17 @@// rather than a nearest match. A silent substitution would show the user "Plan" while codex ran in// on-request, or "Auto" while gemini auto-approved every file edit.//-// Measured: `gemini --help` (0.54.4) and `codex --help` (0.146.0). `--sandbox` is deliberately not-// touched: it is a separate axis (read-only | workspace-write | danger-full-access), and folding-// `danger-full-access` into `bypassPermissions` would widen filesystem access invisibly —-// `--ask-for-approval never` on its own still sandboxes.+// Measured: `gemini --help` (0.54.4) and `codex --help` (0.146.0 … 0.154.0). `--sandbox` is+// deliberately not touched: it is a separate axis (read-only | workspace-write |+// danger-full-access), and folding `danger-full-access` into `bypassPermissions` would widen+// filesystem access invisibly — `--ask-for-approval never` on its own still sandboxes.+//+// AND ONE AGENT'S VOCABULARY IS NOT A CONSTANT. codex accepted `untrusted|on-request|never`+// through 0.148.0 and accepts `on-request|never` from 0.149.0 on — measured release by release,+// see `CODEX_APPROVAL_BASELINE`. clap does not ignore a value it does not know, it EXITS, so a+// table pinned to one release is not a stale mapping, it is a dead node. Every value this module+// emits is therefore checked against what the CLI that will actually run the session says it+// takes (`ApprovalCaps`), and a value we have not seen it advertise is never emitted.import {AGENT_CONFIG,ALL_PERMISSION_MODES,@@ -25,12 +32,68 @@ import {} from './config'import { argvHasFlag } from '../shell-quote'+/**+ * What we know about the CLI that will actually RUN this session — the facts that decide whether a+ * value in the tables below may be emitted at all.+ *+ * Optional and empty-by-default ON PURPOSE. A caller that passes nothing gets the baseline+ * vocabulary, which is the safe answer everywhere: the launch keeps working, at worst one mode+ * degrades to the CLI's own default (and the derived UI copy says so). A caller that forgets to+ * pass its probe result therefore costs a mode, never a dead pane — which is the only degrade+ * direction this file accepts.+ */+export interface ApprovalCaps {+ /** The values this machine's (or this host's) `codex` advertises for `--ask-for-approval`, read+ * 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+}++/**+ * The `--ask-for-approval` values EVERY codex we have measured accepts, and therefore the answer+ * when we do not know which codex will run.+ *+ * Measured one release at a time on real binaries (`@openai/codex@<v>-linux-x64`, `--help`):+ * 0.146.0 · 0.147.0 · 0.148.0 advertise `untrusted, on-request, never`; 0.149.0 · 0.150.0 ·+ * 0.151.0 · 0.152.0 · 0.153.0 · 0.154.0 advertise `on-request, never`. So `untrusted` was removed+ * in **0.149.0** — five releases before the one issue #785 reported it from — and `on-request` /+ * `never` are common to every one of them.+ *+ * `untrusted` is deliberately NOT in the baseline. An unknown value does not degrade: clap answers+ *+ * error: invalid value 'untrusted' for '--ask-for-approval <APPROVAL_POLICY>'+ *+ * and exits, so the pane is left at a bare shell with the launch dead (issue #785). A value we+ * have not SEEN this CLI advertise is never emitted; the two we have seen on every measured+ * release are what an unprobed launch falls back to, because that is the command line nodeterm has+ * always sent for those modes.+ */+const CODEX_APPROVAL_BASELINE: readonly string[] = ['on-request', 'never']+/** One agent's approval dialect: the flag it spells, and the values it accepts. ONE fact per agent —* a flag and a table maintained separately is how a third agent added to the table silently emits* the second agent's flag. */interface ApprovalDialect {flag: stringmodes: Partial<Record<AgentPermissionMode, string>>+ /**+ * Does this CLI's OWN default already prompt before every action?+ *+ * This is what decides whether `manual` ("Ask each time") is honoured by emitting NOTHING. For+ * gemini it is true — its `default` mode is documented as "prompt for approval" — so the bare+ * command already keeps the promise. For codex it is false: its built-in default is+ * `on-request`, "the model decides when to ask", so an unflagged codex delivers something else+ * entirely under that label. Kept as a per-agent fact rather than a special case in+ * `modeSupported`, because it is a property of the CLI, not of the mode.+ */+ manualIsDefault: boolean+ /** The values this CLI accepts, when that is version-dependent. `undefined` = every value in+ * `modes` is stable across the releases we have measured, so the table alone decides (gemini).+ * Only codex has one — see `CODEX_APPROVAL_BASELINE`. */+ vocabulary?: (caps: ApprovalCaps) => readonly string[]+ /** What this CLI actually does when `manual` turns out to be inexpressible, for the UI note.+ * Lives beside the table so the sentence cannot drift from it. */+ manualGapNote?: string}const GEMINI_MODES: Partial<Record<AgentPermissionMode, string>> = {@@ -52,22 +115,34 @@ const GEMINI_MODES: Partial<Record<AgentPermissionMode, string>> = {}const CODEX_MODES: Partial<Record<AgentPermissionMode, string>> = {- // codex is the FIRST agent where `manual` emits a flag, and it has to. For every other agent- // `manual` = no flag = a default that already prompts (gemini's own `default` is documented as- // "prompt for approval"), which is exactly what the label "Ask each time" promises. codex's- // built-in default is NOT that: measured on 0.146.0, `codex doctor` reports `approval policy- // OnRequest` with no `approval` key in ~/.codex/config.toml — the model decides when to ask. So- // leaving `manual` unflagged would deliver `on-request` under an "ask each time" label, and- // collapse two dropdown entries onto one behaviour — the same dishonesty this module exists to- // remove, just expressed as an unflagged claim instead of a substituted flag. `untrusted` is the- // real equivalent: "only run trusted commands without asking; escalate anything not in the trusted- // set". No codex launch has ever carried this flag (codex joined the list in the same change), so- // there is no historical command line to keep byte-identical here.+ // codex is the FIRST agent where `manual` emits a flag, and — where the CLI still has the value+ // — it has to. For every other agent `manual` = no flag = a default that already prompts+ // (gemini's own `default` is documented as "prompt for approval"), which is exactly what the+ // label "Ask each time" promises. codex's built-in default is NOT that: measured on 0.146.0 AND+ // re-measured on 0.151.0, `codex doctor` reports `approval policy OnRequest` with no `approval`+ // key in ~/.codex/config.toml — the model decides when to ask. So leaving `manual` unflagged+ // delivers `on-request` under an "ask each time" label, and collapses two dropdown entries onto+ // one behaviour — the same dishonesty this module exists to remove, just expressed as an+ // unflagged claim instead of a substituted flag. `untrusted` is the real equivalent: "only run+ // trusted commands without asking; escalate anything not in the trusted set".+ //+ // THIS ENTRY IS A CANDIDATE, NOT A PROMISE. codex removed `untrusted` in 0.149.0, so on any+ // current CLI it is filtered out by `vocabulary` below and `manual` emits nothing — and+ // `modeSupported` then answers false, so `unsupportedModesNote` admits it instead of the+ // dropdown quietly lying. It stays in the table because a codex <= 0.148.0 is still a codex a+ // user may be running, and on THAT CLI "Ask each time" really is expressible; the probe is what+ // decides, not this file.+ //+ // What was checked before concluding the mode is gone (all on 0.151.0): `-a unless-trusted` —+ // rejected by clap; `-c approval_policy=untrusted` and `-c approval_policy=unless-trusted` —+ // both refused with "config could not be loaded", so the TOML route is not a back door either;+ // `--approve-for-me` — a real flag, but it routes approvals through AUTOMATIC review, which is+ // the opposite of asking the user. 0.149.0+ genuinely cannot express "ask every time".manual: 'untrusted',auto: 'on-request',bypassPermissions: 'never'- // No `plan` and no edit-specific mode exist in codex 0.146.0, so `plan` and `acceptEdits` are- // absent ON PURPOSE — see modeSupported.+ // No `plan` and no edit-specific mode exists in ANY measured codex (0.146.0 … 0.154.0), so+ // `plan` and `acceptEdits` are absent ON PURPOSE — see modeSupported.}/**@@ -82,8 +157,37 @@ const CODEX_MODES: Partial<Record<AgentPermissionMode, string>> = {* user-typed ids), so a plain-object index answers `'constructor'` with a Function.*/const APPROVAL_DIALECTS: Partial<Record<AgentId, ApprovalDialect>> = {- gemini: { flag: '--approval-mode', modes: GEMINI_MODES },- codex: { flag: '--ask-for-approval', modes: CODEX_MODES }+ gemini: { flag: '--approval-mode', modes: GEMINI_MODES, manualIsDefault: true },+ codex: {+ flag: '--ask-for-approval',+ modes: CODEX_MODES,+ manualIsDefault: false,+ vocabulary: (caps) =>+ caps.codexApprovalValues?.length ? caps.codexApprovalValues : CODEX_APPROVAL_BASELINE,+ manualGapNote:+ 'That default asks only when the model chooses to: `untrusted`, the policy that meant ' ++ 'ask-every-time, was removed in codex-cli 0.149.0 and has no replacement.'+ }+}++/**+ * The value this dialect may actually EMIT for this mode — the table entry, filtered through what+ * the target CLI says it accepts. `undefined` = emit nothing.+ *+ * `Object.hasOwn`, not `[mode]`, for the same reason `dialectFor` uses it: the callers below+ * validate `mode` with `isPermissionMode` first, and this keeps the lookup honest even so — a+ * plain-object index answers `'constructor'` with a Function, and this value is headed for a shell+ * command line.+ */+function emittableValue(+ dialect: ApprovalDialect,+ mode: AgentPermissionMode,+ caps: ApprovalCaps+): string | undefined {+ const value = Object.hasOwn(dialect.modes, mode) ? dialect.modes[mode] : undefined+ if (!value) return undefined+ if (!dialect.vocabulary) return value+ return dialect.vocabulary(caps).includes(value) ? value : undefined}const dialectFor = (agentId: AgentId): ApprovalDialect | null =>@@ -91,17 +195,24 @@ const dialectFor = (agentId: AgentId): ApprovalDialect | null =>/** Can this agent actually start in this mode? `false` means the launch omits the flag and the* agent uses its own default — surfaced in the UI so the user is not misled. */-export function modeSupported(agentId: AgentId, mode: AgentPermissionMode): boolean {+export function modeSupported(+ agentId: AgentId,+ mode: AgentPermissionMode,+ caps: ApprovalCaps = {}+): boolean {if (!isPermissionMode(mode)) return false- // `manual` — "ask each time" — is reachable on every capable agent, but for two different reasons,- // which is why the table is not its authority: claude/grok/gemini get there by emitting NO flag- // (their own default already prompts), and codex gets there through `untrusted`, because its- // default does not. Either way the promise holds; an agent whose CLI could offer neither would- // need this early return revisited.- if (mode === 'manual') return hasPermissionMode(agentId)const dialect = dialectFor(agentId)- if (dialect) return Object.hasOwn(dialect.modes, mode)- return hasPermissionMode(agentId)+ // claude and grok speak our own vocabulary and their defaults prompt: every mode is reachable.+ if (!dialect) return hasPermissionMode(agentId)+ // `manual` — "ask each time" — is reached two different ways, which is why the table alone is+ // not its authority: by emitting NO flag on a CLI whose own default already prompts+ // (`manualIsDefault`: claude, grok, gemini), or by emitting a value that means it (codex's+ // `untrusted`). An agent that can do NEITHER cannot keep the promise, and this is where that is+ // admitted — codex >= 0.149.0 is exactly that case, and it is why this early return stopped+ // being an unconditional `true`.+ if (mode === 'manual')+ return dialect.manualIsDefault || emittableValue(dialect, 'manual', caps) !== undefined+ return emittableValue(dialect, mode, caps) !== undefined}/**@@ -113,11 +224,15 @@ export function modeSupported(agentId: AgentId, mode: AgentPermissionMode): bool* indexes a plain-object table and hands back a Function — one that would have been stringified* onto a tmux `send-keys` line. (`dialectFor` closes the same hole on the agent id.)*/-export function approvalFlags(agentId: AgentId, mode: AgentPermissionMode): string[] {+export function approvalFlags(+ agentId: AgentId,+ mode: AgentPermissionMode,+ caps: ApprovalCaps = {}+): string[] {if (!isPermissionMode(mode)) return []const dialect = dialectFor(agentId)if (dialect) {- const value = dialect.modes[mode]+ const value = emittableValue(dialect, mode, caps)return value ? [dialect.flag, value] : []}// claude + grok keep their exact historical spelling, validated at the interpolation site.@@ -153,8 +268,13 @@ export function approvalFlags(agentId: AgentId, mode: AgentPermissionMode): stri* A command with no override cannot reach the suppression — nodeterm builds it and never puts the* flag in twice — so every existing launch line is byte-identical.*/-export function withPermissionMode(cmd: string, id: AgentId, mode: AgentPermissionMode): string {- const flags = approvalFlags(id, mode)+export function withPermissionMode(+ cmd: string,+ id: AgentId,+ mode: AgentPermissionMode,+ caps: ApprovalCaps = {}+): string {+ const flags = approvalFlags(id, mode, caps)if (!flags.length) return cmdif (argvHasFlag(cmd, flags[0])) return cmdreturn `${cmd} ${flags.join(' ')}`@@ -191,6 +311,9 @@ export function permissionModeAgentsLabel(opts?: PermissionModeAgentFilter): strinterface PermissionModeAgentFilter {mode?: AgentPermissionModeexclude?: readonly AgentId[]+ /** What the target CLIs accept, so a "which agents support this mode?" answer is about the CLIs+ * the user actually has. Omitted = the baseline, exactly as everywhere else in this file. */+ caps?: ApprovalCaps}/**@@ -203,7 +326,8 @@ interface PermissionModeAgentFilter {export function permissionModeAgentIds(opts?: PermissionModeAgentFilter): AgentId[] {return PERMISSION_MODE_CAPABLE.filter((id) =>- !opts?.exclude?.includes(id) && (opts?.mode === undefined || modeSupported(id, opts.mode))+ !opts?.exclude?.includes(id) &&+ (opts?.mode === undefined || modeSupported(id, opts.mode, opts.caps ?? {})))}@@ -212,16 +336,23 @@ export function permissionModeAgentIds(opts?: PermissionModeAgentFilter): AgentI* happens instead. Empty string when there is nothing to admit — so the caller appends it blindly* and the sentence disappears by itself the day a CLI grows the missing mode.*/-export function unsupportedModesNote(): string {+export function unsupportedModesNote(caps: ApprovalCaps = {}): string {return PERMISSION_MODE_CAPABLE.map((id) => ({label: agentLabel(id),- gaps: ALL_PERMISSION_MODES.filter((m) => !modeSupported(id, m))+ gaps: ALL_PERMISSION_MODES.filter((m) => !modeSupported(id, m, caps)),+ // Only rendered when `manual` is among the gaps — see below. A generic "starts in its own+ // default" is honest for Plan and Accept edits (nothing was promised about what the default+ // does), but it is NOT enough for "Ask each time": the user picked a promise about every+ // single action, and codex's default keeps none of it. The sentence lives on the dialect so+ // it can only be written where the behaviour it describes is.+ manualGap: dialectFor(id)?.manualGapNote})).filter((a) => a.gaps.length > 0)- .map(({ label, gaps }) => {+ .map(({ label, gaps, manualGap }) => {const modes = joinAnd(gaps.map((m) => PERMISSION_MODE_LABELS[m]))const verb = gaps.length > 1 ? 'have' : 'has'- return `${modes} ${verb} no ${label} equivalent, so ${label} sessions start in ${label}'s own default.`+ const head = `${modes} ${verb} no ${label} equivalent, so ${label} sessions start in ${label}'s own default.`+ return gaps.includes('manual') && manualGap ? `${head} ${manualGap}` : head}).join(' ')}@@ -236,8 +367,8 @@ const SANDBOX_RETAINED: readonly AgentId[] = ['codex']/** The clause a "Bypass all" warning owes, so "no permission checks" is not read as "no sandbox* either". Empty string when it applies to nobody. */-export function bypassSandboxCaveat(): string {- const ids = permissionModeAgentIds({ mode: 'bypassPermissions' }).filter((id) =>+export function bypassSandboxCaveat(caps: ApprovalCaps = {}): string {+ const ids = permissionModeAgentIds({ mode: 'bypassPermissions', caps }).filter((id) =>SANDBOX_RETAINED.includes(id))if (!ids.length) return ''diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.tsindex 2fd2aff0f..db30e3eb0 100644--- a/src/shared/agents/launch.ts+++ b/src/shared/agents/launch.ts@@ -25,7 +25,7 @@ import {type AgentId,type AgentPermissionMode} from './config'-import { withPermissionMode } from './approval-mode'+import { withPermissionMode, type ApprovalCaps } from './approval-mode'import { resolveAgentConfig } from './custom-agent'import { withAgentModel } from './model-gateway'@@ -65,6 +65,10 @@ export interface LaunchInputs {* CLI? The caller's answer to "will the launcher actually be there?" — false (the default) emits* the bare command byte-for-byte. A remote node must pass false (the host has no launcher). */sharedIdentity?: boolean+ /** What the CLI that will RUN this session accepts, so a flag value it does not have is never+ * emitted (codex dropped `untrusted` in 0.149.0 and clap EXITS on an unknown value). Omitted =+ * the baseline vocabulary, which is the pre-probe command line — see `ApprovalCaps`. */+ approvalCaps?: ApprovalCaps}export interface ResumeInputs {@@ -81,6 +85,10 @@ export interface ResumeInputs {/** Should a SHARED_IDENTITY_CAPABLE agent (codex) name its managed launcher on resume? Same* semantics as `LaunchInputs.sharedIdentity`. */sharedIdentity?: boolean+ /** What the CLI that will RUN this session accepts, so a flag value it does not have is never+ * emitted (codex dropped `untrusted` in 0.149.0 and clap EXITS on an unknown value). Omitted =+ * the baseline vocabulary, which is the pre-probe command line — see `ApprovalCaps`. */+ approvalCaps?: ApprovalCaps}export interface AssembledCommand {@@ -218,7 +226,7 @@ export function assembleLaunchCommand(const flagged = (cmd: string): string => {const withMode = inputs.permissionMode- ? withPermissionMode(cmd, capId, inputs.permissionMode)+ ? withPermissionMode(cmd, capId, inputs.permissionMode, inputs.approvalCaps ?? {}): cmd// Session-id minting: claude-base + CLI supports the flag. On resume this branch is never// taken (assembleResumeCommand does not pass sessionId).@@ -261,7 +269,7 @@ export function assembleResumeCommand(const resumeBase = inputs.sessionId ? resumeCommandWith(baseCmd, capId, inputs.sessionId) : nullconst base = resumeBase ?? baseCmdconst withMode = inputs.permissionMode- ? withPermissionMode(base, capId, inputs.permissionMode)+ ? withPermissionMode(base, capId, inputs.permissionMode, inputs.approvalCaps ?? {}): baseconst command = withAgentModel(withMode, capId, inputs.model)return { command, missingEnv: [...m1, ...m2] }diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 9ad3ab0ab..5854e1dec 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -83,6 +83,7 @@ export const IPC = {grokTakenSessionIds: 'grok-cli:taken-session-ids',/** Can a node on this machine get a managed Codex identity? See core/codex-identity-caps.ts. */codexIdentityCaps: 'codex-identity:caps',+ codexCliCaps: 'codex-cli:caps',/** main/server → renderer: a Codex node's identity mode changed ('shared' | 'plain'). The* 'plain' events are what make the launcher's fallback visible instead of silent. */codexIdentity: 'codex-identity:event',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 136233993..d05cad046 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2939,6 +2939,27 @@ export const UNKNOWN_CLAUDE_CLI_CAPS: ClaudeCliCaps = {sessionIdFlag: false}+/**+ * What the LOCAL `codex` binary can do, read from its own `--help` — see `core/codex-cli.ts`.+ *+ * Separate from `CodexIdentityCaps` on purpose, because the two have OPPOSITE Server Edition+ * answers: shared identity is declined there deliberately (a constant `false`), while the+ * approval vocabulary must be probed for real — the server's own machine is the one that runs its+ * Codex sessions. Folding them into one bag would have made the honest answer to one question the+ * silent absence of the other.+ */+export interface CodexCliCaps {+ /** The values this `codex` advertises for `--ask-for-approval`. `null` = not probed, no codex on+ * PATH, or a help page we could not read — all of which mean "use the baseline vocabulary", not+ * "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+}++/** 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 }+/** Whether a Codex node launched on this machine right now would get a managed shared identity.* Fed by core/codex-identity-caps.ts; the unknown answer is `false`, i.e. plain `codex`. */export interface CodexIdentityCaps {@@ -2980,6 +3001,9 @@ export interface CodexApi {/** Would a Codex node launched right now get a managed shared identity on this machine?* Never rejects — the unknown answer is `{ shared: false }`, i.e. plain `codex`. */identityCaps(): Promise<CodexIdentityCaps>+ /** What the local Codex CLI accepts, so a launch line only carries flag values this binary+ * actually has. Never rejects — the unknown answer is `UNKNOWN_CODEX_CLI_CAPS`. */+ cliCaps(): Promise<CodexCliCaps>/** Fires when a Codex node's launcher reports its identity mode. `plain` is the fallback, and* this event is what stops that fallback being silent. Returns unsubscribe. */onIdentity(listener: (e: CodexIdentityEvent) => void): () => void