The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 20:45 UTC
refactor(web): ChatView's timeline follow and anchoring lives in useTimelineFollow (#22701)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 01:36 UTC
6b13e8f01ce68a2b936f709fccbe803c43b41a05
2 files changed
+702
-587
apps/web/src/components/ChatView.tsx
+37
-587
@@ -44,11 +44,8 @@ import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
44
import { useWorktreeSetup } from "./chat/useWorktreeSetup";
45
import { useChatShortcuts, type ChatShortcutHandler } from "./chat/useChatShortcuts";
46
import {
47
- eventPathContainsSelector,
47
pasteTextToFocusComposer,
48
shouldRedirectInputToComposer,
50
- TYPE_TO_FOCUS_EDITABLE_SELECTOR,
51
- TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
49
} from "./chat/composerFocusRedirect";
50
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
51
import * as Schema from "effect/Schema";
@@ -130,7 +127,6 @@ import {
127
projectScriptTerminalInput,
128
resolveProjectScripts,
129
} from "@t3tools/shared/projectScripts";
133
-import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
130
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
131
import {
132
latestUnheldRun,
@@ -141,17 +137,8 @@ import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
137
import { truncate } from "@t3tools/shared/String";
138
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
139
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
144
-import { Debouncer } from "@tanstack/react-pacer";
140
import { useAtomValue } from "@effect/atom-react";
146
-import {
147
- Fragment,
148
- type SetStateAction,
149
- useEffect,
150
- useEffectEvent,
151
- useLayoutEffect,
152
- useRef,
153
- useState,
154
-} from "react";
141
+import { Fragment, type SetStateAction, useEffect, useLayoutEffect, useRef, useState } from "react";
142
import { flushSync } from "react-dom";
143
import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";
144
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
@@ -189,14 +176,6 @@ import {
176
isLatestRunSettled,
177
} from "../session-logic";
178
import { type LegendListRef } from "@legendapp/list/react";
192
-import {
193
- CHAT_TIMELINE_ANCHOR_OFFSET,
194
- timelineContentOverflowsViewport,
195
- readTimelinePosition,
196
- observeTimelineRun,
197
- type TimelineRunObservation,
198
- type TimelineScrollMode,
199
-} from "./chat/timelineScrollAnchoring";
179
import { useUiStateStore } from "../uiStateStore";
180
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
181
import {
@@ -383,8 +362,6 @@ import {
362
} from "../state/entities";
363
import { environmentShell, useEnvironmentShellHasSnapshot } from "../state/shell";
364
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
386
-import { createPageScrollController, type PageScrollKey } from "./chat/pageScrollController";
387
-import { createUpwardScrollDetector, isTimelineScrollTarget } from "./chat/timelineScrollTarget";
365
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
366
import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog";
367
import {
@@ -401,7 +378,6 @@ import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
378
import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
379
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
380
import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
404
-import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";
381
import {
382
overlayComposerIsResting,
383
resolveComposerTimelineInset,
@@ -476,7 +452,6 @@ import {
452
isBranchMismatchDismissedForSession,
453
shouldShowBranchMismatchBanner,
454
shouldShowPlanFollowUpPrompt,
479
- shouldReleaseTimelineAnchorForToolActivity,
455
shouldRenderPreviewMiniPlayer,
456
getStartedThreadModelChangeBlockReason,
457
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
@@ -542,6 +517,7 @@ import { observeResize } from "~/lib/observeResize";
517
import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
518
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
519
import { ChatRightPanel } from "./chat/ChatRightPanel";
520
+import { useTimelineFollow } from "./chat/useTimelineFollow";
521
import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition";
522
import { useLocalDispatchState } from "./chat/useLocalDispatchState";
523
import {
@@ -557,7 +533,6 @@ import {
533
type LocalThreadErrorEntry,
534
makeModelDisabledReason,
535
makeThreadErrorSetter,
560
- releaseChatTimelineAnchor,
536
} from "./ChatView.logic";
537
538
const EMPTY_PROVIDERS: ServerProvider[] = [];
@@ -565,7 +540,6 @@ const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = [];
540
const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];
541
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
542
568
-const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
543
const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
544
const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
545
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -912,7 +886,6 @@ export default function ChatView(props: ChatViewProps) {
886
return inserted;
887
};
888
const citeAssistantTextStable = useStableCallback(citeAssistantText);
915
- const [showScrollToBottom, setShowScrollToBottom] = useState(false);
889
const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false);
890
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
891
// Set by "Work locally": the draft whose restored message should be resent
@@ -996,10 +969,6 @@ export default function ChatView(props: ChatViewProps) {
969
const composerRestingRef = useRef(false);
970
const composerMountedRef = useRef(true);
971
const [scrollToEndClearance, setScrollToEndClearance] = useState(0);
999
- const isAtEndRef = useRef(true);
1000
- const isTimelineAtLogicalEnd = () =>
1001
- resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
1002
- const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
972
const [timelineOverflows, setTimelineOverflows] = useState(false);
973
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
974
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
@@ -3673,541 +3642,38 @@ export default function ChatView(props: ChatViewProps) {
3642
return result;
3643
};
3644
3676
- // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
3677
- // thread switches. LegendList fires scroll events with isAtEnd=false while
3678
- // initialScrollAtEnd is settling; hiding is always immediate.
3679
- const showScrollDebouncer = useRef(
3680
- new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
3681
- );
3682
- const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);
3683
- const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
3684
- // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
3685
- // re-pins on its own (independent of the refs), so the timeline needs a
3686
- // render-visible flag to switch it off once the user scrolls away.
3687
- const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
3688
- const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
3689
- const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
3690
- const settledTimelineAnchorRef = useRef<MessageId | null>(null);
3691
- const activeTimelineAnchorIndexRef = useRef<number | null>(null);
3692
- const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);
3693
- const anchorUserScrollGenerationRef = useRef(0);
3694
- const cancelPositionRestoreRef = useRef<(() => void) | null>(null);
3695
- const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
3696
- const pendingAnchorScrollRestoreRef = useRef<{
3697
- readonly messageId: MessageId;
3698
- readonly offset: number;
3699
- readonly userScrollGeneration: number;
3700
- } | null>(null);
3701
- const anchorScrollRestoreFrameRef = useRef<number | null>(null);
3702
- const cancelTimelineLiveFollowForUserNavigation = () => {
3703
- cancelPositionRestoreRef.current?.();
3704
- anchorUserScrollGenerationRef.current += 1;
3705
- const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
3706
- timelineScrollModeRef.current = "free-scrolling";
3707
- liveFollowUserScrollGenerationRef.current = null;
3708
- setTimelineLiveFollowEnabled(false);
3709
- pendingTimelineAnchorRef.current = null;
3710
- positionedTimelineAnchorRef.current = null;
3711
- settledTimelineAnchorRef.current = null;
3712
- activeTimelineAnchorIndexRef.current = null;
3713
- pendingAnchorScrollRestoreRef.current = null;
3714
- if (anchorScrollRestoreFrameRef.current !== null) {
3715
- cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
3716
- anchorScrollRestoreFrameRef.current = null;
3717
- }
3718
- if (wasProgrammaticScrollMode) {
3719
- // While following or anchoring, our scrollToEnd/scrollToOffset calls can
3720
- // sit in LegendList's pending-imperative-scroll queue (it defers them
3721
- // while layout settles) and fire seconds later with stale targets,
3722
- // yanking the view away after the user scrolled. Starting a new
3723
- // imperative scroll cancels everything queued; targeting an item that
3724
- // is not in the data makes the new request itself resolve without ever
3725
- // scrolling, so this is a pure cancel.
3726
- void legendListRef.current?.scrollToItem({
3727
- item: TIMELINE_SCROLL_CANCEL_SENTINEL,
3728
- animated: false,
3729
- });
3730
- // An already-started animated scroll (behavior: smooth) keeps running in
3731
- // the browser regardless of the queue; a same-position instant write is
3732
- // the only way to halt it where it is.
3733
- const scrollNode = legendListRef.current?.getScrollableNode() as
3734
- | { scrollTop?: number }
3735
- | null
3736
- | undefined;
3737
- const currentScrollTop = scrollNode?.scrollTop;
3738
- if (scrollNode && typeof currentScrollTop === "number") {
3739
- scrollNode.scrollTop = currentScrollTop;
3740
- }
3741
- }
3742
- };
3743
- const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
3744
- cancelTimelineLiveFollowForUserNavigation,
3745
- );
3746
- const cancelTimelineLiveFollowForUserNavigationRef = useRef(
3645
+ const {
3646
+ showScrollToBottom,
3647
+ timelineLiveFollowEnabled,
3648
+ cancelPositionRestoreRef,
3649
+ isTimelineAtLogicalEndStable,
3650
cancelTimelineLiveFollowForUserNavigationStable,
3748
- );
3749
- useEffect(() => {
3750
- cancelTimelineLiveFollowForUserNavigationRef.current =
3751
- cancelTimelineLiveFollowForUserNavigationStable;
3752
- }, [cancelTimelineLiveFollowForUserNavigationStable]);
3753
- useEffect(() => {
3754
- const previous = observedTimelineActivityRef.current;
3755
- const dispatchedUserItem =
3756
- previous?.hydrated &&
3757
- previous.threadKey === activeThreadKey &&
3758
- activeActivityRun !== null &&
3759
- previous.runId !== activeActivityRun.runId
3760
- ? serverProjection?.visibleTurnItems.find(
3761
- (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
3762
- )
3763
- : undefined;
3764
- const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {
3765
- threadKey: activeThreadKey,
3766
- hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
3767
- runId: activeActivityRun?.runId ?? null,
3768
- queued: activeActivityRun?.status === "queued",
3769
- messageId:
3770
- dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
3771
- });
3772
- observedTimelineActivityRef.current = observation;
3773
- if (messageId === null) return;
3774
- if (
3775
- pendingTimelineAnchorRef.current !== null ||
3776
- timelineScrollModeRef.current === "free-scrolling"
3777
- ) {
3778
- return;
3779
- }
3780
-
3781
- isAtEndRef.current = true;
3782
- timelineScrollModeRef.current = "anchoring-new-turn";
3783
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
3784
- pendingTimelineAnchorRef.current = messageId;
3785
- activeTimelineAnchorIndexRef.current = null;
3786
- showScrollDebouncer.current.cancel();
3787
- setShowScrollToBottom(false);
3788
- setTimelineAnchor({ threadKey: activeThreadKey, messageId });
3789
- }, [activeActivityRun, activeThreadKey, isServerThread, serverProjection, threadStatus]);
3790
- const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
3791
- timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
3792
- composerInset: composerTimelineInset,
3793
- anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
3794
- });
3795
- const timelineRealContentOverflowsViewportStable = useStableCallback(
3796
- timelineRealContentOverflowsViewport,
3797
- );
3798
- const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
3799
- null,
3800
- );
3801
- const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
3802
- timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
3803
- composerRef.current?.collapseForTimelineScrollKey(key);
3804
- if (
3805
- (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
3806
- !isTimelineAtLogicalEndStable()
3807
- ) {
3808
- cancelTimelineLiveFollowForUserNavigationStable();
3809
- }
3810
- });
3811
- useEffect(() => {
3812
- const controller = createPageScrollController({
3813
- getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
3814
- getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
3815
- onScrollStart: handlePageScrollStart,
3816
- });
3817
- pageScrollControllerRef.current = controller;
3818
-
3819
- return () => {
3820
- controller.dispose();
3821
- if (pageScrollControllerRef.current === controller) {
3822
- pageScrollControllerRef.current = null;
3823
- }
3824
- };
3825
- }, [composerOverlayElement]);
3826
- const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
3827
- pageScrollControllerRef.current?.handleKeyDown(key);
3828
- };
3829
- const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
3830
- const onComposerPageScrollKeyUp = (key: string) => {
3831
- pageScrollControllerRef.current?.handleKeyUp(key);
3832
- };
3833
- const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
3834
- const onComposerPageScrollRelease = () => {
3835
- pageScrollControllerRef.current?.releaseActiveKey();
3836
- };
3837
- const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
3838
- const scrollToEnd = (animated: boolean = false) => {
3839
- cancelPositionRestoreRef.current?.();
3840
- isAtEndRef.current = true;
3841
- timelineScrollModeRef.current = "following-end";
3842
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
3843
- setTimelineLiveFollowEnabled(true);
3844
- pendingTimelineAnchorRef.current = null;
3845
- activeTimelineAnchorIndexRef.current = null;
3846
- showScrollDebouncer.current.cancel();
3847
- setShowScrollToBottom(false);
3848
- setTimelineAnchor(releaseChatTimelineAnchor);
3849
- // The anchored end space must be gone before the scroll measures, or the
3850
- // list lands short of the real end (#6519).
3851
- requestAnimationFrame(() => {
3852
- void legendListRef.current?.scrollToEnd?.({
3853
- animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
3854
- });
3855
- });
3856
- };
3857
- const scrollToEndStable = useStableCallback(scrollToEnd);
3858
- useEffect(() => {
3859
- const composer = composerRef;
3860
- let removeListeners: (() => void) | null = null;
3861
- let frame: number | null = null;
3862
- const attach = (remainingAttempts: number) => {
3863
- frame = requestAnimationFrame(() => {
3864
- frame = null;
3865
- const scrollNode = legendListRef.current?.getScrollableNode();
3866
- if (!scrollNode) {
3867
- // The list may not have mounted on the first frame after a thread
3868
- // switch — without a retry the opt-out listeners never attach and
3869
- // live-follow becomes impossible to escape for the whole thread.
3870
- if (remainingAttempts > 0) {
3871
- attach(remainingAttempts - 1);
3872
- }
3873
- return;
3874
- }
3875
- const handleManualNavigation = () => {
3876
- cancelTimelineLiveFollowForUserNavigationRef.current();
3877
- };
3878
- // The gestures below must only break follow when they can actually
3879
- // move the viewport away from the live edge (#5566): a spurious break
3880
- // while pinned at the end produces no scroll event, never re-arms,
3881
- // and streaming silently stops following. Underflowing content can't
3882
- // scroll at all, so nothing there should break follow.
3883
- const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
3884
- // The follow re-arm band, not the strict flag: streaming growth makes
3885
- // isAtEnd flicker false for a frame before the follow scroll catches
3886
- // up, and a gesture landing in that window while still pinned would
3887
- // otherwise break follow with no scroll event left to re-arm it.
3888
- const viewportIsAwayFromEnd = () =>
3889
- resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
3890
- const handleWheel = (event: WheelEvent) => {
3891
- if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
3892
- return;
3893
- if (event.deltaY > 0) {
3894
- timelineScrollIntentRef.current = "toward-end";
3895
- if (isAtEndRef.current) {
3896
- composer.current?.restoreAfterTimelineReachedEnd();
3897
- }
3898
- } else if (event.deltaY < 0) {
3899
- timelineScrollIntentRef.current = "away-from-end";
3900
- }
3901
- if (event.deltaY < 0 && contentScrollsUp()) {
3902
- handleManualNavigation();
3903
- }
3904
- };
3905
- // Touch direction isn't observable here (touchmove fires on any
3906
- // finger motion, scrolling or not), so break only once the drag has
3907
- // actually carried the viewport out of the end band — an upward flick
3908
- // gets there within its first few events and later touchmoves break.
3909
- const handleTouchMove = () => {
3910
- if (viewportIsAwayFromEnd()) {
3911
- handleManualNavigation();
3912
- }
3913
- };
3914
- // Scrollbar drags produce no wheel/touch events; they are the only
3915
- // pointerdowns whose target is the scroll node itself rather than a
3916
- // message row.
3917
- const handlePointerDown = (event: PointerEvent) => {
3918
- if (event.target === scrollNode) {
3919
- if (contentScrollsUp()) {
3920
- handleManualNavigation();
3921
- }
3922
- return;
3923
- }
3924
- if (viewportIsAwayFromEnd()) {
3925
- handleManualNavigation();
3926
- }
3927
- };
3928
- // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
3929
- // pointer events entirely; without this the timeline yanks back to
3930
- // the end on the next stream chunk. Clicking message text can leave
3931
- // DOM focus on body, so these keys must also be heard at document.
3932
- const handleKeyDown = (event: KeyboardEvent) => {
3933
- if (
3934
- !(event.target instanceof Node) ||
3935
- (!scrollNode.contains(event.target) &&
3936
- event.target !== document.body &&
3937
- event.target !== document.documentElement) ||
3938
- event.defaultPrevented ||
3939
- event.isComposing ||
3940
- event.altKey ||
3941
- event.ctrlKey ||
3942
- event.metaKey ||
3943
- event.shiftKey ||
3944
- eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
3945
- document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
3946
- ) {
3947
- return;
3948
- }
3949
- if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
3950
- return;
3951
- const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
3952
- if (
3953
- scrollNode.contains(event.target) &&
3954
- !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
3955
- )
3956
- return;
3957
- switch (event.key) {
3958
- case "PageUp":
3959
- case "Home":
3960
- case "ArrowUp":
3961
- timelineScrollIntentRef.current = "away-from-end";
3962
- if (contentScrollsUp()) {
3963
- handleManualNavigation();
3964
- composer.current?.collapseForTimelineScrollKey(event.key);
3965
- }
3966
- break;
3967
- case "PageDown":
3968
- case "End":
3969
- case "ArrowDown":
3970
- timelineScrollIntentRef.current = "toward-end";
3971
- if (viewportIsAwayFromEnd()) {
3972
- handleManualNavigation();
3973
- }
3974
- composer.current?.collapseForTimelineScrollKey(event.key);
3975
- if (isTimelineAtLogicalEndStable()) {
3976
- composer.current?.restoreAfterTimelineReachedEnd();
3977
- }
3978
- break;
3979
- default:
3980
- break;
3981
- }
3982
- };
3983
- // Input inside an embedded frame reaches none of the listeners above,
3984
- // but its scroll still chains out to the timeline (#17056).
3985
- const scrolledUp = createUpwardScrollDetector({
3986
- top: scrollNode.scrollTop,
3987
- height: scrollNode.scrollHeight,
3988
- });
3989
- const handleScroll = () => {
3990
- if (
3991
- scrolledUp({
3992
- top: scrollNode.scrollTop,
3993
- height: scrollNode.scrollHeight,
3994
- programmatic:
3995
- positionedTimelineAnchorRef.current !== null &&
3996
- positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,
3997
- }) &&
3998
- timelineScrollModeRef.current !== "free-scrolling" &&
3999
- // LegendList updates its scroll state on the next animation frame.
4000
- resolveTimelineIsAtEnd({
4001
- contentLength: scrollNode.scrollHeight,
4002
- scroll: scrollNode.scrollTop,
4003
- scrollLength: scrollNode.clientHeight,
4004
- }) === false
4005
- ) {
4006
- handleManualNavigation();
4007
- }
4008
- };
4009
- scrollNode.addEventListener("scroll", handleScroll, { passive: true });
4010
- scrollNode.addEventListener("wheel", handleWheel, {
4011
- passive: true,
4012
- });
4013
- scrollNode.addEventListener("touchmove", handleTouchMove, {
4014
- passive: true,
4015
- });
4016
- scrollNode.addEventListener("pointerdown", handlePointerDown, {
4017
- passive: true,
4018
- });
4019
- document.addEventListener("keydown", handleKeyDown);
4020
- removeListeners = () => {
4021
- scrollNode.removeEventListener("scroll", handleScroll);
4022
- scrollNode.removeEventListener("wheel", handleWheel);
4023
- scrollNode.removeEventListener("touchmove", handleTouchMove);
4024
- scrollNode.removeEventListener("pointerdown", handlePointerDown);
4025
- document.removeEventListener("keydown", handleKeyDown);
4026
- };
4027
- });
4028
- };
4029
- attach(12);
4030
-
4031
- return () => {
4032
- if (frame !== null) {
4033
- cancelAnimationFrame(frame);
4034
- }
4035
- removeListeners?.();
4036
- };
4037
- }, [
4038
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
4039
- activeThread?.id,
3651
+ onComposerPageScrollKeyDownStable,
3652
+ onComposerPageScrollKeyUpStable,
3653
+ onComposerPageScrollReleaseStable,
3654
+ scrollToEnd,
3655
+ onTimelineAnchorReadyStable,
3656
+ onTimelineAnchorSizeChangedStable,
3657
+ onToolOutputCollapsedAtEndStable,
3658
+ onIsAtEndChangeStable,
3659
+ anchorNewTurn,
3660
+ } = useTimelineFollow({
3661
+ legendListRef,
3662
composerRef,
4041
- isTimelineAtLogicalEndStable,
4042
- timelineRealContentOverflowsViewportStable,
4043
- ]);
4044
-
4045
- const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
4046
- if (pendingTimelineAnchorRef.current === messageId) {
4047
- pendingTimelineAnchorRef.current = null;
4048
- }
4049
- activeTimelineAnchorIndexRef.current = anchorIndex;
4050
- if (positionedTimelineAnchorRef.current === messageId) {
4051
- return;
4052
- }
4053
- positionedTimelineAnchorRef.current = messageId;
4054
- settledTimelineAnchorRef.current = null;
4055
- const positionAnchor = (remainingAttempts: number) => {
4056
- requestAnimationFrame(() => {
4057
- if (positionedTimelineAnchorRef.current !== messageId) {
4058
- return;
4059
- }
4060
- const list = legendListRef.current;
4061
- if (!list) {
4062
- if (remainingAttempts > 0) {
4063
- positionAnchor(remainingAttempts - 1);
4064
- }
4065
- return;
4066
- }
4067
- // LegendList waits for queued layout and the animation before resolving.
4068
- void list
4069
- .scrollToIndex({
4070
- index: anchorIndex,
4071
- animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
4072
- viewPosition: 0,
4073
- viewOffset: CHAT_LIST_ANCHOR_OFFSET,
4074
- })
4075
- .then(() => {
4076
- if (
4077
- legendListRef.current === list &&
4078
- positionedTimelineAnchorRef.current === messageId
4079
- ) {
4080
- settledTimelineAnchorRef.current = messageId;
4081
- }
4082
- });
4083
- });
4084
- };
4085
- requestAnimationFrame(() => positionAnchor(12));
4086
- };
4087
- const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
4088
- const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
4089
- if (settledTimelineAnchorRef.current !== messageId) {
4090
- return;
4091
- }
4092
- if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
4093
- return;
4094
- }
4095
- const scrollOffset = legendListRef.current?.getState().scroll;
4096
- if (scrollOffset === undefined) {
4097
- return;
4098
- }
4099
- if (pendingAnchorScrollRestoreRef.current === null) {
4100
- pendingAnchorScrollRestoreRef.current = {
4101
- messageId,
4102
- offset: scrollOffset,
4103
- userScrollGeneration: anchorUserScrollGenerationRef.current,
4104
- };
4105
- }
4106
- if (anchorScrollRestoreFrameRef.current !== null) {
4107
- return;
4108
- }
4109
- anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
4110
- anchorScrollRestoreFrameRef.current = null;
4111
- const pending = pendingAnchorScrollRestoreRef.current;
4112
- pendingAnchorScrollRestoreRef.current = null;
4113
- if (
4114
- pending &&
4115
- settledTimelineAnchorRef.current === pending.messageId &&
4116
- pending.userScrollGeneration === anchorUserScrollGenerationRef.current
4117
- ) {
4118
- const list = legendListRef.current;
4119
- const currentScrollOffset = list?.getState().scroll;
4120
- if (
4121
- typeof currentScrollOffset === "number" &&
4122
- Math.abs(currentScrollOffset - pending.offset) <= 2
4123
- ) {
4124
- void list?.scrollToOffset({ offset: pending.offset, animated: false });
4125
- }
4126
- }
4127
- });
4128
- };
4129
- const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
4130
-
4131
- const onToolOutputCollapsedAtEnd = () => {
4132
- composerRef.current?.restoreAfterTimelineReachedEnd();
4133
- };
4134
- const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
4135
-
4136
- const onIsAtEndChange = (isAtEnd: boolean) => {
4137
- if (
4138
- !isAtEnd &&
4139
- liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
4140
- ) {
4141
- showScrollDebouncer.current.cancel();
4142
- setShowScrollToBottom(false);
4143
- return;
4144
- }
4145
- if (isAtEndRef.current === isAtEnd) return;
4146
- isAtEndRef.current = isAtEnd;
4147
- if (isAtEnd) {
4148
- if (timelineScrollIntentRef.current === "toward-end") {
4149
- composerRef.current?.restoreAfterTimelineReachedEnd();
4150
- }
4151
- timelineScrollModeRef.current = "following-end";
4152
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
4153
- setTimelineLiveFollowEnabled(true);
4154
- setTimelineAnchor(releaseChatTimelineAnchor);
4155
- showScrollDebouncer.current.cancel();
4156
- setShowScrollToBottom(false);
4157
- } else {
4158
- timelineScrollModeRef.current = "free-scrolling";
4159
- liveFollowUserScrollGenerationRef.current = null;
4160
- showScrollDebouncer.current.maybeExecute();
4161
- }
4162
- };
4163
- const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
4164
-
4165
- useLayoutEffect(() => {
4166
- if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
4167
- if (
4168
- shouldReleaseTimelineAnchorForToolActivity({
4169
- anchorMessageId: timelineAnchorMessageId,
4170
- liveFollowEnabled: timelineLiveFollowEnabled,
4171
- runningTurnId: activeRunningTurnId,
4172
- timelineEntries,
4173
- })
4174
- ) {
4175
- scrollToEndStable();
4176
- }
4177
- }, [
3663
+ composerOverlayElement,
3664
+ composerTimelineInset,
3665
+ routeThreadKey,
3666
+ activeThreadKey,
3667
+ activeThreadId: activeThread?.id,
3668
+ isServerThread,
3669
+ serverProjection,
3670
+ threadStatus,
3671
+ activeActivityRun,
3672
activeRunningTurnId,
4179
- scrollToEndStable,
4180
- timelineAnchorMessageId,
3673
timelineEntries,
4182
- timelineLiveFollowEnabled,
4183
- ]);
4184
-
4185
- // A thread switch restores that thread's remembered follow state; the refs
4186
- // the scroll handlers read catch up after commit.
4187
- const [timelineThreadReset, setTimelineThreadReset] = useState({
4188
- threadKey: activeThreadKey,
4189
- followEnd: true,
3674
+ timelineAnchorMessageId,
3675
+ setTimelineAnchor,
3676
});
4191
- if (timelineThreadReset.threadKey !== activeThreadKey) {
4192
- const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
4193
- setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
4194
- setTimelineLiveFollowEnabled(followEnd);
4195
- setShowScrollToBottom(!followEnd);
4196
- }
4197
- useEffect(() => {
4198
- const { followEnd } = timelineThreadReset;
4199
- isAtEndRef.current = followEnd;
4200
- timelineScrollIntentRef.current = null;
4201
- timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
4202
- liveFollowUserScrollGenerationRef.current = followEnd
4203
- ? anchorUserScrollGenerationRef.current
4204
- : null;
4205
- pendingTimelineAnchorRef.current = null;
4206
- positionedTimelineAnchorRef.current = null;
4207
- settledTimelineAnchorRef.current = null;
4208
- activeTimelineAnchorIndexRef.current = null;
4209
- showScrollDebouncer.current.cancel();
4210
- }, [timelineThreadReset]);
3677
3678
useEffect(() => {
3679
if (!activeThread?.id || terminalUiState.terminalOpen) return;
@@ -6658,18 +6124,10 @@ export default function ChatView(props: ChatViewProps) {
6124
},
6125
);
6126
if (!shouldQueueBehindActiveRun) {
6661
- isAtEndRef.current = true;
6662
- timelineScrollModeRef.current = "anchoring-new-turn";
6663
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
6664
- setTimelineLiveFollowEnabled(true);
6665
- pendingTimelineAnchorRef.current = messageIdForSend;
6666
- activeTimelineAnchorIndexRef.current = null;
6667
- showScrollDebouncer.current.cancel();
6668
- setShowScrollToBottom(false);
6669
- setTimelineAnchor({
6670
- threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
6671
- messageId: messageIdForSend,
6672
- });
6127
+ anchorNewTurn(
6128
+ scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
6129
+ messageIdForSend,
6130
+ );
6131
}
6132
setOptimisticUserMessages((existing) => [
6133
...existing,
@@ -7066,18 +6524,10 @@ export default function ChatView(props: ChatViewProps) {
6524
beginLocalDispatch({ preparingWorktree: false });
6525
setThreadError(threadIdForSend, null);
6526
7069
- isAtEndRef.current = true;
7070
- timelineScrollModeRef.current = "anchoring-new-turn";
7071
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
7072
- setTimelineLiveFollowEnabled(true);
7073
- pendingTimelineAnchorRef.current = messageIdForSend;
7074
- activeTimelineAnchorIndexRef.current = null;
7075
- showScrollDebouncer.current.cancel();
7076
- setShowScrollToBottom(false);
7077
- setTimelineAnchor({
7078
- threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
7079
- messageId: messageIdForSend,
7080
- });
6527
+ anchorNewTurn(
6528
+ scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
6529
+ messageIdForSend,
6530
+ );
6531
6532
setOptimisticUserMessages((existing) => [
6533
...existing,
apps/web/src/components/chat/useTimelineFollow.ts
new
+665
@@ -0,0 +1,665 @@
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";
8
+import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
9
+import { Debouncer } from "@tanstack/react-pacer";
10
+import {
11
+ type SetStateAction,
12
+ useEffect,
13
+ useEffectEvent,
14
+ useLayoutEffect,
15
+ useRef,
16
+ useState,
17
+} from "react";
18
+import { type LegendListRef } from "@legendapp/list/react";
19
+import {
20
+ CHAT_TIMELINE_ANCHOR_OFFSET,
21
+ timelineContentOverflowsViewport,
22
+ readTimelinePosition,
23
+ observeTimelineRun,
24
+ type TimelineRunObservation,
25
+ type TimelineScrollMode,
26
+} from "./timelineScrollAnchoring";
27
+import { type ChatComposerHandle } from "./ChatComposer";
28
+import { createPageScrollController, type PageScrollKey } from "./pageScrollController";
29
+import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
30
+import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
31
+import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
32
+import { releaseChatTimelineAnchor } from "../ChatView.logic";
33
+import type { Dispatch, RefObject } from "react";
34
+import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
35
+import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
36
+import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
37
+import type { TimelineEntry } from "../../session-logic";
38
+
39
+const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
40
+
41
+interface TimelineAnchor {
42
+ readonly threadKey: string | null;
43
+ readonly messageId: MessageId | null;
44
+}
45
+
46
+interface TimelineFollowInput {
47
+ readonly legendListRef: RefObject<LegendListRef | null>;
48
+ readonly composerRef: RefObject<ChatComposerHandle | null>;
49
+ readonly composerOverlayElement: HTMLDivElement | null;
50
+ readonly composerTimelineInset: number;
51
+ readonly routeThreadKey: string;
52
+ readonly activeThreadKey: string | null;
53
+ readonly activeThreadId: ThreadId | undefined;
54
+ readonly isServerThread: boolean;
55
+ readonly serverProjection: EnvironmentThread["projection"] | null;
56
+ readonly threadStatus: EnvironmentThreadStatus;
57
+ readonly activeActivityRun: ReturnType<typeof deriveThreadActivityRun>;
58
+ readonly activeRunningTurnId: RunId | null;
59
+ readonly timelineEntries: ReadonlyArray<TimelineEntry>;
60
+ readonly timelineAnchorMessageId: MessageId | null;
61
+ readonly setTimelineAnchor: Dispatch<SetStateAction<TimelineAnchor>>;
62
+}
63
+
64
+/**
65
+ * Keeps the timeline following the live end, anchoring a newly sent turn near
66
+ * the top, and letting the user scroll away. The scroll handlers read refs, so
67
+ * a scroll gesture does not re-render ChatView unless the follow mode flips.
68
+ */
69
+export function useTimelineFollow(input: TimelineFollowInput) {
70
+ const {
71
+ legendListRef,
72
+ composerRef,
73
+ composerOverlayElement,
74
+ composerTimelineInset,
75
+ routeThreadKey,
76
+ activeThreadKey,
77
+ activeThreadId,
78
+ isServerThread,
79
+ serverProjection,
80
+ threadStatus,
81
+ activeActivityRun,
82
+ activeRunningTurnId,
83
+ timelineEntries,
84
+ timelineAnchorMessageId,
85
+ setTimelineAnchor,
86
+ } = input;
87
+ const [showScrollToBottom, setShowScrollToBottom] = useState(false);
88
+ const isAtEndRef = useRef(true);
89
+ const isTimelineAtLogicalEnd = () =>
90
+ resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
91
+ const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
92
+ // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
93
+ // thread switches. LegendList fires scroll events with isAtEnd=false while
94
+ // initialScrollAtEnd is settling; hiding is always immediate.
95
+ const showScrollDebouncer = useRef(
96
+ new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
97
+ );
98
+ const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);
99
+ const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
100
+ // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
101
+ // re-pins on its own (independent of the refs), so the timeline needs a
102
+ // render-visible flag to switch it off once the user scrolls away.
103
+ const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
104
+ const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
105
+ const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
106
+ const settledTimelineAnchorRef = useRef<MessageId | null>(null);
107
+ const activeTimelineAnchorIndexRef = useRef<number | null>(null);
108
+ const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);
109
+ const anchorUserScrollGenerationRef = useRef(0);
110
+ const cancelPositionRestoreRef = useRef<(() => void) | null>(null);
111
+ const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
112
+ const pendingAnchorScrollRestoreRef = useRef<{
113
+ readonly messageId: MessageId;
114
+ readonly offset: number;
115
+ readonly userScrollGeneration: number;
116
+ } | null>(null);
117
+ const anchorScrollRestoreFrameRef = useRef<number | null>(null);
118
+ const cancelTimelineLiveFollowForUserNavigation = () => {
119
+ cancelPositionRestoreRef.current?.();
120
+ anchorUserScrollGenerationRef.current += 1;
121
+ const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
122
+ timelineScrollModeRef.current = "free-scrolling";
123
+ liveFollowUserScrollGenerationRef.current = null;
124
+ setTimelineLiveFollowEnabled(false);
125
+ pendingTimelineAnchorRef.current = null;
126
+ positionedTimelineAnchorRef.current = null;
127
+ settledTimelineAnchorRef.current = null;
128
+ activeTimelineAnchorIndexRef.current = null;
129
+ pendingAnchorScrollRestoreRef.current = null;
130
+ if (anchorScrollRestoreFrameRef.current !== null) {
131
+ cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
132
+ anchorScrollRestoreFrameRef.current = null;
133
+ }
134
+ if (wasProgrammaticScrollMode) {
135
+ // While following or anchoring, our scrollToEnd/scrollToOffset calls can
136
+ // sit in LegendList's pending-imperative-scroll queue (it defers them
137
+ // while layout settles) and fire seconds later with stale targets,
138
+ // yanking the view away after the user scrolled. Starting a new
139
+ // imperative scroll cancels everything queued; targeting an item that
140
+ // is not in the data makes the new request itself resolve without ever
141
+ // scrolling, so this is a pure cancel.
142
+ void legendListRef.current?.scrollToItem({
143
+ item: TIMELINE_SCROLL_CANCEL_SENTINEL,
144
+ animated: false,
145
+ });
146
+ // An already-started animated scroll (behavior: smooth) keeps running in
147
+ // the browser regardless of the queue; a same-position instant write is
148
+ // the only way to halt it where it is.
149
+ const scrollNode = legendListRef.current?.getScrollableNode() as
150
+ | { scrollTop?: number }
151
+ | null
152
+ | undefined;
153
+ const currentScrollTop = scrollNode?.scrollTop;
154
+ if (scrollNode && typeof currentScrollTop === "number") {
155
+ scrollNode.scrollTop = currentScrollTop;
156
+ }
157
+ }
158
+ };
159
+ const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
160
+ cancelTimelineLiveFollowForUserNavigation,
161
+ );
162
+ const cancelTimelineLiveFollowForUserNavigationRef = useRef(
163
+ cancelTimelineLiveFollowForUserNavigationStable,
164
+ );
165
+ useEffect(() => {
166
+ cancelTimelineLiveFollowForUserNavigationRef.current =
167
+ cancelTimelineLiveFollowForUserNavigationStable;
168
+ }, [cancelTimelineLiveFollowForUserNavigationStable]);
169
+ useEffect(() => {
170
+ const previous = observedTimelineActivityRef.current;
171
+ const dispatchedUserItem =
172
+ previous?.hydrated &&
173
+ previous.threadKey === activeThreadKey &&
174
+ activeActivityRun !== null &&
175
+ previous.runId !== activeActivityRun.runId
176
+ ? serverProjection?.visibleTurnItems.find(
177
+ (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
178
+ )
179
+ : undefined;
180
+ const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {
181
+ threadKey: activeThreadKey,
182
+ hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
183
+ runId: activeActivityRun?.runId ?? null,
184
+ queued: activeActivityRun?.status === "queued",
185
+ messageId:
186
+ dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
187
+ });
188
+ observedTimelineActivityRef.current = observation;
189
+ if (messageId === null) return;
190
+ if (
191
+ pendingTimelineAnchorRef.current !== null ||
192
+ timelineScrollModeRef.current === "free-scrolling"
193
+ ) {
194
+ return;
195
+ }
196
+
197
+ isAtEndRef.current = true;
198
+ timelineScrollModeRef.current = "anchoring-new-turn";
199
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
200
+ pendingTimelineAnchorRef.current = messageId;
201
+ activeTimelineAnchorIndexRef.current = null;
202
+ showScrollDebouncer.current.cancel();
203
+ setShowScrollToBottom(false);
204
+ setTimelineAnchor({ threadKey: activeThreadKey, messageId });
205
+ }, [
206
+ activeActivityRun,
207
+ activeThreadKey,
208
+ isServerThread,
209
+ serverProjection,
210
+ setTimelineAnchor,
211
+ threadStatus,
212
+ ]);
213
+ const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
214
+ timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
215
+ composerInset: composerTimelineInset,
216
+ anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
217
+ });
218
+ const timelineRealContentOverflowsViewportStable = useStableCallback(
219
+ timelineRealContentOverflowsViewport,
220
+ );
221
+ const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
222
+ null,
223
+ );
224
+ const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
225
+ timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
226
+ composerRef.current?.collapseForTimelineScrollKey(key);
227
+ if (
228
+ (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
229
+ !isTimelineAtLogicalEndStable()
230
+ ) {
231
+ cancelTimelineLiveFollowForUserNavigationStable();
232
+ }
233
+ });
234
+ useEffect(() => {
235
+ const controller = createPageScrollController({
236
+ getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
237
+ getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
238
+ onScrollStart: handlePageScrollStart,
239
+ });
240
+ pageScrollControllerRef.current = controller;
241
+
242
+ return () => {
243
+ controller.dispose();
244
+ if (pageScrollControllerRef.current === controller) {
245
+ pageScrollControllerRef.current = null;
246
+ }
247
+ };
248
+ }, [composerOverlayElement, legendListRef]);
249
+ const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
250
+ pageScrollControllerRef.current?.handleKeyDown(key);
251
+ };
252
+ const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
253
+ const onComposerPageScrollKeyUp = (key: string) => {
254
+ pageScrollControllerRef.current?.handleKeyUp(key);
255
+ };
256
+ const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
257
+ const onComposerPageScrollRelease = () => {
258
+ pageScrollControllerRef.current?.releaseActiveKey();
259
+ };
260
+ const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
261
+ const scrollToEnd = (animated: boolean = false) => {
262
+ cancelPositionRestoreRef.current?.();
263
+ isAtEndRef.current = true;
264
+ timelineScrollModeRef.current = "following-end";
265
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
266
+ setTimelineLiveFollowEnabled(true);
267
+ pendingTimelineAnchorRef.current = null;
268
+ activeTimelineAnchorIndexRef.current = null;
269
+ showScrollDebouncer.current.cancel();
270
+ setShowScrollToBottom(false);
271
+ setTimelineAnchor(releaseChatTimelineAnchor);
272
+ // The anchored end space must be gone before the scroll measures, or the
273
+ // list lands short of the real end (#6519).
274
+ requestAnimationFrame(() => {
275
+ void legendListRef.current?.scrollToEnd?.({
276
+ animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
277
+ });
278
+ });
279
+ };
280
+ const scrollToEndStable = useStableCallback(scrollToEnd);
281
+ useEffect(() => {
282
+ const composer = composerRef;
283
+ let removeListeners: (() => void) | null = null;
284
+ let frame: number | null = null;
285
+ const attach = (remainingAttempts: number) => {
286
+ frame = requestAnimationFrame(() => {
287
+ frame = null;
288
+ const scrollNode = legendListRef.current?.getScrollableNode();
289
+ if (!scrollNode) {
290
+ // The list may not have mounted on the first frame after a thread
291
+ // switch — without a retry the opt-out listeners never attach and
292
+ // live-follow becomes impossible to escape for the whole thread.
293
+ if (remainingAttempts > 0) {
294
+ attach(remainingAttempts - 1);
295
+ }
296
+ return;
297
+ }
298
+ const handleManualNavigation = () => {
299
+ cancelTimelineLiveFollowForUserNavigationRef.current();
300
+ };
301
+ // The gestures below must only break follow when they can actually
302
+ // move the viewport away from the live edge (#5566): a spurious break
303
+ // while pinned at the end produces no scroll event, never re-arms,
304
+ // and streaming silently stops following. Underflowing content can't
305
+ // scroll at all, so nothing there should break follow.
306
+ const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
307
+ // The follow re-arm band, not the strict flag: streaming growth makes
308
+ // isAtEnd flicker false for a frame before the follow scroll catches
309
+ // up, and a gesture landing in that window while still pinned would
310
+ // otherwise break follow with no scroll event left to re-arm it.
311
+ const viewportIsAwayFromEnd = () =>
312
+ resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
313
+ const handleWheel = (event: WheelEvent) => {
314
+ if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
315
+ return;
316
+ if (event.deltaY > 0) {
317
+ timelineScrollIntentRef.current = "toward-end";
318
+ if (isAtEndRef.current) {
319
+ composer.current?.restoreAfterTimelineReachedEnd();
320
+ }
321
+ } else if (event.deltaY < 0) {
322
+ timelineScrollIntentRef.current = "away-from-end";
323
+ }
324
+ if (event.deltaY < 0 && contentScrollsUp()) {
325
+ handleManualNavigation();
326
+ }
327
+ };
328
+ // Touch direction isn't observable here (touchmove fires on any
329
+ // finger motion, scrolling or not), so break only once the drag has
330
+ // actually carried the viewport out of the end band — an upward flick
331
+ // gets there within its first few events and later touchmoves break.
332
+ const handleTouchMove = () => {
333
+ if (viewportIsAwayFromEnd()) {
334
+ handleManualNavigation();
335
+ }
336
+ };
337
+ // Scrollbar drags produce no wheel/touch events; they are the only
338
+ // pointerdowns whose target is the scroll node itself rather than a
339
+ // message row.
340
+ const handlePointerDown = (event: PointerEvent) => {
341
+ if (event.target === scrollNode) {
342
+ if (contentScrollsUp()) {
343
+ handleManualNavigation();
344
+ }
345
+ return;
346
+ }
347
+ if (viewportIsAwayFromEnd()) {
348
+ handleManualNavigation();
349
+ }
350
+ };
351
+ // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
352
+ // pointer events entirely; without this the timeline yanks back to
353
+ // the end on the next stream chunk. Clicking message text can leave
354
+ // DOM focus on body, so these keys must also be heard at document.
355
+ const handleKeyDown = (event: KeyboardEvent) => {
356
+ if (
357
+ !(event.target instanceof Node) ||
358
+ (!scrollNode.contains(event.target) &&
359
+ event.target !== document.body &&
360
+ event.target !== document.documentElement) ||
361
+ event.defaultPrevented ||
362
+ event.isComposing ||
363
+ event.altKey ||
364
+ event.ctrlKey ||
365
+ event.metaKey ||
366
+ event.shiftKey ||
367
+ eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
368
+ document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
369
+ ) {
370
+ return;
371
+ }
372
+ if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
373
+ return;
374
+ const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
375
+ if (
376
+ scrollNode.contains(event.target) &&
377
+ !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
378
+ )
379
+ return;
380
+ switch (event.key) {
381
+ case "PageUp":
382
+ case "Home":
383
+ case "ArrowUp":
384
+ timelineScrollIntentRef.current = "away-from-end";
385
+ if (contentScrollsUp()) {
386
+ handleManualNavigation();
387
+ composer.current?.collapseForTimelineScrollKey(event.key);
388
+ }
389
+ break;
390
+ case "PageDown":
391
+ case "End":
392
+ case "ArrowDown":
393
+ timelineScrollIntentRef.current = "toward-end";
394
+ if (viewportIsAwayFromEnd()) {
395
+ handleManualNavigation();
396
+ }
397
+ composer.current?.collapseForTimelineScrollKey(event.key);
398
+ if (isTimelineAtLogicalEndStable()) {
399
+ composer.current?.restoreAfterTimelineReachedEnd();
400
+ }
401
+ break;
402
+ default:
403
+ break;
404
+ }
405
+ };
406
+ // Input inside an embedded frame reaches none of the listeners above,
407
+ // but its scroll still chains out to the timeline (#17056).
408
+ const scrolledUp = createUpwardScrollDetector({
409
+ top: scrollNode.scrollTop,
410
+ height: scrollNode.scrollHeight,
411
+ });
412
+ const handleScroll = () => {
413
+ if (
414
+ scrolledUp({
415
+ top: scrollNode.scrollTop,
416
+ height: scrollNode.scrollHeight,
417
+ programmatic:
418
+ positionedTimelineAnchorRef.current !== null &&
419
+ positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,
420
+ }) &&
421
+ timelineScrollModeRef.current !== "free-scrolling" &&
422
+ // LegendList updates its scroll state on the next animation frame.
423
+ resolveTimelineIsAtEnd({
424
+ contentLength: scrollNode.scrollHeight,
425
+ scroll: scrollNode.scrollTop,
426
+ scrollLength: scrollNode.clientHeight,
427
+ }) === false
428
+ ) {
429
+ handleManualNavigation();
430
+ }
431
+ };
432
+ scrollNode.addEventListener("scroll", handleScroll, { passive: true });
433
+ scrollNode.addEventListener("wheel", handleWheel, {
434
+ passive: true,
435
+ });
436
+ scrollNode.addEventListener("touchmove", handleTouchMove, {
437
+ passive: true,
438
+ });
439
+ scrollNode.addEventListener("pointerdown", handlePointerDown, {
440
+ passive: true,
441
+ });
442
+ document.addEventListener("keydown", handleKeyDown);
443
+ removeListeners = () => {
444
+ scrollNode.removeEventListener("scroll", handleScroll);
445
+ scrollNode.removeEventListener("wheel", handleWheel);
446
+ scrollNode.removeEventListener("touchmove", handleTouchMove);
447
+ scrollNode.removeEventListener("pointerdown", handlePointerDown);
448
+ document.removeEventListener("keydown", handleKeyDown);
449
+ };
450
+ });
451
+ };
452
+ attach(12);
453
+
454
+ return () => {
455
+ if (frame !== null) {
456
+ cancelAnimationFrame(frame);
457
+ }
458
+ removeListeners?.();
459
+ };
460
+ }, [
461
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
462
+ activeThreadId,
463
+ composerRef,
464
+ isTimelineAtLogicalEndStable,
465
+ legendListRef,
466
+ timelineRealContentOverflowsViewportStable,
467
+ ]);
468
+
469
+ const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
470
+ if (pendingTimelineAnchorRef.current === messageId) {
471
+ pendingTimelineAnchorRef.current = null;
472
+ }
473
+ activeTimelineAnchorIndexRef.current = anchorIndex;
474
+ if (positionedTimelineAnchorRef.current === messageId) {
475
+ return;
476
+ }
477
+ positionedTimelineAnchorRef.current = messageId;
478
+ settledTimelineAnchorRef.current = null;
479
+ const positionAnchor = (remainingAttempts: number) => {
480
+ requestAnimationFrame(() => {
481
+ if (positionedTimelineAnchorRef.current !== messageId) {
482
+ return;
483
+ }
484
+ const list = legendListRef.current;
485
+ if (!list) {
486
+ if (remainingAttempts > 0) {
487
+ positionAnchor(remainingAttempts - 1);
488
+ }
489
+ return;
490
+ }
491
+ // LegendList waits for queued layout and the animation before resolving.
492
+ void list
493
+ .scrollToIndex({
494
+ index: anchorIndex,
495
+ animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
496
+ viewPosition: 0,
497
+ viewOffset: CHAT_LIST_ANCHOR_OFFSET,
498
+ })
499
+ .then(() => {
500
+ if (
501
+ legendListRef.current === list &&
502
+ positionedTimelineAnchorRef.current === messageId
503
+ ) {
504
+ settledTimelineAnchorRef.current = messageId;
505
+ }
506
+ });
507
+ });
508
+ };
509
+ requestAnimationFrame(() => positionAnchor(12));
510
+ };
511
+ const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
512
+ const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
513
+ if (settledTimelineAnchorRef.current !== messageId) {
514
+ return;
515
+ }
516
+ if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
517
+ return;
518
+ }
519
+ const scrollOffset = legendListRef.current?.getState().scroll;
520
+ if (scrollOffset === undefined) {
521
+ return;
522
+ }
523
+ if (pendingAnchorScrollRestoreRef.current === null) {
524
+ pendingAnchorScrollRestoreRef.current = {
525
+ messageId,
526
+ offset: scrollOffset,
527
+ userScrollGeneration: anchorUserScrollGenerationRef.current,
528
+ };
529
+ }
530
+ if (anchorScrollRestoreFrameRef.current !== null) {
531
+ return;
532
+ }
533
+ anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
534
+ anchorScrollRestoreFrameRef.current = null;
535
+ const pending = pendingAnchorScrollRestoreRef.current;
536
+ pendingAnchorScrollRestoreRef.current = null;
537
+ if (
538
+ pending &&
539
+ settledTimelineAnchorRef.current === pending.messageId &&
540
+ pending.userScrollGeneration === anchorUserScrollGenerationRef.current
541
+ ) {
542
+ const list = legendListRef.current;
543
+ const currentScrollOffset = list?.getState().scroll;
544
+ if (
545
+ typeof currentScrollOffset === "number" &&
546
+ Math.abs(currentScrollOffset - pending.offset) <= 2
547
+ ) {
548
+ void list?.scrollToOffset({ offset: pending.offset, animated: false });
549
+ }
550
+ }
551
+ });
552
+ };
553
+ const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
554
+
555
+ const onToolOutputCollapsedAtEnd = () => {
556
+ composerRef.current?.restoreAfterTimelineReachedEnd();
557
+ };
558
+ const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
559
+
560
+ const onIsAtEndChange = (isAtEnd: boolean) => {
561
+ if (
562
+ !isAtEnd &&
563
+ liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
564
+ ) {
565
+ showScrollDebouncer.current.cancel();
566
+ setShowScrollToBottom(false);
567
+ return;
568
+ }
569
+ if (isAtEndRef.current === isAtEnd) return;
570
+ isAtEndRef.current = isAtEnd;
571
+ if (isAtEnd) {
572
+ if (timelineScrollIntentRef.current === "toward-end") {
573
+ composerRef.current?.restoreAfterTimelineReachedEnd();
574
+ }
575
+ timelineScrollModeRef.current = "following-end";
576
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
577
+ setTimelineLiveFollowEnabled(true);
578
+ setTimelineAnchor(releaseChatTimelineAnchor);
579
+ showScrollDebouncer.current.cancel();
580
+ setShowScrollToBottom(false);
581
+ } else {
582
+ timelineScrollModeRef.current = "free-scrolling";
583
+ liveFollowUserScrollGenerationRef.current = null;
584
+ showScrollDebouncer.current.maybeExecute();
585
+ }
586
+ };
587
+ const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
588
+
589
+ useLayoutEffect(() => {
590
+ if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
591
+ if (
592
+ shouldReleaseTimelineAnchorForToolActivity({
593
+ anchorMessageId: timelineAnchorMessageId,
594
+ liveFollowEnabled: timelineLiveFollowEnabled,
595
+ runningTurnId: activeRunningTurnId,
596
+ timelineEntries,
597
+ })
598
+ ) {
599
+ scrollToEndStable();
600
+ }
601
+ }, [
602
+ activeRunningTurnId,
603
+ scrollToEndStable,
604
+ timelineAnchorMessageId,
605
+ timelineEntries,
606
+ timelineLiveFollowEnabled,
607
+ ]);
608
+
609
+ // A thread switch restores that thread's remembered follow state; the refs
610
+ // the scroll handlers read catch up after commit.
611
+ const [timelineThreadReset, setTimelineThreadReset] = useState({
612
+ threadKey: activeThreadKey,
613
+ followEnd: true,
614
+ });
615
+ if (timelineThreadReset.threadKey !== activeThreadKey) {
616
+ const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
617
+ setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
618
+ setTimelineLiveFollowEnabled(followEnd);
619
+ setShowScrollToBottom(!followEnd);
620
+ }
621
+ useEffect(() => {
622
+ const { followEnd } = timelineThreadReset;
623
+ isAtEndRef.current = followEnd;
624
+ timelineScrollIntentRef.current = null;
625
+ timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
626
+ liveFollowUserScrollGenerationRef.current = followEnd
627
+ ? anchorUserScrollGenerationRef.current
628
+ : null;
629
+ pendingTimelineAnchorRef.current = null;
630
+ positionedTimelineAnchorRef.current = null;
631
+ settledTimelineAnchorRef.current = null;
632
+ activeTimelineAnchorIndexRef.current = null;
633
+ showScrollDebouncer.current.cancel();
634
+ }, [timelineThreadReset]);
635
+
636
+ /** Arms the anchor for a message the user just sent, before its run exists. */
637
+ const anchorNewTurn = (threadKey: string, messageId: MessageId) => {
638
+ isAtEndRef.current = true;
639
+ timelineScrollModeRef.current = "anchoring-new-turn";
640
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
641
+ setTimelineLiveFollowEnabled(true);
642
+ pendingTimelineAnchorRef.current = messageId;
643
+ activeTimelineAnchorIndexRef.current = null;
644
+ showScrollDebouncer.current.cancel();
645
+ setShowScrollToBottom(false);
646
+ setTimelineAnchor({ threadKey, messageId });
647
+ };
648
+
649
+ return {
650
+ showScrollToBottom,
651
+ timelineLiveFollowEnabled,
652
+ cancelPositionRestoreRef,
653
+ isTimelineAtLogicalEndStable,
654
+ cancelTimelineLiveFollowForUserNavigationStable,
655
+ onComposerPageScrollKeyDownStable,
656
+ onComposerPageScrollKeyUpStable,
657
+ onComposerPageScrollReleaseStable,
658
+ scrollToEnd,
659
+ onTimelineAnchorReadyStable,
660
+ onTimelineAnchorSizeChangedStable,
661
+ onToolOutputCollapsedAtEndStable,
662
+ onIsAtEndChangeStable,
663
+ anchorNewTurn,
664
+ };
665
+}