Skip to content

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): kill the one-shot engine child when its runner is stopped (#31)

Xialie Zhuang5a8a08f4f1ee
diff --git a/server/src/__tests__/agents-computer-engine.test.ts b/server/src/__tests__/agents-computer-engine.test.ts
index 9e94104..452364b 100644
--- a/server/src/__tests__/agents-computer-engine.test.ts
+++ b/server/src/__tests__/agents-computer-engine.test.ts
@@ -334,3 +334,97 @@ test('a multi-byte character split across pipe chunks is not corrupted', { skip:
assert.equal(r.sessionId, 'sess-utf8', 'a codepoint split mid-boundary must not corrupt the JSON')
assert.equal(r.usage?.output_tokens, 2)
})
+
+// ── one-shot engine children must die with their runner ─────────────────────
+// The persistent session is torn down by AgentRunner.stop(); the one-shot child
+// was not, because its AbortSignal came from a controller nothing ever aborted.
+// An orphan keeps a valid runtime token and the `cumora` shim on PATH, so it
+// goes on posting AS the agent while the replacement runner answers the same
+// messages — with the OLD persona the operator just changed.
+
+/** A fake engine shaped like a real one: it spawns a child that INHERITS its
+ * stdio and outlives it, the way `claude` does for every Bash tool command.
+ * That grandchild holds the stdout/stderr pipes open, so `close` may never fire
+ * after the engine is killed — which is why the abort path must settle on
+ * `exit`. Written in Node rather than shell so the process tree is identical on
+ * every platform (bash execs the last command, dash forks it). */
+async function fakeEngineWithLingeringChild(root: string): Promise<string> {
+ const binDir = join(root, 'bin')
+ await mkdir(binDir, { recursive: true })
+ const bin = join(binDir, 'claude')
+ await writeFile(
+ bin,
+ '#!/usr/bin/env node\n' +
+ "require('child_process').spawn('sleep', ['120'], { stdio: 'inherit' })\n" +
+ 'setTimeout(() => {}, 120000)\n',
+ 'utf8',
+ )
+ await chmod(bin, 0o755)
+ return binDir
+}
+
+async function runFakeEngine(binDir: string, home: string, signal: AbortSignal) {
+ return getAdapter('claude').run({
+ home,
+ prompt: 'go',
+ env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },
+ onLog: () => {},
+ signal,
+ })
+}
+
+test('an already-aborted signal kills the engine child immediately', { skip: IS_WIN }, async () => {
+ const root = await mkdtemp(join(tmpdir(), 'cumora-abort-'))
+ tempDirs.push(root)
+ const home = join(root, 'home')
+ await mkdir(home)
+ const binDir = await fakeEngineWithLingeringChild(root)
+
+ // The queued-turn case: the signal is ALREADY aborted by the time run() is
+ // reached, so a listener registered afterwards would never fire.
+ const ac = new AbortController()
+ ac.abort()
+
+ const r = await Promise.race([
+ runFakeEngine(binDir, home, ac.signal),
+ delay(15_000).then(() => 'ORPHANED' as const),
+ ])
+ assert.notEqual(r, 'ORPHANED', 'the child outlived its aborted signal — it would keep posting as the agent')
+ assert.notEqual((r as { exitCode: number }).exitCode, 0, 'a killed turn must not report success')
+})
+
+test('aborting mid-run kills the engine child', { skip: IS_WIN }, async () => {
+ const root = await mkdtemp(join(tmpdir(), 'cumora-abort2-'))
+ tempDirs.push(root)
+ const home = join(root, 'home')
+ await mkdir(home)
+ const binDir = await fakeEngineWithLingeringChild(root)
+
+ const ac = new AbortController()
+ const p = runFakeEngine(binDir, home, ac.signal)
+ await delay(150)
+ ac.abort()
+ const r = await Promise.race([p, delay(15_000).then(() => 'ORPHANED' as const)])
+ assert.notEqual(r, 'ORPHANED', 'abort must terminate the turn even when a grandchild holds the stdio pipes')
+ assert.notEqual((r as { exitCode: number }).exitCode, 0)
+})
+
+test('a normal run is unaffected by the abort wiring', { skip: IS_WIN }, async () => {
+ const root = await mkdtemp(join(tmpdir(), 'cumora-noabort-'))
+ tempDirs.push(root)
+ const binDir = join(root, 'bin')
+ const home = join(root, 'home')
+ await mkdir(binDir); await mkdir(home)
+ const fake = join(binDir, 'claude')
+ await writeFile(fake, '#!/bin/sh\necho ok\nexit 0\n', 'utf8')
+ await chmod(fake, 0o755)
+
+ const r = await getAdapter('claude').run({
+ home,
+ prompt: 'go',
+ env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },
+ onLog: () => {},
+ signal: new AbortController().signal,
+ })
+ assert.equal(r.exitCode, 0)
+})
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index e53f4c5..689a703 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -895,6 +895,12 @@ export function resolveEngineFastModel(
}
class AgentRunner {
+ /** Aborted once in stop(). Handed to every one-shot `adapter.run(...)` so the
+ * engine child dies with its runner, the way the persistent session already
+ * does. Without it those children were orphaned: they keep a valid runtime
+ * token and the `cumora` shim on PATH, so they go on posting AS the agent
+ * while the replacement runner independently answers the same messages. */
+ private readonly teardown = new AbortController()
private token = ''
private tokenExpiresAt = 0
private home: string
@@ -1109,6 +1115,11 @@ class AgentRunner {
this.beginStop()
this.engineSession?.stop()
this.engineSession = null
+ // Kill a one-shot engine child too. sync() tears a runner down on any
+ // config change (engine/model/persona) or unassign while the daemon keeps
+ // running, which is exactly where an orphan does damage: it would still be
+ // acting with the OLD persona the operator just replaced.
+ this.teardown.abort()
// Drain any hops queued at shutdown so the ledger doesn't lose the tail
// (e.g. the agent was mid-turn when the daemon restarts for an update).
this.hopReporter?.stop()
@@ -1685,7 +1696,7 @@ class AgentRunner {
// one-shot fallback (or codex `exec` path) also lands hops in the
// universal ledger.
onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),
- signal: new AbortController().signal,
+ signal: this.teardown.signal,
})
if (session?.sessionId) this.setSessionId(session.sessionId)
if (session && !session.alive) this.engineSession = null
@@ -1990,7 +2001,6 @@ class AgentRunner {
// maybeAgendaTurn for the same hook).
this.currentRunId = run?.runId ?? null
const stopRunBeat = this.beatRun(token, run?.runId)
- const controller = new AbortController()
let exitCode = 0
let engineError: string | null = null
let turnUsage: EngineUsage | undefined
@@ -2054,7 +2064,7 @@ class AgentRunner {
resumeSessionId,
onLog: (line) => this.logEngineLine(line),
onHopUsage: (r) => this.onEngineHop(r, 'agent-turn'),
- signal: controller.signal,
+ signal: this.teardown.signal,
})
if (result.sessionId) this.setSessionId(result.sessionId)
}
diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.ts
index b3e8913..9fece8a 100644
--- a/server/src/agents/computer/engine.ts
+++ b/server/src/agents/computer/engine.ts
@@ -421,6 +421,11 @@ function spawnEngine(
}
const onAbort = (): void => { child.kill('SIGTERM') }
signal.addEventListener('abort', onAbort, { once: true })
+ // A listener registered AFTER the abort event never fires. A turn that was
+ // still queued behind the concurrency gate when its runner was stopped would
+ // otherwise spawn a child nothing owns — with a live runtime token and the
+ // `cumora` shim on PATH.
+ if (signal.aborted) onAbort()
const stderrTail: string[] = []
const stdoutTail: string[] = []
@@ -490,12 +495,11 @@ function spawnEngine(
child.stdout?.on('data', (buf: Buffer) => pump('stdout', buf))
child.stderr?.on('data', (buf: Buffer) => pump('stderr', buf))
child.on('error', (err) => { signal.removeEventListener('abort', onAbort); reject(err) })
- child.on('close', (code, signalName) => {
+ let settled = false
+ const settle = (code: number | null, signalName: NodeJS.Signals | null): void => {
+ if (settled) return
+ settled = true
signal.removeEventListener('abort', onAbort)
- // Flush the held-back tail BEFORE resolving: the terminating `result`
- // event is usually the last line, and it carries the turn's usage.
- pump('stdout', null)
- pump('stderr', null)
const exitCode = code ?? (signalName ? 128 : 1)
resolve({
exitCode,
@@ -504,7 +508,22 @@ function spawnEngine(
usage,
model,
})
+ }
+ // Normal end: wait for 'close', so the last of stdout is parsed. Flush the
+ // held-back tail BEFORE resolving: the terminating `result` event is
+ // usually the last line, and it carries the turn's usage.
+ child.on('close', (code, signalName) => {
+ if (!settled) { pump('stdout', null); pump('stderr', null) }
+ settle(code, signalName)
})
+ // Torn-down end: 'close' waits for every inherited stdio pipe to reach EOF,
+ // and the engine's OWN children (Bash tool commands) hold those pipes — a
+ // grandchild that outlives the kill keeps them open, so 'close' may never
+ // fire at all. Once we've aborted, the turn is being discarded and its
+ // remaining output is moot, so settle on 'exit' instead. Without this the
+ // daemon's shutdown drain waits forever on a turn it already killed, and
+ // `busy` plus the big-brain slot are never released.
+ child.on('exit', (code, signalName) => { if (signal.aborted) settle(code, signalName) })
})
}