Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(codex): answer the --remote question at caps time, and wait out a binding daemon

enes9c33d2f932fe
diff --git a/docs/codex-shared-identity.md b/docs/codex-shared-identity.md
index 682f65869..909d73bb8 100644
--- a/docs/codex-shared-identity.md
+++ b/docs/codex-shared-identity.md
@@ -77,6 +77,11 @@ thing it reports is *"there was no capability to present"*, so requiring one wou
exactly the case it exists for. A report that **does** carry a token must carry the right one, so
only a tokenless caller is trusted on the node id it names.
+A cold app-server is handled on both routes: `codex app-server daemon start` exiting 0 does not
+mean the control socket is accepting connections yet, so `waitForCodexAppServer` (3 × 200 ms)
+precedes the mint, and the bind check retries only when it could not REACH the server — a server
+that answered "I do not have that thread" is never retried, because that is an answer.
+
If secure storage is unavailable the whole feature stays off — `codexIdentityCaps()` answers
`shared: false`, every launch line stays the bare `codex`, and nothing is half-armed.
@@ -128,6 +133,19 @@ that is a later slice — so a launcher-named line there would be `command not f
dead node this exists to prevent.) The default `false` means every call site that has not opted in
emits today's command.
+`shared` is the AND of three things, and the third is the interesting one: the installed `codex`
+must accept **`--remote`**. That is the only precondition with no runtime recovery — the launcher's
+preflight proves `codex app-server daemon start` exits 0 and then **execs**, and a CLI with an
+app-server but no `--remote` dies on a clap usage error where no fallback is left. It is
+feature-detected from the CLI's own `--help` (and `codex resume --help` if the first does not say),
+never version-compared, for the same reason claude's `--session-id` is: an unrecognised flag does
+not degrade, it makes the CLI exit. Unknown — no CLI on the login PATH, a failed or timed-out
+spawn, help text that never mentions the flag — means **false**, i.e. plain codex. A wrong "yes"
+costs the node; a wrong "no" costs only the shared app-server. The probe runs **once per app run,
+inside `refreshCodexIdentityCaps()`, entirely off the launch path**: a per-launch probe would be
+visible latency in the pane every time, to answer a question whose answer cannot change while the
+app runs.
+
Unlike claude's, this probe cannot compute anything until the shell hands the hook server its
secret, so the shell **pushes** the answer in and an early caller **waits**. A sync getter would
answer "no" to anything that asked first, and a "no" pins the feature off for the whole run with no
@@ -245,7 +263,9 @@ PR #112, all still to be sliced.
## 8. Known gaps
-1. **Post-`exec` failures are unrecoverable** (§3, and §9.1-9.3).
+1. **Post-`exec` failures are unrecoverable** (§3). The `--remote` case is closed at caps time;
+ what remains is §9.2 (the composed `resume <id> <prompt> --ask-for-approval never` line) and
+ §9.3 (the persisted session id being the app-server's thread id).
2. **The launcher requires a hook PORT**, not a unix socket — it POSTs to
`http://localhost:$NODETERM_HOOK_PORT`. Fine today (the desktop's hook server is a loopback TCP
listener), but the Server Edition wiring will have to revisit it alongside `NODETERM_HOOK_SOCK`,
@@ -253,7 +273,14 @@ PR #112, all still to be sliced.
3. **The node token rides tmux `-e` on the local path**, i.e. it is in the tmux session env like
every other `NODETERM_*` value. Same exposure as the hook bearer already has; noted rather than
changed, because changing it means changing how all of them are delivered.
-4. **`CODEX_HOME` is resolved twice**: the desktop resolves the app-server socket from the Electron
+4. **Two residual orphan classes**, both inherent rather than bugs, neither covered by the budget
+ ordering in §2. (a) A client that dies for a non-timeout reason — the pane killed, `tmux
+ kill-session`, Ctrl-C mid-mint — still leaves the handler to finish and write its record. That is
+ bounded now: §2's pruning removes it with the node, and the next launch mints a fresh thread
+ anyway. (b) An app-server that aborts mid-conversation can leave the seed and/or the forked
+ thread alive on ITS side, because the closing `thread/delete` may never be sent. Orphan
+ *threads* have no reaper anywhere — not here and not in codex.
+5. **`CODEX_HOME` is resolved twice**: the desktop resolves the app-server socket from the Electron
process's environment, the pane resolves `--remote unix://` from its own. Identical unless a user
sets `CODEX_HOME` in a shell rc only, in which case start succeeds and resume misses. Managed
accounts make this explicit; until then it is a narrow, real mismatch.
@@ -266,11 +293,13 @@ Everything below needs a machine with a logged-in `codex`. Items 1-3 are the ass
implementation could not verify; a failure in any of them is a **dead node**, not a degrade, so they
come first. Items 1, 2 and 5 fall out of a single capture run on one fresh node.
-1. **`codex --remote unix://` exists on the installed CLI.** The preflight only proves
- `codex app-server daemon start` exits 0 — it says nothing about the `--remote` flag. Run
- `codex --help` and confirm `--remote` and its argument form; then open a fresh Codex node and
- confirm the pane shows a working session rather than a clap usage error. If the flag differs,
- the launcher's two `exec` lines are what change.
+1. **`codex --remote unix://` works, and the caps probe reads the flag correctly.** The flag's
+ PRESENCE is now answered per machine (`codexCliSupportsRemote`, §3), so a CLI without it gets a
+ plain-codex node instead of a dead one — but nothing has confirmed that the flag we detect is
+ the flag we then use. Run `codex --help` and check `--remote`'s argument form against the two
+ `exec` lines in the launcher; then open a fresh Codex node and confirm the pane shows a working
+ session rather than a clap usage error. Also confirm the negative: on a CLI without `--remote`
+ (or with the probe forced false), the node runs plain codex and says so.
2. **`codex resume <id> <prompt> --ask-for-approval never` accepts a positional prompt AND a global
flag after the subcommand.** This is the composed line `createAgentNode` builds, and it is
CLAUDE.md rule 5's grok-`--` lesson exactly: a `withPermissionMode` unit test passes while the
@@ -297,6 +326,17 @@ come first. Items 1, 2 and 5 fall out of a single capture run on one fresh node.
`<userDataDir>/codex-thread-nodes/` while other nodes' remain.
9. **Two nodes, one thread.** Point a second node at a thread the first still owns (a `resume` with
a copied id) and confirm it falls back to plain codex instead of both clients attaching.
-10. **A cold app-server.** Kill the app-server, then open a Codex node. This is the H1 case: confirm
- it waits for the mint (which can take seconds) and comes up shared, rather than falling back
- with `thread-start-failed` while an orphan thread is created behind it.
+10. **A cold app-server, on the START path.** Kill the app-server, then open a fresh Codex node.
+ Confirm it waits for the mint (which can take seconds) and comes up shared, rather than falling
+ back with `thread-start-failed` while an orphan thread is created behind it.
+11. **A cold app-server, on the RESUME/BIND path.** Kill the app-server, then cold-start an
+ EXISTING Codex node (restart the app, or reboot). Bind now makes a mandatory app-server round
+ trip, so a daemon whose socket binds a beat late would turn a legitimate resume into
+ `thread-bind-refused` → plain codex. `waitForCodexAppServer` is meant to absorb that; confirm
+ the node comes up shared and that a genuinely absent server still falls back promptly rather
+ than hanging.
+12. **`CODEX_HOME` set in a shell rc only** (§8.5). Put `export CODEX_HOME=…` in `~/.zshrc` (not in
+ the app's environment) and open a Codex node. The desktop resolves the app-server socket from
+ Electron's environment while the pane resolves `--remote unix://` from its own, so this is where
+ they diverge: confirm what actually happens — shared against the wrong home, or a start that
+ succeeds followed by a resume that misses.
diff --git a/src/core/codex-identity-caps.test.ts b/src/core/codex-identity-caps.test.ts
index 94f0a5ead..c7b5b0202 100644
--- a/src/core/codex-identity-caps.test.ts
+++ b/src/core/codex-identity-caps.test.ts
@@ -4,10 +4,14 @@ import os from 'node:os'
import path from 'node:path'
import { randomBytes } from 'node:crypto'
import {
+ codexCliSupportsRemote,
codexIdentityCaps,
refreshCodexIdentityCaps,
resetCodexIdentityCapsForTests
} from './codex-identity-caps'
+
+/** Stand-in for the `codex --help` probe. Every test says explicitly what the CLI answered. */
+const remote = (yes: boolean) => () => Promise.resolve(yes)
import {
resetCodexThreadIdentityAuthSecret,
setCodexThreadIdentityAuthSecret
@@ -33,9 +37,9 @@ afterEach(() => {
})
describe('codexIdentityCaps', () => {
- it('says yes, and installs the launcher, once the secret is in', () => {
+ it('says yes, and installs the launcher, once the secret is in and the CLI has --remote', async () => {
setCodexThreadIdentityAuthSecret(randomBytes(32))
- const caps = refreshCodexIdentityCaps()
+ const caps = await refreshCodexIdentityCaps(remote(true))
expect(caps.shared).toBe(true)
expect(fs.existsSync(caps.launcherPath as string)).toBe(true)
})
@@ -43,8 +47,19 @@ describe('codexIdentityCaps', () => {
it('says no without the secret, and installs nothing', () => {
// Half-armed is the state to avoid: a launcher on PATH with no capability to present would
// reach the routes, be refused, and fall back one process later. Better to never name it.
- const caps = refreshCodexIdentityCaps()
- expect(caps).toEqual({ shared: false, launcherPath: null })
+ return refreshCodexIdentityCaps(remote(true)).then((caps) => {
+ expect(caps).toEqual({ shared: false, launcherPath: null, remoteFlag: true })
+ expect(fs.existsSync(path.join(dir, 'codex-bin', 'nodeterm-codex'))).toBe(false)
+ })
+ })
+
+ it('says no when the installed codex has no --remote, however armed everything else is', async () => {
+ // The one precondition with no runtime recovery: the launcher execs, and a CLI with an
+ // app-server but no --remote dies on a usage error where nothing can fall back. Answering it
+ // here turns a dead node into a plain-codex node on every machine, not just the tester's.
+ setCodexThreadIdentityAuthSecret(randomBytes(32))
+ const caps = await refreshCodexIdentityCaps(remote(false))
+ expect(caps).toEqual({ shared: false, launcherPath: null, remoteFlag: false })
expect(fs.existsSync(path.join(dir, 'codex-bin', 'nodeterm-codex'))).toBe(false)
})
@@ -58,12 +73,32 @@ describe('codexIdentityCaps', () => {
await Promise.resolve()
expect(settled).toBe(false)
setCodexThreadIdentityAuthSecret(randomBytes(32))
- refreshCodexIdentityCaps()
+ await refreshCodexIdentityCaps(remote(true))
expect((await asked).shared).toBe(true)
})
it('answers immediately once refreshed', async () => {
- refreshCodexIdentityCaps()
- expect(await codexIdentityCaps()).toEqual({ shared: false, launcherPath: null })
+ await refreshCodexIdentityCaps(remote(false))
+ expect(await codexIdentityCaps()).toEqual({
+ shared: false,
+ launcherPath: null,
+ remoteFlag: false
+ })
+ })
+})
+
+describe('codexCliSupportsRemote', () => {
+ it('reads the flag out of help text, and is not fooled by a longer flag or by prose', () => {
+ expect(codexCliSupportsRemote(' --remote <URL> connect to an app-server')).toBe(true)
+ expect(codexCliSupportsRemote(' --remote=<URL>')).toBe(true)
+ // `--remote-auth-token-env` exists and is NOT the flag we need; nor is a mention of it.
+ expect(codexCliSupportsRemote(' --remote-auth-token-env <VAR>')).toBe(false)
+ expect(codexCliSupportsRemote('use with --remotely-hosted servers')).toBe(false)
+ expect(codexCliSupportsRemote(null, undefined, '')).toBe(false)
+ })
+
+ it('accepts an answer from either help page', () => {
+ // Some CLIs list a global flag only under the subcommand that takes it.
+ expect(codexCliSupportsRemote('no flags here', ' --remote <URL>')).toBe(true)
})
})
diff --git a/src/core/codex-identity-caps.ts b/src/core/codex-identity-caps.ts
index 83527cb2f..8378531e3 100644
--- a/src/core/codex-identity-caps.ts
+++ b/src/core/codex-identity-caps.ts
@@ -14,20 +14,70 @@
* `codexIdentityCaps` below for why waiting, rather than answering "no", is the only safe default
* here.
*
- * Two things have to be true, and neither is knowable from the renderer:
+ * Three things have to be true, and none is knowable from the renderer:
* 1. the hook server holds the per-node auth secret (no secret ⇒ no capability token ⇒ the
- * launcher would fall back anyway, one process later), and
+ * launcher would fall back anyway, one process later),
* 2. the generated launcher could actually be written (a read-only or full data dir is a real
- * failure mode, and it is the one the renderer cannot see at all).
+ * failure mode, and it is the one the renderer cannot see at all), and
+ * 3. the installed `codex` accepts `--remote` — see `codexCliSupportsRemote`. This is the only
+ * one that cannot be recovered from at runtime: the launcher's preflight proves that
+ * `codex app-server daemon start` exits 0, and then EXECS. A CLI with an app-server but no
+ * `--remote` dies on a clap usage error after that exec, where there is no fallback left. So
+ * it is answered here, once per app run, entirely off the launch path.
*
* SERVER EDITION: `src/server` deliberately registers this and answers `false` — see the comment
* at its registration site. That is what makes "Server Edition runs plain codex" a decision rather
* than an accident.
*/
+import { execFile } from 'child_process'
+import { promisify } from 'util'
import { IPC } from '../shared/ipc'
import { platform } from './platform'
-import { UNKNOWN_CODEX_IDENTITY_CAPS, type CodexIdentityCaps } from '../shared/types'
+import { type CodexIdentityCaps } from '../shared/types'
import { installCodexLauncher, codexThreadIdentityAvailable } from './codex-identity-proxy'
+import { findInLoginPath } from './pty-manager'
+
+const execFileP = promisify(execFile)
+const PROBE_TIMEOUT_MS = 5000
+
+/**
+ * Pure: help text → does this CLI accept `--remote`?
+ *
+ * FEATURE-detected from `--help`, never version-compared, for the same reason claude's
+ * `--session-id` is: the release it appeared in is not documented anywhere this repo can check,
+ * and an unrecognised flag does not degrade — it makes the CLI exit. Anchored on a word boundary
+ * so `--remote-auth-token-env`, or prose mentioning the flag inside another option's description,
+ * cannot answer yes for it.
+ *
+ * Absent help output ⇒ false ⇒ no shared identity ⇒ the bare `codex` command, exactly as before
+ * this feature. That is the same direction every other unknown in this file degrades in: a wrong
+ * "yes" here costs the node, a wrong "no" costs only the shared app-server.
+ */
+export function codexCliSupportsRemote(...helpOutputs: Array<string | null | undefined>): boolean {
+ return helpOutputs.some((h) => /(^|\s)--remote(\s|=|$)/m.test(h ?? ''))
+}
+
+async function probeRemoteFlag(): Promise<boolean> {
+ 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 false
+ const help = await execFileP(bin, ['--help'], { timeout: PROBE_TIMEOUT_MS })
+ .then((r) => r.stdout)
+ .catch(() => null)
+ if (codexCliSupportsRemote(help)) return true
+ // Some CLIs list a global flag only under the subcommand that takes it. One extra spawn, paid
+ // once per app run and only when the top-level help did not already answer yes.
+ const resumeHelp = await execFileP(bin, ['resume', '--help'], { timeout: PROBE_TIMEOUT_MS })
+ .then((r) => r.stdout)
+ .catch(() => null)
+ return codexCliSupportsRemote(resumeHelp)
+ } catch {
+ // Missing CLI, timeout, non-zero exit — all mean "unknown", which means "no shared identity".
+ return false
+ }
+}
let latest: CodexIdentityCaps | null = null
let ready: Promise<CodexIdentityCaps> | null = null
@@ -35,11 +85,19 @@ let announce: ((c: CodexIdentityCaps) => void) | null = null
/**
* Compute the answer and publish it. Called once by the shell, AFTER the node-auth secret has been
- * set (or has definitively failed), because the secret is half of what "shared" means.
+ * set (or has definitively failed), because the secret is a third of what "shared" means.
+ *
+ * Async because of the `--remote` probe, which is a login-shell lookup plus up to two `--help`
+ * spawns. That cost is paid HERE — once, during boot, with nothing waiting on it but the first
+ * Codex launch line — and never on the launch path itself, where it would be visible latency in
+ * the pane every single time, to answer a question whose answer cannot change while the app runs.
*/
-export function refreshCodexIdentityCaps(): CodexIdentityCaps {
- const launcher = codexThreadIdentityAvailable() ? installCodexLauncher() : null
- latest = { shared: !!launcher, launcherPath: launcher }
+export async function refreshCodexIdentityCaps(
+ probeRemote: () => Promise<boolean> = probeRemoteFlag
+): Promise<CodexIdentityCaps> {
+ const remoteFlag = await probeRemote()
+ const launcher = remoteFlag && codexThreadIdentityAvailable() ? installCodexLauncher() : null
+ latest = { shared: !!launcher, launcherPath: launcher, remoteFlag }
if (announce) {
announce(latest)
announce = null
diff --git a/src/core/codex-session-name.test.ts b/src/core/codex-session-name.test.ts
index 89cad2e1e..a47606af4 100644
--- a/src/core/codex-session-name.test.ts
+++ b/src/core/codex-session-name.test.ts
@@ -13,7 +13,8 @@ import { WebSocketServer, type WebSocket } from 'ws'
import {
codexThreadExistsAt,
codexUnixWebSocketUrl,
- readCodexSessionNameAt
+ readCodexSessionNameAt,
+ waitForCodexAppServer
} from './codex-session-name'
let dir = ''
@@ -79,7 +80,38 @@ describe('codexThreadExistsAt', () => {
})
it('refuses when the app-server is not running at all', async () => {
- expect(await codexThreadExistsAt(path.join(dir, 'nope.sock'), 'thread-known', 500)).toBe(false)
+ expect(await codexThreadExistsAt(path.join(dir, 'nope.sock'), 'thread-known', 500, 1)).toBe(
+ false
+ )
+ })
+
+ it('waits out a daemon whose socket is still binding, instead of refusing a good resume', async () => {
+ // `codex app-server daemon start` exiting 0 does not mean the socket is listening yet, and
+ // this check runs immediately after it on the cold/reboot path. Without the retry, a daemon
+ // that binds a beat late turns a legitimate resume into `thread-bind-refused` → plain codex:
+ // a NEW way to lose shared identity on exactly the path the feature exists for.
+ const latePath = path.join(dir, 'late.sock')
+ const late = http.createServer()
+ const lateWss = new WebSocketServer({ server: late })
+ lateWss.on('connection', handle)
+ const listening = new Promise<void>((resolve) =>
+ setTimeout(() => late.listen(latePath, resolve), 250)
+ )
+ try {
+ expect(await codexThreadExistsAt(latePath, 'thread-known', 500)).toBe(true)
+ } finally {
+ await listening
+ await new Promise<void>((resolve) => lateWss.close(() => resolve()))
+ await new Promise<void>((resolve) => late.close(() => resolve()))
+ }
+ })
+
+ it('does NOT retry a server that answered — "I do not have it" is an answer', async () => {
+ // Retrying a definite no just delays it. Measured by the clock: three attempts with the
+ // default 200ms gap could not come back this fast.
+ const started = Date.now()
+ expect(await codexThreadExistsAt(sock, 'thread-from-a-past-life')).toBe(false)
+ expect(Date.now() - started).toBeLessThan(200)
})
it('refuses an id that is not shaped like one, without opening a socket', async () => {
@@ -96,6 +128,13 @@ describe('codexThreadExistsAt', () => {
})
})
+describe('waitForCodexAppServer', () => {
+ it('answers true for a live socket and false for a dead one, without throwing', async () => {
+ expect(await waitForCodexAppServer(sock, 1)).toBe(true)
+ expect(await waitForCodexAppServer(path.join(dir, 'nope.sock'), 2, 10)).toBe(false)
+ })
+})
+
describe('readCodexSessionNameAt', () => {
it("reads the thread's own name", async () => {
expect(await readCodexSessionNameAt(sock, 'thread-known')).toBe('Named by codex')
diff --git a/src/core/codex-session-name.ts b/src/core/codex-session-name.ts
index 4610d9b21..236a00c2c 100644
--- a/src/core/codex-session-name.ts
+++ b/src/core/codex-session-name.ts
@@ -22,6 +22,64 @@ import { WebSocket } from 'ws'
import { CODEX_THREAD_START_TIMEOUT_MS } from './codex-identity-proxy'
const SAFE_THREAD_ID = /^[A-Za-z0-9._-]+$/
+/**
+ * `codex app-server daemon start` exiting 0 does NOT mean its control socket is accepting
+ * connections yet — the daemon binds a beat later. Everything here runs immediately after that
+ * command, on the cold/reboot path this feature exists for, so a single failed connect must not be
+ * read as an answer. Three tries over ~600 ms: long enough for a daemon that is coming up, short
+ * enough that a daemon that is not there costs nothing worth noticing.
+ */
+const SOCKET_WAIT_ATTEMPTS = 3
+const SOCKET_WAIT_MS = 200
+
+const delay = (ms: number): Promise<void> =>
+ new Promise((resolve) => {
+ const t = setTimeout(resolve, ms)
+ t.unref?.()
+ })
+
+/** Resolve once the app-server's socket accepts a connection, or after the attempts run out. */
+export function waitForCodexAppServer(
+ socketPath: string,
+ attempts = SOCKET_WAIT_ATTEMPTS,
+ gapMs = SOCKET_WAIT_MS
+): Promise<boolean> {
+ const tryOnce = (): Promise<boolean> =>
+ new Promise((resolve) => {
+ let ws: WebSocket
+ let settled = false
+ const finish = (ok: boolean): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ try {
+ ws.close()
+ } catch {
+ /* the connection may never have opened */
+ }
+ resolve(ok)
+ }
+ const timer = setTimeout(() => finish(false), REQUEST_TIMEOUT_MS)
+ timer.unref?.()
+ try {
+ ws = connectCodexAppServer(socketPath)
+ } catch {
+ clearTimeout(timer)
+ resolve(false)
+ return
+ }
+ ws.once('open', () => finish(true))
+ ws.once('error', () => finish(false))
+ ws.once('close', () => finish(false))
+ })
+ return (async () => {
+ for (let i = 0; i < attempts; i++) {
+ if (await tryOnce()) return true
+ if (i < attempts - 1) await delay(gapMs)
+ }
+ return false
+ })()
+}
const CACHE_MS = 3_000
const REQUEST_TIMEOUT_MS = 2_000
@@ -124,16 +182,16 @@ export function readCodexSessionNameAt(
* A server we cannot reach answers `false`, which is the safe direction here: refusing costs a
* plain codex session, accepting costs the node.
*/
-export function codexThreadExistsAt(
+function probeCodexThread(
socketPath: string,
threadId: string,
- timeoutMs = REQUEST_TIMEOUT_MS
-): Promise<boolean> {
- if (!SAFE_THREAD_ID.test(threadId)) return Promise.resolve(false)
+ timeoutMs: number
+): Promise<'yes' | 'no' | 'unreachable'> {
return new Promise((resolve) => {
let settled = false
+ let answered = false
let ws: WebSocket
- const finish = (exists: boolean): void => {
+ const finish = (result: 'yes' | 'no' | 'unreachable'): void => {
if (settled) return
settled = true
clearTimeout(timer)
@@ -142,15 +200,15 @@ export function codexThreadExistsAt(
} catch {
/* the connection may never have opened */
}
- resolve(exists)
+ resolve(result)
}
- const timer = setTimeout(() => finish(false), timeoutMs)
+ const timer = setTimeout(() => finish(answered ? 'no' : 'unreachable'), timeoutMs)
timer.unref?.()
try {
ws = connectCodexAppServer(socketPath)
} catch {
clearTimeout(timer)
- resolve(false)
+ resolve('unreachable')
return
}
ws.once('open', () => {
@@ -170,7 +228,10 @@ export function codexThreadExistsAt(
return
}
if (message.id === 1) {
- if (message.error) return finish(false)
+ answered = true
+ // A server that will not initialize is a definite NO, not a transient one: retrying a
+ // logged-out CLI just delays the same answer.
+ if (message.error) return finish('no')
ws.send(JSON.stringify({ method: 'initialized' }))
ws.send(
JSON.stringify({ id: 2, method: 'thread/read', params: { threadId, includeTurns: false } })
@@ -178,14 +239,47 @@ export function codexThreadExistsAt(
} else if (message.id === 2) {
// The id must come back UNCHANGED: a server that answers with some other thread has not
// confirmed the one we asked about.
- finish(!message.error && message.result?.thread?.id === threadId)
+ finish(!message.error && message.result?.thread?.id === threadId ? 'yes' : 'no')
}
})
- ws.once('error', () => finish(false))
- ws.once('close', () => finish(false))
+ ws.once('error', () => finish(answered ? 'no' : 'unreachable'))
+ ws.once('close', () => finish(answered ? 'no' : 'unreachable'))
})
}
+/**
+ * Does the shared app-server actually know this thread?
+ *
+ * The bind route writes a record claiming a node owns a conversation. Without this check ANY
+ * id the caller hands us binds happily — a stale session id, or one persisted from a
+ * plain-codex-era session that the app-server has never heard of — and the launcher then execs
+ * `codex --remote unix:// resume <id>`, which dies with "no rollout found" AFTER exec, where
+ * there is no fallback left. Asking first turns that dead node into an ordinary fallback.
+ *
+ * A server we could not REACH is retried (the daemon may still be binding its socket — see
+ * SOCKET_WAIT_ATTEMPTS), because this check runs on the cold path and a not-yet-listening daemon
+ * would otherwise turn a perfectly good resume into a fallback. A server that ANSWERED is never
+ * retried: "I do not have that thread" is an answer, and asking again just delays it.
+ *
+ * Out of retries, the answer is `false` — the safe direction: refusing costs a plain codex
+ * session, accepting costs the node.
+ */
+export async function codexThreadExistsAt(
+ socketPath: string,
+ threadId: string,
+ timeoutMs = REQUEST_TIMEOUT_MS,
+ attempts = SOCKET_WAIT_ATTEMPTS,
+ gapMs = SOCKET_WAIT_MS
+): Promise<boolean> {
+ if (!SAFE_THREAD_ID.test(threadId)) return false
+ for (let i = 0; i < attempts; i++) {
+ const result = await probeCodexThread(socketPath, threadId, timeoutMs)
+ if (result !== 'unreachable') return result === 'yes'
+ if (i < attempts - 1) await delay(gapMs)
+ }
+ return false
+}
+
export function codexThreadExists(threadId: string): Promise<boolean> {
return codexThreadExistsAt(defaultCodexAppServerSocket(), threadId)
}
@@ -200,10 +294,21 @@ export function codexThreadExists(threadId: string): Promise<boolean> {
* that turn, and deleting the seed. The result is a thread with zero user turns and a valid
* rollout, without the deprecated rollback API.
*/
-export function startCodexThreadAt(
+export async function startCodexThreadAt(
socketPath: string,
cwd: string,
timeoutMs = CODEX_THREAD_START_TIMEOUT_MS
+): Promise<string> {
+ // Same cold-socket window as the bind check: `daemon start` has exited, the socket may still be
+ // binding. Bounded (~600 ms) and charged against the 20 s budget below, which has room for it.
+ await waitForCodexAppServer(socketPath)
+ return startCodexThreadOnce(socketPath, cwd, timeoutMs)
+}
+
+function startCodexThreadOnce(
+ socketPath: string,
+ cwd: string,
+ timeoutMs: number
): Promise<string> {
if (!path.isAbsolute(cwd) || cwd.includes('\0')) {
return Promise.reject(new Error('Unsupported Codex thread cwd'))
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 1e3041bde..e17b92f00 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -3018,9 +3018,14 @@ export class PtyManager {
// OLD cwd's session, and the respawn is a cold start (`fresh`), so replaying it would paint the
// pre-move terminal into the new one.
await deleteScrollback(persistKey)
- // Same hook, same reason: a permanently deleted node's Codex thread records must go with it.
- // Left behind they accumulate one file per thread forever, and the hook prelude keeps
- // re-exporting a dead node's id into any tool shell that still carries that thread id.
+ // Same hook, same reason as the snapshot above: this node's Codex thread records go with the
+ // session. Left behind they accumulate one file per thread forever, and the hook prelude keeps
+ // re-exporting a DELETED node's id into any tool shell that still carries that thread id.
+ //
+ // Like the snapshot, this also runs for a RECYCLE (the worktree move), where the node lives on
+ // — and that is fine rather than intended: a recycle respawns cold, so the next launch mints or
+ // re-binds a record immediately. Worth stating because the two intents share this line: only
+ // `delete` means "gone for good".
forgetCodexThreadIdentitiesForNode(persistKey)
if (sshRemote) {
// Remote (ssh-project) node: end the REMOTE session.
diff --git a/src/main/index.ts b/src/main/index.ts
index f6a5bfbc6..e5eb6038f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -916,12 +916,14 @@ app.whenReady().then(async () => {
} catch (error) {
console.error('[codex-identity] unavailable; Codex nodes run plain codex:', error)
}
- // Installs the launcher and publishes the construction-time answer. MUST stay after the secret
- // above and before the window: it is what unblocks `codexIdentityCaps()`, which the renderer's
- // first Codex launch line waits on. Reordering it later only delays that answer now (callers
- // wait rather than being told "no"), but leaving it out entirely would stall them until their
- // own timeout, so it is not optional.
- refreshCodexIdentityCaps()
+ // Probes the CLI for `--remote`, installs the launcher, and publishes the construction-time
+ // answer. MUST stay after the secret above and before the window: it is what unblocks
+ // `codexIdentityCaps()`, which the renderer's first Codex launch line waits on. NOT awaited —
+ // the probe is a login-shell lookup plus up to two `--help` spawns, and nothing in the boot
+ // chain should queue behind it; callers of `codexIdentityCaps()` wait for it instead of being
+ // told "no". Reordering it later only delays that answer; leaving it out would stall those
+ // callers until their own timeout, so it is not optional.
+ void refreshCodexIdentityCaps()
hookServer.setCodexIdentityListener((ev) => sendToMain(IPC.codexIdentity, ev))
// A node still on a canvas is "live". A thread whose recorded owner is gone (node deleted, or a
// workspace that no longer holds it) is free to be re-claimed; one whose owner is still there is
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 0ada113fe..ba20a891b 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1879,10 +1879,18 @@ export interface CodexIdentityCaps {
shared: boolean
/** Absolute path of the installed launcher, or null when it could not be written. */
launcherPath: string | null
+ /** Does the installed `codex` accept `--remote`? Feature-detected from its own `--help`. The one
+ * precondition that cannot be recovered from at runtime: the launcher execs, and a CLI without
+ * the flag dies on a usage error where no fallback is left. Unknown ⇒ false ⇒ plain codex. */
+ remoteFlag: boolean
}
/** The answer before the probe has run, and the one the Server Edition gives on purpose. */
-export const UNKNOWN_CODEX_IDENTITY_CAPS: CodexIdentityCaps = { shared: false, launcherPath: null }
+export const UNKNOWN_CODEX_IDENTITY_CAPS: CodexIdentityCaps = {
+ shared: false,
+ launcherPath: null,
+ remoteFlag: false
+}
/** A Codex node's identity mode, as reported by the node's own launcher at spawn time.
* `plain` carries the machine-readable reason the managed identity was unavailable. */