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): close Pi process orphan window (#106)

OKNOTOKeb1de1cf10a3
diff --git a/server/src/__tests__/agents-computer-engine-pi.test.ts b/server/src/__tests__/agents-computer-engine-pi.test.ts
index 0a2f62b..96e7cbb 100644
--- a/server/src/__tests__/agents-computer-engine-pi.test.ts
+++ b/server/src/__tests__/agents-computer-engine-pi.test.ts
@@ -39,6 +39,10 @@ const mode = argv.includes('rpc') ? 'rpc' : argv.includes('json') ? 'json' : 'te
const sidIdx = argv.indexOf('--session-id')
const SID = sidIdx >= 0 ? argv[sidIdx + 1] : 'fake-session-' + mode
record({ argv, cwd: process.cwd() })
+if (scenario === 'ignore-eof') {
+ setInterval(() => {}, 1000)
+ process.on('SIGTERM', () => { record({ signal: 'SIGTERM' }); process.exit(0) })
+}
// A turn's worth of events for prompt text \`text\` (same shapes as real pi).
function emitTurn(text, extra) {
@@ -97,7 +101,7 @@ process.stdin.on('data', (d) => {
}
}
})
-process.stdin.on('end', () => process.exit(0))
+process.stdin.on('end', () => { if (scenario !== 'ignore-eof') process.exit(0) })
`
interface Fixture { root: string; binDir: string; home: string; log: string; env: NodeJS.ProcessEnv }
@@ -122,7 +126,7 @@ async function fixture(scenario = 'ok'): Promise<Fixture> {
return { root, binDir, home, log, env }
}
-async function fakeLog(f: Fixture): Promise<Array<{ argv?: string[]; cmd?: { type: string; id?: string; message?: string } }>> {
+async function fakeLog(f: Fixture): Promise<Array<{ argv?: string[]; cmd?: { type: string; id?: string; message?: string }; signal?: string }>> {
if (!existsSync(f.log)) return []
return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((l) => JSON.parse(l))
}
@@ -271,6 +275,40 @@ test('pi run() (one-shot) drives the same rpc path for exactly one turn and repo
await delay(100) // stdin closed → the fake exits on its own; nothing to assert beyond no hang
})
+test('pi already-aborted run and json one-shot never spawn a child', { skip: IS_WIN }, async () => {
+ const f = await fixture()
+ const controller = new AbortController()
+ controller.abort()
+
+ const run = await getAdapter('pi').run({
+ home: f.home, prompt: 'wake', env: f.env, model: null, fastModel: null,
+ resumeSessionId: null, onLog: () => {}, signal: controller.signal,
+ })
+ assert.equal(run.exitCode, 130)
+ assert.match(run.error ?? '', /aborted before start/)
+
+ const classify = await getAdapter('pi').classify({
+ cwd: f.home, prompt: 'triage', env: f.env, signal: controller.signal,
+ })
+ assert.match(classify.error ?? '', /aborted before start/)
+ assert.deepEqual(await fakeLog(f), [], 'an already-cancelled owner must not launch pi')
+})
+
+test('pi forced stop signals an EOF-resistant child before the daemon can exit', { skip: IS_WIN }, async () => {
+ const f = await fixture('ignore-eof')
+ const session = getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: () => {} })
+ assert.ok(session)
+
+ // Wait until the child has started and accepted get_state, then model the
+ // daemon's final shutdown path: there is no two-second timer opportunity.
+ for (let i = 0; i < 50 && (await fakeLog(f)).length < 2; i += 1) await delay(20)
+ session.stop({ force: true })
+ for (let i = 0; i < 50 && !(await fakeLog(f)).some((entry) => entry.signal === 'SIGTERM'); i += 1) await delay(20)
+
+ assert.ok((await fakeLog(f)).some((entry) => entry.signal === 'SIGTERM'), 'force stop must dispatch SIGTERM synchronously instead of relying on the delayed fallback')
+ assert.equal(session.alive, false)
+})
+
test('pi classify() runs a bare json one-shot and returns text + usage + the real model', { skip: IS_WIN }, async () => {
const f = await fixture()
const res = await getAdapter('pi').classify({
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index 5802341..6c6c652 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -1238,9 +1238,9 @@ class AgentRunner {
if (this.wakeDebounceTimer) { clearTimeout(this.wakeDebounceTimer); this.wakeDebounceTimer = null }
}
- stop(): void {
+ stop(options: { forceEngine?: boolean } = {}): void {
this.beginStop()
- this.engineSession?.stop()
+ this.engineSession?.stop({ force: options.forceEngine })
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
@@ -2667,7 +2667,9 @@ async function doRun(serverOverride?: string): Promise<void> {
const deadline = Date.now() + SHUTDOWN_GRACE_MS
if (anyBusy()) console.log(`[computer] ${why}: waiting up to ${Math.round(SHUTDOWN_GRACE_MS / 1000)}s for in-flight turn(s) to finish…`)
while (anyBusy() && Date.now() < deadline) await new Promise((r) => setTimeout(r, 500))
- for (const runner of runners.values()) runner.stop() // now tear down engine children
+ // process.exit() follows immediately, so engine-specific delayed fallbacks
+ // cannot run. Force each child to receive its termination signal first.
+ for (const runner of runners.values()) runner.stop({ forceEngine: true })
console.log(`[computer] shutting down (${why})`)
process.exit(0)
}
diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.ts
index 5523b1a..df41029 100644
--- a/server/src/agents/computer/engine.ts
+++ b/server/src/agents/computer/engine.ts
@@ -314,8 +314,10 @@ export interface EngineSession {
* daemon sends ONLY the per-turn delta; when false it inlines the standing
* prompt each turn (a one-shot path, or delivery failed). */
readonly carriesStandingPrompt: boolean
- /** Tear the process down (daemon shutdown / unrecoverable error). */
- stop(): void
+ /** Tear the process down (daemon shutdown / unrecoverable error). `force`
+ * skips any engine-specific graceful-exit delay when this daemon process is
+ * itself about to exit. */
+ stop(options?: { force?: boolean }): void
}
export interface EngineAdapter {
@@ -2907,6 +2909,11 @@ function spawnPiJson(
args: string[],
opts: { cwd: string; env: NodeJS.ProcessEnv; signal: AbortSignal; onLog?: (line: string) => void; shell: boolean; stdinText?: string; onHopUsage?: (r: EngineHopReport) => void },
): Promise<EngineRunResult & { text: string }> {
+ // A queued wake can be cancelled before it reaches the engine gate. Do not
+ // start a Pi process after its owner has already gone away.
+ if (opts.signal.aborted) {
+ return Promise.resolve({ exitCode: 130, error: 'engine turn aborted before start', sessionId: null, text: '' })
+ }
return new Promise((resolve) => {
const tracker = new PiTurnTracker(opts.onHopUsage)
const child = spawn(command, args, {
@@ -2919,6 +2926,9 @@ function spawnPiJson(
}
const onAbort = (): void => { child.kill('SIGTERM') }
opts.signal.addEventListener('abort', onAbort, { once: true })
+ // Close the small race between the pre-spawn check above and listener
+ // registration. AbortSignal does not replay an earlier abort event.
+ if (opts.signal.aborted) onAbort()
// StringDecoder + carried partial line, for the same reason spawnEngine has
// them: a pipe read chops a long event (a big message_end) at an arbitrary
// byte offset, and a naive per-chunk split would hand JSON.parse two halves.
@@ -3050,12 +3060,23 @@ class PiSession implements EngineSession {
if (this.pending && this.alive && text.trim()) this.write({ type: 'steer', message: stripLoneSurrogates(text) })
}
- stop(): void {
+ stop(options: { force?: boolean } = {}): void {
this.exited = true
- if (this.stopTimer) return
+ if (this.stopTimer) {
+ if (!options.force) return
+ clearTimeout(this.stopTimer)
+ this.stopTimer = null
+ }
// pi exits cleanly when stdin closes (it disposes the session and returns 0),
// so close stdin first and only SIGTERM a process that hasn't gone by itself.
try { this.child.stdin?.end() } catch { /* ignore */ }
+ // During daemon shutdown there is no event loop left to run the delayed
+ // fallback below. Dispatch SIGTERM synchronously before process.exit(), or a
+ // Pi that does not exit on EOF can be orphaned under the supervisor.
+ if (options.force) {
+ try { this.child.kill('SIGTERM') } catch { /* ignore */ }
+ return
+ }
this.stopTimer = setTimeout(() => { try { this.child.kill('SIGTERM') } catch { /* ignore */ } }, 2000)
this.stopTimer.unref?.()
}
@@ -3271,6 +3292,11 @@ class PiAdapter implements EngineAdapter {
}
async run(args: EngineRunArgs): Promise<EngineRunResult> {
+ // Unlike an abort listener registered below, this catches a turn cancelled
+ // while it was queued and avoids spawning the persistent RPC process at all.
+ if (args.signal.aborted) {
+ return { exitCode: 130, error: 'engine turn aborted before start', sessionId: args.resumeSessionId ?? null }
+ }
const flags = extraArgs('CUMORA_PI_ARGS')
if (flags.length) {
// User-owned flag set → one-shot print mode with their flags. We still pin
@@ -3289,8 +3315,11 @@ class PiAdapter implements EngineAdapter {
resumeSessionId: args.resumeSessionId, onLog: args.onLog, onHopUsage: args.onHopUsage,
})
if (!session) return { exitCode: 1, error: 'pi session could not be started', sessionId: args.resumeSessionId ?? null }
- const onAbort = (): void => session.stop()
+ const onAbort = (): void => session.stop({ force: true })
args.signal.addEventListener('abort', onAbort, { once: true })
+ // The signal may have flipped after the pre-spawn check but before the
+ // listener above was installed.
+ if (args.signal.aborted) onAbort()
try {
return await session.send(args.prompt)
} finally {