The best way to control Claude Code, Codex and more from any computer or phone
fix(web): find shows its match after a thread switch, and the timeline hears scrolling through one viewport signal (#25463)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 05:50 UTC
3cb16cf16509e74e2f483f541010996a9e6fac34
11 files changed
+1164
-731
apps/web/src/components/ChatView.tsx
+7
-7
@@ -1999,9 +1999,7 @@ export default function ChatView(props: ChatViewProps) {
1999
const {
2000
showScrollToBottom,
2001
timelineLiveFollowEnabled,
2002
- cancelPositionRestoreRef,
2002
isTimelineAtLogicalEndStable,
2004
- cancelTimelineLiveFollowForUserNavigationStable,
2003
onComposerPageScrollKeyDownStable,
2004
onComposerPageScrollKeyUpStable,
2005
onComposerPageScrollReleaseStable,
@@ -2011,14 +2009,14 @@ export default function ChatView(props: ChatViewProps) {
2009
onToolOutputCollapsedAtEndStable,
2010
onIsAtEndChangeStable,
2011
anchorNewTurn,
2012
+ attachTimelineViewport,
2013
+ attachComposerOverlay: attachFollowComposerOverlay,
2014
} = useTimelineFollow({
2015
legendListRef,
2016
composerRef,
2017
- composerOverlayElement,
2017
composerTimelineInset,
2018
routeThreadKey,
2019
activeThreadKey,
2021
- activeThreadId: activeThread?.id,
2020
isServerThread,
2021
serverProjection,
2022
threadStatus,
@@ -3365,8 +3363,7 @@ export default function ChatView(props: ChatViewProps) {
3363
onIsAtEndChange={onIsAtEndChangeStable}
3364
onContentOverflowChange={setTimelineOverflows}
3365
onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable}
3368
- onManualNavigation={cancelTimelineLiveFollowForUserNavigationStable}
3369
- cancelPositionRestoreRef={cancelPositionRestoreRef}
3366
+ onViewportAttach={attachTimelineViewport}
3367
hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
3368
emptyPlaceholderInset={composerReservedHeight}
3369
topFadeEnabled={!hasTimelineTopBanner}
@@ -3387,7 +3384,10 @@ export default function ChatView(props: ChatViewProps) {
3384
</div>
3385
3386
<div
3390
- ref={setComposerOverlayElement}
3387
+ ref={(overlay: HTMLDivElement | null) => {
3388
+ setComposerOverlayElement(overlay);
3389
+ attachFollowComposerOverlay(overlay);
3390
+ }}
3391
inert={isRevertingCheckpoint}
3392
data-chat-composer-overlay="true"
3393
className={
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+121
-1
@@ -24,6 +24,8 @@ import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
24
import { collectThreadFindRanges } from "./threadFindHighlights";
25
import { toastManager } from "../ui/toast";
26
import type { CitedHistory } from "./citationProcedure";
27
+import type { TimelineNavigation } from "./timelineViewport";
28
+import { rememberTimelinePosition } from "./timelineScrollAnchoring";
29
30
const environmentQuery = vi.hoisted(() => ({
31
error: "Pull request not found",
@@ -91,7 +93,6 @@ function baseProps(): Omit<TimelineProps, "timelineEntries"> {
93
emptyPlaceholderInset: 0,
94
liveFollowEnabled: true,
95
onIsAtEndChange: () => {},
94
- onManualNavigation: () => {},
96
};
97
}
98
@@ -638,6 +639,125 @@ describe("MessagesTimeline attachments", () => {
639
});
640
});
641
642
+describe("MessagesTimeline thread find", () => {
643
+ // Opening find is navigation; on a list already showing the thread the open
644
+ // action navigates, so the list itself releases follow only when it starts
645
+ // showing a thread whose find is already open.
646
+ function renderObserved() {
647
+ const navigations: TimelineNavigation[] = [];
648
+ const base = baseProps();
649
+ const element = (next: Partial<TimelineProps>) => (
650
+ <MessagesTimeline
651
+ {...base}
652
+ timelineEntries={[message("Where is the sidebar fix?")]}
653
+ onViewportAttach={(viewport) =>
654
+ viewport.subscribe((navigation) => navigations.push(navigation))
655
+ }
656
+ {...next}
657
+ />
658
+ );
659
+ return { navigations, element };
660
+ }
661
+ const released = { source: "command", releasesFollow: true };
662
+
663
+ it("releases follow once when it starts showing a thread whose find is open", async () => {
664
+ setup();
665
+ const { navigations, element } = renderObserved();
666
+ await using screen = await renderElement(element({}));
667
+ expect(navigations).toEqual([]);
668
+
669
+ const other = "environment-local:thread-find-open";
670
+ await screen.rerender(element({ routeThreadKey: other, findOpen: true }));
671
+ expect(navigations).toEqual([released]);
672
+ await screen.rerender(element({ routeThreadKey: other, findOpen: false }));
673
+ await screen.rerender(element({ routeThreadKey: other, findOpen: true }));
674
+ expect(navigations).toEqual([released]);
675
+ });
676
+
677
+ it("releases follow once when it mounts on a thread whose find is open", async () => {
678
+ setup();
679
+ const { navigations, element } = renderObserved();
680
+ await using screen = await renderElement(element({ findOpen: true }));
681
+ await screen.rerender(element({ findOpen: true }));
682
+ expect(navigations).toEqual([released]);
683
+ });
684
+
685
+ it("still restores the position of a thread it switches to whose find is open", async () => {
686
+ setup();
687
+ const base = baseProps();
688
+ const other = "environment-local:thread-find-open-positioned";
689
+ const replies = Array.from({ length: 40 }, (_, index) =>
690
+ message(`Reply ${index}\n\n${"line\n\n".repeat(8)}`, { role: "assistant" }, `r-${index}`),
691
+ );
692
+ rememberTimelinePosition(
693
+ other,
694
+ { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },
695
+ false,
696
+ );
697
+ await using screen = await renderElement(
698
+ <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />,
699
+ );
700
+ await screen.rerender(
701
+ <MessagesTimeline
702
+ {...base}
703
+ routeThreadKey={other}
704
+ timelineEntries={replies}
705
+ liveFollowEnabled={false}
706
+ findOpen
707
+ />,
708
+ );
709
+ const viewport = base.listRef.current!.getScrollableNode()!;
710
+ await vi.waitFor(() => {
711
+ const row = screen.container.querySelector('[data-timeline-row-id="entry-r-20"]');
712
+ expect(row).not.toBeNull();
713
+ expect(
714
+ Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top),
715
+ ).toBeLessThanOrEqual(2);
716
+ });
717
+ });
718
+ it("reveals find's match, not the remembered row, on a thread it switches to", async () => {
719
+ setup();
720
+ const base = baseProps();
721
+ const other = "environment-local:thread-find-open-match";
722
+ const replies = Array.from({ length: 40 }, (_, index) =>
723
+ message(
724
+ `${index === 5 ? "Needle here" : `Reply ${index}`}\n\n${"line\n\n".repeat(8)}`,
725
+ { role: "assistant" },
726
+ `r-${index}`,
727
+ ),
728
+ );
729
+ rememberTimelinePosition(
730
+ other,
731
+ { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },
732
+ false,
733
+ );
734
+ await using screen = await renderElement(
735
+ <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />,
736
+ );
737
+ await screen.rerender(
738
+ <MessagesTimeline
739
+ {...base}
740
+ routeThreadKey={other}
741
+ timelineEntries={replies}
742
+ liveFollowEnabled={false}
743
+ findOpen
744
+ findExpanded
745
+ findQuery="Needle"
746
+ activeFindMatch={{ entryId: "entry-r-5", runId: null, occurrence: 0 }}
747
+ />,
748
+ );
749
+ const viewport = base.listRef.current!.getScrollableNode()!;
750
+ await vi.waitFor(() => {
751
+ const row = screen.container.querySelector('[data-timeline-row-id="entry-r-5"]');
752
+ expect(row).not.toBeNull();
753
+ const bounds = viewport.getBoundingClientRect();
754
+ const top = row!.getBoundingClientRect().top;
755
+ expect(top).toBeGreaterThanOrEqual(bounds.top);
756
+ expect(top).toBeLessThan(bounds.bottom);
757
+ });
758
+ });
759
+});
760
+
761
describe("compact reasoning math", () => {
762
it("keeps formulas while flattening compact reasoning previews", () => {
763
const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
apps/web/src/components/chat/MessagesTimeline.tsx
+240
-157
@@ -30,7 +30,6 @@ import {
30
memo,
31
use,
32
useContext,
33
- useEffect,
33
useLayoutEffect,
34
useRef,
35
useState,
@@ -78,7 +77,6 @@ import { useThreadFindNavigation } from "./useThreadFindNavigation";
77
import { TooltipScrollDismissArea } from "../ui/tooltip";
78
import { WorktreeSetupCard } from "./WorktreeSetupCard";
79
import { useOpenPrLink } from "~/lib/openPullRequestLink";
81
-import { useClientSettings } from "~/hooks/useSettings";
80
import { useMediaQuery } from "~/hooks/useMediaQuery";
81
import { cn } from "~/lib/utils";
82
import { type TimestampFormat } from "@t3tools/contracts/settings";
@@ -112,7 +110,13 @@ import {
110
McpAppTimelineRow,
111
} from "./TimelineAssistantRows";
112
import { V2EventTimelineRow } from "./TimelineV2EventRow";
115
-import { useTimelinePositionRestore } from "./useTimelinePositionRestore";
113
+import { startTimelinePositionRestore } from "./useTimelinePositionRestore";
114
+import {
115
+ attachTimelineViewport,
116
+ nextListOpening,
117
+ type TimelineListOpening,
118
+ type TimelineViewport,
119
+} from "./timelineViewport";
120
import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
121
import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer";
122
import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
@@ -260,9 +264,9 @@ interface MessagesTimelineProps {
264
liveFollowEnabled: boolean;
265
onContentOverflowChange?: (overflows: boolean) => void;
266
onToolOutputCollapsedAtEnd?: () => void;
263
- onManualNavigation: () => void;
267
+ /** Receives the list's viewport when it mounts; the returned cleanup runs when it goes away. */
268
+ onViewportAttach?: (viewport: TimelineViewport) => () => void;
269
findOpen?: boolean;
265
- cancelPositionRestoreRef?: React.RefObject<(() => void) | null> | undefined;
270
hideEmptyPlaceholder?: boolean;
271
/** Composer space to center the empty state against; held steady through collapse. */
272
emptyPlaceholderInset: number;
@@ -277,10 +281,6 @@ interface MessagesTimelineProps {
281
export function MessagesTimeline(props: MessagesTimelineProps) {
282
const find = useContext(ThreadFindTimelineContext);
283
const findOpen = find?.findOpen ?? props.findOpen;
280
- const { onManualNavigation } = props;
281
- useEffect(() => {
282
- if (findOpen) onManualNavigation();
283
- }, [findOpen, onManualNavigation]);
284
return (
285
<ConversationTimeline
286
{...props}
@@ -311,6 +311,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
311
awaitingRequestId = null,
312
listRef,
313
timelineEntries,
314
+ findOpen = false,
315
findExpanded = false,
316
findQuery = "",
317
activeFindMatch = null,
@@ -358,8 +359,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
359
onContentOverflowChange,
360
liveFollowEnabled,
361
onToolOutputCollapsedAtEnd,
361
- onManualNavigation,
362
- cancelPositionRestoreRef,
362
+ onViewportAttach,
363
hideEmptyPlaceholder = false,
364
emptyPlaceholderInset,
365
topFadeEnabled = false,
@@ -367,7 +367,12 @@ const ConversationTimeline = memo(function ConversationTimeline({
367
}: MessagesTimelineProps) {
368
const listIdentityKey = displayThreadKey ?? routeThreadKey;
369
// Snapshot restore positions on identity changes; ongoing scroll writes must not move them.
370
- const [listState, setListState] = useState(() => timelineListStateFor(listIdentityKey));
370
+ // Find open at the opening is part of the snapshot: opening find later
371
+ // announces its own navigation (threadFindStore's announceOpening).
372
+ const [listState, setListState] = useState(() => ({
373
+ ...timelineListStateFor(listIdentityKey),
374
+ findOpenAtOpening: findOpen,
375
+ }));
376
const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(
377
() => listState.rememberedPosition?.disclosures?.runs ?? new Set(),
378
);
@@ -377,8 +382,10 @@ const ConversationTimeline = memo(function ConversationTimeline({
382
const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(
383
() => listState.rememberedPosition?.disclosures?.attempts ?? new Set(),
384
);
385
+ // A list that opens on a thread with find open takes the opening step below,
386
+ // so the restore runs and releases follow once for find.
387
const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>
381
- listState.rememberedPosition?.atEnd === false ? null : listIdentityKey,
388
+ listState.rememberedPosition?.atEnd === false || findOpen ? null : listIdentityKey,
389
);
390
const restoringThreadPosition = positionedThreadKey !== listIdentityKey;
391
const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
@@ -386,6 +393,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
393
const [playingAudioRows, setPlayingAudioRows] = useState<ReadonlyMap<HTMLAudioElement, string>>(
394
() => new Map(),
395
);
396
+ const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
397
let paintedExpandedRunIds = expandedRunIds;
398
let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
399
let paintedExpandedAttemptIds = expandedAttemptIds;
@@ -395,9 +403,17 @@ const ConversationTimeline = memo(function ConversationTimeline({
403
: listState;
404
if (identityChanged) {
405
setPlayingAudioRows(new Map());
398
- setListState({ identity: listIdentityKey, rememberedPosition, workGroupViewState });
406
+ setListState({
407
+ identity: listIdentityKey,
408
+ rememberedPosition,
409
+ workGroupViewState,
410
+ findOpenAtOpening: findOpen,
411
+ });
412
setPositionedThreadKey(null);
413
setSettlingListIdentity(listIdentityKey);
414
+ // A viewer pinned in another thread must not keep live follow off here,
415
+ // nor when that thread comes back.
416
+ setFullscreenAppRowId(null);
417
paintedExpandedRunIds = rememberedPosition?.disclosures?.runs ?? new Set();
418
paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();
419
paintedExpandedAttemptIds = rememberedPosition?.disclosures?.attempts ?? new Set();
@@ -415,31 +431,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
431
const normalizedFindQuery = findQuery.trim();
432
const findActive = findExpanded;
433
418
- useEffect(() => {
419
- return () => {
420
- if (disclosureSettleFrameRef.current !== null) {
421
- cancelAnimationFrame(disclosureSettleFrameRef.current);
422
- }
423
- if (disclosureSettleSecondFrameRef.current !== null) {
424
- cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
425
- }
426
- };
427
- }, []);
428
-
429
- useEffect(() => {
430
- if (settlingListIdentity === null) return;
431
- let second: number | null = null;
432
- const first = requestAnimationFrame(() => {
433
- second = requestAnimationFrame(() => {
434
- setSettlingListIdentity((current) => (current === settlingListIdentity ? null : current));
435
- });
436
- });
437
- return () => {
438
- cancelAnimationFrame(first);
439
- if (second !== null) cancelAnimationFrame(second);
440
- };
441
- }, [settlingListIdentity]);
442
-
434
const disclosurePinsEndRef = useRef(false);
435
const disclosureCollapsedRef = useRef(false);
436
const pinDisclosureToEnd = () => {
@@ -525,32 +516,42 @@ const ConversationTimeline = memo(function ConversationTimeline({
516
});
517
};
518
528
- const previousLatestRunRef = useRef({ identity: listIdentityKey, run: latestRun });
529
- useEffect(() => {
530
- const { identity, run: previous } = previousLatestRunRef.current;
531
- previousLatestRunRef.current = { identity: listIdentityKey, run: latestRun };
532
- if (identity !== listIdentityKey || !latestRun || previous?.runId === undefined) {
533
- return;
534
- }
535
- if (latestRun.runId === previous.runId) {
536
- if (previous.status === "running" && latestRun.status === "interrupted") {
519
+ // An interrupted run opens its fold; a newer run closes the previous run's.
520
+ const [observedLatestRun, setObservedLatestRun] = useState({
521
+ identity: listIdentityKey,
522
+ runId: latestRun?.runId,
523
+ status: latestRun?.status,
524
+ });
525
+ if (
526
+ observedLatestRun.identity !== listIdentityKey ||
527
+ observedLatestRun.runId !== latestRun?.runId ||
528
+ observedLatestRun.status !== latestRun?.status
529
+ ) {
530
+ setObservedLatestRun({
531
+ identity: listIdentityKey,
532
+ runId: latestRun?.runId,
533
+ status: latestRun?.status,
534
+ });
535
+ const previousRunId = observedLatestRun.runId;
536
+ if (
537
+ observedLatestRun.identity === listIdentityKey &&
538
+ latestRun &&
539
+ previousRunId !== undefined
540
+ ) {
541
+ if (latestRun.runId === previousRunId) {
542
+ if (observedLatestRun.status === "running" && latestRun.status === "interrupted") {
543
+ setExpandedRunIds((existing) => new Set(existing).add(latestRun.runId));
544
+ }
545
+ } else {
546
setExpandedRunIds((existing) => {
547
+ if (!existing.has(previousRunId)) return existing;
548
const next = new Set(existing);
539
- next.add(latestRun.runId);
549
+ next.delete(previousRunId);
550
return next;
551
});
552
}
543
- return;
553
}
545
- setExpandedRunIds((existing) => {
546
- if (!existing.has(previous.runId)) {
547
- return existing;
548
- }
549
- const next = new Set(existing);
550
- next.delete(previous.runId);
551
- return next;
552
- });
553
- }, [latestRun, listIdentityKey]);
554
+ }
555
556
// Imported turns and post-steer work fold under synthetic keys, not the entries' run ids.
557
const findFoldRunIds = findActive
@@ -665,22 +666,53 @@ const ConversationTimeline = memo(function ConversationTimeline({
666
: -1;
667
const restoringAlwaysRender =
668
restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
668
- useTimelinePositionRestore({
669
- listRef,
669
+ const showsEmptyState =
670
+ rows.length === 0 &&
671
+ !isWorking &&
672
+ parentThreadLink === null &&
673
+ historyControls === undefined &&
674
+ footer === null;
675
+ const [listOpening, setListOpening] = useState<TimelineListOpening>(() =>
676
+ nextListOpening({ mounted: false }, !showsEmptyState, listIdentityKey),
677
+ );
678
+ const nextOpening = nextListOpening(listOpening, !showsEmptyState, listIdentityKey);
679
+ if (nextOpening !== listOpening) setListOpening(nextOpening);
680
+ const listOpenedOn = nextOpening.mounted ? nextOpening.identity : null;
681
+ const viewportRef = useRef<TimelineViewport | null>(null);
682
+ const navigateTimeline = () => viewportRef.current?.navigate({ releasesFollow: true });
683
+ const restoreReady = restoringThreadPosition && rows.length > 0;
684
+ // Z: syncs LegendList's scroll position with which thread it shows. The list
685
+ // is not keyed per thread and reports no "new data" event, and the restore
686
+ // must land before paint, after LegendList's own layout effects applied the
687
+ // new data. A citation request that arrives mid-restore takes over.
688
+ const { findOpenAtOpening } = identityChanged ? { findOpenAtOpening: findOpen } : listState;
689
+ useLayoutEffect(() => {
690
+ const list = listRef.current;
691
+ const viewport = viewportRef.current;
692
+ if (!restoreReady || !list || !viewport) return;
693
+ return startTimelinePositionRestore({
694
+ list,
695
+ viewport,
696
+ listIdentityKey,
697
+ listOpenedOn,
698
+ rememberedPosition,
699
+ citationPending: citationRequest !== null,
700
+ releaseForFind: findOpenAtOpening,
701
+ onPositioned: setPositionedThreadKey,
702
+ });
703
+ }, [
704
+ citationRequest,
705
+ findOpenAtOpening,
706
listIdentityKey,
671
- restoringThreadPosition,
707
+ listOpenedOn,
708
+ listRef,
709
rememberedPosition,
673
- rows,
674
- citationRequest,
675
- cancelPositionRestoreRef,
676
- onManualNavigation,
677
- onPositioned: setPositionedThreadKey,
678
- });
710
+ restoreReady,
711
+ ]);
712
713
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
714
null,
715
);
683
- const chatWidth = useClientSettings((settings) => settings.chatWidth);
716
const {
717
target: readyCitationRequest,
718
positioning: citationPositioning,
@@ -697,7 +729,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
729
})
730
: null,
731
viewport: timelineViewportElement,
700
- onManualNavigation,
732
+ onManualNavigation: navigateTimeline,
733
});
734
const [findListReady, setFindListReady] = useState(false);
735
const handleListLoad = () => {
@@ -705,7 +737,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
737
setFindListReady(true);
738
};
739
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
708
- const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
740
+ // Every full-screen viewer reports false when it unmounts, so a row that leaves the list
741
+ // while full screen releases its pin too.
742
const onAppFullscreenChange = (rowId: string, fullscreen: boolean) => {
743
setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
744
};
@@ -780,12 +813,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
813
onContentOverflowChange(measureContentOverflow());
814
});
815
};
783
- useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);
784
- useLayoutEffect(() => {
785
- cancelContentOverflowFrame();
786
- onContentOverflowChange?.(measureContentOverflow());
787
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.
788
- }, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);
816
817
const refreshMinimap = useStableCallback(() => {
818
const state = listRef.current?.getState?.();
@@ -841,34 +868,53 @@ const ConversationTimeline = memo(function ConversationTimeline({
868
});
869
};
870
844
- const handleScroll = () => {
871
+ // The measurement the last remember wrote, so a follow release can rewrite
872
+ // it without reading render state from a listener.
873
+ const lastRememberedRef = useRef<{
874
+ readonly data: unknown;
875
+ readonly threadKey: string;
876
+ readonly position: Parameters<typeof rememberTimelinePosition>[1];
877
+ } | null>(null);
878
+ const rememberPosition = (followingEnd: boolean) => {
879
const state = listRef.current?.getState?.();
880
if (restoringThreadPosition || state?.data !== rows) return;
881
const isAtEnd = resolveTimelineIsAtEnd(state);
848
- const position = state?.data?.length ? resolveWorkGroupScrollAnchor(state) : undefined;
849
- if (position && state && isAtEnd !== undefined && !paintOnly) {
882
+ const position = state.data.length ? resolveWorkGroupScrollAnchor(state) : undefined;
883
+ if (position && isAtEnd !== undefined && !paintOnly) {
884
const index = state.indexByKey(position.rowId);
885
const row = index === undefined ? undefined : state.elementAtIndex(index);
886
const element = listRef.current?.getScrollableNode();
887
if (row && element) {
854
- rememberTimelinePosition(
855
- listIdentityKey,
856
- {
857
- ...position,
858
- offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,
859
- scrollOffset: element.scrollTop,
860
- atEnd: isAtEnd,
861
- disclosures: {
862
- runs: paintedExpandedRunIds,
863
- workGroups: paintedExpandedWorkGroupIds,
864
- attempts: paintedExpandedAttemptIds,
865
- workGroupState: workGroupViewState,
866
- },
888
+ const measured = {
889
+ ...position,
890
+ offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,
891
+ scrollOffset: element.scrollTop,
892
+ atEnd: isAtEnd,
893
+ disclosures: {
894
+ runs: paintedExpandedRunIds,
895
+ workGroups: paintedExpandedWorkGroupIds,
896
+ attempts: paintedExpandedAttemptIds,
897
+ workGroupState: workGroupViewState,
898
},
868
- liveFollowEnabled && !anchoredEndSpace,
869
- );
899
+ };
900
+ lastRememberedRef.current = { data: rows, threadKey: listIdentityKey, position: measured };
901
+ rememberTimelinePosition(listIdentityKey, measured, followingEnd);
902
}
903
}
904
+ return isAtEnd;
905
+ };
906
+ // A follow release without a scroll after it would leave the position
907
+ // remembered as following.
908
+ const rememberReleasedPosition = () => {
909
+ const last = lastRememberedRef.current;
910
+ if (last && listRef.current?.getState().data === last.data) {
911
+ rememberTimelinePosition(last.threadKey, last.position, false);
912
+ }
913
+ };
914
+
915
+ const handleScroll = () => {
916
+ if (restoringThreadPosition || listRef.current?.getState?.().data !== rows) return;
917
+ const isAtEnd = rememberPosition(liveFollowEnabled && !anchoredEndSpace);
918
if (isAtEnd !== undefined && !citationPositioning) {
919
onIsAtEndChange(isAtEnd);
920
}
@@ -885,61 +931,55 @@ const ConversationTimeline = memo(function ConversationTimeline({
931
scheduleMinimapRefresh();
932
};
933
888
- useEffect(
889
- () => () => {
890
- if (minimapRefreshFrameRef.current !== null) {
891
- cancelAnimationFrame(minimapRefreshFrameRef.current);
892
- minimapRefreshFrameRef.current = null;
893
- }
894
- },
895
- [],
896
- );
897
-
898
- useEffect(() => {
899
- const frame = requestAnimationFrame(handleScroll);
900
- return () => cancelAnimationFrame(frame);
901
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows move the scroll position.
902
- }, [handleScroll, rows.length]);
903
-
904
- const savedLiveFollowEnabledRef = useRef(liveFollowEnabled);
905
- useLayoutEffect(() => {
906
- const wasFollowing = savedLiveFollowEnabledRef.current;
907
- savedLiveFollowEnabledRef.current = liveFollowEnabled;
908
- if (wasFollowing && !liveFollowEnabled) handleScroll();
909
- }, [handleScroll, liveFollowEnabled]);
910
-
911
- useEffect(() => {
912
- if (!timelineViewportElement) {
913
- return;
934
+ const measureTimelineGutter = (viewportElement: HTMLElement) => {
935
+ const viewportWidth = viewportElement.getBoundingClientRect().width;
936
+ const contentWidth =
937
+ viewportElement.querySelector<HTMLElement>("[data-timeline-root]")?.getBoundingClientRect()
938
+ .width ?? viewportWidth;
939
+ const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(
940
+ viewportWidth,
941
+ contentWidth,
942
+ );
943
+ setMinimapHasPersistentGutter((current) =>
944
+ current === nextHasPersistentGutter ? current : nextHasPersistentGutter,
945
+ );
946
+ setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth));
947
+ };
948
+ // Rows added, removed or rewrapped (chat width) change the content size,
949
+ // which moves the scroll position, the overflow, and the content lane width.
950
+ const handleContentSizeChanged = useStableCallback((laidOutData: unknown) => {
951
+ // The first laid-out content of a newly shown thread ends its settling; a
952
+ // frame the previous thread scheduled laid out the previous thread's rows.
953
+ if (laidOutData === rows) {
954
+ setSettlingListIdentity((current) => (current === listIdentityKey ? null : current));
955
}
915
-
916
- const measure = () => {
917
- const viewportWidth = timelineViewportElement.getBoundingClientRect().width;
918
- const contentWidth =
919
- timelineViewportElement
920
- .querySelector<HTMLElement>("[data-timeline-root]")
921
- ?.getBoundingClientRect().width ?? viewportWidth;
922
- const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(
923
- viewportWidth,
924
- contentWidth,
925
- );
926
- setMinimapHasPersistentGutter((current) =>
927
- current === nextHasPersistentGutter ? current : nextHasPersistentGutter,
928
- );
929
- setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth));
930
- reportContentOverflow();
931
- };
932
-
933
- const frame = requestAnimationFrame(measure);
934
-
935
- const stopObserving = observeResize(timelineViewportElement, measure);
936
-
956
+ handleScroll();
957
+ });
958
+ // The content lane only changes width with the viewport or the chat width
959
+ // setting, never with streamed content; measuring per content frame would
960
+ // force a layout on every chunk.
961
+ const measuredLaneWidthRef = useRef<number | null>(null);
962
+ const observeLaneWidth = (lane: HTMLDivElement | null) => {
963
+ if (!lane) return;
964
+ return observeResize(lane, (entries) => {
965
+ const width = entries.at(-1)?.contentRect.width;
966
+ if (width === undefined || width === measuredLaneWidthRef.current) return;
967
+ measuredLaneWidthRef.current = width;
968
+ const viewportElement = lane.closest<HTMLElement>("[data-assistant-citation-viewport]");
969
+ if (viewportElement) measureTimelineGutter(viewportElement);
970
+ });
971
+ };
972
+ const attachTimelineViewportElement = (viewportElement: HTMLDivElement | null) => {
973
+ setTimelineViewportElement(viewportElement);
974
+ if (!viewportElement) return;
975
+ const stopObserving = observeResize(viewportElement, () =>
976
+ measureTimelineGutter(viewportElement),
977
+ );
978
return () => {
938
- cancelAnimationFrame(frame);
979
stopObserving();
980
+ setTimelineViewportElement(null);
981
};
941
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Rows and chat width resize the content without resizing the viewport.
942
- }, [timelineViewportElement, rows.length, reportContentOverflow, chatWidth]);
982
+ };
983
984
const sharedState: TimelineRowSharedState = {
985
citationRequest: readyCitationRequest,
@@ -1049,11 +1089,55 @@ const ConversationTimeline = memo(function ConversationTimeline({
1089
const registerTimeline = canvas?.registerTimeline;
1090
const setTimelineList = (list: LegendListRef | null) => {
1091
listRef.current = list;
1052
- registerTimeline?.(list?.getScrollableNode() ?? null);
1092
+ const scrollNode: HTMLElement | null = list?.getScrollableNode() ?? null;
1093
+ registerTimeline?.(scrollNode);
1094
+ const viewport = scrollNode ? attachTimelineViewport(scrollNode) : null;
1095
+ viewportRef.current = viewport;
1096
+ const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined;
1097
+ const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition);
1098
+ let contentSizeFrame: number | null = null;
1099
+ // LegendList lays rows out from layout effects; the next frame sees them settled.
1100
+ let scheduledData: unknown = null;
1101
+ const scheduleContentSizeChanged = () => {
1102
+ if (!list) return;
1103
+ const laidOutData = list.getState().data;
1104
+ if (contentSizeFrame !== null) {
1105
+ if (scheduledData === laidOutData) return;
1106
+ cancelAnimationFrame(contentSizeFrame);
1107
+ }
1108
+ scheduledData = laidOutData;
1109
+ contentSizeFrame = requestAnimationFrame(() => {
1110
+ contentSizeFrame = null;
1111
+ handleContentSizeChanged(laidOutData);
1112
+ });
1113
+ };
1114
+ const stopListeningToContentSize = list
1115
+ ?.getState()
1116
+ .listen("totalSize", () => scheduleContentSizeChanged());
1117
+ scheduleContentSizeChanged();
1118
+ return () => {
1119
+ stopListeningToContentSize?.();
1120
+ stopRememberingRelease?.();
1121
+ onContentOverflowChange?.(false);
1122
+ if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame);
1123
+ detachViewport?.();
1124
+ viewport?.dispose();
1125
+ if (viewportRef.current === viewport) viewportRef.current = null;
1126
+ // Refresh frames only read the list; disclosure frames still run so the
1127
+ // settle flag clears.
1128
+ cancelContentOverflowFrame();
1129
+ if (minimapRefreshFrameRef.current !== null) {
1130
+ cancelAnimationFrame(minimapRefreshFrameRef.current);
1131
+ minimapRefreshFrameRef.current = null;
1132
+ }
1133
+ listRef.current = null;
1134
+ registerTimeline?.(null);
1135
+ };
1136
};
1137
1138
useThreadFindPositionReader({
1139
threadKey: listIdentityKey,
1140
+ navigate: navigateTimeline,
1141
timelineViewportElement,
1142
findFoldRunIds,
1143
timelineEntries,
@@ -1066,7 +1150,9 @@ const ConversationTimeline = memo(function ConversationTimeline({
1150
});
1151
1152
useThreadFindNavigation({
1069
- listReady: findListReady,
1153
+ // Find reveals its match only after the opening restore settles; both
1154
+ // scroll the list directly, so the restore would otherwise pull it back.
1155
+ listReady: findListReady && !restoringThreadPosition,
1156
historyControls,
1157
entries: timelineEntries,
1158
container: timelineViewportElement,
@@ -1108,6 +1194,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1194
onEndedCapture={(event) => onAudioPlaybackChange(item.id, event)}
1195
>
1196
<div
1197
+ ref={observeLaneWidth}
1198
className="@container/chat-lane chat-content-lane overflow-x-clip"
1199
data-timeline-root="true"
1200
>
@@ -1125,13 +1212,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1212
if (scrollNode) forwardWheelToTimeline(event, scrollNode);
1213
};
1214
1128
- if (
1129
- rows.length === 0 &&
1130
- !isWorking &&
1131
- parentThreadLink === null &&
1132
- historyControls === undefined &&
1133
- footer === null
1134
- ) {
1215
+ if (showsEmptyState) {
1216
if (hideEmptyPlaceholder) {
1217
return (
1218
<>
@@ -1159,7 +1240,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1240
<MarkdownFindContext value={findActive}>
1241
<TimelineRowActivityCtx value={activityState}>
1242
<TooltipScrollDismissArea
1162
- ref={setTimelineViewportElement}
1243
+ ref={attachTimelineViewportElement}
1244
className="relative h-full min-h-0"
1245
data-assistant-citation-viewport="true"
1246
>
@@ -1209,6 +1290,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
1290
maintainScrollAtEndThreshold={1}
1291
onScroll={handleScroll}
1292
onItemSizeChanged={handleItemSizeChanged}
1293
+ // A viewport resize changes how much of the content fits.
1294
+ onLayout={reportContentOverflow}
1295
className={cn(
1296
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
1297
topFadeEnabled && "topbar-scroll-fade",
@@ -1224,7 +1307,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1307
stripMap={minimapStripMap}
1308
onWheel={forwardMinimapWheel}
1309
onSelect={(item) => {
1227
- onManualNavigation();
1310
+ navigateTimeline();
1311
void listRef.current?.scrollToIndex({
1312
index: item.rowIndex,
1313
animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
apps/web/src/components/chat/threadFindStore.test.ts
+8
-3
@@ -19,21 +19,25 @@ const threadKey = "env-1:thread-1";
19
20
function setup() {
21
closeThreadFind();
22
+ const navigate = vi.fn();
23
const readPosition = vi.fn(() => ({ entryId: "entry-9", occurrence: 1 }));
23
- return { readPosition, timeline: { threadKey, readPosition } };
24
+ return { navigate, readPosition, timeline: { threadKey, navigate, readPosition } };
25
}
26
27
describe("thread find store", () => {
28
it("restarts an open query from the viewport of the timeline showing the thread", () => {
28
- const { readPosition, timeline } = setup();
29
+ const { navigate, readPosition, timeline } = setup();
30
const detach = attachThreadFindTimeline(timeline);
31
openThreadFind(threadKey);
32
+ // Opening find is manual navigation; reopening it is not.
33
+ expect(navigate).toHaveBeenCalledTimes(1);
34
expect(useThreadFindStore.getState()).toMatchObject({ threadKey, focusRequestId: 1 });
35
36
setThreadFindQuery(threadKey, " needle ");
37
expect(readPosition).toHaveBeenLastCalledWith("needle");
38
// Opening again refocuses and restarts the search from where the viewport is.
39
openThreadFind(threadKey);
40
+ expect(navigate).toHaveBeenCalledTimes(1);
41
expect(useThreadFindStore.getState()).toMatchObject({
42
query: " needle ",
43
focusRequestId: 2,
@@ -45,7 +49,7 @@ describe("thread find store", () => {
49
});
50
51
it("opens a search result's find for a thread before its timeline shows it", () => {
48
- const { readPosition, timeline } = setup();
52
+ const { navigate, readPosition, timeline } = setup();
53
const detach = attachThreadFindTimeline({ ...timeline, threadKey: "env-1:thread-2" });
54
openThreadFindOnQuery(threadKey, { query: "Café", start: { entryId: "m", occurrence: 0 } });
55
expect(useThreadFindStore.getState()).toMatchObject({
@@ -56,6 +60,7 @@ describe("thread find store", () => {
60
// Another thread's timeline does not answer for this one.
61
setThreadFindQuery(threadKey, "Caf");
62
expect(readPosition).not.toHaveBeenCalled();
63
+ expect(navigate).not.toHaveBeenCalled();
64
detach();
65
});
66
apps/web/src/components/chat/threadFindStore.ts
+14
@@ -49,6 +49,8 @@ export const useThreadFindStore = create<ThreadFindState>(() => CLOSED_THREAD_FI
49
interface ThreadFindTimeline {
50
readonly threadKey: string;
51
readonly readPosition: ThreadFindPositionReader;
52
+ /** Opening find is manual navigation: it releases live follow. */
53
+ readonly navigate: () => void;
54
}
55
56
let attachedTimeline: ThreadFindTimeline | null = null;
@@ -69,12 +71,23 @@ function readThreadFindPosition(threadKey: string, query: string): ThreadFindSta
71
return timelineFor(threadKey)?.readPosition(query);
72
}
73
74
+/**
75
+ * Navigates the timeline showing the thread when find newly opens there. A
76
+ * timeline that starts showing the thread later (a search result opened find
77
+ * before the route switched or the thread painted) releases follow itself as
78
+ * it opens on the thread.
79
+ */
80
+function announceOpening(previous: ThreadFindState, threadKey: string): void {
81
+ if (previous.threadKey !== threadKey) timelineFor(threadKey)?.navigate();
82
+}
83
+
84
/** Opens find, or refocuses it and restarts its search from the viewport when already open. */
85
export function openThreadFind(threadKey: string): void {
86
const previous = useThreadFindStore.getState();
87
const current = previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND;
88
const query = current.query.trim();
89
const start = query ? readThreadFindPosition(threadKey, query) : undefined;
90
+ announceOpening(previous, threadKey);
91
useThreadFindStore.setState({
92
...current,
93
threadKey,
@@ -103,6 +116,7 @@ export interface PendingThreadFind {
116
*/
117
export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind): void {
118
const previous = useThreadFindStore.getState();
119
+ announceOpening(previous, threadKey);
120
useThreadFindStore.setState({
121
...(previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND),
122
threadKey,
apps/web/src/components/chat/timelineViewport.test.ts
new
+103
@@ -0,0 +1,103 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import {
4
+ FOLLOWING,
5
+ initialTimelineFollow,
6
+ navigationReleasesFollow,
7
+ nextListOpening,
8
+ transitionTimelineFollow,
9
+ type TimelineFollow,
10
+ type TimelineListOpening,
11
+} from "./timelineViewport";
12
+
13
+describe("nextListOpening", () => {
14
+ const unmounted: TimelineListOpening = { mounted: false };
15
+
16
+ it("records the thread a list mounts on", () => {
17
+ expect(nextListOpening(unmounted, true, "a")).toEqual({ mounted: true, identity: "a" });
18
+ });
19
+
20
+ it("drops the opening once the list shows another thread, even after returning", () => {
21
+ const switched = nextListOpening({ mounted: true, identity: "a" }, true, "b");
22
+ expect(switched).toEqual({ mounted: true, identity: null });
23
+ expect(nextListOpening(switched, true, "a")).toBe(switched);
24
+ });
25
+
26
+ it("records a fresh opening after the list unmounts and remounts", () => {
27
+ const gone = nextListOpening({ mounted: true, identity: null }, false, "b");
28
+ expect(gone).toEqual(unmounted);
29
+ expect(nextListOpening(gone, true, "b")).toEqual({ mounted: true, identity: "b" });
30
+ });
31
+
32
+ it("keeps the same state object when nothing changes", () => {
33
+ const opened: TimelineListOpening = { mounted: true, identity: "a" };
34
+ expect(nextListOpening(opened, true, "a")).toBe(opened);
35
+ expect(nextListOpening(unmounted, false, "a")).toBe(unmounted);
36
+ });
37
+});
38
+
39
+describe("transitionTimelineFollow", () => {
40
+ const releasedAtEnd: TimelineFollow = { mode: "released", atEnd: true };
41
+ const releasedAway: TimelineFollow = { mode: "released", atEnd: false };
42
+
43
+ it("releases on navigation and stays released", () => {
44
+ expect(transitionTimelineFollow(FOLLOWING, { type: "navigated" })).toEqual(releasedAtEnd);
45
+ expect(transitionTimelineFollow(releasedAway, { type: "navigated" })).toBe(releasedAway);
46
+ });
47
+
48
+ it("ignores the end band flicker while following", () => {
49
+ expect(transitionTimelineFollow(FOLLOWING, { type: "leftEnd" })).toBe(FOLLOWING);
50
+ });
51
+
52
+ it("re-arms only after the released view leaves the end and comes back", () => {
53
+ expect(transitionTimelineFollow(releasedAtEnd, { type: "reachedEnd" })).toBe(releasedAtEnd);
54
+ const away = transitionTimelineFollow(releasedAtEnd, { type: "leftEnd" });
55
+ expect(away).toEqual(releasedAway);
56
+ expect(transitionTimelineFollow(away, { type: "reachedEnd" })).toBe(FOLLOWING);
57
+ });
58
+
59
+ it("follows the end on request from any state", () => {
60
+ expect(transitionTimelineFollow(releasedAway, { type: "followEnd" })).toBe(FOLLOWING);
61
+ });
62
+
63
+ it("starts a thread visit from its remembered position", () => {
64
+ expect(initialTimelineFollow(true)).toBe(FOLLOWING);
65
+ expect(initialTimelineFollow(false)).toEqual(releasedAway);
66
+ });
67
+});
68
+
69
+describe("navigationReleasesFollow", () => {
70
+ const viewport = (contentScrollsUp: boolean, awayFromEnd: boolean) => ({
71
+ contentScrollsUp: () => contentScrollsUp,
72
+ awayFromEnd: () => awayFromEnd,
73
+ });
74
+
75
+ it("releases on upward input only when the content can scroll up", () => {
76
+ const up = { source: "wheel", direction: "up" } as const;
77
+ expect(navigationReleasesFollow(up, viewport(true, false))).toBe(true);
78
+ expect(navigationReleasesFollow(up, viewport(false, true))).toBe(false);
79
+ expect(
80
+ navigationReleasesFollow({ source: "wheel", direction: "down" }, viewport(true, true)),
81
+ ).toBe(false);
82
+ });
83
+
84
+ it("releases on downward keys, touch and row clicks only away from the end", () => {
85
+ const down = { source: "key", key: "PageDown", direction: "down" } as const;
86
+ expect(navigationReleasesFollow(down, viewport(true, false))).toBe(false);
87
+ expect(navigationReleasesFollow(down, viewport(false, true))).toBe(true);
88
+ expect(navigationReleasesFollow({ source: "touch" }, viewport(true, false))).toBe(false);
89
+ expect(
90
+ navigationReleasesFollow({ source: "pointer", onScrollbar: false }, viewport(true, false)),
91
+ ).toBe(false);
92
+ expect(
93
+ navigationReleasesFollow({ source: "pointer", onScrollbar: true }, viewport(true, false)),
94
+ ).toBe(true);
95
+ });
96
+
97
+ it("lets commands decide for themselves", () => {
98
+ expect(
99
+ navigationReleasesFollow({ source: "command", releasesFollow: false }, viewport(true, true)),
100
+ ).toBe(false);
101
+ expect(navigationReleasesFollow({ source: "scroll" }, viewport(false, false))).toBe(true);
102
+ });
103
+});
apps/web/src/components/chat/timelineViewport.ts
new
+243
@@ -0,0 +1,243 @@
1
+import { registerCommands } from "../../shortcuts/dispatcher";
2
+import {
3
+ eventPathContainsSelector,
4
+ TYPE_TO_FOCUS_EDITABLE_SELECTOR,
5
+ TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
6
+} from "./composerFocusRedirect";
7
+import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
8
+import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
9
+
10
+/**
11
+ * Which thread the mounted timeline list opened on. LegendList's
12
+ * initialScrollAtEnd only measures for that thread; once the same list shows
13
+ * another thread the opening no longer applies, even if it later returns.
14
+ */
15
+export type TimelineListOpening =
16
+ | { readonly mounted: false }
17
+ | { readonly mounted: true; readonly identity: string | null };
18
+
19
+export function nextListOpening(
20
+ current: TimelineListOpening,
21
+ listMounted: boolean,
22
+ identity: string,
23
+): TimelineListOpening {
24
+ if (!listMounted) return current.mounted ? { mounted: false } : current;
25
+ if (!current.mounted) return { mounted: true, identity };
26
+ if (current.identity !== null && current.identity !== identity) {
27
+ return { mounted: true, identity: null };
28
+ }
29
+ return current;
30
+}
31
+
32
+export type TimelineScrollDirection = "up" | "down";
33
+
34
+/**
35
+ * One user attempt to move the timeline. Gestures come from the viewport's own
36
+ * listeners; "command" is a UI action that is about to move it (minimap,
37
+ * citation, composer page keys, scroll to end).
38
+ */
39
+export type TimelineNavigation =
40
+ | { readonly source: "wheel"; readonly direction: TimelineScrollDirection }
41
+ | { readonly source: "touch" }
42
+ | { readonly source: "pointer"; readonly onScrollbar: boolean }
43
+ | { readonly source: "key"; readonly key: string; readonly direction: TimelineScrollDirection }
44
+ | { readonly source: "scroll" }
45
+ | { readonly source: "command"; readonly releasesFollow: boolean };
46
+
47
+export interface TimelineViewport {
48
+ readonly scrollNode: HTMLElement;
49
+ /** Every consumer hears the same navigation, in subscription order. */
50
+ readonly subscribe: (listener: (navigation: TimelineNavigation) => void) => () => void;
51
+ readonly navigate: (options: { readonly releasesFollow: boolean }) => void;
52
+ /**
53
+ * Marks our own scrolling (anchoring a turn, restoring a position) so the
54
+ * upward scroll it causes is not read as the user's. Returns the release.
55
+ */
56
+ readonly holdProgrammaticScroll: () => () => void;
57
+ /** Follow announces letting go, so the list can remember it is reading history. */
58
+ readonly followReleased: () => void;
59
+ readonly onFollowReleased: (listener: () => void) => () => void;
60
+}
61
+
62
+const UP_KEYS = new Set(["PageUp", "Home", "ArrowUp"]);
63
+const DOWN_KEYS = new Set(["PageDown", "End", "ArrowDown", " "]);
64
+
65
+/**
66
+ * Owns the timeline scroll node's input listeners for as long as the node is
67
+ * mounted, and turns them into one navigation signal.
68
+ */
69
+export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewport & {
70
+ readonly dispose: () => void;
71
+} {
72
+ const listeners = new Set<(navigation: TimelineNavigation) => void>();
73
+ const followReleasedListeners = new Set<() => void>();
74
+ let programmaticHolds = 0;
75
+ const emit = (navigation: TimelineNavigation) => {
76
+ for (const listener of listeners) listener(navigation);
77
+ };
78
+ const handleWheel = (event: WheelEvent) => {
79
+ if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY)) return;
80
+ emit({ source: "wheel", direction: event.deltaY < 0 ? "up" : "down" });
81
+ };
82
+ const handleTouchMove = () => emit({ source: "touch" });
83
+ // Scrollbar drags produce no wheel/touch events; they are the only
84
+ // pointerdowns whose target is the scroll node itself rather than a row.
85
+ const handlePointerDown = (event: PointerEvent) =>
86
+ emit({ source: "pointer", onScrollbar: event.target === scrollNode });
87
+ // Clicking message text can leave DOM focus on body, and keyboard scrolling
88
+ // bypasses wheel and pointer events, so scroll keys are heard app-wide.
89
+ const handleKeyDown = (event: KeyboardEvent, consumed: boolean) => {
90
+ const direction = UP_KEYS.has(event.key) ? "up" : DOWN_KEYS.has(event.key) ? "down" : null;
91
+ if (
92
+ direction === null ||
93
+ consumed ||
94
+ !(event.target instanceof Node) ||
95
+ (!scrollNode.contains(event.target) &&
96
+ event.target !== document.body &&
97
+ event.target !== document.documentElement) ||
98
+ event.isComposing ||
99
+ event.altKey ||
100
+ event.ctrlKey ||
101
+ event.metaKey ||
102
+ event.shiftKey ||
103
+ eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
104
+ document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR) ||
105
+ (scrollNode.contains(event.target) &&
106
+ !isTimelineScrollTarget(event.target, scrollNode, direction === "up" ? -1 : 1))
107
+ ) {
108
+ return;
109
+ }
110
+ emit({ source: "key", key: event.key, direction });
111
+ };
112
+ // Input inside an embedded frame reaches none of the listeners above, but
113
+ // its scroll still chains out to the timeline.
114
+ const scrolledUp = createUpwardScrollDetector({
115
+ top: scrollNode.scrollTop,
116
+ height: scrollNode.scrollHeight,
117
+ });
118
+ const handleScroll = () => {
119
+ if (
120
+ scrolledUp({
121
+ top: scrollNode.scrollTop,
122
+ height: scrollNode.scrollHeight,
123
+ programmatic: programmaticHolds > 0,
124
+ }) &&
125
+ // LegendList updates its scroll state on the next animation frame.
126
+ resolveTimelineIsAtEnd({
127
+ contentLength: scrollNode.scrollHeight,
128
+ scroll: scrollNode.scrollTop,
129
+ scrollLength: scrollNode.clientHeight,
130
+ }) === false
131
+ ) {
132
+ emit({ source: "scroll" });
133
+ }
134
+ };
135
+ scrollNode.addEventListener("scroll", handleScroll, { passive: true });
136
+ scrollNode.addEventListener("wheel", handleWheel, { passive: true });
137
+ scrollNode.addEventListener("touchmove", handleTouchMove, { passive: true });
138
+ scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true });
139
+ const unregisterKeyDown = registerCommands({}, { observe: handleKeyDown });
140
+ return {
141
+ scrollNode,
142
+ subscribe: (listener) => {
143
+ listeners.add(listener);
144
+ return () => listeners.delete(listener);
145
+ },
146
+ navigate: ({ releasesFollow }) => emit({ source: "command", releasesFollow }),
147
+ holdProgrammaticScroll: () => {
148
+ programmaticHolds += 1;
149
+ let released = false;
150
+ return () => {
151
+ if (released) return;
152
+ released = true;
153
+ programmaticHolds -= 1;
154
+ };
155
+ },
156
+ followReleased: () => {
157
+ for (const listener of followReleasedListeners) listener();
158
+ },
159
+ onFollowReleased: (listener) => {
160
+ followReleasedListeners.add(listener);
161
+ return () => followReleasedListeners.delete(listener);
162
+ },
163
+ dispose: () => {
164
+ listeners.clear();
165
+ followReleasedListeners.clear();
166
+ scrollNode.removeEventListener("scroll", handleScroll);
167
+ scrollNode.removeEventListener("wheel", handleWheel);
168
+ scrollNode.removeEventListener("touchmove", handleTouchMove);
169
+ scrollNode.removeEventListener("pointerdown", handlePointerDown);
170
+ unregisterKeyDown();
171
+ },
172
+ };
173
+}
174
+
175
+/**
176
+ * Whether a navigation can carry the viewport away from the live edge. A spurious
177
+ * release while pinned never re-arms, so streaming stops following. Downward input
178
+ * counts only outside the end band: streaming growth makes isAtEnd flicker false
179
+ * for a frame, and a gesture then must not release follow.
180
+ */
181
+export function navigationReleasesFollow(
182
+ navigation: TimelineNavigation,
183
+ viewport: { readonly contentScrollsUp: () => boolean; readonly awayFromEnd: () => boolean },
184
+): boolean {
185
+ switch (navigation.source) {
186
+ case "wheel":
187
+ return navigation.direction === "up" && viewport.contentScrollsUp();
188
+ case "key":
189
+ return navigation.direction === "up" ? viewport.contentScrollsUp() : viewport.awayFromEnd();
190
+ case "pointer":
191
+ return navigation.onScrollbar ? viewport.contentScrollsUp() : viewport.awayFromEnd();
192
+ case "touch":
193
+ // Touch direction is not observable; an upward flick leaves the end
194
+ // band within its first few events.
195
+ return viewport.awayFromEnd();
196
+ case "scroll":
197
+ return true;
198
+ case "command":
199
+ return navigation.releasesFollow;
200
+ }
201
+}
202
+
203
+/**
204
+ * Whether the timeline keeps the live end in view. An anchored new turn is
205
+ * following with an anchor present (the anchor lives with the thread's
206
+ * timeline state). `atEnd` only matters once released: while following, the
207
+ * list is at its end by definition.
208
+ */
209
+export type TimelineFollow =
210
+ | { readonly mode: "following" }
211
+ | { readonly mode: "released"; readonly atEnd: boolean };
212
+
213
+export type TimelineFollowEvent =
214
+ | { readonly type: "navigated" }
215
+ | { readonly type: "followEnd" }
216
+ | { readonly type: "reachedEnd" }
217
+ | { readonly type: "leftEnd" };
218
+
219
+export const FOLLOWING: TimelineFollow = { mode: "following" };
220
+
221
+export function initialTimelineFollow(followEnd: boolean): TimelineFollow {
222
+ return followEnd ? FOLLOWING : { mode: "released", atEnd: false };
223
+}
224
+
225
+export function transitionTimelineFollow(
226
+ state: TimelineFollow,
227
+ event: TimelineFollowEvent,
228
+): TimelineFollow {
229
+ switch (event.type) {
230
+ case "navigated":
231
+ return state.mode === "released" ? state : { mode: "released", atEnd: true };
232
+ case "followEnd":
233
+ return FOLLOWING;
234
+ case "reachedEnd":
235
+ // Navigating away while still at the end stays released until the list
236
+ // reports leaving and returning, so a scroll key at the end cannot re-arm.
237
+ return state.mode === "released" && !state.atEnd ? FOLLOWING : state;
238
+ case "leftEnd":
239
+ // While following, the list leaves the end band for a frame on every
240
+ // streamed chunk before the follow scroll catches up.
241
+ return state.mode === "released" && state.atEnd ? { mode: "released", atEnd: false } : state;
242
+ }
243
+}
apps/web/src/components/chat/useThreadFindPositionReader.ts
+4
-1
@@ -13,6 +13,7 @@ import { readThreadFindPosition } from "./threadFindPosition";
13
/** Hands thread find how to read the find position of this timeline's viewport. */
14
export function useThreadFindPositionReader({
15
threadKey,
16
+ navigate,
17
timelineViewportElement,
18
findFoldRunIds,
19
timelineEntries,
@@ -24,6 +25,7 @@ export function useThreadFindPositionReader({
25
contentInsetEndAdjustment,
26
}: {
27
readonly threadKey: string;
28
+ readonly navigate: () => void;
29
readonly timelineViewportElement: HTMLDivElement | null;
30
readonly findFoldRunIds: ReadonlyMap<string, RunId> | null;
31
readonly timelineEntries: ReadonlyArray<TimelineEntry>;
@@ -83,11 +85,12 @@ export function useThreadFindPositionReader({
85
contentInsetEndAdjustment,
86
);
87
};
86
- return attachThreadFindTimeline({ threadKey, readPosition: read });
88
+ return attachThreadFindTimeline({ threadKey, readPosition: read, navigate });
89
}, [
90
contentInsetEndAdjustment,
91
findFoldRunIds,
92
isWorking,
93
+ navigate,
94
threadKey,
95
latestRun,
96
rows,
apps/web/src/components/chat/useTimelineFollow.ts
+331
-423
@@ -1,19 +1,13 @@
1
import { useStableCallback } from "../../hooks/useStableCallback";
2
-import {
3
- eventPathContainsSelector,
4
- TYPE_TO_FOCUS_EDITABLE_SELECTOR,
5
- TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
6
-} from "./composerFocusRedirect";
7
-import { type MessageId, type ThreadId, type RunId } from "@t3tools/contracts";
2
+import { type MessageId, type RunId } from "@t3tools/contracts";
3
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
4
import { Debouncer } from "@tanstack/react-pacer";
5
import {
6
type SetStateAction,
12
- useEffect,
13
- useEffectEvent,
7
useLayoutEffect,
8
useRef,
9
useState,
10
+ useSyncExternalStore,
11
} from "react";
12
import { type LegendListRef } from "@legendapp/list/react";
13
import {
@@ -22,15 +16,25 @@ import {
16
readTimelinePosition,
17
observeTimelineRun,
18
type TimelineRunObservation,
25
- type TimelineScrollMode,
19
} from "./timelineScrollAnchoring";
20
import { type ChatComposerHandle } from "./ChatComposer";
21
import { createPageScrollController, type PageScrollKey } from "./pageScrollController";
29
-import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
30
-import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
22
+import {
23
+ FOLLOWING,
24
+ initialTimelineFollow,
25
+ navigationReleasesFollow,
26
+ transitionTimelineFollow,
27
+ type TimelineFollow,
28
+ type TimelineFollowEvent,
29
+ type TimelineNavigation,
30
+ type TimelineViewport,
31
+} from "./timelineViewport";
32
+import { resolveTimelineIsAtEnd, type MessagesTimelineRow } from "./MessagesTimeline.logic";
33
import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";
32
-import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
33
-import { releaseChatTimelineAnchor } from "../ChatView.logic";
34
+import {
35
+ releaseChatTimelineAnchor,
36
+ shouldReleaseTimelineAnchorForToolActivity,
37
+} from "../ChatView.logic";
38
import type { Dispatch, RefObject } from "react";
39
import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
40
import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
@@ -44,14 +48,110 @@ interface TimelineAnchor {
48
readonly messageId: MessageId | null;
49
}
50
51
+/** One visit to a thread; a switch starts a new one from the remembered position. */
52
+interface TimelineFollowVisit {
53
+ readonly threadKey: string | null;
54
+ readonly followEnd: boolean;
55
+}
56
+
57
+/**
58
+ * Scroll bookkeeping that belongs to one visit. Handlers fetch it for the
59
+ * current visit, so a thread switch leaves the old one behind instead of
60
+ * resetting it.
61
+ */
62
+function createVisitScrollState(
63
+ visit: TimelineFollowVisit,
64
+ showScrollToBottom: (visit: TimelineFollowVisit) => void,
65
+) {
66
+ return {
67
+ visit,
68
+ intent: null as "toward-end" | "away-from-end" | null,
69
+ // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
70
+ // thread switches. LegendList fires scroll events with isAtEnd=false while
71
+ // initialScrollAtEnd is settling; hiding is always immediate.
72
+ showScrollDebouncer: new Debouncer(() => showScrollToBottom(visit), { wait: 150 }),
73
+ positionedAnchor: null as MessageId | null,
74
+ settledAnchor: null as MessageId | null,
75
+ releaseAnchorScrollHold: null as (() => void) | null,
76
+ pendingAnchorScrollRestore: null as {
77
+ readonly messageId: MessageId;
78
+ readonly offset: number;
79
+ } | null,
80
+ anchorScrollRestoreFrame: null as number | null,
81
+ };
82
+}
83
+type VisitScrollState = ReturnType<typeof createVisitScrollState>;
84
+
85
+function stopAnchorPositioning(scroll: VisitScrollState) {
86
+ scroll.positionedAnchor = null;
87
+ scroll.settledAnchor = null;
88
+ scroll.releaseAnchorScrollHold?.();
89
+ scroll.releaseAnchorScrollHold = null;
90
+}
91
+
92
+/** Whether the list still shows the anchored message; a thread switch replaces its data. */
93
+function listShowsMessage(list: LegendListRef | null, messageId: MessageId): boolean {
94
+ const rows = list?.getState().data as ReadonlyArray<MessagesTimelineRow> | undefined;
95
+ return rows?.some((row) => row.kind === "message" && row.message.id === messageId) === true;
96
+}
97
+
98
+/**
99
+ * The follow mode, read by scroll listeners at event time and by render
100
+ * through useSyncExternalStore. State recorded for an earlier visit is
101
+ * discarded, so a thread switch needs no reset step.
102
+ */
103
+function createTimelineFollowStore() {
104
+ let snapshot: { readonly visit: TimelineFollowVisit | null; readonly follow: TimelineFollow } = {
105
+ visit: null,
106
+ follow: FOLLOWING,
107
+ };
108
+ const listeners = new Set<() => void>();
109
+ // Page keys read the overlay at keypress time; it changes no rendered state.
110
+ let composerOverlay: HTMLElement | null = null;
111
+ const read = (visit: TimelineFollowVisit) =>
112
+ snapshot.visit === visit ? snapshot.follow : initialTimelineFollow(visit.followEnd);
113
+ return {
114
+ subscribe: (listener: () => void) => {
115
+ listeners.add(listener);
116
+ return () => listeners.delete(listener);
117
+ },
118
+ snapshot: () => snapshot,
119
+ read,
120
+ /** Ref callback for the composer overlay. */
121
+ attachComposerOverlay: (element: HTMLElement | null) => {
122
+ composerOverlay = element;
123
+ },
124
+ readComposerOverlayHeight: () => composerOverlay?.getBoundingClientRect().height ?? 0,
125
+ dispatch: (visit: TimelineFollowVisit, event: TimelineFollowEvent) => {
126
+ const before = read(visit);
127
+ const after = transitionTimelineFollow(before, event);
128
+ if (snapshot.visit !== visit || after !== snapshot.follow) {
129
+ snapshot = { visit, follow: after };
130
+ for (const listener of listeners) listener();
131
+ }
132
+ return { before, after };
133
+ },
134
+ };
135
+}
136
+
137
+function sameRunObservation(
138
+ next: TimelineRunObservation,
139
+ previous: TimelineRunObservation | null,
140
+): boolean {
141
+ return (
142
+ previous !== null &&
143
+ next.threadKey === previous.threadKey &&
144
+ next.hydrated === previous.hydrated &&
145
+ next.runId === previous.runId
146
+ );
147
+}
148
+
149
interface TimelineFollowInput {
150
readonly legendListRef: RefObject<LegendListRef | null>;
151
readonly composerRef: RefObject<ChatComposerHandle | null>;
50
- readonly composerOverlayElement: HTMLDivElement | null;
152
readonly composerTimelineInset: number;
153
readonly routeThreadKey: string;
154
readonly activeThreadKey: string | null;
54
- readonly activeThreadId: ThreadId | undefined;
155
readonly isServerThread: boolean;
156
readonly serverProjection: ThreadStructure | null;
157
readonly threadStatus: EnvironmentThreadStatus;
@@ -64,18 +164,17 @@ interface TimelineFollowInput {
164
165
/**
166
* Keeps the timeline following the live end, anchoring a newly sent turn near
67
- * the top, and letting the user scroll away. The scroll handlers read refs, so
68
- * a scroll gesture does not re-render ChatView unless the follow mode flips.
167
+ * the top, and letting the user scroll away. Follow lives in a store the
168
+ * viewport's navigation signal writes, so a scroll gesture does not re-render
169
+ * ChatView unless the follow mode flips.
170
*/
171
export function useTimelineFollow(input: TimelineFollowInput) {
172
const {
173
legendListRef,
174
composerRef,
74
- composerOverlayElement,
175
composerTimelineInset,
176
routeThreadKey,
177
activeThreadKey,
78
- activeThreadId,
178
isServerThread,
179
serverProjection,
180
threadStatus,
@@ -85,54 +184,75 @@ export function useTimelineFollow(input: TimelineFollowInput) {
184
timelineAnchorMessageId,
185
setTimelineAnchor,
186
} = input;
88
- const [showScrollToBottom, setShowScrollToBottom] = useState(false);
89
- const isAtEndRef = useRef(true);
90
- const isTimelineAtLogicalEnd = () =>
91
- resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
92
- const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
93
- // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
94
- // thread switches. LegendList fires scroll events with isAtEnd=false while
95
- // initialScrollAtEnd is settling; hiding is always immediate.
96
- const showScrollDebouncer = useRef(
97
- new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
187
+ const [visitState, setVisit] = useState<TimelineFollowVisit>({
188
+ threadKey: activeThreadKey,
189
+ followEnd: true,
190
+ });
191
+ let visit = visitState;
192
+ if (visit.threadKey !== activeThreadKey) {
193
+ visit = {
194
+ threadKey: activeThreadKey,
195
+ followEnd: readTimelinePosition(routeThreadKey)?.atEnd !== false,
196
+ };
197
+ setVisit(visit);
198
+ }
199
+ // Keyed by visit, so a pill decision from the previous thread (a pending
200
+ // debounce) never shows here.
201
+ const [pill, setPill] = useState<{ readonly visit: TimelineFollowVisit; readonly show: boolean }>(
202
+ { visit, show: false },
203
);
99
- const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);
100
- const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
101
- // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
102
- // re-pins on its own (independent of the refs), so the timeline needs a
103
- // render-visible flag to switch it off once the user scrolls away.
104
- const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
105
- const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
106
- const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
107
- const settledTimelineAnchorRef = useRef<MessageId | null>(null);
108
- const activeTimelineAnchorIndexRef = useRef<number | null>(null);
109
- const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);
110
- const anchorUserScrollGenerationRef = useRef(0);
111
- const cancelPositionRestoreRef = useRef<(() => void) | null>(null);
112
- const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
113
- const pendingAnchorScrollRestoreRef = useRef<{
114
- readonly messageId: MessageId;
115
- readonly offset: number;
116
- readonly userScrollGeneration: number;
117
- } | null>(null);
118
- const anchorScrollRestoreFrameRef = useRef<number | null>(null);
119
- const cancelTimelineLiveFollowForUserNavigation = () => {
120
- cancelPositionRestoreRef.current?.();
121
- anchorUserScrollGenerationRef.current += 1;
122
- const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
123
- timelineScrollModeRef.current = "free-scrolling";
124
- liveFollowUserScrollGenerationRef.current = null;
125
- setTimelineLiveFollowEnabled(false);
126
- pendingTimelineAnchorRef.current = null;
127
- positionedTimelineAnchorRef.current = null;
128
- settledTimelineAnchorRef.current = null;
129
- activeTimelineAnchorIndexRef.current = null;
130
- pendingAnchorScrollRestoreRef.current = null;
131
- if (anchorScrollRestoreFrameRef.current !== null) {
132
- cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
133
- anchorScrollRestoreFrameRef.current = null;
204
+ const showScrollToBottom = pill.visit === visit ? pill.show : !visit.followEnd;
205
+ // Called on every streamed chunk while following; an unchanged pill must
206
+ // bail out instead of re-rendering ChatView.
207
+ const setShowScrollToBottom = (show: boolean) =>
208
+ setPill((current) =>
209
+ current.visit === visit && current.show === show ? current : { visit, show },
210
+ );
211
+ const [followStore] = useState(createTimelineFollowStore);
212
+ const followSnapshot = useSyncExternalStore(followStore.subscribe, followStore.snapshot);
213
+ const follow =
214
+ followSnapshot.visit === visit ? followSnapshot.follow : initialTimelineFollow(visit.followEnd);
215
+ const timelineLiveFollowEnabled = follow.mode === "following";
216
+ const readFollow = () => followStore.read(visit);
217
+ // Async settles outlive their render; this reads the visit shown now.
218
+ const readCurrentFollow = useStableCallback(readFollow);
219
+ const isTimelineAtLogicalEnd = () => {
220
+ const current = readFollow();
221
+ return (
222
+ resolveTimelineIsAtEnd(legendListRef.current?.getState()) ??
223
+ (current.mode === "following" || current.atEnd)
224
+ );
225
+ };
226
+ const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
227
+ const visitScrollRef = useRef<VisitScrollState | null>(null);
228
+ /** Only from handlers: the bookkeeping of the visit they run in. */
229
+ const visitScroll = () => {
230
+ if (visitScrollRef.current?.visit !== visit) {
231
+ visitScrollRef.current = createVisitScrollState(visit, (shownVisit) => {
232
+ // A debounce that outlived its visit must not overwrite the current one's pill.
233
+ if (visitScrollRef.current?.visit === shownVisit)
234
+ setPill({ visit: shownVisit, show: true });
235
+ });
236
}
135
- if (wasProgrammaticScrollMode) {
237
+ return visitScrollRef.current;
238
+ };
239
+ // The anchor whose list position LegendList reported ready; until then a
240
+ // newly started run must not re-anchor.
241
+ const [laidOutAnchor, setLaidOutAnchor] = useState<MessageId | null>(null);
242
+ const anchorPending =
243
+ timelineAnchorMessageId !== null && laidOutAnchor !== timelineAnchorMessageId;
244
+ const viewportRef = useRef<TimelineViewport | null>(null);
245
+ const releaseFollowForNavigation = () => {
246
+ const { before } = followStore.dispatch(visit, { type: "navigated" });
247
+ if (before.mode === "following") viewportRef.current?.followReleased();
248
+ const scroll = visitScroll();
249
+ stopAnchorPositioning(scroll);
250
+ scroll.pendingAnchorScrollRestore = null;
251
+ if (scroll.anchorScrollRestoreFrame !== null) {
252
+ cancelAnimationFrame(scroll.anchorScrollRestoreFrame);
253
+ scroll.anchorScrollRestoreFrame = null;
254
+ }
255
+ if (before.mode === "following") {
256
// LegendList may run queued scrolls after user navigation. A new imperative
257
// scroll cancels that queue; a missing item cancels without moving the view.
258
void legendListRef.current?.scrollToItem({
@@ -152,96 +272,51 @@ export function useTimelineFollow(input: TimelineFollowInput) {
272
}
273
}
274
};
155
- const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
156
- cancelTimelineLiveFollowForUserNavigation,
157
- );
158
- const cancelTimelineLiveFollowForUserNavigationRef = useRef(
159
- cancelTimelineLiveFollowForUserNavigationStable,
160
- );
161
- useEffect(() => {
162
- cancelTimelineLiveFollowForUserNavigationRef.current =
163
- cancelTimelineLiveFollowForUserNavigationStable;
164
- }, [cancelTimelineLiveFollowForUserNavigationStable]);
165
- useEffect(() => {
166
- const previous = observedTimelineActivityRef.current;
167
- const dispatchedUserItem =
168
- previous?.hydrated &&
169
- previous.threadKey === activeThreadKey &&
170
- activeActivityRun !== null &&
171
- previous.runId !== activeActivityRun.runId
172
- ? serverProjection?.visibleTurnItems.find(
173
- (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
174
- )
175
- : undefined;
176
- const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {
177
- threadKey: activeThreadKey,
178
- hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
179
- runId: activeActivityRun?.runId ?? null,
180
- queued: activeActivityRun?.status === "queued",
181
- messageId:
182
- dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
183
- });
184
- observedTimelineActivityRef.current = observation;
185
- if (messageId === null) return;
186
- if (
187
- pendingTimelineAnchorRef.current !== null ||
188
- timelineScrollModeRef.current === "free-scrolling"
189
- ) {
190
- return;
191
- }
275
193
- isAtEndRef.current = true;
194
- timelineScrollModeRef.current = "anchoring-new-turn";
195
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
196
- pendingTimelineAnchorRef.current = messageId;
197
- activeTimelineAnchorIndexRef.current = null;
198
- showScrollDebouncer.current.cancel();
199
- setShowScrollToBottom(false);
200
- setTimelineAnchor({ threadKey: activeThreadKey, messageId });
201
- }, [
202
- activeActivityRun,
203
- activeThreadKey,
204
- isServerThread,
205
- serverProjection,
206
- setTimelineAnchor,
207
- threadStatus,
208
- ]);
209
- const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
210
- timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
276
+ // A run that starts while the live end is followed anchors its user message
277
+ // near the top, unless the previous anchor has not been laid out yet.
278
+ const [observedRun, setObservedRun] = useState<TimelineRunObservation | null>(null);
279
+ const dispatchedUserItem =
280
+ observedRun?.hydrated &&
281
+ observedRun.threadKey === activeThreadKey &&
282
+ activeActivityRun !== null &&
283
+ observedRun.runId !== activeActivityRun.runId
284
+ ? serverProjection?.visibleTurnItems.find(
285
+ (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
286
+ )
287
+ : undefined;
288
+ const runObservation = observeTimelineRun(observedRun, {
289
+ threadKey: activeThreadKey,
290
+ hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
291
+ runId: activeActivityRun?.runId ?? null,
292
+ queued: activeActivityRun?.status === "queued",
293
+ messageId:
294
+ dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
295
+ });
296
+ if (!sameRunObservation(runObservation.observation, observedRun)) {
297
+ setObservedRun(runObservation.observation);
298
+ const startedRunAnchor = runObservation.anchorMessageId;
299
+ if (startedRunAnchor !== null && !anchorPending && timelineLiveFollowEnabled) {
300
+ setShowScrollToBottom(false);
301
+ setTimelineAnchor({ threadKey: activeThreadKey, messageId: startedRunAnchor });
302
+ }
303
+ }
304
+ const timelineRealContentOverflowsViewport = () =>
305
+ timelineContentOverflowsViewport(legendListRef.current?.getState(), {
306
composerInset: composerTimelineInset,
307
anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
308
});
214
- const timelineRealContentOverflowsViewportStable = useStableCallback(
215
- timelineRealContentOverflowsViewport,
216
- );
309
const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
310
null,
311
);
220
- const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
221
- timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
312
+ const handlePageScrollStart = useStableCallback((key: PageScrollKey) => {
313
+ visitScroll().intent = key === "PageUp" ? "away-from-end" : "toward-end";
314
composerRef.current?.collapseForTimelineScrollKey(key);
223
- if (
224
- (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
225
- !isTimelineAtLogicalEndStable()
226
- ) {
227
- cancelTimelineLiveFollowForUserNavigationStable();
315
+ if ((key === "PageUp" && timelineRealContentOverflowsViewport()) || !isTimelineAtLogicalEnd()) {
316
+ // Through the viewport, so a running position restore stops too.
317
+ viewportRef.current?.navigate({ releasesFollow: true });
318
}
319
});
230
- useEffect(() => {
231
- const controller = createPageScrollController({
232
- getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
233
- getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
234
- onScrollStart: handlePageScrollStart,
235
- });
236
- pageScrollControllerRef.current = controller;
237
-
238
- return () => {
239
- controller.dispose();
240
- if (pageScrollControllerRef.current === controller) {
241
- pageScrollControllerRef.current = null;
242
- }
243
- };
244
- }, [composerOverlayElement, legendListRef]);
320
const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
321
pageScrollControllerRef.current?.handleKeyDown(key);
322
};
@@ -255,14 +330,10 @@ export function useTimelineFollow(input: TimelineFollowInput) {
330
};
331
const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
332
const scrollToEnd = (animated: boolean = false) => {
258
- cancelPositionRestoreRef.current?.();
259
- isAtEndRef.current = true;
260
- timelineScrollModeRef.current = "following-end";
261
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
262
- setTimelineLiveFollowEnabled(true);
263
- pendingTimelineAnchorRef.current = null;
264
- activeTimelineAnchorIndexRef.current = null;
265
- showScrollDebouncer.current.cancel();
333
+ // Stops a running position restore; follow itself is re-armed below.
334
+ viewportRef.current?.navigate({ releasesFollow: false });
335
+ followStore.dispatch(visit, { type: "followEnd" });
336
+ visitScroll().showScrollDebouncer.cancel();
337
setShowScrollToBottom(false);
338
setTimelineAnchor(releaseChatTimelineAnchor);
339
// The anchored end space must be gone before the scroll measures, or the
@@ -278,217 +349,96 @@ export function useTimelineFollow(input: TimelineFollowInput) {
349
settleListScroll(
350
list,
351
measuredEndOffset,
281
- () => timelineScrollModeRef.current !== "following-end" || legendListRef.current !== list,
352
+ () => readCurrentFollow().mode !== "following" || legendListRef.current !== list,
353
),
354
);
355
});
356
};
357
const scrollToEndStable = useStableCallback(scrollToEnd);
287
- useEffect(() => {
288
- const composer = composerRef;
289
- let removeListeners: (() => void) | null = null;
290
- let frame: number | null = null;
291
- const attach = (remainingAttempts: number) => {
292
- frame = requestAnimationFrame(() => {
293
- frame = null;
294
- const scrollNode = legendListRef.current?.getScrollableNode();
295
- if (!scrollNode) {
296
- // The list may not have mounted on the first frame after a thread
297
- // switch — without a retry the opt-out listeners never attach and
298
- // live-follow becomes impossible to escape for the whole thread.
299
- if (remainingAttempts > 0) {
300
- attach(remainingAttempts - 1);
301
- }
302
- return;
303
- }
304
- const handleManualNavigation = () => {
305
- cancelTimelineLiveFollowForUserNavigationRef.current();
306
- };
307
- // Only break follow for gestures that can move away from the live edge.
308
- // A spurious break emits no scroll event to re-arm follow, so streaming stops
309
- // following. Underflowing content cannot scroll and must keep following.
310
- const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
311
- // The follow re-arm band, not the strict flag: streaming growth makes
312
- // isAtEnd flicker false for a frame before the follow scroll catches
313
- // up, and a gesture landing in that window while still pinned would
314
- // otherwise break follow with no scroll event left to re-arm it.
315
- const viewportIsAwayFromEnd = () =>
316
- resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
317
- const handleWheel = (event: WheelEvent) => {
318
- if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
319
- return;
320
- if (event.deltaY > 0) {
321
- timelineScrollIntentRef.current = "toward-end";
322
- if (isAtEndRef.current) {
323
- composer.current?.restoreAfterTimelineReachedEnd();
324
- }
325
- } else if (event.deltaY < 0) {
326
- timelineScrollIntentRef.current = "away-from-end";
327
- }
328
- if (event.deltaY < 0 && contentScrollsUp()) {
329
- handleManualNavigation();
330
- }
331
- };
332
- // Touch direction isn't observable here (touchmove fires on any
333
- // finger motion, scrolling or not), so break only once the drag has
334
- // actually carried the viewport out of the end band — an upward flick
335
- // gets there within its first few events and later touchmoves break.
336
- const handleTouchMove = () => {
337
- if (viewportIsAwayFromEnd()) {
338
- handleManualNavigation();
339
- }
340
- };
341
- // Scrollbar drags produce no wheel/touch events; they are the only
342
- // pointerdowns whose target is the scroll node itself rather than a
343
- // message row.
344
- const handlePointerDown = (event: PointerEvent) => {
345
- if (event.target === scrollNode) {
346
- if (contentScrollsUp()) {
347
- handleManualNavigation();
348
- }
349
- return;
350
- }
351
- if (viewportIsAwayFromEnd()) {
352
- handleManualNavigation();
353
- }
354
- };
355
- // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
356
- // pointer events entirely; without this the timeline yanks back to
357
- // the end on the next stream chunk. Clicking message text can leave
358
- // DOM focus on body, so these keys must also be heard at document.
359
- const handleKeyDown = (event: KeyboardEvent) => {
360
- if (
361
- !(event.target instanceof Node) ||
362
- (!scrollNode.contains(event.target) &&
363
- event.target !== document.body &&
364
- event.target !== document.documentElement) ||
365
- event.defaultPrevented ||
366
- event.isComposing ||
367
- event.altKey ||
368
- event.ctrlKey ||
369
- event.metaKey ||
370
- event.shiftKey ||
371
- eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
372
- document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
373
- ) {
374
- return;
375
- }
376
- if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
377
- return;
378
- const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
379
- if (
380
- scrollNode.contains(event.target) &&
381
- !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
382
- )
383
- return;
384
- switch (event.key) {
385
- case "PageUp":
386
- case "Home":
387
- case "ArrowUp":
388
- timelineScrollIntentRef.current = "away-from-end";
389
- if (contentScrollsUp()) {
390
- handleManualNavigation();
391
- composer.current?.collapseForTimelineScrollKey(event.key);
392
- }
393
- break;
394
- case "PageDown":
395
- case "End":
396
- case "ArrowDown":
397
- timelineScrollIntentRef.current = "toward-end";
398
- if (viewportIsAwayFromEnd()) {
399
- handleManualNavigation();
400
- }
401
- composer.current?.collapseForTimelineScrollKey(event.key);
402
- if (isTimelineAtLogicalEndStable()) {
403
- composer.current?.restoreAfterTimelineReachedEnd();
404
- }
405
- break;
406
- default:
407
- break;
408
- }
409
- };
410
- // Input inside an embedded frame reaches none of the listeners above,
411
- // but its scroll still chains out to the timeline.
412
- const scrolledUp = createUpwardScrollDetector({
413
- top: scrollNode.scrollTop,
414
- height: scrollNode.scrollHeight,
415
- });
416
- const handleScroll = () => {
417
- if (
418
- scrolledUp({
419
- top: scrollNode.scrollTop,
420
- height: scrollNode.scrollHeight,
421
- programmatic:
422
- positionedTimelineAnchorRef.current !== null &&
423
- positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,
424
- }) &&
425
- timelineScrollModeRef.current !== "free-scrolling" &&
426
- // LegendList updates its scroll state on the next animation frame.
427
- resolveTimelineIsAtEnd({
428
- contentLength: scrollNode.scrollHeight,
429
- scroll: scrollNode.scrollTop,
430
- scrollLength: scrollNode.clientHeight,
431
- }) === false
432
- ) {
433
- handleManualNavigation();
434
- }
435
- };
436
- scrollNode.addEventListener("scroll", handleScroll, { passive: true });
437
- scrollNode.addEventListener("wheel", handleWheel, {
438
- passive: true,
439
- });
440
- scrollNode.addEventListener("touchmove", handleTouchMove, {
441
- passive: true,
442
- });
443
- scrollNode.addEventListener("pointerdown", handlePointerDown, {
444
- passive: true,
445
- });
446
- document.addEventListener("keydown", handleKeyDown);
447
- removeListeners = () => {
448
- scrollNode.removeEventListener("scroll", handleScroll);
449
- scrollNode.removeEventListener("wheel", handleWheel);
450
- scrollNode.removeEventListener("touchmove", handleTouchMove);
451
- scrollNode.removeEventListener("pointerdown", handlePointerDown);
452
- document.removeEventListener("keydown", handleKeyDown);
453
- };
454
- });
455
- };
456
- attach(12);
358
458
- return () => {
459
- if (frame !== null) {
460
- cancelAnimationFrame(frame);
359
+ const handleNavigation = (navigation: TimelineNavigation) => {
360
+ const composer = composerRef.current;
361
+ const awayFromEnd = () => resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
362
+ const releases = navigationReleasesFollow(navigation, {
363
+ contentScrollsUp: timelineRealContentOverflowsViewport,
364
+ awayFromEnd,
365
+ });
366
+ if (navigation.source === "wheel") {
367
+ visitScroll().intent = navigation.direction === "down" ? "toward-end" : "away-from-end";
368
+ const current = readFollow();
369
+ if (navigation.direction === "down" && (current.mode === "following" || current.atEnd)) {
370
+ composer?.restoreAfterTimelineReachedEnd();
371
+ }
372
+ }
373
+ if (navigation.source === "key") {
374
+ visitScroll().intent = navigation.direction === "down" ? "toward-end" : "away-from-end";
375
+ }
376
+ if (releases) releaseFollowForNavigation();
377
+ if (navigation.source === "key" && navigation.key !== " ") {
378
+ if (navigation.direction === "up") {
379
+ if (releases) composer?.collapseForTimelineScrollKey(navigation.key);
380
+ } else {
381
+ composer?.collapseForTimelineScrollKey(navigation.key);
382
+ if (isTimelineAtLogicalEnd()) composer?.restoreAfterTimelineReachedEnd();
383
}
462
- removeListeners?.();
384
+ }
385
+ };
386
+ const handleNavigationStable = useStableCallback(handleNavigation);
387
+ /**
388
+ * Attached by the timeline's list ref callback, so follow hears the
389
+ * viewport's navigation exactly as long as the scroll node exists.
390
+ */
391
+ const attachTimelineViewport = (viewport: TimelineViewport) => {
392
+ viewportRef.current = viewport;
393
+ const unsubscribe = viewport.subscribe(handleNavigationStable);
394
+ const controller = createPageScrollController({
395
+ getContainer: () => viewport.scrollNode,
396
+ getScrollPaddingBottomPx: followStore.readComposerOverlayHeight,
397
+ onScrollStart: handlePageScrollStart,
398
+ });
399
+ pageScrollControllerRef.current = controller;
400
+ return () => {
401
+ unsubscribe();
402
+ controller.dispose();
403
+ if (pageScrollControllerRef.current === controller) pageScrollControllerRef.current = null;
404
+ if (viewportRef.current === viewport) viewportRef.current = null;
405
+ const scroll = visitScrollRef.current;
406
+ scroll?.releaseAnchorScrollHold?.();
407
+ if (scroll) scroll.releaseAnchorScrollHold = null;
408
};
464
- }, [
465
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
466
- activeThreadId,
467
- composerRef,
468
- isTimelineAtLogicalEndStable,
469
- legendListRef,
470
- timelineRealContentOverflowsViewportStable,
471
- ]);
409
+ };
410
411
const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
474
- if (pendingTimelineAnchorRef.current === messageId) {
475
- pendingTimelineAnchorRef.current = null;
476
- }
477
- activeTimelineAnchorIndexRef.current = anchorIndex;
478
- if (positionedTimelineAnchorRef.current === messageId) {
412
+ setLaidOutAnchor(messageId);
413
+ const scroll = visitScroll();
414
+ if (scroll.positionedAnchor === messageId) {
415
return;
416
}
481
- positionedTimelineAnchorRef.current = messageId;
482
- settledTimelineAnchorRef.current = null;
417
+ stopAnchorPositioning(scroll);
418
+ scroll.positionedAnchor = messageId;
419
+ // The positioning scroll moves up when the anchor sits above the view.
420
+ const releaseHold = viewportRef.current?.holdProgrammaticScroll() ?? (() => {});
421
+ scroll.releaseAnchorScrollHold = releaseHold;
422
+ const isPositioning = () =>
423
+ scroll.positionedAnchor === messageId && listShowsMessage(legendListRef.current, messageId);
424
+ // Releasing is idempotent, so an attempt that is no longer current (the
425
+ // thread switched, the user navigated) always lets go of its own hold.
426
+ const abandon = () => {
427
+ releaseHold();
428
+ if (scroll.positionedAnchor === messageId) stopAnchorPositioning(scroll);
429
+ };
430
const positionAnchor = (remainingAttempts: number) => {
431
requestAnimationFrame(() => {
485
- if (positionedTimelineAnchorRef.current !== messageId) {
432
+ if (!isPositioning()) {
433
+ abandon();
434
return;
435
}
436
const list = legendListRef.current;
437
if (!list) {
438
if (remainingAttempts > 0) {
439
positionAnchor(remainingAttempts - 1);
440
+ } else {
441
+ abandon();
442
}
443
return;
444
}
@@ -501,11 +451,12 @@ export function useTimelineFollow(input: TimelineFollowInput) {
451
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
452
})
453
.then(() => {
504
- if (
505
- legendListRef.current === list &&
506
- positionedTimelineAnchorRef.current === messageId
507
- ) {
508
- settledTimelineAnchorRef.current = messageId;
454
+ if (legendListRef.current === list && isPositioning()) {
455
+ scroll.settledAnchor = messageId;
456
+ releaseHold();
457
+ scroll.releaseAnchorScrollHold = null;
458
+ } else {
459
+ abandon();
460
}
461
});
462
});
@@ -514,35 +465,25 @@ export function useTimelineFollow(input: TimelineFollowInput) {
465
};
466
const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
467
const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
517
- if (settledTimelineAnchorRef.current !== messageId) {
518
- return;
519
- }
520
- if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
468
+ const scroll = visitScroll();
469
+ if (scroll.settledAnchor !== messageId || readFollow().mode === "following") {
470
return;
471
}
472
const scrollOffset = legendListRef.current?.getState().scroll;
473
if (scrollOffset === undefined) {
474
return;
475
}
527
- if (pendingAnchorScrollRestoreRef.current === null) {
528
- pendingAnchorScrollRestoreRef.current = {
529
- messageId,
530
- offset: scrollOffset,
531
- userScrollGeneration: anchorUserScrollGenerationRef.current,
532
- };
476
+ if (scroll.pendingAnchorScrollRestore === null) {
477
+ scroll.pendingAnchorScrollRestore = { messageId, offset: scrollOffset };
478
}
534
- if (anchorScrollRestoreFrameRef.current !== null) {
479
+ if (scroll.anchorScrollRestoreFrame !== null) {
480
return;
481
}
537
- anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
538
- anchorScrollRestoreFrameRef.current = null;
539
- const pending = pendingAnchorScrollRestoreRef.current;
540
- pendingAnchorScrollRestoreRef.current = null;
541
- if (
542
- pending &&
543
- settledTimelineAnchorRef.current === pending.messageId &&
544
- pending.userScrollGeneration === anchorUserScrollGenerationRef.current
545
- ) {
482
+ scroll.anchorScrollRestoreFrame = requestAnimationFrame(() => {
483
+ scroll.anchorScrollRestoreFrame = null;
484
+ const pending = scroll.pendingAnchorScrollRestore;
485
+ scroll.pendingAnchorScrollRestore = null;
486
+ if (pending && scroll.settledAnchor === pending.messageId) {
487
const list = legendListRef.current;
488
const currentScrollOffset = list?.getState().scroll;
489
if (
@@ -562,30 +503,25 @@ export function useTimelineFollow(input: TimelineFollowInput) {
503
const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
504
505
const onIsAtEndChange = (isAtEnd: boolean) => {
565
- if (
566
- !isAtEnd &&
567
- liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
568
- ) {
569
- showScrollDebouncer.current.cancel();
506
+ const scroll = visitScroll();
507
+ if (!isAtEnd && readFollow().mode === "following") {
508
+ scroll.showScrollDebouncer.cancel();
509
setShowScrollToBottom(false);
510
return;
511
}
573
- if (isAtEndRef.current === isAtEnd) return;
574
- isAtEndRef.current = isAtEnd;
575
- if (isAtEnd) {
576
- if (timelineScrollIntentRef.current === "toward-end") {
512
+ const { before, after } = followStore.dispatch(visit, {
513
+ type: isAtEnd ? "reachedEnd" : "leftEnd",
514
+ });
515
+ if (after === before) return;
516
+ if (after.mode === "following") {
517
+ if (scroll.intent === "toward-end") {
518
composerRef.current?.restoreAfterTimelineReachedEnd();
519
}
579
- timelineScrollModeRef.current = "following-end";
580
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
581
- setTimelineLiveFollowEnabled(true);
520
setTimelineAnchor(releaseChatTimelineAnchor);
583
- showScrollDebouncer.current.cancel();
521
+ scroll.showScrollDebouncer.cancel();
522
setShowScrollToBottom(false);
523
} else {
586
- timelineScrollModeRef.current = "free-scrolling";
587
- liveFollowUserScrollGenerationRef.current = null;
588
- showScrollDebouncer.current.maybeExecute();
524
+ scroll.showScrollDebouncer.maybeExecute();
525
}
526
};
527
const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
@@ -597,10 +533,14 @@ export function useTimelineFollow(input: TimelineFollowInput) {
533
serverProjection?.visibleTurnItems.some(
534
(row) => row.item.type === "reasoning" && row.item.runId === activeRunningTurnId,
535
) === true;
536
+ // Z: the release scrolls, and that scroll must follow the commit that drops
537
+ // the anchored end space; the trigger is streamed thread data. A
538
+ // totalSize listener cannot replace it: the anchored end space can already
539
+ // be 0, so dropping it changes no size and no list event fires.
540
useLayoutEffect(() => {
601
- if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
541
+ if (timelineAnchorMessageId === null || !timelineLiveFollowEnabled) return;
542
if (
603
- (runningTurnHasReasoning && timelineAnchorMessageId !== null && timelineLiveFollowEnabled) ||
543
+ runningTurnHasReasoning ||
544
shouldReleaseTimelineAnchorForToolActivity({
545
anchorMessageId: timelineAnchorMessageId,
546
liveFollowEnabled: timelineLiveFollowEnabled,
@@ -619,42 +559,10 @@ export function useTimelineFollow(input: TimelineFollowInput) {
559
timelineLiveFollowEnabled,
560
]);
561
622
- // A thread switch restores that thread's remembered follow state; the refs
623
- // the scroll handlers read catch up after commit.
624
- const [timelineThreadReset, setTimelineThreadReset] = useState({
625
- threadKey: activeThreadKey,
626
- followEnd: true,
627
- });
628
- if (timelineThreadReset.threadKey !== activeThreadKey) {
629
- const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
630
- setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
631
- setTimelineLiveFollowEnabled(followEnd);
632
- setShowScrollToBottom(!followEnd);
633
- }
634
- useEffect(() => {
635
- const { followEnd } = timelineThreadReset;
636
- isAtEndRef.current = followEnd;
637
- timelineScrollIntentRef.current = null;
638
- timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
639
- liveFollowUserScrollGenerationRef.current = followEnd
640
- ? anchorUserScrollGenerationRef.current
641
- : null;
642
- pendingTimelineAnchorRef.current = null;
643
- positionedTimelineAnchorRef.current = null;
644
- settledTimelineAnchorRef.current = null;
645
- activeTimelineAnchorIndexRef.current = null;
646
- showScrollDebouncer.current.cancel();
647
- }, [timelineThreadReset]);
648
-
562
/** Arms the anchor for a message the user just sent, before its run exists. */
563
const anchorNewTurn = (threadKey: string, messageId: MessageId) => {
651
- isAtEndRef.current = true;
652
- timelineScrollModeRef.current = "anchoring-new-turn";
653
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
654
- setTimelineLiveFollowEnabled(true);
655
- pendingTimelineAnchorRef.current = messageId;
656
- activeTimelineAnchorIndexRef.current = null;
657
- showScrollDebouncer.current.cancel();
564
+ followStore.dispatch(visit, { type: "followEnd" });
565
+ visitScroll().showScrollDebouncer.cancel();
566
setShowScrollToBottom(false);
567
setTimelineAnchor({ threadKey, messageId });
568
};
@@ -662,9 +570,7 @@ export function useTimelineFollow(input: TimelineFollowInput) {
570
return {
571
showScrollToBottom,
572
timelineLiveFollowEnabled,
665
- cancelPositionRestoreRef,
573
isTimelineAtLogicalEndStable,
667
- cancelTimelineLiveFollowForUserNavigationStable,
574
onComposerPageScrollKeyDownStable,
575
onComposerPageScrollKeyUpStable,
576
onComposerPageScrollReleaseStable,
@@ -674,5 +580,7 @@ export function useTimelineFollow(input: TimelineFollowInput) {
580
onToolOutputCollapsedAtEndStable,
581
onIsAtEndChangeStable,
582
anchorNewTurn,
583
+ attachTimelineViewport,
584
+ attachComposerOverlay: followStore.attachComposerOverlay,
585
};
586
}
apps/web/src/components/chat/useTimelinePositionRestore.ts
+92
-135
@@ -1,8 +1,7 @@
1
-import { useLayoutEffect, useRef } from "react";
1
import type { LegendListRef } from "@legendapp/list/react";
3
-import type { AssistantCitationRequest } from "./AssistantCitationSource";
2
import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
3
import type { RememberedTimelinePosition } from "./timelineScrollAnchoring";
4
+import type { TimelineViewport } from "./timelineViewport";
5
6
// A streaming reply moves the end every frame, so the target may never hold
7
// still. Past this many frames the list's own end maintenance takes over.
@@ -48,146 +47,104 @@ export const measuredEndOffset = (element: HTMLElement) =>
47
48
/**
49
* Scrolls a newly shown thread back to where the user left it, or to its end,
51
- * and reports the thread positioned once the saved row settles.
50
+ * and reports the thread positioned once the saved row settles. Any navigation
51
+ * on the viewport cancels it where it is. Returns the cancel for the
52
+ * operation's owner.
53
*/
53
-export function useTimelinePositionRestore({
54
- listRef,
54
+export function startTimelinePositionRestore({
55
+ list,
56
+ viewport,
57
listIdentityKey,
56
- restoringThreadPosition,
57
- rememberedPosition,
58
- rows,
59
- citationRequest,
60
- cancelPositionRestoreRef,
61
- onManualNavigation,
58
+ listOpenedOn,
59
+ rememberedPosition: position,
60
+ citationPending,
61
+ releaseForFind,
62
onPositioned,
63
}: {
64
- readonly listRef: React.RefObject<LegendListRef | null>;
64
+ readonly list: LegendListRef;
65
+ readonly viewport: TimelineViewport;
66
readonly listIdentityKey: string;
66
- readonly restoringThreadPosition: boolean;
67
+ /** The identity the mounted list opened on, until it shows another; see nextListOpening. */
68
+ readonly listOpenedOn: string | null;
69
readonly rememberedPosition: RememberedTimelinePosition | undefined;
68
- readonly rows: MessagesTimelineRow[];
69
- readonly citationRequest: AssistantCitationRequest | null;
70
- readonly cancelPositionRestoreRef: React.RefObject<(() => void) | null> | undefined;
71
- readonly onManualNavigation: () => void;
70
+ readonly citationPending: boolean;
71
+ /**
72
+ * Find was open when the list started showing the thread. Opening find is
73
+ * navigation, so follow lets go; the thread still opens where it was left,
74
+ * and MessagesTimeline holds find's reveal until this reports it positioned.
75
+ */
76
+ readonly releaseForFind: boolean;
77
readonly onPositioned: (identity: string) => void;
73
-}) {
74
- // Preserve initialScrollAtEnd's measured target until the list is reused
75
- // for another thread; scrollToEnd would replace it with an estimated offset.
76
- const listOpenedOnRef = useRef<{
77
- readonly list: LegendListRef;
78
- identity: string | null;
79
- } | null>(null);
80
- useLayoutEffect(() => {
81
- const list = listRef.current;
82
- const opened = listOpenedOnRef.current;
83
- if (!list) return;
84
- if (opened?.list !== list) {
85
- listOpenedOnRef.current = { list, identity: listIdentityKey };
86
- } else if (opened.identity !== listIdentityKey) {
87
- opened.identity = null;
88
- }
78
+}): () => void {
79
+ if (citationPending) {
80
+ // The citation scroll owns positioning once the list has mounted.
81
+ onPositioned(listIdentityKey);
82
+ return () => {};
83
+ }
84
+ let cancelled = false;
85
+ const rows = list.getState().data as ReadonlyArray<MessagesTimelineRow>;
86
+ const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
87
+ // Reading history or finding: follow lets go before the restore claims the viewport.
88
+ if (position?.atEnd === false || releaseForFind) viewport.navigate({ releasesFollow: true });
89
+ const releaseScrollHold = viewport.holdProgrammaticScroll();
90
+ const stop = () => {
91
+ cancelled = true;
92
+ releaseScrollHold();
93
+ unsubscribe();
94
+ };
95
+ const unsubscribe = viewport.subscribe(() => {
96
+ if (cancelled) return;
97
+ stop();
98
+ void list.scrollToOffset({ offset: viewport.scrollNode.scrollTop, animated: false });
99
+ onPositioned(listIdentityKey);
100
});
90
- useLayoutEffect(() => {
91
- if (!restoringThreadPosition || rows.length === 0) return;
92
- const list = listRef.current;
93
- if (!list) return;
94
- if (citationRequest !== null) {
95
- // The citation scroll owns positioning once the list has mounted.
96
- onPositioned(listIdentityKey);
97
- return;
101
+ const finish = () => {
102
+ stop();
103
+ onPositioned(listIdentityKey);
104
+ };
105
+ const scrolling =
106
+ position?.atEnd === false
107
+ ? index >= 0
108
+ ? list.scrollToIndex({
109
+ index,
110
+ animated: false,
111
+ viewPosition: 0,
112
+ viewOffset: -position.offsetWithinRow,
113
+ })
114
+ : list.scrollToOffset({ offset: position.scrollOffset, animated: false })
115
+ : // initialScrollAtEnd measured this target; scrollToEnd would replace it with an estimate.
116
+ listOpenedOn === listIdentityKey
117
+ ? undefined
118
+ : list.scrollToEnd({ animated: false });
119
+ const settlesAtEnd = position?.atEnd !== false && scrolling !== undefined;
120
+ void Promise.resolve(scrolling).then(async () => {
121
+ if (cancelled) return;
122
+ if (settlesAtEnd) {
123
+ await settleListScroll(list, measuredEndOffset, () => cancelled);
124
+ } else if (position?.atEnd === false && index >= 0) {
125
+ // Keep the saved row mounted until its measured position and the DOM agree.
126
+ await settleListScroll(
127
+ list,
128
+ (element) => {
129
+ const state = list.getState();
130
+ const rowIndex = state.indexByKey(position.rowId);
131
+ const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
132
+ if (!row) return undefined;
133
+ return Math.max(
134
+ 0,
135
+ Math.min(
136
+ element.scrollTop +
137
+ row.getBoundingClientRect().top -
138
+ element.getBoundingClientRect().top +
139
+ position.offsetWithinRow,
140
+ measuredEndOffset(element),
141
+ ),
142
+ );
143
+ },
144
+ () => cancelled,
145
+ );
146
}
99
- let cancelled = false;
100
- const viewport: HTMLElement | null = list.getScrollableNode();
101
- const cancelRestoration = () => {
102
- if (cancelled) return;
103
- cancelled = true;
104
- if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
105
- onPositioned(listIdentityKey);
106
- };
107
- const cancelForNavigation = () => {
108
- cancelRestoration();
109
- onManualNavigation();
110
- };
111
- const onScrollKey = (event: globalThis.KeyboardEvent) => {
112
- if (
113
- ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key) &&
114
- !(
115
- event.target instanceof Element &&
116
- event.target.closest("input, textarea, [contenteditable=true]")
117
- )
118
- )
119
- cancelForNavigation();
120
- };
121
- viewport?.addEventListener("wheel", cancelForNavigation, { passive: true });
122
- viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });
123
- viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });
124
- viewport?.ownerDocument.addEventListener("keydown", onScrollKey);
125
- const position = rememberedPosition;
126
- const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
127
- if (position?.atEnd === false) onManualNavigation();
128
- if (cancelPositionRestoreRef) cancelPositionRestoreRef.current = cancelRestoration;
129
- const scrolling =
130
- position?.atEnd === false
131
- ? index >= 0
132
- ? list.scrollToIndex({
133
- index,
134
- animated: false,
135
- viewPosition: 0,
136
- viewOffset: -position.offsetWithinRow,
137
- })
138
- : list.scrollToOffset({ offset: position.scrollOffset, animated: false })
139
- : listOpenedOnRef.current?.identity === listIdentityKey
140
- ? undefined
141
- : list.scrollToEnd({ animated: false });
142
- const settlesAtEnd = position?.atEnd !== false && scrolling !== undefined;
143
- void Promise.resolve(scrolling).then(async () => {
144
- if (cancelled) return;
145
- if (settlesAtEnd) {
146
- await settleListScroll(list, measuredEndOffset, () => cancelled);
147
- } else if (position?.atEnd === false && index >= 0) {
148
- // Keep the saved row mounted until its measured position and the DOM agree.
149
- await settleListScroll(
150
- list,
151
- (element) => {
152
- const state = list.getState();
153
- const rowIndex = state.indexByKey(position.rowId);
154
- const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
155
- if (!row) return undefined;
156
- return Math.max(
157
- 0,
158
- Math.min(
159
- element.scrollTop +
160
- row.getBoundingClientRect().top -
161
- element.getBoundingClientRect().top +
162
- position.offsetWithinRow,
163
- measuredEndOffset(element),
164
- ),
165
- );
166
- },
167
- () => cancelled,
168
- );
169
- }
170
- if (!cancelled) onPositioned(listIdentityKey);
171
- });
172
- return () => {
173
- cancelled = true;
174
- if (cancelPositionRestoreRef?.current === cancelRestoration) {
175
- cancelPositionRestoreRef.current = null;
176
- }
177
- viewport?.removeEventListener("wheel", cancelForNavigation);
178
- viewport?.removeEventListener("touchmove", cancelForNavigation);
179
- viewport?.removeEventListener("pointerdown", cancelForNavigation);
180
- viewport?.ownerDocument.removeEventListener("keydown", onScrollKey);
181
- };
182
- }, [
183
- citationRequest,
184
- cancelPositionRestoreRef,
185
- listIdentityKey,
186
- listRef,
187
- onManualNavigation,
188
- onPositioned,
189
- rememberedPosition,
190
- restoringThreadPosition,
191
- rows,
192
- ]);
147
+ if (!cancelled) finish();
148
+ });
149
+ return stop;
150
}
apps/web/src/components/guest/GuestPage.tsx
+1
-4
@@ -392,11 +392,9 @@ function GuestThread({
392
const follow = useTimelineFollow({
393
legendListRef: listRef,
394
composerRef: NO_COMPOSER,
395
- composerOverlayElement: null,
395
composerTimelineInset: 0,
396
routeThreadKey: threadKey,
397
activeThreadKey: threadKey,
399
- activeThreadId: undefined,
398
// Not a server thread: new turns follow the end instead of anchoring near the top.
399
isServerThread: false,
400
serverProjection: null,
@@ -476,8 +474,7 @@ function GuestThread({
474
emptyPlaceholderInset={0}
475
liveFollowEnabled={follow.timelineLiveFollowEnabled}
476
onIsAtEndChange={follow.onIsAtEndChangeStable}
479
- onManualNavigation={follow.cancelTimelineLiveFollowForUserNavigationStable}
480
- cancelPositionRestoreRef={follow.cancelPositionRestoreRef}
477
+ onViewportAttach={follow.attachTimelineViewport}
478
footer={
479
unplaced.length === 0 ? null : (
480
<ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">