bash-run-conformance.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 explicit background logs the real child pid with toolCallId",
  81. { timeout: 15_000 },
  82. async () => {
  83. const root = await mkdtemp(join(tmpdir(), "zcode-bash-process-log-conformance-"));
  84. const executionPort = new NodeExecutionAdapter({ outputRootDir: root });
  85. const entries: Array<{ message: string; context: Record<string, unknown> }> = [];
  86. const logger = {
  87. debug() {},
  88. info(message: string, context?: Record<string, unknown>) {
  89. entries.push({ message, context: context ?? {} });
  90. },
  91. warn() {},
  92. error() {},
  93. child() {
  94. return logger;
  95. },
  96. } as unknown as NonNullable<ToolExecutionContext["logger"]>;
  97. testRoot = root;
  98. try {
  99. const output = (await bashHandler(
  100. { command: "sleep 0.05", run_in_background: true },
  101. {
  102. ...createContext({}, executionPort),
  103. logger,
  104. toolCallId: "toolu_explicit_process_log",
  105. },
  106. )) as BashOutput;
  107. expect(output.status).toBe("backgrounded");
  108. const snapshot = await executionPort.waitForBackgroundTask(output.backgroundTaskId!);
  109. const started = entries.filter(
  110. (entry) => entry.context.event === "tool.bash.process.started",
  111. );
  112. // 真实 adapter 在 explicit 模式下不转发 started,启动日志必须由 handler 用 task.pid 补写。
  113. expect(started).toHaveLength(1);
  114. expect(started[0]?.context).toMatchObject({
  115. runInBackground: true,
  116. toolCallId: "toolu_explicit_process_log",
  117. });
  118. expect(started[0]?.context.pid).toEqual(expect.any(Number));
  119. expect(started[0]?.context.pid).toBe(snapshot?.pid);
  120. } finally {
  121. await executionPort.close();
  122. await rm(root, { recursive: true, force: true });
  123. }
  124. },
  125. );
  126. test.skipIf(process.platform === "win32")(
  127. "zcode-cli Bash keeps first-token sleep on the hard-timeout foreground path",
  128. async () => {
  129. const root = await mkdtemp(join(tmpdir(), "zcode-bash-sleep-timeout-conformance-"));
  130. const executionPort = new NodeExecutionAdapter({ outputRootDir: root });
  131. testRoot = root;
  132. try {
  133. const output = (await bashHandler(
  134. {
  135. command: "sleep 0.2; printf 'unexpected'",
  136. timeout: 10,
  137. },
  138. {
  139. ...createContext({}, executionPort),
  140. toolCallId: "toolu_sleep_timeout_conformance",
  141. },
  142. )) as BashOutput;
  143. expect(output.status).toBe("timed_out");
  144. expect(output.timedOut).toBe(true);
  145. expect(output.backgroundTaskId).toBeUndefined();
  146. expect(output.stdout).not.toContain("unexpected");
  147. // 真实 adapter 给 Bash 直写输出路径固定 143;10ms 向下取整为 0s,不带中断标记。
  148. expect(bashToolEntry.formatModelContent?.(output)).toBe(
  149. "Exit code 143\nCommand timed out after 0s",
  150. );
  151. } finally {
  152. await executionPort.close();
  153. await rm(root, { recursive: true, force: true });
  154. }
  155. },
  156. );
  157. test("zcode-cli Bash handler auto-backgrounds eligible foreground commands on timeout", async () => {
  158. testRoot = "/repo";
  159. let runBashWithBackgroundLifecycleCalled = false;
  160. const executionPort = {
  161. async run() {
  162. return {
  163. cancelled: false,
  164. completedAt: new Date(),
  165. durationMs: 10,
  166. error: {
  167. message: "Execution timed out after 10ms",
  168. type: "timeout" as const,
  169. },
  170. startedAt: new Date(),
  171. status: "timed_out" as const,
  172. stderr: {
  173. bytes: 0,
  174. text: "",
  175. truncated: false,
  176. },
  177. stdout: {
  178. bytes: 0,
  179. text: "",
  180. truncated: false,
  181. },
  182. timedOut: true,
  183. };
  184. },
  185. async runBashWithBackgroundLifecycle() {
  186. runBashWithBackgroundLifecycleCalled = true;
  187. return {
  188. kind: "backgrounded" as const,
  189. task: {
  190. outputPath: "/tmp/zcode-bash-output.log",
  191. startedAt: new Date(),
  192. status: "running" as const,
  193. taskId: "exec_auto_background",
  194. },
  195. };
  196. },
  197. } as ExecutionPort & {
  198. runBashWithBackgroundLifecycle?: (
  199. request: ExecutionRequest,
  200. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  201. options?: unknown,
  202. ) => Promise<{
  203. kind: "backgrounded";
  204. task: {
  205. outputPath: string;
  206. startedAt: Date;
  207. status: "running";
  208. taskId: string;
  209. };
  210. }>;
  211. };
  212. const output = (await bashHandler(
  213. { command: "npm test", timeout: 10 },
  214. createContext({}, executionPort),
  215. )) as BashOutput;
  216. expect(runBashWithBackgroundLifecycleCalled).toBe(true);
  217. expect(output.status).toBe("backgrounded");
  218. expect(output.backgroundTaskId).toBe("exec_auto_background");
  219. expect(output.assistantAutoBackgrounded).toBeUndefined();
  220. expect(output.backgroundedByUser).toBeUndefined();
  221. expect(output.persistedOutputPath).toBe("/tmp/zcode-bash-output.log");
  222. });
  223. test("zcode-cli Bash handler does not auto-background sleep commands on timeout", async () => {
  224. testRoot = "/repo";
  225. let runCalled = false;
  226. let runBashWithBackgroundLifecycleCalled = false;
  227. const executionPort = {
  228. async run() {
  229. runCalled = true;
  230. return {
  231. cancelled: false,
  232. completedAt: new Date(),
  233. durationMs: 1,
  234. exitCode: 0,
  235. startedAt: new Date(),
  236. status: "completed" as const,
  237. stderr: {
  238. bytes: 0,
  239. text: "",
  240. truncated: false,
  241. },
  242. stdout: {
  243. bytes: 0,
  244. text: "",
  245. truncated: false,
  246. },
  247. timedOut: false,
  248. };
  249. },
  250. async runBashWithBackgroundLifecycle() {
  251. runBashWithBackgroundLifecycleCalled = true;
  252. throw new Error("sleep should not use auto-background");
  253. },
  254. } as ExecutionPort & {
  255. runBashWithBackgroundLifecycle?: (
  256. request: ExecutionRequest,
  257. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  258. options?: unknown,
  259. ) => Promise<unknown>;
  260. };
  261. const output = (await bashHandler(
  262. { command: "sleep 999", timeout: 10 },
  263. createContext({}, executionPort),
  264. )) as BashOutput;
  265. expect(runCalled).toBe(true);
  266. expect(runBashWithBackgroundLifecycleCalled).toBe(false);
  267. expect(output.status).toBe("completed");
  268. });
  269. test("zcode-cli Bash handler auto-backgrounds assignment-prefixed sleep commands on timeout", async () => {
  270. testRoot = "/repo";
  271. let runCalled = false;
  272. let runBashWithBackgroundLifecycleCalled = false;
  273. const executionPort = {
  274. async run() {
  275. runCalled = true;
  276. return {
  277. cancelled: false,
  278. completedAt: new Date(),
  279. durationMs: 1,
  280. exitCode: 0,
  281. startedAt: new Date(),
  282. status: "completed" as const,
  283. stderr: {
  284. bytes: 0,
  285. text: "",
  286. truncated: false,
  287. },
  288. stdout: {
  289. bytes: 0,
  290. text: "",
  291. truncated: false,
  292. },
  293. timedOut: false,
  294. };
  295. },
  296. async runBashWithBackgroundLifecycle() {
  297. runBashWithBackgroundLifecycleCalled = true;
  298. return {
  299. kind: "backgrounded" as const,
  300. task: {
  301. outputPath: "/tmp/zcode-bash-output.log",
  302. startedAt: new Date(),
  303. status: "running" as const,
  304. taskId: "exec_assignment_sleep",
  305. },
  306. };
  307. },
  308. } as ExecutionPort & {
  309. runBashWithBackgroundLifecycle?: (
  310. request: ExecutionRequest,
  311. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  312. options?: unknown,
  313. ) => Promise<{
  314. kind: "backgrounded";
  315. task: {
  316. outputPath: string;
  317. startedAt: Date;
  318. status: "running";
  319. taskId: string;
  320. };
  321. }>;
  322. };
  323. const output = (await bashHandler(
  324. { command: "FOO=1 sleep 999", timeout: 10 },
  325. createContext({}, executionPort),
  326. )) as BashOutput;
  327. expect(runCalled).toBe(false);
  328. expect(runBashWithBackgroundLifecycleCalled).toBe(true);
  329. expect(output.status).toBe("backgrounded");
  330. expect(output.backgroundTaskId).toBe("exec_assignment_sleep");
  331. });
  332. test("zcode-cli Bash does not duplicate production cwd reset stderr", async () => {
  333. testRoot = "/repo";
  334. const executionPort: ExecutionPort = {
  335. async run() {
  336. return {
  337. cancelled: false,
  338. durationMs: 1,
  339. exitCode: 0,
  340. stderr: {
  341. artifactBytes: undefined,
  342. artifactPath: undefined,
  343. bytes: 0,
  344. text: "",
  345. truncated: false,
  346. },
  347. stdout: {
  348. artifactBytes: undefined,
  349. artifactPath: undefined,
  350. bytes: 5,
  351. text: "left\n",
  352. truncated: false,
  353. },
  354. status: "completed",
  355. timedOut: false,
  356. resolvedCwd: "/tmp/outside",
  357. };
  358. },
  359. };
  360. const output = (await bashHandler(
  361. { command: "cd /tmp/outside && echo left" },
  362. createContext({}, executionPort),
  363. )) as BashOutput;
  364. const content = String(bashToolEntry.formatModelContent?.(output));
  365. expect(content.match(/Shell cwd was reset to /g)).toHaveLength(1);
  366. });