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

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