bash-run-conformance.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. } finally {
  148. await executionPort.close();
  149. await rm(root, { recursive: true, force: true });
  150. }
  151. },
  152. );
  153. test("zcode-cli Bash handler auto-backgrounds eligible foreground commands on timeout", async () => {
  154. testRoot = "/repo";
  155. let runBashWithBackgroundLifecycleCalled = false;
  156. const executionPort = {
  157. async run() {
  158. return {
  159. cancelled: false,
  160. completedAt: new Date(),
  161. durationMs: 10,
  162. error: {
  163. message: "Execution timed out after 10ms",
  164. type: "timeout" as const,
  165. },
  166. startedAt: new Date(),
  167. status: "timed_out" as const,
  168. stderr: {
  169. bytes: 0,
  170. text: "",
  171. truncated: false,
  172. },
  173. stdout: {
  174. bytes: 0,
  175. text: "",
  176. truncated: false,
  177. },
  178. timedOut: true,
  179. };
  180. },
  181. async runBashWithBackgroundLifecycle() {
  182. runBashWithBackgroundLifecycleCalled = true;
  183. return {
  184. kind: "backgrounded" as const,
  185. task: {
  186. outputPath: "/tmp/zcode-bash-output.log",
  187. startedAt: new Date(),
  188. status: "running" as const,
  189. taskId: "exec_auto_background",
  190. },
  191. };
  192. },
  193. } as ExecutionPort & {
  194. runBashWithBackgroundLifecycle?: (
  195. request: ExecutionRequest,
  196. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  197. options?: unknown,
  198. ) => Promise<{
  199. kind: "backgrounded";
  200. task: {
  201. outputPath: string;
  202. startedAt: Date;
  203. status: "running";
  204. taskId: string;
  205. };
  206. }>;
  207. };
  208. const output = (await bashHandler(
  209. { command: "npm test", timeout: 10 },
  210. createContext({}, executionPort),
  211. )) as BashOutput;
  212. expect(runBashWithBackgroundLifecycleCalled).toBe(true);
  213. expect(output.status).toBe("backgrounded");
  214. expect(output.backgroundTaskId).toBe("exec_auto_background");
  215. expect(output.assistantAutoBackgrounded).toBeUndefined();
  216. expect(output.backgroundedByUser).toBeUndefined();
  217. expect(output.persistedOutputPath).toBe("/tmp/zcode-bash-output.log");
  218. });
  219. test("zcode-cli Bash handler does not auto-background sleep commands on timeout", async () => {
  220. testRoot = "/repo";
  221. let runCalled = false;
  222. let runBashWithBackgroundLifecycleCalled = false;
  223. const executionPort = {
  224. async run() {
  225. runCalled = true;
  226. return {
  227. cancelled: false,
  228. completedAt: new Date(),
  229. durationMs: 1,
  230. exitCode: 0,
  231. startedAt: new Date(),
  232. status: "completed" as const,
  233. stderr: {
  234. bytes: 0,
  235. text: "",
  236. truncated: false,
  237. },
  238. stdout: {
  239. bytes: 0,
  240. text: "",
  241. truncated: false,
  242. },
  243. timedOut: false,
  244. };
  245. },
  246. async runBashWithBackgroundLifecycle() {
  247. runBashWithBackgroundLifecycleCalled = true;
  248. throw new Error("sleep should not use auto-background");
  249. },
  250. } as ExecutionPort & {
  251. runBashWithBackgroundLifecycle?: (
  252. request: ExecutionRequest,
  253. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  254. options?: unknown,
  255. ) => Promise<unknown>;
  256. };
  257. const output = (await bashHandler(
  258. { command: "sleep 999", timeout: 10 },
  259. createContext({}, executionPort),
  260. )) as BashOutput;
  261. expect(runCalled).toBe(true);
  262. expect(runBashWithBackgroundLifecycleCalled).toBe(false);
  263. expect(output.status).toBe("completed");
  264. });
  265. test("zcode-cli Bash handler auto-backgrounds assignment-prefixed sleep commands on timeout", async () => {
  266. testRoot = "/repo";
  267. let runCalled = false;
  268. let runBashWithBackgroundLifecycleCalled = false;
  269. const executionPort = {
  270. async run() {
  271. runCalled = true;
  272. return {
  273. cancelled: false,
  274. completedAt: new Date(),
  275. durationMs: 1,
  276. exitCode: 0,
  277. startedAt: new Date(),
  278. status: "completed" as const,
  279. stderr: {
  280. bytes: 0,
  281. text: "",
  282. truncated: false,
  283. },
  284. stdout: {
  285. bytes: 0,
  286. text: "",
  287. truncated: false,
  288. },
  289. timedOut: false,
  290. };
  291. },
  292. async runBashWithBackgroundLifecycle() {
  293. runBashWithBackgroundLifecycleCalled = true;
  294. return {
  295. kind: "backgrounded" as const,
  296. task: {
  297. outputPath: "/tmp/zcode-bash-output.log",
  298. startedAt: new Date(),
  299. status: "running" as const,
  300. taskId: "exec_assignment_sleep",
  301. },
  302. };
  303. },
  304. } as ExecutionPort & {
  305. runBashWithBackgroundLifecycle?: (
  306. request: ExecutionRequest,
  307. lifecycle: { mode: "explicit" | "auto_on_timeout" },
  308. options?: unknown,
  309. ) => Promise<{
  310. kind: "backgrounded";
  311. task: {
  312. outputPath: string;
  313. startedAt: Date;
  314. status: "running";
  315. taskId: string;
  316. };
  317. }>;
  318. };
  319. const output = (await bashHandler(
  320. { command: "FOO=1 sleep 999", timeout: 10 },
  321. createContext({}, executionPort),
  322. )) as BashOutput;
  323. expect(runCalled).toBe(false);
  324. expect(runBashWithBackgroundLifecycleCalled).toBe(true);
  325. expect(output.status).toBe("backgrounded");
  326. expect(output.backgroundTaskId).toBe("exec_assignment_sleep");
  327. });
  328. test("zcode-cli Bash does not duplicate production cwd reset stderr", async () => {
  329. testRoot = "/repo";
  330. const executionPort: ExecutionPort = {
  331. async run() {
  332. return {
  333. cancelled: false,
  334. durationMs: 1,
  335. exitCode: 0,
  336. stderr: {
  337. artifactBytes: undefined,
  338. artifactPath: undefined,
  339. bytes: 0,
  340. text: "",
  341. truncated: false,
  342. },
  343. stdout: {
  344. artifactBytes: undefined,
  345. artifactPath: undefined,
  346. bytes: 5,
  347. text: "left\n",
  348. truncated: false,
  349. },
  350. status: "completed",
  351. timedOut: false,
  352. resolvedCwd: "/tmp/outside",
  353. };
  354. },
  355. };
  356. const output = (await bashHandler(
  357. { command: "cd /tmp/outside && echo left" },
  358. createContext({}, executionPort),
  359. )) as BashOutput;
  360. const content = String(bashToolEntry.formatModelContent?.(output));
  361. expect(content.match(/Shell cwd was reset to /g)).toHaveLength(1);
  362. });