Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(messages): preserve pagination scroll anchors (#807)
Gener3dd3cdfd5a3b
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 7a5b6e2f1..72f8d96d4 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -81,6 +81,7 @@ export const SPEC_SECONDS = {"56-remote-image-state-contract.spec.ts": 3.122,"57-server-delete-navigation-races.spec.ts": 55,"58-system-notifications.spec.ts": 46.600,+ "59-message-pagination-anchor.spec.ts": 45.600,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 74914293e..c93ebbd99 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -80,12 +80,12 @@ describe("planE2eShards", () => {expect(new Set(assigned).size).toBe(specs.length)expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)expect(specSeconds).toEqual([- 155.554, 155.114, 155.36, 155.929, 155.489,- 155.164, 155.229, 154.758, 155.247, 156.185,+ 159.35, 159.401, 159.292, 160.394, 160.366,+ 159.32, 160.547, 160.676, 159.332, 160.951,])expect(predictedSeconds).toEqual([- 230.554, 230.114, 230.36, 230.929, 230.489,- 230.164, 230.229, 229.758, 230.247, 231.185,+ 234.35, 234.401, 234.292, 235.394, 235.366,+ 234.32, 235.547, 235.676, 234.332, 235.951,])expect(first.every((shard) => (shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDSdiff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.tsindex a8f7a4a68..309e5c722 100644--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({jumpToIndex: vi.fn(),scrollToBottom: vi.fn(),onImageLoad: vi.fn(),+ captureOlderPageAnchor: vi.fn(),}))vi.mock("@/hooks/community/use-scroll-anchor", () => ({@@ -33,6 +34,8 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({scrollToBottom: mocks.scrollToBottom,jumpTo: mocks.jumpToIndex,onImageLoad: mocks.onImageLoad,+ captureOlderPageAnchor: mocks.captureOlderPageAnchor,+ isOlderPageAnchorSettling: false,}},}))@@ -191,6 +194,7 @@ describe("useMessageListController", () => {newDividerBefore: undefined,initialScrollReady: true,hasMoreNewer: undefined,+ isFetchingOlder: undefined,presentVersion: undefined,viewerUserId: undefined,heroHeight: 0,@@ -202,6 +206,8 @@ describe("useMessageListController", () => {scrollRef: mocks.scrollRef,hasMore: undefined,isFetching: undefined,+ isSettling: false,+ onBeforeLoad: mocks.captureOlderPageAnchor,onLoad: undefined,edge: "start",},@@ -294,6 +300,7 @@ describe("useMessageListController", () => {newDividerBefore: "m1",initialScrollReady: false,hasMoreNewer: true,+ isFetchingOlder: true,presentVersion: 7,viewerUserId: "viewer_1",heroHeight: 0,@@ -305,6 +312,8 @@ describe("useMessageListController", () => {scrollRef: mocks.scrollRef,hasMore: true,isFetching: true,+ isSettling: false,+ onBeforeLoad: mocks.captureOlderPageAnchor,onLoad: loadOlder,edge: "start",},diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex 1a6c51257..1e1b02a40 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -112,11 +112,14 @@ export function useMessageListController({scrollToBottom,jumpTo: jumpToIndex,onImageLoad,+ captureOlderPageAnchor,+ isOlderPageAnchorSettling,} = useScrollAnchor({items,newDividerBefore,initialScrollReady: scrollAnchorReady,hasMoreNewer,+ isFetchingOlder,presentVersion,viewerUserId,heroHeight,@@ -179,6 +182,8 @@ export function useMessageListController({scrollRef,hasMore,isFetching: isFetchingOlder,+ isSettling: isOlderPageAnchorSettling,+ onBeforeLoad: captureOlderPageAnchor,onLoad: onLoadOlder,edge: "start",})diff --git a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts b/src/web/src/components/community/messages/message-list.older-load.dom.test.tsindex 44fb305f1..035dd319d 100644--- a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts+++ b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts@@ -105,6 +105,9 @@ describe("MessageList — older-load sentinel does not cascade", () => {expect(onLoadOlder).toHaveBeenCalledTimes(1)renderer.rerender(view(false))+ expect(onLoadOlder).toHaveBeenCalledTimes(1)++ fireEvent.wheel(scroller, { deltaY: -20 })expect(onLoadOlder).toHaveBeenCalledTimes(2)renderer.rerender(view(false))@@ -124,7 +127,7 @@ describe("MessageList — older-load sentinel does not cascade", () => {intersect()expect(onLoadOlder).toHaveBeenCalledTimes(2)renderer.unmount()- expect(removeEventListener).toHaveBeenCalledWith("scroll", expect.any(Function))+ expect(removeEventListener).toHaveBeenCalledWith("wheel", expect.any(Function))expect(onLoadOlder).toHaveBeenCalledTimes(2)})})diff --git a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.tsnew file mode 100644index 000000000..f99880834--- /dev/null+++ b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts@@ -0,0 +1,244 @@+import { createElement, useLayoutEffect } from "react"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { act, render, screen } from "@/test/react-dom-harness"+import type { FlatItem } from "@/lib/community/message-list-items"++const harness = vi.hoisted(() => ({+ absoluteTops: new Map<string, number>(),+ scroller: null as HTMLDivElement | null,+ scrollToIndex: vi.fn((index: number) => {+ if (!harness.scroller) return+ const row = harness.scroller.querySelector<HTMLElement>(`[data-index="${index}"]`)+ const id = row?.dataset.msgId+ if (id) harness.scroller.scrollTop = harness.absoluteTops.get(id) ?? 0+ }),+ virtualizer: {+ options: { anchorTo: "end" },+ isAtEnd: vi.fn(() => false),+ scrollToEnd: vi.fn(),+ scrollToIndex: vi.fn(),+ range: null,+ shouldAdjustScrollPositionOnItemSizeChange: undefined,+ },+}))++harness.virtualizer.scrollToIndex = harness.scrollToIndex++vi.mock("@tanstack/react-virtual", () => ({+ useVirtualizer: () => harness.virtualizer,+}))++import { useScrollAnchor } from "./use-scroll-anchor"++type AnchorResult = ReturnType<typeof useScrollAnchor>++function message(id: string): FlatItem {+ return {+ kind: "message",+ m: { id, type: "chat", grouped: false },+ key: `msg:${id}`,+ }+}++const day = (key: string): FlatItem => ({ kind: "date-divider", label: key, key: `date:${key}` })++function Harness({+ items,+ isFetchingOlder,+ onResult,+}: {+ items: FlatItem[]+ isFetchingOlder: boolean+ onResult: (result: AnchorResult) => void+}) {+ const result = useScrollAnchor({+ items,+ initialScrollReady: false,+ isFetchingOlder,+ heroHeight: 0,+ heroMeasured: false,+ })+ useLayoutEffect(() => onResult(result), [onResult, result])+ return createElement(+ "div",+ { ref: result.scrollRef, "data-testid": "scroll" },+ ...items.map((item, index) => createElement("div", {+ key: item.key,+ "data-index": index,+ "data-msg-id": item.kind === "message" ? item.m.id : undefined,+ })),+ )+}++describe("useScrollAnchor older-page message anchoring", () => {+ let frames: FrameRequestCallback[]+ let cancelFrame: ReturnType<typeof vi.fn>+ let latest: AnchorResult++ beforeEach(() => {+ frames = []+ harness.absoluteTops.clear()+ harness.scroller = null+ harness.scrollToIndex.mockClear()+ harness.virtualizer.scrollToEnd.mockClear()+ cancelFrame = vi.fn()+ vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} })+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ frames.push(callback)+ return frames.length+ })+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation(cancelFrame)+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(600)+ vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(5_000)+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function () {+ const element = this as HTMLElement+ if (element.dataset.testid === "scroll") {+ return DOMRect.fromRect({ y: 0, height: 600 })+ }+ const id = element.dataset.msgId+ const top = id ? (harness.absoluteTops.get(id) ?? 0) - (harness.scroller?.scrollTop ?? 0) : 0+ return DOMRect.fromRect({ y: top, height: 80 })+ })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ })++ function runCase(initialItems: FlatItem[], nextItems: FlatItem[], nextAnchorTop: number) {+ const onResult = (result: AnchorResult) => { latest = result }+ harness.absoluteTops.set("anchor", 120)+ const rendered = render(createElement(Harness, {+ items: initialItems,+ isFetchingOlder: false,+ onResult,+ }))+ harness.scroller = screen.getByTestId("scroll") as HTMLDivElement++ act(() => latest.captureOlderPageAnchor())+ rendered.rerender(createElement(Harness, {+ items: initialItems,+ isFetchingOlder: true,+ onResult,+ }))+ harness.absoluteTops.set("anchor", nextAnchorTop)+ rendered.rerender(createElement(Harness, {+ items: nextItems,+ isFetchingOlder: false,+ onResult,+ }))+ act(() => {+ while (frames.length > 0) frames.shift()!(0)+ })++ const anchor = rendered.container.querySelector<HTMLElement>('[data-msg-id="anchor"]')!+ expect(anchor.getBoundingClientRect().top).toBe(120)+ expect(latest.isOlderPageAnchorSettling).toBe(false)+ return rendered+ }++ it("preserves the real message across same-day and cross-day divider shapes", () => {+ const initial = [day("2026-09-18"), message("anchor")]+ const sameDay = [day("2026-09-18"), message("older"), message("anchor")]+ let rendered = runCase(initial, sameDay, 520)+ expect(harness.scrollToIndex).toHaveBeenLastCalledWith(2, { align: "start" })+ rendered.unmount()++ harness.scrollToIndex.mockClear()+ const crossDay = [+ day("2026-09-17"),+ message("older"),+ day("2026-09-18"),+ message("anchor"),+ ]+ rendered = runCase(initial, crossDay, 720)+ expect(harness.scrollToIndex).toHaveBeenLastCalledWith(3, { align: "start" })+ rendered.unmount()+ })++ it("settles an empty or fully overlapping page without moving the anchor", () => {+ const items = [day("2026-09-18"), message("anchor")]+ const rendered = runCase(items, items.slice(), 120)+ expect(harness.scrollToIndex).toHaveBeenLastCalledWith(1, { align: "start" })+ rendered.unmount()+ })++ it("cancels a pending reconciliation before capturing a replacement anchor", () => {+ const onResult = (result: AnchorResult) => { latest = result }+ const initial = [message("anchor")]+ const prepended = [message("older"), message("anchor")]+ harness.absoluteTops.set("anchor", 120)+ const rendered = render(createElement(Harness, {+ items: initial,+ isFetchingOlder: false,+ onResult,+ }))+ harness.scroller = screen.getByTestId("scroll") as HTMLDivElement++ act(() => latest.captureOlderPageAnchor())+ rendered.rerender(createElement(Harness, { items: initial, isFetchingOlder: true, onResult }))+ harness.absoluteTops.set("anchor", 520)+ rendered.rerender(createElement(Harness, { items: prepended, isFetchingOlder: false, onResult }))+ expect(frames).toHaveLength(1)++ act(() => latest.captureOlderPageAnchor())+ expect(cancelFrame).toHaveBeenCalledWith(1)+ expect(latest.isOlderPageAnchorSettling).toBe(true)+ rendered.unmount()+ })++ it("clears settlement when the captured anchor disappears from the loaded window", () => {+ const onResult = (result: AnchorResult) => { latest = result }+ const initial = [message("anchor")]+ harness.absoluteTops.set("anchor", 120)+ const rendered = render(createElement(Harness, {+ items: initial,+ isFetchingOlder: false,+ onResult,+ }))+ harness.scroller = screen.getByTestId("scroll") as HTMLDivElement++ act(() => latest.captureOlderPageAnchor())+ rendered.rerender(createElement(Harness, { items: initial, isFetchingOlder: true, onResult }))+ rendered.rerender(createElement(Harness, {+ items: [day("2026-09-17")],+ isFetchingOlder: false,+ onResult,+ }))++ expect(harness.scrollToIndex).not.toHaveBeenCalled()+ expect(latest.isOlderPageAnchorSettling).toBe(false)+ rendered.unmount()+ })++ it("cancels pending reconciliation on effect replacement and unmount", () => {+ const onResult = (result: AnchorResult) => { latest = result }+ const initial = [message("anchor")]+ const prepended = [message("older"), message("anchor")]+ harness.absoluteTops.set("anchor", 120)+ const rendered = render(createElement(Harness, {+ items: initial,+ isFetchingOlder: false,+ onResult,+ }))+ harness.scroller = screen.getByTestId("scroll") as HTMLDivElement++ act(() => latest.captureOlderPageAnchor())+ rendered.rerender(createElement(Harness, { items: initial, isFetchingOlder: true, onResult }))+ harness.absoluteTops.set("anchor", 520)+ rendered.rerender(createElement(Harness, { items: prepended, isFetchingOlder: false, onResult }))+ expect(frames).toHaveLength(1)++ rendered.rerender(createElement(Harness, {+ items: prepended.slice(),+ isFetchingOlder: false,+ onResult,+ }))+ expect(cancelFrame).toHaveBeenCalledWith(1)+ expect(frames).toHaveLength(2)++ rendered.unmount()+ expect(cancelFrame).toHaveBeenCalledWith(2)+ })+})diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.test.tsindex cfa3520bb..bfc55985f 100644--- a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts@@ -12,6 +12,8 @@ let refs: Array<{ current: unknown }> = []let refIndex = 0let layoutEffects: Array<() => void | (() => void)> = []let resizeCallbacks: ResizeObserverCallback[] = []+const OLDER_PAGE_ANCHOR_FRAME_REF_INDEX = 13+const OLDER_PAGE_UNMOUNT_EFFECT_INDEX = 2vi.mock("react", () => ({useRef: (initial: unknown) => {@@ -23,6 +25,7 @@ vi.mock("react", () => ({layoutEffects.push(effect)},useCallback: <T>(callback: T) => callback,+ useState: <T>(initial: T) => [initial, vi.fn()],}))const virtualizer = {@@ -229,6 +232,17 @@ beforeEach(resetHarness)afterEach(() => vi.unstubAllGlobals())describe("useScrollAnchor delayed row-growth re-pin", () => {+ it("cancels a pending older-page frame from the unmount fallback", async () => {+ await mountHook()+ const olderPageAnchorFrameRef = refs[OLDER_PAGE_ANCHOR_FRAME_REF_INDEX]+ olderPageAnchorFrameRef.current = 42+ const cleanup = layoutEffects[OLDER_PAGE_UNMOUNT_EFFECT_INDEX]()++ expect(cleanup).toBeTypeOf("function")+ cleanup!()+ expect(window.cancelAnimationFrame).toHaveBeenCalledWith(42)+ })+it("publishes settlement one frame after the final initial convergence action", async () => {const frameCallbacks: FrameRequestCallback[] = []const cancelFrame = vi.fn()diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 7c12f8934..aca0f946a 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -1,4 +1,4 @@-import { useCallback, useLayoutEffect, useRef } from "react"+import { useCallback, useLayoutEffect, useRef, useState } from "react"import { useVirtualizer, type ReactVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "./virtualizer-react-options"import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"@@ -10,12 +10,13 @@ import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/commu// findings #2/#10 (two disagreeing "near bottom" thresholds, a same-commit// double-write race, a silently-unhandled compound case).//-// This version delegates OLDER-PREPEND compensation entirely to-// `@tanstack/react-virtual`'s `anchorTo: "end"` (verified against the-// installed `[email protected]` source: its `setOptions` anchor-preserving-// branch fires on any edge-key/count change on a non-initial commit — exactly-// what `fetchOlder` prepending rows produces). `decideScrollAction` below-// therefore only covers the 2 behaviors the library does NOT provide:+// `@tanstack/react-virtual`'s `anchorTo: "end"` handles ordinary edge-key+// changes, but a same-day prepend retains the leading date-divider key. At the+// top edge the library then anchors that structural row instead of the first+// visible message. This hook captures the real message before `fetchOlder`+// and restores its id + viewport offset after the page lands.+// `decideScrollAction` below covers the other 2 behaviors the library does+// NOT provide:// mount-time positioning and self-send/peer-follow. Hero-swap compensation// is also NOT delegated to the library (`scrollMargin` shifts the// measurement coordinate system only — verified it never triggers a@@ -102,6 +103,11 @@ export interface ScrollAnchorMessage {authorId?: string}+interface PaginationAnchor {+ messageId: string+ viewportOffset: number+}+export interface ScrollAnchorState {didInitialScroll: boolean// Instant channel switch: the mount scroll now has two phases. Phase 1@@ -370,11 +376,9 @@ export function extractScrollAnchorMessages(items: FlatItem[]): ScrollAnchorMess/*** Owns the message-list scroll container ref, the `useVirtualizer` instance,- * and every automatic scroll-anchor decision (mount / self-send /- * peer-follow / hero-swap) plus the "↓ N below" pill's `belowCount`. Older-- * message prepend compensation is NOT decided here — it's delegated to the- * virtualizer's own `anchorTo: "end"` config (see this file's module doc- * comment for the source-verified rationale).+ * and every automatic scroll-anchor decision (mount / older prepend /+ * self-send / peer-follow / hero-swap) plus the "↓ N below" pill's+ * `belowCount`.** `jumpTo` (scrolling to an arbitrary earlier message on reply-pill click)* DOES live here now, unlike the pre-virtualization hook — it needs direct@@ -391,6 +395,7 @@ export function useScrollAnchor({newDividerBefore,initialScrollReady,hasMoreNewer,+ isFetchingOlder,presentVersion,viewerUserId,heroHeight,@@ -401,6 +406,7 @@ export function useScrollAnchor({newDividerBefore?: stringinitialScrollReady: booleanhasMoreNewer?: boolean+ isFetchingOlder?: booleanpresentVersion?: numberviewerUserId?: string// Current measured height (px) of the non-virtualized hero block that@@ -423,6 +429,8 @@ export function useScrollAnchor({scrollToBottom: () => voidjumpTo: (messageId: string, behavior?: ScrollBehavior) => voidonImageLoad: () => void+ captureOlderPageAnchor: () => void+ isOlderPageAnchorSettling: boolean} {const scrollRef = useRef<HTMLDivElement>(null)const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())@@ -437,6 +445,10 @@ export function useScrollAnchor({const acceptedScrollTopRef = useRef(0)const measuredRowHeightsRef = useRef(new WeakMap<Element, number>())const bottomRepinQueuedRef = useRef(false)+ const olderPageAnchorRef = useRef<PaginationAnchor | null>(null)+ const olderPageFetchObservedRef = useRef(false)+ const olderPageAnchorFrameRef = useRef<number | null>(null)+ const [isOlderPageAnchorSettling, setIsOlderPageAnchorSettling] = useState(false)const liveResizeAnchor = wasExactlyPinnedRef.current && !userScrolledAwayRef.current? "end": "start"@@ -549,6 +561,87 @@ export function useScrollAnchor({// prepend anchoring before this assignment restores the live resize mode.virtualizer.options.anchorTo = liveResizeAnchor+ const captureOlderPageAnchor = useCallback(() => {+ const root = scrollRef.current+ if (!root) return+ const rootRect = root.getBoundingClientRect()+ const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((candidate) => {+ const rect = candidate.getBoundingClientRect()+ return rect.bottom > rootRect.top + 1 && rect.top < rootRect.bottom - 1+ })+ const messageId = row?.dataset.msgId+ if (!row || !messageId) return+ if (olderPageAnchorFrameRef.current !== null) {+ window.cancelAnimationFrame(olderPageAnchorFrameRef.current)+ olderPageAnchorFrameRef.current = null+ }+ olderPageAnchorRef.current = {+ messageId,+ viewportOffset: row.getBoundingClientRect().top - rootRect.top,+ }+ olderPageFetchObservedRef.current = false+ setIsOlderPageAnchorSettling(true)+ }, [])++ useLayoutEffect(() => {+ const anchor = olderPageAnchorRef.current+ if (!anchor) return+ if (isFetchingOlder) {+ olderPageFetchObservedRef.current = true+ return+ }+ if (!olderPageFetchObservedRef.current) return++ const root = scrollRef.current+ const index = findMessageIndex(items, anchor.messageId)+ if (!root || index === null) {+ olderPageAnchorRef.current = null+ setIsOlderPageAnchorSettling(false)+ return+ }++ virtualizer.scrollToIndex(index, { align: "start" })+ let attempts = 0+ let stableFrames = 0+ const restore = () => {+ olderPageAnchorFrameRef.current = null+ if (olderPageAnchorRef.current !== anchor) return+ const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((candidate) => candidate.dataset.msgId === anchor.messageId)+ if (row) {+ const offset = row.getBoundingClientRect().top - root.getBoundingClientRect().top+ const delta = offset - anchor.viewportOffset+ if (Math.abs(delta) > 0.5) {+ root.scrollTop += delta+ stableFrames = 0+ } else {+ stableFrames += 1+ }+ }+ attempts += 1+ if (stableFrames >= 2 || attempts >= 12) {+ olderPageAnchorRef.current = null+ setIsOlderPageAnchorSettling(false)+ return+ }+ olderPageAnchorFrameRef.current = window.requestAnimationFrame(restore)+ }+ olderPageAnchorFrameRef.current = window.requestAnimationFrame(restore)+ return () => {+ if (olderPageAnchorFrameRef.current !== null) {+ window.cancelAnimationFrame(olderPageAnchorFrameRef.current)+ olderPageAnchorFrameRef.current = null+ }+ }+ }, [isFetchingOlder, items, virtualizer])++ useLayoutEffect(() => () => {+ if (olderPageAnchorFrameRef.current !== null) {+ window.cancelAnimationFrame(olderPageAnchorFrameRef.current)+ }+ }, [])+// Whether the viewer was within NEAR_BOTTOM_PX of the end BEFORE this// commit's append — the semantics `decideScrollAction` documents for its// `isAtEnd` input. It must be sampled from the user's real scroll position,@@ -797,5 +890,14 @@ export function useScrollAnchor({virtualizer.scrollToIndex(idx, { align: "center", behavior })}, [items, virtualizer])- return { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo, onImageLoad }+ return {+ scrollRef,+ virtualizer,+ belowCount,+ scrollToBottom,+ jumpTo,+ onImageLoad,+ captureOlderPageAnchor,+ isOlderPageAnchorSettling,+ }}diff --git a/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.ts b/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.tsindex 5a3105d3b..61f32cdce 100644--- a/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.ts+++ b/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.ts@@ -1,12 +1,14 @@import { createElement, useLayoutEffect, useRef } from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { act, render } from "@/test/react-dom-harness"+import { act, fireEvent, render } from "@/test/react-dom-harness"import { useVirtualCursorSentinel } from "./use-virtual-cursor-sentinel"type Props = {edge: "start" | "end"hasMore: booleanisFetching: boolean+ isSettling?: boolean+ onBeforeLoad?: () => voidonLoad: () => void}@@ -63,7 +65,10 @@ describe.each(["start", "end"] as const)("useVirtualCursorSentinel (%s edge)", (vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver)})- afterEach(() => vi.unstubAllGlobals())+ afterEach(() => {+ vi.useRealTimers()+ vi.unstubAllGlobals()+ })it("loads on a true intersection and ignores false entries", () => {const onLoad = vi.fn()@@ -75,17 +80,196 @@ describe.each(["start", "end"] as const)("useVirtualCursorSentinel (%s edge)", (expect(onLoad).toHaveBeenCalledOnce()})- it("replays one busy demand once after settle without cascading", () => {+ it("drops input while busy and requires fresh same-direction input after settle", () => {+ vi.useFakeTimers()const onLoad = vi.fn()- const view = renderView({ edge, hasMore: true, isFetching: true, onLoad })+ const view = renderView({ edge, hasMore: true, isFetching: false, onLoad })intersect(true)- intersect(true)- expect(onLoad).not.toHaveBeenCalled()+ expect(onLoad).toHaveBeenCalledOnce()- view.rerender({ edge, hasMore: true, isFetching: false, onLoad })+ view.rerender({ edge, hasMore: true, isFetching: true, onLoad })+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })expect(onLoad).toHaveBeenCalledOnce()view.rerender({ edge, hasMore: true, isFetching: false, onLoad })expect(onLoad).toHaveBeenCalledOnce()++ act(() => vi.advanceTimersByTime(181))+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })+ expect(onLoad).toHaveBeenCalledTimes(2)+ })++ it("waits for anchor settlement before accepting the next demand", () => {+ vi.useFakeTimers()+ const onLoad = vi.fn()+ const view = renderView({ edge, hasMore: true, isFetching: false, onLoad })+ intersect(true)+ expect(onLoad).toHaveBeenCalledOnce()++ view.rerender({ edge, hasMore: true, isFetching: true, onLoad })+ view.rerender({ edge, hasMore: true, isFetching: false, onLoad, isSettling: true })+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })+ expect(onLoad).toHaveBeenCalledOnce()++ view.rerender({ edge, hasMore: true, isFetching: false, onLoad, isSettling: false })+ act(() => vi.advanceTimersByTime(181))+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })+ expect(onLoad).toHaveBeenCalledTimes(2)+ })++ it("does not accept a second page before the active touch gesture ends", () => {+ const onLoad = vi.fn()+ const base = { edge, hasMore: true, isFetching: false, isSettling: false, onLoad }+ const view = renderView(base)+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!++ fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })+ intersect(true)+ expect(onLoad).toHaveBeenCalledOnce()++ view.rerender({ ...base, isFetching: true, isSettling: true })+ fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })+ view.rerender(base)++ // This is still the same physical gesture: no touchend/new touchstart occurred.+ fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 160 : 40 }] })+ expect(onLoad).toHaveBeenCalledOnce()++ fireEvent.touchEnd(scroll, { touches: [] })+ fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })+ fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })+ expect(onLoad).toHaveBeenCalledTimes(2)+ })++ it("treats trackpad momentum as one wheel gesture until input goes idle", () => {+ vi.useFakeTimers()+ const onLoad = vi.fn()+ const base = { edge, hasMore: true, isFetching: false, onLoad }+ const view = renderView(base)+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ intersect(true)++ view.rerender({ ...base, isFetching: true })+ view.rerender(base)+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })+ expect(onLoad).toHaveBeenCalledTimes(2)++ view.rerender({ ...base, isFetching: true })+ view.rerender(base)+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -10 : 10 })+ expect(onLoad).toHaveBeenCalledTimes(2)++ act(() => vi.advanceTimersByTime(181))+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })+ expect(onLoad).toHaveBeenCalledTimes(3)+ })++ it("treats keyboard repeat as one key gesture until keyup", () => {+ const onLoad = vi.fn()+ const base = { edge, hasMore: true, isFetching: false, onLoad }+ const view = renderView(base)+ const key = edge === "start" ? "PageUp" : "PageDown"+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ intersect(true)++ view.rerender({ ...base, isFetching: true })+ view.rerender(base)+ fireEvent.keyDown(scroll, { key })+ expect(onLoad).toHaveBeenCalledTimes(2)++ view.rerender({ ...base, isFetching: true })+ view.rerender(base)+ fireEvent.keyDown(scroll, { key, repeat: true })+ expect(onLoad).toHaveBeenCalledTimes(2)++ fireEvent.keyUp(scroll, { key })+ fireEvent.keyDown(scroll, { key })+ expect(onLoad).toHaveBeenCalledTimes(3)+ })++ it("ignores navigation keys while focus is outside the scroller", () => {+ const onLoad = vi.fn()+ const base = { edge, hasMore: true, isFetching: false, onLoad }+ const view = renderView(base)+ const key = edge === "start" ? "PageUp" : "PageDown"+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ const outside = document.createElement("button")+ document.body.append(outside)+ intersect(true)+ view.rerender({ ...base, isFetching: true })+ view.rerender(base)++ outside.focus()+ fireEvent.keyDown(outside, { key })+ expect(onLoad).toHaveBeenCalledOnce()++ scroll.tabIndex = -1+ scroll.focus()+ fireEvent.keyDown(scroll, { key })+ expect(onLoad).toHaveBeenCalledTimes(2)+ outside.remove()+ })++ it("clears held key, touch, wheel, and timer state on window blur", () => {+ vi.useFakeTimers()+ const onLoad = vi.fn()+ const base = { edge, hasMore: true, isFetching: false, onLoad }+ const view = renderView(base)+ const key = edge === "start" ? "PageUp" : "PageDown"+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ intersect(true)+ view.rerender({ ...base, isFetching: true })+ view.rerender(base)++ fireEvent.wheel(scroll, { deltaY: edge === "start" ? 20 : -20 })+ fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })+ fireEvent.keyDown(scroll, { key })+ expect(onLoad).toHaveBeenCalledTimes(2)+ expect(vi.getTimerCount()).toBe(1)+ view.rerender({ ...base, isFetching: true })+ view.rerender(base)++ act(() => window.dispatchEvent(new Event("blur")))+ expect(vi.getTimerCount()).toBe(0)++ // No keyup is needed after blur: the next press is a fresh gesture.+ fireEvent.keyDown(scroll, { key })+ expect(onLoad).toHaveBeenCalledTimes(3)+ view.rerender({ ...base, isFetching: true })+ view.rerender(base)++ // The pre-blur touch no longer has a live coordinate, while wheel is fresh.+ fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })+ expect(onLoad).toHaveBeenCalledTimes(3)+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })+ expect(onLoad).toHaveBeenCalledTimes(4)+ })++ it("accepts only fresh input toward the active edge", () => {+ const calls: string[] = []+ const onBeforeLoad = () => calls.push("before")+ const onLoad = () => calls.push("load")+ const base = { edge, hasMore: true, isFetching: false, onBeforeLoad, onLoad }+ const view = renderView(base)+ intersect(true)+ expect(calls).toEqual(["before", "load"])++ view.rerender({ ...base, isFetching: true })+ view.rerender(base)+ const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!+ fireEvent.wheel(scroll, { deltaY: edge === "start" ? 20 : -20 })+ fireEvent.keyDown(scroll, { key: edge === "start" ? "ArrowDown" : "ArrowUp" })+ expect(calls).toHaveLength(2)++ fireEvent.keyDown(scroll, { key: edge === "start" ? "PageUp" : "PageDown" })+ expect(calls).toEqual(["before", "load", "before", "load"])++ view.rerender({ ...base, isFetching: true })+ view.rerender(base)+ fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })+ fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })+ expect(calls).toEqual(["before", "load", "before", "load", "before", "load"])})it("clears pending demand when hasMore becomes false and disconnects on unmount", () => {diff --git a/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts b/src/web/src/hooks/community/use-virtual-cursor-sentinel.tsindex 041b3516f..0fa8c9330 100644--- a/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts+++ b/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts@@ -2,73 +2,187 @@import { useEffect, useRef, type RefObject } from "react"+// Wheel events have no lifecycle boundary. A short quiet window separates one+// trackpad/mouse-wheel burst (including momentum) from the next user gesture.+const WHEEL_GESTURE_IDLE_MS = 180+export function useVirtualCursorSentinel({scrollRef,hasMore,isFetching,+ isSettling,+ onBeforeLoad,onLoad,edge,}: {scrollRef: RefObject<HTMLElement | null>hasMore?: booleanisFetching?: boolean+ isSettling?: boolean+ onBeforeLoad?: () => voidonLoad?: () => voidedge: "start" | "end"}) {const sentinelRef = useRef<HTMLDivElement>(null)- const stateRef = useRef({ onLoad, hasMore, isFetching })+ const stateRef = useRef({ onBeforeLoad, onLoad, hasMore, isFetching, isSettling })const intersectingRef = useRef(false)- const pendingDemandRef = useRef(false)- const wasFetchingRef = useRef(isFetching)+ const intersectionDemandedRef = useRef(false)+ const loadLockedRef = useRef(false)+ const fetchObservedRef = useRef(false)- useEffect(() => { stateRef.current = { onLoad, hasMore, isFetching } })useEffect(() => {- const wasFetching = wasFetchingRef.current- wasFetchingRef.current = isFetching+ stateRef.current = { onBeforeLoad, onLoad, hasMore, isFetching, isSettling }if (!hasMore) {- pendingDemandRef.current = false- intersectingRef.current = false+ loadLockedRef.current = false+ fetchObservedRef.current = false+ intersectionDemandedRef.current = falsereturn}- if (wasFetching && !isFetching && pendingDemandRef.current && intersectingRef.current && onLoad) {- pendingDemandRef.current = false- onLoad()+ if (isFetching) fetchObservedRef.current = true+ if (+ loadLockedRef.current+ && fetchObservedRef.current+ && !isFetching+ && !isSettling+ ) {+ loadLockedRef.current = false+ fetchObservedRef.current = false}- }, [hasMore, isFetching, onLoad])+ })useEffect(() => {const element = sentinelRef.currentconst root = scrollRef.currentif (!element || !root) return- const observer = new IntersectionObserver((entries) => {++ let touchY: number | null = null+ let touchDemanded = false+ let wheelGestureActive = false+ let wheelDemanded = false+ let wheelIdleTimer: ReturnType<typeof setTimeout> | undefined+ const heldKeys = new Set<string>()++ const finishWheelGesture = () => {+ wheelGestureActive = false+ wheelDemanded = false+ wheelIdleTimer = undefined+ }+ const consumeActiveGestures = () => {+ if (touchY !== null) touchDemanded = true+ if (wheelGestureActive) wheelDemanded = true+ }+ const nearEdge = () => edge === "start"+ ? root.scrollTop <= 200+ : root.scrollHeight - root.clientHeight - root.scrollTop <= 200+ const requestPage = (requireNearEdge: boolean) => {const state = stateRef.current+ if (+ loadLockedRef.current+ || !intersectingRef.current+ || (requireNearEdge && !nearEdge())+ || !state.onLoad+ || !state.hasMore+ || state.isFetching+ || state.isSettling+ ) return+ loadLockedRef.current = true+ fetchObservedRef.current = false+ consumeActiveGestures()+ state.onBeforeLoad?.()+ state.onLoad()+ }+ const observer = new IntersectionObserver((entries) => {for (const entry of entries) {intersectingRef.current = entry.isIntersecting- if (!entry.isIntersecting || !state.onLoad || !state.hasMore) continue- if (state.isFetching) pendingDemandRef.current = true- else state.onLoad()+ if (!entry.isIntersecting) {+ intersectionDemandedRef.current = false+ continue+ }+ if (!intersectionDemandedRef.current) {+ intersectionDemandedRef.current = true+ requestPage(false)+ }break}}, { root, rootMargin: "200px" })- let lastScrollTop = root.scrollTop- const onScroll = () => {- const next = root.scrollTop- const movingTowardEdge = edge === "start" ? next < lastScrollTop : next > lastScrollTop- lastScrollTop = next- const nearEdge = edge === "start"- ? next <= 200- : root.scrollHeight - root.clientHeight - next <= 200- const state = stateRef.current- if (movingTowardEdge && nearEdge && intersectingRef.current && state.hasMore && state.isFetching) {- pendingDemandRef.current = true+ const onWheel = (event: WheelEvent) => {+ if (!wheelGestureActive) {+ wheelGestureActive = true+ wheelDemanded = false+ }+ if (wheelIdleTimer !== undefined) clearTimeout(wheelIdleTimer)+ wheelIdleTimer = setTimeout(finishWheelGesture, WHEEL_GESTURE_IDLE_MS)+ const towardEdge = (edge === "start" && event.deltaY < 0)+ || (edge === "end" && event.deltaY > 0)+ if (towardEdge && !wheelDemanded) {+ wheelDemanded = true+ requestPage(true)}}+ const onKeyDown = (event: KeyboardEvent) => {+ const active = root.ownerDocument.activeElement+ if (+ active+ && active !== root.ownerDocument.body+ && active !== root+ && !root.contains(active)+ ) return+ const towardStart = ["ArrowUp", "PageUp", "Home"].includes(event.key)+ const towardEnd = ["ArrowDown", "PageDown", "End"].includes(event.key)+ const towardEdge = (edge === "start" && towardStart) || (edge === "end" && towardEnd)+ if (!towardEdge || event.repeat || heldKeys.has(event.key)) return+ heldKeys.add(event.key)+ requestPage(true)+ }+ const onKeyUp = (event: KeyboardEvent) => { heldKeys.delete(event.key) }+ const onTouchStart = (event: TouchEvent) => {+ if (touchY === null) touchDemanded = false+ touchY = event.touches[0]?.clientY ?? null+ }+ const onTouchMove = (event: TouchEvent) => {+ const nextY = event.touches[0]?.clientY ?? null+ if (touchY === null || nextY === null) return+ const delta = nextY - touchY+ touchY = nextY+ const towardEdge = (edge === "start" && delta > 0) || (edge === "end" && delta < 0)+ if (towardEdge && !touchDemanded) {+ touchDemanded = true+ requestPage(true)+ }+ }+ const onTouchEnd = (event: TouchEvent) => {+ touchY = event.touches[0]?.clientY ?? null+ if (touchY === null) touchDemanded = false+ }+ const onWindowBlur = () => {+ heldKeys.clear()+ touchY = null+ touchDemanded = false+ if (wheelIdleTimer !== undefined) clearTimeout(wheelIdleTimer)+ finishWheelGesture()+ }+observer.observe(element)- root.addEventListener("scroll", onScroll, { passive: true })+ root.addEventListener("wheel", onWheel, { passive: true })+ root.ownerDocument.addEventListener("keydown", onKeyDown)+ root.ownerDocument.addEventListener("keyup", onKeyUp)+ root.ownerDocument.defaultView?.addEventListener("blur", onWindowBlur)+ root.addEventListener("touchstart", onTouchStart, { passive: true })+ root.addEventListener("touchmove", onTouchMove, { passive: true })+ root.addEventListener("touchend", onTouchEnd, { passive: true })+ root.addEventListener("touchcancel", onTouchEnd, { passive: true })return () => {- pendingDemandRef.current = falseintersectingRef.current = false- root.removeEventListener("scroll", onScroll)+ intersectionDemandedRef.current = false+ if (wheelIdleTimer !== undefined) clearTimeout(wheelIdleTimer)+ root.removeEventListener("wheel", onWheel)+ root.ownerDocument.removeEventListener("keydown", onKeyDown)+ root.ownerDocument.removeEventListener("keyup", onKeyUp)+ root.ownerDocument.defaultView?.removeEventListener("blur", onWindowBlur)+ root.removeEventListener("touchstart", onTouchStart)+ root.removeEventListener("touchmove", onTouchMove)+ root.removeEventListener("touchend", onTouchEnd)+ root.removeEventListener("touchcancel", onTouchEnd)observer.disconnect()}}, [edge, hasMore, scrollRef])diff --git a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.tsnew file mode 100644index 000000000..6f3744a68--- /dev/null+++ b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts@@ -0,0 +1,186 @@+import type { Page, Route } from "@playwright/test"+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"+import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"++const VIEWPORT = { width: 1280, height: 800 }++type Geometry = {+ scrollTop: number+ scrollHeight: number+ firstVisibleId: string | null+ firstVisibleOffset: number | null+}++async function readGeometry(page: Page): Promise<Geometry> {+ return page.getByTestId(tid.messageScroller).evaluate((element) => {+ const root = element as HTMLElement+ const rootRect = root.getBoundingClientRect()+ const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((candidate) => {+ const rect = candidate.getBoundingClientRect()+ return rect.bottom > rootRect.top + 1 && rect.top < rootRect.bottom - 1+ }) ?? null+ const rect = row?.getBoundingClientRect() ?? null+ return {+ scrollTop: root.scrollTop,+ scrollHeight: root.scrollHeight,+ firstVisibleId: row?.dataset.msgId ?? null,+ firstVisibleOffset: rect ? rect.top - rootRect.top : null,+ }+ })+}++async function waitForStableGeometry(page: Page): Promise<Geometry> {+ let previous = ""+ let stable: Geometry | null = null+ await expect.poll(async () => {+ await page.getByTestId(tid.messageScroller).evaluate(() => new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))+ }))+ const next = await readGeometry(page)+ const signature = JSON.stringify(next)+ if (signature === previous) stable = next+ previous = signature+ return stable !== null+ }, { timeout: 20_000 }).toBe(true)+ return stable!+}++async function readMessageOffset(page: Page, messageId: string): Promise<number | null> {+ return page.getByTestId(tid.messageScroller).evaluate((element, id) => {+ const root = element as HTMLElement+ const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((candidate) => candidate.dataset.msgId === id)+ return row ? row.getBoundingClientRect().top - root.getBoundingClientRect().top : null+ }, messageId)+}++async function setReadCheckpoint(channelId: string, messageId: string): Promise<void> {+ const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {+ method: "PUT",+ headers: {+ Cookie: sessionCookie("alice"),+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({ lastReadMessageId: messageId }),+ })+ expect(response.ok).toBe(true)+}++async function holdNextPage(page: Page, channelId: string, param: "cursor" | "since") {+ let release!: () => void+ let resolveMatched!: () => void+ let consumed = false+ const gate = new Promise<void>((resolve) => { release = resolve })+ const matched = new Promise<void>((resolve) => { resolveMatched = resolve })+ const pattern = `**/api/community/channels/${channelId}/messages**`+ const handler = async (route: Route) => {+ const url = new URL(route.request().url())+ if (!consumed && url.searchParams.has(param)) {+ consumed = true+ resolveMatched()+ await gate+ }+ await route.continue()+ }+ await page.route(pattern, handler)+ return {+ matched,+ release,+ dispose: async () => {+ release()+ await page.unroute(pattern, handler)+ },+ }+}++async function moveToEdge(page: Page, edge: "start" | "end"): Promise<void> {+ await page.getByTestId(tid.messageScroller).evaluate((element, target) => {+ element.scrollTop = target === "start" ? 0 : element.scrollHeight+ element.dispatchEvent(new Event("scroll"))+ }, edge)+}++function expectAnchorPreserved(before: Geometry, retainedOffset: number | null, label: string): void {+ expect(retainedOffset, `${label}: retained message`).not.toBeNull()+ expect(+ Math.abs((retainedOffset ?? 0) - (before.firstVisibleOffset ?? 0)),+ `${label}: viewport offset`,+ ).toBeLessThanOrEqual(1)+}++test("older and newer pages preserve a real-message anchor and do not replay", async ({ asUser }, testInfo) => {+ test.setTimeout(240_000)+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Pagination anchor ${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const channelId = await seedChannel("alice", serverId, `pagination-anchor-${stamp}`)+ const ids: string[] = []+ for (let index = 0; index < 130; index += 1) {+ const variable = index % 5 === 0+ ? Array.from({ length: 10 }, (_, line) => `row ${index} variable ${line} ${"x".repeat(line * 3)}`).join("\n")+ : `row ${index}`+ ids.push(await seedMessage(index <= 64 ? "alice" : "bob", channelId, variable))+ }+ await setReadCheckpoint(channelId, ids[64])++ const olderUser = await asUser("alice")+ await olderUser.page.setViewportSize(VIEWPORT)+ const olderRequests: string[] = []+ olderUser.page.on("request", (request) => {+ const url = new URL(request.url())+ if (url.pathname.endsWith(`/channels/${channelId}/messages`) && url.searchParams.has("cursor")) {+ olderRequests.push(url.search)+ }+ })+ await olderUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })+ await expect(olderUser.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })+ const olderPage = await holdNextPage(olderUser.page, channelId, "cursor")+ await moveToEdge(olderUser.page, "start")+ await olderPage.matched+ const olderBefore = await waitForStableGeometry(olderUser.page)+ olderPage.release()+ await expect(olderUser.page.getByText("Loading older messages…", { exact: true })).toHaveCount(0)+ const olderAfter = await waitForStableGeometry(olderUser.page)+ const olderRetainedOffset = await readMessageOffset(olderUser.page, olderBefore.firstVisibleId!)+ await olderPage.dispose()++ await setReadCheckpoint(channelId, ids[64])+ const newerUser = await asUser("alice")+ await newerUser.page.setViewportSize(VIEWPORT)+ const newerRequests: string[] = []+ newerUser.page.on("request", (request) => {+ const url = new URL(request.url())+ if (url.pathname.endsWith(`/channels/${channelId}/messages`) && url.searchParams.has("since")) {+ newerRequests.push(url.search)+ }+ })+ await newerUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })+ await expect(newerUser.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })+ const newerPage = await holdNextPage(newerUser.page, channelId, "since")+ await moveToEdge(newerUser.page, "end")+ await newerPage.matched+ const newerBefore = await waitForStableGeometry(newerUser.page)+ newerPage.release()+ await expect(newerUser.page.getByText("Loading newer messages…", { exact: true })).toHaveCount(0)+ const newerAfter = await waitForStableGeometry(newerUser.page)+ const newerRetainedOffset = await readMessageOffset(newerUser.page, newerBefore.firstVisibleId!)+ await newerPage.dispose()++ await testInfo.attach("pagination-anchor-trajectory.json", {+ body: JSON.stringify({+ sourceSha: "b1ea24a7f73778717662b5d894f1e14b019c8c08",+ older: { before: olderBefore, after: olderAfter, retainedOffset: olderRetainedOffset, requests: olderRequests },+ newer: { before: newerBefore, after: newerAfter, retainedOffset: newerRetainedOffset, requests: newerRequests },+ }, null, 2),+ contentType: "application/json",+ })++ expect(olderRequests).toHaveLength(1)+ expect(newerRequests).toHaveLength(1)+ expectAnchorPreserved(olderBefore, olderRetainedOffset, "older prepend")+ expectAnchorPreserved(newerBefore, newerRetainedOffset, "newer append")+})