bash-run-conformance.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { expect, test } from "vitest";
  5. import { type BashOutput, type ExecutionRequest, type ExecutionPort } from "@zcode/contracts";
  6. import { NodeExecutionAdapter } from "../../adapters/src/exec/index.js";
  7. import { bashHandler, bashToolEntry } from "../src/tool/handlers/bash.js";
  8. import type { ToolExecutionContext } from "../src/tool/types.js";
  9. let testRoot = "";
  10. type BashBackgroundLifecycleExecutionPort = ExecutionPort & {
  11. runBashWithBackgroundLifecycle?: (
  12. request: ExecutionRequest,
  13. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  14. options?: unknown,
  15. ) => Promise<unknown>;
  16. waitForBackgroundTask?: (taskId: string, options?: unknown) => Promise<unknown>;
  17. };
  18. function createContext(
  19. options: {
  20. agentId?: string;
  21. onToolJsxUpdate?: (event: unknown) => void;
  22. toolUseId?: string;
  23. } = {},
  24. executionPort: ExecutionPort,
  25. ): ToolExecutionContext {
  26. return {
  27. toolCallId: options.toolUseId ?? "toolu_bash_test",
  28. traceId: "trace_bash_conformance" as never,
  29. spanId: options.agentId ?? "span_bash_conformance",
  30. abortSignal: new AbortController().signal,
  31. executionPort,
  32. workingDirectory: testRoot,
  33. workspaceRoot: testRoot,
  34. runtimeScope: options.agentId ? "subagent" : "main",
  35. sessionId: "sess_bash_conformance" as never,
  36. turnId: "turn_bash_conformance" as never,
  37. emitEvent: async (event) => {
  38. options.onToolJsxUpdate?.(event);
  39. },
  40. };
  41. }
  42. test.skipIf(process.platform === "win32")(
  43. "zcode-cli Bash explicit background survives timeout and parent abort with a real process",
  44. {
  45. // 测试基建修复:该用例会启动并回收真实子进程;全量 Turbo 并发会放大进程调度延迟,
  46. // 不能复用 Vitest 默认 5 秒预算,否则功能已完成时仍可能被测试框架先行超时。
  47. timeout: 15_000,
  48. },
  49. async () => {
  50. const root = await mkdtemp(join(tmpdir(), "zcode-bash-lifecycle-conformance-"));
  51. const executionPort = new NodeExecutionAdapter({ outputRootDir: root });
  52. const parentTurn = new AbortController();
  53. testRoot = root;
  54. try {
  55. const output = (await bashHandler(
  56. {
  57. command: "printf 'started'; sleep 0.08; printf 'completed'",
  58. run_in_background: true,
  59. timeout: 5,
  60. },
  61. {
  62. ...createContext({}, executionPort),
  63. abortSignal: parentTurn.signal,
  64. toolCallId: "toolu_explicit_lifecycle_conformance",
  65. },
  66. )) as BashOutput;
  67. expect(output.status).toBe("backgrounded");
  68. expect(output.backgroundTaskId).toMatch(/^exec_/u);
  69. parentTurn.abort();
  70. const snapshot = await executionPort.waitForBackgroundTask(output.backgroundTaskId!);
  71. expect(snapshot?.status).toBe("completed");
  72. expect(snapshot?.result?.stdout.text).toBe("startedcompleted");
  73. } finally {
  74. await executionPort.close();
  75. await rm(root, { recursive: true, force: true });
  76. }
  77. },
  78. );
  79. test.skipIf(process.platform === "win32")(
  80. "zcode-cli Bash keeps first-token sleep on the hard-timeout foreground path",
  81. async () => {
  82. const root = await mkdtemp(join(tmpdir(), "zcode-bash-sleep-timeout-conformance-"));
  83. const executionPort = new NodeExecutionAdapter({ outputRootDir: root });
  84. testRoot = root;
  85. try {
  86. const output = (await bashHandler(
  87. {
  88. command: "sleep 0.2; printf 'unexpected'",
  89. timeout: 10,
  90. },
  91. {
  92. ...createContext({}, executionPort),
  93. toolCallId: "toolu_sleep_timeout_conformance",
  94. },
  95. )) as BashOutput;
  96. expect(output.status).toBe("timed_out");
  97. expect(output.timedOut).toBe(true);
  98. expect(output.backgroundTaskId).toBeUndefined();
  99. expect(output.stdout).not.toContain("unexpected");
  100. } finally {
  101. await executionPort.close();
  102. await rm(root, { recursive: true, force: true });
  103. }
  104. },
  105. );
  106. test("zcode-cli Bash handler auto-backgrounds eligible foreground commands on timeout", async () => {
  107. testRoot = "/repo";
  108. let runBashWithBackgroundLifecycleCalled = false;
  109. const executionPort = {
  110. async run() {
  111. return {
  112. cancelled: false,
  113. completedAt: new Date(),
  114. durationMs: 10,
  115. error: {
  116. message: "Execution timed out after 10ms",
  117. type: "timeout" as const,
  118. },
  119. startedAt: new Date(),
  120. status: "timed_out" as const,
  121. stderr: {
  122. bytes: 0,
  123. text: "",
  124. truncated: false,
  125. },
  126. stdout: {
  127. bytes: 0,
  128. text: "",
  129. truncated: false,
  130. },
  131. timedOut: true,
  132. };
  133. },
  134. async runBashWithBackgroundLifecycle() {
  135. runBashWithBackgroundLifecycleCalled = true;
  136. return {
  137. kind: "backgrounded" as const,
  138. task: {
  139. outputPath: "/tmp/zcode-bash-output.log",
  140. startedAt: new Date(),
  141. status: "running" as const,
  142. taskId: "exec_auto_background",
  143. },
  144. };
  145. },
  146. } as ExecutionPort & {
  147. runBashWithBackgroundLifecycle?: (
  148. request: ExecutionRequest,
  149. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  150. options?: unknown,
  151. ) => Promise<{
  152. kind: "backgrounded";
  153. task: {
  154. outputPath: string;
  155. startedAt: Date;
  156. status: "running";
  157. taskId: string;
  158. };
  159. }>;
  160. };
  161. const output = (await bashHandler(
  162. { command: "npm test", timeout: 10 },
  163. createContext({}, executionPort),
  164. )) as BashOutput;
  165. expect(runBashWithBackgroundLifecycleCalled).toBe(true);
  166. expect(output.status).toBe("backgrounded");
  167. expect(output.backgroundTaskId).toBe("exec_auto_background");
  168. expect(output.assistantAutoBackgrounded).toBeUndefined();
  169. expect(output.backgroundedByUser).toBeUndefined();
  170. expect(output.persistedOutputPath).toBe("/tmp/zcode-bash-output.log");
  171. });
  172. test("zcode-cli Bash handler does not auto-background sleep commands on timeout", async () => {
  173. testRoot = "/repo";
  174. let runCalled = false;
  175. let runBashWithBackgroundLifecycleCalled = false;
  176. const executionPort = {
  177. async run() {
  178. runCalled = true;
  179. return {
  180. cancelled: false,
  181. completedAt: new Date(),
  182. durationMs: 1,
  183. exitCode: 0,
  184. startedAt: new Date(),
  185. status: "completed" as const,
  186. stderr: {
  187. bytes: 0,
  188. text: "",
  189. truncated: false,
  190. },
  191. stdout: {
  192. bytes: 0,
  193. text: "",
  194. truncated: false,
  195. },
  196. timedOut: false,
  197. };
  198. },
  199. async runBashWithBackgroundLifecycle() {
  200. runBashWithBackgroundLifecycleCalled = true;
  201. throw new Error("sleep should not use auto-background");
  202. },
  203. } as ExecutionPort & {
  204. runBashWithBackgroundLifecycle?: (
  205. request: ExecutionRequest,
  206. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  207. options?: unknown,
  208. ) => Promise<unknown>;
  209. };
  210. const output = (await bashHandler(
  211. { command: "sleep 999", timeout: 10 },
  212. createContext({}, executionPort),
  213. )) as BashOutput;
  214. expect(runCalled).toBe(true);
  215. expect(runBashWithBackgroundLifecycleCalled).toBe(false);
  216. expect(output.status).toBe("completed");
  217. });
  218. test("zcode-cli Bash handler auto-backgrounds assignment-prefixed sleep commands on timeout", async () => {
  219. testRoot = "/repo";
  220. let runCalled = false;
  221. let runBashWithBackgroundLifecycleCalled = false;
  222. const executionPort = {
  223. async run() {
  224. runCalled = true;
  225. return {
  226. cancelled: false,
  227. completedAt: new Date(),
  228. durationMs: 1,
  229. exitCode: 0,
  230. startedAt: new Date(),
  231. status: "completed" as const,
  232. stderr: {
  233. bytes: 0,
  234. text: "",
  235. truncated: false,
  236. },
  237. stdout: {
  238. bytes: 0,
  239. text: "",
  240. truncated: false,
  241. },
  242. timedOut: false,
  243. };
  244. },
  245. async runBashWithBackgroundLifecycle() {
  246. runBashWithBackgroundLifecycleCalled = true;
  247. return {
  248. kind: "backgrounded" as const,
  249. task: {
  250. outputPath: "/tmp/zcode-bash-output.log",
  251. startedAt: new Date(),
  252. status: "running" as const,
  253. taskId: "exec_assignment_sleep",
  254. },
  255. };
  256. },
  257. } as ExecutionPort & {
  258. runBashWithBackgroundLifecycle?: (
  259. request: ExecutionRequest,
  260. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  261. options?: unknown,
  262. ) => Promise<{
  263. kind: "backgrounded";
  264. task: {
  265. outputPath: string;
  266. startedAt: Date;
  267. status: "running";
  268. taskId: string;
  269. };
  270. }>;
  271. };
  272. const output = (await bashHandler(
  273. { command: "FOO=1 sleep 999", timeout: 10 },
  274. createContext({}, executionPort),
  275. )) as BashOutput;
  276. expect(runCalled).toBe(false);
  277. expect(runBashWithBackgroundLifecycleCalled).toBe(true);
  278. expect(output.status).toBe("backgrounded");
  279. expect(output.backgroundTaskId).toBe("exec_assignment_sleep");
  280. });
  281. test("zcode-cli Bash does not duplicate production cwd reset stderr", async () => {
  282. testRoot = "/repo";
  283. const executionPort: ExecutionPort = {
  284. async run() {
  285. return {
  286. cancelled: false,
  287. durationMs: 1,
  288. exitCode: 0,
  289. stderr: {
  290. artifactBytes: undefined,
  291. artifactPath: undefined,
  292. bytes: 0,
  293. text: "",
  294. truncated: false,
  295. },
  296. stdout: {
  297. artifactBytes: undefined,
  298. artifactPath: undefined,
  299. bytes: 5,
  300. text: "left\n",
  301. truncated: false,
  302. },
  303. status: "completed",
  304. timedOut: false,
  305. resolvedCwd: "/tmp/outside",
  306. };
  307. },
  308. };
  309. const output = (await bashHandler(
  310. { command: "cd /tmp/outside && echo left" },
  311. createContext({}, executionPort),
  312. )) as BashOutput;
  313. const content = String(bashToolEntry.formatModelContent?.(output));
  314. expect(content.match(/Shell cwd was reset to /g)).toHaveLength(1);
  315. });