conversation-timeline-resize.test.mjs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. import { registerMarkdownTableMotionCases } from "./markdown-table-motion.cases.mjs";
  2. // SRM10:真实 React timeline、消息组件和 TanStack virtualizer;会话数据由确定性 fixture 提供。
  3. import assert from "node:assert/strict";
  4. import { before, after, test } from "node:test";
  5. import { fileURLToPath } from "node:url";
  6. import { mkdir, writeFile } from "node:fs/promises";
  7. import { join } from "node:path";
  8. import { createServer } from "vite";
  9. import react from "@vitejs/plugin-react";
  10. import tailwindcss from "@tailwindcss/vite";
  11. import { chromium } from "playwright-core";
  12. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  13. const entry =
  14. "/packages/ui/test/browser/manual-review/pending/conversation-timeline-resize.fixture.tsx";
  15. const artifacts =
  16. process.env.ZCODE_E2E_ARTIFACT_DIR ||
  17. join(root, "packages/desktop/.e2e-artifacts/conversation-timeline-resize");
  18. let server, browser, origin;
  19. before(async () => {
  20. await mkdir(artifacts, { recursive: true });
  21. server = await createServer({
  22. root,
  23. configFile: false,
  24. cacheDir: join(artifacts, "vite-cache"),
  25. plugins: [
  26. {
  27. name: "timeline-fixture",
  28. enforce: "pre",
  29. configureServer(vite) {
  30. vite.middlewares.use(async (req, res, next) => {
  31. if (!req.url?.startsWith("/fixture?")) return next();
  32. res.setHeader("Content-Type", "text/html");
  33. res.end(
  34. await vite.transformIndexHtml(
  35. req.url,
  36. `<!doctype html><html><head><link rel="icon" href="data:," /><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  37. ),
  38. );
  39. });
  40. },
  41. },
  42. react(),
  43. tailwindcss(),
  44. ],
  45. resolve: { alias: { "@": `${root}packages/ui/src` } },
  46. optimizeDeps: { entries: [entry.slice(1)] },
  47. server: {
  48. host: "127.0.0.1",
  49. port: 0,
  50. hmr: false,
  51. watch: { ignored: ["**/packages/desktop/out/**", "**/.e2e-artifacts/**"] },
  52. },
  53. });
  54. await server.listen();
  55. origin = server.resolvedUrls.local[0];
  56. browser = await chromium.launch(
  57. process.env.CHROME_EXECUTABLE_PATH
  58. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  59. : { channel: "chrome" },
  60. );
  61. });
  62. after(async () => {
  63. await browser?.close();
  64. await server?.close();
  65. });
  66. for (const mobile of [false, true])
  67. for (const theme of ["light", "dark"])
  68. for (const terminal of ["stop", "complete", "fail"])
  69. for (const reading of [false, true])
  70. test(`SSV06 terminal identity ${mobile ? "mobile" : "desktop"}/${theme}/${terminal}/${reading ? "reading" : "following"}`, async () => {
  71. const page = await browser.newPage({
  72. viewport: { width: mobile ? 430 : 1250, height: 800 },
  73. isMobile: mobile,
  74. hasTouch: mobile,
  75. });
  76. const errors = [];
  77. page.on("pageerror", (error) => errors.push(String(error)));
  78. page.on("console", (message) => {
  79. if (message.type() === "error") errors.push(message.text());
  80. });
  81. const prefix = `terminal-${mobile}-${theme}-${terminal}-${reading}`;
  82. let evidence;
  83. try {
  84. await page.goto(
  85. `${origin}fixture?mobile=${mobile}&theme=${theme}&terminal=${terminal}`,
  86. );
  87. await page.locator('[data-row-id="8"]').waitFor();
  88. await page.evaluate(async (detached) => {
  89. await Promise.all(
  90. document
  91. .getAnimations()
  92. .filter((a) => Number.isFinite(a.effect?.getComputedTiming().iterations))
  93. .map((a) => a.finished.catch(() => {})),
  94. );
  95. const timeline = document.querySelector('[data-testid="v4-timeline"]');
  96. if (detached) {
  97. timeline.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -200 }));
  98. // 阅读顶部历史;完成时过程区折叠后,该位置仍可表示,排除浏览器正常 clamp。
  99. timeline.scrollTop = 0;
  100. timeline.dispatchEvent(new Event("scroll"));
  101. }
  102. await new Promise((resolve) =>
  103. requestAnimationFrame(() => requestAnimationFrame(resolve)),
  104. );
  105. const ids = [3, 5, 6, 7];
  106. const nodes = ids.map((id) => document.querySelector(`[data-row-id="${id}"]`));
  107. if (nodes.some((node) => !node)) throw new Error("SSV06 初始消息缺失");
  108. const turn = nodes[1].closest("[data-v4-turn-unit]");
  109. const probe = { ids, nodes, turn, timeline, animations: [], samples: [] };
  110. probe.listener = (event) => {
  111. if (
  112. event.target instanceof Element &&
  113. probe.ids.some((id) =>
  114. event.target.contains(document.querySelector(`[data-row-id="${id}"]`)),
  115. )
  116. )
  117. probe.animations.push(event.animationName);
  118. };
  119. document.addEventListener("animationstart", probe.listener);
  120. window.__stopIdentityProbe = probe;
  121. }, reading);
  122. await page.getByRole("button", { name: "Stop", exact: true }).click();
  123. evidence = await page.evaluate(async () => {
  124. const probe = window.__stopIdentityProbe;
  125. for (let frame = 0; frame < 24; frame++) {
  126. await new Promise(requestAnimationFrame);
  127. const nodes = probe.ids.map((id) =>
  128. document.querySelector(`[data-row-id="${id}"]`),
  129. );
  130. probe.samples.push({
  131. sameTimeline:
  132. document.querySelector('[data-testid="v4-timeline"]') === probe.timeline,
  133. sameTurn:
  134. document.querySelector('[data-v4-turn-unit][data-turn-id="terminal-turn"]') ===
  135. probe.turn,
  136. sameRows: nodes.map((node, index) => node === probe.nodes[index]),
  137. opacity: nodes.map((node) => {
  138. let opacity = 1;
  139. for (let element = node; element; element = element.parentElement)
  140. opacity *= Number(getComputedStyle(element).opacity);
  141. return node ? opacity : 0;
  142. }),
  143. following: probe.timeline.dataset.following,
  144. bottomGap:
  145. probe.timeline.scrollHeight -
  146. probe.timeline.clientHeight -
  147. probe.timeline.scrollTop,
  148. });
  149. }
  150. document.removeEventListener("animationstart", probe.listener);
  151. return { animations: probe.animations, samples: probe.samples };
  152. });
  153. for (const sample of evidence.samples) {
  154. assert.equal(sample.sameTimeline, true);
  155. assert.equal(sample.sameTurn, true, `终态重挂整轮:${JSON.stringify(sample)}`);
  156. assert.equal(sample.sameRows[0], true, "旧轮消息被重挂");
  157. assert.equal(sample.following, String(!reading), "终态改变滚动归属");
  158. if (terminal !== "complete") {
  159. assert.ok(sample.sameRows.every(Boolean), "停止/失败重挂已有过程内容");
  160. assert.ok(
  161. sample.opacity.every((value) => value === 1),
  162. "已有过程内容出现透明帧",
  163. );
  164. }
  165. if (!reading) assert.ok(Math.abs(sample.bottomGap) <= 1, JSON.stringify(sample));
  166. }
  167. assert.equal(evidence.animations.includes("enter"), false, "终态重播已有内容的淡入");
  168. await page.screenshot({ path: join(artifacts, `${prefix}.png`) });
  169. await page.getByRole("button", { name: "Next turn", exact: true }).click();
  170. await page.locator('[data-row-id="11"]').waitFor();
  171. assert.equal(await page.locator('[data-v4-live-tail="true"]').count(), 1);
  172. assert.equal(
  173. await page.locator('[data-v4-live-tail="true"]').getAttribute("data-turn-id"),
  174. "next-turn",
  175. );
  176. assert.equal(
  177. await page
  178. .locator(
  179. '[data-v4-timeline-virtual-history] [data-v4-turn-unit][data-turn-id="terminal-turn"]',
  180. )
  181. .count(),
  182. 1,
  183. );
  184. assert.equal(
  185. await page.locator('[data-row-id="5"]').count(),
  186. 1,
  187. "下一轮交接丢失或重复旧输入",
  188. );
  189. await page.getByRole("button", { name: "Draft", exact: true }).click();
  190. assert.equal(await page.locator("[data-v4-turn-unit]").count(), 0, "空列表残留尾轮");
  191. assert.deepEqual(errors, []);
  192. } finally {
  193. await writeFile(
  194. join(artifacts, `${prefix}.json`),
  195. JSON.stringify({ evidence, errors }, null, 2),
  196. );
  197. await page.close();
  198. }
  199. });
  200. for (const mobile of [false, true])
  201. for (const theme of ["light", "dark"])
  202. for (const mode of ["tail", "final", "cua", "stream"])
  203. test(`SSV05 group identity ${mobile ? "mobile" : "desktop"}/${theme}/${mode}`, async () => {
  204. const page = await browser.newPage({
  205. viewport: { width: mobile ? 430 : 1250, height: 800 },
  206. isMobile: mobile,
  207. hasTouch: mobile,
  208. });
  209. const errors = [];
  210. page.on("pageerror", (error) => errors.push(String(error)));
  211. page.on("console", (message) => {
  212. if (message.type() === "error") errors.push(message.text());
  213. });
  214. const samples = [];
  215. try {
  216. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}&identity=${mode}`);
  217. const rowId = mode === "stream" ? 60 : 241;
  218. await page.locator(`[data-row-id="${rowId}"]`).waitFor();
  219. await page.evaluate(async (id) => {
  220. const row = document.querySelector(`[data-row-id="${id}"]`);
  221. const content = row.closest('[data-slot="collapsible-content"]');
  222. await Promise.all(
  223. document
  224. .getAnimations()
  225. .filter((animation) =>
  226. Number.isFinite(animation.effect?.getComputedTiming().iterations),
  227. )
  228. .map((animation) => animation.finished.catch(() => {})),
  229. );
  230. window.__identityProbe = { row, content, replacements: 0, animationRestarts: 0 };
  231. const probe = window.__identityProbe;
  232. let last = row;
  233. probe.observer = new MutationObserver(() => {
  234. const current = document.querySelector(`[data-row-id="${id}"]`);
  235. if (current !== last) probe.replacements += 1;
  236. last = current;
  237. });
  238. probe.observer.observe(document.querySelector('[data-testid="v4-timeline"]'), {
  239. childList: true,
  240. subtree: true,
  241. });
  242. document.addEventListener("animationstart", (event) => {
  243. const current = document.querySelector(`[data-row-id="${id}"]`);
  244. if (event.target instanceof Element && event.target.contains(current))
  245. probe.animationRestarts += 1;
  246. });
  247. }, rowId);
  248. for (const expected of [120, 180, 240, mode === "final" || mode === "cua" ? 242 : 241]) {
  249. await page.getByRole("button", { name: "Next page", exact: true }).click();
  250. await page.waitForFunction(
  251. (count) =>
  252. document.querySelector('[data-testid="v4-timeline"]').dataset.windowRowCount ===
  253. String(count),
  254. expected,
  255. );
  256. samples.push(
  257. await page.evaluate(async (id) => {
  258. await new Promise((resolve) =>
  259. requestAnimationFrame(() => requestAnimationFrame(resolve)),
  260. );
  261. const timeline = document.querySelector('[data-testid="v4-timeline"]');
  262. const row = document.querySelector(`[data-row-id="${id}"]`);
  263. const probe = window.__identityProbe;
  264. const content = row?.closest('[data-slot="collapsible-content"]');
  265. return {
  266. rows: timeline.dataset.windowRowCount,
  267. sameRow: row === probe.row,
  268. sameContent: content === probe.content,
  269. replacements: probe.replacements,
  270. animationRestarts: probe.animationRestarts,
  271. rowHeight: row?.getBoundingClientRect().height,
  272. scrollTop: timeline.scrollTop,
  273. opacity: content ? getComputedStyle(content.firstElementChild).opacity : null,
  274. };
  275. }, rowId),
  276. );
  277. }
  278. for (const sample of samples) {
  279. assert.equal(sample.sameRow, true, `已有消息被重挂:${JSON.stringify(sample)}`);
  280. assert.equal(sample.sameContent, true, `折叠内容被重挂:${JSON.stringify(sample)}`);
  281. assert.equal(sample.replacements, 0);
  282. assert.equal(sample.animationRestarts, 0, "补页或追加重播了已有内容的入场动画");
  283. if (sample.opacity !== null) assert.equal(sample.opacity, "1");
  284. }
  285. assert.deepEqual(errors, []);
  286. } finally {
  287. await writeFile(
  288. join(artifacts, `identity-${mobile}-${theme}-${mode}.json`),
  289. JSON.stringify(samples, null, 2),
  290. );
  291. await page.screenshot({
  292. path: join(artifacts, `identity-${mobile}-${theme}-${mode}.png`),
  293. });
  294. await page.close();
  295. }
  296. });
  297. for (const mobile of [false, true])
  298. for (const theme of ["light", "dark"])
  299. for (const mode of ["mixed", "append"])
  300. test(`SSV05 CR-01 ${mobile ? "mobile" : "desktop"}/${theme}/${mode}`, async () => {
  301. const page = await browser.newPage({
  302. viewport: { width: mobile ? 430 : 1250, height: 800 },
  303. isMobile: mobile,
  304. hasTouch: mobile,
  305. });
  306. const errors = [];
  307. page.on("pageerror", (error) => errors.push(String(error)));
  308. page.on("console", (message) => {
  309. if (message.type() === "error") errors.push(message.text());
  310. });
  311. const samples = [];
  312. try {
  313. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}&boundary=${mode}`);
  314. await page.locator('[data-row-id="50"]').waitFor();
  315. if (mode === "mixed") {
  316. await page.locator("[data-summary-group-trigger]").first().click();
  317. await page.locator('[data-tool-call-id="boundary-tool-40"]').waitFor();
  318. }
  319. await page.evaluate(async (mixed) => {
  320. await Promise.all(
  321. document
  322. .getAnimations()
  323. .filter((a) => Number.isFinite(a.effect?.getComputedTiming().iterations))
  324. .map((a) => a.finished.catch(() => {})),
  325. );
  326. // 组头的代表图标也会渲染行外壳;只跟踪展开内容中的真实行,排除图标副本。
  327. const rows = (mixed ? [40, 50] : [50]).map((id) =>
  328. document.querySelector(`[data-row-id="${id}"]:not([data-summary-group-icon] *)`),
  329. );
  330. const contents = rows.map((row) => row.closest('[data-slot="collapsible-content"]'));
  331. window.__boundaryProbe = {
  332. rows,
  333. contents,
  334. groups: [...document.querySelectorAll("[data-consecutive-summary-group]")],
  335. animationRestarts: 0,
  336. };
  337. document.addEventListener("animationstart", (event) => {
  338. if (
  339. event.target instanceof Element &&
  340. (mixed ? [40, 50] : [50]).some((id) =>
  341. event.target.contains(
  342. document.querySelector(
  343. `[data-row-id="${id}"]:not([data-summary-group-icon] *)`,
  344. ),
  345. ),
  346. )
  347. )
  348. window.__boundaryProbe.animationRestarts += 1;
  349. });
  350. }, mode === "mixed");
  351. for (const step of [1, 2]) {
  352. await page.getByRole("button", { name: "Next boundary", exact: true }).click();
  353. await page.waitForFunction(
  354. (value) =>
  355. document.querySelector('[data-testid="boundary-page"]').textContent ===
  356. String(value),
  357. step,
  358. );
  359. samples.push(
  360. await page.evaluate(
  361. async ({ mode, step }) => {
  362. await new Promise((resolve) =>
  363. requestAnimationFrame(() => requestAnimationFrame(resolve)),
  364. );
  365. const probe = window.__boundaryProbe;
  366. const ids = mode === "mixed" ? [40, 50] : [50];
  367. const rows = ids.map((id) =>
  368. document.querySelector(
  369. `[data-row-id="${id}"]:not([data-summary-group-icon] *)`,
  370. ),
  371. );
  372. const groups = [...document.querySelectorAll("[data-consecutive-summary-group]")];
  373. const timeline = document.querySelector('[data-testid="v4-timeline"]');
  374. return {
  375. step,
  376. sameRows: rows.map((row, index) => row === probe.rows[index]),
  377. sameContents: rows.map(
  378. (row, index) =>
  379. row?.closest('[data-slot="collapsible-content"]') === probe.contents[index],
  380. ),
  381. animationRestarts: probe.animationRestarts,
  382. heights: rows.map((row) => row?.getBoundingClientRect().height),
  383. scrollTop: timeline.scrollTop,
  384. sameGroups:
  385. mode === "mixed"
  386. ? probe.groups.map((group, index) => group === groups[index + 1])
  387. : [],
  388. groupIds: groups.map((group) =>
  389. group
  390. .querySelector("[data-summary-group-trigger]")
  391. ?.getAttribute("aria-controls"),
  392. ),
  393. expanded: groups.map((group) =>
  394. group
  395. .querySelector('[role="button"][aria-expanded]')
  396. ?.getAttribute("aria-expanded"),
  397. ),
  398. toolCounts: ids.map(
  399. (id) =>
  400. document.querySelectorAll(
  401. `[data-row-id="${id}"]:not([data-summary-group-icon] *)`,
  402. ).length,
  403. ),
  404. };
  405. },
  406. { mode, step },
  407. ),
  408. );
  409. }
  410. for (const sample of samples) {
  411. assert.ok(sample.sameRows.every(Boolean), `消息/分组重挂:${JSON.stringify(sample)}`);
  412. assert.ok(
  413. sample.sameContents.every(Boolean),
  414. `历史容器重挂:${JSON.stringify(sample)}`,
  415. );
  416. assert.equal(sample.animationRestarts, 0, JSON.stringify(sample));
  417. assert.ok(sample.sameGroups.every(Boolean), JSON.stringify(sample));
  418. assert.deepEqual(
  419. sample.toolCounts,
  420. mode === "mixed" ? [1, 1] : [1],
  421. "已有消息丢失或重复",
  422. );
  423. assert.equal(new Set(sample.groupIds).size, sample.groupIds.length, "CUA 展开身份重复");
  424. const count =
  425. mode === "mixed" ? (sample.step === 1 ? 3 : 4) : sample.step === 1 ? 1 : 3;
  426. assert.equal(sample.groupIds.length, count, "CUA 组丢失或重复");
  427. assert.deepEqual(
  428. sample.expanded,
  429. mode === "mixed"
  430. ? Array.from({ length: count }, (_, index) => (index === 1 ? "true" : "false"))
  431. : Array(count).fill("false"),
  432. "展开状态丢失或串组",
  433. );
  434. }
  435. assert.deepEqual(errors, [], "React 不得报告重复兄弟 key");
  436. } finally {
  437. await writeFile(
  438. join(artifacts, `boundary-${mobile}-${theme}-${mode}.json`),
  439. JSON.stringify({ samples, errors }, null, 2),
  440. );
  441. await page.screenshot({
  442. path: join(artifacts, `boundary-${mobile}-${theme}-${mode}.png`),
  443. });
  444. await page.close();
  445. }
  446. });
  447. for (const width of [390, 1100, 1440])
  448. for (const theme of ["light", "dark"])
  449. test(`SP01 draft first frame ${width}/${theme}`, async () => {
  450. const page = await browser.newPage({ viewport: { width, height: 800 } });
  451. const errors = [];
  452. page.on("pageerror", (error) => errors.push(String(error)));
  453. try {
  454. await page.goto(`${origin}fixture?draft=true&mobile=${width === 390}&theme=${theme}`);
  455. await page.getByTestId("fixture-composer").waitFor();
  456. const samples = await page.evaluate(async () => {
  457. const dock = document.querySelector("[data-v4-composer-dock-content]");
  458. const composer = document.querySelector('[data-testid="fixture-composer"]');
  459. const host = dock.parentElement;
  460. await Promise.all(dock.getAnimations().map((animation) => animation.finished));
  461. const frames = [];
  462. // 在 React 提交的 mutation 回调和后续绘制帧取坐标,不能等动画结束才断言。
  463. await new Promise((resolve) => {
  464. const capture = () => {
  465. const outer = host.getBoundingClientRect();
  466. const input = composer.getBoundingClientRect();
  467. frames.push({
  468. x: input.x,
  469. width: input.width,
  470. centerError: input.x + input.width / 2 - outer.x - outer.width / 2,
  471. animations: dock.getAnimations().map((animation) => animation.transitionProperty),
  472. });
  473. if (frames.length < 18) requestAnimationFrame(capture);
  474. else resolve();
  475. };
  476. const observer = new MutationObserver(() => {
  477. if (!composer.classList.contains("max-w-2xl")) return;
  478. observer.disconnect();
  479. capture();
  480. });
  481. observer.observe(composer, { attributes: true });
  482. [...document.querySelectorAll("button")]
  483. .find((button) => button.textContent === "Draft")
  484. .click();
  485. });
  486. return frames;
  487. });
  488. await writeFile(
  489. join(artifacts, `draft-${width}-${theme}.json`),
  490. JSON.stringify(samples, null, 2),
  491. );
  492. for (const sample of samples) {
  493. assert.ok(Math.abs(sample.centerError) <= 1, JSON.stringify(sample));
  494. assert.deepEqual(sample.animations, []);
  495. assert.ok(Math.abs(sample.x - samples[0].x) <= 1, JSON.stringify(samples));
  496. }
  497. await page.screenshot({ path: join(artifacts, `draft-${width}-${theme}.png`) });
  498. assert.deepEqual(errors, []);
  499. } finally {
  500. await page.close();
  501. }
  502. });
  503. for (const mobile of [false, true])
  504. for (const theme of ["light", "dark"]) {
  505. test(`SRM10 ${mobile ? "mobile" : "desktop"}/${theme}`, async () => {
  506. const page = await browser.newPage({
  507. viewport: { width: mobile ? 430 : 1250, height: 800 },
  508. isMobile: mobile,
  509. hasTouch: mobile,
  510. });
  511. const errors = [];
  512. page.on("pageerror", (error) => errors.push(String(error)));
  513. const prefix = `${mobile ? "mobile" : "desktop"}-${theme}`;
  514. try {
  515. await page.addInitScript(() => {
  516. window.__timelineErrors = [];
  517. window.addEventListener(
  518. "error",
  519. (event) => window.__timelineErrors.push(event.message),
  520. true,
  521. );
  522. });
  523. await page.goto(
  524. `${origin}fixture?mobile=${mobile}&theme=${theme}&heavy=${process.env.ZCODE_RESIZE_HEAVY_TOOLS === "1"}`,
  525. );
  526. const timeline = page.getByTestId("v4-timeline");
  527. await timeline.waitFor();
  528. if (process.env.ZCODE_RESIZE_HEAVY_TOOLS === "1") {
  529. await page.getByRole("button", { name: "Tools", exact: true }).click();
  530. await page.waitForFunction(
  531. () =>
  532. document.querySelectorAll('[data-testid^="tool-summary-trigger-resize-tool-"]')
  533. .length === 134,
  534. );
  535. }
  536. const state = () =>
  537. timeline.evaluate((e) => ({
  538. following: e.dataset.following,
  539. top: e.scrollTop,
  540. gap: e.scrollHeight - e.clientHeight - e.scrollTop,
  541. }));
  542. const settle = () =>
  543. page.evaluate(
  544. () =>
  545. new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  546. );
  547. await settle();
  548. await page.getByRole("button", { name: "Bottom", exact: true }).click();
  549. const evidence = [];
  550. // 每个宽度点都检查布局提交后的实际几何,不只检查整个拖动结束后的落点。
  551. for (const width of mobile
  552. ? [420, 390, 360, 390, 430]
  553. : [1400, 1300, 1250, 1050, 900, 750, 900, 1100, 1250]) {
  554. await page.setViewportSize({ width, height: 800 });
  555. await settle();
  556. const metrics = await timeline.evaluate((e) => {
  557. const history = e.querySelector("[data-v4-timeline-virtual-history]");
  558. const last = history?.lastElementChild;
  559. return {
  560. following: e.dataset.following,
  561. gap: e.scrollHeight - e.clientHeight - e.scrollTop,
  562. stale: last
  563. ? last.getBoundingClientRect().bottom - history.getBoundingClientRect().bottom
  564. : 0,
  565. };
  566. });
  567. evidence.push({ width, ...metrics });
  568. assert.equal(metrics.following, "true");
  569. assert.ok(Math.abs(metrics.gap) <= 1, JSON.stringify(metrics));
  570. assert.ok(Math.abs(metrics.stale) <= 1, JSON.stringify(metrics));
  571. }
  572. // 外层视口不变,仅内容列继续 CSS 宽度过渡:不能停留在旧 stableWidth。
  573. await timeline.evaluate((e) => {
  574. const history = e.querySelector("[data-v4-timeline-virtual-history]");
  575. history.style.transition = "width 160ms linear";
  576. history.style.width = "75%";
  577. });
  578. for (let frame = 0; frame < 8; frame++) {
  579. await settle();
  580. const metrics = await state();
  581. assert.equal(metrics.following, "true");
  582. assert.ok(Math.abs(metrics.gap) <= 1, JSON.stringify(metrics));
  583. }
  584. await timeline.evaluate((e) => {
  585. const history = e.querySelector("[data-v4-timeline-virtual-history]");
  586. history.style.removeProperty("transition");
  587. history.style.removeProperty("width");
  588. });
  589. await settle();
  590. await page.getByRole("button", { name: "Grow", exact: true }).click();
  591. await settle();
  592. assert.ok(Math.abs((await state()).gap) <= 1);
  593. await timeline.evaluate((e) => {
  594. e.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -400 }));
  595. e.scrollTop -= 500;
  596. e.dispatchEvent(new Event("scroll"));
  597. });
  598. await settle();
  599. assert.equal((await state()).following, "false");
  600. for (const width of mobile ? [390, 430] : [1000, 1250]) {
  601. await page.setViewportSize({ width, height: 800 });
  602. await settle();
  603. assert.equal((await state()).following, "false");
  604. }
  605. await page.getByRole("button", { name: "Grow", exact: true }).click();
  606. await settle();
  607. assert.equal((await state()).following, "false");
  608. await timeline.evaluate((e) => {
  609. e.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -400 }));
  610. e.scrollTop = 0;
  611. e.dispatchEvent(new Event("scroll"));
  612. });
  613. await settle();
  614. const saved = await state();
  615. await page.getByRole("button", { name: "Switch", exact: true }).click();
  616. await settle();
  617. await page.getByRole("button", { name: "Switch", exact: true }).click();
  618. await settle();
  619. assert.equal((await state()).following, "false");
  620. await page.waitForFunction(
  621. (top) =>
  622. Math.abs(document.querySelector('[data-testid="v4-timeline"]').scrollTop - top) <= 1,
  623. saved.top,
  624. );
  625. await page.getByRole("button", { name: "Bottom", exact: true }).click();
  626. await settle();
  627. assert.equal((await state()).following, "true");
  628. assert.ok(Math.abs((await state()).gap) <= 1);
  629. await page.getByRole("button", { name: "Locate", exact: true }).click();
  630. await settle();
  631. assert.equal((await state()).following, "false");
  632. await page.getByRole("button", { name: "Bottom", exact: true }).click();
  633. await settle();
  634. assert.equal((await state()).following, "true");
  635. assert.ok(Math.abs((await state()).gap) <= 1);
  636. await page.screenshot({ path: join(artifacts, `${prefix}.png`) });
  637. await writeFile(join(artifacts, `${prefix}.json`), JSON.stringify(evidence, null, 2));
  638. assert.deepEqual(errors, []);
  639. assert.deepEqual(await page.evaluate(() => window.__timelineErrors), []);
  640. } catch (error) {
  641. console.error(error);
  642. throw error;
  643. } finally {
  644. await page.close();
  645. }
  646. });
  647. }
  648. for (const mobile of [false, true])
  649. for (const theme of ["light", "dark"])
  650. for (const reading of [false, true])
  651. test(`SSV03 hydrate ${mobile ? "mobile" : "desktop"}/${theme}/${reading ? "reading" : "following"}`, async () => {
  652. const page = await browser.newPage({
  653. viewport: { width: mobile ? 430 : 1250, height: 800 },
  654. });
  655. const samples = [];
  656. try {
  657. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}&hydrate=true`);
  658. await page.getByTestId("v4-timeline").waitFor();
  659. await page.waitForFunction(
  660. () => document.querySelectorAll("[data-v4-turn-unit]").length >= 2,
  661. );
  662. if (reading) {
  663. await page.getByTestId("v4-timeline").evaluate((e) => {
  664. e.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
  665. e.scrollTop -= 100;
  666. e.dispatchEvent(new Event("scroll"));
  667. });
  668. await page.waitForFunction(
  669. () =>
  670. document.querySelector('[data-testid="v4-timeline"]').dataset.following === "false",
  671. );
  672. }
  673. const anchor = page.locator('[data-v4-turn-unit][data-turn-id="turn-1"]');
  674. const beforeTop = reading
  675. ? await anchor.evaluate((e) => e.getBoundingClientRect().top)
  676. : null;
  677. await page.evaluate(() => {
  678. window.__hydrationFrames = [];
  679. window.__hydrationStop = false;
  680. const sample = () => {
  681. if (window.__hydrationStop) return;
  682. const units = [...document.querySelectorAll("[data-v4-turn-unit]")];
  683. const pairs = units.slice(1).map((node, index) => ({
  684. from: units[index].dataset.turnId,
  685. to: node.dataset.turnId,
  686. overlap:
  687. units[index].getBoundingClientRect().bottom - node.getBoundingClientRect().top,
  688. }));
  689. window.__hydrationFrames.push({
  690. count: document.querySelector('[data-testid="v4-timeline"]').dataset.windowRowCount,
  691. top: document.querySelector('[data-testid="v4-timeline"]').scrollTop,
  692. gap: (() => {
  693. const e = document.querySelector('[data-testid="v4-timeline"]');
  694. return e.scrollHeight - e.clientHeight - e.scrollTop;
  695. })(),
  696. following: document.querySelector('[data-testid="v4-timeline"]').dataset.following,
  697. anchorTop: document
  698. .querySelector('[data-v4-turn-unit][data-turn-id="turn-1"]')
  699. ?.getBoundingClientRect().top,
  700. pairs,
  701. });
  702. requestAnimationFrame(sample);
  703. };
  704. requestAnimationFrame(sample);
  705. });
  706. await page.getByRole("button", { name: "Hydrate", exact: true }).click();
  707. await page.waitForFunction(
  708. () => window.__hydrationFrames.filter((f) => f.count === "140").length >= 8,
  709. );
  710. samples.push(
  711. ...(await page.evaluate(() => {
  712. window.__hydrationStop = true;
  713. return window.__hydrationFrames;
  714. })),
  715. );
  716. assert.ok(
  717. samples.some((frame) => frame.count === "60"),
  718. "缺少局部历史前置帧",
  719. );
  720. assert.ok(
  721. samples.some((frame) => frame.count === "140"),
  722. "没有补齐历史",
  723. );
  724. const overlapping = samples.filter((frame) =>
  725. frame.pairs.some((pair) => pair.overlap > 1),
  726. );
  727. assert.deepEqual(overlapping, [], "补齐历史出现重叠帧");
  728. assert.equal(
  729. await page.getByTestId("v4-timeline").getAttribute("data-following"),
  730. reading ? "false" : "true",
  731. );
  732. if (reading)
  733. assert.ok(
  734. Math.abs((await anchor.evaluate((e) => e.getBoundingClientRect().top)) - beforeTop) <=
  735. 1,
  736. "历史补齐改变阅读锚点",
  737. );
  738. } finally {
  739. await writeFile(
  740. join(artifacts, `hydrate-${mobile}-${theme}-${reading}.json`),
  741. JSON.stringify(samples, null, 2),
  742. );
  743. await page.screenshot({
  744. path: join(artifacts, `hydrate-${mobile}-${theme}-${reading}.png`),
  745. });
  746. await page.close();
  747. }
  748. });
  749. registerMarkdownTableMotionCases(() => ({ browser, origin, artifacts }));