Skip to content

Commit 930f063

Browse files
authored
Merge pull request #1027 from CodeAgentMobile/fix/spawn-capture-drain
fix(cli): one-shot capture waits for stdout to drain before settling
2 parents 36988f8 + 432c11d commit 930f063

1 file changed

Lines changed: 19 additions & 3 deletions

File tree

‎apps/cli/src/services/spawn-and-capture.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ export interface SpawnAndCaptureOpts {
5858
onFailedOutput?: (stdout: string) => void;
5959
}
6060

61+
/** How long after `exit` to wait for stdout to drain before settling anyway. */
62+
const EXIT_DRAIN_GRACE_MS = 500;
63+
6164
export async function spawnAndCapture(
6265
cmd: string,
6366
args: ReadonlyArray<string>,
@@ -107,17 +110,30 @@ export async function spawnAndCapture(
107110
activeChildren.delete(child);
108111
settle(null);
109112
});
110-
child.on('exit', (code) => {
113+
// `exit` can fire BEFORE the last stdout chunk is read (seen in CI: a
114+
// failed one-shot's "API_KEY_INVALID" lost), so settle on `close` — the
115+
// stdio streams are drained by then — with a short grace after `exit` for
116+
// a grandchild that keeps the pipe open (an agent's background daemon).
117+
let exitCode: number | null | undefined;
118+
const finish = (): void => {
111119
clearTimeout(timer);
112120
activeChildren.delete(child);
113-
if (code !== 0) {
121+
if (exitCode !== 0) {
114122
const failedOut = stdout.trim();
115-
if (failedOut) opts.onFailedOutput?.(failedOut);
123+
if (failedOut && !settled) opts.onFailedOutput?.(failedOut);
116124
settle(null);
117125
return;
118126
}
119127
const trimmed = stdout.trim();
120128
settle(trimmed.length > 0 ? trimmed : null);
129+
};
130+
child.on('exit', (code) => {
131+
exitCode = code;
132+
setTimeout(finish, EXIT_DRAIN_GRACE_MS).unref();
133+
});
134+
child.on('close', (code) => {
135+
if (exitCode === undefined) exitCode = code;
136+
finish();
121137
});
122138
});
123139
}

0 commit comments

Comments
 (0)