Open History to see the last commit
1import { useStableCallback } from "../../hooks/useStableCallback";
2import {
3 eventPathContainsSelector,
4 TYPE_TO_FOCUS_EDITABLE_SELECTOR,
5 TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
6} from "./composerFocusRedirect";
7import { type MessageId, type ThreadId, type RunId } from "@t3tools/contracts";
8import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
9import { Debouncer } from "@tanstack/react-pacer";
10import {
11 type SetStateAction,
12 useEffect,
13 useEffectEvent,
14 useLayoutEffect,
15 useRef,
16 useState,
17} from "react";
18import { type LegendListRef } from "@legendapp/list/react";
19import {
20 CHAT_TIMELINE_ANCHOR_OFFSET,
21 timelineContentOverflowsViewport,
22 readTimelinePosition,
23 observeTimelineRun,
24 type TimelineRunObservation,
25 type TimelineScrollMode,
26} from "./timelineScrollAnchoring";
27import { type ChatComposerHandle } from "./ChatComposer";
28import { createPageScrollController, type PageScrollKey } from "./pageScrollController";
29import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
30import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
31import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";
32import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
33import { releaseChatTimelineAnchor } from "../ChatView.logic";
34import type { Dispatch, RefObject } from "react";
35import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
36import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
37import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
38import type { TimelineEntry } from "../../session-logic";
39
40const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
41
42interface TimelineAnchor {
43 readonly threadKey: string | null;
44 readonly messageId: MessageId | null;
45}
46
47interface TimelineFollowInput {
48 readonly legendListRef: RefObject<LegendListRef | null>;
49 readonly composerRef: RefObject<ChatComposerHandle | null>;
50 readonly composerOverlayElement: HTMLDivElement | null;
51 readonly composerTimelineInset: number;
52 readonly routeThreadKey: string;
53 readonly activeThreadKey: string | null;
54 readonly activeThreadId: ThreadId | undefined;
55 readonly isServerThread: boolean;
56 readonly serverProjection: ThreadStructure | null;
57 readonly threadStatus: EnvironmentThreadStatus;
58 readonly activeActivityRun: ReturnType<typeof deriveThreadActivityRun>;
59 readonly activeRunningTurnId: RunId | null;
60 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
61 readonly timelineAnchorMessageId: MessageId | null;
62 readonly setTimelineAnchor: Dispatch<SetStateAction<TimelineAnchor>>;
63}
64
65/**
66 * Keeps the timeline following the live end, anchoring a newly sent turn near
67 * the top, and letting the user scroll away. The scroll handlers read refs, so
68 * a scroll gesture does not re-render ChatView unless the follow mode flips.
69 */
70export function useTimelineFollow(input: TimelineFollowInput) {
71 const {
72 legendListRef,
73 composerRef,
74 composerOverlayElement,
75 composerTimelineInset,
76 routeThreadKey,
77 activeThreadKey,
78 activeThreadId,
79 isServerThread,
80 serverProjection,
81 threadStatus,
82 activeActivityRun,
83 activeRunningTurnId,
84 timelineEntries,
85 timelineAnchorMessageId,
86 setTimelineAnchor,
87 } = input;
88 const [showScrollToBottom, setShowScrollToBottom] = useState(false);
89 const isAtEndRef = useRef(true);
90 const isTimelineAtLogicalEnd = () =>
91 resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
92 const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
93 // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
94 // thread switches. LegendList fires scroll events with isAtEnd=false while
95 // initialScrollAtEnd is settling; hiding is always immediate.
96 const showScrollDebouncer = useRef(
97 new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
98 );
99 const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);
100 const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");
101 // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd
102 // re-pins on its own (independent of the refs), so the timeline needs a
103 // render-visible flag to switch it off once the user scrolls away.
104 const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);
105 const pendingTimelineAnchorRef = useRef<MessageId | null>(null);
106 const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
107 const settledTimelineAnchorRef = useRef<MessageId | null>(null);
108 const activeTimelineAnchorIndexRef = useRef<number | null>(null);
109 const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);
110 const anchorUserScrollGenerationRef = useRef(0);
111 const cancelPositionRestoreRef = useRef<(() => void) | null>(null);
112 const liveFollowUserScrollGenerationRef = useRef<number | null>(0);
113 const pendingAnchorScrollRestoreRef = useRef<{
114 readonly messageId: MessageId;
115 readonly offset: number;
116 readonly userScrollGeneration: number;
117 } | null>(null);
118 const anchorScrollRestoreFrameRef = useRef<number | null>(null);
119 const cancelTimelineLiveFollowForUserNavigation = () => {
120 cancelPositionRestoreRef.current?.();
121 anchorUserScrollGenerationRef.current += 1;
122 const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
123 timelineScrollModeRef.current = "free-scrolling";
124 liveFollowUserScrollGenerationRef.current = null;
125 setTimelineLiveFollowEnabled(false);
126 pendingTimelineAnchorRef.current = null;
127 positionedTimelineAnchorRef.current = null;
128 settledTimelineAnchorRef.current = null;
129 activeTimelineAnchorIndexRef.current = null;
130 pendingAnchorScrollRestoreRef.current = null;
131 if (anchorScrollRestoreFrameRef.current !== null) {
132 cancelAnimationFrame(anchorScrollRestoreFrameRef.current);
133 anchorScrollRestoreFrameRef.current = null;
134 }
135 if (wasProgrammaticScrollMode) {
136 // LegendList may run queued scrolls after user navigation. A new imperative
137 // scroll cancels that queue; a missing item cancels without moving the view.
138 void legendListRef.current?.scrollToItem({
139 item: TIMELINE_SCROLL_CANCEL_SENTINEL,
140 animated: false,
141 });
142 // An already-started animated scroll (behavior: smooth) keeps running in
143 // the browser regardless of the queue; a same-position instant write is
144 // the only way to halt it where it is.
145 const scrollNode = legendListRef.current?.getScrollableNode() as
146 | { scrollTop?: number }
147 | null
148 | undefined;
149 const currentScrollTop = scrollNode?.scrollTop;
150 if (scrollNode && typeof currentScrollTop === "number") {
151 scrollNode.scrollTop = currentScrollTop;
152 }
153 }
154 };
155 const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
156 cancelTimelineLiveFollowForUserNavigation,
157 );
158 const cancelTimelineLiveFollowForUserNavigationRef = useRef(
159 cancelTimelineLiveFollowForUserNavigationStable,
160 );
161 useEffect(() => {
162 cancelTimelineLiveFollowForUserNavigationRef.current =
163 cancelTimelineLiveFollowForUserNavigationStable;
164 }, [cancelTimelineLiveFollowForUserNavigationStable]);
165 useEffect(() => {
166 const previous = observedTimelineActivityRef.current;
167 const dispatchedUserItem =
168 previous?.hydrated &&
169 previous.threadKey === activeThreadKey &&
170 activeActivityRun !== null &&
171 previous.runId !== activeActivityRun.runId
172 ? serverProjection?.visibleTurnItems.find(
173 (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
174 )
175 : undefined;
176 const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {
177 threadKey: activeThreadKey,
178 hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
179 runId: activeActivityRun?.runId ?? null,
180 queued: activeActivityRun?.status === "queued",
181 messageId:
182 dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
183 });
184 observedTimelineActivityRef.current = observation;
185 if (messageId === null) return;
186 if (
187 pendingTimelineAnchorRef.current !== null ||
188 timelineScrollModeRef.current === "free-scrolling"
189 ) {
190 return;
191 }
192
193 isAtEndRef.current = true;
194 timelineScrollModeRef.current = "anchoring-new-turn";
195 liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
196 pendingTimelineAnchorRef.current = messageId;
197 activeTimelineAnchorIndexRef.current = null;
198 showScrollDebouncer.current.cancel();
199 setShowScrollToBottom(false);
200 setTimelineAnchor({ threadKey: activeThreadKey, messageId });
201 }, [
202 activeActivityRun,
203 activeThreadKey,
204 isServerThread,
205 serverProjection,
206 setTimelineAnchor,
207 threadStatus,
208 ]);
209 const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
210 timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
211 composerInset: composerTimelineInset,
212 anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
213 });
214 const timelineRealContentOverflowsViewportStable = useStableCallback(
215 timelineRealContentOverflowsViewport,
216 );
217 const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
218 null,
219 );
220 const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
221 timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
222 composerRef.current?.collapseForTimelineScrollKey(key);
223 if (
224 (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
225 !isTimelineAtLogicalEndStable()
226 ) {
227 cancelTimelineLiveFollowForUserNavigationStable();
228 }
229 });
230 useEffect(() => {
231 const controller = createPageScrollController({
232 getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
233 getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
234 onScrollStart: handlePageScrollStart,
235 });
236 pageScrollControllerRef.current = controller;
237
238 return () => {
239 controller.dispose();
240 if (pageScrollControllerRef.current === controller) {
241 pageScrollControllerRef.current = null;
242 }
243 };
244 }, [composerOverlayElement, legendListRef]);
245 const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
246 pageScrollControllerRef.current?.handleKeyDown(key);
247 };
248 const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
249 const onComposerPageScrollKeyUp = (key: string) => {
250 pageScrollControllerRef.current?.handleKeyUp(key);
251 };
252 const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
253 const onComposerPageScrollRelease = () => {
254 pageScrollControllerRef.current?.releaseActiveKey();
255 };
256 const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
257 const scrollToEnd = (animated: boolean = false) => {
258 cancelPositionRestoreRef.current?.();
259 isAtEndRef.current = true;
260 timelineScrollModeRef.current = "following-end";
261 liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
262 setTimelineLiveFollowEnabled(true);
263 pendingTimelineAnchorRef.current = null;
264 activeTimelineAnchorIndexRef.current = null;
265 showScrollDebouncer.current.cancel();
266 setShowScrollToBottom(false);
267 setTimelineAnchor(releaseChatTimelineAnchor);
268 // The anchored end space must be gone before the scroll measures, or the
269 // list lands short of the real end.
270 requestAnimationFrame(() => {
271 const list = legendListRef.current;
272 if (!list) return;
273 void Promise.resolve(
274 list.scrollToEnd?.({
275 animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
276 }),
277 ).then(() =>
278 settleListScroll(
279 list,
280 measuredEndOffset,
281 () => timelineScrollModeRef.current !== "following-end" || legendListRef.current !== list,
282 ),
283 );
284 });
285 };
286 const scrollToEndStable = useStableCallback(scrollToEnd);
287 useEffect(() => {
288 const composer = composerRef;
289 let removeListeners: (() => void) | null = null;
290 let frame: number | null = null;
291 const attach = (remainingAttempts: number) => {
292 frame = requestAnimationFrame(() => {
293 frame = null;
294 const scrollNode = legendListRef.current?.getScrollableNode();
295 if (!scrollNode) {
296 // The list may not have mounted on the first frame after a thread
297 // switch — without a retry the opt-out listeners never attach and
298 // live-follow becomes impossible to escape for the whole thread.
299 if (remainingAttempts > 0) {
300 attach(remainingAttempts - 1);
301 }
302 return;
303 }
304 const handleManualNavigation = () => {
305 cancelTimelineLiveFollowForUserNavigationRef.current();
306 };
307 // Only break follow for gestures that can move away from the live edge.
308 // A spurious break emits no scroll event to re-arm follow, so streaming stops
309 // following. Underflowing content cannot scroll and must keep following.
310 const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
311 // The follow re-arm band, not the strict flag: streaming growth makes
312 // isAtEnd flicker false for a frame before the follow scroll catches
313 // up, and a gesture landing in that window while still pinned would
314 // otherwise break follow with no scroll event left to re-arm it.
315 const viewportIsAwayFromEnd = () =>
316 resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
317 const handleWheel = (event: WheelEvent) => {
318 if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
319 return;
320 if (event.deltaY > 0) {
321 timelineScrollIntentRef.current = "toward-end";
322 if (isAtEndRef.current) {
323 composer.current?.restoreAfterTimelineReachedEnd();
324 }
325 } else if (event.deltaY < 0) {
326 timelineScrollIntentRef.current = "away-from-end";
327 }
328 if (event.deltaY < 0 && contentScrollsUp()) {
329 handleManualNavigation();
330 }
331 };
332 // Touch direction isn't observable here (touchmove fires on any
333 // finger motion, scrolling or not), so break only once the drag has
334 // actually carried the viewport out of the end band — an upward flick
335 // gets there within its first few events and later touchmoves break.
336 const handleTouchMove = () => {
337 if (viewportIsAwayFromEnd()) {
338 handleManualNavigation();
339 }
340 };
341 // Scrollbar drags produce no wheel/touch events; they are the only
342 // pointerdowns whose target is the scroll node itself rather than a
343 // message row.
344 const handlePointerDown = (event: PointerEvent) => {
345 if (event.target === scrollNode) {
346 if (contentScrollsUp()) {
347 handleManualNavigation();
348 }
349 return;
350 }
351 if (viewportIsAwayFromEnd()) {
352 handleManualNavigation();
353 }
354 };
355 // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
356 // pointer events entirely; without this the timeline yanks back to
357 // the end on the next stream chunk. Clicking message text can leave
358 // DOM focus on body, so these keys must also be heard at document.
359 const handleKeyDown = (event: KeyboardEvent) => {
360 if (
361 !(event.target instanceof Node) ||
362 (!scrollNode.contains(event.target) &&
363 event.target !== document.body &&
364 event.target !== document.documentElement) ||
365 event.defaultPrevented ||
366 event.isComposing ||
367 event.altKey ||
368 event.ctrlKey ||
369 event.metaKey ||
370 event.shiftKey ||
371 eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
372 document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
373 ) {
374 return;
375 }
376 if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
377 return;
378 const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
379 if (
380 scrollNode.contains(event.target) &&
381 !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
382 )
383 return;
384 switch (event.key) {
385 case "PageUp":
386 case "Home":
387 case "ArrowUp":
388 timelineScrollIntentRef.current = "away-from-end";
389 if (contentScrollsUp()) {
390 handleManualNavigation();
391 composer.current?.collapseForTimelineScrollKey(event.key);
392 }
393 break;
394 case "PageDown":
395 case "End":
396 case "ArrowDown":
397 timelineScrollIntentRef.current = "toward-end";
398 if (viewportIsAwayFromEnd()) {
399 handleManualNavigation();
400 }
401 composer.current?.collapseForTimelineScrollKey(event.key);
402 if (isTimelineAtLogicalEndStable()) {
403 composer.current?.restoreAfterTimelineReachedEnd();
404 }
405 break;
406 default:
407 break;
408 }
409 };
410 // Input inside an embedded frame reaches none of the listeners above,
411 // but its scroll still chains out to the timeline.
412 const scrolledUp = createUpwardScrollDetector({
413 top: scrollNode.scrollTop,
414 height: scrollNode.scrollHeight,
415 });
416 const handleScroll = () => {
417 if (
418 scrolledUp({
419 top: scrollNode.scrollTop,
420 height: scrollNode.scrollHeight,
421 programmatic:
422 positionedTimelineAnchorRef.current !== null &&
423 positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,
424 }) &&
425 timelineScrollModeRef.current !== "free-scrolling" &&
426 // LegendList updates its scroll state on the next animation frame.
427 resolveTimelineIsAtEnd({
428 contentLength: scrollNode.scrollHeight,
429 scroll: scrollNode.scrollTop,
430 scrollLength: scrollNode.clientHeight,
431 }) === false
432 ) {
433 handleManualNavigation();
434 }
435 };
436 scrollNode.addEventListener("scroll", handleScroll, { passive: true });
437 scrollNode.addEventListener("wheel", handleWheel, {
438 passive: true,
439 });
440 scrollNode.addEventListener("touchmove", handleTouchMove, {
441 passive: true,
442 });
443 scrollNode.addEventListener("pointerdown", handlePointerDown, {
444 passive: true,
445 });
446 document.addEventListener("keydown", handleKeyDown);
447 removeListeners = () => {
448 scrollNode.removeEventListener("scroll", handleScroll);
449 scrollNode.removeEventListener("wheel", handleWheel);
450 scrollNode.removeEventListener("touchmove", handleTouchMove);
451 scrollNode.removeEventListener("pointerdown", handlePointerDown);
452 document.removeEventListener("keydown", handleKeyDown);
453 };
454 });
455 };
456 attach(12);
457
458 return () => {
459 if (frame !== null) {
460 cancelAnimationFrame(frame);
461 }
462 removeListeners?.();
463 };
464 }, [
465 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
466 activeThreadId,
467 composerRef,
468 isTimelineAtLogicalEndStable,
469 legendListRef,
470 timelineRealContentOverflowsViewportStable,
471 ]);
472
473 const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
474 if (pendingTimelineAnchorRef.current === messageId) {
475 pendingTimelineAnchorRef.current = null;
476 }
477 activeTimelineAnchorIndexRef.current = anchorIndex;
478 if (positionedTimelineAnchorRef.current === messageId) {
479 return;
480 }
481 positionedTimelineAnchorRef.current = messageId;
482 settledTimelineAnchorRef.current = null;
483 const positionAnchor = (remainingAttempts: number) => {
484 requestAnimationFrame(() => {
485 if (positionedTimelineAnchorRef.current !== messageId) {
486 return;
487 }
488 const list = legendListRef.current;
489 if (!list) {
490 if (remainingAttempts > 0) {
491 positionAnchor(remainingAttempts - 1);
492 }
493 return;
494 }
495 // LegendList waits for queued layout and the animation before resolving.
496 void list
497 .scrollToIndex({
498 index: anchorIndex,
499 animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
500 viewPosition: 0,
501 viewOffset: CHAT_LIST_ANCHOR_OFFSET,
502 })
503 .then(() => {
504 if (
505 legendListRef.current === list &&
506 positionedTimelineAnchorRef.current === messageId
507 ) {
508 settledTimelineAnchorRef.current = messageId;
509 }
510 });
511 });
512 };
513 requestAnimationFrame(() => positionAnchor(12));
514 };
515 const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
516 const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
517 if (settledTimelineAnchorRef.current !== messageId) {
518 return;
519 }
520 if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {
521 return;
522 }
523 const scrollOffset = legendListRef.current?.getState().scroll;
524 if (scrollOffset === undefined) {
525 return;
526 }
527 if (pendingAnchorScrollRestoreRef.current === null) {
528 pendingAnchorScrollRestoreRef.current = {
529 messageId,
530 offset: scrollOffset,
531 userScrollGeneration: anchorUserScrollGenerationRef.current,
532 };
533 }
534 if (anchorScrollRestoreFrameRef.current !== null) {
535 return;
536 }
537 anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
538 anchorScrollRestoreFrameRef.current = null;
539 const pending = pendingAnchorScrollRestoreRef.current;
540 pendingAnchorScrollRestoreRef.current = null;
541 if (
542 pending &&
543 settledTimelineAnchorRef.current === pending.messageId &&
544 pending.userScrollGeneration === anchorUserScrollGenerationRef.current
545 ) {
546 const list = legendListRef.current;
547 const currentScrollOffset = list?.getState().scroll;
548 if (
549 typeof currentScrollOffset === "number" &&
550 Math.abs(currentScrollOffset - pending.offset) <= 2
551 ) {
552 void list?.scrollToOffset({ offset: pending.offset, animated: false });
553 }
554 }
555 });
556 };
557 const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
558
559 const onToolOutputCollapsedAtEnd = () => {
560 composerRef.current?.restoreAfterTimelineReachedEnd();
561 };
562 const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
563
564 const onIsAtEndChange = (isAtEnd: boolean) => {
565 if (
566 !isAtEnd &&
567 liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
568 ) {
569 showScrollDebouncer.current.cancel();
570 setShowScrollToBottom(false);
571 return;
572 }
573 if (isAtEndRef.current === isAtEnd) return;
574 isAtEndRef.current = isAtEnd;
575 if (isAtEnd) {
576 if (timelineScrollIntentRef.current === "toward-end") {
577 composerRef.current?.restoreAfterTimelineReachedEnd();
578 }
579 timelineScrollModeRef.current = "following-end";
580 liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
581 setTimelineLiveFollowEnabled(true);
582 setTimelineAnchor(releaseChatTimelineAnchor);
583 showScrollDebouncer.current.cancel();
584 setShowScrollToBottom(false);
585 } else {
586 timelineScrollModeRef.current = "free-scrolling";
587 liveFollowUserScrollGenerationRef.current = null;
588 showScrollDebouncer.current.maybeExecute();
589 }
590 };
591 const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
592
593 // timelineEntries leave out reasoning rows (their text is not in the
594 // structure), and reasoning counts as tool activity, like any work row.
595 const runningTurnHasReasoning =
596 activeRunningTurnId !== null &&
597 serverProjection?.visibleTurnItems.some(
598 (row) => row.item.type === "reasoning" && row.item.runId === activeRunningTurnId,
599 ) === true;
600 useLayoutEffect(() => {
601 if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
602 if (
603 (runningTurnHasReasoning && timelineAnchorMessageId !== null && timelineLiveFollowEnabled) ||
604 shouldReleaseTimelineAnchorForToolActivity({
605 anchorMessageId: timelineAnchorMessageId,
606 liveFollowEnabled: timelineLiveFollowEnabled,
607 runningTurnId: activeRunningTurnId,
608 timelineEntries,
609 })
610 ) {
611 scrollToEndStable();
612 }
613 }, [
614 activeRunningTurnId,
615 runningTurnHasReasoning,
616 scrollToEndStable,
617 timelineAnchorMessageId,
618 timelineEntries,
619 timelineLiveFollowEnabled,
620 ]);
621
622 // A thread switch restores that thread's remembered follow state; the refs
623 // the scroll handlers read catch up after commit.
624 const [timelineThreadReset, setTimelineThreadReset] = useState({
625 threadKey: activeThreadKey,
626 followEnd: true,
627 });
628 if (timelineThreadReset.threadKey !== activeThreadKey) {
629 const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
630 setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
631 setTimelineLiveFollowEnabled(followEnd);
632 setShowScrollToBottom(!followEnd);
633 }
634 useEffect(() => {
635 const { followEnd } = timelineThreadReset;
636 isAtEndRef.current = followEnd;
637 timelineScrollIntentRef.current = null;
638 timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
639 liveFollowUserScrollGenerationRef.current = followEnd
640 ? anchorUserScrollGenerationRef.current
641 : null;
642 pendingTimelineAnchorRef.current = null;
643 positionedTimelineAnchorRef.current = null;
644 settledTimelineAnchorRef.current = null;
645 activeTimelineAnchorIndexRef.current = null;
646 showScrollDebouncer.current.cancel();
647 }, [timelineThreadReset]);
648
649 /** Arms the anchor for a message the user just sent, before its run exists. */
650 const anchorNewTurn = (threadKey: string, messageId: MessageId) => {
651 isAtEndRef.current = true;
652 timelineScrollModeRef.current = "anchoring-new-turn";
653 liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
654 setTimelineLiveFollowEnabled(true);
655 pendingTimelineAnchorRef.current = messageId;
656 activeTimelineAnchorIndexRef.current = null;
657 showScrollDebouncer.current.cancel();
658 setShowScrollToBottom(false);
659 setTimelineAnchor({ threadKey, messageId });
660 };
661
662 return {
663 showScrollToBottom,
664 timelineLiveFollowEnabled,
665 cancelPositionRestoreRef,
666 isTimelineAtLogicalEndStable,
667 cancelTimelineLiveFollowForUserNavigationStable,
668 onComposerPageScrollKeyDownStable,
669 onComposerPageScrollKeyUpStable,
670 onComposerPageScrollReleaseStable,
671 scrollToEnd,
672 onTimelineAnchorReadyStable,
673 onTimelineAnchorSizeChangedStable,
674 onToolOutputCollapsedAtEndStable,
675 onIsAtEndChangeStable,
676 anchorNewTurn,
677 };
678}