v4ConversationTimelineScrollMemory.test.ts 32 KB

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