xonecas.io
64875
Mc

mini-coder / commit 92878b3

fix: avoid shell hangs from background jobs

xonecas2026-04-14 92878b399a26a70f508401cd2ab3f4e5ba623e55 parent 19c89cd

2 files changed

src/tools.test.ts+30−0
@@ -482,6 +482,36 @@ describe("shell", () => {
482482 }
483483 });
484484
485+ test("closes captured pipes after the shell exits so background writers do not keep running", async () => {
486+ const pidFile = join(tmp, "child.pid");
487+ const command =
488+ `bun -e "setInterval(() => process.stdout.write('tick\\n'), 50)" & ` +
489+ `echo $! > '${pidFile}'; echo ready`;
490+ let childPid: number | null = null;
491+
492+ try {
493+ const result = await Promise.race([
494+ executeShell({ command }, tmp),
495+ new Promise<never>((_, reject) => {
496+ setTimeout(() => {
497+ reject(new Error("Shell command did not return promptly"));
498+ }, 1_000);
499+ }),
500+ ]);
501+
502+ childPid = Number(readFileSync(pidFile, "utf-8").trim());
503+
504+ expect(result.isError).toBe(false);
505+ expect(resultText(result)).toContain("Exit code: 0");
506+ expect(resultText(result)).toContain("ready");
507+ await waitFor(() => childPid !== null && !isProcessAlive(childPid));
508+ } finally {
509+ if (childPid !== null && isProcessAlive(childPid)) {
510+ process.kill(childPid, "SIGKILL");
511+ }
512+ }
513+ });
514+
485515 test("abort signal kills spawned child processes that keep the shell pipes open", async () => {
486516 const controller = new AbortController();
487517 const pidFile = join(tmp, "child.pid");
src/tools.ts+131−60
@@ -9,15 +9,7 @@
99 * @module
1010 */
1111
12-import {
13- existsSync,
14- mkdirSync,
15- mkdtempSync,
16- readFileSync,
17- rmSync,
18- writeFileSync,
19-} from "node:fs";
20-import { tmpdir } from "node:os";
12+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2113 import { dirname, extname, isAbsolute, join } from "node:path";
2214 import type { ImageContent, TextContent, Tool } from "@mariozechner/pi-ai";
2315 import { Type } from "@mariozechner/pi-ai";
@@ -503,6 +495,7 @@ type ShellProcess = ReturnType<typeof Bun.spawn>;
503495 const DEFAULT_MAX_LINES = 1000;
504496 const DEFAULT_MAX_BYTES = 50_000;
505497 const SHELL_UPDATE_INTERVAL_MS = 75;
498+const SHELL_STREAM_DRAIN_TIMEOUT_MS = 25;
506499
507500 /** Format combined stdout/stderr for display in tool results. */
508501 function formatShellOutput(stdout: string, stderr: string): string {
@@ -847,52 +840,90 @@ function normalizeShellCommand(command: string): string {
847840 }
848841 }
849842
850-interface ShellCaptureFiles {
851- stdoutPath: string;
852- stderrPath: string;
853- cleanup: () => void;
843+interface ShellStreamCapture {
844+ done: Promise<void>;
845+ getOutput: () => string;
846+ isFinished: () => boolean;
847+ close: () => Promise<void>;
854848 }
855849
856-function createShellCaptureFiles(): ShellCaptureFiles {
857- const dir = mkdtempSync(join(tmpdir(), "mini-coder-shell-"));
850+function startShellStreamCapture(
851+ stream: ReadableStream<Uint8Array>,
852+ onChunk: (chunk: string) => void,
853+): ShellStreamCapture {
854+ const reader = stream.getReader();
855+ const decoder = new TextDecoder();
856+ let output = "";
857+ let closed = false;
858+ let finished = false;
859+
860+ const done = (async (): Promise<void> => {
861+ try {
862+ while (true) {
863+ const { done, value } = await reader.read();
864+ if (done) {
865+ break;
866+ }
867+
868+ const chunk = decoder.decode(value, { stream: true });
869+ output += chunk;
870+ onChunk(chunk);
871+ }
872+ } catch (error) {
873+ if (!closed) {
874+ throw error;
875+ }
876+ } finally {
877+ const trailing = decoder.decode();
878+ output += trailing;
879+ onChunk(trailing);
880+ finished = true;
881+ }
882+ })();
883+
858884 return {
859- stdoutPath: join(dir, "stdout.log"),
860- stderrPath: join(dir, "stderr.log"),
861- cleanup: () => {
862- try {
863- rmSync(dir, { recursive: true, force: true });
864- } catch {
865- // Best-effort cleanup. Background processes may still hold the files open.
885+ done,
886+ getOutput: () => output,
887+ isFinished: () => finished,
888+ close: async (): Promise<void> => {
889+ if (!finished) {
890+ closed = true;
891+ try {
892+ await reader.cancel();
893+ } catch {
894+ // Ignore cancellation errors while closing the pipe after exit/abort.
895+ }
866896 }
897+ await done;
867898 },
868899 };
869900 }
870901
871-function readShellCapture(path: string): string {
872- try {
873- return readFileSync(path, "utf-8");
874- } catch {
875- return "";
902+async function finalizeShellStreamCaptures(
903+ captures: readonly ShellStreamCapture[],
904+): Promise<void> {
905+ const pending = captures
906+ .filter((capture) => !capture.isFinished())
907+ .map((capture) => capture.done);
908+
909+ if (pending.length > 0) {
910+ await new Promise<void>((resolve) => {
911+ const timer = setTimeout(resolve, SHELL_STREAM_DRAIN_TIMEOUT_MS);
912+ void Promise.allSettled(pending).then(() => {
913+ clearTimeout(timer);
914+ resolve();
915+ });
916+ });
876917 }
877-}
878918
879-function readShellCaptureOutput(
880- capture: Pick<ShellCaptureFiles, "stdoutPath" | "stderrPath">,
881-): { stdout: string; stderr: string } {
882- return {
883- stdout: readShellCapture(capture.stdoutPath),
884- stderr: readShellCapture(capture.stderrPath),
885- };
919+ await Promise.all(captures.map((capture) => capture.close()));
886920 }
887921
888-function buildShellSpawnOptions(
889- cwd: string,
890- capture: Pick<ShellCaptureFiles, "stdoutPath" | "stderrPath">,
891-): Parameters<typeof Bun.spawn>[1] {
922+function buildShellSpawnOptions(cwd: string): Parameters<typeof Bun.spawn>[1] {
892923 return {
893924 cwd,
894- stdout: Bun.file(capture.stdoutPath),
895- stderr: Bun.file(capture.stderrPath),
925+ stdout: "pipe",
926+ stderr: "pipe",
896927 ...(process.platform === "win32" ? {} : { detached: true }),
897928 };
898929 }
@@ -957,14 +988,24 @@ export async function executeShell(
957988 const shell = process.env.SHELL || "/bin/sh";
958989 const maxLines = opts?.maxLines ?? DEFAULT_MAX_LINES;
959990 const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
960- const capture = createShellCaptureFiles();
961- let updateTimer: ReturnType<typeof setInterval> | null = null;
991+ let updateTimer: ReturnType<typeof setTimeout> | null = null;
962992 let cleanupAbort: (() => void) | null = null;
963993 let lastReportedOutput = "";
994+ let lastReportAt = 0;
995+ let stdoutCapture: ShellStreamCapture | null = null;
996+ let stderrCapture: ShellStreamCapture | null = null;
964997
965998 try {
999+ const clearPendingUpdate = (): void => {
1000+ if (updateTimer) {
1001+ clearTimeout(updateTimer);
1002+ updateTimer = null;
1003+ }
1004+ };
1005+
9661006 const buildOutput = (trimEnd: boolean): string => {
967- const { stdout, stderr } = readShellCaptureOutput(capture);
1007+ const stdout = stdoutCapture?.getOutput() ?? "";
1008+ const stderr = stderrCapture?.getOutput() ?? "";
9681009 return truncateOutput(
9691010 formatShellOutput(
9701011 trimEnd ? stdout.trimEnd() : stdout,
@@ -976,6 +1017,7 @@ export async function executeShell(
9761017 };
9771018
9781019 const emitUpdate = (): void => {
1020+ clearPendingUpdate();
9791021 if (!opts?.onUpdate) {
9801022 return;
9811023 }
@@ -986,30 +1028,54 @@ export async function executeShell(
9861028 }
9871029
9881030 lastReportedOutput = output;
1031+ lastReportAt = Date.now();
9891032 opts.onUpdate(textResult(output, false));
9901033 };
9911034
1035+ const scheduleUpdate = (): void => {
1036+ if (!opts?.onUpdate) {
1037+ return;
1038+ }
1039+
1040+ const elapsed = Date.now() - lastReportAt;
1041+ if (elapsed >= SHELL_UPDATE_INTERVAL_MS) {
1042+ emitUpdate();
1043+ return;
1044+ }
1045+ if (updateTimer) {
1046+ return;
1047+ }
1048+
1049+ updateTimer = setTimeout(() => {
1050+ emitUpdate();
1051+ }, SHELL_UPDATE_INTERVAL_MS - elapsed);
1052+ };
1053+
9921054 const command = normalizeShellCommand(args.command);
993- const proc = Bun.spawn(
994- [shell, "-c", command],
995- buildShellSpawnOptions(cwd, capture),
996- );
1055+ const proc = Bun.spawn([shell, "-c", command], buildShellSpawnOptions(cwd));
9971056 cleanupAbort = registerShellAbort(opts?.signal, proc);
998-
999- if (opts?.onUpdate) {
1000- updateTimer = setInterval(emitUpdate, SHELL_UPDATE_INTERVAL_MS);
1001- }
1057+ stdoutCapture = startShellStreamCapture(
1058+ proc.stdout as ReadableStream<Uint8Array>,
1059+ () => {
1060+ scheduleUpdate();
1061+ },
1062+ );
1063+ stderrCapture = startShellStreamCapture(
1064+ proc.stderr as ReadableStream<Uint8Array>,
1065+ () => {
1066+ scheduleUpdate();
1067+ },
1068+ );
10021069
10031070 const exitCode = await proc.exited;
1004-
1005- if (updateTimer) {
1006- clearInterval(updateTimer);
1007- updateTimer = null;
1008- }
10091071 cleanupAbort?.();
1072+ cleanupAbort = null;
10101073
1074+ await finalizeShellStreamCaptures([stdoutCapture, stderrCapture]);
1075+ clearPendingUpdate();
10111076 const output = buildOutput(true);
10121077 if (opts?.onUpdate && output && output !== lastReportedOutput) {
1078+ lastReportedOutput = output;
10131079 opts.onUpdate(textResult(output, false));
10141080 }
10151081
@@ -1018,14 +1084,19 @@ export async function executeShell(
10181084 return textResult(`Exit code: ${exitCode}\n${body}`, isError);
10191085 } catch (err) {
10201086 cleanupAbort?.();
1087+ cleanupAbort = null;
1088+ const captures = [stdoutCapture, stderrCapture].filter(
1089+ (capture): capture is ShellStreamCapture => capture !== null,
1090+ );
1091+ if (captures.length > 0) {
1092+ await Promise.allSettled(captures.map((capture) => capture.close()));
1093+ }
10211094 if (updateTimer) {
1022- clearInterval(updateTimer);
1095+ clearTimeout(updateTimer);
10231096 updateTimer = null;
10241097 }
10251098 const message = err instanceof Error ? err.message : String(err);
10261099 return textResult(`Shell error: ${message}`, true);
1027- } finally {
1028- capture.cleanup();
10291100 }
10301101 }