conversation-session-background-bash-output.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  4. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  5. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  6. import { countUpstreamRequests } from "#e2e/helpers/conversation-session-network";
  7. import {
  8. getV4PaneSnapshot,
  9. getV4ConfigProjection,
  10. openV4ComposerRunningBackgroundWorks,
  11. prepareV4ConversationE2E,
  12. selectV4TaskById,
  13. sendV4Prompt,
  14. switchV4Mode,
  15. waitForV4AssistantMessageContaining,
  16. setV4ElectronWindowSize,
  17. } from "#e2e/helpers/v4-conversation";
  18. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  19. import {
  20. activateResourceManagerTab,
  21. closeResourceManagerWindow,
  22. isMainRendererUrl,
  23. isResourceManagerUrl,
  24. openResourceManager,
  25. readResourceUsageSnapshot,
  26. switchToElectronRendererTarget,
  27. waitForResourceManagerReady,
  28. } from "#e2e/helpers/resource-manager";
  29. const ROOT = resolveE2ERuntimePath("background-bash-output", "中文 空格");
  30. const names: string[] = [];
  31. const outputFiles = new Set<string>();
  32. const details = () =>
  33. $('[role="tabpanel"][data-state="active"] [data-testid="background-bash-details"]');
  34. const body = () =>
  35. $('[role="tabpanel"][data-state="active"] [data-testid="background-bash-output"]');
  36. async function release(name: string, phase: number) {
  37. await writeFile(join(ROOT, `${name}.${phase}.release`), "go");
  38. }
  39. async function text() {
  40. return body().getText();
  41. }
  42. async function contains(value: string) {
  43. await browser.waitUntil(async () => (await text()).includes(value), {
  44. timeout: 15000,
  45. timeoutMsg: `后台详情缺少 ${value}`,
  46. });
  47. }
  48. async function openRow() {
  49. await openV4ComposerRunningBackgroundWorks(30000);
  50. const row = await $('[data-testid="background-bash-open"]');
  51. await row.waitForClickable();
  52. await row.click();
  53. await details().waitForDisplayed();
  54. }
  55. async function launch(name: string) {
  56. names.push(name);
  57. // 合并适配:全局新任务落到独立聊天目录,Bash fixture 必须从 ZCodeProject 发起。
  58. await startDraftFromProject(DEFAULT_WORKSPACE);
  59. // 项目新草稿恢复 build;显式选择 yolo,避免把模式切换动画中的旧文案当成已选中。
  60. await switchV4Mode("yolo");
  61. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  62. timeout: 15000,
  63. timeoutMsg: "项目草稿未应用 yolo 模式",
  64. });
  65. await sendV4Prompt(`E2E_BGV_${name}: Run the exact background Bash fixture.`);
  66. await waitForV4AssistantMessageContaining(`E2E_BGV_${name}_DONE`, 60000);
  67. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  68. await openRow();
  69. // 文件入口使用运行时返回的 canonical 路径;临时输出根不再固定在 HOME 下。
  70. const file = $('[role="tabpanel"][data-state="active"] [data-testid="background-bash-file"]');
  71. await file.waitForDisplayed();
  72. const outputPath = await file.getAttribute("title");
  73. if (!outputPath) throw new Error("后台详情没有返回实际输出文件路径");
  74. outputFiles.add(outputPath);
  75. await contains(`${name}_STDERR_中文`);
  76. return { sessionId, outputPath };
  77. }
  78. async function terminal() {
  79. await browser.waitUntil(async () => (await details().getAttribute("data-status")) !== "running", {
  80. timeout: 15000,
  81. });
  82. }
  83. async function expectStatusBarAlignment() {
  84. const gaps = await browser.execute(() => {
  85. const pane = document.querySelector('[role="tabpanel"][data-state="active"]')!;
  86. const bar = pane.querySelector('[data-testid="background-bash-statusbar"]')!;
  87. const file = pane.querySelector('[data-testid="background-bash-file"]')!;
  88. const running = pane.querySelector('[data-testid="background-bash-running"]');
  89. const style = getComputedStyle(bar);
  90. return {
  91. right:
  92. bar.getBoundingClientRect().right -
  93. Number.parseFloat(style.paddingRight) -
  94. file.getBoundingClientRect().right,
  95. left: running
  96. ? running.getBoundingClientRect().left -
  97. bar.getBoundingClientRect().left -
  98. Number.parseFloat(style.paddingLeft)
  99. : 0,
  100. sameColor: !running || getComputedStyle(file).color === getComputedStyle(running).color,
  101. };
  102. });
  103. expect(Math.abs(gaps.right)).toBeLessThanOrEqual(1);
  104. expect(Math.abs(gaps.left)).toBeLessThanOrEqual(1);
  105. expect(gaps.sameColor).toBe(true);
  106. }
  107. async function alive(name: string) {
  108. const pid = Number(await readFile(join(ROOT, `${name}.pid`), "utf8"));
  109. try {
  110. process.kill(pid, 0);
  111. return true;
  112. } catch {
  113. return false;
  114. }
  115. }
  116. async function expectTaskProcessResources(pid: number, running: boolean) {
  117. await openResourceManager();
  118. await switchToElectronRendererTarget(isResourceManagerUrl);
  119. try {
  120. await waitForResourceManagerReady();
  121. await browser.waitUntil(
  122. async () => {
  123. const snapshot = await readResourceUsageSnapshot();
  124. if (!snapshot) return false;
  125. const process = snapshot.processes.find((row) => row.pid === pid);
  126. return running
  127. ? process?.category === "task" && process.sampled && process.memoryBytes > 0
  128. : !process;
  129. },
  130. { timeout: 30_000, interval: 500, timeoutMsg: `任务进程 ${pid} 分类或退出状态未更新` },
  131. );
  132. const snapshot = await readResourceUsageSnapshot();
  133. expect(snapshot).not.toBeNull();
  134. if (!snapshot) throw new Error("资源管理器快照缺失");
  135. const agents = snapshot.processes.filter((row) => row.name.startsWith("zcode-agent-"));
  136. expect(agents.length).toBeGreaterThan(0);
  137. expect(agents.every((row) => row.category === "base")).toBe(true);
  138. expect(new Set(snapshot.processes.map((row) => row.pid)).size).toBe(snapshot.processes.length);
  139. expect(snapshot.app.memoryBytes).toBe(
  140. snapshot.processes.reduce((sum, row) => sum + row.memoryBytes, 0),
  141. );
  142. expect(snapshot.app.cpuPercent).toBeCloseTo(
  143. snapshot.processes.reduce((sum, row) => sum + row.cpuPercent, 0),
  144. 1,
  145. );
  146. for (const metric of ["cpu", "memory"] as const) {
  147. await activateResourceManagerTab(metric);
  148. const group = $('[data-testid="resource-manager-group-task"]');
  149. await expect(group).toBeDisplayed();
  150. await browser.waitUntil(
  151. async () => (await group.getText()).split(/\s+/).includes(String(pid)) === running,
  152. { timeout: 10_000, timeoutMsg: `任务进程 ${pid} 的 ${metric} 分组展示不符` },
  153. );
  154. const toggle = group.$("button");
  155. await toggle.click();
  156. await expect(toggle).toHaveAttribute("aria-expanded", "false");
  157. await toggle.click();
  158. await expect(toggle).toHaveAttribute("aria-expanded", "true");
  159. }
  160. if (running) {
  161. await $('[data-testid="resource-manager-group-task"]').scrollIntoView({ block: "center" });
  162. await browser.saveScreenshot(
  163. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "task-process-memory.png"),
  164. );
  165. }
  166. } finally {
  167. await switchToElectronRendererTarget(isMainRendererUrl);
  168. await closeResourceManagerWindow();
  169. }
  170. }
  171. async function readAgentLogs() {
  172. const logDir = process.env.ZCODE_LOG_DIR!;
  173. const files = (await readdir(logDir)).filter((file) => file.endsWith(".jsonl"));
  174. return (await Promise.all(files.map((file) => readFile(join(logDir, file), "utf8")))).join("\n");
  175. }
  176. describe("后台 Bash 实时输出详情", () => {
  177. before(async function () {
  178. this.timeout(120000);
  179. await rm(ROOT, { recursive: true, force: true });
  180. await mkdir(ROOT, { recursive: true });
  181. await copyFile(
  182. new URL(
  183. "../../fixtures/fs/conversation-session/background-bash-output/writer.cjs",
  184. import.meta.url,
  185. ),
  186. join(ROOT, "writer.cjs"),
  187. );
  188. await prepareV4ConversationE2E();
  189. await switchV4Mode("yolo");
  190. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  191. timeout: 15000,
  192. timeoutMsg: "项目草稿未应用 yolo 模式",
  193. });
  194. // 宿主显示器会截断 1000px 高窗口;800px 仍覆盖原有输出滚动和标签页断言。
  195. await setV4ElectronWindowSize(1440, 800);
  196. });
  197. afterEach(async () => {
  198. // 所有 barrier 均由用例拥有;断言失败也释放 producer,避免遗留后台任务。
  199. for (const name of names.splice(0)) {
  200. for (let phase = 1; phase <= 3; phase++) await release(name, phase);
  201. await browser.waitUntil(async () => !(await alive(name)), { timeout: 15000 });
  202. }
  203. });
  204. after(async () => {
  205. for (const file of outputFiles) await rm(file, { force: true });
  206. await browser.electron.restoreAllMocks();
  207. await clearAppData();
  208. });
  209. for (const [caseId, name] of [
  210. ["BGV01", "EXPLICIT"],
  211. ["BGV02", "AUTO"],
  212. ]) {
  213. it(`${caseId}: 退出前两次更新、两流中文无换行、8 KiB 淘汰与复用标签页 (${name})`, async function () {
  214. this.timeout(120000);
  215. const { outputPath } = await launch(name!);
  216. const taskPid = Number(await readFile(join(ROOT, `${name}.pid`), "utf8"));
  217. if (name === "EXPLICIT") await expectTaskProcessResources(taskPid, true);
  218. expect(await details().$('button[data-testid="background-bash-stop"]').isExisting()).toBe(
  219. false,
  220. );
  221. expect(await details().$("header").isExisting()).toBe(false);
  222. expect(await details().$('[data-testid="background-bash-running"]').isDisplayed()).toBe(true);
  223. await expectStatusBarAlignment();
  224. const requests = await countUpstreamRequests({ includes: [`E2E_BGV_${name}`] });
  225. const id = await details().getAttribute("data-work-id");
  226. await openRow();
  227. expect(await $$(`[data-testid="background-bash-details"][data-work-id="${id}"]`).length).toBe(
  228. 1,
  229. );
  230. await release(name!, 1);
  231. await contains(`${name}_SECOND_中文`);
  232. expect(await text()).not.toContain(`${name}_FIRST`);
  233. expect(Buffer.byteLength(await text())).toBeLessThanOrEqual(8192);
  234. expect(await details().$('[data-testid="background-bash-truncated"]').isExisting()).toBe(
  235. false,
  236. );
  237. expect(
  238. await browser.execute(() => {
  239. const pane = document.querySelector('[role="tabpanel"][data-state="active"]');
  240. const running = pane?.querySelector('[data-testid="background-bash-running"]');
  241. const output = pane?.querySelector('[data-testid="background-bash-scroll"]');
  242. return Boolean(
  243. running &&
  244. output &&
  245. running.getBoundingClientRect().bottom <= output.getBoundingClientRect().top + 1,
  246. );
  247. }),
  248. ).toBe(true);
  249. await expectStatusBarAlignment();
  250. expect((await stat(outputPath)).size).toBeGreaterThan(8192);
  251. await release(name!, 2);
  252. await contains(`${name}_THIRD_no_newline`);
  253. if (name === "EXPLICIT")
  254. await browser.saveScreenshot(
  255. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-bash-live.png"),
  256. );
  257. expect(await alive(name!)).toBe(true);
  258. expect(await details().getAttribute("data-status")).toBe("running");
  259. expect(await countUpstreamRequests({ includes: [`E2E_BGV_${name}`] })).toBe(requests);
  260. await release(name!, 3);
  261. await terminal();
  262. if (name === "EXPLICIT") await expectTaskProcessResources(taskPid, false);
  263. await contains(`${name}_FINAL`);
  264. expect(await details().getAttribute("data-status")).toBe("completed");
  265. expect(await details().$('[data-testid="background-bash-running"]').isExisting()).toBe(false);
  266. await expectStatusBarAlignment();
  267. if (name === "EXPLICIT") {
  268. const logDir = process.env.ZCODE_E2E_RUNTIME_LOG_DIR;
  269. expect(logDir).toBeTruthy();
  270. const files = (await readdir(logDir!)).filter((file) => file.endsWith(".log"));
  271. const logs = (
  272. await Promise.all(files.map((file) => readFile(join(logDir!, file), "utf8")))
  273. ).join("\n");
  274. // 成功日志曾随每秒轮询持续落盘;先确认真实 RPC 日志存在,再验证该查询被 debug 门控。
  275. expect(logs).toContain("[rpc:call]");
  276. expect(logs).not.toContain("[rpc:call] zcode-agent.backgroundBashOutputV4 OK");
  277. }
  278. });
  279. }
  280. it("BGV03: 向上滚动冻结、后台结束保留阅读位置、回到最新显示最终窗口", async function () {
  281. this.timeout(120000);
  282. await launch("PAUSE");
  283. const firstWindow = await text();
  284. const hiddenDetails = await details();
  285. await $('[role="tabpanel"][data-state="active"] [data-testid="background-bash-file"]').click();
  286. await browser.waitUntil(async () => !(await hiddenDetails.isDisplayed()), { timeout: 5000 });
  287. // 等已发出的旧查询结束,再制造新内容;隐藏 tab 不能读取这次变化。
  288. await browser.pause(1200);
  289. await release("PAUSE", 1);
  290. await browser.pause(1500);
  291. expect(await hiddenDetails.$('[data-testid="background-bash-output"]').getHTML()).toContain(
  292. "PAUSE_FIRST",
  293. );
  294. expect(await hiddenDetails.$('[data-testid="background-bash-output"]').getHTML()).not.toContain(
  295. "PAUSE_SECOND",
  296. );
  297. expect(firstWindow).toContain("PAUSE_FIRST");
  298. await openRow();
  299. await contains("PAUSE_SECOND");
  300. const viewport = await $(
  301. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-scroll"]',
  302. );
  303. await browser.waitUntil(
  304. async () => (await viewport.getAttribute("data-scroll-mask")) === "top",
  305. {
  306. timeout: 5000,
  307. timeoutMsg: "后台 Bash 吸底后没有顶部渐隐",
  308. },
  309. );
  310. expect((await viewport.getCSSProperty("mask-image")).value).toContain("linear-gradient");
  311. // 手动滚到底部必须恢复跟随;此前只有按钮调用 resume,实际到底后箭头仍常驻。
  312. await browser.execute(() => {
  313. const el = document.querySelector<HTMLElement>(
  314. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-scroll"]',
  315. )!;
  316. el.scrollTop = 0;
  317. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  318. });
  319. await details().$('[data-testid="background-bash-resume"]').waitForDisplayed();
  320. await browser.execute(() => {
  321. const el = document.querySelector<HTMLElement>(
  322. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-scroll"]',
  323. )!;
  324. el.scrollTop = el.scrollHeight;
  325. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  326. });
  327. const bottomState = await browser.execute(() => {
  328. const pane = document.querySelector(
  329. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-details"]',
  330. )!;
  331. const el = pane.querySelector('[data-testid="background-bash-scroll"]')!;
  332. return {
  333. following: pane.getAttribute("data-following"),
  334. bottomGap: el.scrollHeight - el.clientHeight - el.scrollTop,
  335. };
  336. });
  337. expect(bottomState.bottomGap).toBeLessThanOrEqual(8);
  338. await browser.waitUntil(
  339. async () => (await details().getAttribute("data-following")) === "true",
  340. {
  341. timeout: 5000,
  342. timeoutMsg: `手动到底后未恢复跟随: ${JSON.stringify(bottomState)}`,
  343. },
  344. );
  345. expect(await details().$('[data-testid="background-bash-resume"]').isExisting()).toBe(false);
  346. await release("PAUSE", 2);
  347. await contains("PAUSE_THIRD_no_newline");
  348. expect(await details().getAttribute("data-following")).toBe("true");
  349. await browser.execute(() => {
  350. const el = document.querySelector<HTMLElement>(
  351. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-scroll"]',
  352. )!;
  353. el.scrollTop = (el.scrollHeight - el.clientHeight) / 2;
  354. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  355. });
  356. await browser.waitUntil(
  357. async () => (await viewport.getAttribute("data-scroll-mask")) === "both",
  358. {
  359. timeout: 5000,
  360. timeoutMsg: "后台 Bash 中间位置没有上下渐隐",
  361. },
  362. );
  363. await browser.execute(() => {
  364. const el = document.querySelector<HTMLElement>(
  365. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-scroll"]',
  366. )!;
  367. el.scrollTop = 0;
  368. el.dispatchEvent(new Event("scroll", { bubbles: true }));
  369. });
  370. await $(
  371. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-resume"]',
  372. ).waitForDisplayed();
  373. const resume = await $(
  374. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-resume"]',
  375. );
  376. expect(await resume.getText()).toBe("");
  377. expect(await resume.getAttribute("aria-label")).toMatch(/Scroll to bottom|滚动到底部/i);
  378. expect(
  379. await browser.execute(() => {
  380. const pane = document.querySelector('[role="tabpanel"][data-state="active"]')!;
  381. const button = pane.querySelector<HTMLElement>('[data-testid="background-bash-resume"]')!;
  382. const output = pane.querySelector<HTMLElement>('[data-testid="background-bash-scroll"]')!;
  383. const bar = pane.querySelector('[data-testid="background-bash-statusbar"]');
  384. const rect = button.getBoundingClientRect();
  385. const viewport = output.getBoundingClientRect();
  386. const style = getComputedStyle(button);
  387. return (
  388. !output.contains(button) &&
  389. !bar?.contains(button) &&
  390. style.position === "absolute" &&
  391. Math.abs(rect.width - rect.height) < 1 &&
  392. Number.parseFloat(style.borderRadius) >= rect.width / 2 &&
  393. Math.abs(rect.left + rect.width / 2 - viewport.left - viewport.width / 2) < 1 &&
  394. rect.bottom < viewport.bottom &&
  395. rect.bottom > viewport.bottom - 24 &&
  396. getComputedStyle(button.parentElement!).maskImage === "none"
  397. );
  398. }),
  399. ).toBe(true);
  400. await browser.saveScreenshot(
  401. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-bash-paused.png"),
  402. );
  403. expect(await viewport.getAttribute("data-scroll-mask")).toBe("bottom");
  404. const frozen = await text();
  405. await release("PAUSE", 3);
  406. await terminal();
  407. expect(await text()).toBe(frozen);
  408. await $(
  409. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-resume"]',
  410. ).click();
  411. await contains("PAUSE_FINAL");
  412. await browser.waitUntil(
  413. async () => (await viewport.getAttribute("data-scroll-mask")) === "top",
  414. {
  415. timeout: 5000,
  416. timeoutMsg: "后台 Bash 恢复吸底后渐隐未更新",
  417. },
  418. );
  419. });
  420. it("BGV04: 切换会话隔离标签页,返回立即读取仍在运行的原任务", async function () {
  421. this.timeout(120000);
  422. const first = await launch("SCOPE_A");
  423. const second = await launch("SCOPE_B");
  424. expect(first.sessionId).not.toBe(second.sessionId);
  425. expect(await text()).not.toContain("SCOPE_A");
  426. await release("SCOPE_A", 1);
  427. await selectV4TaskById(first.sessionId);
  428. await openRow();
  429. await contains("SCOPE_A_SECOND");
  430. expect(await text()).not.toContain("SCOPE_B");
  431. expect(await alive("SCOPE_A")).toBe(true);
  432. expect(await alive("SCOPE_B")).toBe(true);
  433. });
  434. it("BGV04: 子会话冷恢复后仍能读取原后台 Bash,完成后保留最终输出", async function () {
  435. this.timeout(360000);
  436. names.push("CHILD");
  437. // 合并适配:全局新任务落到独立聊天目录,Bash fixture 必须从 ZCodeProject 发起。
  438. await startDraftFromProject(DEFAULT_WORKSPACE);
  439. await switchV4Mode("yolo");
  440. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  441. timeout: 15000,
  442. timeoutMsg: "项目草稿未应用 yolo 模式",
  443. });
  444. await sendV4Prompt("E2E_BGV_PARENT: Launch the exact background child fixture.");
  445. await waitForV4AssistantMessageContaining("E2E_BGV_PARENT_DONE", 60000);
  446. const rootSessionId = (await getV4PaneSnapshot()).sessionId;
  447. await openV4ComposerRunningBackgroundWorks(30000);
  448. const entry = await $('[data-running-subagent-session-trigger="true"]');
  449. await entry.waitForClickable({ timeout: 15000 });
  450. const childSessionId = await entry.getAttribute("data-child-session-id");
  451. expect(childSessionId).toBeTruthy();
  452. await entry.click();
  453. const openChildOutput = () =>
  454. browser.waitUntil(
  455. async () =>
  456. browser.execute(() => {
  457. const pane = document.querySelector('[role="tabpanel"][data-state="active"]');
  458. // 浮层通过 Portal 展示;先从当前子会话触发,再在浮层内打开输出。
  459. const button = document.querySelector<HTMLButtonElement>(
  460. '[data-status-capsule-content="activity"] [data-testid="background-bash-open"]',
  461. );
  462. if (button) {
  463. button.click();
  464. return true;
  465. }
  466. const trigger = pane?.querySelector<HTMLButtonElement>(
  467. '[data-status-capsule="activity"]',
  468. );
  469. if (trigger?.dataset.state !== "open") trigger?.click();
  470. return false;
  471. }),
  472. { timeout: 15000, timeoutMsg: "子会话没有显示后台 Bash 入口" },
  473. );
  474. await openChildOutput();
  475. await details().waitForDisplayed();
  476. // 子页 forceMount 隐藏时不会卸载;导航必须主动关闭 Portal,避免浮层跳到左上角。
  477. await browser.waitUntil(
  478. async () => !(await $('[data-status-capsule-content="activity"]').isDisplayed()),
  479. { timeout: 5000, timeoutMsg: "后台输出已打开,但子会话 Activity 浮层仍残留" },
  480. );
  481. await contains("CHILD_STDERR_中文");
  482. const workId = await details().getAttribute("data-work-id");
  483. const outputTabId = await $(
  484. '[data-side-pane-tab-id^="bash-output:"][data-state="active"]',
  485. ).getAttribute("data-side-pane-tab-id");
  486. expect(workId).toBeTruthy();
  487. expect(await details().getAttribute("data-status")).toBe("running");
  488. // 旧任务由祖先 adapter 持有;必须实际释放 child publisher,再经普通订阅创建新 record。
  489. // 保留输出 tab,但关闭 child conversation 的订阅,让现有 120s grace / 60s tick 自然淘汰。
  490. await browser.execute((sessionId) => {
  491. document
  492. .querySelector<HTMLButtonElement>(
  493. `[data-side-pane-tab-id^="subagent-session:"][data-side-pane-tab-id$=":${sessionId}"] button`,
  494. )!
  495. .click();
  496. }, childSessionId);
  497. const releasedMessage = `release detached live child publisher session=${childSessionId}`;
  498. await browser.waitUntil(async () => (await readAgentLogs()).includes(releasedMessage), {
  499. timeout: 260000,
  500. interval: 1000,
  501. timeoutMsg: "子会话 publisher 未实际释放",
  502. });
  503. expect(await alive("CHILD")).toBe(true);
  504. await browser.saveScreenshot(
  505. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-bash-child-released.png"),
  506. );
  507. // Agent 摘要在已折叠的执行历史中;先展开历史,再从真实摘要入口重新订阅 child。
  508. const history = await $(
  509. `[data-session-id="${rootSessionId}"] [data-testid^="chat-assistant-history-trigger-"]`,
  510. );
  511. if ((await history.getAttribute("aria-expanded")) === "false") await history.click();
  512. const childSummary = await $(`[data-testid="v4-subagent-open-side-pane-${childSessionId}"]`);
  513. await childSummary.scrollIntoView();
  514. await childSummary.waitForClickable();
  515. await childSummary.click();
  516. const resumedMessage = `cold resume completed session=${childSessionId}`;
  517. await browser.waitUntil(async () => (await readAgentLogs()).includes(resumedMessage), {
  518. timeout: 15000,
  519. timeoutMsg: "重新打开子会话未完成冷恢复",
  520. });
  521. // 冷恢复不新增历史后台任务目录;回到之前保留的输出 tab,验证它仍能查询原任务。
  522. await $(`[data-side-pane-tab-id="${outputTabId}"]`).click();
  523. await details().waitForDisplayed();
  524. expect(await details().getAttribute("data-work-id")).toBe(workId);
  525. const requests = await countUpstreamRequests({ includes: ["E2E_BGV_CHILD_WORK:"] });
  526. await release("CHILD", 1);
  527. await contains("CHILD_SECOND");
  528. await release("CHILD", 2);
  529. await contains("CHILD_THIRD_no_newline");
  530. expect(await alive("CHILD")).toBe(true);
  531. expect(await countUpstreamRequests({ includes: ["E2E_BGV_CHILD_WORK:"] })).toBe(requests);
  532. await writeFile(
  533. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-bash-cold-resume.json"),
  534. JSON.stringify(
  535. {
  536. childSessionId,
  537. rootSessionId,
  538. workId,
  539. releasedMessage,
  540. resumedMessage,
  541. requests,
  542. output: await text(),
  543. },
  544. null,
  545. 2,
  546. ),
  547. );
  548. await release("CHILD", 3);
  549. await terminal();
  550. await contains("CHILD_FINAL");
  551. expect(await details().getAttribute("data-status")).toBe("completed");
  552. expect((await getV4PaneSnapshot()).sessionId).toBe(rootSessionId);
  553. });
  554. it("BGV05: 文件删除明确报错、保留上一份输出,失败与关闭详情不停止进程", async function () {
  555. this.timeout(120000);
  556. const { outputPath } = await launch("ERROR");
  557. const previous = await text();
  558. await rm(outputPath);
  559. const error = await $(
  560. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-details"] [role="alert"]',
  561. );
  562. await error.waitForDisplayed({ timeout: 15000 });
  563. expect(await error.getText()).toMatch(/无法读取|Could not read/);
  564. expect(await text()).toBe(previous);
  565. expect(await alive("ERROR")).toBe(true);
  566. await $('[data-side-pane-tab-id^="bash-output:"][data-state="active"] button').click();
  567. expect(await alive("ERROR")).toBe(true);
  568. });
  569. it("BGV06: 原后台条目 Stop 后详情保留终态输出,详情本身没有停止按钮", async function () {
  570. this.timeout(120000);
  571. await launch("STOP");
  572. await openV4ComposerRunningBackgroundWorks(30000);
  573. const id = await details().getAttribute("data-work-id");
  574. await $(`[data-testid="v4-background-work-cancel-${id}"]`).click();
  575. await terminal();
  576. expect(await details().getAttribute("data-status")).toBe("cancelled");
  577. await browser.waitUntil(async () => !(await alive("STOP")), { timeout: 15000 });
  578. await contains("STOP_STDERR_中文");
  579. await $(
  580. '[role="tabpanel"][data-state="active"] [data-testid="background-bash-file"]',
  581. ).waitForDisplayed();
  582. });
  583. });