From 6e9184dc9baccb99988293e71cdc9ffa2e2161d8 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 00:04:50 -0700 Subject: [PATCH 1/9] Re-attach the timeline when a collapse clamps a detached reader to the end #5951 dropped shrink re-attach, so a reader who scrolled up a few pixels to collapse a tool call landed at the very bottom but stayed detached, with the jump-to-bottom button showing. Attach once the clamp to the end persists into the next frame; a one-frame shrink still keeps the reader on their row. Co-Authored-By: Claude Opus 5.5 --- .../ui/scroll-position-keeper.test.ts | 25 ++++++++++++++++++- .../components/ui/scroll-position-keeper.ts | 6 ++++- docs/timeline-pagination.md | 7 +++--- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/apps/app/src/components/ui/scroll-position-keeper.test.ts b/apps/app/src/components/ui/scroll-position-keeper.test.ts index 61d60aae4d5..013e2934134 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -147,7 +147,10 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("row-3")).toBe(before); }); - it("never attaches when content shrinks under a detached reader and the browser clamps to the end", () => { + it("attaches when content shrinks under a detached reader and the clamp to the end persists", () => { + vi.useFakeTimers({ + toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], + }); const rows = rowsOf(10); const timeline = createTimeline(rows); timeline.userScrollTo(1200); @@ -155,8 +158,28 @@ describe("ScrollPositionKeeper", () => { timeline.setRows(rows.slice(0, 7)); timeline.keeper.reconcile(); timeline.scrollElement.dispatchEvent(new Event("scroll")); + expect(timeline.keeper.isAttached()).toBe(false); + vi.advanceTimersToNextFrame(); expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + + it("keeps a detached reader on their row when content shrinks onto the end for a single frame", () => { + vi.useFakeTimers({ + toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], + }); + const rows = rowsOf(10); + const timeline = createTimeline(rows); + timeline.userScrollTo(1200); + const before = timeline.topOf("row-7"); + + timeline.setRows(rows.slice(0, 7)); + timeline.keeper.reconcile(); + timeline.setRows(rows); + vi.advanceTimersToNextFrame(); + + expect(timeline.topOf("row-7")).toBe(before); expect(timeline.keeper.isAttached()).toBe(false); }); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index d2444fde65f..8a59841970f 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -898,7 +898,11 @@ export class ScrollPositionKeeper { this.reconcile(); return; } - this.setPosition(this.capture(scrollElement) ?? FREE); + this.setPosition( + target > max && this.isAtEnd(scrollTop) + ? { kind: "bottom" } + : (this.capture(scrollElement) ?? FREE), + ); }); } diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index ed3c1c98f72..469f51d85d3 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -243,9 +243,10 @@ A scroll without input or size change, such as find in page or focus moving to an offscreen control, is navigation, and the position follows it. Moving down into the last 4 px, or a wheel, End/PageDown or a touch drag toward the end while at the end, attaches. A navigation, a restore, or a viewport resize that -leaves the reading position at or past the end also attaches. Moving up out of -the end detaches. Content changes never attach or detach: a detached reader -whose content shrinks onto the end stays detached until they scroll toward it. +leaves the reading position at or past the end also attaches. So does content +that shrinks under a detached reader until the browser clamps to the end, once +the clamp is still there on the next frame, as when a row collapses near the +end. Moving up out of the end detaches. Content changes never detach. Every layout change is reconciled before paint. Triggers are ResizeObservers on the root, its content, and every mounted row, plus each windowed list's layout From 5144b9fb6ac1730fd7519774ea0d467889a54deb Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 00:21:36 -0700 Subject: [PATCH 2/9] Attach when a shrink leaves a detached reader at the end, even mid-gesture The previous commit only attached through the clamp-settle path, which a touch drag's three-second momentum window bypasses: the browser's clamp was folded in as the reader's own scroll and re-anchored at the end. On phones, dragging up to a tool call and tapping it closed left the view at the bottom with the jump button showing. Any reconcile in which the content shrank and the detached view sits at the end now attaches on the next frame if it is still there. Co-Authored-By: Claude Opus 5.5 --- .../ui/scroll-position-keeper.test.ts | 29 +++++++++++++++++++ .../components/ui/scroll-position-keeper.ts | 29 +++++++++++++++---- docs/timeline-pagination.md | 7 +++-- 3 files changed, 57 insertions(+), 8 deletions(-) diff --git a/apps/app/src/components/ui/scroll-position-keeper.test.ts b/apps/app/src/components/ui/scroll-position-keeper.test.ts index 013e2934134..b4d9189f26e 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -165,6 +165,35 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(true); }); + it("attaches when a row collapses onto the end right after a touch drag, while fling momentum still counts as the reader's", () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); + const rows = rowsOf(10); + const timeline = createTimeline(rows, { attached: true }); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.layout.layoutScrollTo(timeline.layout.scrollTop - 55); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + vi.advanceTimersByTime(500); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + timeline.resize("row-9", 40); + timeline.layout.layoutScrollTo(timeline.layout.maxScrollTop()); + timeline.keeper.reconcile(); + vi.advanceTimersToNextFrame(); + + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + it("keeps a detached reader on their row when content shrinks onto the end for a single frame", () => { vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index 8a59841970f..0b105619af5 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -131,6 +131,7 @@ export class ScrollPositionKeeper { private scrollMovedAt = Number.NEGATIVE_INFINITY; private settleTimeout: number | null = null; private clampFrame: number | null = null; + private shrinkFrame: number | null = null; private readonly lists = new Set(); private readonly listeners = new Set<() => void>(); private readonly positionListeners = new Set<() => void>(); @@ -316,8 +317,11 @@ export class ScrollPositionKeeper { if (this.settleTimeout !== null) window.clearTimeout(this.settleTimeout); if (this.clampFrame !== null) window.cancelAnimationFrame(this.clampFrame); + if (this.shrinkFrame !== null) + window.cancelAnimationFrame(this.shrinkFrame); this.settleTimeout = null; this.clampFrame = null; + this.shrinkFrame = null; this.setDeferred(0); }; } @@ -532,6 +536,7 @@ export class ScrollPositionKeeper { const restored = this.advancePendingRestore(scrollElement); const scrollHeight = scrollElement.scrollHeight; const extentChanged = scrollHeight !== this.reconciledScrollHeight; + const shrank = scrollHeight < this.reconciledScrollHeight; this.reconciledScrollHeight = scrollHeight; const defer = this.shouldDefer(scrollTop, max); const bouncing = @@ -571,6 +576,13 @@ export class ScrollPositionKeeper { this.scheduleClampSettle(); } } + if ( + shrank && + this.position.kind !== "bottom" && + this.isAtEnd(scrollElement.scrollTop) + ) { + this.scheduleShrinkAttach(); + } if (notify) this.notifyLists(urgent); } @@ -898,11 +910,18 @@ export class ScrollPositionKeeper { this.reconcile(); return; } - this.setPosition( - target > max && this.isAtEnd(scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + }); + } + + private scheduleShrinkAttach(): void { + if (this.shrinkFrame !== null) return; + this.shrinkFrame = window.requestAnimationFrame(() => { + this.shrinkFrame = null; + const scrollElement = this.options.getScrollElement(); + if (scrollElement === null) return; + this.refreshExtent(scrollElement); + this.attachIfAtEnd(); }); } diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 469f51d85d3..8d738a6e81b 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -244,9 +244,10 @@ an offscreen control, is navigation, and the position follows it. Moving down into the last 4 px, or a wheel, End/PageDown or a touch drag toward the end while at the end, attaches. A navigation, a restore, or a viewport resize that leaves the reading position at or past the end also attaches. So does content -that shrinks under a detached reader until the browser clamps to the end, once -the clamp is still there on the next frame, as when a row collapses near the -end. Moving up out of the end detaches. Content changes never detach. +that shrinks under a detached reader and leaves the view at the end, if it is +still at the end on the next frame, as when a row collapses near the end. This +holds during a gesture's momentum too. Moving up out of the end detaches. +Content changes never detach. Every layout change is reconciled before paint. Triggers are ResizeObservers on the root, its content, and every mounted row, plus each windowed list's layout From f2b25ca9469f89fe3ecd89d743cd72c895735637 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 16:45:06 -0700 Subject: [PATCH 3/9] Land unread threads at the NEW divider when reopened or paged Opening an unread thread could leave NEW mid-screen or off-screen instead of at the top: - Reopening a thread showed its cached copy first. The detail query is only live while the thread is open, so that copy still read as read, and the fresh fetch's divider was treated as a live reply with no reveal. The thread now counts as opening until its post-mount fetch settles. - When the cutoff was older than the first loaded segment, the divider sat above the oldest loaded row, the reveal went there, and the divider moved once older rows loaded. The list now holds the divider back and loads older rows until the cutoff is covered. - The reveal ran once against estimated heights for windowed rows; rows rendering around it pushed NEW down. It now repeats until the divider's position is stable, like search reveals. Co-Authored-By: Claude Opus 5.5 --- .../thread/timeline/ThreadTimelineRows.tsx | 119 +++++++++++++++++- .../ThreadTimelineRows.unread-divider.test.ts | 17 +++ .../thread/timeline/reveal-timeline-row.ts | 3 + .../timeline/useScrollToSearchedMessage.ts | 9 +- .../views/thread-detail/ThreadDetailView.tsx | 4 + .../useThreadUnreadDividerState.test.ts | 52 +++++++- .../useThreadUnreadDividerState.ts | 26 ++-- 7 files changed, 209 insertions(+), 21 deletions(-) diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index 6d7fface156..6e428dd7ca0 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -76,6 +76,10 @@ import { import { TimelineSelectionMenu } from "./TimelineSelectionMenu.js"; import type { MessageProseSelection } from "./SelectableMessageProse.js"; import { TimelineReasoningDetail } from "./TimelineReasoningDetail.js"; +import { + REVEAL_MAX_FRAME_COUNT, + REVEAL_STABLE_FRAME_COUNT, +} from "./reveal-timeline-row.js"; import { ExpandableTimelineRow } from "./ExpandableTimelineRow.js"; import { TimelineRowBodyPlaceholder } from "./TimelineRowBodyPlaceholder.js"; import { @@ -246,6 +250,15 @@ interface TimelineUnreadDividerProps { autoScroll: boolean; } +interface UseLoadOlderRowsForUnreadDividerArgs { + hasOlderRows: boolean; + isLoadingOlderRows: boolean; + onLoadOlderRows: (() => Promise | void) | undefined; + rows: readonly ThreadTimelineViewRow[]; + unreadDividerAutoScroll: boolean; + unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; +} + interface TimelineRowViewProps { activeLatestBundleId: string | null; compactActivityIntents: boolean; @@ -284,11 +297,13 @@ interface TimelineSystemDetailBlockProps { } interface BuildTimelineRowsListItemsArgs { + hasOlderRows: boolean; rows: readonly ThreadTimelineViewRow[]; unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } interface FindUnreadDividerIndexArgs { + hasOlderRows: boolean; rows: readonly ThreadTimelineViewRow[]; unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } @@ -1045,6 +1060,39 @@ const ConversationRowContent = memo(function ConversationRowContent({ ); }); +function useLoadOlderRowsForUnreadDivider({ + hasOlderRows, + isLoadingOlderRows, + onLoadOlderRows, + rows, + unreadDividerAutoScroll, + unreadDividerPlacement, +}: UseLoadOlderRowsForUnreadDividerArgs): void { + const attemptedFirstRowIdRef = useRef(null); + const firstRowId = rows[0]?.id ?? null; + const isAwaitingOlderRows = + unreadDividerAutoScroll && + isUnreadDividerAwaitingOlderRows({ + hasOlderRows, + rows, + unreadDividerPlacement, + }); + + useEffect(() => { + if ( + !isAwaitingOlderRows || + isLoadingOlderRows || + onLoadOlderRows === undefined || + firstRowId === null || + attemptedFirstRowIdRef.current === firstRowId + ) { + return; + } + attemptedFirstRowIdRef.current = firstRowId; + void Promise.resolve(onLoadOlderRows()).catch(() => undefined); + }, [firstRowId, isAwaitingOlderRows, isLoadingOlderRows, onLoadOlderRows]); +} + function TimelineUnreadDivider({ autoScroll }: TimelineUnreadDividerProps) { const bottomAnchor = useBottomAnchoredScroll(); const dividerRef = useRef(null); @@ -1055,7 +1103,11 @@ function TimelineUnreadDivider({ autoScroll }: TimelineUnreadDividerProps) { return; } - const frameId = window.requestAnimationFrame(() => { + let frameId = 0; + let frameCount = 0; + let stableFrameCount = 0; + let previousGeometry: string | null = null; + const revealDivider = () => { const divider = dividerRef.current; if (!divider) { return; @@ -1065,7 +1117,26 @@ function TimelineUnreadDivider({ autoScroll }: TimelineUnreadDividerProps) { bottomAnchor.scrollElementIntoViewClampedToMaxScroll({ element: divider, }); - }); + const scrollElement = bottomAnchor.getScrollElement(); + const geometry = [ + Math.round( + divider.getBoundingClientRect().top + (scrollElement?.scrollTop ?? 0), + ), + scrollElement?.scrollHeight ?? 0, + ].join(":"); + stableFrameCount = + geometry === previousGeometry ? stableFrameCount + 1 : 0; + previousGeometry = geometry; + frameCount += 1; + if ( + stableFrameCount >= REVEAL_STABLE_FRAME_COUNT || + frameCount >= REVEAL_MAX_FRAME_COUNT + ) { + return; + } + frameId = window.requestAnimationFrame(revealDivider); + }; + frameId = window.requestAnimationFrame(revealDivider); return () => window.cancelAnimationFrame(frameId); }, [autoScroll, bottomAnchor]); @@ -1901,11 +1972,33 @@ const MemoizedTimelineExpandableRowView = memo( areTimelineExpandableRowViewPropsEqual, ); +export function isUnreadDividerAwaitingOlderRows({ + hasOlderRows, + rows, + unreadDividerPlacement, +}: FindUnreadDividerIndexArgs): boolean { + const firstRow = rows[0]; + return ( + hasOlderRows && + firstRow !== undefined && + unreadDividerPlacement?.kind === "after-cutoff" && + firstRow.startedAt > unreadDividerPlacement.cutoffAt + ); +} + function findUnreadDividerIndex({ + hasOlderRows, rows, unreadDividerPlacement, }: FindUnreadDividerIndexArgs): number { - if (unreadDividerPlacement === null) { + if ( + unreadDividerPlacement === null || + isUnreadDividerAwaitingOlderRows({ + hasOlderRows, + rows, + unreadDividerPlacement, + }) + ) { return -1; } @@ -1944,11 +2037,13 @@ function isUnreadDividerCandidateAfterCutoff({ } export function buildTimelineRowsListItems({ + hasOlderRows, rows, unreadDividerPlacement, }: BuildTimelineRowsListItemsArgs): TimelineRowsListItem[] { const items: TimelineRowsListItem[] = []; const dividerIndex = findUnreadDividerIndex({ + hasOlderRows, rows, unreadDividerPlacement, }); @@ -2054,10 +2149,24 @@ function TimelineRowsList({ () => findActiveLatestBundleId(rows), [rows], ); + const hasOlderRows = hasOlderTimelineRows ?? false; const items = useMemo( - () => buildTimelineRowsListItems({ rows, unreadDividerPlacement }), - [rows, unreadDividerPlacement], + () => + buildTimelineRowsListItems({ + hasOlderRows, + rows, + unreadDividerPlacement, + }), + [hasOlderRows, rows, unreadDividerPlacement], ); + useLoadOlderRowsForUnreadDivider({ + hasOlderRows, + isLoadingOlderRows: isLoadingOlderTimelineRows ?? false, + onLoadOlderRows, + rows, + unreadDividerAutoScroll, + unreadDividerPlacement, + }); const itemKeys = useMemo( () => items.map((item) => diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts index e85f5593b4b..a09ae206342 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts @@ -14,8 +14,10 @@ const DIVIDER = "__divider__"; function renderTopLevelSequence( timelineRows: TimelineRow[], unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null, + hasOlderRows = false, ): string[] { return buildTimelineRowsListItems({ + hasOlderRows, rows: buildTimelineViewRows(timelineRows), unreadDividerPlacement, }).map((item) => { @@ -143,4 +145,19 @@ describe("unread divider placement", () => { expect(sequence[0]).toBe(DIVIDER); }); + + it("holds the divider back while every loaded row is newer than the cutoff and older rows exist", () => { + const timelineRows = [command(400), assistantMessage(500)]; + const placement = { kind: "after-cutoff", cutoffAt: 350 } as const; + + expect(renderTopLevelSequence(timelineRows, placement, true)).toEqual([ + "work", + "assistant", + ]); + expect(renderTopLevelSequence(timelineRows, placement, false)).toEqual([ + DIVIDER, + "work", + "assistant", + ]); + }); }); diff --git a/apps/app/src/components/thread/timeline/reveal-timeline-row.ts b/apps/app/src/components/thread/timeline/reveal-timeline-row.ts index 24a76fcfa3d..420bd6b05a4 100644 --- a/apps/app/src/components/thread/timeline/reveal-timeline-row.ts +++ b/apps/app/src/components/thread/timeline/reveal-timeline-row.ts @@ -1,6 +1,9 @@ import type { BottomAnchorContextValue } from "@/components/ui/bottom-anchored-scroll-body.js"; import { flashSearchTarget } from "@/lib/search-flash"; +export const REVEAL_STABLE_FRAME_COUNT = 2; +export const REVEAL_MAX_FRAME_COUNT = 12; + export function revealTimelineRow( element: HTMLElement, bottomAnchor: BottomAnchorContextValue | null, diff --git a/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts b/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts index 38907a2b3c5..9cc25981d6b 100644 --- a/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts +++ b/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts @@ -14,7 +14,11 @@ import { useLocation } from "react-router-dom"; import { parseMessageLink } from "@bb/client-core"; import { appToast } from "@/components/ui/app-toast"; import { useBottomAnchoredScroll } from "@/components/ui/bottom-anchored-scroll-body.js"; -import { revealTimelineRow } from "./reveal-timeline-row.js"; +import { + REVEAL_MAX_FRAME_COUNT, + REVEAL_STABLE_FRAME_COUNT, + revealTimelineRow, +} from "./reveal-timeline-row.js"; interface SeqAnchoredRow { id: string; @@ -57,9 +61,6 @@ interface SeqRange { max: number; } -const REVEAL_STABLE_FRAME_COUNT = 2; -const REVEAL_MAX_FRAME_COUNT = 12; - function escapeTimelineRowId(rowId: string): string { if (typeof CSS !== "undefined" && typeof CSS.escape === "function") { return CSS.escape(rowId); diff --git a/apps/app/src/views/thread-detail/ThreadDetailView.tsx b/apps/app/src/views/thread-detail/ThreadDetailView.tsx index a39630e96b2..aa054b5ce62 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailView.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailView.tsx @@ -576,6 +576,10 @@ function ThreadDetailViewInternal( const pendingInteractions = pendingInteractionsQuery.data ?? []; const hasPendingInteraction = pendingInteractions.length > 0; const unreadDividerState = useThreadUnreadDividerState({ + hasFreshThread: + thread !== undefined && + !isFetching && + !threadDetailBootstrapQuery.isFetching, routeThreadId: threadId, thread, }); diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts index 7491bd854aa..1232e5fcc68 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts @@ -10,25 +10,39 @@ interface DividerThread { latestAttentionAt: number; } -function renderDividerState(initialThread: DividerThread) { +interface DividerProps { + hasFreshThread: boolean; + thread: DividerThread; +} + +function renderDividerState( + initialThread: DividerThread, + initialHasFreshThread = true, +) { const renders: ReturnType[] = []; const view = renderHook( - ({ thread }: { thread: DividerThread }) => { + ({ hasFreshThread, thread }: DividerProps) => { const state = useThreadUnreadDividerState({ + hasFreshThread, routeThreadId: thread.id, thread, }); renders.push(state); return state; }, - { initialProps: { thread: initialThread } }, + { + initialProps: { + hasFreshThread: initialHasFreshThread, + thread: initialThread, + }, + }, ); return { renders, result: view.result, - show: (thread: DividerThread) => { + show: (thread: DividerThread, hasFreshThread = true) => { renders.length = 0; - view.rerender({ thread }); + view.rerender({ hasFreshThread, thread }); }, }; } @@ -92,4 +106,32 @@ describe("useThreadUnreadDividerState", () => { expect(renders[0]).toEqual({ autoScroll: false, placement: null }); }); + + it("auto-scrolls to a divider that arrives with the fresh fetch after reopening on cached read state", () => { + const { result, show } = renderDividerState( + { id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }, + false, + ); + expect(result.current).toEqual({ autoScroll: false, placement: null }); + + show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); + expect(result.current).toEqual({ + autoScroll: true, + placement: { kind: "after-cutoff", cutoffAt: 300 }, + }); + }); + + it("does not auto-scroll to a divider from a reply that lands after the thread settled", () => { + const { result, show } = renderDividerState( + { id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }, + false, + ); + show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }); + + show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); + expect(result.current).toEqual({ + autoScroll: false, + placement: { kind: "after-cutoff", cutoffAt: 300 }, + }); + }); }); diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts index 884e9470291..67f64e8cc89 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts @@ -10,6 +10,7 @@ interface ThreadUnreadDividerThreadState { interface ThreadUnreadDividerSnapshot { attentionAt: number; autoScroll: boolean; + isOpening: boolean; placement: ThreadTimelineUnreadDividerPlacement | null; threadId: string; } @@ -25,6 +26,7 @@ interface ShouldTrackThreadUnreadDividerArgs { } interface UseThreadUnreadDividerStateArgs { + hasFreshThread: boolean; routeThreadId: string | undefined; thread: ThreadUnreadDividerThreadState | undefined; } @@ -60,36 +62,46 @@ function buildUnreadDividerPlacement( function nextThreadUnreadDividerSnapshot( currentSnapshot: ThreadUnreadDividerSnapshot | null, thread: ThreadUnreadDividerThreadState, + hasFreshThread: boolean, ): ThreadUnreadDividerSnapshot { + const isOpening = + currentSnapshot?.threadId !== thread.id || currentSnapshot.isOpening; + const isStillOpening = isOpening && !hasFreshThread; if ( currentSnapshot?.threadId === thread.id && currentSnapshot.attentionAt === thread.latestAttentionAt ) { - if (thread.lastReadAt === null) { - if (currentSnapshot.placement?.kind === "before-first") { - return currentSnapshot; - } + if ( + thread.lastReadAt === null && + currentSnapshot.placement?.kind !== "before-first" + ) { return { attentionAt: thread.latestAttentionAt, autoScroll: currentSnapshot.placement !== null && currentSnapshot.autoScroll, + isOpening: isStillOpening, placement: { kind: "before-first" }, threadId: thread.id, }; } - return currentSnapshot; + if (currentSnapshot.isOpening === isStillOpening) { + return currentSnapshot; + } + return { ...currentSnapshot, isOpening: isStillOpening }; } const placement = buildUnreadDividerPlacement(thread); return { attentionAt: thread.latestAttentionAt, - autoScroll: currentSnapshot?.threadId !== thread.id && placement !== null, + autoScroll: isOpening && placement !== null, + isOpening: isStillOpening, placement, threadId: thread.id, }; } export function useThreadUnreadDividerState({ + hasFreshThread, routeThreadId, thread, }: UseThreadUnreadDividerStateArgs): ThreadUnreadDividerState { @@ -113,7 +125,7 @@ export function useThreadUnreadDividerState({ const currentSnapshot = trackedThread === null ? null - : nextThreadUnreadDividerSnapshot(snapshot, trackedThread); + : nextThreadUnreadDividerSnapshot(snapshot, trackedThread, hasFreshThread); if (currentSnapshot !== snapshot) { setSnapshot(currentSnapshot); } From aabaf4208f36c2f8b967fb0911069a8e19dba8a2 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 18:22:56 -0700 Subject: [PATCH 4/9] Open threads marked unread at the bottom without a NEW divider A thread with no read time, which only Mark as unread produces, placed NEW above the first loaded row. With paged history that is not the thread's start, so the view landed mid-thread with NEW off-screen once older rows loaded. Such threads now get no divider and open like a read thread; the unread dot is unchanged. The before-first placement is removed. Co-Authored-By: Claude Opus 5.5 --- .../thread/timeline/ThreadTimelineRows.tsx | 21 +++++-------- .../ThreadTimelineRows.unread-divider.test.ts | 21 ++++--------- .../timeline/rows/UnreadDivider.stories.tsx | 1 - .../src/components/thread/timeline/types.ts | 11 ++----- .../useThreadUnreadDividerState.test.ts | 25 +++++++++++---- .../useThreadUnreadDividerState.ts | 31 +++++++------------ 6 files changed, 46 insertions(+), 64 deletions(-) diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index 6e428dd7ca0..d6dc0b102b3 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -1981,7 +1981,7 @@ export function isUnreadDividerAwaitingOlderRows({ return ( hasOlderRows && firstRow !== undefined && - unreadDividerPlacement?.kind === "after-cutoff" && + unreadDividerPlacement !== null && firstRow.startedAt > unreadDividerPlacement.cutoffAt ); } @@ -2002,19 +2002,12 @@ function findUnreadDividerIndex({ return -1; } - switch (unreadDividerPlacement.kind) { - case "before-first": - return rows.length > 0 ? 0 : -1; - case "after-cutoff": - return rows.findIndex((row) => - isUnreadDividerCandidateAfterCutoff({ - cutoffAt: unreadDividerPlacement.cutoffAt, - row, - }), - ); - default: - assertNever(unreadDividerPlacement); - } + return rows.findIndex((row) => + isUnreadDividerCandidateAfterCutoff({ + cutoffAt: unreadDividerPlacement.cutoffAt, + row, + }), + ); } function isUserAuthoredConversationRow(row: ThreadTimelineViewRow): boolean { diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts index a09ae206342..58831b87cf6 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts @@ -71,7 +71,7 @@ describe("unread divider placement", () => { command(400), assistantMessage(500), ], - { kind: "after-cutoff", cutoffAt: 350 }, + { cutoffAt: 350 }, ); expect(sequence).toEqual(["user", "step-summary", DIVIDER, "assistant"]); @@ -86,7 +86,7 @@ describe("unread divider placement", () => { command(500), assistantMessage(600), ], - { kind: "after-cutoff", cutoffAt: 300 }, + { cutoffAt: 300 }, ); expect(sequence).toEqual([ @@ -113,7 +113,7 @@ describe("unread divider placement", () => { }), assistantMessage(500), ], - { kind: "after-cutoff", cutoffAt: 350 }, + { cutoffAt: 350 }, ); expect(collapsed).toEqual(["user", "turn", DIVIDER, "assistant"]); @@ -122,7 +122,7 @@ describe("unread divider placement", () => { it("never anchors the divider on the reader's own message", () => { const sequence = renderTopLevelSequence( [assistantMessage(100), userMessage(400), command(500)], - { kind: "after-cutoff", cutoffAt: 300 }, + { cutoffAt: 300 }, ); expect(sequence).toEqual(["assistant", "user", DIVIDER, "work"]); @@ -131,24 +131,15 @@ describe("unread divider placement", () => { it("omits the divider when no row started after the cutoff", () => { const sequence = renderTopLevelSequence( [userMessage(100), command(200), assistantMessage(300)], - { kind: "after-cutoff", cutoffAt: 400 }, + { cutoffAt: 400 }, ); expect(sequence).not.toContain(DIVIDER); }); - it("places the divider above the first row for an explicitly unread thread", () => { - const sequence = renderTopLevelSequence( - [userMessage(100), command(200), assistantMessage(300)], - { kind: "before-first" }, - ); - - expect(sequence[0]).toBe(DIVIDER); - }); - it("holds the divider back while every loaded row is newer than the cutoff and older rows exist", () => { const timelineRows = [command(400), assistantMessage(500)]; - const placement = { kind: "after-cutoff", cutoffAt: 350 } as const; + const placement = { cutoffAt: 350 } as const; expect(renderTopLevelSequence(timelineRows, placement, true)).toEqual([ "work", diff --git a/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx b/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx index c3b83ac64f1..d0d1eedd538 100644 --- a/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx +++ b/apps/app/src/components/thread/timeline/rows/UnreadDivider.stories.tsx @@ -107,7 +107,6 @@ const conversationRows: TimelineRow[] = [ ]; const afterCutoffPlacement: ThreadTimelineUnreadDividerPlacement = { - kind: "after-cutoff", cutoffAt: T0 + 3 * MINUTE + 30_000, }; diff --git a/apps/app/src/components/thread/timeline/types.ts b/apps/app/src/components/thread/timeline/types.ts index a6cff2ee899..2cc27257b7b 100644 --- a/apps/app/src/components/thread/timeline/types.ts +++ b/apps/app/src/components/thread/timeline/types.ts @@ -63,14 +63,9 @@ export interface ThreadTimelineConsumerMessageAction { run(message: ThreadChatMessageReference): void | Promise; } -export type ThreadTimelineUnreadDividerPlacement = - | { - kind: "after-cutoff"; - cutoffAt: number; - } - | { - kind: "before-first"; - }; +export interface ThreadTimelineUnreadDividerPlacement { + cutoffAt: number; +} export type UserAttachmentImageSrcResolver = ( pathOrUrl: string, diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts index 1232e5fcc68..18bd6975fd4 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts @@ -61,7 +61,7 @@ describe("useThreadUnreadDividerState", () => { expect(renders[0]).toEqual({ autoScroll: true, - placement: { kind: "after-cutoff", cutoffAt: 100 }, + placement: { cutoffAt: 100 }, }); }); @@ -72,14 +72,27 @@ describe("useThreadUnreadDividerState", () => { latestAttentionAt: 200, }); - show({ id: "thr_b", lastReadAt: null, latestAttentionAt: 300 }); + show({ id: "thr_b", lastReadAt: 250, latestAttentionAt: 300 }); expect(renders[0]).toEqual({ autoScroll: true, - placement: { kind: "before-first" }, + placement: { cutoffAt: 250 }, }); }); + it("opens a thread marked unread without a divider, and adds none when marked unread while open", () => { + const { result, show } = renderDividerState({ + id: "thr_a", + lastReadAt: null, + latestAttentionAt: 200, + }); + expect(result.current).toEqual({ autoScroll: false, placement: null }); + + show({ id: "thr_b", lastReadAt: 300, latestAttentionAt: 200 }); + show({ id: "thr_b", lastReadAt: null, latestAttentionAt: 200 }); + expect(result.current).toEqual({ autoScroll: false, placement: null }); + }); + it("keeps the opening divider when the thread is marked read, and drops it after a watched reply", () => { const { result, show } = renderDividerState({ id: "thr_a", @@ -90,7 +103,7 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_a", lastReadAt: 250, latestAttentionAt: 200 }); expect(result.current).toEqual({ autoScroll: true, - placement: { kind: "after-cutoff", cutoffAt: 100 }, + placement: { cutoffAt: 100 }, }); show({ id: "thr_a", lastReadAt: 400, latestAttentionAt: 300 }); @@ -117,7 +130,7 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); expect(result.current).toEqual({ autoScroll: true, - placement: { kind: "after-cutoff", cutoffAt: 300 }, + placement: { cutoffAt: 300 }, }); }); @@ -131,7 +144,7 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); expect(result.current).toEqual({ autoScroll: false, - placement: { kind: "after-cutoff", cutoffAt: 300 }, + placement: { cutoffAt: 300 }, }); }); }); diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts index 67f64e8cc89..72496e19692 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts @@ -50,13 +50,13 @@ function shouldTrackThreadUnreadDivider({ function buildUnreadDividerPlacement( thread: ThreadUnreadDividerThreadState, ): ThreadTimelineUnreadDividerPlacement | null { - if (thread.lastReadAt === null) { - return { kind: "before-first" }; - } - if (thread.lastReadAt < thread.latestAttentionAt) { - return { kind: "after-cutoff", cutoffAt: thread.lastReadAt }; + if ( + thread.lastReadAt === null || + thread.lastReadAt >= thread.latestAttentionAt + ) { + return null; } - return null; + return { cutoffAt: thread.lastReadAt }; } function nextThreadUnreadDividerSnapshot( @@ -71,19 +71,6 @@ function nextThreadUnreadDividerSnapshot( currentSnapshot?.threadId === thread.id && currentSnapshot.attentionAt === thread.latestAttentionAt ) { - if ( - thread.lastReadAt === null && - currentSnapshot.placement?.kind !== "before-first" - ) { - return { - attentionAt: thread.latestAttentionAt, - autoScroll: - currentSnapshot.placement !== null && currentSnapshot.autoScroll, - isOpening: isStillOpening, - placement: { kind: "before-first" }, - threadId: thread.id, - }; - } if (currentSnapshot.isOpening === isStillOpening) { return currentSnapshot; } @@ -125,7 +112,11 @@ export function useThreadUnreadDividerState({ const currentSnapshot = trackedThread === null ? null - : nextThreadUnreadDividerSnapshot(snapshot, trackedThread, hasFreshThread); + : nextThreadUnreadDividerSnapshot( + snapshot, + trackedThread, + hasFreshThread, + ); if (currentSnapshot !== snapshot) { setSnapshot(currentSnapshot); } From 711aa6ab92132596001ea24c39952821a214402f Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 18:51:30 -0700 Subject: [PATCH 5/9] Open at the bottom when NEW is outside the loaded history Instead of loading older pages until the read cutoff is covered, the divider is placed only when the cutoff falls inside the rows loaded when it is first evaluated. Otherwise the thread opens at the bottom with no divider, and that placement stays dropped, so paging back by hand later neither shows NEW nor pulls the view to it. Co-Authored-By: Claude Opus 5.5 --- .../thread/timeline/ThreadTimelineRows.tsx | 98 +++++-------------- .../ThreadTimelineRows.unread-divider.test.ts | 69 ++++++++++--- 2 files changed, 77 insertions(+), 90 deletions(-) diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index d6dc0b102b3..725e7e7fc0e 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -250,15 +250,6 @@ interface TimelineUnreadDividerProps { autoScroll: boolean; } -interface UseLoadOlderRowsForUnreadDividerArgs { - hasOlderRows: boolean; - isLoadingOlderRows: boolean; - onLoadOlderRows: (() => Promise | void) | undefined; - rows: readonly ThreadTimelineViewRow[]; - unreadDividerAutoScroll: boolean; - unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; -} - interface TimelineRowViewProps { activeLatestBundleId: string | null; compactActivityIntents: boolean; @@ -297,12 +288,11 @@ interface TimelineSystemDetailBlockProps { } interface BuildTimelineRowsListItemsArgs { - hasOlderRows: boolean; rows: readonly ThreadTimelineViewRow[]; unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } -interface FindUnreadDividerIndexArgs { +interface UseLoadedUnreadDividerPlacementArgs { hasOlderRows: boolean; rows: readonly ThreadTimelineViewRow[]; unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; @@ -1060,39 +1050,6 @@ const ConversationRowContent = memo(function ConversationRowContent({ ); }); -function useLoadOlderRowsForUnreadDivider({ - hasOlderRows, - isLoadingOlderRows, - onLoadOlderRows, - rows, - unreadDividerAutoScroll, - unreadDividerPlacement, -}: UseLoadOlderRowsForUnreadDividerArgs): void { - const attemptedFirstRowIdRef = useRef(null); - const firstRowId = rows[0]?.id ?? null; - const isAwaitingOlderRows = - unreadDividerAutoScroll && - isUnreadDividerAwaitingOlderRows({ - hasOlderRows, - rows, - unreadDividerPlacement, - }); - - useEffect(() => { - if ( - !isAwaitingOlderRows || - isLoadingOlderRows || - onLoadOlderRows === undefined || - firstRowId === null || - attemptedFirstRowIdRef.current === firstRowId - ) { - return; - } - attemptedFirstRowIdRef.current = firstRowId; - void Promise.resolve(onLoadOlderRows()).catch(() => undefined); - }, [firstRowId, isAwaitingOlderRows, isLoadingOlderRows, onLoadOlderRows]); -} - function TimelineUnreadDivider({ autoScroll }: TimelineUnreadDividerProps) { const bottomAnchor = useBottomAnchoredScroll(); const dividerRef = useRef(null); @@ -1972,33 +1929,31 @@ const MemoizedTimelineExpandableRowView = memo( areTimelineExpandableRowViewPropsEqual, ); -export function isUnreadDividerAwaitingOlderRows({ +export function useLoadedUnreadDividerPlacement({ hasOlderRows, rows, unreadDividerPlacement, -}: FindUnreadDividerIndexArgs): boolean { +}: UseLoadedUnreadDividerPlacementArgs): ThreadTimelineUnreadDividerPlacement | null { + const [unplaceablePlacement, setUnplaceablePlacement] = + useState(null); const firstRow = rows[0]; - return ( - hasOlderRows && - firstRow !== undefined && + const isUnplaceable = unreadDividerPlacement !== null && - firstRow.startedAt > unreadDividerPlacement.cutoffAt - ); + (unreadDividerPlacement === unplaceablePlacement || + (hasOlderRows && + firstRow !== undefined && + firstRow.startedAt > unreadDividerPlacement.cutoffAt)); + if (isUnplaceable && unreadDividerPlacement !== unplaceablePlacement) { + setUnplaceablePlacement(unreadDividerPlacement); + } + return isUnplaceable ? null : unreadDividerPlacement; } function findUnreadDividerIndex({ - hasOlderRows, rows, unreadDividerPlacement, -}: FindUnreadDividerIndexArgs): number { - if ( - unreadDividerPlacement === null || - isUnreadDividerAwaitingOlderRows({ - hasOlderRows, - rows, - unreadDividerPlacement, - }) - ) { +}: BuildTimelineRowsListItemsArgs): number { + if (unreadDividerPlacement === null) { return -1; } @@ -2030,13 +1985,11 @@ function isUnreadDividerCandidateAfterCutoff({ } export function buildTimelineRowsListItems({ - hasOlderRows, rows, unreadDividerPlacement, }: BuildTimelineRowsListItemsArgs): TimelineRowsListItem[] { const items: TimelineRowsListItem[] = []; const dividerIndex = findUnreadDividerIndex({ - hasOlderRows, rows, unreadDividerPlacement, }); @@ -2142,24 +2095,19 @@ function TimelineRowsList({ () => findActiveLatestBundleId(rows), [rows], ); - const hasOlderRows = hasOlderTimelineRows ?? false; + const loadedUnreadDividerPlacement = useLoadedUnreadDividerPlacement({ + hasOlderRows: hasOlderTimelineRows ?? false, + rows, + unreadDividerPlacement, + }); const items = useMemo( () => buildTimelineRowsListItems({ - hasOlderRows, rows, - unreadDividerPlacement, + unreadDividerPlacement: loadedUnreadDividerPlacement, }), - [hasOlderRows, rows, unreadDividerPlacement], + [rows, loadedUnreadDividerPlacement], ); - useLoadOlderRowsForUnreadDivider({ - hasOlderRows, - isLoadingOlderRows: isLoadingOlderTimelineRows ?? false, - onLoadOlderRows, - rows, - unreadDividerAutoScroll, - unreadDividerPlacement, - }); const itemKeys = useMemo( () => items.map((item) => diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts index 58831b87cf6..1e23fb51e6d 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.unread-divider.test.ts @@ -1,3 +1,6 @@ +// @vitest-environment jsdom + +import { renderHook } from "@testing-library/react"; import { buildTimelineViewRows } from "@bb/thread-view"; import { describe, expect, it } from "vitest"; import type { TimelineRow } from "@bb/server-contract"; @@ -7,17 +10,18 @@ import { turnRow, } from "@/test/fixtures/thread-timeline-rows"; import type { ThreadTimelineUnreadDividerPlacement } from "./types"; -import { buildTimelineRowsListItems } from "./ThreadTimelineRows"; +import { + buildTimelineRowsListItems, + useLoadedUnreadDividerPlacement, +} from "./ThreadTimelineRows"; const DIVIDER = "__divider__"; function renderTopLevelSequence( timelineRows: TimelineRow[], unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null, - hasOlderRows = false, ): string[] { return buildTimelineRowsListItems({ - hasOlderRows, rows: buildTimelineViewRows(timelineRows), unreadDividerPlacement, }).map((item) => { @@ -136,19 +140,54 @@ describe("unread divider placement", () => { expect(sequence).not.toContain(DIVIDER); }); +}); - it("holds the divider back while every loaded row is newer than the cutoff and older rows exist", () => { - const timelineRows = [command(400), assistantMessage(500)]; - const placement = { cutoffAt: 350 } as const; - - expect(renderTopLevelSequence(timelineRows, placement, true)).toEqual([ - "work", - "assistant", - ]); - expect(renderTopLevelSequence(timelineRows, placement, false)).toEqual([ - DIVIDER, - "work", - "assistant", +describe("loaded unread divider placement", () => { + it("drops a divider whose cutoff is older than the loaded rows, and keeps it dropped after older rows load", () => { + const placement = { cutoffAt: 350 }; + const latestPage = buildTimelineViewRows([ + command(400), + assistantMessage(500), ]); + const { result, rerender } = renderHook( + (props: Parameters[0]) => + useLoadedUnreadDividerPlacement(props), + { + initialProps: { + hasOlderRows: true, + rows: latestPage, + unreadDividerPlacement: placement, + }, + }, + ); + expect(result.current).toBeNull(); + + rerender({ + hasOlderRows: false, + rows: buildTimelineViewRows([ + userMessage(100), + command(200), + command(400), + assistantMessage(500), + ]), + unreadDividerPlacement: placement, + }); + expect(result.current).toBeNull(); + }); + + it("keeps a divider whose cutoff falls inside the loaded rows", () => { + const placement = { cutoffAt: 350 }; + const { result } = renderHook(() => + useLoadedUnreadDividerPlacement({ + hasOlderRows: true, + rows: buildTimelineViewRows([ + userMessage(300), + command(400), + assistantMessage(500), + ]), + unreadDividerPlacement: placement, + }), + ); + expect(result.current).toBe(placement); }); }); From 4aa0590613b553e3a92f815d1188cf74eb837466 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 20:11:40 -0700 Subject: [PATCH 6/9] Replace attach rules with one invariant and land unread threads via the keeper Attachment: the keeper attached from seven places, most tied to an event (wheel down, touch drag, End/PageDown, resize or restore at the end, a collapse that shrank content). Each new way of reaching the end needed a new rule. Now one rule covers them: a detached view within the bottom threshold attaches, unless a restore is still waiting for its row. It attaches at once when the reader's scroll, a navigation, or a completed restore put it there, and on the next frame when only layout did, so a shrink that regrows within a frame does not attach. Landing: opening an unread thread was decided by five independent pieces (the read-state snapshot, loaded rows, the divider's own scroll effect with a retry loop, the saved-position restore, and the keeper). Now the divider snapshot is taken from the first fresh copy of the thread, placeability is decided once against the loaded rows, and the landing goes through the keeper's restore path with the divider as a landmark anchor. The keeper then holds NEW at the top while rows render around it. This removes the divider's scroll effect, the frame-retry loop, the opening flag, and scrollElementIntoViewClampedToMaxScroll. Co-Authored-By: Claude Opus 5.5 --- .../promptbox/FollowUpPromptBox.test.tsx | 1 - .../promptbox/composer-contract.test.tsx | 1 - .../ThreadPendingInteractionBanner.test.tsx | 1 - .../thread/timeline/ThreadTimelineRows.tsx | 113 ++++++------- .../ThreadTimelineRows.windowing.test.tsx | 3 - .../timeline/ThreadTimelineSurface.test.tsx | 1 - .../conversation-message-overflow.test.tsx | 1 - .../thread/timeline/reveal-timeline-row.ts | 3 - .../timeline/useAutoLoadOlderRows.test.tsx | 1 - .../timeline/useScrollToSearchedMessage.ts | 9 +- .../useThreadTimelineController.test.tsx | 1 - .../thread/toc/ThreadTableOfContents.test.tsx | 1 - .../useStickyFooterAvailableHeight.test.tsx | 1 - .../ui/bottom-anchored-scroll-body.tsx | 26 --- .../ui/scroll-position-keeper.test.ts | 51 ++++-- .../components/ui/scroll-position-keeper.ts | 152 ++++++++---------- .../useThreadUnreadDividerState.ts | 16 +- docs/timeline-pagination.md | 31 ++-- 18 files changed, 183 insertions(+), 230 deletions(-) diff --git a/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx b/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx index d961a0981af..4b39b7538bd 100644 --- a/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx +++ b/apps/app/src/components/promptbox/FollowUpPromptBox.test.tsx @@ -41,7 +41,6 @@ vi.mock("@/components/ui/bottom-anchored-scroll-body.js", () => ({ isAtBottom: false, scrollToBottom: mocks.scrollToBottom, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: vi.fn(), }), diff --git a/apps/app/src/components/promptbox/composer-contract.test.tsx b/apps/app/src/components/promptbox/composer-contract.test.tsx index 8b896ceed20..5b4647e4cdc 100644 --- a/apps/app/src/components/promptbox/composer-contract.test.tsx +++ b/apps/app/src/components/promptbox/composer-contract.test.tsx @@ -73,7 +73,6 @@ vi.mock("@/components/ui/bottom-anchored-scroll-body.js", () => ({ isAtBottom: true, scrollToBottom: () => {}, scrollElementIntoView: () => {}, - scrollElementIntoViewClampedToMaxScroll: () => {}, positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: () => {}, }), diff --git a/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx b/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx index fe7e942d53f..4e0edecc248 100644 --- a/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx +++ b/apps/app/src/components/thread/pending-interactions/ThreadPendingInteractionBanner.test.tsx @@ -472,7 +472,6 @@ describe("ThreadPendingInteractionBanner collapsed strip", () => { isAtBottom: true, scrollToBottom: () => {}, scrollElementIntoView: () => {}, - scrollElementIntoViewClampedToMaxScroll: () => {}, positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: () => {}, }} diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index 725e7e7fc0e..0c07780787b 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -76,10 +76,6 @@ import { import { TimelineSelectionMenu } from "./TimelineSelectionMenu.js"; import type { MessageProseSelection } from "./SelectableMessageProse.js"; import { TimelineReasoningDetail } from "./TimelineReasoningDetail.js"; -import { - REVEAL_MAX_FRAME_COUNT, - REVEAL_STABLE_FRAME_COUNT, -} from "./reveal-timeline-row.js"; import { ExpandableTimelineRow } from "./ExpandableTimelineRow.js"; import { TimelineRowBodyPlaceholder } from "./TimelineRowBodyPlaceholder.js"; import { @@ -115,6 +111,7 @@ import { TimelineScrollRestoreContext, useBottomAnchoredScroll, } from "@/components/ui/bottom-anchored-scroll-body.js"; +import type { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper.js"; import { collectSearchedMessageAncestorRowIds, SearchMessageLocationProvider, @@ -246,10 +243,6 @@ interface TimelineRowsListProps { unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } -interface TimelineUnreadDividerProps { - autoScroll: boolean; -} - interface TimelineRowViewProps { activeLatestBundleId: string | null; compactActivityIntents: boolean; @@ -292,6 +285,13 @@ interface BuildTimelineRowsListItemsArgs { unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } +interface UseLandOnUnreadDividerArgs { + items: readonly TimelineRowsListItem[]; + positionKeeper: ScrollPositionKeeper | null; + unreadDividerAutoScroll: boolean; + unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; +} + interface UseLoadedUnreadDividerPlacementArgs { hasOlderRows: boolean; rows: readonly ThreadTimelineViewRow[]; @@ -1050,57 +1050,9 @@ const ConversationRowContent = memo(function ConversationRowContent({ ); }); -function TimelineUnreadDivider({ autoScroll }: TimelineUnreadDividerProps) { - const bottomAnchor = useBottomAnchoredScroll(); - const dividerRef = useRef(null); - const hasScrolledRef = useRef(false); - - useLayoutEffect(() => { - if (!autoScroll || !bottomAnchor || hasScrolledRef.current) { - return; - } - - let frameId = 0; - let frameCount = 0; - let stableFrameCount = 0; - let previousGeometry: string | null = null; - const revealDivider = () => { - const divider = dividerRef.current; - if (!divider) { - return; - } - - hasScrolledRef.current = true; - bottomAnchor.scrollElementIntoViewClampedToMaxScroll({ - element: divider, - }); - const scrollElement = bottomAnchor.getScrollElement(); - const geometry = [ - Math.round( - divider.getBoundingClientRect().top + (scrollElement?.scrollTop ?? 0), - ), - scrollElement?.scrollHeight ?? 0, - ].join(":"); - stableFrameCount = - geometry === previousGeometry ? stableFrameCount + 1 : 0; - previousGeometry = geometry; - frameCount += 1; - if ( - stableFrameCount >= REVEAL_STABLE_FRAME_COUNT || - frameCount >= REVEAL_MAX_FRAME_COUNT - ) { - return; - } - frameId = window.requestAnimationFrame(revealDivider); - }; - frameId = window.requestAnimationFrame(revealDivider); - - return () => window.cancelAnimationFrame(frameId); - }, [autoScroll, bottomAnchor]); - +function TimelineUnreadDivider() { return (
(null); + const divider = items.find((item) => item.kind === "unread-divider"); + const dividerId = divider?.id ?? null; + + useLayoutEffect(() => { + if ( + !unreadDividerAutoScroll || + unreadDividerPlacement === null || + dividerId === null || + positionKeeper === null || + landedPlacementRef.current === unreadDividerPlacement + ) { + return; + } + landedPlacementRef.current = unreadDividerPlacement; + if (positionKeeper.hasUserScrolled()) return; + positionKeeper.restore({ + rowId: dividerId, + offsetWithinRow: 0, + atBottom: false, + }); + }, [ + dividerId, + positionKeeper, + unreadDividerAutoScroll, + unreadDividerPlacement, + ]); +} + function findUnreadDividerIndex({ rows, unreadDividerPlacement, @@ -2108,6 +2096,12 @@ function TimelineRowsList({ }), [rows, loadedUnreadDividerPlacement], ); + useLandOnUnreadDivider({ + items, + positionKeeper: bottomAnchor?.positionKeeper ?? null, + unreadDividerAutoScroll, + unreadDividerPlacement: loadedUnreadDividerPlacement, + }); const itemKeys = useMemo( () => items.map((item) => @@ -2191,11 +2185,10 @@ function TimelineRowsList({
- +
); } diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx index 18f6a24d71f..79c2a8aa58e 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx @@ -185,7 +185,6 @@ describe("ThreadTimelineRows windowing", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const rows = Array.from({ length: count }, (_, index) => @@ -245,7 +244,6 @@ describe("ThreadTimelineRows windowing", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const rows = Array.from({ length: 80 }, (_, index) => { @@ -300,7 +298,6 @@ describe("ThreadTimelineRows windowing", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const rows = Array.from({ length: 80 }, (_, index) => diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx index d31d132356e..fb4ec106e4d 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineSurface.test.tsx @@ -51,7 +51,6 @@ describe("ThreadTimelineSurface load-older control", () => { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const onLoadOlderRows = vi diff --git a/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx b/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx index cdead28f9c6..bbd9772c19a 100644 --- a/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx +++ b/apps/app/src/components/thread/timeline/conversation-message-overflow.test.tsx @@ -124,7 +124,6 @@ describe("ConversationMessageOverflowToggle", () => { isAtBottom: true, scrollToBottom: vi.fn(), scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper: createInertScrollPositionKeeper(), holdContentPosition, }; diff --git a/apps/app/src/components/thread/timeline/reveal-timeline-row.ts b/apps/app/src/components/thread/timeline/reveal-timeline-row.ts index 420bd6b05a4..24a76fcfa3d 100644 --- a/apps/app/src/components/thread/timeline/reveal-timeline-row.ts +++ b/apps/app/src/components/thread/timeline/reveal-timeline-row.ts @@ -1,9 +1,6 @@ import type { BottomAnchorContextValue } from "@/components/ui/bottom-anchored-scroll-body.js"; import { flashSearchTarget } from "@/lib/search-flash"; -export const REVEAL_STABLE_FRAME_COUNT = 2; -export const REVEAL_MAX_FRAME_COUNT = 12; - export function revealTimelineRow( element: HTMLElement, bottomAnchor: BottomAnchorContextValue | null, diff --git a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx index 5b71065af23..9a38fac47d8 100644 --- a/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx +++ b/apps/app/src/components/thread/timeline/useAutoLoadOlderRows.test.tsx @@ -25,7 +25,6 @@ function createBottomAnchor( isAtBottom: false, scrollToBottom: vi.fn(), scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper, holdContentPosition: vi.fn(), }; diff --git a/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts b/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts index 9cc25981d6b..38907a2b3c5 100644 --- a/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts +++ b/apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts @@ -14,11 +14,7 @@ import { useLocation } from "react-router-dom"; import { parseMessageLink } from "@bb/client-core"; import { appToast } from "@/components/ui/app-toast"; import { useBottomAnchoredScroll } from "@/components/ui/bottom-anchored-scroll-body.js"; -import { - REVEAL_MAX_FRAME_COUNT, - REVEAL_STABLE_FRAME_COUNT, - revealTimelineRow, -} from "./reveal-timeline-row.js"; +import { revealTimelineRow } from "./reveal-timeline-row.js"; interface SeqAnchoredRow { id: string; @@ -61,6 +57,9 @@ interface SeqRange { max: number; } +const REVEAL_STABLE_FRAME_COUNT = 2; +const REVEAL_MAX_FRAME_COUNT = 12; + function escapeTimelineRowId(rowId: string): string { if (typeof CSS !== "undefined" && typeof CSS.escape === "function") { return CSS.escape(rowId); diff --git a/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx b/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx index 58cc4d57923..607903105f2 100644 --- a/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx +++ b/apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx @@ -253,7 +253,6 @@ function installAutoLoadEnvironment() { getScrollElement: () => scrollElement, isAtBottom: false, scrollElementIntoView: vi.fn(), - scrollElementIntoViewClampedToMaxScroll: vi.fn(), scrollToBottom: vi.fn(), }; const emitIntersection = () => { diff --git a/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx b/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx index b6d19719ae3..d2e4880a798 100644 --- a/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx +++ b/apps/app/src/components/thread/toc/ThreadTableOfContents.test.tsx @@ -329,7 +329,6 @@ beforeEach(() => { isAtBottom: false, scrollToBottom: vi.fn(), scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll: vi.fn(), positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: vi.fn(), } as unknown as ReturnType); diff --git a/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx b/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx index d0be93e5ef7..1e87488d9eb 100644 --- a/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx +++ b/apps/app/src/components/thread/user-questions/useStickyFooterAvailableHeight.test.tsx @@ -60,7 +60,6 @@ function scrollBodyContext(scrollElement: HTMLElement) { isAtBottom: true, scrollToBottom: () => {}, scrollElementIntoView: () => {}, - scrollElementIntoViewClampedToMaxScroll: () => {}, positionKeeper: createInertScrollPositionKeeper(), holdContentPosition: () => {}, }; diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx index b43dde0df98..72637cc1c06 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.tsx @@ -28,9 +28,6 @@ export interface BottomAnchorContextValue { isAtBottom: boolean; scrollToBottom: () => void; scrollElementIntoView: (args: ScrollElementIntoViewArgs) => void; - scrollElementIntoViewClampedToMaxScroll: ( - args: ScrollElementIntoViewClampedToMaxScrollArgs, - ) => void; holdContentPosition: (args: HoldContentPositionArgs) => void; positionKeeper: ScrollPositionKeeper; } @@ -55,10 +52,6 @@ interface ScrollElementIntoViewArgs { options?: ScrollIntoViewOptions; } -interface ScrollElementIntoViewClampedToMaxScrollArgs { - element: HTMLElement; -} - interface HoldContentPositionArgs { edge: "top" | "bottom"; element: HTMLElement; @@ -164,23 +157,6 @@ export function BottomAnchoredScrollBody({ [positionKeeper], ); - const scrollElementIntoViewClampedToMaxScroll = useCallback( - ({ element }: ScrollElementIntoViewClampedToMaxScrollArgs) => { - const scrollArea = scrollAreaRef.current; - if (!scrollArea) { - element.scrollIntoView({ block: "start", inline: "nearest" }); - return; - } - positionKeeper.scrollTo( - element.getBoundingClientRect().top - - scrollArea.getBoundingClientRect().top + - scrollArea.scrollTop, - "instant", - ); - }, - [positionKeeper], - ); - const holdContentPosition = useCallback( ({ edge, element, update }: HoldContentPositionArgs) => { positionKeeper.hold(element, edge); @@ -332,7 +308,6 @@ export function BottomAnchoredScrollBody({ isAtBottom, scrollToBottom, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll, holdContentPosition, positionKeeper, }), @@ -341,7 +316,6 @@ export function BottomAnchoredScrollBody({ isAtBottom, scrollToBottom, scrollElementIntoView, - scrollElementIntoViewClampedToMaxScroll, holdContentPosition, positionKeeper, ], diff --git a/apps/app/src/components/ui/scroll-position-keeper.test.ts b/apps/app/src/components/ui/scroll-position-keeper.test.ts index b4d9189f26e..716db3a2bd3 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -213,7 +213,15 @@ describe("ScrollPositionKeeper", () => { }); it("attaches when the viewport grows and the reader's position no longer fits above the end", () => { - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); const timeline = createTimeline(rowsOf(10)); timeline.userScrollTo(1350); vi.advanceTimersByTime(500); @@ -222,6 +230,7 @@ describe("ScrollPositionKeeper", () => { timeline.layout.setViewportHeight(800); timeline.layout.layoutScrollTo(timeline.layout.maxScrollTop()); timeline.keeper.reconcile(); + vi.advanceTimersToNextFrame(); expect(timeline.keeper.isAttached()).toBe(true); timeline.setRows(rowsOf(11)); @@ -243,22 +252,6 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("row-3")).toBe(before); }); - it("attaches a reader left detached at the end when they drag toward the end, though the drag cannot scroll", () => { - const rows = rowsOf(10); - const timeline = createTimeline(rows); - timeline.userScrollTo(1200); - timeline.setRows(rows.slice(0, 7)); - timeline.keeper.reconcile(); - expect(timeline.keeper.isAttached()).toBe(false); - const touch = (type: string, clientY: number) => - Object.assign(new Event(type), { touches: [{ clientY }] }); - - timeline.scrollElement.dispatchEvent(touch("touchstart", 300)); - timeline.scrollElement.dispatchEvent(touch("touchmove", 280)); - - expect(timeline.keeper.isAttached()).toBe(true); - }); - it("saves a detached reader who sits at the end as at the bottom", () => { const rows = rowsOf(10); const timeline = createTimeline(rows); @@ -287,6 +280,30 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(true); }); + it("lands on a landmark between rows and holds it at the top while rows above it change height", () => { + const rows = rowsOf(10); + const timeline = createTimeline(rows, { attached: true }); + const landmark = document.createElement("div"); + landmark.setAttribute("data-scroll-landmark-id", "divider"); + setFakeHeight(landmark, 24); + const items = timeline.scrollElement.querySelector("[data-timeline-items]"); + const rowFour = items?.children[4] ?? null; + items?.insertBefore(landmark, rowFour); + + timeline.keeper.restore({ + rowId: "divider", + offsetWithinRow: 0, + atBottom: false, + }); + const viewportTop = timeline.scrollElement.getBoundingClientRect().top; + expect(landmark.getBoundingClientRect().top).toBe(viewportTop); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.resize("row-1", 520); + timeline.keeper.reconcile(); + expect(landmark.getBoundingClientRect().top).toBe(viewportTop); + }); + it("keeps the end in view on every layout change while attached and stays attached", () => { const timeline = createTimeline(rowsOf(10), { attached: true }); expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index 0b105619af5..2322744c1ed 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -50,7 +50,9 @@ interface PendingRestore { } const ROW_ID_ATTRIBUTE = "data-timeline-row-id"; +const LANDMARK_ID_ATTRIBUTE = "data-scroll-landmark-id"; const ROW_SELECTOR = `[${ROW_ID_ATTRIBUTE}]`; +const ANCHORABLE_SELECTOR = `${ROW_SELECTOR}, [${LANDMARK_ID_ATTRIBUTE}]`; const DIRECT_ROW_SELECTOR = [ `:scope > ${ROW_SELECTOR}`, `:scope > [data-timeline-items] > ${ROW_SELECTOR}`, @@ -61,26 +63,41 @@ const MAX_ANCHOR_NEIGHBORS = 8; const SCROLL_SETTLE_MS = 150; const RESTORE_WAIT_MS = 1_000; const PASSIVE_CAPTURE = { capture: true, passive: true } as const; -const ATTACH_KEYS = new Set(["End", "PageDown", " ", "ArrowDown"]); -const SCROLL_KEYS = new Set([...ATTACH_KEYS, "Home", "PageUp", "ArrowUp"]); +const SCROLL_KEYS = new Set([ + "End", + "PageDown", + " ", + "ArrowDown", + "Home", + "PageUp", + "ArrowUp", +]); const WHEEL_SESSION_MS = 150; const KEY_SESSION_MS = 500; const PROGRAMMATIC_SMOOTH_SESSION_MS = 1_000; const SESSION_EXTENSION_MS = 150; const MOMENTUM_SESSION_MS = 3_000; -const TOUCH_ATTACH_DRAG_PX = 8; const FREE: ReadingPosition = { kind: "free" }; export function getDirectTimelineRows(list: Element): NodeListOf { return list.querySelectorAll(DIRECT_ROW_SELECTOR); } +function anchorKey(element: HTMLElement): string | null { + return ( + element.getAttribute(ROW_ID_ATTRIBUTE) ?? + element.getAttribute(LANDMARK_ID_ATTRIBUTE) + ); +} + function findMountedRow( scrollElement: HTMLElement, - rowId: string, + key: string, ): HTMLElement | null { - for (const row of scrollElement.querySelectorAll(ROW_SELECTOR)) { - if (row.getAttribute(ROW_ID_ATTRIBUTE) === rowId) return row; + for (const element of scrollElement.querySelectorAll( + ANCHORABLE_SELECTOR, + )) { + if (anchorKey(element) === key) return element; } return null; } @@ -116,7 +133,6 @@ export class ScrollPositionKeeper { private maxScrollTop = 0; private viewportHeight = 0; private reconciledWidth = 0; - private reconciledViewportHeight = 0; private reconciledScrollHeight = 0; private topRow: TopRow | null = null; private deferred = 0; @@ -126,12 +142,11 @@ export class ScrollPositionKeeper { private gestureScrolled = false; private inputUntil = Number.NEGATIVE_INFINITY; private touchStartScrollTop = 0; - private touchStartY: number | null = null; private userScrolled = false; private scrollMovedAt = Number.NEGATIVE_INFINITY; private settleTimeout: number | null = null; private clampFrame: number | null = null; - private shrinkFrame: number | null = null; + private attachFrame: number | null = null; private readonly lists = new Set(); private readonly listeners = new Set<() => void>(); private readonly positionListeners = new Set<() => void>(); @@ -186,26 +201,18 @@ export class ScrollPositionKeeper { scrollElement.style.overflowAnchor = "none"; this.ownScrollTop = scrollElement.scrollTop; const onScroll = () => this.handleScroll(); - const onTouchStart = (event: TouchEvent) => { + const onTouchStart = () => { if (!this.touching) { this.gestureScrolled = false; this.touchStartScrollTop = scrollElement.scrollTop; - this.touchStartY = event.touches[0]?.clientY ?? null; } this.touching = true; }; - const onTouchMove = (event: TouchEvent) => { - const startY = this.touchStartY; - const y = event.touches[0]?.clientY; - if (startY === null || y === undefined) return; - if (startY - y >= TOUCH_ATTACH_DRAG_PX) this.attachIfAtEnd(); - }; const activeTouchPointers = new Set(); const endTouch = () => { if (!this.touching) return; activeTouchPointers.clear(); this.touching = false; - this.touchStartY = null; if (Math.abs(scrollElement.scrollTop - this.touchStartScrollTop) >= 1) { this.gestureScrolled = true; this.scrollMovedAt = window.performance.now(); @@ -239,9 +246,8 @@ export class ScrollPositionKeeper { this.pointerDown = false; if (this.gestureScrolled) this.extendInput(SESSION_EXTENSION_MS); }; - const onWheel = (event: WheelEvent) => { + const onWheel = () => { this.extendInput(WHEEL_SESSION_MS); - if (event.deltaY > 0) this.attachIfAtEnd(); }; const onKeyDown = (event: KeyboardEvent) => { if (!SCROLL_KEYS.has(event.key) || isEditableTarget(event.target)) { @@ -256,12 +262,10 @@ export class ScrollPositionKeeper { return; } this.extendInput(KEY_SESSION_MS); - if (ATTACH_KEYS.has(event.key)) this.attachIfAtEnd(); }; scrollElement.addEventListener("scroll", onScroll, { passive: true }); scrollElement.addEventListener("wheel", onWheel, { passive: true }); scrollElement.addEventListener("touchstart", onTouchStart, PASSIVE_CAPTURE); - scrollElement.addEventListener("touchmove", onTouchMove, PASSIVE_CAPTURE); scrollElement.addEventListener("touchend", onTouchEnd, PASSIVE_CAPTURE); scrollElement.addEventListener("touchcancel", onTouchEnd, PASSIVE_CAPTURE); scrollElement.addEventListener("pointerdown", onPointerDown, { @@ -293,11 +297,6 @@ export class ScrollPositionKeeper { onTouchStart, PASSIVE_CAPTURE, ); - scrollElement.removeEventListener( - "touchmove", - onTouchMove, - PASSIVE_CAPTURE, - ); scrollElement.removeEventListener( "touchend", onTouchEnd, @@ -317,11 +316,11 @@ export class ScrollPositionKeeper { if (this.settleTimeout !== null) window.clearTimeout(this.settleTimeout); if (this.clampFrame !== null) window.cancelAnimationFrame(this.clampFrame); - if (this.shrinkFrame !== null) - window.cancelAnimationFrame(this.shrinkFrame); + if (this.attachFrame !== null) + window.cancelAnimationFrame(this.attachFrame); this.settleTimeout = null; this.clampFrame = null; - this.shrinkFrame = null; + this.attachFrame = null; this.setDeferred(0); }; } @@ -346,11 +345,8 @@ export class ScrollPositionKeeper { if (scrollElement === null) return; this.ownScrollTop = scrollElement.scrollTop; this.refreshExtent(scrollElement); - this.setPosition( - this.isAtEnd(scrollElement.scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.attachIfAtEnd(scrollElement); this.notifyLists(); } @@ -369,11 +365,8 @@ export class ScrollPositionKeeper { } this.write(scrollElement, top); this.refreshExtent(scrollElement); - this.setPosition( - this.isAtEnd(scrollElement.scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.attachIfAtEnd(scrollElement); this.notifyLists(); } @@ -483,8 +476,6 @@ export class ScrollPositionKeeper { this.setPosition(this.capture(scrollElement) ?? FREE); } } - } else if (movedDown && this.isAtEnd(scrollTop)) { - this.setPosition({ kind: "bottom" }); } else { if (position.kind === "anchor") this.apply(scrollElement, false); const current = this.position; @@ -496,6 +487,7 @@ export class ScrollPositionKeeper { this.setPosition(this.capture(scrollElement) ?? FREE); } if (this.deferred !== 0) this.scheduleDeferredWrite(); + this.attachIfAtEnd(scrollElement); this.notifyLists(); } @@ -516,12 +508,7 @@ export class ScrollPositionKeeper { const widthChanged = this.reconciledWidth > 0 && Math.abs(this.reconciledWidth - width) >= 1; if (widthChanged) this.keepAnchorVisible(scrollElement); - const resized = - widthChanged || - (this.reconciledViewportHeight > 0 && - Math.abs(this.reconciledViewportHeight - this.viewportHeight) >= 1); this.reconciledWidth = width; - this.reconciledViewportHeight = this.viewportHeight; const previous = this.ownScrollTop; if ( previous !== null && @@ -536,7 +523,6 @@ export class ScrollPositionKeeper { const restored = this.advancePendingRestore(scrollElement); const scrollHeight = scrollElement.scrollHeight; const extentChanged = scrollHeight !== this.reconciledScrollHeight; - const shrank = scrollHeight < this.reconciledScrollHeight; this.reconciledScrollHeight = scrollHeight; const defer = this.shouldDefer(scrollTop, max); const bouncing = @@ -545,19 +531,10 @@ export class ScrollPositionKeeper { this.position.kind === "bottom" && !extentChanged && Math.abs(max - scrollTop) <= this.options.bottomThresholdPx; - let target = + const target = bouncing || settledAtEnd ? null : this.targetScrollTop(scrollElement, scrollTop, max); - if ( - target !== null && - (resized || restored) && - this.position.kind === "anchor" && - target >= max - this.options.bottomThresholdPx - ) { - this.setPosition({ kind: "bottom" }); - target = max; - } if (target !== null) { const clamped = defer ? Math.min( @@ -576,13 +553,8 @@ export class ScrollPositionKeeper { this.scheduleClampSettle(); } } - if ( - shrank && - this.position.kind !== "bottom" && - this.isAtEnd(scrollElement.scrollTop) - ) { - this.scheduleShrinkAttach(); - } + if (restored) this.attachIfAtEnd(scrollElement); + else this.scheduleAttachAtEnd(scrollElement); if (notify) this.notifyLists(urgent); } @@ -655,7 +627,7 @@ export class ScrollPositionKeeper { if ( element === null || !element.isConnected || - element.getAttribute(ROW_ID_ATTRIBUTE) !== position.key + anchorKey(element) !== position.key ) { element = findMountedRow(scrollElement, position.key); if (element !== null) position.element = element; @@ -799,15 +771,6 @@ export class ScrollPositionKeeper { ); } - private attachIfAtEnd(): void { - const scrollElement = this.options.getScrollElement(); - if (scrollElement === null || this.position.kind === "bottom") return; - if (!this.isAtEnd(scrollElement.scrollTop)) return; - this.pendingRestore = null; - this.setPosition({ kind: "bottom" }); - this.reconcile(); - } - private foldPendingInputScroll(): void { const scrollElement = this.options.getScrollElement(); const previous = this.ownScrollTop; @@ -818,11 +781,8 @@ export class ScrollPositionKeeper { if (Math.abs(scrollTop - previous) < MIN_WRITE_PX) return; this.ownScrollTop = scrollTop; this.refreshExtent(scrollElement); - this.setPosition( - this.isAtEnd(scrollTop) - ? { kind: "bottom" } - : (this.capture(scrollElement) ?? FREE), - ); + this.setPosition(this.capture(scrollElement) ?? FREE); + this.attachIfAtEnd(scrollElement); } private isAtEnd(scrollTop: number): boolean { @@ -914,14 +874,30 @@ export class ScrollPositionKeeper { }); } - private scheduleShrinkAttach(): void { - if (this.shrinkFrame !== null) return; - this.shrinkFrame = window.requestAnimationFrame(() => { - this.shrinkFrame = null; - const scrollElement = this.options.getScrollElement(); - if (scrollElement === null) return; - this.refreshExtent(scrollElement); - this.attachIfAtEnd(); + private isDetachedAtEnd(scrollElement: HTMLElement): boolean { + return ( + this.position.kind !== "bottom" && + this.pendingRestore === null && + this.isAtEnd(scrollElement.scrollTop) + ); + } + + private attachIfAtEnd(scrollElement: HTMLElement): void { + if (!this.isDetachedAtEnd(scrollElement)) return; + this.setPosition({ kind: "bottom" }); + this.reconcile(); + } + + private scheduleAttachAtEnd(scrollElement: HTMLElement): void { + if (this.attachFrame !== null || !this.isDetachedAtEnd(scrollElement)) { + return; + } + this.attachFrame = window.requestAnimationFrame(() => { + this.attachFrame = null; + const current = this.options.getScrollElement(); + if (current === null) return; + this.refreshExtent(current); + this.attachIfAtEnd(current); }); } diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts index 72496e19692..a5dbf49d5db 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts @@ -10,7 +10,6 @@ interface ThreadUnreadDividerThreadState { interface ThreadUnreadDividerSnapshot { attentionAt: number; autoScroll: boolean; - isOpening: boolean; placement: ThreadTimelineUnreadDividerPlacement | null; threadId: string; } @@ -63,25 +62,22 @@ function nextThreadUnreadDividerSnapshot( currentSnapshot: ThreadUnreadDividerSnapshot | null, thread: ThreadUnreadDividerThreadState, hasFreshThread: boolean, -): ThreadUnreadDividerSnapshot { - const isOpening = - currentSnapshot?.threadId !== thread.id || currentSnapshot.isOpening; - const isStillOpening = isOpening && !hasFreshThread; +): ThreadUnreadDividerSnapshot | null { + const isOpening = currentSnapshot?.threadId !== thread.id; + if (isOpening && !hasFreshThread) { + return null; + } if ( currentSnapshot?.threadId === thread.id && currentSnapshot.attentionAt === thread.latestAttentionAt ) { - if (currentSnapshot.isOpening === isStillOpening) { - return currentSnapshot; - } - return { ...currentSnapshot, isOpening: isStillOpening }; + return currentSnapshot; } const placement = buildUnreadDividerPlacement(thread); return { attentionAt: thread.latestAttentionAt, autoScroll: isOpening && placement !== null, - isOpening: isStillOpening, placement, threadId: thread.id, }; diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 8d738a6e81b..3df50ee607a 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -226,7 +226,8 @@ anchor. The position changes only when: - the viewport gets narrower or wider and the anchor would leave the visible viewport, in which case the anchor moves just enough to stay on screen; - the content really shrinks, so the browser clamps a correction, and the clamp - is still there on the next frame. + is still there on the next frame; +- the view sits at the end while detached (see below). A scroll counts as the reader's during an input session: a wheel, a scroll key, a touch or pointer drag that scrolled, and the momentum that follows (up to @@ -240,14 +241,15 @@ so the app's own jump is never counted as the reader's gesture. Any other scroll that comes with a change in the scroll extent is layout, such as a clamp after content briefly shrank, and the owner reconciles it back to the position. A scroll without input or size change, such as find in page or focus moving to -an offscreen control, is navigation, and the position follows it. Moving down -into the last 4 px, or a wheel, End/PageDown or a touch drag toward the end -while at the end, attaches. A navigation, a restore, or a viewport resize that -leaves the reading position at or past the end also attaches. So does content -that shrinks under a detached reader and leaves the view at the end, if it is -still at the end on the next frame, as when a row collapses near the end. This -holds during a gesture's momentum too. Moving up out of the end detaches. -Content changes never detach. +an offscreen control, is navigation, and the position follows it. + +Attachment follows one rule: a detached view within 4 px of the end attaches, +whatever put it there, unless a restore or landing is still waiting for its row. +When the reader's scroll, a navigation, or a completed restore put it there, it +attaches at once. When only layout did, such as a row collapsing near the end +or the viewport growing, it attaches if the view is still at the end on the +next frame, so content that shrinks and regrows within a frame does not attach. +Moving up out of the end detaches. Content changes never detach. Every layout change is reconciled before paint. Triggers are ResizeObservers on the root, its content, and every mounted row, plus each windowed list's layout @@ -316,5 +318,16 @@ at the bottom for up to a second. The timeline keeps the loaded pages of the eight most recent threads for each query client, so a position in older history survives a thread switch. +Opening an unread thread decides its landing once, from the first copy of the +thread fetched after it opens, not a cached one, and the rows loaded at that +moment. If the read cutoff falls inside the loaded rows, the NEW divider is +placed and the owner lands on it through the restore path, with the divider as +the anchor at the top of the viewport, so rows that render or resize around it +afterwards do not move it. Otherwise, and for a thread marked unread, there is +no divider and the saved position or the bottom stands. No older pages are +loaded to find the cutoff, and a divider dropped this way stays dropped when +the reader pages back. A reader who scrolls before the landing keeps their +position. + Content shorter than the viewport is top-aligned. In that case a row that expands moves the rows below it, including the latest row. From c14ab814c8487d0afd10c1f106114f903fadac2c Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 20:25:19 -0700 Subject: [PATCH 7/9] Add a randomised keeper test and keep unplaced views out of layout attach scroll-position-keeper.model.test.ts drives the keeper through random sequences of wheel and touch scrolls, row toggles, streaming, removals, prepends, regroups, one-frame shrinks, viewport resizes, navigations, restores, and jumps to the bottom, with and without iOS write deferral and with the browser's clamp scroll before or after the resize callbacks. After each step it checks that the keeper is attached exactly when the view is at the end, that content changes never detach, that the reading row does not move without the reader unless the content cannot hold it, and that a reader's scroll is not moved. On main's keeper 75 of 300 sequences end detached at the end; on this keeper none of 5000 do. The test also showed the one attach rule would pull a tool output box that was not streaming when it opened down to the bottom as its output loaded in, which main never does. Layout alone now attaches only a view with a reading position; a view the reader never placed still attaches when the reader or a navigation brings it to the end. Co-Authored-By: Claude Opus 5.5 --- .../ui/scroll-position-keeper.model.test.ts | 472 ++++++++++++++++++ .../ui/scroll-position-keeper.test.ts | 15 + .../components/ui/scroll-position-keeper.ts | 6 +- docs/timeline-pagination.md | 13 +- 4 files changed, 504 insertions(+), 2 deletions(-) create mode 100644 apps/app/src/components/ui/scroll-position-keeper.model.test.ts diff --git a/apps/app/src/components/ui/scroll-position-keeper.model.test.ts b/apps/app/src/components/ui/scroll-position-keeper.model.test.ts new file mode 100644 index 00000000000..747bc6b618a --- /dev/null +++ b/apps/app/src/components/ui/scroll-position-keeper.model.test.ts @@ -0,0 +1,472 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { installFakeFlowLayout, setFakeHeight } from "@/test/fake-flow-layout"; +import { ScrollPositionKeeper } from "./scroll-position-keeper"; + +const THRESHOLD_PX = 4; +const SEED_COUNT = Number(process.env.KEEPER_MODEL_SEEDS ?? 200); +const STEPS_PER_SEED = 40; +const SETTLE_MS = 3_600; + +interface Row { + id: string; + height: number; +} + +type StepKind = "reader" | "layout" | "navigation"; + +interface Step { + kind: StepKind; + label: string; + heldRowId?: string; + run: () => void; +} + +function createRandom(seed: number) { + let state = seed >>> 0; + const next = () => { + state = (state + 0x6d2b79f5) >>> 0; + let value = state; + value = Math.imul(value ^ (value >>> 15), value | 1); + value ^= value + Math.imul(value ^ (value >>> 7), value | 61); + return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296; + }; + return { + next, + int: (min: number, max: number) => + min + Math.floor(next() * (max - min + 1)), + pick: (items: readonly T[]): T => { + const item = items[Math.floor(next() * items.length)]; + if (item === undefined) throw new Error("pick from empty list"); + return item; + }, + }; +} + +let restoreLayout: (() => void) | null = null; + +afterEach(() => { + restoreLayout?.(); + restoreLayout = null; + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +function runSeed(seed: number): string[] { + const random = createRandom(seed); + const deferWrites = random.next() < 0.5; + let nextId = 0; + const newRow = (): Row => ({ + id: `r${nextId++}`, + height: random.int(20, 420), + }); + let rows: Row[] = Array.from({ length: random.int(1, 30) }, newRow); + const initiallyAttached = random.next() < 0.7; + + const scrollElement = document.createElement("div"); + const content = document.createElement("div"); + const items = document.createElement("div"); + items.setAttribute("data-timeline-items", ""); + content.append(items); + scrollElement.append(content); + document.body.append(scrollElement); + let viewportHeight = random.int(300, 900); + const layout = installFakeFlowLayout({ scrollElement, viewportHeight }); + const elements = new Map(); + const render = () => { + items.replaceChildren( + ...rows.map((row) => { + const element = elements.get(row.id) ?? document.createElement("div"); + elements.set(row.id, element); + element.setAttribute("data-timeline-row-id", row.id); + setFakeHeight(element, row.height); + return element; + }), + ); + }; + render(); + const keeper = new ScrollPositionKeeper({ + bottomThresholdPx: THRESHOLD_PX, + deferWritesWhileScrolling: deferWrites, + getContentElement: () => content, + getFooterElement: () => null, + getScrollElement: () => scrollElement, + getTopLevelRows: () => + items.querySelectorAll(":scope > [data-timeline-row-id]"), + initiallyAttached, + }); + const disconnect = keeper.connect(scrollElement); + restoreLayout = () => { + disconnect(); + layout.restore(); + }; + + const history: string[] = [ + `seed ${seed} ${initiallyAttached ? "timeline" : "detail box"} deferWrites=${deferWrites}`, + ]; + const fromEnd = () => layout.maxScrollTop() - layout.scrollTop; + const topOf = (id: string) => + elements.get(id)?.isConnected === true + ? elements.get(id)!.getBoundingClientRect().top + : null; + + const browserLayout = () => { + const clamped = layout.scrollTop > layout.maxScrollTop(); + if (clamped) layout.bounceTo(layout.maxScrollTop()); + const fireScroll = () => { + if (clamped) scrollElement.dispatchEvent(new Event("scroll")); + }; + if (random.next() < 0.5) { + fireScroll(); + layout.flushResizeObservers(); + } else { + layout.flushResizeObservers(); + fireScroll(); + } + }; + const changeRows = (next: Row[]) => { + rows = next; + render(); + browserLayout(); + }; + const randomIndex = () => random.int(0, Math.max(0, rows.length - 1)); + + const steps: Array<{ weight: number; make: () => Step }> = [ + { + weight: 6, + make: () => { + const toEnd = random.next() < 0.2; + const delta = random.int(-900, 900); + return { + kind: "reader", + label: toEnd ? "wheel to end" : `wheel ${delta}`, + run: () => + layout.userScrollTo( + toEnd ? layout.maxScrollTop() : layout.scrollTop + delta, + ), + }; + }, + }, + { + weight: 4, + make: () => { + const delta = random.int(-700, 700); + return { + kind: "reader", + label: `touch drag ${delta}`, + run: () => { + scrollElement.dispatchEvent(new TouchEvent("touchstart")); + layout.layoutScrollTo(layout.scrollTop + delta); + scrollElement.dispatchEvent(new TouchEvent("touchend")); + }, + }; + }, + }, + { + weight: 4, + make: () => { + const visible = rows.filter((row) => { + const top = topOf(row.id); + return top !== null && top >= 0 && top < viewportHeight; + }); + const row = visible.length === 0 ? null : random.pick(visible); + const height = random.int(20, 600); + return { + kind: "layout", + label: `tap toggle row ${row?.id ?? "none"} to ${height}`, + ...(row === null ? {} : { heldRowId: row.id }), + run: () => { + if (row === null) return; + scrollElement.dispatchEvent(new TouchEvent("touchstart")); + scrollElement.dispatchEvent(new TouchEvent("touchend")); + const element = elements.get(row.id); + if (element !== undefined) keeper.hold(element, "top"); + changeRows( + rows.map((candidate) => + candidate.id === row.id ? { ...candidate, height } : candidate, + ), + ); + keeper.reconcile(); + }, + }; + }, + }, + { + weight: 4, + make: () => { + const index = randomIndex(); + const height = random.int(20, 600); + return { + kind: "layout", + label: `resize row ${index} to ${height}`, + run: () => + changeRows( + rows.map((row, current) => + current === index ? { ...row, height } : row, + ), + ), + }; + }, + }, + { + weight: 4, + make: () => { + const count = random.int(1, 3); + return { + kind: "layout", + label: `append ${count}`, + run: () => + changeRows([...rows, ...Array.from({ length: count }, newRow)]), + }; + }, + }, + { + weight: 3, + make: () => { + const grow = random.int(5, 200); + return { + kind: "layout", + label: `stream into last row +${grow}`, + run: () => + changeRows( + rows.map((row, index) => + index === rows.length - 1 + ? { ...row, height: row.height + grow } + : row, + ), + ), + }; + }, + }, + { + weight: 2, + make: () => { + const count = random.int(1, 3); + return { + kind: "layout", + label: `remove last ${count}`, + run: () => + changeRows(rows.slice(0, Math.max(1, rows.length - count))), + }; + }, + }, + { + weight: 3, + make: () => { + const count = random.int(1, 8); + return { + kind: "layout", + label: `prepend ${count}`, + run: () => + changeRows([...Array.from({ length: count }, newRow), ...rows]), + }; + }, + }, + { + weight: 2, + make: () => { + const index = randomIndex(); + return { + kind: "layout", + label: `regroup rows ${index}..${index + 1}`, + run: () => { + const first = rows[index]; + const second = rows[index + 1]; + if (first === undefined || second === undefined) return; + const merged = { + id: `r${nextId++}`, + height: first.height + second.height - random.int(0, 40), + }; + changeRows([ + ...rows.slice(0, index), + merged, + ...rows.slice(index + 2), + ]); + }, + }; + }, + }, + { + weight: 2, + make: () => { + const index = randomIndex(); + const shrunk = random.int(10, 60); + return { + kind: "layout", + label: `shrink row ${index} to ${shrunk} for one frame`, + run: () => { + const original = rows; + changeRows( + rows.map((row, current) => + current === index ? { ...row, height: shrunk } : row, + ), + ); + changeRows(original); + }, + }; + }, + }, + { + weight: 2, + make: () => { + const height = random.int(250, 1000); + return { + kind: "layout", + label: `viewport ${height}`, + run: () => { + viewportHeight = height; + layout.setViewportHeight(height); + browserLayout(); + }, + }; + }, + }, + { + weight: 2, + make: () => { + const fraction = random.next(); + return { + kind: "navigation", + label: `navigate to ${fraction.toFixed(2)}`, + run: () => + keeper.scrollTo( + Math.round(fraction * (layout.maxScrollTop() + 200)), + "instant", + ), + }; + }, + }, + { + weight: 2, + make: () => { + const index = randomIndex(); + const missing = random.next() < 0.15; + const offset = random.int(0, 300); + const atBottom = random.next() < 0.2; + return { + kind: "navigation", + label: `restore ${missing ? "missing row" : `row ${index}`} offset ${offset}${atBottom ? " at bottom" : ""}`, + run: () => + keeper.restore({ + rowId: missing ? "not-loaded" : (rows[index]?.id ?? "none"), + offsetWithinRow: offset, + atBottom, + }), + }; + }, + }, + { + weight: 1, + make: () => ({ + kind: "navigation", + label: "jump to bottom", + run: () => keeper.scrollToBottom(), + }), + }, + ]; + const totalWeight = steps.reduce((sum, step) => sum + step.weight, 0); + const nextStep = (): Step => { + let roll = random.next() * totalWeight; + for (const step of steps) { + roll -= step.weight; + if (roll < 0) return step.make(); + } + return steps[0]!.make(); + }; + + const settle = () => { + vi.advanceTimersByTime(SETTLE_MS); + keeper.reconcile(); + vi.advanceTimersByTime(50); + }; + const fail = (message: string): never => + expect.fail( + `${message}\n scrollTop=${layout.scrollTop} max=${layout.maxScrollTop()} attached=${keeper.isAttached()}\n ${history.join("\n ")}`, + ); + + settle(); + for (let index = 0; index < STEPS_PER_SEED; index += 1) { + const step = nextStep(); + history.push(step.label); + const wasAttached = keeper.isAttached(); + const position = keeper.getPosition(); + const anchorKey = + step.heldRowId ?? + (position.kind === "anchor" && keeper.pendingRestoreRowId() === null + ? position.key + : null); + const anchorTop = anchorKey === null ? null : topOf(anchorKey); + + step.run(); + const afterGesture = layout.scrollTop; + const transform = content.style.transform; + const runState = `${Math.round(layout.scrollTop)}/${Math.round(layout.maxScrollTop())} ${keeper.isAttached() ? "attached" : "detached"}${transform === "" ? "" : ` ${transform}`}`; + settle(); + history[history.length - 1] += + ` [after: ${runState}; settled: ${Math.round(layout.scrollTop)}/${Math.round(layout.maxScrollTop())} ${keeper.isAttached() ? "attached" : "detached"}]`; + + const attached = keeper.isAttached(); + const atEnd = fromEnd() <= THRESHOLD_PX; + const placed = keeper.getPosition().kind !== "free"; + if (attached !== atEnd && (attached || placed)) { + fail( + attached + ? "attached but not at the end" + : "detached while at the end (scroll-to-bottom button shows at the bottom)", + ); + } + if (step.kind === "layout" && wasAttached && !attached) { + fail("a content change detached the reader"); + } + if ( + step.kind === "layout" && + !attached && + anchorKey !== null && + anchorTop !== null + ) { + const top = topOf(anchorKey); + const clamped = + layout.scrollTop <= 0.5 || + layout.scrollTop >= layout.maxScrollTop() - 0.5; + if (top !== null && !clamped && Math.abs(top - anchorTop) > 1) { + fail( + `the reading row ${anchorKey} moved from ${anchorTop} to ${top} without the reader`, + ); + } + } + if (step.kind === "reader" && !attached) { + if (Math.abs(layout.scrollTop - afterGesture) > 1) { + fail( + `the reader's scroll to ${afterGesture} was moved to ${layout.scrollTop}`, + ); + } + } + } + return history; +} + +describe("ScrollPositionKeeper model", () => { + it( + `keeps the button, the bottom, and the reading row consistent across ${SEED_COUNT} random sequences`, + { timeout: SEED_COUNT * 200 }, + () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); + for (let seed = 1; seed <= SEED_COUNT; seed += 1) { + runSeed(seed); + restoreLayout?.(); + restoreLayout = null; + document.body.replaceChildren(); + } + }, + ); +}); diff --git a/apps/app/src/components/ui/scroll-position-keeper.test.ts b/apps/app/src/components/ui/scroll-position-keeper.test.ts index 716db3a2bd3..cd8a033cd19 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -194,6 +194,21 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(true); }); + it("leaves a view the reader never placed at the top while its content loads in, instead of following it", () => { + vi.useFakeTimers({ + toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], + }); + const timeline = createTimeline(rowsOf(1, 100)); + vi.advanceTimersToNextFrame(); + + timeline.setRows(rowsOf(10)); + timeline.keeper.reconcile(); + vi.advanceTimersToNextFrame(); + + expect(timeline.layout.scrollTop).toBe(0); + expect(timeline.keeper.isAttached()).toBe(false); + }); + it("keeps a detached reader on their row when content shrinks onto the end for a single frame", () => { vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index 2322744c1ed..6d687dceba2 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -889,7 +889,11 @@ export class ScrollPositionKeeper { } private scheduleAttachAtEnd(scrollElement: HTMLElement): void { - if (this.attachFrame !== null || !this.isDetachedAtEnd(scrollElement)) { + if ( + this.attachFrame !== null || + this.position.kind === "free" || + !this.isDetachedAtEnd(scrollElement) + ) { return; } this.attachFrame = window.requestAnimationFrame(() => { diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 3df50ee607a..cac0e960883 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -249,7 +249,18 @@ When the reader's scroll, a navigation, or a completed restore put it there, it attaches at once. When only layout did, such as a row collapsing near the end or the viewport growing, it attaches if the view is still at the end on the next frame, so content that shrinks and regrows within a frame does not attach. -Moving up out of the end detaches. Content changes never detach. +Moving up out of the end detaches. Content changes never detach. A view the +reader never placed, such as a tool output box that was not streaming when it +opened, attaches only when the reader or a navigation brings it to the end, so +output that loads in after it opens does not pull it down. + +`scroll-position-keeper.model.test.ts` checks these rules over random sequences +of reader scrolls, touch gestures, toggles, streaming, prepends, regroups, +transient shrinks, resizes, navigations, and restores, with and without iOS +write deferral: attached exactly when at the end, content changes never detach, +the reading row never moves without the reader unless the content cannot hold +it, and a reader's scroll is never moved. It runs 200 sequences by default; set +`KEEPER_MODEL_SEEDS` for a deeper local run. Every layout change is reconciled before paint. Triggers are ResizeObservers on the root, its content, and every mounted row, plus each windowed list's layout From 621d4be8f3fe2e0a44d5002fcc6d3854301c2e4b Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Sat, 24 Oct 2026 20:53:20 -0700 Subject: [PATCH 8/9] Add a randomised test for where unread threads open thread-opening.model.test.tsx renders the timeline with the thread view's own loading path: the bootstrap and thread queries (now shared with ThreadDetailView through useThreadDetailThread), the divider state, the timeline controller, the scroll body, and the keeper. A fake server pages a random history the way the real one does. Each sequence opens or returns to the thread with a random read state, page size, and time away, resolves the requests in a random order, and sometimes scrolls while they load. Once settled, NEW must sit above the first unread row of the whole history, be at the top unless the reader scrolled or the view is at the end, and show whenever the cutoff is inside the first page; otherwise the saved position or the bottom stands. Reintroducing each opening bug fails it: trusting the cached thread copy (NEW left 2513px down after a return), placing NEW above the first loaded row, and the one-shot reveal (NEW 156px above the top once real heights replace estimates). Co-Authored-By: Claude Opus 5.5 --- apps/app/src/test/fake-flow-layout.ts | 8 +- .../views/thread-detail/ThreadDetailView.tsx | 32 +- .../thread-opening.model.test.tsx | 536 ++++++++++++++++++ .../thread-detail/useThreadDetailThread.ts | 35 ++ docs/timeline-pagination.md | 11 + 5 files changed, 594 insertions(+), 28 deletions(-) create mode 100644 apps/app/src/views/thread-detail/thread-opening.model.test.tsx create mode 100644 apps/app/src/views/thread-detail/useThreadDetailThread.ts diff --git a/apps/app/src/test/fake-flow-layout.ts b/apps/app/src/test/fake-flow-layout.ts index 23848106764..74b09eac71a 100644 --- a/apps/app/src/test/fake-flow-layout.ts +++ b/apps/app/src/test/fake-flow-layout.ts @@ -1,6 +1,7 @@ import { vi } from "vitest"; interface FakeFlowLayoutOptions { + heightOf?: (element: Element) => number | null; scrollElement: HTMLElement | (() => HTMLElement | null); viewportHeight: number; } @@ -31,6 +32,7 @@ export function setFakeHeight(element: Element, height: number): void { } export function installFakeFlowLayout({ + heightOf, scrollElement: scrollElementOption, viewportHeight: initialViewportHeight, }: FakeFlowLayoutOptions) { @@ -45,12 +47,14 @@ export function installFakeFlowLayout({ const layout = () => { boxes.clear(); const place = (element: Element, top: number): number => { - const own = element.getAttribute(HEIGHT_ATTRIBUTE); + const attribute = element.getAttribute(HEIGHT_ATTRIBUTE); + const own = + attribute !== null ? Number(attribute) : (heightOf?.(element) ?? null); const style = element instanceof HTMLElement ? element.style : null; const shift = element instanceof HTMLElement ? translateY(element) : 0; let height: number; if (own !== null) { - height = Number(own); + height = own; let childTop = top + shift; for (const child of element.children) { childTop += place(child, childTop); diff --git a/apps/app/src/views/thread-detail/ThreadDetailView.tsx b/apps/app/src/views/thread-detail/ThreadDetailView.tsx index aa054b5ce62..81556c977ac 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailView.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailView.tsx @@ -75,11 +75,9 @@ import { type ChildThreadPendingAttentionSource, } from "../../hooks/queries/child-thread-pending-interactions"; import { - didThreadDetailBootstrapRefreshAfterMount, useChildThreads, useProjectThreadSubset, useThread, - useThreadDetailBootstrap, useThreadPendingInteractions, type ProjectThreadSubsetFilters, } from "../../hooks/queries/thread-queries"; @@ -235,7 +233,7 @@ import type { import { useEnvironmentMergeBase } from "@/components/secondary-panel/git-diff/useEnvironmentMergeBase"; import { useThreadGitActions } from "./useThreadGitActions"; import { useThreadReadTracking } from "@/hooks/useThreadReadTracking"; -import { useThreadUnreadDividerState } from "./useThreadUnreadDividerState"; +import { useThreadDetailThread } from "./useThreadDetailThread"; import { buildTerminalSyncedSecondaryFileTabs, syncTerminalTabsInFixedPanelState, @@ -465,22 +463,12 @@ function ThreadDetailViewInternal( const navigate = useImmediateRouteNavigate(); useFixedPanelTabsStorageMaintenance(); const systemConfigQuery = useSystemConfig(); - const threadDetailBootstrapQuery = useThreadDetailBootstrap(threadId); - const hasThreadDetailBootstrapSettled = - threadDetailBootstrapQuery.isSuccess || threadDetailBootstrapQuery.isError; const { - data: thread, - isFetching, - isLoadingError, - error, - } = useThread(threadId, { - enabled: hasThreadDetailBootstrapSettled, - refetchOnMount: didThreadDetailBootstrapRefreshAfterMount( - threadDetailBootstrapQuery, - ) - ? false - : "always", - }); + hasThreadDetailBootstrapSettled, + threadDetailBootstrapQuery, + threadQuery: { data: thread, isFetching, isLoadingError, error }, + unreadDividerState, + } = useThreadDetailThread(threadId); const environmentQuery = useEnvironment(thread?.environmentId, { enabled: hasThreadDetailBootstrapSettled, staleTime: 5_000, @@ -575,14 +563,6 @@ function ThreadDetailViewInternal( ); const pendingInteractions = pendingInteractionsQuery.data ?? []; const hasPendingInteraction = pendingInteractions.length > 0; - const unreadDividerState = useThreadUnreadDividerState({ - hasFreshThread: - thread !== undefined && - !isFetching && - !threadDetailBootstrapQuery.isFetching, - routeThreadId: threadId, - thread, - }); const [hasRequestedMergeBaseOptions, setHasRequestedMergeBaseOptions] = useState(false); const [shouldAutoFocusNewTab, setShouldAutoFocusNewTab] = useState(false); diff --git a/apps/app/src/views/thread-detail/thread-opening.model.test.tsx b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx new file mode 100644 index 00000000000..8d38ac9b843 --- /dev/null +++ b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx @@ -0,0 +1,536 @@ +// @vitest-environment jsdom + +import { act, cleanup, render } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import type { + ThreadResponse, + ThreadTimelineResponse, + TimelineRow, +} from "@bb/server-contract"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BottomAnchoredScrollBody } from "@/components/ui/bottom-anchored-scroll-body"; +import { ThreadTimelineSurface } from "@/components/thread/timeline/ThreadTimelineSurface"; +import { useThreadTimelineController } from "@/components/thread/timeline/useThreadTimelineController"; +import { sdk } from "@/lib/sdk"; +import { installFakeFlowLayout } from "@/test/fake-flow-layout"; +import { + makeThreadResponse, + makeThreadTimelineResponse, +} from "@/test/fixtures/thread-responses"; +import { conversationRow } from "@/test/fixtures/thread-timeline-rows"; +import { createQueryClientTestHarness } from "@/test/queryClientTestHarness"; +import { useThreadDetailThread } from "./useThreadDetailThread"; + +const SEED_COUNT = Number(process.env.OPENING_MODEL_SEEDS ?? 40); +const THREAD_ID = "thr_opening"; +const DESKTOP_SEGMENT_LIMIT = 20; +const COMPACT_SEGMENT_LIMIT = 8; +const THRESHOLD_PX = 4; + +const viewport = vi.hoisted(() => ({ compact: false })); + +vi.mock("@/lib/sdk", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + sdk: { threads: { get: vi.fn(), timeline: vi.fn() } }, + }; +}); + +vi.mock("@/hooks/useRealtimeSubscription", () => ({ + useThreadDetailRealtimeSubscription: vi.fn(), + useThreadTimelineRealtimeSubscription: vi.fn(), +})); + +vi.mock("@/hooks/useServerConnectionState", () => ({ + useServerConnectionState: () => "connected", +})); + +vi.mock("@bb/shared-ui/hooks/use-compact-viewport", async (importOriginal) => { + const actual = + await importOriginal< + typeof import("@bb/shared-ui/hooks/use-compact-viewport") + >(); + return { ...actual, useIsCompactViewport: () => viewport.compact }; +}); + +function createRandom(seed: number) { + let state = seed >>> 0; + const next = () => { + state = (state + 0x6d2b79f5) >>> 0; + let value = state; + value = Math.imul(value ^ (value >>> 15), value | 1); + value ^= value + Math.imul(value ^ (value >>> 7), value | 61); + return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296; + }; + return { + next, + int: (min: number, max: number) => + min + Math.floor(next() * (max - min + 1)), + }; +} + +interface HistoryRow { + row: TimelineRow; + height: number; + segmentStart: boolean; + authoredByReader: boolean; +} + +interface Pending { + label: string; + release: () => void; +} + +function OpenedThread() { + const { unreadDividerState } = useThreadDetailThread(THREAD_ID); + const timeline = useThreadTimelineController({ threadId: THREAD_ID }); + return ( + + + + ); +} + +function Host({ shown }: { shown: boolean }) { + return shown ? :
; +} + +let restoreLayout: (() => void) | null = null; + +beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + "Date", + ], + }); + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { + configurable: true, + value: vi.fn(), + }); +}); + +afterEach(() => { + cleanup(); + restoreLayout?.(); + restoreLayout = null; + vi.mocked(sdk.threads.get).mockReset(); + vi.mocked(sdk.threads.timeline).mockReset(); + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +async function runSeed(seed: number): Promise { + const random = createRandom(seed); + const compact = random.next() < 0.5; + viewport.compact = compact; + const segmentLimit = compact ? COMPACT_SEGMENT_LIMIT : DESKTOP_SEGMENT_LIMIT; + const viewportHeight = compact ? 760 : random.int(500, 950); + + let seq = 0; + let clock = 1_000_000; + const history: HistoryRow[] = []; + const appendSegment = (kind: "reader" | "agent") => { + seq += 1; + clock += random.int(500, 60_000); + history.push({ + row: conversationRow({ + id: `msg-${seq}`, + role: "user", + initiator: kind === "reader" ? "user" : "agent", + seq, + createdAt: clock, + startedAt: clock, + text: `${kind} message ${seq}`, + threadId: THREAD_ID, + turnId: `turn-${seq}`, + }), + height: random.int(50, 160), + segmentStart: true, + authoredByReader: kind === "reader", + }); + const replies = random.int(1, 3); + for (let index = 0; index < replies; index += 1) { + seq += 1; + clock += random.int(500, 30_000); + history.push({ + row: conversationRow({ + id: `msg-${seq}`, + role: "assistant", + seq, + createdAt: clock, + startedAt: clock, + text: `reply ${seq}`, + threadId: THREAD_ID, + turnId: `turn-${seq}`, + }), + height: random.int(40, 520), + segmentStart: false, + authoredByReader: false, + }); + } + }; + const segmentCount = random.int(3, 34); + for (let index = 0; index < segmentCount; index += 1) { + appendSegment(random.next() < 0.6 ? "reader" : "agent"); + } + + const heights = new Map(); + const heightOfRow = (id: string) => heights.get(id) ?? 80; + const syncHeights = () => { + for (const entry of history) heights.set(entry.row.id, entry.height); + }; + syncHeights(); + + let lastReadAt: number | null = clock + 1; + let latestAttentionAt = clock; + let snapshot = 1; + + const pending: Pending[] = []; + const deferred = (label: string, value: () => T): Promise => + new Promise((resolve) => { + pending.push({ label, release: () => resolve(value()) }); + }); + const threadResponse = (): ThreadResponse => + makeThreadResponse({ + id: THREAD_ID, + lastReadAt, + latestAttentionAt, + status: "idle", + }); + const pageBefore = (anchorSeq: number | null): ThreadTimelineResponse => { + const eligible = history.filter( + (entry) => anchorSeq === null || entry.row.sourceSeqStart < anchorSeq, + ); + let segments = 0; + let start = eligible.length; + while (start > 0 && segments < segmentLimit) { + start -= 1; + if (eligible[start]!.segmentStart) segments += 1; + } + const pageRows = eligible.slice(start); + const first = pageRows[0]; + const hasOlder = start > 0 && first !== undefined; + return makeThreadTimelineResponse({ + rows: pageRows.map((entry) => entry.row), + maxSeq: seq, + timelinePage: { + returnedSegmentCount: segments, + historySnapshot: `snapshot-${snapshot}`, + olderCursor: hasOlder + ? { + anchorId: `anchor-${first.row.sourceSeqStart}`, + anchorSeq: first.row.sourceSeqStart, + } + : null, + olderRowsSourceSeqEnd: hasOlder + ? eligible[start - 1]!.row.sourceSeqEnd + : null, + }, + }); + }; + vi.mocked(sdk.threads.get).mockImplementation(((args: { include?: string }) => + deferred(args.include === undefined ? "thread" : "bootstrap", () => + threadResponse(), + )) as unknown as typeof sdk.threads.get); + vi.mocked(sdk.threads.timeline).mockImplementation(((args: { + beforeAnchorSeq?: string; + }) => + deferred( + args.beforeAnchorSeq === undefined ? "latest page" : "older page", + () => + pageBefore( + args.beforeAnchorSeq === undefined + ? null + : Number(args.beforeAnchorSeq), + ), + )) as unknown as typeof sdk.threads.timeline); + + const getScrollElement = () => + document.querySelector("[data-page-scroll-viewport]"); + const layout = installFakeFlowLayout({ + heightOf: (element) => { + if (element.hasAttribute("data-scroll-landmark-id")) return 24; + const rowId = element.getAttribute("data-timeline-row-id"); + if (rowId === null) return null; + return element.parentElement?.closest("[data-timeline-row-id]") + ? null + : heightOfRow(rowId); + }, + scrollElement: getScrollElement, + viewportHeight, + }); + restoreLayout = layout.restore; + + const log: string[] = [ + `seed ${seed} ${compact ? "phone" : "desktop"} viewport=${viewportHeight} segments=${segmentCount}`, + ]; + const flush = async (ms: number) => { + await act(async () => { + await vi.advanceTimersByTimeAsync(ms); + }); + await act(async () => { + layout.flushResizeObservers(); + await vi.advanceTimersByTimeAsync(0); + }); + }; + const releaseAll = async (onRelease?: () => Promise) => { + for (let guard = 0; guard < 200; guard += 1) { + await flush(random.int(0, 40)); + if (pending.length === 0) { + await flush(20); + if (pending.length === 0) return; + } + const index = random.int(0, pending.length - 1); + const [next] = pending.splice(index, 1); + log.push(`release ${next!.label}`); + next!.release(); + await onRelease?.(); + } + throw new Error(`requests never settled\n ${log.join("\n ")}`); + }; + const rowTop = (id: string): number | null => { + const scrollElement = getScrollElement(); + const element = [ + ...document.querySelectorAll("[data-timeline-row-id]"), + ].find( + (candidate) => candidate.getAttribute("data-timeline-row-id") === id, + ); + if (scrollElement === null || element === undefined) return null; + return ( + element.getBoundingClientRect().top - + scrollElement.getBoundingClientRect().top + ); + }; + const topRowOnScreen = (): { id: string; top: number } | null => { + for (const entry of history) { + const top = rowTop(entry.row.id); + if (top !== null && top + entry.height > 1) { + return { id: entry.row.id, top }; + } + } + return null; + }; + const fail = (message: string): never => + expect.fail( + `${message}\n scrollTop=${layout.scrollTop} max=${layout.maxScrollTop()}\n ${log.join("\n ")}`, + ); + + const { wrapper: Wrapper } = createQueryClientTestHarness(); + const tree = (shown: boolean) => ( + + + + + + ); + const view = render(tree(true)); + const showThread = (shown: boolean) => view.rerender(tree(shown)); + + const returning = random.next() < 0.5; + let saved: { id: string; top: number } | null = null; + if (returning) { + log.push("first visit, read"); + await releaseAll(); + await flush(500); + if (random.next() < 0.5 && layout.maxScrollTop() > 0) { + const up = random.int(50, 1_500); + layout.userScrollTo(layout.scrollTop - up); + log.push(`reader scrolls up ${up}`); + await flush(3_600); + if (layout.maxScrollTop() - layout.scrollTop > THRESHOLD_PX) { + saved = topRowOnScreen(); + } + } + await act(async () => showThread(false)); + const away = random.int(10_000, 600_000); + await flush(away); + const added = random.int(1, 4); + for (let index = 0; index < added; index += 1) { + appendSegment(random.next() < 0.7 ? "agent" : "reader"); + } + syncHeights(); + snapshot += 1; + log.push( + `switched away for ${Math.round(away / 1000)}s; ${added} segments arrived`, + ); + } + + const readState = random.next(); + const lastReaderRow = [...history] + .reverse() + .find((entry) => entry.authoredByReader); + const realistic = history.filter( + (entry) => + lastReaderRow === undefined || + entry.row.startedAt >= lastReaderRow.row.startedAt, + ); + if (readState < 0.15) { + lastReadAt = clock + 1; + log.push("thread read"); + } else if (readState < 0.25) { + lastReadAt = null; + log.push("thread marked unread"); + } else { + const pool = readState < 0.85 ? realistic : history; + const at = pool[random.int(0, pool.length - 1)]!; + lastReadAt = at.row.startedAt + random.int(0, 400); + log.push( + `read up to ${at.row.id}${pool === history ? " (any point)" : ""}`, + ); + } + latestAttentionAt = clock + 2; + + if (returning) { + await act(async () => showThread(true)); + } + log.push(returning ? "returns to the thread" : "opens the thread"); + + let readerScroll: { id: string; top: number } | null = null; + const scrollWhileLoading = random.next() < 0.2; + await releaseAll(async () => { + if (!scrollWhileLoading || readerScroll !== null) return; + if (random.next() > 0.3 || layout.maxScrollTop() <= 0) return; + const up = random.int(50, 900); + layout.userScrollTo(layout.scrollTop - up); + await flush(16); + readerScroll = topRowOnScreen(); + log.push(`reader scrolls up ${up} while loading`); + }); + await flush(4_000); + + const divider = document.querySelector( + "[data-testid=thread-unread-divider]", + ); + const scrollElement = getScrollElement(); + if (scrollElement === null) return fail("no scroll element"); + const dividerTop = + divider === null + ? null + : divider.getBoundingClientRect().top - + scrollElement.getBoundingClientRect().top; + const fromEnd = layout.maxScrollTop() - layout.scrollTop; + const attached = + scrollElement.closest("[data-scroll-attached]") !== null || + document.querySelector("[data-scroll-attached]") !== null; + log.push( + `settled: divider=${dividerTop === null ? "none" : Math.round(dividerTop)} fromEnd=${Math.round(fromEnd)} attached=${attached}`, + ); + + const unread = lastReadAt !== null && lastReadAt < latestAttentionAt; + const cutoff = lastReadAt ?? 0; + const expected = unread + ? history.find( + (entry) => entry.row.startedAt > cutoff && !entry.authoredByReader, + ) + : undefined; + const firstPage = pageBefore(null).rows; + const firstPageStart = firstPage[0]?.startedAt ?? 0; + const firstPageHasOlder = firstPage.length < history.length; + + if (attached !== fromEnd <= THRESHOLD_PX) { + fail( + attached + ? "attached but not at the end" + : "detached at the end (the jump-to-bottom button shows at the bottom)", + ); + } + if (divider !== null) { + if (expected === undefined) fail("a divider shows on a read thread"); + const landmark = divider.closest("[data-scroll-landmark-id]"); + const nextId = landmark?.nextElementSibling?.getAttribute( + "data-timeline-row-id", + ); + const previousId = landmark?.previousElementSibling?.getAttribute( + "data-timeline-row-id", + ); + const expectedIndex = history.findIndex( + (entry) => entry.row.id === expected!.row.id, + ); + if (nextId != null && nextId !== expected!.row.id) { + fail(`NEW sits above ${nextId}, not above ${expected!.row.id}`); + } + if ( + previousId != null && + previousId !== history[expectedIndex - 1]?.row.id + ) { + fail(`NEW sits below ${previousId}, not above ${expected!.row.id}`); + } + if (readerScroll === null && dividerTop !== null) { + const atTop = Math.abs(dividerTop) <= 1; + if (!atTop && !(attached && fromEnd <= THRESHOLD_PX)) { + fail(`NEW landed at ${Math.round(dividerTop)} instead of the top`); + } + } + } else if ( + expected !== undefined && + (cutoff >= firstPageStart || !firstPageHasOlder) + ) { + fail(`no NEW although the read point is in the first page`); + } + if (readerScroll !== null) { + const scrolled: { id: string; top: number } = readerScroll; + const top = rowTop(scrolled.id); + const clamped = layout.scrollTop <= 0.5 || fromEnd <= THRESHOLD_PX; + if (top !== null && !clamped && Math.abs(top - scrolled.top) > 1) { + fail( + `the reader's row ${scrolled.id} moved from ${Math.round(scrolled.top)} to ${Math.round(top)}`, + ); + } + } else if (divider === null && returning && saved !== null) { + const top = rowTop(saved.id); + const clamped = fromEnd <= THRESHOLD_PX; + if (top !== null && !clamped && Math.abs(top - saved.top) > 1) { + fail( + `returned to ${saved.id} at ${Math.round(top)} instead of its saved ${Math.round(saved.top)}`, + ); + } + } else if (divider === null && readerScroll === null && saved === null) { + if (!attached) fail("opened without NEW but not at the bottom"); + } +} + +describe("thread opening model", () => { + it( + `lands every opening where the read state says, across ${SEED_COUNT} random loading orders`, + { timeout: SEED_COUNT * 2_000 }, + async () => { + for (let seed = 1; seed <= SEED_COUNT; seed += 1) { + await runSeed(seed); + cleanup(); + restoreLayout?.(); + restoreLayout = null; + document.body.replaceChildren(); + } + }, + ); +}); diff --git a/apps/app/src/views/thread-detail/useThreadDetailThread.ts b/apps/app/src/views/thread-detail/useThreadDetailThread.ts new file mode 100644 index 00000000000..252a5885c08 --- /dev/null +++ b/apps/app/src/views/thread-detail/useThreadDetailThread.ts @@ -0,0 +1,35 @@ +import { + didThreadDetailBootstrapRefreshAfterMount, + useThread, + useThreadDetailBootstrap, +} from "@/hooks/queries/thread-queries"; +import { useThreadUnreadDividerState } from "./useThreadUnreadDividerState"; + +export function useThreadDetailThread(threadId: string) { + const threadDetailBootstrapQuery = useThreadDetailBootstrap(threadId); + const hasThreadDetailBootstrapSettled = + threadDetailBootstrapQuery.isSuccess || threadDetailBootstrapQuery.isError; + const threadQuery = useThread(threadId, { + enabled: hasThreadDetailBootstrapSettled, + refetchOnMount: didThreadDetailBootstrapRefreshAfterMount( + threadDetailBootstrapQuery, + ) + ? false + : "always", + }); + const thread = threadQuery.data; + const unreadDividerState = useThreadUnreadDividerState({ + hasFreshThread: + thread !== undefined && + !threadQuery.isFetching && + !threadDetailBootstrapQuery.isFetching, + routeThreadId: threadId, + thread, + }); + return { + hasThreadDetailBootstrapSettled, + threadDetailBootstrapQuery, + threadQuery, + unreadDividerState, + }; +} diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index cac0e960883..f3677870f98 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -340,5 +340,16 @@ loaded to find the cutoff, and a divider dropped this way stays dropped when the reader pages back. A reader who scrolls before the landing keeps their position. +`thread-opening.model.test.tsx` checks the landing end to end. It renders the +timeline with the thread view's own loading hooks against a fake server that +pages a random history, opens or returns to the thread with random read +states, page sizes, and time away, and resolves the bootstrap, thread, and +timeline requests in random orders, sometimes with the reader scrolling while +they load. Once settled, NEW must sit above the first unread row of the whole +history, must be at the top unless the reader scrolled or the view is at the +end, and must show whenever the read cutoff is inside the first page; +otherwise the saved position or the bottom stands. It runs 40 sequences by +default; set `OPENING_MODEL_SEEDS` for more. + Content shorter than the viewport is top-aligned. In that case a row that expands moves the rows below it, including the latest row. From 5eda6f9ed4fa2c57ea83343aa5427c97f1a066e9 Mon Sep 17 00:00:00 2001 From: Michael Yong Date: Mon, 26 Oct 2026 10:13:48 -0700 Subject: [PATCH 9/9] Capture unread landing before automatic read tracking --- .../views/thread-detail/ThreadDetailView.tsx | 13 ++----- .../thread-opening.model.test.tsx | 34 +++++++++++++----- .../thread-detail/useThreadDetailThread.ts | 9 ++++- .../useThreadUnreadDividerState.test.ts | 35 ++++++++++++++++--- .../useThreadUnreadDividerState.ts | 3 ++ docs/timeline-pagination.md | 7 ++-- 6 files changed, 73 insertions(+), 28 deletions(-) diff --git a/apps/app/src/views/thread-detail/ThreadDetailView.tsx b/apps/app/src/views/thread-detail/ThreadDetailView.tsx index 81556c977ac..c80c891079a 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailView.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailView.tsx @@ -56,10 +56,7 @@ import { import { useForkThreadFromMessage } from "@/hooks/useForkThreadFromMessage"; import { isThreadForkable } from "@bb/client-core"; import { useRequestEnvironmentAction } from "../../hooks/mutations/environment-mutations"; -import { - useMarkThreadRead, - useUpdateThread, -} from "../../hooks/mutations/thread-state-mutations"; +import { useUpdateThread } from "../../hooks/mutations/thread-state-mutations"; import { useCreateThreadQueuedMessage, useEditThreadMessage, @@ -232,7 +229,6 @@ import type { } from "@/components/secondary-panel/ThreadSecondaryPanel"; import { useEnvironmentMergeBase } from "@/components/secondary-panel/git-diff/useEnvironmentMergeBase"; import { useThreadGitActions } from "./useThreadGitActions"; -import { useThreadReadTracking } from "@/hooks/useThreadReadTracking"; import { useThreadDetailThread } from "./useThreadDetailThread"; import { buildTerminalSyncedSecondaryFileTabs, @@ -468,7 +464,7 @@ function ThreadDetailViewInternal( threadDetailBootstrapQuery, threadQuery: { data: thread, isFetching, isLoadingError, error }, unreadDividerState, - } = useThreadDetailThread(threadId); + } = useThreadDetailThread(threadId, timelineEnabled); const environmentQuery = useEnvironment(thread?.environmentId, { enabled: hasThreadDetailBootstrapSettled, staleTime: 5_000, @@ -757,7 +753,6 @@ function ThreadDetailViewInternal( const editMessage = useEditThreadMessage(); const createQueuedMessage = useCreateThreadQueuedMessage(); const requestEnvironmentAction = useRequestEnvironmentAction(); - const markThreadRead = useMarkThreadRead(); const updateEnvironment = useUpdateEnvironment(); const updateThread = useUpdateThread({ errorMessage: "Failed to assign parent thread.", @@ -1754,10 +1749,6 @@ function ThreadDetailViewInternal( return { ...childThreadsSection, pendingInteractions }; }, [childThreadsSection, childPendingInteractions]); const isThreadTimelinePending = timelineLoading && timelineRows.length === 0; - useThreadReadTracking({ - markThreadRead, - thread: timelineEnabled ? thread : undefined, - }); const { effectiveMergeBaseBranch, handleMergeBaseBranchChange, diff --git a/apps/app/src/views/thread-detail/thread-opening.model.test.tsx b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx index 8d38ac9b843..b28e65ab2d1 100644 --- a/apps/app/src/views/thread-detail/thread-opening.model.test.tsx +++ b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx @@ -12,6 +12,8 @@ import { BottomAnchoredScrollBody } from "@/components/ui/bottom-anchored-scroll import { ThreadTimelineSurface } from "@/components/thread/timeline/ThreadTimelineSurface"; import { useThreadTimelineController } from "@/components/thread/timeline/useThreadTimelineController"; import { sdk } from "@/lib/sdk"; +import { makeThreadListEntry } from "@bb/test-helpers/domain-fixtures"; +import { threadListQueryKey } from "@/hooks/queries/query-keys"; import { installFakeFlowLayout } from "@/test/fake-flow-layout"; import { makeThreadResponse, @@ -33,7 +35,7 @@ vi.mock("@/lib/sdk", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - sdk: { threads: { get: vi.fn(), timeline: vi.fn() } }, + sdk: { threads: { get: vi.fn(), timeline: vi.fn(), markRead: vi.fn() } }, }; }); @@ -54,6 +56,8 @@ vi.mock("@bb/shared-ui/hooks/use-compact-viewport", async (importOriginal) => { return { ...actual, useIsCompactViewport: () => viewport.compact }; }); +vi.mock("@/lib/user-activity", () => ({ useUserActive: () => true })); + function createRandom(seed: number) { let state = seed >>> 0; const next = () => { @@ -83,7 +87,7 @@ interface Pending { } function OpenedThread() { - const { unreadDividerState } = useThreadDetailThread(THREAD_ID); + const { unreadDividerState } = useThreadDetailThread(THREAD_ID, true); const timeline = useThreadTimelineController({ threadId: THREAD_ID }); return ( { restoreLayout = null; vi.mocked(sdk.threads.get).mockReset(); vi.mocked(sdk.threads.timeline).mockReset(); + vi.mocked(sdk.threads.markRead).mockReset(); vi.useRealTimers(); vi.restoreAllMocks(); document.body.replaceChildren(); @@ -275,6 +280,13 @@ async function runSeed(seed: number): Promise { ), )) as unknown as typeof sdk.threads.timeline); + vi.mocked(sdk.threads.markRead).mockImplementation(() => + deferred("mark read", () => { + lastReadAt = latestAttentionAt; + return threadResponse(); + }), + ); + const getScrollElement = () => document.querySelector("[data-page-scroll-viewport]"); const layout = installFakeFlowLayout({ @@ -345,7 +357,7 @@ async function runSeed(seed: number): Promise { `${message}\n scrollTop=${layout.scrollTop} max=${layout.maxScrollTop()}\n ${log.join("\n ")}`, ); - const { wrapper: Wrapper } = createQueryClientTestHarness(); + const { wrapper: Wrapper, queryClient } = createQueryClientTestHarness(); const tree = (shown: boolean) => ( @@ -353,13 +365,14 @@ async function runSeed(seed: number): Promise { ); - const view = render(tree(true)); + const view = render(tree(false)); const showThread = (shown: boolean) => view.rerender(tree(shown)); const returning = random.next() < 0.5; let saved: { id: string; top: number } | null = null; if (returning) { log.push("first visit, read"); + await act(async () => showThread(true)); await releaseAll(); await flush(500); if (random.next() < 0.5 && layout.maxScrollTop() > 0) { @@ -409,10 +422,12 @@ async function runSeed(seed: number): Promise { ); } latestAttentionAt = clock + 2; + const openingLastReadAt = lastReadAt; - if (returning) { - await act(async () => showThread(true)); - } + queryClient.setQueryData(threadListQueryKey({ archived: false }), [ + makeThreadListEntry({ id: THREAD_ID, lastReadAt, latestAttentionAt }), + ]); + await act(async () => showThread(true)); log.push(returning ? "returns to the thread" : "opens the thread"); let readerScroll: { id: string; top: number } | null = null; @@ -446,8 +461,9 @@ async function runSeed(seed: number): Promise { `settled: divider=${dividerTop === null ? "none" : Math.round(dividerTop)} fromEnd=${Math.round(fromEnd)} attached=${attached}`, ); - const unread = lastReadAt !== null && lastReadAt < latestAttentionAt; - const cutoff = lastReadAt ?? 0; + const unread = + openingLastReadAt !== null && openingLastReadAt < latestAttentionAt; + const cutoff = openingLastReadAt ?? 0; const expected = unread ? history.find( (entry) => entry.row.startedAt > cutoff && !entry.authoredByReader, diff --git a/apps/app/src/views/thread-detail/useThreadDetailThread.ts b/apps/app/src/views/thread-detail/useThreadDetailThread.ts index 252a5885c08..c6fdb9c9d5d 100644 --- a/apps/app/src/views/thread-detail/useThreadDetailThread.ts +++ b/apps/app/src/views/thread-detail/useThreadDetailThread.ts @@ -3,9 +3,11 @@ import { useThread, useThreadDetailBootstrap, } from "@/hooks/queries/thread-queries"; +import { useMarkThreadRead } from "@/hooks/mutations/thread-state-mutations"; +import { useThreadReadTracking } from "@/hooks/useThreadReadTracking"; import { useThreadUnreadDividerState } from "./useThreadUnreadDividerState"; -export function useThreadDetailThread(threadId: string) { +export function useThreadDetailThread(threadId: string, trackRead: boolean) { const threadDetailBootstrapQuery = useThreadDetailBootstrap(threadId); const hasThreadDetailBootstrapSettled = threadDetailBootstrapQuery.isSuccess || threadDetailBootstrapQuery.isError; @@ -21,11 +23,16 @@ export function useThreadDetailThread(threadId: string) { const unreadDividerState = useThreadUnreadDividerState({ hasFreshThread: thread !== undefined && + !threadQuery.isPlaceholderData && !threadQuery.isFetching && !threadDetailBootstrapQuery.isFetching, routeThreadId: threadId, thread, }); + useThreadReadTracking({ + markThreadRead: useMarkThreadRead(), + thread: trackRead && unreadDividerState.ready ? thread : undefined, + }); return { hasThreadDetailBootstrapSettled, threadDetailBootstrapQuery, diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts index 18bd6975fd4..b3fd45c6ae5 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.test.ts @@ -60,6 +60,7 @@ describe("useThreadUnreadDividerState", () => { }); expect(renders[0]).toEqual({ + ready: true, autoScroll: true, placement: { cutoffAt: 100 }, }); @@ -75,6 +76,7 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_b", lastReadAt: 250, latestAttentionAt: 300 }); expect(renders[0]).toEqual({ + ready: true, autoScroll: true, placement: { cutoffAt: 250 }, }); @@ -86,11 +88,19 @@ describe("useThreadUnreadDividerState", () => { lastReadAt: null, latestAttentionAt: 200, }); - expect(result.current).toEqual({ autoScroll: false, placement: null }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); show({ id: "thr_b", lastReadAt: 300, latestAttentionAt: 200 }); show({ id: "thr_b", lastReadAt: null, latestAttentionAt: 200 }); - expect(result.current).toEqual({ autoScroll: false, placement: null }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); }); it("keeps the opening divider when the thread is marked read, and drops it after a watched reply", () => { @@ -102,12 +112,17 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_a", lastReadAt: 250, latestAttentionAt: 200 }); expect(result.current).toEqual({ + ready: true, autoScroll: true, placement: { cutoffAt: 100 }, }); show({ id: "thr_a", lastReadAt: 400, latestAttentionAt: 300 }); - expect(result.current).toEqual({ autoScroll: false, placement: null }); + expect(result.current).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); }); it("opens a read thread without a divider", () => { @@ -117,7 +132,11 @@ describe("useThreadUnreadDividerState", () => { latestAttentionAt: 200, }); - expect(renders[0]).toEqual({ autoScroll: false, placement: null }); + expect(renders[0]).toEqual({ + ready: true, + autoScroll: false, + placement: null, + }); }); it("auto-scrolls to a divider that arrives with the fresh fetch after reopening on cached read state", () => { @@ -125,10 +144,15 @@ describe("useThreadUnreadDividerState", () => { { id: "thr_a", lastReadAt: 300, latestAttentionAt: 200 }, false, ); - expect(result.current).toEqual({ autoScroll: false, placement: null }); + expect(result.current).toEqual({ + ready: false, + autoScroll: false, + placement: null, + }); show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); expect(result.current).toEqual({ + ready: true, autoScroll: true, placement: { cutoffAt: 300 }, }); @@ -143,6 +167,7 @@ describe("useThreadUnreadDividerState", () => { show({ id: "thr_a", lastReadAt: 300, latestAttentionAt: 400 }); expect(result.current).toEqual({ + ready: true, autoScroll: false, placement: { cutoffAt: 300 }, }); diff --git a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts index a5dbf49d5db..feae801c015 100644 --- a/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts +++ b/apps/app/src/views/thread-detail/useThreadUnreadDividerState.ts @@ -15,6 +15,7 @@ interface ThreadUnreadDividerSnapshot { } interface ThreadUnreadDividerState { + ready: boolean; autoScroll: boolean; placement: ThreadTimelineUnreadDividerPlacement | null; } @@ -31,6 +32,7 @@ interface UseThreadUnreadDividerStateArgs { } const NO_UNREAD_DIVIDER_STATE: ThreadUnreadDividerState = { + ready: false, autoScroll: false, placement: null, }; @@ -122,6 +124,7 @@ export function useThreadUnreadDividerState({ } return { + ready: true, autoScroll: currentSnapshot.autoScroll, placement: currentSnapshot.placement, }; diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index f3677870f98..6e2cff21b19 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -331,7 +331,9 @@ survives a thread switch. Opening an unread thread decides its landing once, from the first copy of the thread fetched after it opens, not a cached one, and the rows loaded at that -moment. If the read cutoff falls inside the loaded rows, the NEW divider is +moment. Automatic read tracking waits for that opening snapshot, so sidebar +placeholder data cannot mark the thread read before its unread cutoff is saved. +If the read cutoff falls inside the loaded rows, the NEW divider is placed and the owner lands on it through the restore path, with the divider as the anchor at the top of the viewport, so rows that render or resize around it afterwards do not move it. Otherwise, and for a thread marked unread, there is @@ -341,7 +343,8 @@ the reader pages back. A reader who scrolls before the landing keeps their position. `thread-opening.model.test.tsx` checks the landing end to end. It renders the -timeline with the thread view's own loading hooks against a fake server that +timeline with the thread view's own loading and automatic read-tracking hooks, +including cached sidebar placeholders, against a fake server that pages a random history, opens or returns to the thread with random read states, page sizes, and time away, and resolves the bootstrap, thread, and timeline requests in random orders, sometimes with the reader scrolling while