Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): stop upward message scroll jitter

Gener45ba78189686
diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.ts
index 129184024..b968b0165 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -7,10 +7,12 @@ import {
findMountScrollTargetIndex,
extractScrollAnchorMessages,
NEAR_BOTTOM_PX,
+ shouldAdjustMessageScrollPosition,
type ScrollAnchorState,
type ScrollAnchorMessage,
} from "./use-scroll-anchor"
import type { FlatItem } from "@/components/community/message-list-items"
+import type { VirtualItem } from "@tanstack/react-virtual"
const msgs = (...ids: string[]): ScrollAnchorMessage[] => ids.map((id) => ({ id }))
@@ -218,6 +220,54 @@ describe("NEAR_BOTTOM_PX", () => {
})
})
+describe("shouldAdjustMessageScrollPosition", () => {
+ const item: VirtualItem = {
+ key: "message:12",
+ index: 12,
+ start: 800,
+ end: 900,
+ size: 100,
+ lane: 0,
+ }
+
+ function instance(overrides: Partial<Parameters<typeof shouldAdjustMessageScrollPosition>[2]> = {}) {
+ return {
+ itemSizeCache: new Map(),
+ scrollAdjustments: 0,
+ scrollDirection: null,
+ scrollOffset: 1_000,
+ ...overrides,
+ }
+ }
+
+ it("does not compensate a first measurement while the user scrolls upward", () => {
+ expect(shouldAdjustMessageScrollPosition(item, 96, instance({ scrollDirection: "backward" }))).toBe(false)
+ })
+
+ it("keeps first-measurement compensation above the fold while idle or scrolling forward", () => {
+ expect(shouldAdjustMessageScrollPosition(item, 96, instance())).toBe(true)
+ expect(shouldAdjustMessageScrollPosition(item, 96, instance({ scrollDirection: "forward" }))).toBe(true)
+ })
+
+ it("keeps remeasurement compensation only for rows entirely above the fold", () => {
+ const measured = new Map([[item.key, item.size]])
+ expect(shouldAdjustMessageScrollPosition(item, 20, instance({ itemSizeCache: measured }))).toBe(true)
+ expect(shouldAdjustMessageScrollPosition(
+ { ...item, end: 1_040 },
+ 20,
+ instance({ itemSizeCache: measured }),
+ )).toBe(false)
+ })
+
+ it("includes pending virtualizer adjustments in the effective fold offset", () => {
+ expect(shouldAdjustMessageScrollPosition(
+ { ...item, start: 1_020, end: 1_120 },
+ 20,
+ instance({ scrollAdjustments: 40 }),
+ )).toBe(true)
+ })
+})
+
describe("computeHeroScrollCompensation", () => {
it("returns 0 when the hero's height is unchanged", () => {
expect(computeHeroScrollCompensation(80, 80)).toBe(0)
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index d56610b8c..752aaebf0 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -1,5 +1,5 @@
import { useCallback, useLayoutEffect, useRef } from "react"
-import { useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
+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 "@/components/community/message-list-items"
@@ -40,6 +40,37 @@ import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/component
// `resizeItem` above-viewport compensation (defaults to 1px otherwise).
export const NEAR_BOTTOM_PX = 100
+type SizeAdjustmentVirtualizer = Pick<
+ ReactVirtualizer<HTMLDivElement, Element>,
+ "itemSizeCache" | "scrollAdjustments" | "scrollDirection" | "scrollOffset"
+>
+
+/**
+ * Keep TanStack Virtual's normal estimate-to-measurement anchoring except
+ * while the user is actively scrolling upward. Its default first-measure
+ * branch compensates every row whose estimated top is above the fold,
+ * including rows that have just entered the overscan window during a
+ * backward scroll. With variable-height messages that correction pushes
+ * scrollTop downward by the estimate delta and repeatedly cancels wheel
+ * input — visible as the NEW-divider view shuddering and refusing to move.
+ *
+ * Re-measurements retain the library's narrower "entirely above the fold"
+ * rule, and forward/idle first measurements retain the original rule, so
+ * image growth, prepend anchoring, and normal downward navigation keep their
+ * existing compensation behavior.
+ */
+export function shouldAdjustMessageScrollPosition(
+ item: VirtualItem,
+ _delta: number,
+ instance: SizeAdjustmentVirtualizer,
+): boolean {
+ if (instance.scrollDirection === "backward") return false
+
+ const offset = (instance.scrollOffset ?? 0) + instance.scrollAdjustments
+ const isFirstMeasure = !instance.itemSizeCache.has(item.key)
+ return isFirstMeasure ? item.start < offset : item.end <= offset
+}
+
export interface ScrollAnchorMessage {
id: string
authorId?: string
@@ -384,6 +415,10 @@ export function useScrollAnchor({
scrollMargin: heroHeight,
overscan: 8,
})
+ // virtual-core exposes this predicate on the instance (and `resizeItem`
+ // reads it there), not through VirtualizerOptions. Assign during render so
+ // it is already installed when React attaches row refs in the commit.
+ virtualizer.shouldAdjustScrollPositionOnItemSizeChange = shouldAdjustMessageScrollPosition
// Whether the viewer was within NEAR_BOTTOM_PX of the end BEFORE this
// commit's append — the semantics `decideScrollAction` documents for its
diff --git a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
new file mode 100644
index 000000000..3e1426f93
--- /dev/null
+++ b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
@@ -0,0 +1,90 @@
+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"
+import { tid } from "./_fixtures/testids"
+import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"
+import { WEB_URL } from "./_setup/paths"
+
+test("NEW divider does not fight upward scrolling while a peer message arrives", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `NEW scroll ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "new-scroll")
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "carol", serverId)
+
+ let readThroughId = ""
+ for (let index = 0; index < 24; index++) {
+ readThroughId = await seedMessage(
+ "alice",
+ channelId,
+ `read history ${index}\n${Array.from({ length: 10 + (index % 8) }, (_, line) => `line ${line} variable width ${"x".repeat((line % 4) * 18)}`).join("\n")}`,
+ )
+ }
+
+ const readResponse = 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: readThroughId }),
+ })
+ expect(readResponse.status).toBe(200)
+
+ for (let index = 0; index < 48; index++) {
+ await seedMessage(
+ index % 2 === 0 ? "bob" : "carol",
+ channelId,
+ `unread history ${index}\n${Array.from({ length: 8 + (index % 10) }, (_, line) => `line ${line} variable height ${"y".repeat((line % 5) * 15)}`).join("\n")}`,
+ )
+ }
+
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000, waitUntil: "commit" })
+ const divider = page.getByTestId(tid.newDivider)
+ await expect(divider).toBeVisible({ timeout: 30_000 })
+
+ await divider.evaluate((element) => {
+ const scroller = element.closest<HTMLElement>(".overflow-y-auto")
+ if (!scroller) throw new Error("message scroller not found")
+ scroller.dataset.e2eMessageScroller = "true"
+ })
+ const scroller = page.locator("[data-e2e-message-scroller='true']")
+ await expect(scroller).toHaveCount(1)
+ const box = await scroller.boundingBox()
+ expect(box).not.toBeNull()
+ await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)
+
+ await scroller.evaluate((element) => {
+ const samples: number[] = [element.scrollTop]
+ Object.defineProperty(window, "__newDividerScrollEvents", {
+ configurable: true,
+ value: samples,
+ })
+ element.addEventListener("scroll", () => samples.push(element.scrollTop), { passive: true })
+ })
+
+ const samples: number[] = [await scroller.evaluate((element) => element.scrollTop)]
+ const liveAppend = (async () => {
+ await page.waitForTimeout(250)
+ return seedMessage("bob", channelId, `live during upward scroll ${Date.now()}`)
+ })()
+ for (let index = 0; index < 60; index++) {
+ await page.mouse.wheel(0, -24)
+ await page.waitForTimeout(24)
+ samples.push(await scroller.evaluate((element) => element.scrollTop))
+ }
+ await liveAppend
+ await page.waitForTimeout(250)
+ samples.push(await scroller.evaluate((element) => element.scrollTop))
+ const scrollEvents = await page.evaluate(() => (
+ window as unknown as { __newDividerScrollEvents: number[] }
+ ).__newDividerScrollEvents)
+
+ const start = samples[0]!
+ const end = samples.at(-1)!
+ expect(end).toBeLessThan(start - 600)
+ for (let index = 1; index < scrollEvents.length; index++) {
+ expect(scrollEvents[index]!).toBeLessThanOrEqual(scrollEvents[index - 1]! + 4)
+ }
+})