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 { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
32import { releaseChatTimelineAnchor } from "../ChatView.logic";
33import type { Dispatch, RefObject } from "react";
34import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
35import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
36import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
37import type { TimelineEntry } from "../../session-logic";
38
39const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
40
41interface TimelineAnchor {
42 readonly threadKey: string | null;
43 readonly messageId: MessageId | null;
44}
45
46interface 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 */
69export 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}