bash-resource-lifecycle.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { ExecutionRequest, ExecutionShellSelection } from "@zcode/contracts";
  5. import type { ZCodeToolExecResource } from "@zcode/shared";
  6. import { describe, expect, it, vi } from "vitest";
  7. import { NodeExecutionAdapter } from "../src/exec/node-execution-adapter.js";
  8. describe("Bash 执行适配器资源生命周期", () => {
  9. it("真实 Bash 退出保留输出和 exit code,资源耗时从 spawn 起算", async () => {
  10. const root = await mkdtemp(join(tmpdir(), "bash-resource-"));
  11. const onToolExecResource = vi.fn();
  12. const adapter = new NodeExecutionAdapter({ outputRootDir: root, onToolExecResource });
  13. let now = 0;
  14. vi.spyOn(performance, "now").mockImplementation(() => now);
  15. try {
  16. const result = await adapter.run(
  17. {
  18. command: {
  19. mode: "shell",
  20. shellProfile: "posix-bash",
  21. shellOverride: shell,
  22. command: "echo telemetry-output && exit 7",
  23. },
  24. cwd: root,
  25. },
  26. {
  27. onEvent: (event) => {
  28. if (event.type === "started") now = 40000;
  29. },
  30. },
  31. );
  32. expect(result.stdout.text).toContain("telemetry-output");
  33. expect(result.exitCode).toBe(7);
  34. expect(onToolExecResource).toHaveBeenCalledExactlyOnceWith(
  35. expect.objectContaining({ durationMs: 40000, exitKind: "completed", toolName: "bash" }),
  36. );
  37. } finally {
  38. vi.restoreAllMocks();
  39. await adapter.close();
  40. await rm(root, { recursive: true, force: true });
  41. }
  42. });
  43. });
  44. const shell: ExecutionShellSelection =
  45. process.platform === "win32"
  46. ? {
  47. dialect: "cmd",
  48. path: process.env.ComSpec ?? "cmd.exe",
  49. display: { name: "CMD" },
  50. source: "user-config",
  51. }
  52. : { dialect: "posix", path: "/bin/bash", display: { name: "Bash" }, source: "user-config" };
  53. async function gatedCommand(
  54. onToolExecResource: NonNullable<
  55. ConstructorParameters<typeof NodeExecutionAdapter>[0]
  56. >["onToolExecResource"],
  57. ) {
  58. const root = await mkdtemp(join(tmpdir(), "bash-resource-gated-"));
  59. const script = join(root, "command.cjs");
  60. const release = join(root, "release");
  61. await writeFile(
  62. script,
  63. `const fs = require('node:fs/promises');
  64. process.stdout.write('ready\\n');
  65. const timer = setInterval(async () => {
  66. try { await fs.access(process.env.PROBE_RELEASE); clearInterval(timer); }
  67. catch {}
  68. }, 10);`,
  69. );
  70. const adapter = new NodeExecutionAdapter({ outputRootDir: root, onToolExecResource });
  71. const request: ExecutionRequest = {
  72. command: {
  73. mode: "shell",
  74. shellProfile: "posix-bash",
  75. shellOverride: shell,
  76. command: `"${process.execPath}" "${script}"`,
  77. },
  78. env: { set: { PROBE_RELEASE: release } },
  79. cwd: root,
  80. timeoutMs: 0,
  81. };
  82. return {
  83. adapter,
  84. request,
  85. release: () => writeFile(release, "done"),
  86. async close() {
  87. await writeFile(release, "done");
  88. await adapter.close();
  89. await rm(root, { force: true, recursive: true });
  90. },
  91. };
  92. }
  93. it.each(["timeout", "cancel", "output_limit", "signal"] as const)(
  94. "真实子进程退出分类:%s",
  95. async (kind) => {
  96. if (kind === "signal" && process.platform === "win32") return;
  97. const onToolExecResource = vi.fn();
  98. const fixture = await gatedCommand(onToolExecResource);
  99. const controller = new AbortController();
  100. let now = 0;
  101. vi.spyOn(performance, "now").mockImplementation(() => now);
  102. try {
  103. const result = await fixture.adapter.run(
  104. { ...fixture.request, timeoutMs: kind === "timeout" ? 100 : 0 },
  105. {
  106. signal: controller.signal,
  107. onEvent: (event) => {
  108. if (event.type !== "started") return;
  109. now = 40000;
  110. if (kind === "cancel" || kind === "output_limit")
  111. controller.abort(kind === "output_limit" ? kind : undefined);
  112. if (kind === "signal" && event.pid) process.kill(event.pid, "SIGTERM");
  113. },
  114. },
  115. );
  116. expect(result.status).toBe(
  117. kind === "timeout" ? "timed_out" : kind === "signal" ? "failed" : "cancelled",
  118. );
  119. expect(onToolExecResource).toHaveBeenCalledExactlyOnceWith(
  120. expect.objectContaining({
  121. durationMs: 40000,
  122. exitKind: kind === "timeout" ? "timeout" : "killed",
  123. }),
  124. );
  125. } finally {
  126. vi.restoreAllMocks();
  127. await fixture.close();
  128. }
  129. },
  130. );
  131. it.each(["explicit", "auto_on_timeout"] as const)(
  132. "前后台沿用同一命令,移交不发完成通知:%s",
  133. async (mode) => {
  134. const onToolExecResource = vi.fn();
  135. const fixture = await gatedCommand(onToolExecResource);
  136. let now = 0;
  137. vi.spyOn(performance, "now").mockImplementation(() => now);
  138. try {
  139. const outcome = await fixture.adapter.runBashWithBackgroundLifecycle(
  140. { ...fixture.request, timeoutMs: 20 },
  141. { mode },
  142. );
  143. expect(outcome.kind).toBe("backgrounded");
  144. expect(onToolExecResource).not.toHaveBeenCalled();
  145. now = 40000;
  146. await fixture.release();
  147. if (outcome.kind !== "backgrounded") throw new Error("expected background task");
  148. const done = await fixture.adapter.waitForBackgroundTask(outcome.task.taskId);
  149. expect(done?.result?.stdout.text).toContain("ready");
  150. expect(onToolExecResource).toHaveBeenCalledExactlyOnceWith(
  151. expect.objectContaining({ durationMs: 40000, exitKind: "completed" }),
  152. );
  153. } finally {
  154. vi.restoreAllMocks();
  155. await fixture.close();
  156. }
  157. },
  158. );
  159. it("运行时烟测:真实慢命令经平台探针产生非零 RSS,通知失败不影响输出", async () => {
  160. const onToolExecResource = vi.fn((_sample: ZCodeToolExecResource) => {
  161. throw new Error("telemetry sink closed");
  162. });
  163. const fixture = await gatedCommand(onToolExecResource);
  164. try {
  165. const running = fixture.adapter.run(fixture.request, {
  166. onEvent: (event) => {
  167. if (event.type === "started") setTimeout(() => void fixture.release(), 16500);
  168. },
  169. });
  170. const result = await running;
  171. expect(result.exitCode).toBe(0);
  172. expect(result.stdout.text).toContain("ready");
  173. expect(onToolExecResource).toHaveBeenCalledTimes(1);
  174. const sample = onToolExecResource.mock.calls[0]?.[0];
  175. expect(sample.durationMs).toBeGreaterThanOrEqual(15000);
  176. if (process.platform !== "win32") {
  177. expect(sample.treeRssKbPeak).toBeGreaterThan(0);
  178. expect(sample.sampleCount).toBe(1);
  179. }
  180. } finally {
  181. await fixture.close();
  182. }
  183. }, 25000);