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

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