Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(byoa): tear down a Codex session when the thread handshake fails (#24)
Xialie Zhuang81e81def952f
diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.tsindex 8bc74b0..decd9ad 100644--- a/server/src/__tests__/agents-computer-engine.test.ts+++ b/server/src/__tests__/agents-computer-engine.test.ts@@ -13,8 +13,12 @@ import { getAdapter, resolveSpawn } from '../agents/computer/engine.js'const IS_WIN = process.platform === 'win32'const tempDirs: string[] = []+// Sessions spawn a child process. Track them so a FAILING assertion still tears+// the child down — otherwise it outlives the test and the runner never exits.+const liveSessions: Array<{ stop(): void }> = []afterEach(async () => {+ for (const s of liveSessions.splice(0)) { try { s.stop() } catch { /* already gone */ } }await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))})@@ -116,3 +120,101 @@ test('persistent Claude startup failure keeps stderr for first send', async () =assert.equal(r.shell, true, '.cmd must run via the shell')assert.equal(r.wantsStdinPrompt, true, '.cmd needs the big prompt via stdin')})++// ── Codex app-server handshake failures must kill the SESSION ────────────────+// The handshake is one-shot: threadReq is consumed at the initialize ack, and+// only a failed thread/resume re-issues a thread/start. So if the thread never+// opens, `ready` can never flip — and because the app-server SURVIVES rejecting+// the handshake, the session would keep reporting alive and the daemon would+// reuse it, parking every later prompt in queuedPrompt with nothing able to+// drain it. That is a permanently, silently dead agent.++/** A fake `codex app-server --listen stdio://`: acks `initialize`, then rejects+ * whatever thread request follows, and STAYS ALIVE — the condition that makes+ * the zombie possible. */+async function fakeCodexRejectingThread(root: string): Promise<string> {+ const binDir = join(root, 'bin')+ await mkdir(binDir, { recursive: true })+ const bin = join(binDir, 'codex')+ await writeFile(+ bin,+ '#!/usr/bin/env node\n' ++ "let buf = ''\n" ++ "process.stdin.on('data', (d) => {\n" ++ " buf += d.toString('utf8')\n" ++ " let nl\n" ++ " while ((nl = buf.indexOf('\\n')) >= 0) {\n" ++ ' const line = buf.slice(0, nl); buf = buf.slice(nl + 1)\n' ++ ' if (!line.trim()) continue\n' ++ ' let msg; try { msg = JSON.parse(line) } catch { continue }\n' ++ " if (msg.method === 'initialize') {\n" ++ " process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} }) + '\\n')\n" ++ " } else if (msg.method === 'thread/start' || msg.method === 'thread/resume') {\n" ++ " process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { message: 'unsupported model for this account' } }) + '\\n')\n" ++ ' }\n' ++ ' }\n' ++ '})\n' ++ // Never exit on our own: the whole point is an app-server that outlives a+ // rejected handshake.+ 'setInterval(() => {}, 1 << 30)\n',+ 'utf8',+ )+ await chmod(bin, 0o755)+ return binDir+}++async function startFakeCodexSession(opts: { resume?: string } = {}) {+ const root = await mkdtemp(join(tmpdir(), 'cumora-codex-'))+ tempDirs.push(root)+ const home = join(root, 'home')+ await mkdir(home, { recursive: true })+ const binDir = await fakeCodexRejectingThread(root)+ const logs: string[] = []+ const session = getAdapter('codex').startSession!({+ home,+ env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ resumeSessionId: opts.resume ?? null,+ onLog: (l) => logs.push(l),+ })+ assert.ok(session, 'codex adapter must start a persistent session on this platform')+ liveSessions.push(session!)+ return { session: session!, logs }+}++test('a Codex session whose thread never opens dies instead of wedging', { skip: IS_WIN }, async () => {+ const { session } = await startFakeCodexSession()++ const first = await session.send('first wake')+ assert.notEqual(first.exitCode, 0, 'the rejected handshake must fail the turn')+ assert.match(String(first.error), /unsupported model for this account/)++ // The session must NOT advertise itself as reusable: the daemon drops a+ // !alive session and spawns a clean one on the next wake.+ assert.equal(session.alive, false, 'a session that can never open a thread must not stay alive')++ // And a send() that still lands on it has to settle, not hang forever.+ const second = await Promise.race([+ session.send('second wake'),+ delay(1000).then(() => 'HUNG' as const),+ ])+ assert.notEqual(second, 'HUNG', 'a later turn must settle rather than park forever in queuedPrompt')+ assert.notEqual((second as { exitCode: number }).exitCode, 0)+ assert.match(String((second as { error?: string }).error), /unsupported model for this account/,+ 'the later turn should report the real handshake cause')+})++test('a Codex session whose resume fallback also fails dies instead of wedging', { skip: IS_WIN }, async () => {+ // thread/resume is rejected, the adapter retries with a fresh thread/start,+ // and that is rejected too — the second failure must still tear down.+ const { session } = await startFakeCodexSession({ resume: 'thread_stale' })++ const first = await session.send('first wake')+ assert.notEqual(first.exitCode, 0)+ assert.equal(session.alive, false, 'a failed resume AND failed fresh start must not leave a live zombie')++ const second = await Promise.race([+ session.send('second wake'),+ delay(1000).then(() => 'HUNG' as const),+ ])+ assert.notEqual(second, 'HUNG', 'a later turn must settle rather than park forever')+})diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 4515d07..e36b443 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -1005,6 +1005,9 @@ class CodexSession implements EngineSession {// thread params WITHOUT threadId — reused to start a FRESH thread if a resume fails.private readonly baseThreadParams: Record<string, unknown>private ready = false+ // Why the handshake died, when it did — so a send() landing after the teardown+ // reports the real cause instead of a generic "process gone".+ private handshakeError: string | null = nullprivate pending: { resolve: (r: EngineRunResult) => void } | null = nullprivate queuedPrompt: string | null = nullprivate activeTurnId: string | null = null@@ -1045,7 +1048,7 @@ class CodexSession implements EngineSession {send(prompt: string): Promise<EngineRunResult> {if (this.pending) return Promise.resolve({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.threadId })- if (!this.alive) return Promise.resolve({ exitCode: this.exitCode || 1, error: 'engine session is not alive (process gone)', sessionId: this.threadId })+ if (!this.alive) return Promise.resolve({ exitCode: this.exitCode || 1, error: this.handshakeError ?? 'engine session is not alive (process gone)', sessionId: this.threadId })return new Promise<EngineRunResult>((resolve) => {this.pending = { resolve }this.turnStart = { ...this.cum }@@ -1227,6 +1230,18 @@ class CodexSession implements EngineSession {private failPending(error: string): void {if (this.pending) this.settle(error)else this.onLog(`[codex] ${error}`)+ // A failure BEFORE the thread ever opened kills the SESSION, not just this+ // turn. The handshake is one-shot — threadReq is consumed at the initialize+ // ack, and only a failed thread/resume re-issues a thread/start — so `ready`+ // can never flip afterwards, and every later send() would park its prompt in+ // queuedPrompt with nothing left able to drain it (the daemon awaits that+ // promise forever, so the agent goes silently and permanently dead and its+ // big-brain slot never comes back). The app-server SURVIVES rejecting the+ // handshake (a malformed ~/.codex/config.toml, a model this account can't+ // use, protocol drift), so `alive` would keep advertising a usable session+ // and the daemon would reuse the zombie on every wake. Tear it down instead:+ // a !alive session is dropped and the next wake spawns a clean one.+ if (!this.ready) { this.handshakeError = error; this.stop() }}private die(code: number, why: string): void {const alreadyDown = this.exited