conversation-session-status-panel-inline-layout.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { setRendererViewport, clearRendererViewport } from "#e2e/helpers/renderer-viewport";
  4. import { chromium } from "playwright-core";
  5. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  6. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  7. import {
  8. TID_CHAT_SUMMARY_PANEL,
  9. TID_TASK_ITEM,
  10. TID_TASK_NEW_BUTTON,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import { clearAppData } from "#e2e/helpers/desktop-app";
  14. import {
  15. E2E_REPLY_TOKEN,
  16. getV4ConversationState,
  17. selectV4TaskById,
  18. prepareV4ConversationE2E,
  19. sendV4Prompt,
  20. startNewV4Draft,
  21. waitForV4AssistantMessageContaining,
  22. waitForV4ConversationState,
  23. waitForV4ComposerText,
  24. waitForV4UserMessageContaining,
  25. } from "#e2e/helpers/v4-conversation";
  26. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/composer-width");
  27. let completedTaskId: string;
  28. const WIDE_VIEWPORT = { width: 1800, height: 1000 };
  29. const NARROW_VIEWPORT = { width: 1200, height: 900 };
  30. const DRAFT_WIDTH_CLASS = "max-w-2xl";
  31. const NORMAL_WIDTH_CLASS =
  32. "w-full @min-[864px]/conversation:w-[calc(100%_-_6rem)] @min-[864px]/conversation:max-w-4xl @min-[1280px]/conversation:w-[calc(100%_-_24rem)] @min-[1280px]/conversation:max-w-6xl";
  33. const INLINE_WIDTH_CLASS = NORMAL_WIDTH_CLASS;
  34. const INLINE_OFFSET_CLASS = "@min-[1280px]/conversation:-translate-x-42";
  35. describe("会话区 status panel inline layout E2E", () => {
  36. after(async () => {
  37. await clearRendererViewport();
  38. await browser.electron.restoreAllMocks();
  39. await clearAppData();
  40. });
  41. it("status panel 只有出现 inline 偏移时才收敛消息列和输入区宽度", async function () {
  42. this.timeout(180000);
  43. await setRendererViewport(WIDE_VIEWPORT.width, WIDE_VIEWPORT.height);
  44. await prepareV4ConversationE2E();
  45. await setRendererViewport(WIDE_VIEWPORT.width, WIDE_VIEWPORT.height);
  46. const draftLayout = await waitForChatLayoutSnapshot(
  47. (snapshot) =>
  48. snapshot.panelState === null &&
  49. snapshot.dockClassName.includes(DRAFT_WIDTH_CLASS) &&
  50. !snapshot.dockClassName.includes(INLINE_OFFSET_CLASS),
  51. "新建草稿没有保持无 status panel 的窄 composer 布局",
  52. );
  53. expect(draftLayout.panelState).toBeNull();
  54. const runId = Date.now();
  55. const plainPrompt = `E2E_STATUS_PANEL_EMPTY_${runId}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  56. await sendV4Prompt(plainPrompt);
  57. await waitForV4ComposerText("", "普通首发后输入框没有清空");
  58. await waitForV4UserMessageContaining(plainPrompt);
  59. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  60. await waitForV4ConversationState(
  61. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  62. "普通首发完成后没有回到 idle",
  63. 90000,
  64. );
  65. const noPanelLayout = await waitForChatLayoutSnapshot(
  66. (snapshot) =>
  67. snapshot.panelState === null &&
  68. snapshot.contentClassName?.includes(NORMAL_WIDTH_CLASS) === true &&
  69. snapshot.dockClassName.includes(NORMAL_WIDTH_CLASS) &&
  70. !snapshot.hasContentInlineOffset &&
  71. !snapshot.hasDockInlineOffset,
  72. "无 status 内容的历史 task 没有保持普通消息列宽度",
  73. );
  74. expect(noPanelLayout.panelState).toBeNull();
  75. const taskId = (await getV4ConversationState()).taskId;
  76. if (!taskId) throw new Error("completed task missing");
  77. completedTaskId = taskId;
  78. await mkdir(artifactDir, { recursive: true });
  79. for (const theme of ["zai-light", "zai-dark"] as const) {
  80. await browser.execute((value) => {
  81. const actions = (window as Window & { __testActions?: { setTheme(theme: string): void } })
  82. .__testActions;
  83. if (!actions) throw new Error("theme actions missing");
  84. actions.setTheme(value);
  85. }, theme);
  86. for (const viewport of [NARROW_VIEWPORT, WIDE_VIEWPORT]) {
  87. await setRendererViewport(viewport.width, viewport.height);
  88. await startNewV4Draft();
  89. await startLayoutTrace();
  90. await selectV4TaskById(completedTaskId);
  91. const trace = await finishLayoutTrace();
  92. const name = `composer-${theme}-${viewport.width}`;
  93. await writeFile(join(artifactDir, `${name}.json`), JSON.stringify(trace, null, 2));
  94. await browser.saveScreenshot(join(artifactDir, `${name}.png`));
  95. expect(trace.transitions).toEqual([]);
  96. const conversationFrames = trace.widths.filter((frame) => frame.content !== null);
  97. expect(conversationFrames.length).toBeGreaterThan(0);
  98. expect(
  99. conversationFrames.every((frame) => Math.abs(frame.dock - frame.content!) <= 1),
  100. ).toBe(true);
  101. const layout = await getChatLayoutSnapshot();
  102. expect(layout.dockTransitionDuration).toBe("0s");
  103. expect(layout.contentTransitionDuration).toBe("0s");
  104. expect(Math.abs(layout.bottomGap - 16)).toBeLessThanOrEqual(1);
  105. expect(layout.dockBottomPadding).toBe("0px");
  106. expect(layout.messageMask).toBe("none");
  107. }
  108. }
  109. // 首帧断言必须在新建点击前注册,不能复用等到草稿就绪后才返回的 helper。
  110. await setRendererViewport(1400, 900);
  111. const draftFrames = await browser.executeAsync(
  112. (
  113. newTaskTestId,
  114. done: (frames: Array<{ x: number; error: number; animations: number }>) => void,
  115. ) => {
  116. const frames: Array<{ x: number; error: number; animations: number }> = [];
  117. const capture = () => {
  118. const pane = document.querySelector('[data-session-id="draft"]');
  119. const dock = pane?.querySelector<HTMLElement>("[data-v4-composer-dock-content]");
  120. const composer = dock?.querySelector<HTMLElement>('[data-testid="v4-composer"]');
  121. if (!dock || !composer) return;
  122. const outer = dock.parentElement!.getBoundingClientRect();
  123. const input = composer.getBoundingClientRect();
  124. frames.push({
  125. x: input.x,
  126. error: input.x + input.width / 2 - outer.x - outer.width / 2,
  127. animations: dock.getAnimations().length,
  128. });
  129. if (frames.length < 18) requestAnimationFrame(capture);
  130. else done(frames);
  131. };
  132. const observer = new MutationObserver(() => {
  133. if (!document.querySelector('[data-session-id="draft"] [data-testid="v4-composer"]'))
  134. return;
  135. observer.disconnect();
  136. capture();
  137. });
  138. observer.observe(document.body, { subtree: true, attributes: true, childList: true });
  139. document.querySelector<HTMLElement>(`[data-testid="${newTaskTestId}"]`)!.click();
  140. },
  141. TID_TASK_NEW_BUTTON,
  142. );
  143. expect(draftFrames).toHaveLength(18);
  144. for (const frame of draftFrames) {
  145. expect(Math.abs(frame.error)).toBeLessThanOrEqual(1);
  146. expect(Math.abs(frame.x - draftFrames[0]!.x)).toBeLessThanOrEqual(1);
  147. expect(frame.animations).toBe(0);
  148. }
  149. await setRendererViewport(WIDE_VIEWPORT.width, WIDE_VIEWPORT.height);
  150. const goalMarker = `E2E_STATUS_PANEL_GOAL_${runId}`;
  151. const goalPrompt = `/goal ${goalMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  152. await sendV4Prompt(goalPrompt);
  153. await waitForV4ComposerText("", "goal 首发后输入框没有清空");
  154. await waitForV4UserMessageContaining(goalMarker);
  155. await waitForV4ConversationState(
  156. (snapshot) =>
  157. snapshot.targetObjective?.includes(goalMarker) === true && Boolean(snapshot.taskId),
  158. "goal 首发没有形成 status panel 可展示的 target",
  159. 60000,
  160. );
  161. await expectInlinePanelLayout("宽屏自动展开 status panel 后没有同步收敛聊天宽度");
  162. await setRendererViewport(NARROW_VIEWPORT.width, NARROW_VIEWPORT.height);
  163. await expectMiniPanelLayout("窄屏自动收起 status panel 后没有恢复普通聊天宽度");
  164. await setRendererViewport(WIDE_VIEWPORT.width, WIDE_VIEWPORT.height);
  165. await expectInlinePanelLayout("重新放大后自动展开 status panel 没有恢复 inline 布局");
  166. await clickSummaryPanelButton(["Collapse to capsule", "收起为胶囊"]);
  167. await expectMiniPanelLayout("手动收起 status panel 后没有移除 inline 偏移");
  168. await clickSummaryPanelButton(["Expand status", "展开状态"]);
  169. await expectInlinePanelLayout("手动展开 status panel 后没有恢复 inline 偏移");
  170. });
  171. it("手机 Web 打开历史对话和刷新时输入区无布局过渡,深浅主题均不溢出", async function () {
  172. this.timeout(180000);
  173. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  174. if (!endpoint || !completedTaskId) throw new Error("mobile fixture or completed task missing");
  175. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  176. const executablePath = process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE;
  177. const chrome = await chromium.launch({
  178. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  179. headless: true,
  180. });
  181. try {
  182. const context = await chrome.newContext({
  183. viewport: { width: 390, height: 844 },
  184. isMobile: true,
  185. hasTouch: true,
  186. locale: "zh-CN",
  187. });
  188. await seedMobileFixtureLogin(context);
  189. const page = await context.newPage();
  190. await openMobilePairingPage(page, pairingUrl, {
  191. artifactDir,
  192. caseMarker: "SP07",
  193. phase: "pairing",
  194. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  195. });
  196. for (const theme of ["zai-light", "zai-dark"] as const) {
  197. await page.evaluate((value) => {
  198. const actions = (window as Window & { __testActions?: { setTheme(theme: string): void } })
  199. .__testActions;
  200. if (!actions) throw new Error("mobile theme actions missing");
  201. actions.setTheme(value);
  202. }, theme);
  203. await showMobileTaskHome(page);
  204. const toggles = page.getByTestId("virtual-project-toggle");
  205. for (let index = 0; index < (await toggles.count()); index++) {
  206. const toggle = toggles.nth(index);
  207. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  208. }
  209. await page.getByTestId(testId(TID_TASK_ITEM, completedTaskId)).first().click();
  210. for (const phase of ["open", "reload"]) {
  211. if (phase === "reload") await page.reload();
  212. await page
  213. .locator(`[data-session-id="${completedTaskId}"]`)
  214. .getByText(E2E_REPLY_TOKEN, { exact: false })
  215. .first()
  216. .waitFor();
  217. const geometry = await page
  218. .locator("[data-v4-composer-dock-content]")
  219. .evaluate((dock) => {
  220. const rect = dock.getBoundingClientRect();
  221. const scroll = dock.closest<HTMLElement>('[data-v4-timeline-scroll="true"]')!;
  222. const message = scroll.querySelector<HTMLElement>(
  223. "[data-v4-timeline-message-layer]",
  224. )!;
  225. return {
  226. left: rect.left,
  227. right: rect.right,
  228. viewport: innerWidth,
  229. duration: getComputedStyle(dock).transitionDuration,
  230. translate: getComputedStyle(dock).translate,
  231. bottomGap:
  232. scroll.parentElement!.getBoundingClientRect().bottom -
  233. scroll.getBoundingClientRect().bottom,
  234. dockBottomPadding: getComputedStyle(dock).paddingBottom,
  235. messageMask: getComputedStyle(message).maskImage,
  236. };
  237. });
  238. expect(geometry.duration).toBe("0s");
  239. expect(geometry.left).toBeGreaterThanOrEqual(0);
  240. expect(geometry.right).toBeLessThanOrEqual(geometry.viewport);
  241. expect(["none", "0px"]).toContain(geometry.translate);
  242. expect(Math.abs(geometry.bottomGap - 16)).toBeLessThanOrEqual(1);
  243. expect(geometry.dockBottomPadding).toBe("0px");
  244. expect(geometry.messageMask).toBe("none");
  245. await page.screenshot({
  246. path: join(artifactDir, `composer-mobile-${theme}-${phase}.png`),
  247. });
  248. }
  249. }
  250. } finally {
  251. await chrome.close();
  252. }
  253. });
  254. });
  255. async function expectInlinePanelLayout(timeoutMsg: string) {
  256. const snapshot = await waitForChatLayoutSnapshot(
  257. (current) =>
  258. current.panelState === "expanded" &&
  259. current.contentClassName?.includes(INLINE_WIDTH_CLASS) === true &&
  260. current.dockClassName.includes(INLINE_WIDTH_CLASS) &&
  261. current.hasContentInlineOffset &&
  262. current.hasDockInlineOffset &&
  263. current.contentTransitionDuration === "0s" &&
  264. current.dockTransitionDuration === "0s",
  265. timeoutMsg,
  266. );
  267. expect(snapshot.panelState).toBe("expanded");
  268. }
  269. async function expectMiniPanelLayout(timeoutMsg: string) {
  270. const snapshot = await waitForChatLayoutSnapshot(
  271. (current) =>
  272. current.panelState === "collapsed" &&
  273. current.contentClassName?.includes(NORMAL_WIDTH_CLASS) === true &&
  274. current.dockClassName.includes(NORMAL_WIDTH_CLASS) &&
  275. !current.hasContentInlineOffset &&
  276. !current.hasDockInlineOffset &&
  277. current.contentTransitionDuration === "0s" &&
  278. current.dockTransitionDuration === "0s",
  279. timeoutMsg,
  280. );
  281. expect(snapshot.panelState).toBe("collapsed");
  282. }
  283. async function waitForChatLayoutSnapshot(
  284. predicate: (snapshot: ChatLayoutSnapshot) => boolean,
  285. timeoutMsg: string,
  286. timeout = 30000,
  287. ) {
  288. let latest: ChatLayoutSnapshot | null = null;
  289. try {
  290. await browser.waitUntil(
  291. async () => {
  292. latest = await getChatLayoutSnapshot();
  293. return predicate(latest);
  294. },
  295. {
  296. timeout,
  297. timeoutMsg,
  298. },
  299. );
  300. } catch (error) {
  301. latest = await getChatLayoutSnapshot().catch(() => latest);
  302. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  303. cause: error,
  304. });
  305. }
  306. return getChatLayoutSnapshot();
  307. }
  308. interface ChatLayoutSnapshot {
  309. containerWidth: number;
  310. contentClassName: string | null;
  311. contentTransitionProperty: string;
  312. contentTransitionDuration: string;
  313. dockClassName: string;
  314. dockTransitionProperty: string;
  315. dockTransitionDuration: string;
  316. hasContentInlineOffset: boolean;
  317. hasDockInlineOffset: boolean;
  318. panelState: string | null;
  319. bottomGap: number;
  320. dockBottomPadding: string;
  321. messageMask: string;
  322. }
  323. function getChatLayoutSnapshot(): Promise<ChatLayoutSnapshot> {
  324. return browser.execute((summaryPanelTestId) => {
  325. const panel = document.querySelector<HTMLElement>(`[data-testid="${summaryPanelTestId}"]`);
  326. // V4 的内容列和 dock 都有专用锚点;旧 chat-message 容器已不存在。
  327. const pane = document.querySelector('[data-testid="v4-session-pane-workspace-main"]');
  328. const dock = pane?.querySelector<HTMLElement>("[data-v4-composer-dock-content]") ?? null;
  329. const content = pane?.querySelector<HTMLElement>("[data-v4-timeline-virtual-history]") ?? null;
  330. const container = pane?.querySelector<HTMLElement>('[class*="@container/conversation"]');
  331. const fullPanelButton = panel?.querySelector<HTMLElement>(
  332. 'button[aria-label="Collapse to capsule"], button[aria-label="收起为胶囊"]',
  333. );
  334. const contentStyle = content ? window.getComputedStyle(content) : null;
  335. const dockStyle = dock ? window.getComputedStyle(dock) : null;
  336. const scroll = dock?.closest<HTMLElement>('[data-v4-timeline-scroll="true"]');
  337. const message = scroll?.querySelector<HTMLElement>("[data-v4-timeline-message-layer]");
  338. return {
  339. containerWidth: container?.getBoundingClientRect().width ?? 0,
  340. contentClassName: content?.className ?? null,
  341. contentTransitionProperty: contentStyle?.transitionProperty ?? "",
  342. contentTransitionDuration: contentStyle?.transitionDuration ?? "",
  343. dockClassName: dock?.className ?? "",
  344. dockTransitionProperty: dockStyle?.transitionProperty ?? "",
  345. dockTransitionDuration: dockStyle?.transitionDuration ?? "",
  346. bottomGap: scroll
  347. ? scroll.parentElement!.getBoundingClientRect().bottom -
  348. scroll.getBoundingClientRect().bottom
  349. : 0,
  350. dockBottomPadding: dockStyle?.paddingBottom ?? "",
  351. messageMask: message ? getComputedStyle(message).maskImage : "none",
  352. hasContentInlineOffset: Math.abs(Number.parseFloat(contentStyle?.translate ?? "0") + 168) < 1,
  353. hasDockInlineOffset: Math.abs(Number.parseFloat(dockStyle?.translate ?? "0") + 168) < 1,
  354. panelState: panel
  355. ? fullPanelButton && fullPanelButton.getBoundingClientRect().width > 0
  356. ? "expanded"
  357. : "collapsed"
  358. : null,
  359. };
  360. }, TID_CHAT_SUMMARY_PANEL);
  361. }
  362. async function clickSummaryPanelButton(labels: readonly string[]) {
  363. const clicked = await browser.execute(
  364. (summaryPanelTestId, candidateLabels) => {
  365. const panel = document.querySelector<HTMLElement>(`[data-testid="${summaryPanelTestId}"]`);
  366. const buttons = Array.from(panel?.querySelectorAll<HTMLButtonElement>("button") ?? []);
  367. const button = buttons.find((item) =>
  368. candidateLabels.includes(item.getAttribute("aria-label") ?? ""),
  369. );
  370. button?.click();
  371. return Boolean(button);
  372. },
  373. TID_CHAT_SUMMARY_PANEL,
  374. labels,
  375. );
  376. if (!clicked) {
  377. throw new Error(`没有找到 status panel 按钮: ${labels.join(" / ")}`);
  378. }
  379. }
  380. interface LayoutTrace {
  381. transitions: { property: string; target: string }[];
  382. widths: { time: number; dock: number; content: number | null }[];
  383. }
  384. type LayoutTraceWindow = Window & { __finishComposerLayoutTrace?: () => LayoutTrace };
  385. async function startLayoutTrace() {
  386. await browser.execute(() => {
  387. const trace: LayoutTrace = { transitions: [], widths: [] };
  388. const selector = "[data-v4-composer-dock-content], [data-v4-timeline-content-column]";
  389. const started = performance.now();
  390. let frame = 0;
  391. const sample = () => {
  392. const dock = document.querySelector<HTMLElement>("[data-v4-composer-dock-content]");
  393. const content = document.querySelector<HTMLElement>("[data-v4-timeline-virtual-history]");
  394. if (dock) {
  395. const width = dock.getBoundingClientRect().width;
  396. const contentWidth = content?.getBoundingClientRect().width ?? null;
  397. const previous = trace.widths.at(-1);
  398. if (previous?.dock !== width || previous?.content !== contentWidth)
  399. trace.widths.push({
  400. time: performance.now() - started,
  401. dock: width,
  402. content: contentWidth,
  403. });
  404. }
  405. frame = requestAnimationFrame(sample);
  406. };
  407. const onTransition = (event: TransitionEvent) => {
  408. if (event.target instanceof HTMLElement && event.target.matches(selector))
  409. trace.transitions.push({ property: event.propertyName, target: event.target.className });
  410. };
  411. document.addEventListener("transitionrun", onTransition, true);
  412. sample();
  413. (window as LayoutTraceWindow).__finishComposerLayoutTrace = () => {
  414. cancelAnimationFrame(frame);
  415. document.removeEventListener("transitionrun", onTransition, true);
  416. delete (window as LayoutTraceWindow).__finishComposerLayoutTrace;
  417. return trace;
  418. };
  419. });
  420. }
  421. async function finishLayoutTrace(): Promise<LayoutTrace> {
  422. return browser.execute(async () => {
  423. // 采样窗口覆盖原有 150ms 过渡,不用固定暂停掩盖产品布局变化。
  424. const start = performance.now();
  425. await new Promise<void>((resolve) => {
  426. const sample = () =>
  427. performance.now() - start >= 300 ? resolve() : requestAnimationFrame(sample);
  428. requestAnimationFrame(sample);
  429. });
  430. const finish = (window as LayoutTraceWindow).__finishComposerLayoutTrace;
  431. if (!finish) throw new Error("layout trace missing");
  432. return finish();
  433. });
  434. }