conversation-session-v4-load-older.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // HLP02/M5④ 门禁:长历史无感分页(顶部历史可达 + prepend 不跳)。
  2. // 证据层 L3:21 个 completed turn 产出 >60 raw rows,越过快照尾窗;
  3. // 切走再切回(keep-warm 过期 → 全新 subscribe)拿到截断快照,验证:
  4. // ① 截断可见:data-window-row-count=60 < data-total-row-count,但不显示「加载更早」;
  5. // ② 用户向更早历史滚动时自动触发 loadOlder → 全部历史可达(首个 turn 可见);
  6. // ③ prepend 锚定不跳:补页前视口首行在补页后仍停留在视口附近(不弹回顶部/底部)。
  7. // 合并/游标语义的完整覆盖在 L1(v4SessionDataLayer.test.ts loadOlder 组 +
  8. // bootstrap conversation-topic-publisher rows/range 黄金组)。
  9. import { TID_V4_TIMELINE, TID_V4_TIMELINE_LOAD_OLDER } from "@zcode/shared/test-ids";
  10. import { clearAppData } from "#e2e/helpers/desktop-app";
  11. import {
  12. getV4PaneSnapshot,
  13. getV4TimelineScrollState,
  14. prepareV4ConversationE2E,
  15. scrollV4TimelineToTop,
  16. selectV4TaskById,
  17. sendV4Prompt,
  18. startNewV4Draft,
  19. waitForV4ComposerText,
  20. waitForV4ConversationState,
  21. waitForV4Pane,
  22. waitForV4TimelineContaining,
  23. } from "#e2e/helpers/v4-conversation";
  24. /** E2E build 的 SessionDataLayer keep-warm 窗口(1s)+ 余量。 */
  25. const KEEP_WARM_EXPIRY_MS = 2_000;
  26. const HISTORY_TURNS = 21;
  27. const SNAPSHOT_TAIL_RAW_ROWS = 60;
  28. const PREPEND_ANCHOR_MAX_DELTA_PX = 48;
  29. interface V4TimelineWindowObservation {
  30. firstVisibleOffsetTop: number | null;
  31. firstVisibleTurnId: string | null;
  32. renderUnitCount: number;
  33. totalRowCount: number;
  34. visibleTurnOffsets: Record<string, number>;
  35. windowRowCount: number;
  36. }
  37. function hasV4LoadOlderButton(): Promise<boolean> {
  38. return browser.execute(
  39. (loadOlderTestId) => Boolean(document.querySelector(`[data-testid="${loadOlderTestId}"]`)),
  40. TID_V4_TIMELINE_LOAD_OLDER,
  41. );
  42. }
  43. /**
  44. * 在切回 session 前从 renderer 内观察 timeline 属性变化。
  45. *
  46. * 修复原因:冷快照 60 行到自动预取完成可能只持续几十毫秒,WDIO 全量并发时下一次
  47. * execute 往返会直接读到 63 行。MutationObserver 留住真实中间态,避免把机器负载
  48. * 当成 rows.window 是否截断的产品结论。
  49. */
  50. function startV4TimelineWindowObservation(): Promise<void> {
  51. return browser.execute((timelineTestId) => {
  52. interface BrowserObservationState {
  53. capture: () => void;
  54. frame: number | null;
  55. observer: MutationObserver;
  56. samples: V4TimelineWindowObservation[];
  57. }
  58. const target = window as typeof window & {
  59. __zcodeV4TimelineWindowObservation?: BrowserObservationState;
  60. };
  61. target.__zcodeV4TimelineWindowObservation?.observer.disconnect();
  62. const samples: V4TimelineWindowObservation[] = [];
  63. const capture = () => {
  64. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  65. if (!timeline) return;
  66. const timelineTop = timeline.getBoundingClientRect().top;
  67. const visibleTurnOffsets: Record<string, number> = {};
  68. for (const unit of timeline.querySelectorAll<HTMLElement>('[data-v4-turn-unit="true"]')) {
  69. const turnId = unit.dataset.turnId;
  70. if (!turnId) continue;
  71. const rect = unit.getBoundingClientRect();
  72. const offsetTop = rect.top - timelineTop;
  73. if (rect.bottom - timelineTop <= 0 || offsetTop >= timeline.clientHeight) continue;
  74. visibleTurnOffsets[turnId] = offsetTop;
  75. }
  76. const firstVisibleEntry =
  77. Object.entries(visibleTurnOffsets).sort((left, right) => left[1] - right[1])[0] ?? null;
  78. const sample: V4TimelineWindowObservation = {
  79. firstVisibleOffsetTop: firstVisibleEntry?.[1] ?? null,
  80. firstVisibleTurnId: firstVisibleEntry?.[0] ?? null,
  81. renderUnitCount: Number(timeline.dataset.renderUnitCount ?? 0),
  82. totalRowCount: Number(timeline.dataset.totalRowCount ?? 0),
  83. visibleTurnOffsets,
  84. windowRowCount: Number(timeline.dataset.windowRowCount ?? 0),
  85. };
  86. const previous = samples.at(-1);
  87. if (
  88. previous &&
  89. previous.windowRowCount === sample.windowRowCount &&
  90. previous.totalRowCount === sample.totalRowCount &&
  91. previous.firstVisibleTurnId === sample.firstVisibleTurnId &&
  92. Math.abs((previous.firstVisibleOffsetTop ?? 0) - (sample.firstVisibleOffsetTop ?? 0)) < 0.5
  93. ) {
  94. return;
  95. }
  96. samples.push(sample);
  97. };
  98. const observer = new MutationObserver(() => {
  99. capture();
  100. const state = target.__zcodeV4TimelineWindowObservation;
  101. if (!state) return;
  102. if (state.frame !== null) cancelAnimationFrame(state.frame);
  103. state.frame = requestAnimationFrame(capture);
  104. });
  105. observer.observe(document.documentElement, {
  106. attributeFilter: ["data-render-unit-count", "data-total-row-count", "data-window-row-count"],
  107. attributes: true,
  108. childList: true,
  109. subtree: true,
  110. });
  111. target.__zcodeV4TimelineWindowObservation = {
  112. capture,
  113. frame: null,
  114. observer,
  115. samples,
  116. };
  117. capture();
  118. }, TID_V4_TIMELINE);
  119. }
  120. async function stopV4TimelineWindowObservation(): Promise<V4TimelineWindowObservation[]> {
  121. return await browser.execute(async () => {
  122. const target = window as typeof window & {
  123. __zcodeV4TimelineWindowObservation?: {
  124. capture: () => void;
  125. frame: number | null;
  126. observer: MutationObserver;
  127. samples: V4TimelineWindowObservation[];
  128. };
  129. };
  130. await new Promise<void>((resolve) => {
  131. requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
  132. });
  133. const state = target.__zcodeV4TimelineWindowObservation;
  134. if (!state) return [];
  135. state.capture();
  136. state.observer.disconnect();
  137. if (state.frame !== null) cancelAnimationFrame(state.frame);
  138. delete target.__zcodeV4TimelineWindowObservation;
  139. return state.samples;
  140. });
  141. }
  142. function getObservedPrependAnchorState(fullRawRows: number): Promise<{
  143. samples: V4TimelineWindowObservation[];
  144. stable: boolean;
  145. }> {
  146. return browser.execute(
  147. (expectedFullRawRows, snapshotTailRawRows, historyTurns, maxDeltaPx) => {
  148. const target = window as typeof window & {
  149. __zcodeV4TimelineWindowObservation?: {
  150. capture: () => void;
  151. samples: V4TimelineWindowObservation[];
  152. };
  153. };
  154. const state = target.__zcodeV4TimelineWindowObservation;
  155. if (!state) return { samples: [], stable: false };
  156. state.capture();
  157. const truncatedIndex = state.samples.findIndex(
  158. (sample) =>
  159. sample.windowRowCount === snapshotTailRawRows &&
  160. sample.totalRowCount === expectedFullRawRows &&
  161. sample.renderUnitCount > 0 &&
  162. sample.renderUnitCount < historyTurns,
  163. );
  164. const prefetchedIndex = state.samples.findIndex(
  165. (sample, index) => index > truncatedIndex && sample.windowRowCount > snapshotTailRawRows,
  166. );
  167. if (truncatedIndex < 0 || prefetchedIndex <= truncatedIndex) {
  168. return { samples: state.samples.slice(-12), stable: false };
  169. }
  170. // React 同一 commit 中可能先替换虚拟行 DOM、再刷新 data-window-row-count;
  171. // 因此最后一个“60 行”样本不一定仍属于旧窗口。按稳定 turnId 在截断阶段
  172. // 与补页阶段的所有样本间配对,避免把属性/DOM 的过渡帧当成锚定基准。
  173. const stable = state.samples
  174. .slice(truncatedIndex, prefetchedIndex)
  175. .some((anchorBefore) =>
  176. state.samples
  177. .slice(prefetchedIndex)
  178. .some((prefetched) =>
  179. Object.entries(anchorBefore.visibleTurnOffsets).some(
  180. ([turnId, beforeOffset]) =>
  181. prefetched.visibleTurnOffsets[turnId] !== undefined &&
  182. Math.abs(prefetched.visibleTurnOffsets[turnId] - beforeOffset) < maxDeltaPx,
  183. ),
  184. ),
  185. );
  186. return { samples: state.samples.slice(-12), stable };
  187. },
  188. fullRawRows,
  189. SNAPSHOT_TAIL_RAW_ROWS,
  190. HISTORY_TURNS,
  191. PREPEND_ANCHOR_MAX_DELTA_PX,
  192. );
  193. }
  194. describe("v4 HLP02 门禁:长历史无感分页(R-06)", () => {
  195. after(async () => {
  196. await browser.electron.restoreAllMocks();
  197. await clearAppData();
  198. });
  199. it("尾窗截断 → 自动预取补页 → 顶部可达且 prepend 不跳", async function () {
  200. this.timeout(180000);
  201. await prepareV4ConversationE2E();
  202. // 多 completed turn 是 live/cold 都稳定的持久语义;不再靠单 turn text-block segmentation。
  203. for (let index = 1; index <= HISTORY_TURNS; index += 1) {
  204. const marker = String(index).padStart(3, "0");
  205. await sendV4Prompt(`E2E_V4_OLDER_HISTORY_${marker} 历史轮次`);
  206. await browser.waitUntil(
  207. async () => (await getV4TimelineScrollState()).renderUnitCount >= index,
  208. { timeout: 30000, timeoutMsg: `第 ${index} 个历史 turn 没有完成投影` },
  209. );
  210. // 修复原因:row 数达到阈值只证明 projection 已追加,不能证明上一轮的
  211. // command/composer 收口已完成;紧接着写下一轮会被迟到的清空提交覆盖。
  212. await waitForV4ConversationState(
  213. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  214. `第 ${index} 个历史 turn 没有回到 idle`,
  215. 30_000,
  216. );
  217. await waitForV4ComposerText("", `第 ${index} 个历史 turn 后 composer 没有清空`, 30_000);
  218. }
  219. const sessionId = (await getV4PaneSnapshot()).sessionId as string;
  220. expect(sessionId).not.toBe("draft");
  221. // live 订阅期间行是流式追加的,客户端窗口=全量;不截断、无「加载更早」。
  222. const live = await getV4TimelineScrollState();
  223. // 修复原因:分页合同以 logical turn 和 60-row 窗口为边界;provider 可以把
  224. // 同一 logical turn 投影成不同数量的 raw rows,不能再硬编码 3 rows/turn。
  225. const fullRawRows = live.totalRowCount;
  226. expect(fullRawRows).toBeGreaterThan(SNAPSHOT_TAIL_RAW_ROWS);
  227. expect(live.windowRowCount).toBe(live.totalRowCount);
  228. expect(live.renderUnitCount).toBe(HISTORY_TURNS);
  229. expect(await hasV4LoadOlderButton()).toBe(false);
  230. // ── 切走 + keep-warm 过期 → 切回拿全新 subscribe(快照尾窗截断) ──
  231. await startNewV4Draft();
  232. await browser.pause(KEEP_WARM_EXPIRY_MS);
  233. await startV4TimelineWindowObservation();
  234. await selectV4TaskById(sessionId);
  235. await waitForV4Pane(
  236. (s) => s.sessionId === sessionId && s.rowCount > 0,
  237. "切回原会话后 pane 没有绑定/收到快照",
  238. 30000,
  239. );
  240. // ① 冷快照必须经过 60/全量截断态。若恢复布局已经进入顶部预取区,补页可能在
  241. // WDIO 下一次采样前完成;renderer observer 仍会保留该中间态。
  242. const stateAfterSubscribe = await getV4TimelineScrollState();
  243. expect(await hasV4LoadOlderButton()).toBe(false);
  244. if (stateAfterSubscribe.windowRowCount === SNAPSHOT_TAIL_RAW_ROWS) {
  245. // ── ② 用户向更早历史滚动时自动触发 loadOlder ──
  246. // scrollV4TimelineToTop 内部已等虚拟化窗口对齐(scroll 事件下一帧才派发,
  247. // 对齐前 DOM 仍是旧的底部窗口,采样会拿到过期行)。
  248. await scrollV4TimelineToTop();
  249. await browser.waitUntil(
  250. async () => (await getV4TimelineScrollState()).windowRowCount > SNAPSHOT_TAIL_RAW_ROWS,
  251. {
  252. timeout: 30000,
  253. timeoutMsg: "滚动到顶后 loadOlder 没有把更早的行并入窗口",
  254. },
  255. );
  256. } else {
  257. await browser.waitUntil(
  258. async () => (await getV4TimelineScrollState()).windowRowCount === fullRawRows,
  259. {
  260. timeout: 30000,
  261. timeoutMsg: "恢复期自动预取没有把更早的行并入窗口",
  262. },
  263. );
  264. }
  265. // ③ prepend 锚定不跳:不能在 scroll helper 返回后才读取 anchorBefore;补页可能
  266. // 已在 WDIO 往返期间提交,此时读到的是新 prepend 的 turn,它本来就应留在视口
  267. // 上方。以 renderer observer 留下的截断阶段稳定 turnId 为基准,条件等待 DOM
  268. // 锚点收敛;属性与虚拟 DOM 同 commit 的过渡帧由下方配对逻辑排除。
  269. let observedAnchorState = await getObservedPrependAnchorState(fullRawRows);
  270. try {
  271. await browser.waitUntil(
  272. async () => {
  273. observedAnchorState = await getObservedPrependAnchorState(fullRawRows);
  274. return observedAnchorState.stable;
  275. },
  276. {
  277. timeout: 15_000,
  278. interval: 50,
  279. timeoutMsg: "prepend 后虚拟列表没有恢复补页前的视口锚点",
  280. },
  281. );
  282. } catch (error) {
  283. throw new Error(`prepend 锚点采样:${JSON.stringify(observedAnchorState.samples)}`, {
  284. cause: error,
  285. });
  286. }
  287. const observations = await stopV4TimelineWindowObservation();
  288. const truncatedIndex = observations.findIndex(
  289. (sample) =>
  290. sample.windowRowCount === SNAPSHOT_TAIL_RAW_ROWS &&
  291. sample.totalRowCount === fullRawRows &&
  292. sample.renderUnitCount > 0 &&
  293. sample.renderUnitCount < HISTORY_TURNS,
  294. );
  295. expect(truncatedIndex).toBeGreaterThanOrEqual(0);
  296. const prefetchedIndex = observations.findIndex(
  297. (sample, index) => index > truncatedIndex && sample.windowRowCount > SNAPSHOT_TAIL_RAW_ROWS,
  298. );
  299. expect(prefetchedIndex).toBeGreaterThan(truncatedIndex);
  300. // 全部历史已并入:窗口 = 全序,且始终没有手动补页按钮。
  301. const complete = await getV4TimelineScrollState();
  302. expect(complete.windowRowCount).toBe(complete.totalRowCount);
  303. expect(complete.renderUnitCount).toBe(HISTORY_TURNS);
  304. expect(await hasV4LoadOlderButton()).toBe(false);
  305. // 顶部可达:滚到顶后最早的 turn 进入 DOM(逐字节同全量重放前缀,
  306. // 服务端等价性由 bootstrap rows/range 黄金测试背书,这里验证用户可达性)。
  307. await scrollV4TimelineToTop();
  308. await waitForV4TimelineContaining("E2E_V4_OLDER_HISTORY_001", 15000);
  309. });
  310. });