bash-direct-execution.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { mkdtemp, mkdir, open, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { setTimeout as sleep } from "node:timers/promises";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { NodeExecutionAdapter } from "../src/exec/node-execution-adapter.js";
  7. import { OutputCollector } from "../src/exec/output-collector.js";
  8. import { BashFileOutput } from "../src/exec/bash-file-output.js";
  9. import * as outputEncoding from "../src/exec/outputEncoding.js";
  10. import { resolveWindowsGitBashShell } from "../src/exec/bash-shell-provider.js";
  11. import type { ExecutionEvent, ExecutionRequest, ExecutionShellSelection } from "@zcode/contracts";
  12. const shells: ExecutionShellSelection[] =
  13. process.platform === "win32"
  14. ? [
  15. {
  16. dialect: "cmd",
  17. path: process.env.ComSpec ?? "cmd.exe",
  18. display: { name: "CMD" },
  19. source: "user-config",
  20. },
  21. ...(resolveWindowsGitBashShell(process.env)
  22. ? [
  23. {
  24. dialect: "git-bash" as const,
  25. path: resolveWindowsGitBashShell(process.env)!,
  26. display: { name: "Git Bash" },
  27. source: "user-config" as const,
  28. },
  29. ]
  30. : []),
  31. ]
  32. : [{ dialect: "posix", path: "/bin/bash", display: { name: "bash" }, source: "user-config" }];
  33. const cleanup: Array<() => Promise<void>> = [];
  34. afterEach(async () => {
  35. for (const dispose of cleanup.splice(0).reverse()) await dispose();
  36. vi.restoreAllMocks();
  37. });
  38. async function fixture(shell: ExecutionShellSelection, code: string) {
  39. const root = await mkdtemp(join(tmpdir(), "zcode-direct-"));
  40. const cwd = join(root, "中文 with spaces");
  41. await mkdir(cwd);
  42. const script = join(cwd, "writer.cjs");
  43. const release = join(cwd, "release");
  44. await writeFile(script, code);
  45. const adapter = new NodeExecutionAdapter({
  46. outputRootDir: root,
  47. progressThresholdMs: 0,
  48. progressIntervalMs: 20,
  49. });
  50. cleanup.push(async () => {
  51. await writeFile(release, "release").catch(() => undefined);
  52. await adapter.close();
  53. await rm(root, { recursive: true, force: true });
  54. });
  55. const request: ExecutionRequest = {
  56. command: {
  57. mode: "shell",
  58. shellProfile: "posix-bash",
  59. shellOverride: shell,
  60. command:
  61. shell.dialect === "cmd"
  62. ? '"%PROBE_NODE%" "%PROBE_SCRIPT%"'
  63. : '"$PROBE_NODE" "$PROBE_SCRIPT"',
  64. },
  65. cwd,
  66. timeoutMs: 10_000,
  67. env: { set: { PROBE_NODE: process.execPath, PROBE_SCRIPT: script, PROBE_RELEASE: release } },
  68. outputLimit: {
  69. maxInlineBytes: 30_000,
  70. maxArtifactBytes: 64 * 1024 ** 2,
  71. persistOutput: "always",
  72. },
  73. trace: {
  74. sessionId: "probe",
  75. attributes: { toolCallId: "direct" },
  76. } as ExecutionRequest["trace"],
  77. };
  78. return { adapter, request, release, path: join(root, "probe", "direct-stdout.log") };
  79. }
  80. const gatedWriter = `const fs = require('node:fs');
  81. fs.writeSync(1, 'file:' + fs.fstatSync(1).isFile() + ':' + fs.fstatSync(2).isFile() + '\\n');
  82. fs.writeSync(2, 'stderr-first\\n');
  83. const timer = setInterval(() => {
  84. if (!fs.existsSync(process.env.PROBE_RELEASE)) return;
  85. clearInterval(timer); fs.writeSync(1, 'last-no-newline');
  86. }, 10);`;
  87. describe.each(shells)("direct Bash $display.name", (shell) => {
  88. it.each(["foreground", "explicit", "auto_on_timeout", "start"] as const)(
  89. "resolves output encoding once and reuses it for output reads (%s)",
  90. async (mode) => {
  91. const resolveEncoding = vi
  92. .spyOn(outputEncoding, "resolveLegacyExecutionOutputEncoding")
  93. .mockReturnValueOnce("gb18030")
  94. .mockReturnValue("cp437");
  95. const { adapter, request, path, release } = await fixture(
  96. shell,
  97. `const fs = require('node:fs');
  98. const text = Buffer.from([0xd6, 0xd0, 0xce, 0xc4]);
  99. fs.writeSync(1, text);
  100. const timer = setInterval(() => {
  101. if (!fs.existsSync(process.env.PROBE_RELEASE)) return;
  102. clearInterval(timer); fs.writeSync(2, text);
  103. }, 10);`,
  104. );
  105. if (mode === "foreground") {
  106. await writeFile(release, "release");
  107. const outcome = await adapter.runBashWithBackgroundLifecycle(request, {
  108. mode: "auto_on_timeout",
  109. });
  110. expect(outcome.kind).toBe("foreground");
  111. if (outcome.kind === "foreground") expect(outcome.result.stdout.text).toBe("中文中文");
  112. } else {
  113. request.timeoutMs = mode === "auto_on_timeout" ? 20 : 10_000;
  114. const outcome =
  115. mode === "start"
  116. ? { kind: "backgrounded" as const, task: await adapter.start(request) }
  117. : await adapter.runBashWithBackgroundLifecycle(request, { mode });
  118. expect(outcome.kind).toBe("backgrounded");
  119. if (outcome.kind !== "backgrounded") throw new Error("expected background");
  120. const id = outcome.task.taskId;
  121. await vi.waitFor(async () => expect((await readFile(path)).length).toBe(4), {
  122. timeout: 5_000,
  123. });
  124. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  125. kind: "output",
  126. status: "running",
  127. output: "中文",
  128. });
  129. await writeFile(release, "release");
  130. const completed = await adapter.waitForBackgroundTask(id);
  131. expect(completed?.result?.stdout.text).toBe("中文中文");
  132. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  133. kind: "output",
  134. status: "completed",
  135. output: "中文中文",
  136. });
  137. }
  138. expect(resolveEncoding.mock.calls.length).toBe(1);
  139. },
  140. );
  141. it("does not probe output encoding when cancelled before preparation", async () => {
  142. const resolveEncoding = vi.spyOn(outputEncoding, "resolveLegacyExecutionOutputEncoding");
  143. const { adapter, request } = await fixture(shell, gatedWriter);
  144. const outcome = await adapter.runBashWithBackgroundLifecycle(
  145. request,
  146. { mode: "explicit" },
  147. { signal: AbortSignal.abort() },
  148. );
  149. expect(outcome).toMatchObject({ kind: "foreground", result: { status: "cancelled" } });
  150. expect(resolveEncoding.mock.calls.length).toBe(0);
  151. });
  152. it.each(["explicit", "auto_on_timeout"] as const)(
  153. "reads background output live and terminal with a bounded tail (%s)",
  154. async (mode) => {
  155. const { adapter, request, path, release } = await fixture(shell, gatedWriter);
  156. request.timeoutMs = 50;
  157. const outcome = await adapter.runBashWithBackgroundLifecycle(request, { mode });
  158. expect(outcome.kind).toBe("backgrounded");
  159. if (outcome.kind !== "backgrounded") return;
  160. const id = outcome.task.taskId;
  161. await vi.waitFor(async () => expect(await readFile(path, "utf8")).toContain("stderr-first"));
  162. expect(await adapter.readBackgroundBashOutput(id, "other-session")).toEqual({
  163. kind: "unavailable",
  164. workId: id,
  165. });
  166. const first = await adapter.readBackgroundBashOutput(id, "probe");
  167. expect(first).toMatchObject({ kind: "output", status: "running", outputPath: path });
  168. expect(Object.keys(first).sort()).toEqual([
  169. "kind",
  170. "output",
  171. "outputPath",
  172. "status",
  173. "truncated",
  174. "workId",
  175. ]);
  176. await writeFile(path, "old-prefix" + "x".repeat(9000) + "中文\r\nNEW");
  177. const second = await adapter.readBackgroundBashOutput(id, "probe");
  178. expect(second.kind).toBe("output");
  179. if (second.kind === "output") {
  180. expect(second.output).not.toContain("old-prefix");
  181. expect(second.output).toContain("中文\r\nNEW");
  182. expect(Buffer.byteLength(second.output)).toBeLessThanOrEqual(8192);
  183. expect(second.truncated).toBe(true);
  184. }
  185. await writeFile(release, "release");
  186. await adapter.waitForBackgroundTask(id);
  187. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  188. kind: "output",
  189. status: "completed",
  190. });
  191. await rm(path);
  192. expect(await adapter.readBackgroundBashOutput(id, "probe")).toMatchObject({
  193. kind: "read_failed",
  194. });
  195. expect(await adapter.readBackgroundBashOutput("other", "probe")).toEqual({
  196. kind: "unavailable",
  197. workId: "other",
  198. });
  199. },
  200. );
  201. it("does not expose cancellation as final while output settlement is still pending", async () => {
  202. const { adapter, request, path } = await fixture(shell, gatedWriter);
  203. const outcome = await adapter.runBashWithBackgroundLifecycle(request, { mode: "explicit" });
  204. if (outcome.kind !== "backgrounded") throw new Error("expected background");
  205. await vi.waitFor(async () => expect(await readFile(path, "utf8")).toContain("stderr-first"));
  206. let releaseRead!: () => void;
  207. const gate = new Promise<void>((resolve) => {
  208. releaseRead = resolve;
  209. });
  210. const original = BashFileOutput.prototype.result;
  211. vi.spyOn(BashFileOutput.prototype, "result").mockImplementation(async function (limit) {
  212. await gate;
  213. return original.call(this, limit);
  214. });
  215. try {
  216. await adapter.cancelBackgroundTask(outcome.task.taskId);
  217. expect(await adapter.readBackgroundBashOutput(outcome.task.taskId, "probe")).toMatchObject({
  218. kind: "output",
  219. status: "running",
  220. });
  221. } finally {
  222. releaseRead();
  223. }
  224. await vi.waitFor(async () =>
  225. expect(await adapter.readBackgroundBashOutput(outcome.task.taskId, "probe")).toMatchObject({
  226. kind: "output",
  227. status: "cancelled",
  228. }),
  229. );
  230. });
  231. it("rejects generic argv tasks even when the session matches", async () => {
  232. const { adapter, request } = await fixture(shell, gatedWriter);
  233. request.command = { mode: "argv", file: process.execPath, args: ["-e", gatedWriter] };
  234. const task = await adapter.start(request);
  235. expect(await adapter.readBackgroundBashOutput(task.taskId, "probe")).toEqual({
  236. kind: "unavailable",
  237. workId: task.taskId,
  238. });
  239. await adapter.cancelBackgroundTask(task.taskId);
  240. });
  241. it.each([false, true])(
  242. "retains more than 64 MiB with bounded head and complete tail (lifecycle=%s)",
  243. async (lifecycle) => {
  244. const { adapter, request } = await fixture(
  245. shell,
  246. `
  247. const fs = require('node:fs');
  248. fs.writeSync(1, 'HEAD');
  249. const chunk = Buffer.alloc(1024 * 1024, 120);
  250. for (let i = 0; i < 65; i++) fs.writeSync(1, chunk);
  251. fs.writeSync(2, 'TAIL');
  252. `,
  253. );
  254. const outcome = lifecycle
  255. ? await adapter.runBashWithBackgroundLifecycle(request, { mode: "auto_on_timeout" })
  256. : undefined;
  257. if (outcome) expect(outcome.kind).toBe("foreground");
  258. const result = outcome?.kind === "foreground" ? outcome.result : await adapter.run(request);
  259. expect(result.stdout.text).toHaveLength(30_000);
  260. expect(result.stdout.text.startsWith("HEAD")).toBe(true);
  261. expect(result.stdout).toMatchObject({
  262. bytes: 65 * 1024 ** 2 + 8,
  263. artifactBytes: 65 * 1024 ** 2 + 8,
  264. artifactTruncated: false,
  265. });
  266. const file = await open(result.stdout.artifactPath!, "r");
  267. try {
  268. const size = (await file.stat()).size;
  269. expect(size).toBe(65 * 1024 ** 2 + 8);
  270. const tail = Buffer.alloc(4);
  271. await file.read(tail, 0, 4, size - 4);
  272. expect(tail.toString()).toBe("TAIL");
  273. } finally {
  274. await file.close();
  275. }
  276. },
  277. );
  278. it("does not background an exited root while its result is being read", async () => {
  279. const { adapter, request } = await fixture(shell, "require('node:fs').writeSync(1, 'done')");
  280. request.timeoutMs = 1_000;
  281. const original = BashFileOutput.prototype.result;
  282. vi.spyOn(BashFileOutput.prototype, "result").mockImplementation(async function (maxBytes) {
  283. const result = await original.call(this, maxBytes);
  284. await sleep(1_100);
  285. return result;
  286. });
  287. const result = await adapter.runBashWithBackgroundLifecycle(request, {
  288. mode: "auto_on_timeout",
  289. });
  290. expect(result.kind).toBe("foreground");
  291. if (result.kind === "foreground") expect(result.result.stdout.text).toBe("done");
  292. });
  293. it("writes a regular file before exit without collector or chunk events", async () => {
  294. const { adapter, request, path, release } = await fixture(shell, gatedWriter);
  295. const append = vi.spyOn(OutputCollector.prototype, "append");
  296. const prepare = vi.spyOn(BashFileOutput.prototype, "prepare");
  297. const events: ExecutionEvent[] = [];
  298. const running = adapter.run(request, {
  299. onEvent: (event) => {
  300. events.push(event);
  301. },
  302. });
  303. await vi.waitFor(
  304. async () => expect(await readFile(path, "utf8")).toBe("file:true:true\nstderr-first\n"),
  305. { timeout: 5_000 },
  306. );
  307. await vi.waitFor(
  308. () =>
  309. expect(
  310. events.some(
  311. (event) => event.type === "progress" && event.stdoutTail?.includes("stderr-first"),
  312. ),
  313. ).toBe(true),
  314. { timeout: 5_000 },
  315. );
  316. expect(events.some((event) => event.type === "completed")).toBe(false);
  317. await writeFile(release, "go");
  318. const result = await running;
  319. expect(result.stdout.text).toBe("file:true:true\nstderr-first\nlast-no-newline");
  320. expect(result.stderr.text).toBe("");
  321. expect(append).not.toHaveBeenCalled();
  322. expect(prepare).toHaveBeenCalledTimes(1);
  323. expect(events.some((event) => event.type === "stdout" || event.type === "stderr")).toBe(false);
  324. });
  325. it.each(["explicit", "auto_on_timeout"] as const)(
  326. "keeps the same file through %s and detaches parent abort",
  327. async (mode) => {
  328. const { adapter, request, path, release } = await fixture(shell, gatedWriter);
  329. request.timeoutMs = 50;
  330. const abort = new AbortController();
  331. const prepare = vi.spyOn(BashFileOutput.prototype, "prepare");
  332. const watch = vi.spyOn(BashFileOutput.prototype, "watchLimit");
  333. const launch = await adapter.runBashWithBackgroundLifecycle(
  334. request,
  335. { mode },
  336. { signal: abort.signal },
  337. );
  338. expect(launch.kind).toBe("backgrounded");
  339. if (launch.kind !== "backgrounded") throw new Error("Expected background task");
  340. expect(launch.task.outputPath).toBe(path);
  341. await vi.waitFor(async () => expect(await readFile(path, "utf8")).toContain("stderr-first"), {
  342. timeout: 5_000,
  343. });
  344. abort.abort();
  345. expect((await adapter.getBackgroundTask(launch.task.taskId))?.status).toBe("running");
  346. await writeFile(release, "go");
  347. const result = await adapter.waitForBackgroundTask(launch.task.taskId);
  348. expect(result?.status).toBe("completed");
  349. expect(result?.result?.stdout.text).toContain("last-no-newline");
  350. expect(prepare).toHaveBeenCalledTimes(1);
  351. expect(watch).toHaveBeenCalledTimes(2);
  352. },
  353. );
  354. it("settles at root exit and allows inherited descendants to write afterward", async () => {
  355. const code = `const fs = require('node:fs'), {spawn} = require('node:child_process');
  356. fs.writeSync(1, 'root\\n');
  357. 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();`;
  358. const { adapter, request, path, release } = await fixture(shell, code);
  359. const launch = await adapter.runBashWithBackgroundLifecycle(request, { mode: "explicit" });
  360. if (launch.kind !== "backgrounded") throw new Error("Expected background task");
  361. const completed = await adapter.waitForBackgroundTask(launch.task.taskId);
  362. expect(completed?.result?.stdout.text).toBe("root\n");
  363. await writeFile(release, "go");
  364. await vi.waitFor(
  365. async () => expect(await readFile(path, "utf8")).toBe("root\nlate-out\nlate-err\n"),
  366. { timeout: 5_000 },
  367. );
  368. expect((await adapter.getBackgroundTask(launch.task.taskId))?.result).toEqual(
  369. completed?.result,
  370. );
  371. await sleep(20);
  372. });
  373. });