v4ConversationTimelineSessionSwitchScrollRestoreRepro.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // 复现测试(ZCT-2092635483465441280 / ZCT-2092650540916523008 / ZCT-202608-C5F84801):
  2. // 切换/打开会话时滚动落在"既不是底部、也不是上次阅读位置"的随机历史中部。
  3. //
  4. // 回归断言按【预期行为】书写,锁定以下两个曾经导致随机历史落点的边界:
  5. // 1. lease 竞态:SessionPane 切会话不重挂、lease 在 useEffect 里晚一拍到达,
  6. // scrollMemoryKey/sessionKey 先变而 rows 仍是旧会话内容;恢复 effect
  7. // (ConversationTimeline.tsx 会话切换 effect)在旧会话坐标系上执行像素钳制,
  8. // 之后 rows 换成新会话(keep-warm 30s 内不经过 0 行)也不再重跑恢复。
  9. // 2. 分片坐标系错位:记忆保存的是"全量窗口 × 真实测高"下的像素 scrollTop;
  10. // 冷开只有尾部 60 行 + 72px 估算(heightCache 已清),钳制后的落点不再对应
  11. // 保存时的阅读位置,且内容补齐后没有任何重新锚定。
  12. //
  13. // 器具复制自 v4ConversationTimelineScrollMemory.test.ts(最小 DOM + mock virtualizer)。
  14. import { act, createElement } from "react";
  15. import { createRoot, type Root } from "react-dom/client";
  16. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  17. import { TID_V4_TIMELINE, TID_V4_TIMELINE_BOTTOM } from "@zcode/shared";
  18. import type { ConversationRow, UserInputRow } from "@zcode/shared/zcode-protocol-v4";
  19. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  20. import {
  21. clearChatSessionScrollMemoryForTest,
  22. saveChatSessionScrollMemoryState,
  23. } from "@/lib/chatSessionScrollMemory.js";
  24. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  25. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  26. import { ConversationTimeline } from "@/v4/ConversationTimeline.js";
  27. const layout = vi.hoisted(() => ({ clientHeight: 300, scrollHeight: 1200 }));
  28. const virtualizer = vi.hoisted(() => ({
  29. getVirtualItemForOffset: vi.fn(),
  30. getTotalSize: () => layout.scrollHeight,
  31. getVirtualItems: () => [],
  32. measurementsCache: [] as Array<{
  33. end: number;
  34. index: number;
  35. key: string;
  36. lane: number;
  37. size: number;
  38. start: number;
  39. }>,
  40. measure: vi.fn(),
  41. measureElement: vi.fn(),
  42. scrollOffset: null as number | null,
  43. scrollRect: null as { height: number } | null,
  44. scrollToIndex: vi.fn(),
  45. shouldAdjustScrollPositionOnItemSizeChange: null as
  46. | null
  47. | ((item: { end: number; start: number }) => boolean),
  48. }));
  49. vi.mock("@tanstack/react-virtual", () => ({
  50. useVirtualizer: () => virtualizer,
  51. }));
  52. vi.mock("@/v4/ConversationTurnGroup.js", async () => {
  53. const React = await import("react");
  54. return {
  55. ConversationTurnGroup: () => React.createElement("div"),
  56. };
  57. });
  58. vi.mock("@/v4/ConversationTurnNavigator.js", () => ({
  59. ConversationTurnNavigator: () => null,
  60. }));
  61. vi.mock("@/v4/useConversationTimelineFind.js", () => ({
  62. useConversationTimelineFind: () => undefined,
  63. }));
  64. type TestEventHandler = (event: Record<string, unknown>) => void;
  65. type TestElement = Element & {
  66. __attrs: Map<string, string>;
  67. __listeners: Map<string, TestEventHandler[]>;
  68. childNodes: TestElement[];
  69. parentNode: TestElement | null;
  70. scrollTop: number;
  71. };
  72. let nextFrameId = 1;
  73. const animationFrames = new Map<number, FrameRequestCallback>();
  74. const scheduledMicrotasks: Array<() => void> = [];
  75. const nativeQueueMicrotask = globalThis.queueMicrotask;
  76. let mountedRoot: Root | null = null;
  77. function createMinimalElement(ownerDocument: Document, tagName = "div"): TestElement {
  78. let scrollTop = 0;
  79. const element = {
  80. __attrs: new Map<string, string>(),
  81. __listeners: new Map<string, TestEventHandler[]>(),
  82. addEventListener: (type: string, handler: TestEventHandler) => {
  83. element.__listeners.set(type, [...(element.__listeners.get(type) ?? []), handler]);
  84. },
  85. appendChild: (child: TestElement) => {
  86. child.parentNode = element as unknown as TestElement;
  87. element.childNodes.push(child);
  88. return child;
  89. },
  90. childNodes: [] as TestElement[],
  91. dispatchEvent: (event: Event) => {
  92. const forwardedEvent = {
  93. bubbles: event.bubbles,
  94. cancelBubble: event.cancelBubble,
  95. currentTarget: element,
  96. defaultPrevented: event.defaultPrevented,
  97. preventDefault: () => event.preventDefault(),
  98. stopPropagation: () => event.stopPropagation(),
  99. target: element,
  100. timeStamp: event.timeStamp,
  101. type: event.type,
  102. };
  103. for (const handler of element.__listeners.get(event.type) ?? []) {
  104. handler(forwardedEvent);
  105. }
  106. return !event.defaultPrevented;
  107. },
  108. getBoundingClientRect: () => ({
  109. bottom: layout.clientHeight,
  110. height: layout.clientHeight,
  111. left: 0,
  112. right: 800,
  113. top: 0,
  114. width: 800,
  115. x: 0,
  116. y: 0,
  117. toJSON: () => ({}),
  118. }),
  119. getAttribute: (name: string) => element.__attrs.get(name) ?? null,
  120. insertBefore: (child: TestElement, beforeChild?: TestElement | null) => {
  121. child.parentNode = element as unknown as TestElement;
  122. const index = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  123. if (index >= 0) element.childNodes.splice(index, 0, child);
  124. else element.childNodes.push(child);
  125. return child;
  126. },
  127. nodeName: tagName.toUpperCase(),
  128. nodeType: 1,
  129. ownerDocument,
  130. parentNode: null as TestElement | null,
  131. removeAttribute: (name: string) => element.__attrs.delete(name),
  132. removeChild: (child: TestElement) => {
  133. element.childNodes = element.childNodes.filter((item) => item !== child);
  134. child.parentNode = null;
  135. return child;
  136. },
  137. removeEventListener: (type: string, handler: TestEventHandler) => {
  138. element.__listeners.set(
  139. type,
  140. (element.__listeners.get(type) ?? []).filter((item) => item !== handler),
  141. );
  142. },
  143. querySelectorAll: () => [],
  144. setAttribute: (name: string, value: string) => {
  145. element.__attrs.set(name, String(value));
  146. },
  147. style: {},
  148. tagName: tagName.toUpperCase(),
  149. };
  150. Object.defineProperties(element, {
  151. clientHeight: { get: () => layout.clientHeight },
  152. scrollHeight: { get: () => layout.scrollHeight },
  153. scrollTop: {
  154. get: () => scrollTop,
  155. set: (value: number) => {
  156. // 与浏览器一致:赋值按当前内容高度钳制。
  157. scrollTop = Math.min(
  158. Math.max(Number(value) || 0, 0),
  159. Math.max(layout.scrollHeight - layout.clientHeight, 0),
  160. );
  161. },
  162. },
  163. });
  164. return element as unknown as TestElement;
  165. }
  166. function installMinimalDom(): TestElement {
  167. const documentMock = {
  168. addEventListener: () => {},
  169. createElement: (tagName: string) =>
  170. createMinimalElement(documentMock as unknown as Document, tagName),
  171. createElementNS: (_namespace: string, tagName: string) =>
  172. createMinimalElement(documentMock as unknown as Document, tagName),
  173. createTextNode: (nodeValue: string) => ({
  174. nodeType: 3,
  175. nodeValue,
  176. ownerDocument: documentMock,
  177. parentNode: null,
  178. }),
  179. nodeType: 9,
  180. removeEventListener: () => {},
  181. } as unknown as Document & { defaultView?: unknown };
  182. const windowMock = {
  183. addEventListener: () => {},
  184. cancelAnimationFrame: (frameId: number) => animationFrames.delete(frameId),
  185. document: documentMock,
  186. HTMLElement: function HTMLElement() {},
  187. HTMLIFrameElement: function HTMLIFrameElement() {},
  188. Node: function Node() {},
  189. queueMicrotask: (callback: () => void) => scheduledMicrotasks.push(callback),
  190. removeEventListener: () => {},
  191. requestAnimationFrame: (callback: FrameRequestCallback) => {
  192. const frameId = nextFrameId;
  193. nextFrameId += 1;
  194. animationFrames.set(frameId, callback);
  195. return frameId;
  196. },
  197. };
  198. documentMock.defaultView = windowMock;
  199. Object.assign(globalThis, {
  200. document: documentMock,
  201. HTMLElement: windowMock.HTMLElement,
  202. HTMLIFrameElement: windowMock.HTMLIFrameElement,
  203. IS_REACT_ACT_ENVIRONMENT: true,
  204. Node: windowMock.Node,
  205. queueMicrotask: windowMock.queueMicrotask,
  206. window: windowMock,
  207. });
  208. return createMinimalElement(documentMock, "div");
  209. }
  210. function findByTestId(node: TestElement, testId: string): TestElement | null {
  211. if (node.getAttribute("data-testid") === testId) return node;
  212. for (const child of node.childNodes) {
  213. if (child.nodeType !== 1) continue;
  214. const match = findByTestId(child, testId);
  215. if (match) return match;
  216. }
  217. return null;
  218. }
  219. function flushAnimationFrame(): void {
  220. const frameIds = [...animationFrames.keys()];
  221. for (const frameId of frameIds) {
  222. const callback = animationFrames.get(frameId);
  223. if (!callback) continue;
  224. animationFrames.delete(frameId);
  225. callback(0);
  226. }
  227. }
  228. function flushScheduledMicrotasks(): void {
  229. while (scheduledMicrotasks.length > 0) {
  230. scheduledMicrotasks.shift()?.();
  231. }
  232. }
  233. function userInputRow(rowId: number): UserInputRow {
  234. return {
  235. rowId,
  236. turnId: `turn-${rowId}`,
  237. createdAt: 1_700_000_000_000 + rowId,
  238. createdAtSeq: rowId,
  239. kind: "userInput",
  240. origin: "realUser",
  241. text: `message ${rowId}`,
  242. attachments: [],
  243. };
  244. }
  245. const rowContext: ConversationRowRenderContext = {
  246. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  247. sessionId: "session-1",
  248. theme: "system",
  249. workspacePath: "/workspace",
  250. };
  251. function renderTimeline(
  252. root: Root,
  253. sessionKey: string,
  254. scrollMemoryKey: string | null,
  255. rows: readonly ConversationRow[],
  256. options: { canLoadOlder?: boolean; totalCount?: number } = {},
  257. ): void {
  258. root.render(
  259. createElement(
  260. ZCodeIntlProvider,
  261. { initialLocale: "zh-CN" },
  262. createElement(ConversationTimeline, {
  263. canLoadOlder: options.canLoadOlder,
  264. rows,
  265. totalCount: options.totalCount ?? rows.length,
  266. sessionKey,
  267. scrollMemoryKey,
  268. rowContext,
  269. }),
  270. ),
  271. );
  272. }
  273. const KEY_A = "workspace::pane:a::session:a";
  274. const KEY_B = "workspace::pane:a::session:b";
  275. const ROWS_A = [userInputRow(1), userInputRow(2), userInputRow(3)];
  276. // 新会话的分片尾窗(rowId 不同即可;真实场景是最后 60 行)。
  277. const ROWS_B_TAIL = [userInputRow(101), userInputRow(102), userInputRow(103)];
  278. beforeEach(() => {
  279. clearChatSessionScrollMemoryForTest();
  280. layout.clientHeight = 300;
  281. layout.scrollHeight = 1200;
  282. nextFrameId = 1;
  283. animationFrames.clear();
  284. scheduledMicrotasks.length = 0;
  285. virtualizer.getVirtualItemForOffset.mockReset();
  286. virtualizer.measurementsCache = [];
  287. virtualizer.measure.mockClear();
  288. });
  289. afterEach(() => {
  290. act(() => {
  291. flushScheduledMicrotasks();
  292. mountedRoot?.unmount();
  293. flushScheduledMicrotasks();
  294. });
  295. mountedRoot = null;
  296. animationFrames.clear();
  297. scheduledMicrotasks.length = 0;
  298. globalThis.queueMicrotask = nativeQueueMicrotask;
  299. delete (globalThis as { document?: unknown }).document;
  300. delete (globalThis as { window?: unknown }).window;
  301. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  302. });
  303. describe("会话切换滚动恢复(ZCT 复现)", () => {
  304. it("lease 迟一拍时,恢复必须以新会话内容为坐标系,而不是把旧会话钳制值当成最终落点", () => {
  305. const container = installMinimalDom();
  306. mountedRoot = createRoot(container);
  307. // ── commit 0:正在看会话 A(无记忆 → 吸底)。
  308. act(() => renderTimeline(mountedRoot!, "session-a", KEY_A, ROWS_A));
  309. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  310. act(() => {
  311. flushAnimationFrame();
  312. flushAnimationFrame();
  313. flushScheduledMicrotasks();
  314. });
  315. expect(timeline.scrollTop).toBe(900); // A 的底部(1200 - 300)
  316. // 会话 B 上次离开时处于离底阅读态:位置保存在 B 的全量坐标系(scrollHeight=20000)。
  317. saveChatSessionScrollMemoryState(KEY_B, {
  318. scrollTop: 5000,
  319. scrollHeight: 20000,
  320. clientHeight: 300,
  321. wasPinnedToBottom: false,
  322. updatedAt: 1,
  323. });
  324. // ── commit 1:SessionPane 切到 B。sessionKey/scrollMemoryKey 立即变化,
  325. // 但 lease 在 useEffect 里晚一拍 → rows 仍是 A 的内容(SessionPane.tsx rows
  326. // 无 sessionLeaseReady 守卫)。恢复 effect 此刻执行:clamp(5000, 1200-300)=900。
  327. act(() => renderTimeline(mountedRoot!, "session-b", KEY_B, ROWS_A));
  328. act(() => {
  329. flushAnimationFrame(); // 恢复 correction rAF(rows 仍是 A)
  330. flushAnimationFrame(); // release guard rAF
  331. flushScheduledMicrotasks();
  332. });
  333. // ── commit 2:lease 到位,B 在 keep-warm 内 → rows 直接替换为 B 的窗口,
  334. // 从未经过 0 行;B 的内容高度为 2400。
  335. act(() => {
  336. layout.scrollHeight = 2400;
  337. renderTimeline(mountedRoot!, "session-b", KEY_B, ROWS_B_TAIL);
  338. });
  339. act(() => {
  340. flushAnimationFrame();
  341. flushAnimationFrame();
  342. flushScheduledMicrotasks();
  343. });
  344. // 预期行为:恢复应以 B 的实际内容为坐标系 → clamp(5000, 2400-300)=2100
  345. //(至少要把保存位置在新坐标系下重放)。
  346. // 回归前实现:停在 commit 1 里按 A 内容钳出的 900 —— 既不是 B 的上次位置,
  347. // 也不是 B 的底部(2100),即工单描述的"落在历史中间"。
  348. expect(timeline.scrollTop).toBe(2100);
  349. });
  350. it("冷开时记忆的全量坐标像素被分片尾窗钳制后,内容补齐必须重新锚定回保存位置", () => {
  351. // 上次离开:全量窗口(20000px 高)里读到 12000px 处。
  352. saveChatSessionScrollMemoryState(KEY_B, {
  353. scrollTop: 12000,
  354. scrollHeight: 20000,
  355. clientHeight: 300,
  356. wasPinnedToBottom: false,
  357. updatedAt: 1,
  358. });
  359. // 冷开:只有尾部分片 + 72px 估算 → 内容只有 1200px 高。
  360. const container = installMinimalDom();
  361. mountedRoot = createRoot(container);
  362. act(() =>
  363. renderTimeline(mountedRoot!, "session-b", KEY_B, ROWS_B_TAIL, {
  364. canLoadOlder: true,
  365. totalCount: 5,
  366. }),
  367. );
  368. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  369. act(() => {
  370. flushAnimationFrame();
  371. flushAnimationFrame();
  372. flushScheduledMicrotasks();
  373. });
  374. // 恢复被钳进分片坐标系:clamp(12000, 900)=900。
  375. expect(timeline.scrollTop).toBe(900);
  376. expect(timeline.getAttribute("data-following")).toBe("false");
  377. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).not.toBeNull();
  378. // 历史补拉 + 真实测高完成:更早的行前插,总高度回到 20000。
  379. act(() => {
  380. layout.scrollHeight = 20000;
  381. renderTimeline(
  382. mountedRoot!,
  383. "session-b",
  384. KEY_B,
  385. [userInputRow(1), userInputRow(2), ...ROWS_B_TAIL],
  386. { canLoadOlder: false, totalCount: 5 },
  387. );
  388. });
  389. act(() => {
  390. flushAnimationFrame();
  391. flushAnimationFrame();
  392. flushScheduledMicrotasks();
  393. });
  394. // 预期行为:内容补齐后应回到保存的阅读位置 12000。
  395. // 回归前实现:prepend 锚定把"钳制瞬间恰好在视口里的那一行"当作阅读锚点平移
  396. //(900 + 18800 = 19700),落点漂到接近底部/任意历史处,保存位置永久丢失。
  397. expect(timeline.scrollTop).toBe(12000);
  398. });
  399. });