bash-direct-execution.test.ts 26 KB

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