v4ConversationTimelineScrollMemory.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import { TID_V4_TIMELINE, TID_V4_TIMELINE_BOTTOM } from "@zcode/shared/test-ids";
  5. import type { ConversationRow, UserInputRow } from "@zcode/shared/zcode-protocol-v4";
  6. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  7. import {
  8. clearChatSessionScrollMemoryForTest,
  9. readChatSessionScrollMemoryState,
  10. saveChatSessionScrollMemoryState,
  11. } from "@/lib/chatSessionScrollMemory.js";
  12. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  13. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  14. import { ConversationTimeline } from "@/v4/ConversationTimeline.js";
  15. const layout = vi.hoisted(() => ({ clientHeight: 300, scrollHeight: 1200 }));
  16. const virtualizer = vi.hoisted(() => ({
  17. getVirtualItemForOffset: vi.fn(),
  18. getTotalSize: () => layout.scrollHeight,
  19. getVirtualItems: () => [],
  20. measurementsCache: [] as Array<{
  21. end: number;
  22. index: number;
  23. key: string;
  24. lane: number;
  25. size: number;
  26. start: number;
  27. }>,
  28. measure: vi.fn(),
  29. measureElement: vi.fn(),
  30. resizeItem: vi.fn(),
  31. scrollOffset: null as number | null,
  32. scrollRect: null as { height: number } | null,
  33. scrollToIndex: vi.fn(),
  34. shouldAdjustScrollPositionOnItemSizeChange: null as
  35. | null
  36. | ((item: { end: number; start: number }) => boolean),
  37. }));
  38. vi.mock("@tanstack/react-virtual", () => ({
  39. useVirtualizer: () => virtualizer,
  40. }));
  41. vi.mock("@/v4/ConversationTurnGroup.js", async () => {
  42. const React = await import("react");
  43. return {
  44. ConversationTurnGroup: () => React.createElement("div"),
  45. };
  46. });
  47. vi.mock("@/v4/ConversationTurnNavigator.js", () => ({
  48. ConversationTurnNavigator: () => null,
  49. }));
  50. vi.mock("@/v4/useConversationTimelineFind.js", () => ({
  51. useConversationTimelineFind: () => undefined,
  52. }));
  53. type TestEventHandler = (event: Record<string, unknown>) => void;
  54. type TestElement = Element & {
  55. __attrs: Map<string, string>;
  56. __listeners: Map<string, TestEventHandler[]>;
  57. childNodes: TestElement[];
  58. parentNode: TestElement | null;
  59. scrollTop: number;
  60. };
  61. let nextFrameId = 1;
  62. const animationFrames = new Map<number, FrameRequestCallback>();
  63. const scheduledMicrotasks: Array<() => void> = [];
  64. const nativeQueueMicrotask = globalThis.queueMicrotask;
  65. let mountedRoot: Root | null = null;
  66. let collapseLayoutWhenTimelineBecomesEmpty = false;
  67. function createMinimalElement(ownerDocument: Document, tagName = "div"): TestElement {
  68. let scrollTop = 0;
  69. const element = {
  70. __attrs: new Map<string, string>(),
  71. __listeners: new Map<string, TestEventHandler[]>(),
  72. addEventListener: (type: string, handler: TestEventHandler) => {
  73. element.__listeners.set(type, [...(element.__listeners.get(type) ?? []), handler]);
  74. },
  75. appendChild: (child: TestElement) => {
  76. child.parentNode = element as unknown as TestElement;
  77. element.childNodes.push(child);
  78. return child;
  79. },
  80. childNodes: [] as TestElement[],
  81. dispatchEvent: (event: Event) => {
  82. // Bug 回归:ConversationTimeline 会在 commit 后派发标准 scroll 事件同步
  83. // virtualizer;最小 DOM 必须实现真实依赖,不能只提供测试专用 dispatchScroll。
  84. const forwardedEvent = {
  85. bubbles: event.bubbles,
  86. cancelBubble: event.cancelBubble,
  87. currentTarget: element,
  88. defaultPrevented: event.defaultPrevented,
  89. preventDefault: () => event.preventDefault(),
  90. stopPropagation: () => event.stopPropagation(),
  91. target: element,
  92. timeStamp: event.timeStamp,
  93. type: event.type,
  94. };
  95. for (const handler of element.__listeners.get(event.type) ?? []) {
  96. handler(forwardedEvent);
  97. }
  98. return !event.defaultPrevented;
  99. },
  100. getBoundingClientRect: () => ({
  101. bottom: layout.clientHeight,
  102. height: layout.clientHeight,
  103. left: 0,
  104. right: 800,
  105. top: 0,
  106. width: 800,
  107. x: 0,
  108. y: 0,
  109. toJSON: () => ({}),
  110. }),
  111. getAttribute: (name: string) => element.__attrs.get(name) ?? null,
  112. insertBefore: (child: TestElement, beforeChild?: TestElement | null) => {
  113. child.parentNode = element as unknown as TestElement;
  114. const index = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  115. if (index >= 0) element.childNodes.splice(index, 0, child);
  116. else element.childNodes.push(child);
  117. return child;
  118. },
  119. nodeName: tagName.toUpperCase(),
  120. nodeType: 1,
  121. ownerDocument,
  122. parentNode: null as TestElement | null,
  123. removeAttribute: (name: string) => element.__attrs.delete(name),
  124. removeChild: (child: TestElement) => {
  125. element.childNodes = element.childNodes.filter((item) => item !== child);
  126. child.parentNode = null;
  127. return child;
  128. },
  129. removeEventListener: (type: string, handler: TestEventHandler) => {
  130. element.__listeners.set(
  131. type,
  132. (element.__listeners.get(type) ?? []).filter((item) => item !== handler),
  133. );
  134. },
  135. querySelectorAll: () => [],
  136. setAttribute: (name: string, value: string) => {
  137. element.__attrs.set(name, String(value));
  138. if (
  139. collapseLayoutWhenTimelineBecomesEmpty &&
  140. name === "data-render-unit-count" &&
  141. String(value) === "0"
  142. ) {
  143. layout.scrollHeight = layout.clientHeight;
  144. }
  145. },
  146. style: {},
  147. tagName: tagName.toUpperCase(),
  148. };
  149. Object.defineProperties(element, {
  150. clientHeight: { get: () => layout.clientHeight },
  151. scrollHeight: { get: () => layout.scrollHeight },
  152. scrollTop: {
  153. get: () => scrollTop,
  154. set: (value: number) => {
  155. scrollTop = Math.min(
  156. Math.max(Number(value) || 0, 0),
  157. Math.max(layout.scrollHeight - layout.clientHeight, 0),
  158. );
  159. },
  160. },
  161. });
  162. return element as unknown as TestElement;
  163. }
  164. function installMinimalDom(): TestElement {
  165. const documentMock = {
  166. addEventListener: () => {},
  167. createElement: (tagName: string) =>
  168. createMinimalElement(documentMock as unknown as Document, tagName),
  169. createElementNS: (_namespace: string, tagName: string) =>
  170. createMinimalElement(documentMock as unknown as Document, tagName),
  171. createTextNode: (nodeValue: string) => ({
  172. nodeType: 3,
  173. nodeValue,
  174. ownerDocument: documentMock,
  175. parentNode: null,
  176. }),
  177. nodeType: 9,
  178. removeEventListener: () => {},
  179. } as unknown as Document & { defaultView?: unknown };
  180. const windowMock = {
  181. setTimeout,
  182. clearTimeout,
  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(
  211. node: TestElement,
  212. testId: string,
  213. attribute = "data-testid",
  214. ): TestElement | null {
  215. if (node.getAttribute(attribute) === testId) return node;
  216. for (const child of node.childNodes) {
  217. if (child.nodeType !== 1) continue;
  218. const match = findByTestId(child, testId, attribute);
  219. if (match) return match;
  220. }
  221. return null;
  222. }
  223. function dispatchScroll(element: TestElement): void {
  224. element.dispatchEvent(new Event("scroll"));
  225. }
  226. function dispatchWheel(element: TestElement, deltaY: number): void {
  227. const event = {
  228. bubbles: true,
  229. cancelBubble: false,
  230. currentTarget: element,
  231. defaultPrevented: false,
  232. deltaMode: 0,
  233. deltaX: 0,
  234. deltaY,
  235. preventDefault: () => {},
  236. stopPropagation: () => {},
  237. target: element,
  238. timeStamp: Date.now(),
  239. type: "wheel",
  240. };
  241. const path: TestElement[] = [];
  242. let current: TestElement | null = element;
  243. while (current) {
  244. path.push(current);
  245. current = current.parentNode;
  246. }
  247. for (const currentTarget of path.reverse()) {
  248. event.currentTarget = currentTarget;
  249. for (const handler of currentTarget.__listeners.get("wheel") ?? []) handler(event);
  250. }
  251. for (const currentTarget of path) {
  252. event.currentTarget = currentTarget;
  253. for (const handler of currentTarget.__listeners.get("wheel") ?? []) handler(event);
  254. }
  255. }
  256. function flushAnimationFrame(): void {
  257. const frameIds = [...animationFrames.keys()];
  258. for (const frameId of frameIds) {
  259. const callback = animationFrames.get(frameId);
  260. if (!callback) continue;
  261. animationFrames.delete(frameId);
  262. callback(0);
  263. }
  264. }
  265. function flushScheduledMicrotasks(): void {
  266. while (scheduledMicrotasks.length > 0) {
  267. scheduledMicrotasks.shift()?.();
  268. }
  269. }
  270. const row: UserInputRow = {
  271. rowId: 1,
  272. turnId: "turn-1",
  273. createdAt: 1_700_000_000_000,
  274. createdAtSeq: 1,
  275. kind: "userInput",
  276. origin: "realUser",
  277. text: "hello",
  278. attachments: [],
  279. };
  280. const rowContext: ConversationRowRenderContext = {
  281. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  282. sessionId: "session-1",
  283. theme: "system",
  284. workspacePath: "/workspace",
  285. };
  286. function renderTimeline(
  287. root: Root,
  288. sessionKey: string,
  289. scrollMemoryKey: string | null,
  290. scrollToBottomActionRef?: { current: (() => void) | null },
  291. options: {
  292. canLoadOlder?: boolean;
  293. onLoadOlder?: () => void;
  294. rows?: readonly ConversationRow[];
  295. withComposerDock?: boolean;
  296. } = {},
  297. ): void {
  298. const timelineRows = options.rows ?? [row];
  299. root.render(
  300. createElement(
  301. ZCodeIntlProvider,
  302. { initialLocale: "zh-CN" },
  303. createElement(ConversationTimeline, {
  304. canLoadOlder: options.canLoadOlder,
  305. onLoadOlder: options.onLoadOlder,
  306. scrollToBottomActionRef,
  307. rows: timelineRows,
  308. totalCount: timelineRows.length,
  309. sessionKey,
  310. scrollMemoryKey,
  311. rowContext,
  312. // composer dock。它上方那条浮层带随浮岛一起删除,圆钮回到自己的居中定位。
  313. ...(options.withComposerDock
  314. ? {
  315. bottomDock: createElement("div", { "data-testid": "test-composer-dock" }),
  316. }
  317. : {}),
  318. }),
  319. ),
  320. );
  321. }
  322. beforeEach(() => {
  323. clearChatSessionScrollMemoryForTest();
  324. layout.clientHeight = 300;
  325. layout.scrollHeight = 1200;
  326. nextFrameId = 1;
  327. animationFrames.clear();
  328. scheduledMicrotasks.length = 0;
  329. collapseLayoutWhenTimelineBecomesEmpty = false;
  330. virtualizer.getVirtualItemForOffset.mockReset();
  331. virtualizer.measurementsCache = [];
  332. virtualizer.measure.mockClear();
  333. });
  334. afterEach(() => {
  335. act(() => {
  336. flushScheduledMicrotasks();
  337. mountedRoot?.unmount();
  338. flushScheduledMicrotasks();
  339. });
  340. mountedRoot = null;
  341. animationFrames.clear();
  342. scheduledMicrotasks.length = 0;
  343. globalThis.queueMicrotask = nativeQueueMicrotask;
  344. delete (globalThis as { document?: unknown }).document;
  345. delete (globalThis as { window?: unknown }).window;
  346. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  347. });
  348. describe("ConversationTimeline renderer-local scroll memory", () => {
  349. it("跟随时先提交新行高再吸底,用户离底后 resize 不抢回滚动权", () => {
  350. const container = installMinimalDom();
  351. const observations: Array<{ target: Element; callback: ResizeObserverCallback }> = [];
  352. vi.stubGlobal(
  353. "ResizeObserver",
  354. class {
  355. constructor(private callback: ResizeObserverCallback) {}
  356. observe(target: Element) {
  357. observations.push({ target, callback: this.callback });
  358. }
  359. unobserve() {}
  360. disconnect() {}
  361. },
  362. );
  363. try {
  364. mountedRoot = createRoot(container);
  365. const backToBottom = { current: null as (() => void) | null };
  366. act(() => {
  367. renderTimeline(mountedRoot!, "session-1", null, backToBottom);
  368. });
  369. act(() => flushAnimationFrame());
  370. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  371. const observers = observations.filter((item) => item.target === timeline);
  372. expect(observers.length).toBeGreaterThan(0);
  373. const column = findByTestId(container, "true", "data-v4-timeline-virtual-history")!;
  374. let measuredHeight = 1200;
  375. let contentWidth = 1000;
  376. Object.defineProperty(column, "clientWidth", { configurable: true, get: () => contentWidth });
  377. const row = {
  378. getAttribute: () => "0",
  379. getBoundingClientRect: () => ({ height: measuredHeight }),
  380. } as unknown as Element;
  381. const query = vi
  382. .spyOn(column, "querySelectorAll")
  383. .mockReturnValue([row] as unknown as NodeListOf<Element>);
  384. // 模拟库已测高但 React 尚未提交占位高度;只有重新 render 才能读到新布局。
  385. const totalSize = vi.spyOn(virtualizer, "getTotalSize").mockImplementation(() => {
  386. layout.scrollHeight = measuredHeight;
  387. return measuredHeight;
  388. });
  389. for (const height of [1500, 1800, 1350, 2100]) {
  390. act(() => {
  391. measuredHeight = height;
  392. contentWidth -= 10;
  393. for (const observer of observers) observer.callback([], {} as ResizeObserver);
  394. });
  395. expect(timeline.scrollTop).toBe(height - layout.clientHeight);
  396. expect(virtualizer.resizeItem).toHaveBeenLastCalledWith(0, height);
  397. }
  398. act(() => {
  399. flushAnimationFrame();
  400. flushAnimationFrame();
  401. dispatchWheel(timeline, -120);
  402. timeline.scrollTop = 200;
  403. dispatchScroll(timeline);
  404. });
  405. expect(timeline.getAttribute("data-following")).toBe("false");
  406. act(() => {
  407. measuredHeight = 2400;
  408. contentWidth -= 10;
  409. for (const observer of observers) observer.callback([], {} as ResizeObserver);
  410. });
  411. expect(timeline.scrollTop).toBe(200);
  412. act(() => backToBottom.current?.());
  413. contentWidth -= 10;
  414. act(() => {
  415. for (const observer of observers) observer.callback([], {} as ResizeObserver);
  416. });
  417. expect(timeline.scrollTop).toBe(2100);
  418. // 用户在批量测高期间上滚,提交后必须再次检查跟随权。
  419. virtualizer.resizeItem.mockImplementationOnce(() => dispatchWheel(timeline, -120));
  420. const beforeInterrupt = timeline.scrollTop;
  421. act(() => {
  422. measuredHeight = 2700;
  423. contentWidth -= 10;
  424. for (const observer of observers) observer.callback([], {} as ResizeObserver);
  425. });
  426. expect(timeline.getAttribute("data-following")).toBe("false");
  427. expect(timeline.scrollTop).toBe(beforeInterrupt);
  428. totalSize.mockRestore();
  429. query.mockRestore();
  430. virtualizer.resizeItem.mockReset();
  431. } finally {
  432. vi.restoreAllMocks();
  433. virtualizer.resizeItem.mockReset();
  434. vi.unstubAllGlobals();
  435. }
  436. });
  437. it("keeps the visible turn anchored when a large prepend unmounts its DOM row", () => {
  438. layout.scrollHeight = 5000;
  439. const previousAnchorMeasurement = {
  440. end: 620,
  441. index: 0,
  442. key: "turn-100",
  443. lane: 0,
  444. size: 120,
  445. start: 500,
  446. };
  447. virtualizer.getVirtualItemForOffset.mockReturnValue(previousAnchorMeasurement);
  448. virtualizer.measurementsCache = [previousAnchorMeasurement];
  449. const onLoadOlder = vi.fn();
  450. const container = installMinimalDom();
  451. mountedRoot = createRoot(container);
  452. act(() =>
  453. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1", undefined, {
  454. canLoadOlder: true,
  455. onLoadOlder,
  456. rows: [{ ...row, rowId: 100, turnId: "turn-100" }],
  457. }),
  458. );
  459. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  460. act(() => {
  461. flushAnimationFrame();
  462. flushAnimationFrame();
  463. dispatchWheel(timeline, -120);
  464. timeline.scrollTop = 500;
  465. dispatchScroll(timeline);
  466. });
  467. expect(onLoadOlder).toHaveBeenCalledTimes(1);
  468. const olderRows: UserInputRow[] = Array.from({ length: 10 }, (_, index) => ({
  469. ...row,
  470. rowId: index + 1,
  471. turnId: `turn-${index + 1}`,
  472. }));
  473. virtualizer.measurementsCache = [
  474. ...olderRows.map((olderRow, index) => ({
  475. end: (index + 1) * 100,
  476. index,
  477. key: olderRow.turnId,
  478. lane: 0,
  479. size: 100,
  480. start: index * 100,
  481. })),
  482. {
  483. ...previousAnchorMeasurement,
  484. end: 1620,
  485. index: olderRows.length,
  486. start: 1500,
  487. },
  488. ];
  489. act(() =>
  490. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1", undefined, {
  491. canLoadOlder: false,
  492. onLoadOlder,
  493. rows: [...olderRows, { ...row, rowId: 100, turnId: "turn-100" }],
  494. }),
  495. );
  496. // 旧锚点已在 viewport + 8 行 overscan 之外,DOM 查询和旧 totalSize 都无法给出位移。
  497. expect(timeline.querySelectorAll('[data-v4-turn-unit="true"]')).toHaveLength(0);
  498. expect(timeline.scrollTop).toBe(1500);
  499. });
  500. it("restores a detached history position immediately and after RAF correction", () => {
  501. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  502. scrollTop: 240,
  503. scrollHeight: 1000,
  504. clientHeight: 300,
  505. wasPinnedToBottom: false,
  506. updatedAt: 1,
  507. });
  508. const container = installMinimalDom();
  509. mountedRoot = createRoot(container);
  510. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  511. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  512. expect(timeline.scrollTop).toBe(240);
  513. expect((timeline.childNodes[0] as unknown as HTMLElement).style.overflowAnchor).toBe("none");
  514. expect(
  515. virtualizer.shouldAdjustScrollPositionOnItemSizeChange?.({
  516. end: 100,
  517. start: 0,
  518. }),
  519. ).toBe(false);
  520. expect(timeline.getAttribute("data-following")).toBe("false");
  521. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).not.toBeNull();
  522. act(() => {
  523. flushAnimationFrame();
  524. flushAnimationFrame();
  525. });
  526. expect(timeline.scrollTop).toBe(240);
  527. expect(
  528. virtualizer.shouldAdjustScrollPositionOnItemSizeChange?.({
  529. end: 100,
  530. start: 0,
  531. }),
  532. ).toBe(true);
  533. expect(
  534. virtualizer.shouldAdjustScrollPositionOnItemSizeChange?.({
  535. end: 300,
  536. start: 100,
  537. }),
  538. ).toBe(false);
  539. });
  540. it("restores pinned intent to the current bottom after background growth", () => {
  541. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  542. scrollTop: 700,
  543. scrollHeight: 1000,
  544. clientHeight: 300,
  545. wasPinnedToBottom: true,
  546. updatedAt: 1,
  547. });
  548. layout.scrollHeight = 1800;
  549. const container = installMinimalDom();
  550. mountedRoot = createRoot(container);
  551. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  552. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  553. expect(timeline.scrollTop).toBe(1500);
  554. expect(timeline.getAttribute("data-following")).toBe("true");
  555. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).toBeNull();
  556. expect(
  557. virtualizer.shouldAdjustScrollPositionOnItemSizeChange?.({
  558. end: 100,
  559. start: 0,
  560. }),
  561. ).toBe(false);
  562. });
  563. it("keeps following when terminal layout shrink moves scrollTop without user input", () => {
  564. const container = installMinimalDom();
  565. mountedRoot = createRoot(container);
  566. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  567. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  568. expect(timeline.scrollTop).toBe(900);
  569. act(() => {
  570. flushAnimationFrame();
  571. flushAnimationFrame();
  572. layout.scrollHeight = 1000;
  573. timeline.scrollTop = 700;
  574. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1");
  575. dispatchScroll(timeline);
  576. });
  577. expect(timeline.scrollTop).toBe(700);
  578. expect(timeline.getAttribute("data-following")).toBe("true");
  579. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).toBeNull();
  580. });
  581. it("lets an upward wheel win when terminal layout changes in the same commit", () => {
  582. const container = installMinimalDom();
  583. mountedRoot = createRoot(container);
  584. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  585. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  586. act(() => {
  587. flushAnimationFrame();
  588. flushAnimationFrame();
  589. dispatchWheel(timeline, -120);
  590. timeline.scrollTop = 600;
  591. layout.scrollHeight = 1100;
  592. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1");
  593. dispatchScroll(timeline);
  594. });
  595. expect(timeline.scrollTop).toBe(600);
  596. expect(timeline.getAttribute("data-following")).toBe("false");
  597. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).not.toBeNull();
  598. });
  599. it("exposes the same one-shot bottom action used by prompt submission", () => {
  600. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  601. scrollTop: 240,
  602. scrollHeight: 1200,
  603. clientHeight: 300,
  604. wasPinnedToBottom: false,
  605. updatedAt: 1,
  606. });
  607. const container = installMinimalDom();
  608. mountedRoot = createRoot(container);
  609. const scrollToBottomActionRef = { current: null as (() => void) | null };
  610. act(() =>
  611. renderTimeline(
  612. mountedRoot!,
  613. "session-1",
  614. "workspace::pane:a::session:1",
  615. scrollToBottomActionRef,
  616. ),
  617. );
  618. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  619. expect(timeline.getAttribute("data-following")).toBe("false");
  620. act(() => scrollToBottomActionRef.current?.());
  621. expect(timeline.scrollTop).toBe(900);
  622. expect(timeline.getAttribute("data-following")).toBe("true");
  623. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).toBeNull();
  624. act(() => {
  625. dispatchWheel(timeline, -120);
  626. timeline.scrollTop = 240;
  627. dispatchScroll(timeline);
  628. });
  629. expect(timeline.getAttribute("data-following")).toBe("false");
  630. });
  631. it("commits a bottom action before an immediate session switch", () => {
  632. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  633. scrollTop: 240,
  634. scrollHeight: 1200,
  635. clientHeight: 300,
  636. wasPinnedToBottom: false,
  637. updatedAt: 1,
  638. });
  639. const container = installMinimalDom();
  640. mountedRoot = createRoot(container);
  641. const scrollToBottomActionRef = { current: null as (() => void) | null };
  642. act(() =>
  643. renderTimeline(
  644. mountedRoot!,
  645. "session-1",
  646. "workspace::pane:a::session:1",
  647. scrollToBottomActionRef,
  648. ),
  649. );
  650. act(() => scrollToBottomActionRef.current?.());
  651. expect(readChatSessionScrollMemoryState("workspace::pane:a::session:1")).toMatchObject({
  652. scrollTop: 900,
  653. wasPinnedToBottom: true,
  654. });
  655. act(() => renderTimeline(mountedRoot!, "session-2", "workspace::pane:a::session:2"));
  656. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  657. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  658. expect(timeline.scrollTop).toBe(900);
  659. expect(timeline.getAttribute("data-following")).toBe("true");
  660. });
  661. it("restores a detached position after delayed rows arrive", () => {
  662. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  663. scrollTop: 240,
  664. scrollHeight: 1200,
  665. clientHeight: 300,
  666. wasPinnedToBottom: false,
  667. updatedAt: 1,
  668. });
  669. layout.scrollHeight = layout.clientHeight;
  670. const container = installMinimalDom();
  671. mountedRoot = createRoot(container);
  672. act(() =>
  673. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1", undefined, {
  674. rows: [],
  675. }),
  676. );
  677. let timeline = findByTestId(container, TID_V4_TIMELINE)!;
  678. expect(timeline.scrollTop).toBe(0);
  679. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).toBeNull();
  680. act(() => {
  681. flushAnimationFrame();
  682. flushAnimationFrame();
  683. });
  684. layout.scrollHeight = 1200;
  685. act(() =>
  686. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1", undefined, {
  687. rows: [row],
  688. }),
  689. );
  690. timeline = findByTestId(container, TID_V4_TIMELINE)!;
  691. expect(timeline.scrollTop).toBe(240);
  692. expect(timeline.getAttribute("data-following")).toBe("false");
  693. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).not.toBeNull();
  694. });
  695. it("keeps detached memory when switching away before rows arrive", () => {
  696. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  697. scrollTop: 240,
  698. scrollHeight: 1200,
  699. clientHeight: 300,
  700. wasPinnedToBottom: false,
  701. updatedAt: 1,
  702. });
  703. layout.scrollHeight = layout.clientHeight;
  704. const container = installMinimalDom();
  705. mountedRoot = createRoot(container);
  706. act(() =>
  707. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1", undefined, {
  708. rows: [],
  709. }),
  710. );
  711. act(() =>
  712. renderTimeline(mountedRoot!, "session-2", "workspace::pane:a::session:2", undefined, {
  713. rows: [],
  714. }),
  715. );
  716. expect(readChatSessionScrollMemoryState("workspace::pane:a::session:1")).toMatchObject({
  717. scrollTop: 240,
  718. wasPinnedToBottom: false,
  719. });
  720. });
  721. it("cancels the second restore write when the user takes scroll ownership", () => {
  722. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  723. scrollTop: 240,
  724. scrollHeight: 1200,
  725. clientHeight: 300,
  726. wasPinnedToBottom: false,
  727. updatedAt: 1,
  728. });
  729. const container = installMinimalDom();
  730. mountedRoot = createRoot(container);
  731. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  732. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  733. act(() => {
  734. dispatchWheel(timeline, 120);
  735. timeline.scrollTop = 520;
  736. dispatchScroll(timeline);
  737. flushAnimationFrame();
  738. flushAnimationFrame();
  739. });
  740. expect(timeline.scrollTop).toBe(520);
  741. expect(readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.scrollTop).toBe(520);
  742. });
  743. it("saves an unobserved up-scroll on scope change and keeps pane keys isolated", () => {
  744. saveChatSessionScrollMemoryState("workspace::pane:b::session:1", {
  745. scrollTop: 620,
  746. scrollHeight: 1200,
  747. clientHeight: 300,
  748. wasPinnedToBottom: false,
  749. updatedAt: 1,
  750. });
  751. const container = installMinimalDom();
  752. mountedRoot = createRoot(container);
  753. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  754. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  755. act(() => {
  756. flushAnimationFrame();
  757. flushAnimationFrame();
  758. timeline.scrollTop = 310;
  759. renderTimeline(mountedRoot!, "draft", null);
  760. });
  761. act(() => {
  762. renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1");
  763. });
  764. expect(timeline.scrollTop).toBe(310);
  765. expect(
  766. readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.wasPinnedToBottom,
  767. ).toBe(false);
  768. expect(readChatSessionScrollMemoryState("workspace::pane:b::session:1")?.scrollTop).toBe(620);
  769. });
  770. it("captures an unobserved downward scroll before the scope DOM mutates", () => {
  771. const container = installMinimalDom();
  772. mountedRoot = createRoot(container);
  773. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  774. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  775. act(() => {
  776. flushAnimationFrame();
  777. flushAnimationFrame();
  778. dispatchWheel(timeline, -120);
  779. timeline.scrollTop = 240;
  780. dispatchScroll(timeline);
  781. timeline.scrollTop = 520;
  782. renderTimeline(mountedRoot!, "draft", null);
  783. });
  784. expect(readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.scrollTop).toBe(520);
  785. expect(
  786. readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.wasPinnedToBottom,
  787. ).toBe(false);
  788. });
  789. it("does not overwrite a saved user position after the next scope collapses the DOM", () => {
  790. const container = installMinimalDom();
  791. mountedRoot = createRoot(container);
  792. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  793. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  794. act(() => {
  795. flushAnimationFrame();
  796. flushAnimationFrame();
  797. dispatchWheel(timeline, -120);
  798. timeline.scrollTop = 280;
  799. dispatchScroll(timeline);
  800. collapseLayoutWhenTimelineBecomesEmpty = true;
  801. renderTimeline(mountedRoot!, "draft", null);
  802. });
  803. expect(readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.scrollTop).toBe(280);
  804. expect(
  805. readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.wasPinnedToBottom,
  806. ).toBe(false);
  807. });
  808. it("saves the last observed DOM position when the timeline unmounts", () => {
  809. const container = installMinimalDom();
  810. mountedRoot = createRoot(container);
  811. act(() => renderTimeline(mountedRoot!, "session-1", "workspace::pane:a::session:1"));
  812. const timeline = findByTestId(container, TID_V4_TIMELINE)!;
  813. act(() => {
  814. flushAnimationFrame();
  815. flushAnimationFrame();
  816. timeline.scrollTop = 410;
  817. mountedRoot?.unmount();
  818. mountedRoot = null;
  819. });
  820. expect(readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.scrollTop).toBe(410);
  821. expect(
  822. readChatSessionScrollMemoryState("workspace::pane:a::session:1")?.wasPinnedToBottom,
  823. ).toBe(false);
  824. });
  825. it("hides the back-to-bottom button after its action while retaining the composer dock", () => {
  826. saveChatSessionScrollMemoryState("workspace::pane:a::session:1", {
  827. scrollTop: 240,
  828. scrollHeight: 1000,
  829. clientHeight: 300,
  830. wasPinnedToBottom: false,
  831. updatedAt: 1,
  832. });
  833. const container = installMinimalDom();
  834. mountedRoot = createRoot(container);
  835. const scrollToBottomActionRef = { current: null as (() => void) | null };
  836. act(() =>
  837. renderTimeline(
  838. mountedRoot!,
  839. "session-1",
  840. "workspace::pane:a::session:1",
  841. scrollToBottomActionRef,
  842. { withComposerDock: true },
  843. ),
  844. );
  845. const button = findByTestId(container, TID_V4_TIMELINE_BOTTOM)!;
  846. expect(button).not.toBeNull();
  847. expect(findByTestId(container, "test-composer-dock")).not.toBeNull();
  848. act(() => scrollToBottomActionRef.current?.());
  849. expect(findByTestId(container, TID_V4_TIMELINE_BOTTOM)).toBeNull();
  850. });
  851. });