conversation-session-background-history-layout.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import { join } from "node:path";
  2. import { writeFile } from "node:fs/promises";
  3. import { chromium } from "playwright-core";
  4. import { TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  5. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  6. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  7. import { clearAppData } from "#e2e/helpers/desktop-app";
  8. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  9. import {
  10. getUpstreamRequestEvidence,
  11. waitForUpstreamRequest,
  12. } from "#e2e/helpers/conversation-session-network";
  13. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  14. import {
  15. prepareV4ConversationE2E,
  16. sendV4Prompt,
  17. startNewV4Draft,
  18. waitForV4Pane,
  19. waitForV4TimelineContaining,
  20. setV4ElectronWindowSize,
  21. getV4PaneSnapshot,
  22. selectV4TaskById,
  23. } from "#e2e/helpers/v4-conversation";
  24. const artifacts = () => process.env.ZCODE_E2E_ARTIFACT_DIR!;
  25. const EMPTY = "E2E_BG_HISTORY_EMPTY";
  26. const HISTORY = "E2E_BG_HISTORY_HISTORY";
  27. const TITLE = '[data-testid^="chat-background-result-title-"]';
  28. const TRIGGER = '[data-testid^="chat-assistant-history-trigger-"]';
  29. const CONTENT = '[data-testid^="chat-assistant-history-content-"]';
  30. async function assertMobileEmptyHistory() {
  31. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  32. const pairingUrl = await obtainUnreadPairingUrl(
  33. new URL(process.env.ZCODE_WEB_REMOTE_CONTROL_URL!).origin,
  34. );
  35. const executablePath = process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE;
  36. const mobileBrowser = await chromium.launch({
  37. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  38. headless: true,
  39. });
  40. try {
  41. const context = await mobileBrowser.newContext({
  42. viewport: { width: 390, height: 844 },
  43. isMobile: true,
  44. hasTouch: true,
  45. locale: "zh-CN",
  46. });
  47. await seedMobileFixtureLogin(context);
  48. const page = await context.newPage();
  49. await openMobilePairingPage(page, pairingUrl, {
  50. artifactDir: artifacts(),
  51. caseMarker: "BGH01",
  52. phase: "empty-history",
  53. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  54. });
  55. await showMobileTaskHome(page);
  56. for (const toggle of await page.getByTestId("virtual-project-toggle").all()) {
  57. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  58. }
  59. await page.getByTestId(testId(TID_TASK_ITEM, sessionId)).first().click();
  60. const title = page.locator(TITLE).filter({ hasText: EMPTY });
  61. await title.waitFor();
  62. const turn = title.locator("xpath=ancestor::*[@data-turn-key]");
  63. for (const theme of ["light", "dark"] as const) {
  64. await page.evaluate((value) => {
  65. const actions = (window as Window & { __testActions?: { setTheme(theme: string): void } })
  66. .__testActions;
  67. if (!actions) throw new Error("mobile theme actions missing");
  68. actions.setTheme(value);
  69. }, theme);
  70. await page.waitForFunction(
  71. (dark) => document.documentElement.classList.contains("dark") === dark,
  72. theme === "dark",
  73. );
  74. expect(await turn.locator(TRIGGER).count()).toBe(0);
  75. expect(await turn.locator(CONTENT).count()).toBe(0);
  76. const before = await turn.boundingBox();
  77. await turn.getByText(/已工作|Worked/).click();
  78. expect((await turn.boundingBox())!.height).toBe(before!.height);
  79. await page.screenshot({ path: join(artifacts(), `background-empty-mobile-${theme}.png`) });
  80. }
  81. } finally {
  82. await mobileBrowser.close();
  83. }
  84. }
  85. async function launchBackgroundResult(marker: string, gate: string) {
  86. await startNewV4Draft();
  87. await ensureToolCrossProductFullAccessMode();
  88. await sendV4Prompt(marker);
  89. await waitForV4TimelineContaining(marker + "_ACK");
  90. await waitForV4Pane((state) => !state.canStop, "父轮未结束");
  91. await releaseControlledReplay(gate);
  92. await waitForUpstreamRequest(
  93. { lastUserMessageIncludes: ["<task-notification>", marker + "_CHILD_RESULT"] },
  94. "非空子代理结果未进入父模型请求",
  95. 60_000,
  96. );
  97. await browser.waitUntil(
  98. () =>
  99. browser.execute(
  100. (selector, title) =>
  101. [...document.querySelectorAll(selector)].some((node) => node.textContent === title),
  102. TITLE,
  103. marker,
  104. ),
  105. { timeout: 60_000, timeoutMsg: "后台结果标题未出现" },
  106. );
  107. await waitForV4Pane((state) => !state.canStop, "后台唤醒轮未结束");
  108. const requests = await getUpstreamRequestEvidence({
  109. lastUserMessageIncludes: ["<task-notification>", marker + "_CHILD_RESULT"],
  110. });
  111. expect(requests.map((request) => request.fixtureId)).toEqual([
  112. marker === EMPTY ? "bg-history-empty-empty" : "bg-history-history-tool",
  113. ]);
  114. }
  115. async function assertEmptyHistory(marker: string) {
  116. const result = (await browser.executeAsync(
  117. (selectors, title, done) => {
  118. const node = [...document.querySelectorAll<HTMLElement>(selectors.title)].find(
  119. (item) => item.textContent === title,
  120. )!;
  121. const turn = node.closest<HTMLElement>("[data-turn-key]")!;
  122. const shell = node.closest<HTMLElement>('[data-slot="collapsible"]')!;
  123. const status = shell.firstElementChild as HTMLElement;
  124. const viewport = turn.closest<HTMLElement>('[data-testid="v4-timeline"]')!;
  125. const before = { height: turn.getBoundingClientRect().height, top: viewport.scrollTop };
  126. status.click();
  127. requestAnimationFrame(() =>
  128. requestAnimationFrame(() =>
  129. done({
  130. triggerCount: turn.querySelectorAll(selectors.trigger).length,
  131. contentCount: turn.querySelectorAll(selectors.content).length,
  132. statusButtons: status.querySelectorAll("button, [role=button], svg").length,
  133. status: status.textContent,
  134. rawResultVisible: turn.innerText.includes(title + "_CHILD_RESULT"),
  135. heightDelta: turn.getBoundingClientRect().height - before.height,
  136. scrollDelta: viewport.scrollTop - before.top,
  137. }),
  138. ),
  139. );
  140. },
  141. { title: TITLE, trigger: TRIGGER, content: CONTENT },
  142. marker,
  143. )) as {
  144. status: string;
  145. triggerCount: number;
  146. contentCount: number;
  147. statusButtons: number;
  148. rawResultVisible: boolean;
  149. heightDelta: number;
  150. scrollDelta: number;
  151. };
  152. expect(result).toMatchObject({
  153. triggerCount: 0,
  154. contentCount: 0,
  155. statusButtons: 0,
  156. rawResultVisible: false,
  157. heightDelta: 0,
  158. scrollDelta: 0,
  159. });
  160. expect(result.status).toMatch(/已工作|Worked/);
  161. }
  162. interface Sample {
  163. height: number;
  164. contentHeight: number;
  165. hidden: boolean;
  166. elapsed: number;
  167. }
  168. async function toggleHistory(open: boolean) {
  169. const result = (await browser.executeAsync(
  170. (selectors, shouldOpen, done) => {
  171. const node = [...document.querySelectorAll<HTMLElement>(selectors.title)].find(
  172. (item) => item.textContent === "E2E_BG_HISTORY_HISTORY",
  173. )!;
  174. const shell = node.closest<HTMLElement>('[data-slot="collapsible"]')!;
  175. const trigger = shell.querySelector<HTMLElement>(selectors.trigger)!;
  176. const content = shell.querySelector<HTMLElement>(selectors.content)!;
  177. const started = performance.now();
  178. const samples: Sample[] = [];
  179. const sample = () => ({
  180. height: shell.getBoundingClientRect().height,
  181. contentHeight: content.getBoundingClientRect().height,
  182. hidden: getComputedStyle(content).display === "none",
  183. elapsed: performance.now() - started,
  184. });
  185. samples.push(sample());
  186. trigger.click();
  187. let stable = 0;
  188. const tick = () => {
  189. const current = sample();
  190. samples.push(current);
  191. const animating = shell
  192. .getAnimations({ subtree: true })
  193. .some(
  194. (animation) =>
  195. animation.playState === "running" &&
  196. animation.effect?.getComputedTiming().iterations !== Infinity,
  197. );
  198. const settled =
  199. trigger.getAttribute("aria-expanded") === String(shouldOpen) &&
  200. current.hidden !== shouldOpen &&
  201. !animating;
  202. stable = settled ? stable + 1 : 0;
  203. if (stable >= 3 || current.elapsed > 2000) {
  204. done({
  205. samples,
  206. settled,
  207. finalVisible: shell.innerText.includes("E2E_BG_HISTORY_HISTORY_FINAL"),
  208. });
  209. } else requestAnimationFrame(tick);
  210. };
  211. requestAnimationFrame(tick);
  212. },
  213. { title: TITLE, trigger: TRIGGER, content: CONTENT },
  214. open,
  215. )) as { samples: Sample[]; settled: boolean; finalVisible: boolean };
  216. expect(result.settled).toBe(true);
  217. expect(result.finalVisible).toBe(true);
  218. // 外层不应在内容 display:none 时额外丢失一个 gap;动画全过程的非内容高度保持一致。
  219. const baseHeights = result.samples.map((sample) => sample.height - sample.contentHeight);
  220. expect(Math.max(...baseHeights) - Math.min(...baseHeights)).toBeLessThanOrEqual(2);
  221. await writeFile(
  222. join(artifacts(), open ? "background-open.json" : "background-close.json"),
  223. JSON.stringify(result, null, 2),
  224. );
  225. }
  226. describe("BGH01 后台结果空历史与折叠高度", () => {
  227. before(async function () {
  228. this.timeout(120_000);
  229. await prepareV4ConversationE2E();
  230. });
  231. after(async () => {
  232. await browser.electron.restoreAllMocks();
  233. await clearAppData();
  234. });
  235. it("子代理有结果、父回复为空:状态没有箭头和空折叠区,窄屏与主题切换保持稳定", async function () {
  236. this.timeout(180_000);
  237. await launchBackgroundResult(EMPTY, "bg-history-empty-child");
  238. for (const [width, theme] of [
  239. [1280, "dark"],
  240. [480, "light"],
  241. ] as const) {
  242. await setV4ElectronWindowSize(width, 800);
  243. await browser.execute((value) => {
  244. (
  245. window as Window & { __testActions?: { setTheme(theme: string): void } }
  246. ).__testActions?.setTheme(value);
  247. }, theme);
  248. await browser.waitUntil(() =>
  249. browser.execute(
  250. (dark) => document.documentElement.classList.contains("dark") === dark,
  251. theme === "dark",
  252. ),
  253. );
  254. await assertEmptyHistory(EMPTY);
  255. await browser.saveScreenshot(join(artifacts(), `background-empty-${width}-${theme}.png`));
  256. }
  257. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  258. await browser.refresh();
  259. await selectV4TaskById(sessionId);
  260. await waitForV4TimelineContaining(EMPTY);
  261. await assertEmptyHistory(EMPTY);
  262. await setV4ElectronWindowSize(1280, 800);
  263. await assertMobileEmptyHistory();
  264. });
  265. it("有历史:展开收起保留正文,最后一帧无额外间距跳变", async function () {
  266. this.timeout(180_000);
  267. await launchBackgroundResult(HISTORY, "bg-history-history-child");
  268. await waitForV4TimelineContaining(HISTORY + "_FINAL");
  269. await toggleHistory(true);
  270. await toggleHistory(false);
  271. await browser.saveScreenshot(join(artifacts(), "background-content-closed.png"));
  272. });
  273. });