conversation-session-bash-direct-output.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import {
  2. copyFile,
  3. mkdir,
  4. open,
  5. readFile,
  6. readdir,
  7. rm,
  8. stat,
  9. statfs,
  10. writeFile,
  11. } from "node:fs/promises";
  12. import { dirname, join } from "node:path";
  13. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  14. import { findE2EBashOutputPath, resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  15. import {
  16. getLatestUpstreamToolResultByToolCallId,
  17. countUpstreamRequests,
  18. } from "../helpers/conversation-session-network.js";
  19. import {
  20. listToolCallBlocks,
  21. waitForToolCallBlockByToolCallId,
  22. } from "../helpers/conversation-session-tool.js";
  23. import {
  24. clickV4Stop,
  25. getV4PaneSnapshot,
  26. getV4ConfigProjection,
  27. prepareV4ConversationE2E,
  28. sendV4Prompt,
  29. switchV4Mode,
  30. selectV4TaskById,
  31. waitForV4AssistantMessageContaining,
  32. waitForV4ConversationState,
  33. } from "../helpers/v4-conversation.js";
  34. import { startDraftFromProject } from "../helpers/project-sidebar.js";
  35. const ROOT = resolveE2ERuntimePath("bash-direct-output", "中文 空格");
  36. const LIMIT = 5 * 1024 ** 3;
  37. const RELEASES = [
  38. "A.release",
  39. "B.release",
  40. "B.finish",
  41. "query.grow",
  42. "query.release",
  43. "foreground.release",
  44. "foreground.finish",
  45. "background.release",
  46. "background.finish",
  47. "read-failure.release",
  48. "realtime.1.release",
  49. "realtime.2.release",
  50. "realtime.3.release",
  51. "realtime.4.release",
  52. "realtime.5.release",
  53. ];
  54. const outputs = new Set<string>();
  55. async function release(name: string) {
  56. await writeFile(join(ROOT, name), "release");
  57. }
  58. async function waitFile(name: string) {
  59. await browser.waitUntil(async () => (await stat(join(ROOT, name)).catch(() => null)) !== null, {
  60. timeout: 90000,
  61. timeoutMsg: `producer 没有到达 ${name}`,
  62. });
  63. }
  64. async function idle() {
  65. await waitForV4ConversationState((s) => s.state === "idle", "BDO 会话没有回到 idle", 30000);
  66. }
  67. async function prompt(marker: string, newTask = true) {
  68. if (newTask) {
  69. // 合并适配:全局新任务落到独立聊天目录,Bash fixture 必须从 ZCodeProject 发起。
  70. await startDraftFromProject(DEFAULT_WORKSPACE);
  71. // 项目新草稿恢复 build;显式选择 yolo,避免把模式切换动画中的旧文案当成已选中。
  72. await switchV4Mode("yolo");
  73. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  74. timeout: 15000,
  75. timeoutMsg: "项目草稿未应用 yolo 模式",
  76. });
  77. }
  78. await sendV4Prompt(`${marker}: Execute the exact Bash output regression fixture.`);
  79. }
  80. async function done(marker: string) {
  81. await waitForV4AssistantMessageContaining(`${marker}_DONE`, 90000);
  82. await idle();
  83. }
  84. async function result(id: string) {
  85. const value = await getLatestUpstreamToolResultByToolCallId(id);
  86. expect(value).not.toBeNull();
  87. return value!;
  88. }
  89. async function outputPath(id: string) {
  90. const sessionId = (await getV4PaneSnapshot()).sessionId;
  91. expect(sessionId).not.toBe("draft");
  92. const path = await findE2EBashOutputPath(sessionId!, id);
  93. if (!path) throw new Error(`Bash 未保留预期输出文件: ${sessionId}/${id}`);
  94. outputs.add(path);
  95. return path;
  96. }
  97. async function snippet(path: string, tail = false) {
  98. const handle = await open(path, "r");
  99. try {
  100. const size = (await handle.stat()).size;
  101. const buffer = Buffer.alloc(Math.min(size, 128));
  102. await handle.read(buffer, 0, buffer.length, tail ? size - buffer.length : 0);
  103. return buffer.toString();
  104. } finally {
  105. await handle.close();
  106. }
  107. }
  108. async function setExpanded(id: string, expanded: boolean) {
  109. await waitForToolCallBlockByToolCallId(id);
  110. const trigger = await $(`[data-testid="tool-summary-trigger-${id}"]`);
  111. if ((await trigger.getAttribute("aria-expanded")) !== String(expanded)) await trigger.click();
  112. }
  113. async function assertOutputHidden(id: string) {
  114. await browser.waitUntil(
  115. async () =>
  116. browser.execute((toolId) => {
  117. const block = document.querySelector(`[data-testid="chat-tool-call-block-${toolId}"]`);
  118. return (
  119. Boolean(block) &&
  120. !block!.querySelector(
  121. '[data-testid^="bash-output-preview-"], [data-testid="bash-result-output"], [data-testid="bash-output-notice"], [data-testid="bash-output-file"]',
  122. )
  123. );
  124. }, id),
  125. { timeout: 5000, timeoutMsg: `收起后的 Bash 仍渲染输出:${id}` },
  126. );
  127. }
  128. describe("Bash 直接文件输出补充 E2E", () => {
  129. before(async function () {
  130. this.timeout(120000);
  131. await mkdir(ROOT, { recursive: true });
  132. await copyFile(
  133. new URL("../fixtures/fs/conversation-session/bash-direct-output/writer.cjs", import.meta.url),
  134. join(ROOT, "writer.cjs"),
  135. );
  136. await prepareV4ConversationE2E();
  137. await switchV4Mode("yolo");
  138. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  139. timeout: 15000,
  140. timeoutMsg: "项目草稿未应用 yolo 模式",
  141. });
  142. });
  143. beforeEach(async () => {
  144. for (const name of await readdir(ROOT)) if (name.endsWith(".pid")) await rm(join(ROOT, name));
  145. for (const name of [
  146. ...RELEASES,
  147. "query.ready",
  148. "query.grown",
  149. "foreground.ready",
  150. "background.ready",
  151. "read-failure.ready",
  152. "realtime.1.ready",
  153. "realtime.2.ready",
  154. "realtime.3.ready",
  155. "realtime.4.ready",
  156. "realtime.5.ready",
  157. ]) {
  158. await rm(join(ROOT, name), { force: true });
  159. }
  160. });
  161. afterEach(async () => {
  162. // 失败同样释放本 case 的子进程,避免下一条测试或 coverage teardown 被遗留任务影响。
  163. await Promise.all(RELEASES.map(release));
  164. if ((await getV4PaneSnapshot()).canStop) await clickV4Stop();
  165. const pids = await Promise.all(
  166. (await readdir(ROOT))
  167. .filter((name) => name.endsWith(".pid"))
  168. .map(async (name) => Number(await readFile(join(ROOT, name), "utf8"))),
  169. );
  170. await browser.waitUntil(
  171. async () =>
  172. pids.every((pid) => {
  173. try {
  174. process.kill(pid, 0);
  175. return false;
  176. } catch {
  177. return true;
  178. }
  179. }),
  180. { timeout: 10000, timeoutMsg: "本条 Bash producer 没有清理完成" },
  181. );
  182. for (const path of outputs) await rm(path, { force: true, recursive: true });
  183. outputs.clear();
  184. });
  185. after(async () => {
  186. await browser.electron.restoreAllMocks();
  187. await clearAppData();
  188. });
  189. it("BDO01: 中文空格路径、两流无换行与非零空输出保持正确结果", async function () {
  190. this.timeout(120000);
  191. await prompt("E2E_BDO_SMALL");
  192. await done("E2E_BDO_SMALL");
  193. expect((await result("toolu_bdo_small")).content).toBe("BDO_中文_STDOUT|中文_STDERR");
  194. expect((await result("toolu_bdo_empty_error")).content).toContain("Exit code 7");
  195. // 小输出应清理实际临时文件;检查当前 session/tool 的所有候选,而不是旧 HOME 路径。
  196. expect(
  197. await findE2EBashOutputPath((await getV4PaneSnapshot()).sessionId!, "toolu_bdo_small"),
  198. ).toBeNull();
  199. });
  200. it("BDO02: 超过 64 MiB 的前台输出保留完整文件,详情只展示正文", async function () {
  201. this.timeout(120000);
  202. await prompt("E2E_BDO_LARGE");
  203. await done("E2E_BDO_LARGE");
  204. const path = await outputPath("toolu_bdo_large");
  205. expect((await stat(path)).size).toBe(
  206. 65 * 1024 ** 2 + Buffer.byteLength("BDO_HEAD\n\nBDO_TAIL\n"),
  207. );
  208. expect(await snippet(path)).toContain("BDO_HEAD");
  209. expect(await snippet(path, true)).toContain("BDO_TAIL");
  210. expect((await result("toolu_bdo_large")).content).toContain(path);
  211. await setExpanded("toolu_bdo_large", false);
  212. await assertOutputHidden("toolu_bdo_large");
  213. await setExpanded("toolu_bdo_large", true);
  214. const body = await $('[data-testid="bash-result-output"]');
  215. await body.waitForDisplayed();
  216. await browser.waitUntil(async () => (await body.getText()).includes("BDO_HEAD"), {
  217. timeout: 10000,
  218. timeoutMsg: "展开后的 Bash 头部摘要没有显示",
  219. });
  220. expect(await body.getText()).toContain("BDO_HEAD");
  221. expect(await body.getText()).not.toContain("BDO_TAIL");
  222. expect(Buffer.byteLength(await body.getText())).toBe(30000);
  223. expect(await $('[data-testid="bash-output-notice"]').isExisting()).toBe(false);
  224. expect(await $('[data-testid="bash-output-file"]').isExisting()).toBe(false);
  225. await setExpanded("toolu_bdo_large", false);
  226. await assertOutputHidden("toolu_bdo_large");
  227. });
  228. it("BDO03: 并发前台 Bash 共享进度期间一个退出不影响另一个", async function () {
  229. this.timeout(120000);
  230. const previews = () =>
  231. browser.execute(() =>
  232. Array.from(document.querySelectorAll('[data-testid="bash-output-preview-full"]')).map(
  233. (el) => el.textContent ?? "",
  234. ),
  235. );
  236. const waitPreview = (text: string) =>
  237. browser.waitUntil(async () => (await previews()).some((s) => s.includes(text)), {
  238. timeout: 30000,
  239. timeoutMsg: `Bash 没有更新进度:${text}`,
  240. });
  241. // 同一批 mutating Bash 会串行执行;两个独立会话才能形成真实并发。
  242. await prompt("E2E_BDO_PROGRESS_A");
  243. await setExpanded("toolu_bdo_progress_a", true);
  244. await waitPreview("A-STAGE1");
  245. const fullPreview = await $('[data-testid="bash-output-preview-full"]');
  246. await fullPreview.waitForDisplayed();
  247. // 展开动画期间元素已有尺寸但可见文本仍可能为空;等待实际预览再检查行数和字节数。
  248. await browser.waitUntil(async () => (await fullPreview.getText()).includes("A-STAGE1"), {
  249. timeout: 10000,
  250. timeoutMsg: "展开后的 Bash 进度预览没有显示",
  251. });
  252. const fullText = await fullPreview.getText();
  253. expect(fullText).toContain("A-STAGE1");
  254. expect(fullText.split("\n").length).toBeGreaterThan(5);
  255. expect(fullText.split("\n").length).toBeLessThanOrEqual(100);
  256. expect(Buffer.byteLength(fullText)).toBeLessThanOrEqual(4096);
  257. await setExpanded("toolu_bdo_progress_a", false);
  258. await assertOutputHidden("toolu_bdo_progress_a");
  259. const sessionA = (await getV4PaneSnapshot()).sessionId!;
  260. await outputPath("toolu_bdo_progress_a");
  261. await prompt("E2E_BDO_PROGRESS_B");
  262. await setExpanded("toolu_bdo_progress_b", true);
  263. await waitPreview("B-STAGE1");
  264. const sessionB = (await getV4PaneSnapshot()).sessionId!;
  265. await outputPath("toolu_bdo_progress_b");
  266. for (const text of await previews()) expect(text.length).toBeLessThanOrEqual(4096);
  267. await selectV4TaskById(sessionA);
  268. // 切回会话后明确展开,再检查进度;不隐含验证卡片展开状态的恢复。
  269. await setExpanded("toolu_bdo_progress_a", true);
  270. await waitPreview("A-STAGE1");
  271. await release("A.release");
  272. await done("E2E_BDO_PROGRESS_A");
  273. await selectV4TaskById(sessionB);
  274. await setExpanded("toolu_bdo_progress_b", true);
  275. await release("B.release");
  276. await browser.waitUntil(async () => (await previews()).some((s) => s.includes("B-STAGE2")), {
  277. timeout: 10000,
  278. timeoutMsg: "第一个 Bash 完成后另一个 Bash 的进度停止更新",
  279. });
  280. await release("B.finish");
  281. await done("E2E_BDO_PROGRESS_B");
  282. expect(await previews()).toEqual([]);
  283. });
  284. it("BDO07: 展开时实时刷新,收起不渲染输出,再展开显示最新内容", async function () {
  285. this.timeout(60000);
  286. const id = "toolu_bdo_realtime";
  287. const marker = "E2E_BDO_REALTIME";
  288. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  289. if (!artifactDir) throw new Error("E2E artifact directory is required for refresh timings");
  290. const observations: {
  291. stage: number;
  292. fileVisibleMs: number;
  293. previewVisibleMs: number;
  294. height: number;
  295. lineHeight: number;
  296. bottomGap: number;
  297. }[] = [];
  298. await prompt(marker);
  299. await waitFile("realtime.1.ready");
  300. const path = await outputPath(id);
  301. const pid = Number(await readFile(join(ROOT, "realtime.pid"), "utf8"));
  302. await setExpanded(id, true);
  303. let expectedOutput = "";
  304. let frozenOutput = "";
  305. const scrollMetrics = () =>
  306. browser.execute(() => {
  307. const el = document.querySelector<HTMLElement>('[data-testid="bash-output-scroll"]')!;
  308. return {
  309. height: el.clientHeight,
  310. lineHeight: Number.parseFloat(getComputedStyle(el.querySelector("pre")!).lineHeight),
  311. bottomGap: el.scrollHeight - el.scrollTop - el.clientHeight,
  312. };
  313. });
  314. for (const stage of [1, 2, 3, 4, 5]) {
  315. if (stage > 1) await waitFile(`realtime.${stage}.ready`);
  316. const writtenAt = Number(await readFile(join(ROOT, `realtime.${stage}.ready`), "utf8"));
  317. const fragment = `实时-${stage}-stdout|实时-${stage}-stderr`;
  318. expectedOutput += (stage > 1 ? `line-${stage} abcdefghijklmnop\n`.repeat(80) : "") + fragment;
  319. // ready 由 producer 在两流写入后创建;release 前直接读原文件,不能用最终结果冒充实时输出。
  320. expect(await readFile(path, "utf8")).toBe(expectedOutput);
  321. const fileVisibleMs = Date.now() - writtenAt;
  322. if (stage === 3) {
  323. // 收起期间跨过一次 1 秒进度轮询;新输出仍不能重新渲染正文。
  324. await browser.pause(1200);
  325. await assertOutputHidden(id);
  326. await setExpanded(id, true);
  327. }
  328. const preview = await $('[data-testid="bash-output-preview-full"]');
  329. if (stage === 4) {
  330. // 用户上滚后即使 CLI 已发布新一段,正在阅读的有界窗口也不能被替换。
  331. await browser.pause(1500);
  332. expect(await preview.getText()).toBe(frozenOutput);
  333. await browser.execute(() => {
  334. const el = document.querySelector<HTMLElement>('[data-testid="bash-output-scroll"]')!;
  335. el.scrollTop = el.scrollHeight;
  336. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  337. });
  338. }
  339. await browser.waitUntil(
  340. async () => (await preview.isExisting()) && (await preview.getText()).includes(fragment),
  341. {
  342. timeout: stage === 1 ? 8000 : 5000,
  343. timeoutMsg: `第 ${stage} 段 Bash 输出未在退出前刷新`,
  344. },
  345. );
  346. const previewVisibleMs = Date.now() - writtenAt;
  347. expect(previewVisibleMs).toBeLessThanOrEqual(stage === 1 ? 8000 : 5000);
  348. expect(process.kill(pid, 0)).toBe(true);
  349. expect((await listToolCallBlocks()).find((block) => block.toolCallId === id)?.status).toBe(
  350. "in_progress",
  351. );
  352. expect(await getLatestUpstreamToolResultByToolCallId(id)).toBeNull();
  353. const metrics = await scrollMetrics();
  354. observations.push({ stage, fileVisibleMs, previewVisibleMs, ...metrics });
  355. console.log("BASH_REALTIME_VIEWPORT", JSON.stringify(observations.at(-1)));
  356. await writeFile(
  357. join(artifactDir, "bash-realtime-refresh.json"),
  358. JSON.stringify(observations, null, 2),
  359. );
  360. expect(metrics.lineHeight).toBeGreaterThan(0);
  361. expect(metrics.height).toBe(metrics.lineHeight * (stage === 1 ? 1 : 5));
  362. expect(metrics.bottomGap).toBeLessThanOrEqual(1);
  363. const scrollViewport = await $('[data-testid="bash-output-scroll"]');
  364. await browser.waitUntil(
  365. async () =>
  366. (await scrollViewport.getAttribute("data-scroll-mask")) ===
  367. (stage === 1 ? "none" : "top"),
  368. { timeout: 5000, timeoutMsg: "Bash 吸底后渐隐方向不正确" },
  369. );
  370. expect(
  371. await scrollViewport.getCSSProperty("mask-image").then((value) => value.value === "none"),
  372. ).toBe(stage === 1);
  373. expect(await $('[data-testid="bash-output-resume"]').isExisting()).toBe(false);
  374. if (stage === 2) {
  375. await setExpanded(id, false);
  376. await assertOutputHidden(id);
  377. }
  378. if (stage === 3 || stage === 5) {
  379. frozenOutput = await preview.getText();
  380. await browser.execute(() => {
  381. const el = document.querySelector<HTMLElement>('[data-testid="bash-output-scroll"]')!;
  382. el.scrollTop = (el.scrollHeight - el.clientHeight) / 2;
  383. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  384. });
  385. await browser.waitUntil(
  386. async () => (await scrollViewport.getAttribute("data-scroll-mask")) === "both",
  387. {
  388. timeout: 5000,
  389. timeoutMsg: "Bash 中间位置没有上下渐隐",
  390. },
  391. );
  392. await browser.execute(() => {
  393. const el = document.querySelector<HTMLElement>('[data-testid="bash-output-scroll"]')!;
  394. el.scrollTop = 0;
  395. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  396. });
  397. await browser.waitUntil(
  398. async () =>
  399. (await $('[data-testid="bash-output-scroll"]').getAttribute("data-following")) ===
  400. "false",
  401. { timeout: 5000, timeoutMsg: "用户上滚后没有暂停跟随" },
  402. );
  403. expect(await $('[data-testid="bash-output-resume"]').isExisting()).toBe(false);
  404. expect(await scrollViewport.getAttribute("data-scroll-mask")).toBe("bottom");
  405. }
  406. await release(`realtime.${stage}.release`);
  407. }
  408. await done(marker);
  409. // assistant 收尾会把工具移入可折叠历史;重新定位展开,不把父级卸载当成输出视口丢失。
  410. await setExpanded(id, false);
  411. await assertOutputHidden(id);
  412. await setExpanded(id, true);
  413. // 详情有展开动画;等待真实可见文本,不能把动画首帧的空 getText 当成丢输出。
  414. const finalOutput = await $('[data-testid="bash-result-output"]');
  415. await browser.waitUntil(async () => (await finalOutput.getText()) === expectedOutput, {
  416. timeout: 10000,
  417. timeoutMsg: "重新展开后没有显示最终 Bash 输出",
  418. });
  419. const finalMetrics = await scrollMetrics();
  420. expect(finalMetrics.height).toBe(finalMetrics.lineHeight * 5);
  421. expect(await $('[data-testid="bash-output-resume"]').isExisting()).toBe(false);
  422. expect((await result(id)).content).toBe(expectedOutput);
  423. expect((await waitForToolCallBlockByToolCallId(id)).status).toBe("completed");
  424. expect(await $('[data-testid="bash-output-preview-short"]').isExisting()).toBe(false);
  425. expect(await $('[data-testid="bash-output-preview-full"]').isExisting()).toBe(false);
  426. await setExpanded(id, false);
  427. await assertOutputHidden(id);
  428. expect(
  429. await countUpstreamRequests({ includes: [marker], excludes: ["Generate a concise title"] }),
  430. ).toBe(2);
  431. });
  432. it("BDO04: TaskOutput 运行时重复头读、完成后尾读", async function () {
  433. this.timeout(120000);
  434. await prompt("E2E_BDO_QUERY");
  435. await done("E2E_BDO_QUERY");
  436. await waitFile("query.ready");
  437. const path = await outputPath("toolu_bdo_query");
  438. await prompt("E2E_BDO_QUERY_FIRST", false);
  439. await done("E2E_BDO_QUERY_FIRST");
  440. const first = (await result("toolu_bdo_query_first")).content;
  441. expect(first).toContain("BDO_QUERY_HEAD");
  442. expect(first).not.toContain("BDO_QUERY_FIRST_TAIL");
  443. await release("query.grow");
  444. await waitFile("query.grown");
  445. await prompt("E2E_BDO_QUERY_SECOND", false);
  446. await done("E2E_BDO_QUERY_SECOND");
  447. const second = (await result("toolu_bdo_query_second")).content;
  448. const firstOutput = first.match(/<output>([\s\S]*?)<\/output>/)?.[1];
  449. expect(firstOutput).toBeDefined();
  450. expect(second.match(/<output>([\s\S]*?)<\/output>/)?.[1]).toBe(firstOutput);
  451. expect(second).not.toContain("BDO_QUERY_SECOND_TAIL");
  452. await release("query.release");
  453. await waitForV4AssistantMessageContaining("E2E_BDO_QUERY_NOTIFIED", 30000);
  454. await prompt("E2E_BDO_QUERY_FINAL", false);
  455. await done("E2E_BDO_QUERY_FINAL");
  456. const final = (await result("toolu_bdo_query_final")).content;
  457. expect(final).toContain("BDO_QUERY_FINAL_TAIL");
  458. expect(final).not.toContain("BDO_QUERY_HEAD");
  459. expect((await stat(path)).size).toBeGreaterThan(600000);
  460. });
  461. for (const mode of ["foreground", "background"] as const) {
  462. it(`BDO05: ${mode} 真实 5 GiB 边界与 5 秒 watchdog`, async function () {
  463. this.timeout(150000);
  464. const disk = await statfs(ROOT, { bigint: true });
  465. if (disk.bavail * disk.bsize < BigInt(12 * 1024 ** 3))
  466. throw new Error("5 GiB 实写需要至少 12 GiB 可用空间,未执行不能算通过");
  467. const marker = `E2E_BDO_LIMIT_${mode.toUpperCase()}`;
  468. await prompt(marker);
  469. await waitFile(`${mode}.ready`);
  470. const path = await outputPath(`toolu_bdo_limit_${mode}`);
  471. expect((await stat(path)).size).toBe(LIMIT);
  472. // 跨过完整检查周期后,等于阈值的命令必须仍存活。
  473. await browser.pause(5500);
  474. const pid = Number(await readFile(join(ROOT, `${mode}.pid`), "utf8"));
  475. expect(() => process.kill(pid, 0)).not.toThrow();
  476. await release(`${mode}.release`);
  477. await waitFile(`${mode}.exceeded`);
  478. await waitForV4AssistantMessageContaining(`${marker}_KILLED`, 20000);
  479. await idle();
  480. if (mode === "foreground") {
  481. const output = await result("toolu_bdo_limit_foreground");
  482. expect(output.isError).toBe(true);
  483. // 取消结果超过模型预算时沿用 artifact 包装,诊断在完整结果中而非 2 KiB 预览里。
  484. const persisted = output.content.match(/Full output saved to: ([^\n]+)/)?.[1];
  485. const full = persisted ? await readFile(persisted, "utf8") : output.content;
  486. expect(full).toContain("Command killed: output file exceeded 5GB");
  487. expect(await stat(path).catch(() => null)).toBeNull();
  488. } else {
  489. expect((await stat(path)).size).toBe(LIMIT + 1);
  490. expect(
  491. await countUpstreamRequests({
  492. includes: [marker, "<task-notification>", "<status>killed</status>"],
  493. }),
  494. ).toBe(1);
  495. }
  496. await browser.waitUntil(
  497. async () => {
  498. try {
  499. process.kill(pid, 0);
  500. return false;
  501. } catch {
  502. return true;
  503. }
  504. },
  505. { timeout: 10000, timeoutMsg: "超限 producer 没有退出" },
  506. );
  507. });
  508. }
  509. it("BDO06: 真实输出读取/打开失败有诊断,后续 Bash 仍能执行", async function () {
  510. this.timeout(120000);
  511. await prompt("E2E_BDO_READ_FAILURE");
  512. await waitFile("read-failure.ready");
  513. const path = await outputPath("toolu_bdo_read_failure");
  514. await rm(path);
  515. await release("read-failure.release");
  516. await done("E2E_BDO_READ_FAILURE");
  517. expect((await result("toolu_bdo_read_failure")).content).toContain("bash output unavailable");
  518. // 故障注入必须沿用本 session 已发布的实际输出目录,不能在退役 HOME 根创建障碍。
  519. const blocked = join(dirname(path), "toolu_bdo_open_failure-stdout.log");
  520. outputs.add(blocked);
  521. await mkdir(blocked, { recursive: true });
  522. await prompt("E2E_BDO_OPEN_FAILURE", false);
  523. await done("E2E_BDO_OPEN_FAILURE");
  524. // 启动失败没有进程退出码;验证实际错误诊断,不套用命令非零退出的 is_error 契约。
  525. expect((await result("toolu_bdo_open_failure")).content).toContain("EISDIR");
  526. expect((await stat(blocked)).isDirectory()).toBe(true);
  527. await prompt("E2E_BDO_RECOVERY", false);
  528. await done("E2E_BDO_RECOVERY");
  529. expect((await result("toolu_bdo_recovery")).content).toBe("BDO_中文_STDOUT|中文_STDERR");
  530. });
  531. });