From 432c11d4491b6ea8e45c18fc823eb7658032860b Mon Sep 17 00:00:00 2001 From: Edgar Durand Date: Mon, 23 Nov 2026 16:54:22 -0300 Subject: [PATCH] fix(cli): one-shot capture waits for stdout to drain before settling spawnAndCapture settled on the child's `exit`, which can fire before the last stdout chunk is read: the v2.76.48 release gate lost a failed one-shot's output ("API_KEY_INVALID" -> ''), and a successful one-shot (preview detect, AI summary) could lose the tail of its answer the same way. Settle on `close` (stdio drained), with a 500 ms grace after `exit` for a grandchild that keeps the pipe open. Co-Authored-By: Claude Opus 5.5 --- apps/cli/src/services/spawn-and-capture.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/apps/cli/src/services/spawn-and-capture.ts b/apps/cli/src/services/spawn-and-capture.ts index 178cb647..8ee2f237 100644 --- a/apps/cli/src/services/spawn-and-capture.ts +++ b/apps/cli/src/services/spawn-and-capture.ts @@ -58,6 +58,9 @@ export interface SpawnAndCaptureOpts { onFailedOutput?: (stdout: string) => void; } +/** How long after `exit` to wait for stdout to drain before settling anyway. */ +const EXIT_DRAIN_GRACE_MS = 500; + export async function spawnAndCapture( cmd: string, args: ReadonlyArray, @@ -107,17 +110,30 @@ export async function spawnAndCapture( activeChildren.delete(child); settle(null); }); - child.on('exit', (code) => { + // `exit` can fire BEFORE the last stdout chunk is read (seen in CI: a + // failed one-shot's "API_KEY_INVALID" lost), so settle on `close` — the + // stdio streams are drained by then — with a short grace after `exit` for + // a grandchild that keeps the pipe open (an agent's background daemon). + let exitCode: number | null | undefined; + const finish = (): void => { clearTimeout(timer); activeChildren.delete(child); - if (code !== 0) { + if (exitCode !== 0) { const failedOut = stdout.trim(); - if (failedOut) opts.onFailedOutput?.(failedOut); + if (failedOut && !settled) opts.onFailedOutput?.(failedOut); settle(null); return; } const trimmed = stdout.trim(); settle(trimmed.length > 0 ? trimmed : null); + }; + child.on('exit', (code) => { + exitCode = code; + setTimeout(finish, EXIT_DRAIN_GRACE_MS).unref(); + }); + child.on('close', (code) => { + if (exitCode === undefined) exitCode = code; + finish(); }); }); }