Skip to content
TypeScript

refactor(web): ChatView's timeline follow and anchoring lives in useTimelineFollow (#22701)

Julius Marminge6b13e8f01ce6
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 1082c518c56..3956d4b65fa 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -44,11 +44,8 @@ import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
import { useWorktreeSetup } from "./chat/useWorktreeSetup";
import { useChatShortcuts, type ChatShortcutHandler } from "./chat/useChatShortcuts";
import {
- eventPathContainsSelector,
pasteTextToFocusComposer,
shouldRedirectInputToComposer,
- TYPE_TO_FOCUS_EDITABLE_SELECTOR,
- TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
} from "./chat/composerFocusRedirect";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as Schema from "effect/Schema";
@@ -130,7 +127,6 @@ import {
projectScriptTerminalInput,
resolveProjectScripts,
} from "@t3tools/shared/projectScripts";
-import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import {
latestUnheldRun,
@@ -141,17 +137,8 @@ import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
import { truncate } from "@t3tools/shared/String";
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
-import { Debouncer } from "@tanstack/react-pacer";
import { useAtomValue } from "@effect/atom-react";
-import {
- Fragment,
- type SetStateAction,
- useEffect,
- useEffectEvent,
- useLayoutEffect,
- useRef,
- useState,
-} from "react";
+import { Fragment, type SetStateAction, useEffect, useLayoutEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
@@ -189,14 +176,6 @@ import {
isLatestRunSettled,
} from "../session-logic";
import { type LegendListRef } from "@legendapp/list/react";
-import {
- CHAT_TIMELINE_ANCHOR_OFFSET,
- timelineContentOverflowsViewport,
- readTimelinePosition,
- observeTimelineRun,
- type TimelineRunObservation,
- type TimelineScrollMode,
-} from "./chat/timelineScrollAnchoring";
import { useUiStateStore } from "../uiStateStore";
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
import {
@@ -383,8 +362,6 @@ import {
} from "../state/entities";
import { environmentShell, useEnvironmentShellHasSnapshot } from "../state/shell";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
-import { createPageScrollController, type PageScrollKey } from "./chat/pageScrollController";
-import { createUpwardScrollDetector, isTimelineScrollTarget } from "./chat/timelineScrollTarget";
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog";
import {
@@ -401,7 +378,6 @@ import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
-import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";
import {
overlayComposerIsResting,
resolveComposerTimelineInset,
@@ -476,7 +452,6 @@ import {
isBranchMismatchDismissedForSession,
shouldShowBranchMismatchBanner,
shouldShowPlanFollowUpPrompt,
- shouldReleaseTimelineAnchorForToolActivity,
shouldRenderPreviewMiniPlayer,
getStartedThreadModelChangeBlockReason,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
@@ -542,6 +517,7 @@ import { observeResize } from "~/lib/observeResize";
import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
import { ChatRightPanel } from "./chat/ChatRightPanel";
+import { useTimelineFollow } from "./chat/useTimelineFollow";
import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition";
import { useLocalDispatchState } from "./chat/useLocalDispatchState";
import {
@@ -557,7 +533,6 @@ import {
type LocalThreadErrorEntry,
makeModelDisabledReason,
makeThreadErrorSetter,
- releaseChatTimelineAnchor,
} from "./ChatView.logic";
const EMPTY_PROVIDERS: ServerProvider[] = [];
@@ -565,7 +540,6 @@ const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = [];
const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
-const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -912,7 +886,6 @@ export default function ChatView(props: ChatViewProps) {
return inserted;
};
const citeAssistantTextStable = useStableCallback(citeAssistantText);
- const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
// Set by "Work locally": the draft whose restored message should be resent
@@ -996,10 +969,6 @@ export default function ChatView(props: ChatViewProps) {
const composerRestingRef = useRef(false);
const composerMountedRef = useRef(true);
const [scrollToEndClearance, setScrollToEndClearance] = useState(0);
- const isAtEndRef = useRef(true);
- const isTimelineAtLogicalEnd = () =>
- resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
- const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
const [timelineOverflows, setTimelineOverflows] = useState(false);
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
@@ -3673,541 +3642,38 @@ export default function ChatView(props: ChatViewProps) {
return result;
};
- // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
- // thread switches. LegendList fires scroll events with isAtEnd=false while
- // initialScrollAtEnd is settling; hiding is always immediate.
- const showScrollDebouncer = useRef(
- new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
- );
- const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);
- const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
- // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
- // re-pins on its own (independent of the refs), so the timeline needs a
- // render-visible flag to switch it off once the user scrolls away.
- const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
- const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
- const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
- const settledTimelineAnchorRef = useRef<MessageId | null>(null);
- const activeTimelineAnchorIndexRef = useRef<number | null>(null);
- const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);
- const anchorUserScrollGenerationRef = useRef(0);
- const cancelPositionRestoreRef = useRef<(() => void) | null>(null);
- const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
- const pendingAnchorScrollRestoreRef = useRef<{
- readonly messageId: MessageId;
- readonly offset: number;
- readonly userScrollGeneration: number;
- } | null>(null);
- const anchorScrollRestoreFrameRef = useRef<number | null>(null);
- const cancelTimelineLiveFollowForUserNavigation = () => {
- cancelPositionRestoreRef.current?.();
- anchorUserScrollGenerationRef.current += 1;
- const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
- timelineScrollModeRef.current = "free-scrolling";
- liveFollowUserScrollGenerationRef.current = null;
- setTimelineLiveFollowEnabled(false);
- pendingTimelineAnchorRef.current = null;
- positionedTimelineAnchorRef.current = null;
- settledTimelineAnchorRef.current = null;
- activeTimelineAnchorIndexRef.current = null;
- pendingAnchorScrollRestoreRef.current = null;
- if (anchorScrollRestoreFrameRef.current !== null) {
- cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
- anchorScrollRestoreFrameRef.current = null;
- }
- if (wasProgrammaticScrollMode) {
- // While following or anchoring, our scrollToEnd/scrollToOffset calls can
- // sit in LegendList's pending-imperative-scroll queue (it defers them
- // while layout settles) and fire seconds later with stale targets,
- // yanking the view away after the user scrolled. Starting a new
- // imperative scroll cancels everything queued; targeting an item that
- // is not in the data makes the new request itself resolve without ever
- // scrolling, so this is a pure cancel.
- void legendListRef.current?.scrollToItem({
- item: TIMELINE_SCROLL_CANCEL_SENTINEL,
- animated: false,
- });
- // An already-started animated scroll (behavior: smooth) keeps running in
- // the browser regardless of the queue; a same-position instant write is
- // the only way to halt it where it is.
- const scrollNode = legendListRef.current?.getScrollableNode() as
- | { scrollTop?: number }
- | null
- | undefined;
- const currentScrollTop = scrollNode?.scrollTop;
- if (scrollNode && typeof currentScrollTop === "number") {
- scrollNode.scrollTop = currentScrollTop;
- }
- }
- };
- const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
- cancelTimelineLiveFollowForUserNavigation,
- );
- const cancelTimelineLiveFollowForUserNavigationRef = useRef(
+ const {
+ showScrollToBottom,
+ timelineLiveFollowEnabled,
+ cancelPositionRestoreRef,
+ isTimelineAtLogicalEndStable,
cancelTimelineLiveFollowForUserNavigationStable,
- );
- useEffect(() => {
- cancelTimelineLiveFollowForUserNavigationRef.current =
- cancelTimelineLiveFollowForUserNavigationStable;
- }, [cancelTimelineLiveFollowForUserNavigationStable]);
- useEffect(() => {
- const previous = observedTimelineActivityRef.current;
- const dispatchedUserItem =
- previous?.hydrated &&
- previous.threadKey === activeThreadKey &&
- activeActivityRun !== null &&
- previous.runId !== activeActivityRun.runId
- ? serverProjection?.visibleTurnItems.find(
- (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
- )
- : undefined;
- const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {
- threadKey: activeThreadKey,
- hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
- runId: activeActivityRun?.runId ?? null,
- queued: activeActivityRun?.status === "queued",
- messageId:
- dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
- });
- observedTimelineActivityRef.current = observation;
- if (messageId === null) return;
- if (
- pendingTimelineAnchorRef.current !== null ||
- timelineScrollModeRef.current === "free-scrolling"
- ) {
- return;
- }
-
- isAtEndRef.current = true;
- timelineScrollModeRef.current = "anchoring-new-turn";
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
- pendingTimelineAnchorRef.current = messageId;
- activeTimelineAnchorIndexRef.current = null;
- showScrollDebouncer.current.cancel();
- setShowScrollToBottom(false);
- setTimelineAnchor({ threadKey: activeThreadKey, messageId });
- }, [activeActivityRun, activeThreadKey, isServerThread, serverProjection, threadStatus]);
- const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
- timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
- composerInset: composerTimelineInset,
- anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
- });
- const timelineRealContentOverflowsViewportStable = useStableCallback(
- timelineRealContentOverflowsViewport,
- );
- const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
- null,
- );
- const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
- timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
- composerRef.current?.collapseForTimelineScrollKey(key);
- if (
- (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
- !isTimelineAtLogicalEndStable()
- ) {
- cancelTimelineLiveFollowForUserNavigationStable();
- }
- });
- useEffect(() => {
- const controller = createPageScrollController({
- getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
- getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
- onScrollStart: handlePageScrollStart,
- });
- pageScrollControllerRef.current = controller;
-
- return () => {
- controller.dispose();
- if (pageScrollControllerRef.current === controller) {
- pageScrollControllerRef.current = null;
- }
- };
- }, [composerOverlayElement]);
- const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
- pageScrollControllerRef.current?.handleKeyDown(key);
- };
- const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
- const onComposerPageScrollKeyUp = (key: string) => {
- pageScrollControllerRef.current?.handleKeyUp(key);
- };
- const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
- const onComposerPageScrollRelease = () => {
- pageScrollControllerRef.current?.releaseActiveKey();
- };
- const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
- const scrollToEnd = (animated: boolean = false) => {
- cancelPositionRestoreRef.current?.();
- isAtEndRef.current = true;
- timelineScrollModeRef.current = "following-end";
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
- setTimelineLiveFollowEnabled(true);
- pendingTimelineAnchorRef.current = null;
- activeTimelineAnchorIndexRef.current = null;
- showScrollDebouncer.current.cancel();
- setShowScrollToBottom(false);
- setTimelineAnchor(releaseChatTimelineAnchor);
- // The anchored end space must be gone before the scroll measures, or the
- // list lands short of the real end (#6519).
- requestAnimationFrame(() => {
- void legendListRef.current?.scrollToEnd?.({
- animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
- });
- });
- };
- const scrollToEndStable = useStableCallback(scrollToEnd);
- useEffect(() => {
- const composer = composerRef;
- let removeListeners: (() => void) | null = null;
- let frame: number | null = null;
- const attach = (remainingAttempts: number) => {
- frame = requestAnimationFrame(() => {
- frame = null;
- const scrollNode = legendListRef.current?.getScrollableNode();
- if (!scrollNode) {
- // The list may not have mounted on the first frame after a thread
- // switch — without a retry the opt-out listeners never attach and
- // live-follow becomes impossible to escape for the whole thread.
- if (remainingAttempts > 0) {
- attach(remainingAttempts - 1);
- }
- return;
- }
- const handleManualNavigation = () => {
- cancelTimelineLiveFollowForUserNavigationRef.current();
- };
- // The gestures below must only break follow when they can actually
- // move the viewport away from the live edge (#5566): a spurious break
- // while pinned at the end produces no scroll event, never re-arms,
- // and streaming silently stops following. Underflowing content can't
- // scroll at all, so nothing there should break follow.
- const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
- // The follow re-arm band, not the strict flag: streaming growth makes
- // isAtEnd flicker false for a frame before the follow scroll catches
- // up, and a gesture landing in that window while still pinned would
- // otherwise break follow with no scroll event left to re-arm it.
- const viewportIsAwayFromEnd = () =>
- resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
- const handleWheel = (event: WheelEvent) => {
- if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
- return;
- if (event.deltaY > 0) {
- timelineScrollIntentRef.current = "toward-end";
- if (isAtEndRef.current) {
- composer.current?.restoreAfterTimelineReachedEnd();
- }
- } else if (event.deltaY < 0) {
- timelineScrollIntentRef.current = "away-from-end";
- }
- if (event.deltaY < 0 && contentScrollsUp()) {
- handleManualNavigation();
- }
- };
- // Touch direction isn't observable here (touchmove fires on any
- // finger motion, scrolling or not), so break only once the drag has
- // actually carried the viewport out of the end band — an upward flick
- // gets there within its first few events and later touchmoves break.
- const handleTouchMove = () => {
- if (viewportIsAwayFromEnd()) {
- handleManualNavigation();
- }
- };
- // Scrollbar drags produce no wheel/touch events; they are the only
- // pointerdowns whose target is the scroll node itself rather than a
- // message row.
- const handlePointerDown = (event: PointerEvent) => {
- if (event.target === scrollNode) {
- if (contentScrollsUp()) {
- handleManualNavigation();
- }
- return;
- }
- if (viewportIsAwayFromEnd()) {
- handleManualNavigation();
- }
- };
- // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
- // pointer events entirely; without this the timeline yanks back to
- // the end on the next stream chunk. Clicking message text can leave
- // DOM focus on body, so these keys must also be heard at document.
- const handleKeyDown = (event: KeyboardEvent) => {
- if (
- !(event.target instanceof Node) ||
- (!scrollNode.contains(event.target) &&
- event.target !== document.body &&
- event.target !== document.documentElement) ||
- event.defaultPrevented ||
- event.isComposing ||
- event.altKey ||
- event.ctrlKey ||
- event.metaKey ||
- event.shiftKey ||
- eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
- document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
- ) {
- return;
- }
- if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
- return;
- const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
- if (
- scrollNode.contains(event.target) &&
- !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
- )
- return;
- switch (event.key) {
- case "PageUp":
- case "Home":
- case "ArrowUp":
- timelineScrollIntentRef.current = "away-from-end";
- if (contentScrollsUp()) {
- handleManualNavigation();
- composer.current?.collapseForTimelineScrollKey(event.key);
- }
- break;
- case "PageDown":
- case "End":
- case "ArrowDown":
- timelineScrollIntentRef.current = "toward-end";
- if (viewportIsAwayFromEnd()) {
- handleManualNavigation();
- }
- composer.current?.collapseForTimelineScrollKey(event.key);
- if (isTimelineAtLogicalEndStable()) {
- composer.current?.restoreAfterTimelineReachedEnd();
- }
- break;
- default:
- break;
- }
- };
- // Input inside an embedded frame reaches none of the listeners above,
- // but its scroll still chains out to the timeline (#17056).
- const scrolledUp = createUpwardScrollDetector({
- top: scrollNode.scrollTop,
- height: scrollNode.scrollHeight,
- });
- const handleScroll = () => {
- if (
- scrolledUp({
- top: scrollNode.scrollTop,
- height: scrollNode.scrollHeight,
- programmatic:
- positionedTimelineAnchorRef.current !== null &&
- positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,
- }) &&
- timelineScrollModeRef.current !== "free-scrolling" &&
- // LegendList updates its scroll state on the next animation frame.
- resolveTimelineIsAtEnd({
- contentLength: scrollNode.scrollHeight,
- scroll: scrollNode.scrollTop,
- scrollLength: scrollNode.clientHeight,
- }) === false
- ) {
- handleManualNavigation();
- }
- };
- scrollNode.addEventListener("scroll", handleScroll, { passive: true });
- scrollNode.addEventListener("wheel", handleWheel, {
- passive: true,
- });
- scrollNode.addEventListener("touchmove", handleTouchMove, {
- passive: true,
- });
- scrollNode.addEventListener("pointerdown", handlePointerDown, {
- passive: true,
- });
- document.addEventListener("keydown", handleKeyDown);
- removeListeners = () => {
- scrollNode.removeEventListener("scroll", handleScroll);
- scrollNode.removeEventListener("wheel", handleWheel);
- scrollNode.removeEventListener("touchmove", handleTouchMove);
- scrollNode.removeEventListener("pointerdown", handlePointerDown);
- document.removeEventListener("keydown", handleKeyDown);
- };
- });
- };
- attach(12);
-
- return () => {
- if (frame !== null) {
- cancelAnimationFrame(frame);
- }
- removeListeners?.();
- };
- }, [
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
- activeThread?.id,
+ onComposerPageScrollKeyDownStable,
+ onComposerPageScrollKeyUpStable,
+ onComposerPageScrollReleaseStable,
+ scrollToEnd,
+ onTimelineAnchorReadyStable,
+ onTimelineAnchorSizeChangedStable,
+ onToolOutputCollapsedAtEndStable,
+ onIsAtEndChangeStable,
+ anchorNewTurn,
+ } = useTimelineFollow({
+ legendListRef,
composerRef,
- isTimelineAtLogicalEndStable,
- timelineRealContentOverflowsViewportStable,
- ]);
-
- const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
- if (pendingTimelineAnchorRef.current === messageId) {
- pendingTimelineAnchorRef.current = null;
- }
- activeTimelineAnchorIndexRef.current = anchorIndex;
- if (positionedTimelineAnchorRef.current === messageId) {
- return;
- }
- positionedTimelineAnchorRef.current = messageId;
- settledTimelineAnchorRef.current = null;
- const positionAnchor = (remainingAttempts: number) => {
- requestAnimationFrame(() => {
- if (positionedTimelineAnchorRef.current !== messageId) {
- return;
- }
- const list = legendListRef.current;
- if (!list) {
- if (remainingAttempts > 0) {
- positionAnchor(remainingAttempts - 1);
- }
- return;
- }
- // LegendList waits for queued layout and the animation before resolving.
- void list
- .scrollToIndex({
- index: anchorIndex,
- animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
- viewPosition: 0,
- viewOffset: CHAT_LIST_ANCHOR_OFFSET,
- })
- .then(() => {
- if (
- legendListRef.current === list &&
- positionedTimelineAnchorRef.current === messageId
- ) {
- settledTimelineAnchorRef.current = messageId;
- }
- });
- });
- };
- requestAnimationFrame(() => positionAnchor(12));
- };
- const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
- const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
- if (settledTimelineAnchorRef.current !== messageId) {
- return;
- }
- if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
- return;
- }
- const scrollOffset = legendListRef.current?.getState().scroll;
- if (scrollOffset === undefined) {
- return;
- }
- if (pendingAnchorScrollRestoreRef.current === null) {
- pendingAnchorScrollRestoreRef.current = {
- messageId,
- offset: scrollOffset,
- userScrollGeneration: anchorUserScrollGenerationRef.current,
- };
- }
- if (anchorScrollRestoreFrameRef.current !== null) {
- return;
- }
- anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
- anchorScrollRestoreFrameRef.current = null;
- const pending = pendingAnchorScrollRestoreRef.current;
- pendingAnchorScrollRestoreRef.current = null;
- if (
- pending &&
- settledTimelineAnchorRef.current === pending.messageId &&
- pending.userScrollGeneration === anchorUserScrollGenerationRef.current
- ) {
- const list = legendListRef.current;
- const currentScrollOffset = list?.getState().scroll;
- if (
- typeof currentScrollOffset === "number" &&
- Math.abs(currentScrollOffset - pending.offset) <= 2
- ) {
- void list?.scrollToOffset({ offset: pending.offset, animated: false });
- }
- }
- });
- };
- const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
-
- const onToolOutputCollapsedAtEnd = () => {
- composerRef.current?.restoreAfterTimelineReachedEnd();
- };
- const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
-
- const onIsAtEndChange = (isAtEnd: boolean) => {
- if (
- !isAtEnd &&
- liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
- ) {
- showScrollDebouncer.current.cancel();
- setShowScrollToBottom(false);
- return;
- }
- if (isAtEndRef.current === isAtEnd) return;
- isAtEndRef.current = isAtEnd;
- if (isAtEnd) {
- if (timelineScrollIntentRef.current === "toward-end") {
- composerRef.current?.restoreAfterTimelineReachedEnd();
- }
- timelineScrollModeRef.current = "following-end";
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
- setTimelineLiveFollowEnabled(true);
- setTimelineAnchor(releaseChatTimelineAnchor);
- showScrollDebouncer.current.cancel();
- setShowScrollToBottom(false);
- } else {
- timelineScrollModeRef.current = "free-scrolling";
- liveFollowUserScrollGenerationRef.current = null;
- showScrollDebouncer.current.maybeExecute();
- }
- };
- const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
-
- useLayoutEffect(() => {
- if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
- if (
- shouldReleaseTimelineAnchorForToolActivity({
- anchorMessageId: timelineAnchorMessageId,
- liveFollowEnabled: timelineLiveFollowEnabled,
- runningTurnId: activeRunningTurnId,
- timelineEntries,
- })
- ) {
- scrollToEndStable();
- }
- }, [
+ composerOverlayElement,
+ composerTimelineInset,
+ routeThreadKey,
+ activeThreadKey,
+ activeThreadId: activeThread?.id,
+ isServerThread,
+ serverProjection,
+ threadStatus,
+ activeActivityRun,
activeRunningTurnId,
- scrollToEndStable,
- timelineAnchorMessageId,
timelineEntries,
- timelineLiveFollowEnabled,
- ]);
-
- // A thread switch restores that thread's remembered follow state; the refs
- // the scroll handlers read catch up after commit.
- const [timelineThreadReset, setTimelineThreadReset] = useState({
- threadKey: activeThreadKey,
- followEnd: true,
+ timelineAnchorMessageId,
+ setTimelineAnchor,
});
- if (timelineThreadReset.threadKey !== activeThreadKey) {
- const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
- setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
- setTimelineLiveFollowEnabled(followEnd);
- setShowScrollToBottom(!followEnd);
- }
- useEffect(() => {
- const { followEnd } = timelineThreadReset;
- isAtEndRef.current = followEnd;
- timelineScrollIntentRef.current = null;
- timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
- liveFollowUserScrollGenerationRef.current = followEnd
- ? anchorUserScrollGenerationRef.current
- : null;
- pendingTimelineAnchorRef.current = null;
- positionedTimelineAnchorRef.current = null;
- settledTimelineAnchorRef.current = null;
- activeTimelineAnchorIndexRef.current = null;
- showScrollDebouncer.current.cancel();
- }, [timelineThreadReset]);
useEffect(() => {
if (!activeThread?.id || terminalUiState.terminalOpen) return;
@@ -6658,18 +6124,10 @@ export default function ChatView(props: ChatViewProps) {
},
);
if (!shouldQueueBehindActiveRun) {
- isAtEndRef.current = true;
- timelineScrollModeRef.current = "anchoring-new-turn";
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
- setTimelineLiveFollowEnabled(true);
- pendingTimelineAnchorRef.current = messageIdForSend;
- activeTimelineAnchorIndexRef.current = null;
- showScrollDebouncer.current.cancel();
- setShowScrollToBottom(false);
- setTimelineAnchor({
- threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
- messageId: messageIdForSend,
- });
+ anchorNewTurn(
+ scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
+ messageIdForSend,
+ );
}
setOptimisticUserMessages((existing) => [
...existing,
@@ -7066,18 +6524,10 @@ export default function ChatView(props: ChatViewProps) {
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
- isAtEndRef.current = true;
- timelineScrollModeRef.current = "anchoring-new-turn";
- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
- setTimelineLiveFollowEnabled(true);
- pendingTimelineAnchorRef.current = messageIdForSend;
- activeTimelineAnchorIndexRef.current = null;
- showScrollDebouncer.current.cancel();
- setShowScrollToBottom(false);
- setTimelineAnchor({
- threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
- messageId: messageIdForSend,
- });
+ anchorNewTurn(
+ scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
+ messageIdForSend,
+ );
setOptimisticUserMessages((existing) => [
...existing,
diff --git a/apps/web/src/components/chat/useTimelineFollow.ts b/apps/web/src/components/chat/useTimelineFollow.ts
new file mode 100644
index 00000000000..f0a96742c3d
--- /dev/null
+++ b/apps/web/src/components/chat/useTimelineFollow.ts
@@ -0,0 +1,665 @@
+import { useStableCallback } from "../../hooks/useStableCallback";
+import {
+ eventPathContainsSelector,
+ TYPE_TO_FOCUS_EDITABLE_SELECTOR,
+ TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
+} from "./composerFocusRedirect";
+import { type MessageId, type ThreadId, type RunId } from "@t3tools/contracts";
+import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
+import { Debouncer } from "@tanstack/react-pacer";
+import {
+ type SetStateAction,
+ useEffect,
+ useEffectEvent,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import { type LegendListRef } from "@legendapp/list/react";
+import {
+ CHAT_TIMELINE_ANCHOR_OFFSET,
+ timelineContentOverflowsViewport,
+ readTimelinePosition,
+ observeTimelineRun,
+ type TimelineRunObservation,
+ type TimelineScrollMode,
+} from "./timelineScrollAnchoring";
+import { type ChatComposerHandle } from "./ChatComposer";
+import { createPageScrollController, type PageScrollKey } from "./pageScrollController";
+import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
+import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
+import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
+import { releaseChatTimelineAnchor } from "../ChatView.logic";
+import type { Dispatch, RefObject } from "react";
+import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
+import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
+import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
+import type { TimelineEntry } from "../../session-logic";
+
+const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
+
+interface TimelineAnchor {
+ readonly threadKey: string | null;
+ readonly messageId: MessageId | null;
+}
+
+interface TimelineFollowInput {
+ readonly legendListRef: RefObject<LegendListRef | null>;
+ readonly composerRef: RefObject<ChatComposerHandle | null>;
+ readonly composerOverlayElement: HTMLDivElement | null;
+ readonly composerTimelineInset: number;
+ readonly routeThreadKey: string;
+ readonly activeThreadKey: string | null;
+ readonly activeThreadId: ThreadId | undefined;
+ readonly isServerThread: boolean;
+ readonly serverProjection: EnvironmentThread["projection"] | null;
+ readonly threadStatus: EnvironmentThreadStatus;
+ readonly activeActivityRun: ReturnType<typeof deriveThreadActivityRun>;
+ readonly activeRunningTurnId: RunId | null;
+ readonly timelineEntries: ReadonlyArray<TimelineEntry>;
+ readonly timelineAnchorMessageId: MessageId | null;
+ readonly setTimelineAnchor: Dispatch<SetStateAction<TimelineAnchor>>;
+}
+
+/**
+ * Keeps the timeline following the live end, anchoring a newly sent turn near
+ * the top, and letting the user scroll away. The scroll handlers read refs, so
+ * a scroll gesture does not re-render ChatView unless the follow mode flips.
+ */
+export function useTimelineFollow(input: TimelineFollowInput) {
+ const {
+ legendListRef,
+ composerRef,
+ composerOverlayElement,
+ composerTimelineInset,
+ routeThreadKey,
+ activeThreadKey,
+ activeThreadId,
+ isServerThread,
+ serverProjection,
+ threadStatus,
+ activeActivityRun,
+ activeRunningTurnId,
+ timelineEntries,
+ timelineAnchorMessageId,
+ setTimelineAnchor,
+ } = input;
+ const [showScrollToBottom, setShowScrollToBottom] = useState(false);
+ const isAtEndRef = useRef(true);
+ const isTimelineAtLogicalEnd = () =>
+ resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
+ const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
+ // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
+ // thread switches. LegendList fires scroll events with isAtEnd=false while
+ // initialScrollAtEnd is settling; hiding is always immediate.
+ const showScrollDebouncer = useRef(
+ new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
+ );
+ const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);
+ const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
+ // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
+ // re-pins on its own (independent of the refs), so the timeline needs a
+ // render-visible flag to switch it off once the user scrolls away.
+ const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
+ const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
+ const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
+ const settledTimelineAnchorRef = useRef<MessageId | null>(null);
+ const activeTimelineAnchorIndexRef = useRef<number | null>(null);
+ const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);
+ const anchorUserScrollGenerationRef = useRef(0);
+ const cancelPositionRestoreRef = useRef<(() => void) | null>(null);
+ const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
+ const pendingAnchorScrollRestoreRef = useRef<{
+ readonly messageId: MessageId;
+ readonly offset: number;
+ readonly userScrollGeneration: number;
+ } | null>(null);
+ const anchorScrollRestoreFrameRef = useRef<number | null>(null);
+ const cancelTimelineLiveFollowForUserNavigation = () => {
+ cancelPositionRestoreRef.current?.();
+ anchorUserScrollGenerationRef.current += 1;
+ const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
+ timelineScrollModeRef.current = "free-scrolling";
+ liveFollowUserScrollGenerationRef.current = null;
+ setTimelineLiveFollowEnabled(false);
+ pendingTimelineAnchorRef.current = null;
+ positionedTimelineAnchorRef.current = null;
+ settledTimelineAnchorRef.current = null;
+ activeTimelineAnchorIndexRef.current = null;
+ pendingAnchorScrollRestoreRef.current = null;
+ if (anchorScrollRestoreFrameRef.current !== null) {
+ cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
+ anchorScrollRestoreFrameRef.current = null;
+ }
+ if (wasProgrammaticScrollMode) {
+ // While following or anchoring, our scrollToEnd/scrollToOffset calls can
+ // sit in LegendList's pending-imperative-scroll queue (it defers them
+ // while layout settles) and fire seconds later with stale targets,
+ // yanking the view away after the user scrolled. Starting a new
+ // imperative scroll cancels everything queued; targeting an item that
+ // is not in the data makes the new request itself resolve without ever
+ // scrolling, so this is a pure cancel.
+ void legendListRef.current?.scrollToItem({
+ item: TIMELINE_SCROLL_CANCEL_SENTINEL,
+ animated: false,
+ });
+ // An already-started animated scroll (behavior: smooth) keeps running in
+ // the browser regardless of the queue; a same-position instant write is
+ // the only way to halt it where it is.
+ const scrollNode = legendListRef.current?.getScrollableNode() as
+ | { scrollTop?: number }
+ | null
+ | undefined;
+ const currentScrollTop = scrollNode?.scrollTop;
+ if (scrollNode && typeof currentScrollTop === "number") {
+ scrollNode.scrollTop = currentScrollTop;
+ }
+ }
+ };
+ const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
+ cancelTimelineLiveFollowForUserNavigation,
+ );
+ const cancelTimelineLiveFollowForUserNavigationRef = useRef(
+ cancelTimelineLiveFollowForUserNavigationStable,
+ );
+ useEffect(() => {
+ cancelTimelineLiveFollowForUserNavigationRef.current =
+ cancelTimelineLiveFollowForUserNavigationStable;
+ }, [cancelTimelineLiveFollowForUserNavigationStable]);
+ useEffect(() => {
+ const previous = observedTimelineActivityRef.current;
+ const dispatchedUserItem =
+ previous?.hydrated &&
+ previous.threadKey === activeThreadKey &&
+ activeActivityRun !== null &&
+ previous.runId !== activeActivityRun.runId
+ ? serverProjection?.visibleTurnItems.find(
+ (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
+ )
+ : undefined;
+ const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {
+ threadKey: activeThreadKey,
+ hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
+ runId: activeActivityRun?.runId ?? null,
+ queued: activeActivityRun?.status === "queued",
+ messageId:
+ dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
+ });
+ observedTimelineActivityRef.current = observation;
+ if (messageId === null) return;
+ if (
+ pendingTimelineAnchorRef.current !== null ||
+ timelineScrollModeRef.current === "free-scrolling"
+ ) {
+ return;
+ }
+
+ isAtEndRef.current = true;
+ timelineScrollModeRef.current = "anchoring-new-turn";
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
+ pendingTimelineAnchorRef.current = messageId;
+ activeTimelineAnchorIndexRef.current = null;
+ showScrollDebouncer.current.cancel();
+ setShowScrollToBottom(false);
+ setTimelineAnchor({ threadKey: activeThreadKey, messageId });
+ }, [
+ activeActivityRun,
+ activeThreadKey,
+ isServerThread,
+ serverProjection,
+ setTimelineAnchor,
+ threadStatus,
+ ]);
+ const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
+ timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
+ composerInset: composerTimelineInset,
+ anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
+ });
+ const timelineRealContentOverflowsViewportStable = useStableCallback(
+ timelineRealContentOverflowsViewport,
+ );
+ const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
+ null,
+ );
+ const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
+ timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
+ composerRef.current?.collapseForTimelineScrollKey(key);
+ if (
+ (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
+ !isTimelineAtLogicalEndStable()
+ ) {
+ cancelTimelineLiveFollowForUserNavigationStable();
+ }
+ });
+ useEffect(() => {
+ const controller = createPageScrollController({
+ getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
+ getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
+ onScrollStart: handlePageScrollStart,
+ });
+ pageScrollControllerRef.current = controller;
+
+ return () => {
+ controller.dispose();
+ if (pageScrollControllerRef.current === controller) {
+ pageScrollControllerRef.current = null;
+ }
+ };
+ }, [composerOverlayElement, legendListRef]);
+ const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
+ pageScrollControllerRef.current?.handleKeyDown(key);
+ };
+ const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
+ const onComposerPageScrollKeyUp = (key: string) => {
+ pageScrollControllerRef.current?.handleKeyUp(key);
+ };
+ const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
+ const onComposerPageScrollRelease = () => {
+ pageScrollControllerRef.current?.releaseActiveKey();
+ };
+ const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
+ const scrollToEnd = (animated: boolean = false) => {
+ cancelPositionRestoreRef.current?.();
+ isAtEndRef.current = true;
+ timelineScrollModeRef.current = "following-end";
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
+ setTimelineLiveFollowEnabled(true);
+ pendingTimelineAnchorRef.current = null;
+ activeTimelineAnchorIndexRef.current = null;
+ showScrollDebouncer.current.cancel();
+ setShowScrollToBottom(false);
+ setTimelineAnchor(releaseChatTimelineAnchor);
+ // The anchored end space must be gone before the scroll measures, or the
+ // list lands short of the real end (#6519).
+ requestAnimationFrame(() => {
+ void legendListRef.current?.scrollToEnd?.({
+ animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
+ });
+ });
+ };
+ const scrollToEndStable = useStableCallback(scrollToEnd);
+ useEffect(() => {
+ const composer = composerRef;
+ let removeListeners: (() => void) | null = null;
+ let frame: number | null = null;
+ const attach = (remainingAttempts: number) => {
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ const scrollNode = legendListRef.current?.getScrollableNode();
+ if (!scrollNode) {
+ // The list may not have mounted on the first frame after a thread
+ // switch — without a retry the opt-out listeners never attach and
+ // live-follow becomes impossible to escape for the whole thread.
+ if (remainingAttempts > 0) {
+ attach(remainingAttempts - 1);
+ }
+ return;
+ }
+ const handleManualNavigation = () => {
+ cancelTimelineLiveFollowForUserNavigationRef.current();
+ };
+ // The gestures below must only break follow when they can actually
+ // move the viewport away from the live edge (#5566): a spurious break
+ // while pinned at the end produces no scroll event, never re-arms,
+ // and streaming silently stops following. Underflowing content can't
+ // scroll at all, so nothing there should break follow.
+ const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
+ // The follow re-arm band, not the strict flag: streaming growth makes
+ // isAtEnd flicker false for a frame before the follow scroll catches
+ // up, and a gesture landing in that window while still pinned would
+ // otherwise break follow with no scroll event left to re-arm it.
+ const viewportIsAwayFromEnd = () =>
+ resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
+ const handleWheel = (event: WheelEvent) => {
+ if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
+ return;
+ if (event.deltaY > 0) {
+ timelineScrollIntentRef.current = "toward-end";
+ if (isAtEndRef.current) {
+ composer.current?.restoreAfterTimelineReachedEnd();
+ }
+ } else if (event.deltaY < 0) {
+ timelineScrollIntentRef.current = "away-from-end";
+ }
+ if (event.deltaY < 0 && contentScrollsUp()) {
+ handleManualNavigation();
+ }
+ };
+ // Touch direction isn't observable here (touchmove fires on any
+ // finger motion, scrolling or not), so break only once the drag has
+ // actually carried the viewport out of the end band — an upward flick
+ // gets there within its first few events and later touchmoves break.
+ const handleTouchMove = () => {
+ if (viewportIsAwayFromEnd()) {
+ handleManualNavigation();
+ }
+ };
+ // Scrollbar drags produce no wheel/touch events; they are the only
+ // pointerdowns whose target is the scroll node itself rather than a
+ // message row.
+ const handlePointerDown = (event: PointerEvent) => {
+ if (event.target === scrollNode) {
+ if (contentScrollsUp()) {
+ handleManualNavigation();
+ }
+ return;
+ }
+ if (viewportIsAwayFromEnd()) {
+ handleManualNavigation();
+ }
+ };
+ // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
+ // pointer events entirely; without this the timeline yanks back to
+ // the end on the next stream chunk. Clicking message text can leave
+ // DOM focus on body, so these keys must also be heard at document.
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ !(event.target instanceof Node) ||
+ (!scrollNode.contains(event.target) &&
+ event.target !== document.body &&
+ event.target !== document.documentElement) ||
+ event.defaultPrevented ||
+ event.isComposing ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey ||
+ eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
+ document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
+ ) {
+ return;
+ }
+ if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
+ return;
+ const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
+ if (
+ scrollNode.contains(event.target) &&
+ !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
+ )
+ return;
+ switch (event.key) {
+ case "PageUp":
+ case "Home":
+ case "ArrowUp":
+ timelineScrollIntentRef.current = "away-from-end";
+ if (contentScrollsUp()) {
+ handleManualNavigation();
+ composer.current?.collapseForTimelineScrollKey(event.key);
+ }
+ break;
+ case "PageDown":
+ case "End":
+ case "ArrowDown":
+ timelineScrollIntentRef.current = "toward-end";
+ if (viewportIsAwayFromEnd()) {
+ handleManualNavigation();
+ }
+ composer.current?.collapseForTimelineScrollKey(event.key);
+ if (isTimelineAtLogicalEndStable()) {
+ composer.current?.restoreAfterTimelineReachedEnd();
+ }
+ break;
+ default:
+ break;
+ }
+ };
+ // Input inside an embedded frame reaches none of the listeners above,
+ // but its scroll still chains out to the timeline (#17056).
+ const scrolledUp = createUpwardScrollDetector({
+ top: scrollNode.scrollTop,
+ height: scrollNode.scrollHeight,
+ });
+ const handleScroll = () => {
+ if (
+ scrolledUp({
+ top: scrollNode.scrollTop,
+ height: scrollNode.scrollHeight,
+ programmatic:
+ positionedTimelineAnchorRef.current !== null &&
+ positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,
+ }) &&
+ timelineScrollModeRef.current !== "free-scrolling" &&
+ // LegendList updates its scroll state on the next animation frame.
+ resolveTimelineIsAtEnd({
+ contentLength: scrollNode.scrollHeight,
+ scroll: scrollNode.scrollTop,
+ scrollLength: scrollNode.clientHeight,
+ }) === false
+ ) {
+ handleManualNavigation();
+ }
+ };
+ scrollNode.addEventListener("scroll", handleScroll, { passive: true });
+ scrollNode.addEventListener("wheel", handleWheel, {
+ passive: true,
+ });
+ scrollNode.addEventListener("touchmove", handleTouchMove, {
+ passive: true,
+ });
+ scrollNode.addEventListener("pointerdown", handlePointerDown, {
+ passive: true,
+ });
+ document.addEventListener("keydown", handleKeyDown);
+ removeListeners = () => {
+ scrollNode.removeEventListener("scroll", handleScroll);
+ scrollNode.removeEventListener("wheel", handleWheel);
+ scrollNode.removeEventListener("touchmove", handleTouchMove);
+ scrollNode.removeEventListener("pointerdown", handlePointerDown);
+ document.removeEventListener("keydown", handleKeyDown);
+ };
+ });
+ };
+ attach(12);
+
+ return () => {
+ if (frame !== null) {
+ cancelAnimationFrame(frame);
+ }
+ removeListeners?.();
+ };
+ }, [
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
+ activeThreadId,
+ composerRef,
+ isTimelineAtLogicalEndStable,
+ legendListRef,
+ timelineRealContentOverflowsViewportStable,
+ ]);
+
+ const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
+ if (pendingTimelineAnchorRef.current === messageId) {
+ pendingTimelineAnchorRef.current = null;
+ }
+ activeTimelineAnchorIndexRef.current = anchorIndex;
+ if (positionedTimelineAnchorRef.current === messageId) {
+ return;
+ }
+ positionedTimelineAnchorRef.current = messageId;
+ settledTimelineAnchorRef.current = null;
+ const positionAnchor = (remainingAttempts: number) => {
+ requestAnimationFrame(() => {
+ if (positionedTimelineAnchorRef.current !== messageId) {
+ return;
+ }
+ const list = legendListRef.current;
+ if (!list) {
+ if (remainingAttempts > 0) {
+ positionAnchor(remainingAttempts - 1);
+ }
+ return;
+ }
+ // LegendList waits for queued layout and the animation before resolving.
+ void list
+ .scrollToIndex({
+ index: anchorIndex,
+ animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
+ viewPosition: 0,
+ viewOffset: CHAT_LIST_ANCHOR_OFFSET,
+ })
+ .then(() => {
+ if (
+ legendListRef.current === list &&
+ positionedTimelineAnchorRef.current === messageId
+ ) {
+ settledTimelineAnchorRef.current = messageId;
+ }
+ });
+ });
+ };
+ requestAnimationFrame(() => positionAnchor(12));
+ };
+ const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
+ const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
+ if (settledTimelineAnchorRef.current !== messageId) {
+ return;
+ }
+ if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
+ return;
+ }
+ const scrollOffset = legendListRef.current?.getState().scroll;
+ if (scrollOffset === undefined) {
+ return;
+ }
+ if (pendingAnchorScrollRestoreRef.current === null) {
+ pendingAnchorScrollRestoreRef.current = {
+ messageId,
+ offset: scrollOffset,
+ userScrollGeneration: anchorUserScrollGenerationRef.current,
+ };
+ }
+ if (anchorScrollRestoreFrameRef.current !== null) {
+ return;
+ }
+ anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
+ anchorScrollRestoreFrameRef.current = null;
+ const pending = pendingAnchorScrollRestoreRef.current;
+ pendingAnchorScrollRestoreRef.current = null;
+ if (
+ pending &&
+ settledTimelineAnchorRef.current === pending.messageId &&
+ pending.userScrollGeneration === anchorUserScrollGenerationRef.current
+ ) {
+ const list = legendListRef.current;
+ const currentScrollOffset = list?.getState().scroll;
+ if (
+ typeof currentScrollOffset === "number" &&
+ Math.abs(currentScrollOffset - pending.offset) <= 2
+ ) {
+ void list?.scrollToOffset({ offset: pending.offset, animated: false });
+ }
+ }
+ });
+ };
+ const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
+
+ const onToolOutputCollapsedAtEnd = () => {
+ composerRef.current?.restoreAfterTimelineReachedEnd();
+ };
+ const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
+
+ const onIsAtEndChange = (isAtEnd: boolean) => {
+ if (
+ !isAtEnd &&
+ liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
+ ) {
+ showScrollDebouncer.current.cancel();
+ setShowScrollToBottom(false);
+ return;
+ }
+ if (isAtEndRef.current === isAtEnd) return;
+ isAtEndRef.current = isAtEnd;
+ if (isAtEnd) {
+ if (timelineScrollIntentRef.current === "toward-end") {
+ composerRef.current?.restoreAfterTimelineReachedEnd();
+ }
+ timelineScrollModeRef.current = "following-end";
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
+ setTimelineLiveFollowEnabled(true);
+ setTimelineAnchor(releaseChatTimelineAnchor);
+ showScrollDebouncer.current.cancel();
+ setShowScrollToBottom(false);
+ } else {
+ timelineScrollModeRef.current = "free-scrolling";
+ liveFollowUserScrollGenerationRef.current = null;
+ showScrollDebouncer.current.maybeExecute();
+ }
+ };
+ const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
+
+ useLayoutEffect(() => {
+ if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
+ if (
+ shouldReleaseTimelineAnchorForToolActivity({
+ anchorMessageId: timelineAnchorMessageId,
+ liveFollowEnabled: timelineLiveFollowEnabled,
+ runningTurnId: activeRunningTurnId,
+ timelineEntries,
+ })
+ ) {
+ scrollToEndStable();
+ }
+ }, [
+ activeRunningTurnId,
+ scrollToEndStable,
+ timelineAnchorMessageId,
+ timelineEntries,
+ timelineLiveFollowEnabled,
+ ]);
+
+ // A thread switch restores that thread's remembered follow state; the refs
+ // the scroll handlers read catch up after commit.
+ const [timelineThreadReset, setTimelineThreadReset] = useState({
+ threadKey: activeThreadKey,
+ followEnd: true,
+ });
+ if (timelineThreadReset.threadKey !== activeThreadKey) {
+ const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
+ setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
+ setTimelineLiveFollowEnabled(followEnd);
+ setShowScrollToBottom(!followEnd);
+ }
+ useEffect(() => {
+ const { followEnd } = timelineThreadReset;
+ isAtEndRef.current = followEnd;
+ timelineScrollIntentRef.current = null;
+ timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
+ liveFollowUserScrollGenerationRef.current = followEnd
+ ? anchorUserScrollGenerationRef.current
+ : null;
+ pendingTimelineAnchorRef.current = null;
+ positionedTimelineAnchorRef.current = null;
+ settledTimelineAnchorRef.current = null;
+ activeTimelineAnchorIndexRef.current = null;
+ showScrollDebouncer.current.cancel();
+ }, [timelineThreadReset]);
+
+ /** Arms the anchor for a message the user just sent, before its run exists. */
+ const anchorNewTurn = (threadKey: string, messageId: MessageId) => {
+ isAtEndRef.current = true;
+ timelineScrollModeRef.current = "anchoring-new-turn";
+ liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
+ setTimelineLiveFollowEnabled(true);
+ pendingTimelineAnchorRef.current = messageId;
+ activeTimelineAnchorIndexRef.current = null;
+ showScrollDebouncer.current.cancel();
+ setShowScrollToBottom(false);
+ setTimelineAnchor({ threadKey, messageId });
+ };
+
+ return {
+ showScrollToBottom,
+ timelineLiveFollowEnabled,
+ cancelPositionRestoreRef,
+ isTimelineAtLogicalEndStable,
+ cancelTimelineLiveFollowForUserNavigationStable,
+ onComposerPageScrollKeyDownStable,
+ onComposerPageScrollKeyUpStable,
+ onComposerPageScrollReleaseStable,
+ scrollToEnd,
+ onTimelineAnchorReadyStable,
+ onTimelineAnchorSizeChangedStable,
+ onToolOutputCollapsedAtEndStable,
+ onIsAtEndChangeStable,
+ anchorNewTurn,
+ };
+}