graceful-terminate.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. import { type ChildProcess, spawn, spawnSync } from "node:child_process";
  2. import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { createRequire } from "node:module";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { afterEach, describe, expect, it } from "vitest";
  8. import { createLocalBashOperations } from "../src/core/tools/bash.ts";
  9. import { terminateProcessTreeGracefully } from "../src/utils/shell.ts";
  10. function isAlive(pid: number): boolean {
  11. try {
  12. process.kill(pid, 0);
  13. // An orphan killed by the guardian can remain briefly as a zombie on
  14. // macOS/Linux. It is already inert and must not be mistaken for a
  15. // still-running process tree merely because kill(pid, 0) succeeds.
  16. const state = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], {
  17. encoding: "utf8",
  18. }).stdout.trim();
  19. return state.length > 0 && !state.startsWith("Z");
  20. } catch {
  21. return false;
  22. }
  23. }
  24. // Unix-only: the SIGTERM→grace→SIGKILL escalation is signal-specific. On Windows
  25. // the analogue is `taskkill /T` (graceful) then `taskkill /F /T` (force); that
  26. // path has no catchable-signal semantics to assert here.
  27. describe.skipIf(process.platform === "win32")("terminateProcessTreeGracefully (Unix signals)", () => {
  28. const spawned: ChildProcess[] = [];
  29. afterEach(() => {
  30. for (const child of spawned.splice(0)) {
  31. if (child.pid && child.exitCode === null && child.signalCode === null) {
  32. try {
  33. process.kill(-child.pid, "SIGKILL");
  34. } catch {
  35. // Already gone.
  36. }
  37. }
  38. }
  39. });
  40. function spawnDetached(script: string): { child: ChildProcess; getStdout: () => string } {
  41. const child = spawn("/bin/bash", ["-c", script], {
  42. detached: true,
  43. stdio: ["ignore", "pipe", "pipe"],
  44. });
  45. spawned.push(child);
  46. let stdout = "";
  47. child.stdout?.on("data", (chunk: Buffer) => {
  48. stdout += chunk.toString();
  49. });
  50. return { child, getStdout: () => stdout };
  51. }
  52. function waitForExit(child: ChildProcess): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
  53. return new Promise((resolve) => {
  54. child.once("exit", (code, signal) => resolve({ code, signal }));
  55. });
  56. }
  57. async function waitFor(predicate: () => boolean, timeoutMs = 3000): Promise<void> {
  58. const start = Date.now();
  59. while (Date.now() - start < timeoutMs) {
  60. if (predicate()) return;
  61. await new Promise((resolve) => setTimeout(resolve, 20));
  62. }
  63. throw new Error("waitFor timed out");
  64. }
  65. it("sends SIGTERM first so a TERM trap runs its cleanup before exit", async () => {
  66. const { child, getStdout } = spawnDetached(
  67. `trap 'echo TRAPPED; exit 0' TERM; echo READY; while true; do sleep 0.05; done`,
  68. );
  69. await waitFor(() => getStdout().includes("READY"));
  70. const cancel = terminateProcessTreeGracefully(child.pid!);
  71. const { code, signal } = await waitForExit(child);
  72. cancel();
  73. // The trap fired (SIGTERM was delivered, not an uncatchable SIGKILL) and
  74. // the script exited on its own terms.
  75. expect(getStdout()).toContain("TRAPPED");
  76. expect(signal).toBeNull();
  77. expect(code).toBe(0);
  78. });
  79. it("escalates to SIGKILL when the process ignores SIGTERM past the grace window", async () => {
  80. const { child, getStdout } = spawnDetached(`trap '' TERM; echo READY; while true; do sleep 0.05; done`);
  81. await waitFor(() => getStdout().includes("READY"));
  82. const termination = terminateProcessTreeGracefully(child.pid!, 200);
  83. const { signal } = await waitForExit(child);
  84. await termination.settled;
  85. expect(signal).toBe("SIGKILL");
  86. });
  87. it("returns a canceller that disarms the pending SIGKILL escalation", async () => {
  88. const { child, getStdout } = spawnDetached(
  89. `trap 'echo TRAPPED; exit 0' TERM; echo READY; while true; do sleep 0.05; done`,
  90. );
  91. await waitFor(() => getStdout().includes("READY"));
  92. // A long grace window; the trap exits the process well before it elapses,
  93. // then we cancel so no late SIGKILL is aimed at a possibly-reused PID.
  94. const cancel = terminateProcessTreeGracefully(child.pid!, 10_000);
  95. await waitForExit(child);
  96. expect(() => cancel()).not.toThrow();
  97. });
  98. });
  99. // P1 regression: on abort, createLocalBashOperations must NOT cancel the SIGKILL
  100. // escalation while a SIGTERM-ignoring descendant is still alive in the group.
  101. // waitForChildProcess resolves when the shell exits, but a background child that
  102. // ignores SIGTERM keeps the group alive; cancelling then would leave it running.
  103. describe.skipIf(process.platform === "win32")("createLocalBashOperations abort escalation", () => {
  104. async function readPgidChildPid(markerFile: string): Promise<number> {
  105. const start = Date.now();
  106. const { readFileSync, existsSync } = await import("node:fs");
  107. while (Date.now() - start < 3000) {
  108. if (existsSync(markerFile)) {
  109. const pid = Number.parseInt(readFileSync(markerFile, "utf-8").trim(), 10);
  110. if (Number.isFinite(pid) && pid > 0) return pid;
  111. }
  112. await new Promise((resolve) => setTimeout(resolve, 20));
  113. }
  114. throw new Error("descendant pid marker never appeared");
  115. }
  116. it("still SIGKILLs a SIGTERM-ignoring descendant after abort (no early cancel)", async () => {
  117. const { mkdtempSync, rmSync } = await import("node:fs");
  118. const { tmpdir } = await import("node:os");
  119. const { join } = await import("node:path");
  120. const dir = mkdtempSync(join(tmpdir(), "graceful-abort-"));
  121. const marker = join(dir, "descendant.pid");
  122. let descendantPid = 0;
  123. const controller = new AbortController();
  124. // The shell backgrounds a child that ignores SIGTERM and records its PID,
  125. // installs its own quick TERM trap, then waits. On abort the shell's trap
  126. // exits fast (shell gone) but the backgrounded child must still be killed.
  127. const command =
  128. `bash -c 'trap "" TERM; echo $$ > ${marker}; while true; do sleep 0.1; done' & ` + `trap 'exit 0' TERM; wait`;
  129. const ops = createLocalBashOperations();
  130. const exec = ops.exec(command, dir, { onData: () => {}, signal: controller.signal });
  131. descendantPid = await readPgidChildPid(marker);
  132. expect(isAlive(descendantPid)).toBe(true);
  133. controller.abort();
  134. await exec.catch(() => {});
  135. try {
  136. // Give the grace-window escalation time to fire on the process group.
  137. const start = Date.now();
  138. while (Date.now() - start < 6000 && isAlive(descendantPid)) {
  139. await new Promise((resolve) => setTimeout(resolve, 50));
  140. }
  141. expect(isAlive(descendantPid)).toBe(false);
  142. } finally {
  143. if (descendantPid && isAlive(descendantPid)) {
  144. try {
  145. process.kill(descendantPid, "SIGKILL");
  146. } catch {
  147. // already gone
  148. }
  149. }
  150. rmSync(dir, { recursive: true, force: true });
  151. }
  152. });
  153. });
  154. describe.skipIf(process.platform === "win32")("createLocalBashOperations parent-death guard", () => {
  155. const waitUntil = async (predicate: () => boolean, timeoutMs: number): Promise<void> => {
  156. const deadline = Date.now() + timeoutMs;
  157. while (Date.now() < deadline) {
  158. if (predicate()) return;
  159. await new Promise((resolve) => setTimeout(resolve, 20));
  160. }
  161. throw new Error("waitUntil timed out");
  162. };
  163. it("stops the detached bash process group when its host is SIGKILLed", async () => {
  164. const { mkdtempSync, readFileSync, rmSync } = await import("node:fs");
  165. const { tmpdir } = await import("node:os");
  166. const { join } = await import("node:path");
  167. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-"));
  168. const marker = join(dir, "bash.pid");
  169. const fixture = fileURLToPath(new URL("./fixtures/parent-death-guard-host.ts", import.meta.url));
  170. const tsxLoader = createRequire(import.meta.url).resolve("tsx/esm");
  171. const host = spawn(process.execPath, ["--import", tsxLoader, fixture, marker], {
  172. cwd: dir,
  173. stdio: "ignore",
  174. });
  175. let bashPid = 0;
  176. try {
  177. await waitUntil(() => {
  178. try {
  179. bashPid = Number.parseInt(readFileSync(marker, "utf8").trim(), 10);
  180. return Number.isFinite(bashPid) && bashPid > 0 && isAlive(bashPid);
  181. } catch {
  182. return false;
  183. }
  184. }, 5000);
  185. host.kill("SIGKILL");
  186. await waitUntil(() => !isAlive(bashPid), 6000);
  187. expect(isAlive(bashPid)).toBe(false);
  188. } finally {
  189. if (host.pid && isAlive(host.pid)) host.kill("SIGKILL");
  190. if (bashPid && isAlive(bashPid)) {
  191. try {
  192. process.kill(-bashPid, "SIGKILL");
  193. } catch {
  194. // Already gone.
  195. }
  196. }
  197. rmSync(dir, { recursive: true, force: true });
  198. }
  199. });
  200. it("registers every target on the shared guardian before its command is released", async () => {
  201. const { mkdtempSync, readFileSync, rmSync } = await import("node:fs");
  202. const { tmpdir } = await import("node:os");
  203. const { join } = await import("node:path");
  204. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-shared-"));
  205. const markers = [join(dir, "first.pid"), join(dir, "second.pid")];
  206. const fixture = fileURLToPath(new URL("./fixtures/parent-death-guard-shared-host.ts", import.meta.url));
  207. const tsxLoader = createRequire(import.meta.url).resolve("tsx/esm");
  208. const host = spawn(process.execPath, ["--import", tsxLoader, fixture, ...markers], {
  209. cwd: dir,
  210. stdio: "ignore",
  211. });
  212. const bashPids = [0, 0];
  213. try {
  214. await waitUntil(() => {
  215. for (const [index, marker] of markers.entries()) {
  216. try {
  217. bashPids[index] = Number.parseInt(readFileSync(marker, "utf8").trim(), 10);
  218. } catch {
  219. return false;
  220. }
  221. }
  222. return bashPids.every((pid) => Number.isFinite(pid) && pid > 0 && isAlive(pid));
  223. }, 5000);
  224. host.kill("SIGKILL");
  225. await waitUntil(() => bashPids.every((pid) => !isAlive(pid)), 6000);
  226. expect(bashPids.every((pid) => !isAlive(pid))).toBe(true);
  227. } finally {
  228. if (host.pid && isAlive(host.pid)) host.kill("SIGKILL");
  229. for (const pid of bashPids) {
  230. if (!pid || !isAlive(pid)) continue;
  231. try {
  232. process.kill(-pid, "SIGKILL");
  233. } catch {
  234. // Already gone.
  235. }
  236. }
  237. rmSync(dir, { recursive: true, force: true });
  238. }
  239. });
  240. it("keeps a second lease armed when an older lease for the same PID disarms", async () => {
  241. const { mkdtempSync, readFileSync, rmSync } = await import("node:fs");
  242. const { tmpdir } = await import("node:os");
  243. const { join } = await import("node:path");
  244. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-lease-"));
  245. const marker = join(dir, "target.pid");
  246. const fixture = fileURLToPath(new URL("./fixtures/parent-death-guard-lease-host.ts", import.meta.url));
  247. const tsxLoader = createRequire(import.meta.url).resolve("tsx/esm");
  248. const host = spawn(process.execPath, ["--import", tsxLoader, fixture, marker], {
  249. cwd: dir,
  250. stdio: "ignore",
  251. });
  252. let targetPid = 0;
  253. try {
  254. await waitUntil(() => {
  255. try {
  256. targetPid = Number.parseInt(readFileSync(marker, "utf8").trim(), 10);
  257. return Number.isFinite(targetPid) && targetPid > 0 && isAlive(targetPid);
  258. } catch {
  259. return false;
  260. }
  261. }, 5000);
  262. host.kill("SIGKILL");
  263. await waitUntil(() => !isAlive(targetPid), 6000);
  264. expect(isAlive(targetPid)).toBe(false);
  265. } finally {
  266. if (host.pid && isAlive(host.pid)) host.kill("SIGKILL");
  267. if (targetPid && isAlive(targetPid)) {
  268. try {
  269. process.kill(-targetPid, "SIGKILL");
  270. } catch {
  271. // Already gone.
  272. }
  273. }
  274. rmSync(dir, { recursive: true, force: true });
  275. }
  276. });
  277. it("does not release a command canceled while guardian registration is pending", async () => {
  278. const { existsSync, mkdtempSync, rmSync } = await import("node:fs");
  279. const { tmpdir } = await import("node:os");
  280. const { join } = await import("node:path");
  281. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-cancel-"));
  282. const marker = join(dir, "must-not-run");
  283. const controller = new AbortController();
  284. try {
  285. const operations = createLocalBashOperations({ parentDeathGuard: true });
  286. const execution = operations.exec(`touch ${marker}`, dir, {
  287. onData: () => undefined,
  288. signal: controller.signal,
  289. });
  290. controller.abort("user stopped");
  291. await expect(execution).rejects.toThrow("aborted");
  292. expect(existsSync(marker)).toBe(false);
  293. } finally {
  294. rmSync(dir, { recursive: true, force: true });
  295. }
  296. });
  297. it("preserves the original PowerShell script as the shell command", async () => {
  298. const { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = await import("node:fs");
  299. const { tmpdir } = await import("node:os");
  300. const { join } = await import("node:path");
  301. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-pwsh-"));
  302. const fakePwsh = join(dir, "fake-pwsh");
  303. const marker = join(dir, "command.txt");
  304. const command = 'param([string]$Name)\n"hello $Name"';
  305. try {
  306. writeFileSync(
  307. fakePwsh,
  308. '#!/bin/sh\nfor argument do last="$argument"; done\nprintf "%s" "$last" > "$FAKE_PWSH_MARKER"\n',
  309. );
  310. chmodSync(fakePwsh, 0o755);
  311. const operations = createLocalBashOperations({ shellPath: fakePwsh, parentDeathGuard: true });
  312. await operations.exec(command, dir, {
  313. onData: () => undefined,
  314. env: { ...process.env, FAKE_PWSH_MARKER: marker },
  315. });
  316. expect(readFileSync(marker, "utf8")).toBe(command);
  317. } finally {
  318. rmSync(dir, { recursive: true, force: true });
  319. }
  320. });
  321. it("keeps FullLanguage Windows PowerShell setup outside the original script block", async () => {
  322. const { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = await import("node:fs");
  323. const { tmpdir } = await import("node:os");
  324. const { join } = await import("node:path");
  325. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-full-language-powershell-"));
  326. const fakePowerShell = join(dir, "fake-powershell");
  327. const marker = join(dir, "command.txt");
  328. const command = `#requires -Version 5.1\nusing namespace System.Text\nparam([string]$Name)\n#${"x".repeat(13_000)}\n"hello $Name"`;
  329. try {
  330. writeFileSync(
  331. fakePowerShell,
  332. [
  333. "#!/usr/bin/env node",
  334. 'const fs = require("node:fs");',
  335. "const launcher = process.argv.at(-1);",
  336. 'if (launcher === "$ExecutionContext.SessionState.LanguageMode") {',
  337. ' process.stdout.write("FullLanguage\\n");',
  338. " process.exit(0);",
  339. "}",
  340. 'process.stdin.setEncoding("utf8");',
  341. 'let source = "";',
  342. 'process.stdin.on("data", (chunk) => { source += chunk; });',
  343. 'process.stdin.on("end", () => {',
  344. " fs.writeFileSync(process.env.FAKE_POWERSHELL_MARKER, JSON.stringify({ launcher, source }));",
  345. "});",
  346. ].join("\n"),
  347. );
  348. chmodSync(fakePowerShell, 0o755);
  349. const operations = createLocalBashOperations({ shellPath: fakePowerShell });
  350. await operations.exec(command, dir, {
  351. onData: () => undefined,
  352. env: { ...process.env, FAKE_POWERSHELL_MARKER: marker },
  353. });
  354. const captured = JSON.parse(readFileSync(marker, "utf8")) as { launcher: string; source: string };
  355. expect(captured.source).toBe(command);
  356. expect(captured.launcher).toContain("OutputEncoding");
  357. expect(captured.launcher).toContain("ScriptRequirements");
  358. expect(captured.launcher).toContain("RequiredPSVersion");
  359. expect(captured.launcher).toContain("RequiredModules");
  360. expect(captured.launcher).toContain("ScriptBlock]::Create");
  361. expect(captured.launcher).not.toContain("$__mavisSource");
  362. expect(captured.launcher).not.toContain(".ps1");
  363. expect(captured.launcher.length).toBeLessThan(8192);
  364. } finally {
  365. rmSync(dir, { recursive: true, force: true });
  366. }
  367. });
  368. it("executes Windows PowerShell commands without restricted APIs in ConstrainedLanguage", async () => {
  369. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-powershell-"));
  370. const fakePowerShell = join(dir, "fake-powershell");
  371. const marker = join(dir, "command.txt");
  372. const command = `#requires -Version 5.1\nusing namespace System.Text\nparam([string]$Name)\n#${"x".repeat(13_000)}\n"你好 $Name"`;
  373. try {
  374. writeFileSync(
  375. fakePowerShell,
  376. [
  377. "#!/usr/bin/env node",
  378. 'const fs = require("node:fs");',
  379. "const launcher = process.argv.at(-1);",
  380. 'if (launcher === "$ExecutionContext.SessionState.LanguageMode") {',
  381. ' process.stdout.write("ConstrainedLanguage\\n");',
  382. " process.exit(0);",
  383. "}",
  384. 'const transport = launcher.match(/\\$env:([A-Z0-9_]+)/)?.[1];',
  385. "const source = transport ? process.env[transport] : undefined;",
  386. "const forbidden = [",
  387. ' "[Console]::",',
  388. ' "Parser]::ParseInput",',
  389. ' "ScriptBlock]::Create",',
  390. "].filter((value) => launcher.includes(value));",
  391. "fs.writeFileSync(",
  392. " process.env.FAKE_POWERSHELL_MARKER,",
  393. " JSON.stringify({ launcher, source, forbidden }),",
  394. ");",
  395. "process.exit(forbidden.length || !source ? 1 : 0);",
  396. ].join("\n"),
  397. );
  398. chmodSync(fakePowerShell, 0o755);
  399. const operations = createLocalBashOperations({ shellPath: fakePowerShell, parentDeathGuard: true });
  400. const result = await operations.exec(command, dir, {
  401. onData: () => undefined,
  402. env: { ...process.env, FAKE_POWERSHELL_MARKER: marker },
  403. });
  404. const captured = JSON.parse(readFileSync(marker, "utf8")) as {
  405. launcher: string;
  406. source: string;
  407. forbidden: string[];
  408. };
  409. expect(result.exitCode).toBe(0);
  410. expect(captured.source).toBe(command);
  411. expect(captured.forbidden).toEqual([]);
  412. expect(captured.launcher).toContain("Invoke-Expression");
  413. expect(captured.launcher).not.toContain("$__mavisSource");
  414. expect(captured.launcher).not.toContain(".ps1");
  415. expect(captured.launcher.length).toBeLessThan(1024);
  416. } finally {
  417. rmSync(dir, { recursive: true, force: true });
  418. }
  419. });
  420. it("does not apply NODE_OPTIONS to the guarded launcher", async () => {
  421. let output = "";
  422. const operations = createLocalBashOperations({ parentDeathGuard: true });
  423. const result = await operations.exec("echo OK", process.cwd(), {
  424. onData: (chunk) => {
  425. output += chunk.toString("utf8");
  426. },
  427. env: { ...process.env, NODE_OPTIONS: "--require=./missing-launcher-hook.cjs" },
  428. });
  429. expect(result.exitCode).toBe(0);
  430. expect(output.trim()).toBe("OK");
  431. });
  432. it("does not resolve the Unix guardian gate through the command PATH", async () => {
  433. const { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } = await import("node:fs");
  434. const { tmpdir } = await import("node:os");
  435. const { join } = await import("node:path");
  436. const dir = mkdtempSync(join(tmpdir(), "bash-parent-death-path-"));
  437. const fakeSh = join(dir, "sh");
  438. const marker = join(dir, "fake-sh-ran");
  439. let output = "";
  440. try {
  441. writeFileSync(fakeSh, '#!/bin/sh\n: > "$FAKE_SH_MARKER"\nexit 99\n');
  442. chmodSync(fakeSh, 0o755);
  443. const operations = createLocalBashOperations({ shellPath: "/bin/bash", parentDeathGuard: true });
  444. const result = await operations.exec("printf OK", dir, {
  445. onData: (chunk) => {
  446. output += chunk.toString("utf8");
  447. },
  448. env: { PATH: dir, FAKE_SH_MARKER: marker },
  449. });
  450. expect(result.exitCode).toBe(0);
  451. expect(output).toBe("OK");
  452. expect(existsSync(marker)).toBe(false);
  453. } finally {
  454. rmSync(dir, { recursive: true, force: true });
  455. }
  456. });
  457. it("keeps the user shell as its Unix process-group leader", async () => {
  458. let output = "";
  459. const operations = createLocalBashOperations({ parentDeathGuard: true });
  460. const result = await operations.exec('printf "%s %s" "$$" "$(ps -o pgid= -p $$ | tr -d " ")"', process.cwd(), {
  461. onData: (chunk) => {
  462. output += chunk.toString("utf8");
  463. },
  464. });
  465. const [shellPid, processGroupId] = output.trim().split(" ");
  466. expect(result.exitCode).toBe(0);
  467. expect(shellPid).toBe(processGroupId);
  468. });
  469. it("captures shell diagnostics emitted immediately after guarded launch", async () => {
  470. let output = "";
  471. const operations = createLocalBashOperations({ shellPath: "/bin/bash", parentDeathGuard: true });
  472. const result = await operations.exec("if then", process.cwd(), {
  473. onData: (chunk) => {
  474. output += chunk.toString("utf8");
  475. },
  476. });
  477. expect(result.exitCode).toBe(2);
  478. expect(output.toLowerCase()).toMatch(/syntax|unexpected/);
  479. });
  480. it("keeps guarded output open until delayed TERM cleanup finishes", async () => {
  481. let output = "";
  482. const controller = new AbortController();
  483. const operations = createLocalBashOperations({ parentDeathGuard: true });
  484. const execution = operations.exec(
  485. "trap 'sleep 0.3; echo DELAYED-CLEANUP; exit 0' TERM; echo READY; while true; do sleep 0.05; done",
  486. process.cwd(),
  487. {
  488. onData: (chunk) => {
  489. output += chunk.toString("utf8");
  490. },
  491. signal: controller.signal,
  492. },
  493. );
  494. await waitUntil(() => output.includes("READY"), 3000);
  495. controller.abort("user stopped");
  496. await expect(execution).rejects.toThrow("aborted");
  497. expect(output).toContain("DELAYED-CLEANUP");
  498. });
  499. });