reasoning-render-performance.test.mjs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import assert from "node:assert/strict";
  2. import { before, after, test } from "node:test";
  3. import { fileURLToPath } from "node:url";
  4. import { mkdir, writeFile } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { build, preview } from "vite";
  7. import { execFile } from "node:child_process";
  8. import { promisify } from "node:util";
  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/reasoning-render-performance.fixture.tsx";
  15. const artifacts =
  16. process.env.ZCODE_E2E_ARTIFACT_DIR ||
  17. join(root, "packages/desktop/.e2e-artifacts/reasoning-render-performance");
  18. let server, browser, origin;
  19. before(async () => {
  20. await mkdir(artifacts, { recursive: true });
  21. await writeFile(
  22. join(artifacts, "index.html"),
  23. '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="data:,"><div id="root"></div><script type="module" src="/reasoning-fixture.tsx"></script>',
  24. );
  25. // 用同一夹具加载指定基线的三个实现,比较生产 React,排除开发检查与热更新开销。
  26. const baseline = new Map();
  27. for (const path of process.env.ZCODE_REASONING_BASELINE_REF
  28. ? [
  29. "packages/ui/src/v4/conversationAssistantWorkItems.ts",
  30. "packages/ui/src/v4/ConversationTurnGroup.tsx",
  31. "packages/ui/src/components/ui/collapsible.tsx",
  32. ]
  33. : []) {
  34. const { stdout } = await promisify(execFile)(
  35. "git",
  36. ["show", `${process.env.ZCODE_REASONING_BASELINE_REF}:${path}`],
  37. { cwd: root },
  38. );
  39. baseline.set(root + path, stdout);
  40. }
  41. await build({
  42. root: artifacts,
  43. configFile: false,
  44. base: "./",
  45. logLevel: "warn",
  46. plugins: [
  47. { name: "reasoning-baseline", enforce: "pre", load: (id) => baseline.get(id) ?? null },
  48. react(),
  49. tailwindcss(),
  50. ],
  51. resolve: {
  52. alias: { "@": `${root}packages/ui/src`, "/reasoning-fixture.tsx": root + entry.slice(1) },
  53. },
  54. build: {
  55. outDir: join(artifacts, "out"),
  56. emptyOutDir: true,
  57. minify: false,
  58. chunkSizeWarningLimit: 10000,
  59. },
  60. });
  61. server = await preview({
  62. root: artifacts,
  63. configFile: false,
  64. build: { outDir: join(artifacts, "out") },
  65. preview: { host: "127.0.0.1", port: 0 },
  66. });
  67. origin = server.resolvedUrls.local[0];
  68. browser = await chromium.launch(
  69. process.env.CHROME_EXECUTABLE_PATH
  70. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  71. : { channel: "chrome" },
  72. );
  73. });
  74. after(async () => {
  75. await browser?.close();
  76. await server?.close();
  77. });
  78. const metricNames = [
  79. "TaskDuration",
  80. "ScriptDuration",
  81. "LayoutDuration",
  82. "RecalcStyleDuration",
  83. "LayoutCount",
  84. "RecalcStyleCount",
  85. ];
  86. const delta = (before, after) =>
  87. Object.fromEntries(metricNames.map((name) => [name, after[name] - before[name]]));
  88. const frames = (page) =>
  89. page.evaluate(
  90. () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  91. );
  92. const percentile = (values, ratio) =>
  93. [...values].sort((a, b) => a - b)[
  94. Math.min(values.length - 1, Math.floor(values.length * ratio))
  95. ] ?? 0;
  96. for (const mobile of [false, true])
  97. for (const theme of ["light", "dark"]) {
  98. test(`XSG04 streaming and folding ${mobile ? "mobile" : "desktop"}/${theme}`, async () => {
  99. const page = await browser.newPage({
  100. viewport: { width: mobile ? 390 : 1280, height: 900 },
  101. isMobile: mobile,
  102. hasTouch: mobile,
  103. });
  104. const errors = [];
  105. page.on("pageerror", (error) => errors.push(error.message));
  106. const client = await page.context().newCDPSession(page);
  107. await client.send("Performance.enable");
  108. const metrics = async () =>
  109. Object.fromEntries(
  110. (await client.send("Performance.getMetrics")).metrics.map(({ name, value }) => [
  111. name,
  112. value,
  113. ]),
  114. );
  115. const evidence = {
  116. build: "production",
  117. baseline: process.env.ZCODE_REASONING_BASELINE_REF ?? null,
  118. streaming: [],
  119. folds: [],
  120. errors,
  121. };
  122. const settle = () =>
  123. page.waitForFunction(
  124. () =>
  125. !Array.from(document.querySelectorAll('[data-slot="collapsible-content"]')).some(
  126. (node) => node.getAnimations().some((animation) => animation.playState === "running"),
  127. ),
  128. );
  129. try {
  130. await page.goto(`${origin}?mobile=${mobile}&theme=${theme}`);
  131. const group = page.locator("[data-consecutive-summary-group]").first();
  132. const trigger = group.locator("[data-summary-group-trigger]");
  133. await trigger.waitFor();
  134. await page.evaluate(() => {
  135. window.__groupIdentity = document.querySelector("[data-consecutive-summary-group]");
  136. });
  137. // 热身后对同一批不可变历史行进行尾部更新,不以开发构建冷加载时间冒充交互开销。
  138. await page.evaluate(() => window.__reasoningPerf.step());
  139. await frames(page);
  140. if (process.env.ZCODE_REASONING_CPU_PROFILE) {
  141. await client.send("Profiler.enable");
  142. await client.send("Profiler.start");
  143. }
  144. for (let pass = 0; pass < 3; pass++) {
  145. const previous = await metrics();
  146. const times = await page.evaluate(async () => {
  147. const times = [];
  148. for (let index = 0; index < 40; index++) {
  149. window.__reasoningPerf.step();
  150. await new Promise((resolve) =>
  151. requestAnimationFrame((time) => {
  152. times.push(time);
  153. resolve();
  154. }),
  155. );
  156. }
  157. await new Promise((resolve) => requestAnimationFrame(resolve));
  158. return times.slice(1).map((time, index) => time - times[index]);
  159. });
  160. evidence.streaming.push({
  161. ...delta(previous, await metrics()),
  162. frameP95: percentile(times, 0.95),
  163. frameMax: Math.max(...times),
  164. });
  165. }
  166. if (process.env.ZCODE_REASONING_CPU_PROFILE) {
  167. const { profile } = await client.send("Profiler.stop");
  168. await writeFile(
  169. join(artifacts, `${mobile ? "mobile" : "desktop"}-${theme}.cpuprofile`),
  170. JSON.stringify(profile),
  171. );
  172. }
  173. assert.equal(await page.getByTestId("tick").innerText(), "121");
  174. assert.equal(
  175. await page.evaluate(
  176. () =>
  177. document.querySelector("[data-consecutive-summary-group]") === window.__groupIdentity,
  178. ),
  179. true,
  180. );
  181. await trigger.scrollIntoViewIfNeeded();
  182. for (let pass = 0; pass < 6; pass++) {
  183. const previous = await metrics();
  184. const start = performance.now();
  185. await trigger.click();
  186. await settle();
  187. await frames(page);
  188. evidence.folds.push({
  189. open: pass % 2 === 0,
  190. ...delta(previous, await metrics()),
  191. elapsedMs: performance.now() - start,
  192. });
  193. assert.equal(await trigger.getAttribute("aria-expanded"), String(pass % 2 === 0));
  194. }
  195. await trigger.click();
  196. await settle();
  197. const thought = group.locator('[data-testid="chat-reasoning-trigger"]').first();
  198. await thought.click();
  199. await settle();
  200. await group.getByText(/E2E_XSG04_THOUGHT_0/).waitFor();
  201. // 高度动画结束后,吸底滚动仍可能推进;截图等几何稳定,避免把中间帧误判为视觉变化。
  202. await page.waitForFunction(
  203. () => {
  204. const nodes = document.querySelectorAll(
  205. "[data-consecutive-summary-group], [data-summary-group-scroll], [data-reasoning-scroll-mask]",
  206. );
  207. const signature = JSON.stringify(
  208. Array.from(nodes, (node) => [
  209. node.getBoundingClientRect().top,
  210. node.getBoundingClientRect().height,
  211. node.scrollTop,
  212. ]),
  213. );
  214. const previous = window.__reasoningVisual;
  215. const stable = previous?.signature === signature ? previous.stable + 1 : 0;
  216. window.__reasoningVisual = { signature, stable };
  217. return stable >= 3;
  218. },
  219. undefined,
  220. { polling: "raf" },
  221. );
  222. await page.screenshot({
  223. path: join(artifacts, `${mobile ? "mobile" : "desktop"}-${theme}.png`),
  224. animations: "disabled",
  225. });
  226. // 动画中反向操作仍由原 Presence 管理,流式更新不能覆盖手动展开。
  227. await trigger.click();
  228. await frames(page);
  229. await trigger.click();
  230. await settle();
  231. await page.evaluate(() => window.__reasoningPerf.step());
  232. await frames(page);
  233. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  234. assert.equal(
  235. await page.evaluate(
  236. () =>
  237. document.querySelector("[data-consecutive-summary-group]") === window.__groupIdentity,
  238. ),
  239. true,
  240. );
  241. // 同 rowId 的新事实必须失效;不能把缓存误做成按标识永久复用。
  242. await page.evaluate(() => window.__reasoningPerf.revise());
  243. await page.waitForFunction(() =>
  244. document.querySelector("[data-summary-group-statistics]")?.textContent?.includes("119"),
  245. );
  246. assert.deepEqual(errors, []);
  247. evidence.domNodes = await page.locator("*").count();
  248. } finally {
  249. await writeFile(
  250. join(artifacts, `${mobile ? "mobile" : "desktop"}-${theme}.json`),
  251. JSON.stringify(evidence, null, 2),
  252. );
  253. await page.close();
  254. }
  255. });
  256. }