bash-direct-execution.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import { mkdtemp, mkdir, open, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join, relative, dirname } from "node:path";
  4. import * as fsPromises from "node:fs/promises";
  5. import { setTimeout as sleep } from "node:timers/promises";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. import { NodeExecutionAdapter } from "../src/exec/node-execution-adapter.js";
  8. import { OutputCollector } from "../src/exec/output-collector.js";
  9. import { BashFileOutput } from "../src/exec/bash-file-output.js";
  10. import * as outputEncoding from "../src/exec/outputEncoding.js";
  11. import { resolveWindowsGitBashShell } from "../src/exec/bash-shell-provider.js";
  12. import type { ExecutionEvent, ExecutionRequest, ExecutionShellSelection } from "@zcode/contracts";
  13. const shells: ExecutionShellSelection[] =
  14. process.platform === "win32"
  15. ? [
  16. {
  17. dialect: "cmd",
  18. path: process.env.ComSpec ?? "cmd.exe",
  19. display: { name: "CMD" },
  20. source: "user-config",
  21. },
  22. ...(resolveWindowsGitBashShell(process.env)
  23. ? [
  24. {
  25. dialect: "git-bash" as const,
  26. path: resolveWindowsGitBashShell(process.env)!,
  27. display: { name: "Git Bash" },
  28. source: "user-config" as const,
  29. },
  30. ]
  31. : []),
  32. ]
  33. : [{ dialect: "posix", path: "/bin/bash", display: { name: "bash" }, source: "user-config" }];
  34. const cleanup: Array<() => Promise<void>> = [];
  35. afterEach(async () => {
  36. for (const dispose of cleanup.splice(0).reverse()) await dispose();
  37. vi.restoreAllMocks();
  38. });
  39. async function fixture(shell: ExecutionShellSelection, code: string, useTmp = false) {
  40. const root = await mkdtemp(join(tmpdir(), "zcode-direct-"));
  41. const cwd = join(root, "中文 with spaces");
  42. await mkdir(cwd);
  43. const tempParent = join(root, "temporary-output");
  44. if (useTmp) await mkdir(tempParent);
  45. const script = join(cwd, "writer.cjs");
  46. const release = join(cwd, "release");
  47. await writeFile(script, code);
  48. const adapter = new NodeExecutionAdapter({
  49. outputRootDir: root,
  50. ...(useTmp ? { bashOutputTempDir: tempParent } : {}),
  51. progressThresholdMs: 0,
  52. progressIntervalMs: 20,
  53. });
  54. cleanup.push(async () => {
  55. await writeFile(release, "release").catch(() => undefined);
  56. await adapter.close();
  57. await rm(root, { recursive: true, force: true });
  58. });
  59. const request: ExecutionRequest = {
  60. command: {
  61. mode: "shell",
  62. shellProfile: "posix-bash",
  63. shellOverride: shell,
  64. command:
  65. shell.dialect === "cmd"
  66. ? '"%PROBE_NODE%" "%PROBE_SCRIPT%"'
  67. : '"$PROBE_NODE" "$PROBE_SCRIPT"',
  68. },
  69. cwd,
  70. timeoutMs: 10_000,
  71. env: { set: { PROBE_NODE: process.execPath, PROBE_SCRIPT: script, PROBE_RELEASE: release } },
  72. outputLimit: {
  73. maxInlineBytes: 30_000,
  74. maxArtifactBytes: 64 * 1024 ** 2,
  75. persistOutput: "always",
  76. },
  77. trace: {
  78. sessionId: "probe",
  79. attributes: { toolCallId: "direct" },
  80. } as ExecutionRequest["trace"],
  81. };
  82. return { adapter, request, release, tempParent, path: join(root, "probe", "direct-stdout.log") };
  83. }
  84. const gatedWriter = `const fs = require('node:fs');
  85. fs.writeSync(1, 'file:' + fs.fstatSync(1).isFile() + ':' + fs.fstatSync(2).isFile() + '\\n');
  86. fs.writeSync(2, 'stderr-first\\n');
  87. const timer = setInterval(() => {
  88. if (!fs.existsSync(process.env.PROBE_RELEASE)) return;
  89. clearInterval(timer); fs.writeSync(1, 'last-no-newline');
  90. }, 10);`;
  91. describe.each(shells)("direct Bash $display.name", (shell) => {
  92. it.each(["foreground", "explicit", "auto_on_timeout", "start"] as const)(
  93. "resolves output encoding once and reuses it for output reads (%s)",
  94. async (mode) => {
  95. const resolveEncoding = vi
  96. .spyOn(outputEncoding, "resolveLegacyExecutionOutputEncoding")
  97. .mockReturnValueOnce("gb18030")
  98. .mockReturnValue("cp437");
  99. const { adapter, request, path, release } = await fixture(
  100. shell,
  101. `const fs = require('node:fs');
  102. const text = Buffer.from([0xd6, 0xd0, 0xce, 0xc4]);
  103. fs.writeSync(1, text);
  104. const timer = setInterval(() => {
  105. if (!fs.existsSync(process.env.PROBE_RELEASE)) return;
  106. clearInterval(timer); fs.writeSync(2, text);
  107. }, 10);`,
  108. );
  109. if (mode === "foreground") {
  110. await writeFile(release, "release");
  111. const outcome = await adapter.runBashWithBackgroundLifecycle(request, {
  112. mode: "auto_on_timeout",
  113. });
  114. expect(outcome.kind).toBe("foreground");
  115. if (outcome.kind === "foreground") expect(outcome.result.stdout.text).toBe("中文中文");
  116. } else {
  117. request.timeoutMs = mode === "auto_on_timeout" ? 20 : 10_000;
  118. const outcome =
  119. mode === "start"
  120. ? { kind: "backgrounded" as const, task: await adapter.start(request) }
  121. : await adapter.runBashWithBackgroundLifecycle(request, { mode });
  122. expect(outcome.kind).toBe("backgrounded");
  123. if (outcome.kind !== "backgrounded") throw new Error("expected background");
  124. const id = outcome.task.taskId;
  125. await vi.waitFor(async () => expect((await readFile(path)).length).toBe(4), {
  126. timeout: 5_000,
  127. });
  128. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  129. kind: "output",
  130. status: "running",
  131. output: "中文",
  132. });
  133. await writeFile(release, "release");
  134. const completed = await adapter.waitForBackgroundTask(id);
  135. expect(completed?.result?.stdout.text).toBe("中文中文");
  136. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  137. kind: "output",
  138. status: "completed",
  139. output: "中文中文",
  140. });
  141. }
  142. expect(resolveEncoding.mock.calls.length).toBe(1);
  143. },
  144. );
  145. it("does not probe output encoding when cancelled before preparation", async () => {
  146. const resolveEncoding = vi.spyOn(outputEncoding, "resolveLegacyExecutionOutputEncoding");
  147. const { adapter, request } = await fixture(shell, gatedWriter);
  148. const outcome = await adapter.runBashWithBackgroundLifecycle(
  149. request,
  150. { mode: "explicit" },
  151. { signal: AbortSignal.abort() },
  152. );
  153. expect(outcome).toMatchObject({ kind: "foreground", result: { status: "cancelled" } });
  154. expect(resolveEncoding.mock.calls.length).toBe(0);
  155. });
  156. it.each(["explicit", "auto_on_timeout"] as const)(
  157. "reads background output live and terminal with a bounded tail (%s)",
  158. async (mode) => {
  159. const { adapter, request, path, release } = await fixture(shell, gatedWriter);
  160. request.timeoutMs = 50;
  161. const outcome = await adapter.runBashWithBackgroundLifecycle(request, { mode });
  162. expect(outcome.kind).toBe("backgrounded");
  163. if (outcome.kind !== "backgrounded") return;
  164. const id = outcome.task.taskId;
  165. await vi.waitFor(async () => expect(await readFile(path, "utf8")).toContain("stderr-first"));
  166. expect(await adapter.readBackgroundBashOutput(id, "other-session")).toEqual({
  167. kind: "unavailable",
  168. workId: id,
  169. });
  170. const first = await adapter.readBackgroundBashOutput(id, "probe");
  171. expect(first).toMatchObject({ kind: "output", status: "running", outputPath: path });
  172. expect(Object.keys(first).sort()).toEqual([
  173. "kind",
  174. "output",
  175. "outputPath",
  176. "status",
  177. "truncated",
  178. "workId",
  179. ]);
  180. await writeFile(path, "old-prefix" + "x".repeat(9000) + "中文\r\nNEW");
  181. const second = await adapter.readBackgroundBashOutput(id, "probe");
  182. expect(second.kind).toBe("output");
  183. if (second.kind === "output") {
  184. expect(second.output).not.toContain("old-prefix");
  185. expect(second.output).toContain("中文\r\nNEW");
  186. expect(Buffer.byteLength(second.output)).toBeLessThanOrEqual(8192);
  187. expect(second.truncated).toBe(true);
  188. }
  189. await writeFile(release, "release");
  190. await adapter.waitForBackgroundTask(id);
  191. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  192. kind: "output",
  193. status: "completed",
  194. });
  195. await rm(path);
  196. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  197. kind: "read_failed",
  198. });
  199. expect(await adapter.readBackgroundBashOutput("other", "probe")).toEqual({
  200. kind: "unavailable",
  201. workId: "other",
  202. });
  203. },
  204. );
  205. it("does not expose cancellation as final while output settlement is still pending", async () => {
  206. const { adapter, request, path } = await fixture(shell, gatedWriter);
  207. const outcome = await adapter.runBashWithBackgroundLifecycle(request, { mode: "explicit" });
  208. if (outcome.kind !== "backgrounded") throw new Error("expected background");
  209. await vi.waitFor(async () => expect(await readFile(path, "utf8")).toContain("stderr-first"));
  210. let releaseRead!: () => void;
  211. const gate = new Promise<void>((resolve) => {
  212. releaseRead = resolve;
  213. });
  214. const original = BashFileOutput.prototype.result;
  215. vi.spyOn(BashFileOutput.prototype, "result").mockImplementation(async function (limit) {
  216. await gate;
  217. return original.call(this, limit);
  218. });
  219. try {
  220. await adapter.cancelBackgroundTask(outcome.task.taskId);
  221. expect(await adapter.readBackgroundBashOutput(outcome.task.taskId, "probe")).toMatchObject({
  222. kind: "output",
  223. status: "running",
  224. });
  225. } finally {
  226. releaseRead();
  227. }
  228. await vi.waitFor(async () =>
  229. expect(await adapter.readBackgroundBashOutput(outcome.task.taskId, "probe")).toMatchObject({
  230. kind: "output",
  231. status: "cancelled",
  232. }),
  233. );
  234. });
  235. it("rejects generic argv tasks even when the session matches", async () => {
  236. const { adapter, request } = await fixture(shell, gatedWriter);
  237. request.command = { mode: "argv", file: process.execPath, args: ["-e", gatedWriter] };
  238. const task = await adapter.start(request);
  239. expect(await adapter.readBackgroundBashOutput(task.taskId, "probe")).toEqual({
  240. kind: "unavailable",
  241. workId: task.taskId,
  242. });
  243. await adapter.cancelBackgroundTask(task.taskId);
  244. });
  245. it.each([false, true])(
  246. "retains more than 64 MiB with bounded head and complete tail (lifecycle=%s)",
  247. async (lifecycle) => {
  248. const { adapter, request } = await fixture(
  249. shell,
  250. `
  251. const fs = require('node:fs');
  252. fs.writeSync(1, 'HEAD');
  253. const chunk = Buffer.alloc(1024 * 1024, 120);
  254. for (let i = 0; i < 65; i++) fs.writeSync(1, chunk);
  255. fs.writeSync(2, 'TAIL');
  256. `,
  257. );
  258. const outcome = lifecycle
  259. ? await adapter.runBashWithBackgroundLifecycle(request, { mode: "auto_on_timeout" })
  260. : undefined;
  261. if (outcome) expect(outcome.kind).toBe("foreground");
  262. const result = outcome?.kind === "foreground" ? outcome.result : await adapter.run(request);
  263. expect(result.stdout.text).toHaveLength(30_000);
  264. expect(result.stdout.text.startsWith("HEAD")).toBe(true);
  265. expect(result.stdout).toMatchObject({
  266. bytes: 65 * 1024 ** 2 + 8,
  267. artifactBytes: 65 * 1024 ** 2 + 8,
  268. artifactTruncated: false,
  269. });
  270. const file = await open(result.stdout.artifactPath!, "r");
  271. try {
  272. const size = (await file.stat()).size;
  273. expect(size).toBe(65 * 1024 ** 2 + 8);
  274. const tail = Buffer.alloc(4);
  275. await file.read(tail, 0, 4, size - 4);
  276. expect(tail.toString()).toBe("TAIL");
  277. } finally {
  278. await file.close();
  279. }
  280. },
  281. );
  282. it("does not background an exited root while its result is being read", async () => {
  283. const { adapter, request } = await fixture(shell, "require('node:fs').writeSync(1, 'done')");
  284. request.timeoutMs = 1_000;
  285. const original = BashFileOutput.prototype.result;
  286. vi.spyOn(BashFileOutput.prototype, "result").mockImplementation(async function (maxBytes) {
  287. const result = await original.call(this, maxBytes);
  288. await sleep(1_100);
  289. return result;
  290. });
  291. const result = await adapter.runBashWithBackgroundLifecycle(request, {
  292. mode: "auto_on_timeout",
  293. });
  294. expect(result.kind).toBe("foreground");
  295. if (result.kind === "foreground") expect(result.result.stdout.text).toBe("done");
  296. });
  297. it("writes a regular file before exit without collector or chunk events", async () => {
  298. const { adapter, request, path, release } = await fixture(shell, gatedWriter);
  299. const append = vi.spyOn(OutputCollector.prototype, "append");
  300. const prepare = vi.spyOn(BashFileOutput.prototype, "prepare");
  301. const events: ExecutionEvent[] = [];
  302. const running = adapter.run(request, {
  303. onEvent: (event) => {
  304. events.push(event);
  305. },
  306. });
  307. await vi.waitFor(
  308. async () => expect(await readFile(path, "utf8")).toBe("file:true:true\nstderr-first\n"),
  309. { timeout: 5_000 },
  310. );
  311. await vi.waitFor(
  312. () =>
  313. expect(
  314. events.some(
  315. (event) => event.type === "progress" && event.stdoutTail?.includes("stderr-first"),
  316. ),
  317. ).toBe(true),
  318. { timeout: 5_000 },
  319. );
  320. expect(events.some((event) => event.type === "completed")).toBe(false);
  321. await writeFile(release, "go");
  322. const result = await running;
  323. expect(result.stdout.text).toBe("file:true:true\nstderr-first\nlast-no-newline");
  324. expect(result.stderr.text).toBe("");
  325. expect(append).not.toHaveBeenCalled();
  326. expect(prepare).toHaveBeenCalledTimes(1);
  327. expect(events.some((event) => event.type === "stdout" || event.type === "stderr")).toBe(false);
  328. });
  329. it.each(["explicit", "auto_on_timeout"] as const)(
  330. "keeps the same file through %s and detaches parent abort",
  331. async (mode) => {
  332. const { adapter, request, path, release } = await fixture(shell, gatedWriter);
  333. request.timeoutMs = 50;
  334. const abort = new AbortController();
  335. const prepare = vi.spyOn(BashFileOutput.prototype, "prepare");
  336. const watch = vi.spyOn(BashFileOutput.prototype, "watchLimit");
  337. const launch = await adapter.runBashWithBackgroundLifecycle(
  338. request,
  339. { mode },
  340. { signal: abort.signal },
  341. );
  342. expect(launch.kind).toBe("backgrounded");
  343. if (launch.kind !== "backgrounded") throw new Error("Expected background task");
  344. expect(launch.task.outputPath).toBe(path);
  345. await vi.waitFor(async () => expect(await readFile(path, "utf8")).toContain("stderr-first"), {
  346. timeout: 5_000,
  347. });
  348. abort.abort();
  349. expect((await adapter.getBackgroundTask(launch.task.taskId))?.status).toBe("running");
  350. await writeFile(release, "go");
  351. const result = await adapter.waitForBackgroundTask(launch.task.taskId);
  352. expect(result?.status).toBe("completed");
  353. expect(result?.result?.stdout.text).toContain("last-no-newline");
  354. expect(prepare).toHaveBeenCalledTimes(1);
  355. expect(watch).toHaveBeenCalledTimes(2);
  356. },
  357. );
  358. it("settles at root exit and allows inherited descendants to write afterward", async () => {
  359. const code = `const fs = require('node:fs'), {spawn} = require('node:child_process');
  360. fs.writeSync(1, 'root\\n');
  361. spawn(process.execPath, ['-e', "const fs=require('node:fs');const t=setInterval(()=>{if(fs.existsSync(process.env.PROBE_RELEASE)){clearInterval(t);fs.writeSync(1,'late-out\\\\n');fs.writeSync(2,'late-err\\\\n');}},10)"], {stdio:['ignore',1,2],detached:true}).unref();`;
  362. const { adapter, request, path, release } = await fixture(shell, code);
  363. const launch = await adapter.runBashWithBackgroundLifecycle(request, { mode: "explicit" });
  364. if (launch.kind !== "backgrounded") throw new Error("Expected background task");
  365. const completed = await adapter.waitForBackgroundTask(launch.task.taskId);
  366. expect(completed?.result?.stdout.text).toBe("root\n");
  367. await writeFile(release, "go");
  368. await vi.waitFor(
  369. async () => expect(await readFile(path, "utf8")).toBe("root\nlate-out\nlate-err\n"),
  370. { timeout: 5_000 },
  371. );
  372. expect((await adapter.getBackgroundTask(launch.task.taskId))?.result).toEqual(
  373. completed?.result,
  374. );
  375. await sleep(20);
  376. });
  377. });
  378. describe.each(shells)("temporary Bash output $display.name", (shell) => {
  379. it.each(["run", "foreground", "explicit", "auto_on_timeout", "start"] as const)(
  380. "publishes one prepared file across the entire execution (%s)",
  381. async (mode) => {
  382. const { adapter, request, release, tempParent, path } = await fixture(
  383. shell,
  384. gatedWriter,
  385. true,
  386. );
  387. const prepare = vi.spyOn(BashFileOutput.prototype, "prepare");
  388. const append = vi.spyOn(OutputCollector.prototype, "append");
  389. const watch = vi.spyOn(BashFileOutput.prototype, "watchLimit");
  390. const encoding = vi.spyOn(outputEncoding, "resolveLegacyExecutionOutputEncoding");
  391. let actualPath: string;
  392. if (mode === "run" || mode === "foreground") {
  393. await writeFile(release, "go");
  394. const result =
  395. mode === "run"
  396. ? await adapter.run(request)
  397. : await adapter
  398. .runBashWithBackgroundLifecycle(request, { mode: "auto_on_timeout" })
  399. .then((outcome) => {
  400. if (outcome.kind !== "foreground") throw new Error("expected foreground");
  401. return outcome.result;
  402. });
  403. expect(result.status).toBe("completed");
  404. actualPath = result.stdout.artifactPath!;
  405. } else {
  406. request.timeoutMs = mode === "auto_on_timeout" ? 20 : 10_000;
  407. const task =
  408. mode === "start"
  409. ? await adapter.start(request)
  410. : await adapter.runBashWithBackgroundLifecycle(request, { mode }).then((outcome) => {
  411. if (outcome.kind !== "backgrounded") throw new Error("expected background");
  412. return outcome.task;
  413. });
  414. actualPath = task.outputPath!;
  415. expect(task.stdoutPersistedOutputPath).toBe(actualPath);
  416. // Windows Git Bash 启动可能超过默认的一秒;仍以实际输出标记确认就绪。
  417. await vi.waitFor(
  418. async () => expect(await readFile(actualPath, "utf8")).toContain("stderr-first"),
  419. { timeout: 5_000 },
  420. );
  421. expect(await adapter.readBackgroundBashOutput(task.taskId, "probe")).toMatchObject({
  422. kind: "output",
  423. outputPath: actualPath,
  424. status: "running",
  425. });
  426. await writeFile(release, "go");
  427. const done = await adapter.waitForBackgroundTask(task.taskId);
  428. expect(done?.result?.stdout.artifactPath).toBe(actualPath);
  429. }
  430. expect(relative(tempParent, actualPath)).toMatch(
  431. /^zcode-bash-[^/\\]+[/\\]probe[/\\]direct-stdout\.log$/,
  432. );
  433. expect(prepare).toHaveBeenCalledTimes(1);
  434. expect(encoding).toHaveBeenCalledTimes(1);
  435. expect(append).not.toHaveBeenCalled();
  436. expect(watch).toHaveBeenCalled();
  437. expect(watch.mock.instances.every((file) => file === prepare.mock.instances[0])).toBe(true);
  438. expect(await readFile(actualPath, "utf8")).toBe(
  439. "file:true:true\nstderr-first\nlast-no-newline",
  440. );
  441. await expect(fsPromises.stat(path)).rejects.toMatchObject({ code: "ENOENT" });
  442. await adapter.close();
  443. expect(await readFile(actualPath, "utf8")).toContain("last-no-newline");
  444. },
  445. );
  446. it.each(["EACCES", "EPERM", "EROFS", "ENOENT", "ENOTDIR", "ENOSPC", "EDQUOT"])(
  447. "reuses the configured fallback after a tmp open failure (%s)",
  448. async (code) => {
  449. const { adapter, request, release, tempParent, path } = await fixture(
  450. shell,
  451. gatedWriter,
  452. true,
  453. );
  454. const original = BashFileOutput.prototype.prepare;
  455. const attempts: string[] = [];
  456. vi.spyOn(BashFileOutput.prototype, "prepare").mockImplementation(async function () {
  457. attempts.push(this.path);
  458. if (this.path.startsWith(tempParent))
  459. throw Object.assign(new Error("tmp unavailable"), { code });
  460. return original.call(this);
  461. });
  462. await writeFile(release, "go");
  463. const started = vi.fn();
  464. const result = await adapter.run(request, {
  465. onEvent: (event) => {
  466. if (event.type === "started") started();
  467. },
  468. });
  469. expect(result.status).toBe("completed");
  470. expect(result.stdout.artifactPath).toBe(path);
  471. expect(await readFile(path, "utf8")).toBe("file:true:true\nstderr-first\nlast-no-newline");
  472. expect(attempts).toHaveLength(2);
  473. expect(attempts[1]).toBe(path);
  474. expect(started).toHaveBeenCalledTimes(1);
  475. },
  476. );
  477. it.each(["small", "large"])("preserves foreground %s output retention in tmp", async (size) => {
  478. const { adapter, request, release, tempParent } = await fixture(shell, gatedWriter, true);
  479. request.outputLimit = {
  480. persistOutput: "on_truncate",
  481. maxInlineBytes: size === "small" ? 30_000 : 16,
  482. };
  483. const prepare = vi.spyOn(BashFileOutput.prototype, "prepare");
  484. await writeFile(release, "go");
  485. const outcome = await adapter.runBashWithBackgroundLifecycle(request, {
  486. mode: "auto_on_timeout",
  487. });
  488. if (outcome.kind !== "foreground") throw new Error("expected foreground");
  489. expect(outcome.result.status).toBe("completed");
  490. const path = prepare.mock.instances[0]!.path;
  491. expect(path.startsWith(tempParent)).toBe(true);
  492. if (size === "small") {
  493. expect(outcome.result.stdout.artifactPath).toBeUndefined();
  494. await expect(fsPromises.stat(path)).rejects.toMatchObject({ code: "ENOENT" });
  495. } else {
  496. expect(outcome.result.stdout.artifactPath).toBe(path);
  497. expect(await readFile(path, "utf8")).toContain("last-no-newline");
  498. }
  499. });
  500. it.each(["unexpected", "both-fail"])(
  501. "does not spawn after preparation failure (%s)",
  502. async (mode) => {
  503. const { adapter, request, tempParent } = await fixture(shell, gatedWriter, true);
  504. const attempts: string[] = [];
  505. vi.spyOn(BashFileOutput.prototype, "prepare").mockImplementation(async function () {
  506. attempts.push(this.path);
  507. throw Object.assign(new Error("open failed"), {
  508. code: mode === "both-fail" && this.path.startsWith(tempParent) ? "EACCES" : "EMFILE",
  509. });
  510. });
  511. const events: ExecutionEvent[] = [];
  512. const result = await adapter.runBashWithBackgroundLifecycle(
  513. request,
  514. { mode: "explicit" },
  515. {
  516. onEvent: (event) => {
  517. events.push(event);
  518. },
  519. },
  520. );
  521. expect(result).toMatchObject({ kind: "foreground", result: { status: "spawn_error" } });
  522. expect(events.some((event) => event.type === "started")).toBe(false);
  523. expect(attempts).toHaveLength(mode === "both-fail" ? 2 : 1);
  524. },
  525. );
  526. it("does not cache a failed tmp directory creation and shares a successful directory", async () => {
  527. const { adapter, request, release, tempParent, path } = await fixture(shell, gatedWriter, true);
  528. await rm(tempParent, { recursive: true });
  529. await writeFile(release, "go");
  530. expect((await adapter.run(request)).stdout.artifactPath).toBe(path);
  531. await mkdir(tempParent);
  532. const next = () => ({
  533. ...request,
  534. trace: { ...request.trace!, attributes: { toolCallId: crypto.randomUUID() } },
  535. });
  536. const results = await Promise.all([adapter.run(next()), adapter.run(next())]);
  537. expect(results.every((result) => result.status === "completed")).toBe(true);
  538. expect(results[0].stdout.artifactPath!.startsWith(tempParent)).toBe(true);
  539. expect(dirname(results[0].stdout.artifactPath!)).toBe(dirname(results[1].stdout.artifactPath!));
  540. expect(await fsPromises.readdir(tempParent)).toHaveLength(1);
  541. });
  542. it("reports preparation errors through the generic background event and result paths", async () => {
  543. const { adapter, request } = await fixture(shell, gatedWriter, true);
  544. vi.spyOn(BashFileOutput.prototype, "prepare").mockRejectedValue(
  545. Object.assign(new Error("too many open files"), { code: "EMFILE" }),
  546. );
  547. const events: ExecutionEvent[] = [];
  548. const task = await adapter.start(request, {
  549. onEvent: (event) => {
  550. events.push(event);
  551. },
  552. });
  553. const result = await adapter.waitForBackgroundTask(task.taskId);
  554. expect(result?.status).toBe("spawn_error");
  555. expect(task.outputPath).toBeUndefined();
  556. expect(events.some((event) => event.type === "started")).toBe(false);
  557. expect(events.some((event) => event.type === "failed")).toBe(true);
  558. });
  559. it.each(["abort", "close"] as const)(
  560. "releases a file when %s wins during preparation",
  561. async (mode) => {
  562. const { adapter, request } = await fixture(shell, gatedWriter, true);
  563. const controller = new AbortController();
  564. let release!: () => void;
  565. let ready!: () => void;
  566. const gate = new Promise<void>((resolve) => {
  567. release = resolve;
  568. });
  569. const opened = new Promise<void>((resolve) => {
  570. ready = resolve;
  571. });
  572. const original = BashFileOutput.prototype.prepare;
  573. let file!: BashFileOutput;
  574. vi.spyOn(BashFileOutput.prototype, "prepare").mockImplementation(async function () {
  575. file = this;
  576. await original.call(this);
  577. ready();
  578. await gate;
  579. });
  580. const events: ExecutionEvent[] = [];
  581. const running = adapter.runBashWithBackgroundLifecycle(
  582. request,
  583. { mode: "explicit" },
  584. {
  585. signal: controller.signal,
  586. onEvent: (event) => {
  587. events.push(event);
  588. },
  589. },
  590. );
  591. await opened;
  592. let closing: Promise<void> | undefined;
  593. try {
  594. if (mode === "abort") controller.abort();
  595. else closing = adapter.close();
  596. } finally {
  597. release();
  598. }
  599. expect(await running).toMatchObject({ kind: "foreground", result: { status: "cancelled" } });
  600. await closing;
  601. expect(events.some((event) => event.type === "started")).toBe(false);
  602. expect(file.fd).toBeUndefined();
  603. await expect(fsPromises.stat(file.path)).rejects.toMatchObject({ code: "ENOENT" });
  604. },
  605. );
  606. it("keeps the configured fallback when a request is reused after a tmp success", async () => {
  607. const { adapter, request, release, tempParent, path } = await fixture(shell, gatedWriter, true);
  608. await writeFile(release, "go");
  609. expect((await adapter.run(request)).stdout.artifactPath!.startsWith(tempParent)).toBe(true);
  610. const original = BashFileOutput.prototype.prepare;
  611. vi.spyOn(BashFileOutput.prototype, "prepare").mockImplementation(async function () {
  612. if (this.path.startsWith(tempParent))
  613. throw Object.assign(new Error("tmp denied"), { code: "EACCES" });
  614. return original.call(this);
  615. });
  616. expect((await adapter.run(request)).stdout.artifactPath).toBe(path);
  617. });
  618. });