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

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