conversation-session-v4-scroll.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // M5④ 门禁:长会话虚拟滚动(timeline 动态测高 + 底部锚定 + 回到底部)。
  2. // 证据层 L3:14 个 completed turn 构造稳定多 turn 历史,验证
  3. // ① 底部锚定跟随——完流后无需手动滚动即可见末行;
  4. // ② 顶部历史可达——scrollTop=0 后最早的行在 DOM 中可见(虚拟窗口正确回填);
  5. // ③ 上滚不被流式拉回——turn2 慢流期间用户停留在顶部,scrollTop 不被增量拽回底部;
  6. // ④ 回到底部按钮——解除跟随后出现,点按恢复跟随并贴底。
  7. // ⑤ 快速滚动边缘——深浅主题均由固定视口裁剪,输入框下方留白不出现消息。
  8. // 原 L1 锚定状态机单测已退役;本 spec 只证明上述产品场景,不代表完整状态空间覆盖。
  9. import { mkdir, writeFile } from "node:fs/promises";
  10. import { join, resolve } from "node:path";
  11. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  12. import { clearAppData } from "#e2e/helpers/desktop-app";
  13. import {
  14. clickV4TimelineBackToBottom,
  15. getV4TimelineScrollState,
  16. prepareV4ConversationE2E,
  17. scrollV4TimelineToTop,
  18. selectV4TaskById,
  19. sendV4Prompt,
  20. startNewV4Draft,
  21. waitForV4Pane,
  22. waitForV4TimelineContaining,
  23. } from "#e2e/helpers/v4-conversation";
  24. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/scroll-edges");
  25. describe("v4 M5④ 门禁:长会话虚拟滚动", () => {
  26. const HISTORY_TURNS = 14;
  27. after(async () => {
  28. await browser.electron.restoreAllMocks();
  29. await clearAppData();
  30. });
  31. it("50+ 行历史:底部锚定跟随 → 顶部可达 → 流式不拉回 → 回到底部", async () => {
  32. await skipOccupationOnboardingIfPresent();
  33. await prepareV4ConversationE2E();
  34. for (let index = 1; index <= HISTORY_TURNS; index += 1) {
  35. const marker = String(index).padStart(3, "0");
  36. await sendV4Prompt(`E2E_V4_SCROLL_HISTORY_${marker} 长会话历史`);
  37. await browser.waitUntil(
  38. async () => {
  39. const state = await getV4TimelineScrollState();
  40. // render unit 在 user row 到达时就会建立;若只等 unit 数量,最后一个
  41. // assistant/timeline row 尚未物化便会进入断言,默认 CI 串行负载下会读到 41/42。
  42. return state.renderUnitCount >= index && state.windowRowCount >= index * 3;
  43. },
  44. { timeout: 30000, timeoutMsg: `第 ${index} 个 scroll history turn 未完成` },
  45. );
  46. }
  47. const anchored = await getV4TimelineScrollState();
  48. const sessionA = await waitForV4Pane(
  49. (snapshot) => snapshot.sessionId !== null,
  50. "长会话没有绑定 session id",
  51. );
  52. if (!sessionA.sessionId) throw new Error("长会话 session id 缺失");
  53. // 修复原因:这个 case 验证的是 logical turn 虚拟化;provider 可把单个 logical
  54. // turn 投影为更多 raw rows,精确绑定 3 rows/turn 会把合法投影误报成滚动失败。
  55. expect(anchored.windowRowCount).toBeGreaterThanOrEqual(HISTORY_TURNS * 3);
  56. expect(anchored.renderUnitCount).toBe(HISTORY_TURNS);
  57. expect(anchored.following).toBe("true");
  58. // 虚拟化生效:DOM 中挂载的行数少于投影窗口行数(长会话不全量渲染)。
  59. expect(anchored.mountedRenderUnitCount).toBeLessThan(anchored.renderUnitCount);
  60. // 内容总高远超视口(可滚动历史确实存在)。
  61. expect(anchored.scrollHeight).toBeGreaterThan(anchored.clientHeight * 2);
  62. // SRM11:用原生 wheel 验证快速滚动期间的裁剪边界,不能只在 scroll 回调收口后取样。
  63. for (const theme of ["zai-light", "zai-dark"]) {
  64. await browser.execute((value) => {
  65. const actions = (window as Window & { __testActions?: { setTheme(theme: string): void } })
  66. .__testActions;
  67. if (!actions) throw new Error("theme actions missing");
  68. actions.setTheme(value);
  69. }, theme);
  70. await startScrollEdgeTrace();
  71. for (const deltaY of [-240, -320, -420, 260, -380, 300]) {
  72. await browser
  73. .action("wheel")
  74. .scroll({ origin: await $('[data-v4-timeline-scroll="true"]'), deltaY, duration: 0 })
  75. .perform();
  76. }
  77. await browser.waitUntil(async () => (await getV4TimelineScrollState()).hasBackToBottom, {
  78. timeout: 10000,
  79. timeoutMsg: "真实 wheel 没有滚离底部",
  80. });
  81. await mkdir(artifactDir, { recursive: true });
  82. await browser.saveScreenshot(join(artifactDir, `scroll-edges-${theme}.png`));
  83. await clickV4TimelineBackToBottom();
  84. const frames = await browser.execute(() =>
  85. (window as ScrollEdgeTraceWindow).__finishScrollEdgeTrace!(),
  86. );
  87. await writeFile(
  88. join(artifactDir, `scroll-edges-${theme}.json`),
  89. JSON.stringify(frames, null, 2),
  90. );
  91. expect(frames.length).toBeGreaterThan(2);
  92. expect(new Set(frames.map((frame) => Math.round(frame.scrollTop))).size).toBeGreaterThan(1);
  93. for (const frame of frames) {
  94. expect(frame.mask).toBe("none");
  95. expect(Math.abs(frame.bottomGap - 16)).toBeLessThanOrEqual(1);
  96. expect(Math.abs(frame.dockBottomOffset)).toBeLessThanOrEqual(1);
  97. expect(frame.messageInGap).toBe(false);
  98. }
  99. }
  100. // ── 顶部历史可达:滚到顶后最早的行进入 DOM ──
  101. await scrollV4TimelineToTop();
  102. await waitForV4TimelineContaining("E2E_V4_SCROLL_HISTORY_001", 15000);
  103. await browser.waitUntil(
  104. async () => {
  105. const state = await getV4TimelineScrollState();
  106. return state.following === "false" && state.hasBackToBottom;
  107. },
  108. {
  109. timeout: 10000,
  110. timeoutMsg: "上滚离底后没有解除跟随/出现回到底部按钮",
  111. },
  112. );
  113. const savedHistoricalPosition = await getV4TimelineScrollState();
  114. await startNewV4Draft();
  115. await selectV4TaskById(sessionA.sessionId);
  116. await waitForV4Pane(
  117. (snapshot) => snapshot.sessionId === sessionA.sessionId,
  118. "切回长会话后 session 没有恢复",
  119. );
  120. await browser.waitUntil(
  121. async () => {
  122. const restored = await getV4TimelineScrollState();
  123. return (
  124. restored.following === "false" &&
  125. restored.hasBackToBottom &&
  126. Math.abs(restored.scrollTop - savedHistoricalPosition.scrollTop) <= 4
  127. );
  128. },
  129. {
  130. timeout: 15000,
  131. timeoutMsg: "切回长会话后没有恢复离底阅读位置",
  132. },
  133. );
  134. // ── turn2:慢流期间停在顶部,流式增量不得拉回 ──
  135. await clickV4TimelineBackToBottom();
  136. await sendV4Prompt("E2E_V4_SCROLL_TURN2 保持输出");
  137. await waitForV4TimelineContaining("V4_SCROLL_TURN2_STREAMING", 45000);
  138. await waitForV4Pane((s) => s.canStop, "turn2 streaming 没有出现 stop 按钮");
  139. await scrollV4TimelineToTop();
  140. await waitForV4TimelineContaining("E2E_V4_SCROLL_HISTORY_001", 15000);
  141. // 流式仍在进行的窗口内多次采样:scrollTop 必须停在顶部附近(不被增量拽回)。
  142. for (let sample = 0; sample < 4; sample += 1) {
  143. await browser.pause(700);
  144. const during = await getV4TimelineScrollState();
  145. expect(during.scrollTop).toBeLessThan(200);
  146. expect(during.following).toBe("false");
  147. }
  148. // 采样窗口结束时 turn2 仍在流式(证明上面的采样发生在流式期间)。
  149. const midStream = await waitForV4Pane(() => true, "读取流式中 pane 状态失败", 5000);
  150. expect(midStream.canStop).toBe(true);
  151. // ── 回到底部:恢复跟随,完流文本自动可见 ──
  152. await clickV4TimelineBackToBottom();
  153. const beforeBackgroundOutput = await waitForV4Pane(
  154. (snapshot) => snapshot.timelineText.includes("turn2 持续输出片段"),
  155. "切走前没有可比较的 turn2 流式片段",
  156. );
  157. const beforeBackgroundFragmentCount =
  158. beforeBackgroundOutput.timelineText.match(/turn2 持续输出片段/g)?.length ?? 0;
  159. await startNewV4Draft();
  160. await browser.pause(1200);
  161. await selectV4TaskById(sessionA.sessionId);
  162. const afterBackgroundOutput = await waitForV4Pane((snapshot) => {
  163. const fragmentCount = snapshot.timelineText.match(/turn2 持续输出片段/g)?.length ?? 0;
  164. // 修复原因:E2E 的 session projection keep-warm 只有 1 秒;切走 1.2 秒后
  165. // 切回时 data-session-id 会先于新 lease/snapshot 生效。只等待 session id 会
  166. // 在 timeline rows 仍为空的过渡帧返回 0,误判后台流式丢失。这里同时等待目标
  167. // timeline 恢复且片段确实增长,保持 SRM03 的后台输出 + 吸底恢复原始语义。
  168. return (
  169. snapshot.sessionId === sessionA.sessionId && fragmentCount > beforeBackgroundFragmentCount
  170. );
  171. }, "后台流式期间切回原 session 后投影没有恢复新增片段");
  172. const afterBackgroundFragmentCount =
  173. afterBackgroundOutput.timelineText.match(/turn2 持续输出片段/g)?.length ?? 0;
  174. expect(afterBackgroundFragmentCount).toBeGreaterThan(beforeBackgroundFragmentCount);
  175. await browser.waitUntil(
  176. async () => {
  177. const restored = await getV4TimelineScrollState();
  178. const distanceToBottom = Math.max(
  179. 0,
  180. restored.scrollHeight - restored.clientHeight - restored.scrollTop,
  181. );
  182. return restored.following === "true" && distanceToBottom <= 48;
  183. },
  184. {
  185. timeout: 15000,
  186. timeoutMsg: "吸底 session 切回后没有定位到当前最新底部",
  187. },
  188. );
  189. await waitForV4TimelineContaining("V4_SCROLL_TURN2_DONE", 60000);
  190. await waitForV4Pane((s) => !s.canStop, "turn2 没有回到空闲态", 45000);
  191. const final = await getV4TimelineScrollState();
  192. expect(final.following).toBe("true");
  193. expect(final.hasBackToBottom).toBe(false);
  194. });
  195. });
  196. interface ScrollEdgeFrame {
  197. scrollTop: number;
  198. mask: string;
  199. bottomGap: number;
  200. dockBottomOffset: number;
  201. messageInGap: boolean;
  202. }
  203. type ScrollEdgeTraceWindow = Window & { __finishScrollEdgeTrace?: () => ScrollEdgeFrame[] };
  204. async function startScrollEdgeTrace() {
  205. await browser.execute(() => {
  206. const scroll = document.querySelector<HTMLElement>('[data-v4-timeline-scroll="true"]');
  207. const message = scroll?.querySelector<HTMLElement>('[data-v4-timeline-message-layer="true"]');
  208. const dock = scroll?.querySelector<HTMLElement>('[data-v4-composer-dock="true"]');
  209. if (!scroll || !message || !dock) throw new Error("timeline edge elements missing");
  210. const frames: ScrollEdgeFrame[] = [];
  211. let frameId = 0;
  212. const capture = () => {
  213. const rect = scroll.getBoundingClientRect();
  214. const root = scroll.parentElement!.getBoundingClientRect();
  215. frames.push({
  216. scrollTop: scroll.scrollTop,
  217. mask: getComputedStyle(message).maskImage,
  218. bottomGap: root.bottom - rect.bottom,
  219. dockBottomOffset: rect.bottom - dock.getBoundingClientRect().bottom,
  220. messageInGap: document
  221. .elementsFromPoint(rect.x + rect.width / 2, root.bottom - 8)
  222. .some((element) => message.contains(element)),
  223. });
  224. frameId = requestAnimationFrame(capture);
  225. };
  226. capture();
  227. (window as ScrollEdgeTraceWindow).__finishScrollEdgeTrace = () => {
  228. cancelAnimationFrame(frameId);
  229. delete (window as ScrollEdgeTraceWindow).__finishScrollEdgeTrace;
  230. return frames;
  231. };
  232. });
  233. }