Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useTimelineFollow.ts

602 lines24.0 KB

1import { useStableCallback } from "../../hooks/useStableCallback";
2import { type MessageId, type RunId } from "@t3tools/contracts";
3import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
4import { Debouncer } from "@tanstack/react-pacer";
5import {
6 type SetStateAction,
7 useLayoutEffect,
8 useRef,
9 useState,
10 useSyncExternalStore,
11} from "react";
12import { type LegendListRef } from "@legendapp/list/react";
13import {
14 CHAT_TIMELINE_ANCHOR_OFFSET,
15 timelineContentOverflowsViewport,
16 readTimelinePosition,
17 observeTimelineRun,
18 type TimelineRunObservation,
19} from "./timelineScrollAnchoring";
20import { type ChatComposerHandle } from "./ChatComposer";
21import { createPageScrollController, type PageScrollKey } from "./pageScrollController";
22import {
23 FOLLOWING,
24 initialTimelineFollow,
25 navigationReleasesFollow,
26 transitionTimelineFollow,
27 type TimelineFollow,
28 type TimelineFollowEvent,
29 type TimelineNavigation,
30 type TimelineViewport,
31} from "./timelineViewport";
32import { resolveTimelineIsAtEnd, type MessagesTimelineRow } from "./MessagesTimeline.logic";
33import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";
34import {
35 releaseChatTimelineAnchor,
36 shouldReleaseTimelineAnchorForToolActivity,
37} from "../ChatView.logic";
38import type { Dispatch, RefObject } from "react";
39import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
40import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
41import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
42import type { TimelineEntry } from "../../session-logic";
43​
44const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
45​
46interface TimelineAnchor {
47 readonly threadKey: string | null;
48 readonly messageId: MessageId | null;
50​
51/** One visit to a thread; a switch starts a new one from the remembered position. */
52interface TimelineFollowVisit {
53 readonly threadKey: string | null;
54 readonly followEnd: boolean;
56​
57/**
58 * Scroll bookkeeping that belongs to one visit. Handlers fetch it for the
59 * current visit, so a thread switch leaves the old one behind instead of
60 * resetting it.
61 */
62function createVisitScrollState(
63 visit: TimelineFollowVisit,
64 showScrollToBottom: (visit: TimelineFollowVisit) => void,
65) {
66 return {
67 visit,
68 intent: null as "toward-end" | "away-from-end" | null,
69 // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
70 // thread switches. LegendList fires scroll events with isAtEnd=false while
71 // initialScrollAtEnd is settling; hiding is always immediate.
72 showScrollDebouncer: new Debouncer(() => showScrollToBottom(visit), { wait: 150 }),
73 positionedAnchor: null as MessageId | null,
74 settledAnchor: null as MessageId | null,
75 releaseAnchorScrollHold: null as (() => void) | null,
76 pendingAnchorScrollRestore: null as {
77 readonly messageId: MessageId;
78 readonly offset: number;
79 } | null,
80 anchorScrollRestoreFrame: null as number | null,
81 };
83type VisitScrollState = ReturnType<typeof createVisitScrollState>;
84​
85function stopAnchorPositioning(scroll: VisitScrollState) {
86 scroll.positionedAnchor = null;
87 scroll.settledAnchor = null;
88 scroll.releaseAnchorScrollHold?.();
89 scroll.releaseAnchorScrollHold = null;
91​
92/** Whether the list still shows the anchored message; a thread switch replaces its data. */
93function listShowsMessage(list: LegendListRef | null, messageId: MessageId): boolean {
94 const rows = list?.getState().data as ReadonlyArray<MessagesTimelineRow> | undefined;
95 return rows?.some((row) => row.kind === "message" && row.message.id === messageId) === true;
97​
98/**
99 * The follow mode, read by scroll listeners at event time and by render
100 * through useSyncExternalStore. State recorded for an earlier visit is
101 * discarded, so a thread switch needs no reset step.
102 */
103function createTimelineFollowStore() {
104 let snapshot: { readonly visit: TimelineFollowVisit | null; readonly follow: TimelineFollow } = {
105 visit: null,
106 follow: FOLLOWING,
107 };
108 const listeners = new Set<() => void>();
109 // Page keys read the overlay at keypress time; it changes no rendered state.
110 let composerOverlay: HTMLElement | null = null;
111 const read = (visit: TimelineFollowVisit) =>
112 snapshot.visit === visit ? snapshot.follow : initialTimelineFollow(visit.followEnd);
113 return {
114 subscribe: (listener: () => void) => {
115 listeners.add(listener);
116 return () => listeners.delete(listener);
117 },
118 snapshot: () => snapshot,
119 read,
120 /** Ref callback for the composer overlay. */
121 attachComposerOverlay: (element: HTMLElement | null) => {
122 composerOverlay = element;
123 },
124 readComposerOverlayHeight: () => composerOverlay?.getBoundingClientRect().height ?? 0,
125 dispatch: (visit: TimelineFollowVisit, event: TimelineFollowEvent) => {
126 const before = read(visit);
127 const after = transitionTimelineFollow(before, event);
128 if (snapshot.visit !== visit || after !== snapshot.follow) {
129 snapshot = { visit, follow: after };
130 for (const listener of listeners) listener();
131 }
132 return { before, after };
133 },
134 };
136​
137function sameRunObservation(
138 next: TimelineRunObservation,
139 previous: TimelineRunObservation | null,
140): boolean {
141 return (
142 previous !== null &&
143 next.threadKey === previous.threadKey &&
144 next.hydrated === previous.hydrated &&
145 next.runId === previous.runId
146 );
148​
149interface TimelineFollowInput {
150 readonly legendListRef: RefObject<LegendListRef | null>;
151 readonly composerRef: RefObject<ChatComposerHandle | null>;
152 readonly composerTimelineInset: number;
153 readonly routeThreadKey: string;
154 readonly activeThreadKey: string | null;
155 readonly isServerThread: boolean;
156 readonly serverProjection: ThreadStructure | null;
157 readonly threadStatus: EnvironmentThreadStatus;
158 readonly activeActivityRun: ReturnType<typeof deriveThreadActivityRun>;
159 readonly activeRunningTurnId: RunId | null;
160 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
161 readonly timelineAnchorMessageId: MessageId | null;
162 readonly setTimelineAnchor: Dispatch<SetStateAction<TimelineAnchor>>;
164​
165/**
166 * Keeps the timeline following the live end, anchoring a newly sent turn near
167 * the top, and letting the user scroll away. Follow lives in a store the
168 * viewport's navigation signal writes, so a scroll gesture does not re-render
169 * ChatView unless the follow mode flips.
170 */
171export function useTimelineFollow(input: TimelineFollowInput) {
172 const {
173 legendListRef,
174 composerRef,
175 composerTimelineInset,
176 routeThreadKey,
177 activeThreadKey,
178 isServerThread,
179 serverProjection,
180 threadStatus,
181 activeActivityRun,
182 activeRunningTurnId,
183 timelineEntries,
184 timelineAnchorMessageId,
185 setTimelineAnchor,
186 } = input;
187 const [visitState, setVisit] = useState<TimelineFollowVisit>({
188 threadKey: activeThreadKey,
189 followEnd: true,
190 });
191 let visit = visitState;
192 if (visit.threadKey !== activeThreadKey) {
193 visit = {
194 threadKey: activeThreadKey,
195 followEnd: readTimelinePosition(routeThreadKey)?.atEnd !== false,
196 };
197 setVisit(visit);
198 }
199 // Keyed by visit, so a pill decision from the previous thread (a pending
200 // debounce) never shows here.
201 const [pill, setPill] = useState<{ readonly visit: TimelineFollowVisit; readonly show: boolean }>(
202 { visit, show: false },
203 );
204 const showScrollToBottom = pill.visit === visit ? pill.show : !visit.followEnd;
205 // Called on every streamed chunk while following; an unchanged pill must
206 // bail out instead of re-rendering ChatView.
207 const setShowScrollToBottom = (show: boolean) =>
208 setPill((current) =>
209 current.visit === visit && current.show === show ? current : { visit, show },
210 );
211 const [followStore] = useState(createTimelineFollowStore);
212 const followSnapshot = useSyncExternalStore(followStore.subscribe, followStore.snapshot);
213 const follow =
214 followSnapshot.visit === visit ? followSnapshot.follow : initialTimelineFollow(visit.followEnd);
215 const timelineLiveFollowEnabled = follow.mode === "following";
216 const readFollow = () => followStore.read(visit);
217 // Async settles outlive their render; this reads the visit shown now.
218 const readCurrentFollow = useStableCallback(readFollow);
219 const isTimelineAtLogicalEnd = () => {
220 const current = readFollow();
221 return (
222 resolveTimelineIsAtEnd(legendListRef.current?.getState()) ??
223 (current.mode === "following" || current.atEnd)
224 );
225 };
226 const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
227 const visitScrollRef = useRef<VisitScrollState | null>(null);
228 /** Only from handlers: the bookkeeping of the visit they run in. */
229 const visitScroll = () => {
230 if (visitScrollRef.current?.visit !== visit) {
231 visitScrollRef.current = createVisitScrollState(visit, (shownVisit) => {
232 // A debounce that outlived its visit must not overwrite the current one's pill.
233 if (visitScrollRef.current?.visit === shownVisit)
234 setPill({ visit: shownVisit, show: true });
235 });
236 }
237 return visitScrollRef.current;
238 };
239 // The anchor whose list position LegendList reported ready; until then a
240 // newly started run must not re-anchor.
241 const [laidOutAnchor, setLaidOutAnchor] = useState<MessageId | null>(null);
242 const anchorPending =
243 timelineAnchorMessageId !== null && laidOutAnchor !== timelineAnchorMessageId;
244 const viewportRef = useRef<TimelineViewport | null>(null);
245 const releaseFollowForNavigation = () => {
246 const { before } = followStore.dispatch(visit, { type: "navigated" });
247 if (before.mode === "following") viewportRef.current?.followReleased();
248 const scroll = visitScroll();
249 stopAnchorPositioning(scroll);
250 scroll.pendingAnchorScrollRestore = null;
251 if (scroll.anchorScrollRestoreFrame !== null) {
252 cancelAnimationFrame(scroll.anchorScrollRestoreFrame);
253 scroll.anchorScrollRestoreFrame = null;
254 }
255 if (before.mode === "following") {
256 // LegendList may run queued scrolls after user navigation. A new imperative
257 // scroll cancels that queue; a missing item cancels without moving the view.
258 void legendListRef.current?.scrollToItem({
259 item: TIMELINE_SCROLL_CANCEL_SENTINEL,
260 animated: false,
261 });
262 // An already-started animated scroll (behavior: smooth) keeps running in
263 // the browser regardless of the queue; a same-position instant write is
264 // the only way to halt it where it is.
265 const scrollNode = legendListRef.current?.getScrollableNode() as
266 | { scrollTop?: number }
267 | null
268 | undefined;
269 const currentScrollTop = scrollNode?.scrollTop;
270 if (scrollNode && typeof currentScrollTop === "number") {
271 scrollNode.scrollTop = currentScrollTop;
272 }
273 }
274 };
275​
276 // A run that starts while the live end is followed anchors its user message
277 // near the top, unless the previous anchor has not been laid out yet.
278 const [observedRun, setObservedRun] = useState<TimelineRunObservation | null>(null);
279 const dispatchedUserItem =
280 observedRun?.hydrated &&
281 observedRun.threadKey === activeThreadKey &&
282 activeActivityRun !== null &&
283 observedRun.runId !== activeActivityRun.runId
284 ? serverProjection?.visibleTurnItems.find(
285 (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,
286 )
287 : undefined;
288 const runObservation = observeTimelineRun(observedRun, {
289 threadKey: activeThreadKey,
290 hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),
291 runId: activeActivityRun?.runId ?? null,
292 queued: activeActivityRun?.status === "queued",
293 messageId:
294 dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,
295 });
296 if (!sameRunObservation(runObservation.observation, observedRun)) {
297 setObservedRun(runObservation.observation);
298 const startedRunAnchor = runObservation.anchorMessageId;
299 if (startedRunAnchor !== null && !anchorPending && timelineLiveFollowEnabled) {
300 setShowScrollToBottom(false);
301 setTimelineAnchor({ threadKey: activeThreadKey, messageId: startedRunAnchor });
302 }
303 }
304 const timelineRealContentOverflowsViewport = () =>
305 timelineContentOverflowsViewport(legendListRef.current?.getState(), {
306 composerInset: composerTimelineInset,
307 anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
308 });
309 const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
310 null,
311 );
312 const handlePageScrollStart = useStableCallback((key: PageScrollKey) => {
313 visitScroll().intent = key === "PageUp" ? "away-from-end" : "toward-end";
314 composerRef.current?.collapseForTimelineScrollKey(key);
315 if ((key === "PageUp" && timelineRealContentOverflowsViewport()) || !isTimelineAtLogicalEnd()) {
316 // Through the viewport, so a running position restore stops too.
317 viewportRef.current?.navigate({ releasesFollow: true });
318 }
319 });
320 const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
321 pageScrollControllerRef.current?.handleKeyDown(key);
322 };
323 const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
324 const onComposerPageScrollKeyUp = (key: string) => {
325 pageScrollControllerRef.current?.handleKeyUp(key);
326 };
327 const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
328 const onComposerPageScrollRelease = () => {
329 pageScrollControllerRef.current?.releaseActiveKey();
330 };
331 const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
332 const scrollToEnd = (animated: boolean = false) => {
333 // Stops a running position restore; follow itself is re-armed below.
334 viewportRef.current?.navigate({ releasesFollow: false });
335 followStore.dispatch(visit, { type: "followEnd" });
336 visitScroll().showScrollDebouncer.cancel();
337 setShowScrollToBottom(false);
338 setTimelineAnchor(releaseChatTimelineAnchor);
339 // The anchored end space must be gone before the scroll measures, or the
340 // list lands short of the real end.
341 requestAnimationFrame(() => {
342 const list = legendListRef.current;
343 if (!list) return;
344 void Promise.resolve(
345 list.scrollToEnd?.({
346 animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
347 }),
348 ).then(() =>
349 settleListScroll(
350 list,
351 measuredEndOffset,
352 () => readCurrentFollow().mode !== "following" || legendListRef.current !== list,
353 ),
354 );
355 });
356 };
357 const scrollToEndStable = useStableCallback(scrollToEnd);
358 // The list does not follow footer layout, so the resting composer cannot scroll it. Growth
359 // above the composer (a new notice) would cover the last rows instead.
360 const followedInsetRef = useRef(composerTimelineInset);
361 // oxlint-disable-next-line t3code/react-effect-budget -- scrolls the list after its bottom inset grows
362 useLayoutEffect(() => {
363 const grew = composerTimelineInset > followedInsetRef.current;
364 followedInsetRef.current = composerTimelineInset;
365 if (grew && readCurrentFollow().mode === "following") scrollToEndStable();
366 }, [composerTimelineInset, readCurrentFollow, scrollToEndStable]);
367​
368 const handleNavigation = (navigation: TimelineNavigation) => {
369 const composer = composerRef.current;
370 const awayFromEnd = () => resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
371 const releases = navigationReleasesFollow(navigation, {
372 contentScrollsUp: timelineRealContentOverflowsViewport,
373 awayFromEnd,
374 });
375 if (navigation.source === "wheel") {
376 visitScroll().intent = navigation.direction === "down" ? "toward-end" : "away-from-end";
377 const current = readFollow();
378 if (navigation.direction === "down" && (current.mode === "following" || current.atEnd)) {
379 composer?.restoreAfterTimelineReachedEnd();
380 }
381 }
382 if (navigation.source === "key") {
383 visitScroll().intent = navigation.direction === "down" ? "toward-end" : "away-from-end";
384 }
385 if (releases) releaseFollowForNavigation();
386 if (navigation.source === "key" && navigation.key !== " ") {
387 if (navigation.direction === "up") {
388 if (releases) composer?.collapseForTimelineScrollKey(navigation.key);
389 } else {
390 composer?.collapseForTimelineScrollKey(navigation.key);
391 if (isTimelineAtLogicalEnd()) composer?.restoreAfterTimelineReachedEnd();
392 }
393 }
394 };
395 const handleNavigationStable = useStableCallback(handleNavigation);
396 /**
397 * Attached by the timeline's list ref callback, so follow hears the
398 * viewport's navigation exactly as long as the scroll node exists.
399 */
400 const attachTimelineViewport = (viewport: TimelineViewport) => {
401 viewportRef.current = viewport;
402 const unsubscribe = viewport.subscribe(handleNavigationStable);
403 const controller = createPageScrollController({
404 getContainer: () => viewport.scrollNode,
405 getScrollPaddingBottomPx: followStore.readComposerOverlayHeight,
406 onScrollStart: handlePageScrollStart,
407 });
408 pageScrollControllerRef.current = controller;
409 return () => {
410 unsubscribe();
411 controller.dispose();
412 if (pageScrollControllerRef.current === controller) pageScrollControllerRef.current = null;
413 if (viewportRef.current === viewport) viewportRef.current = null;
414 const scroll = visitScrollRef.current;
415 scroll?.releaseAnchorScrollHold?.();
416 if (scroll) scroll.releaseAnchorScrollHold = null;
417 };
418 };
419​
420 const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
421 setLaidOutAnchor(messageId);
422 const scroll = visitScroll();
423 if (scroll.positionedAnchor === messageId) {
424 return;
425 }
426 stopAnchorPositioning(scroll);
427 scroll.positionedAnchor = messageId;
428 // The positioning scroll moves up when the anchor sits above the view.
429 const releaseHold = viewportRef.current?.holdProgrammaticScroll() ?? (() => {});
430 scroll.releaseAnchorScrollHold = releaseHold;
431 const isPositioning = () =>
432 scroll.positionedAnchor === messageId && listShowsMessage(legendListRef.current, messageId);
433 // Releasing is idempotent, so an attempt that is no longer current (the
434 // thread switched, the user navigated) always lets go of its own hold.
435 const abandon = () => {
436 releaseHold();
437 if (scroll.positionedAnchor === messageId) stopAnchorPositioning(scroll);
438 };
439 const positionAnchor = (remainingAttempts: number) => {
440 requestAnimationFrame(() => {
441 if (!isPositioning()) {
442 abandon();
443 return;
444 }
445 const list = legendListRef.current;
446 if (!list) {
447 if (remainingAttempts > 0) {
448 positionAnchor(remainingAttempts - 1);
449 } else {
450 abandon();
451 }
452 return;
453 }
454 // LegendList waits for queued layout and the animation before resolving.
455 void list
456 .scrollToIndex({
457 index: anchorIndex,
458 animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
459 viewPosition: 0,
460 viewOffset: CHAT_LIST_ANCHOR_OFFSET,
461 })
462 .then(() => {
463 if (legendListRef.current === list && isPositioning()) {
464 scroll.settledAnchor = messageId;
465 releaseHold();
466 scroll.releaseAnchorScrollHold = null;
467 } else {
468 abandon();
469 }
470 });
471 });
472 };
473 requestAnimationFrame(() => positionAnchor(12));
474 };
475 const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
476 const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
477 const scroll = visitScroll();
478 if (scroll.settledAnchor !== messageId || readFollow().mode === "following") {
479 return;
480 }
481 const scrollOffset = legendListRef.current?.getState().scroll;
482 if (scrollOffset === undefined) {
483 return;
484 }
485 if (scroll.pendingAnchorScrollRestore === null) {
486 scroll.pendingAnchorScrollRestore = { messageId, offset: scrollOffset };
487 }
488 if (scroll.anchorScrollRestoreFrame !== null) {
489 return;
490 }
491 scroll.anchorScrollRestoreFrame = requestAnimationFrame(() => {
492 scroll.anchorScrollRestoreFrame = null;
493 const pending = scroll.pendingAnchorScrollRestore;
494 scroll.pendingAnchorScrollRestore = null;
495 if (pending && scroll.settledAnchor === pending.messageId) {
496 const list = legendListRef.current;
497 const currentScrollOffset = list?.getState().scroll;
498 if (
499 typeof currentScrollOffset === "number" &&
500 Math.abs(currentScrollOffset - pending.offset) <= 2
501 ) {
502 void list?.scrollToOffset({ offset: pending.offset, animated: false });
503 }
504 }
505 });
506 };
507 const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
508​
509 const onToolOutputCollapsedAtEnd = () => {
510 composerRef.current?.restoreAfterTimelineReachedEnd();
511 };
512 const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
513 // The list ignores footer layout, so a new queued turn or status line there would land
514 // under the composer. Follow it when the reader was following the end.
515 const onTimelineFooterGrow = () => {
516 if (readFollow().mode === "following") scrollToEndStable();
517 };
518 const onTimelineFooterGrowStable = useStableCallback(onTimelineFooterGrow);
519​
520 const onIsAtEndChange = (isAtEnd: boolean) => {
521 const scroll = visitScroll();
522 if (!isAtEnd && readFollow().mode === "following") {
523 scroll.showScrollDebouncer.cancel();
524 setShowScrollToBottom(false);
525 return;
526 }
527 const { before, after } = followStore.dispatch(visit, {
528 type: isAtEnd ? "reachedEnd" : "leftEnd",
529 });
530 if (after === before) return;
531 if (after.mode === "following") {
532 if (scroll.intent === "toward-end") {
533 composerRef.current?.restoreAfterTimelineReachedEnd();
534 }
535 setTimelineAnchor(releaseChatTimelineAnchor);
536 scroll.showScrollDebouncer.cancel();
537 setShowScrollToBottom(false);
538 } else {
539 scroll.showScrollDebouncer.maybeExecute();
540 }
541 };
542 const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
543​
544 // timelineEntries leave out reasoning rows (their text is not in the
545 // structure), and reasoning counts as tool activity, like any work row.
546 const runningTurnHasReasoning =
547 activeRunningTurnId !== null &&
548 serverProjection?.visibleTurnItems.some(
549 (row) => row.item.type === "reasoning" && row.item.runId === activeRunningTurnId,
550 ) === true;
551 // Z: the release scrolls, and that scroll must follow the commit that drops
552 // the anchored end space; the trigger is streamed thread data. A
553 // totalSize listener cannot replace it: the anchored end space can already
554 // be 0, so dropping it changes no size and no list event fires.
555 useLayoutEffect(() => {
556 if (timelineAnchorMessageId === null || !timelineLiveFollowEnabled) return;
557 if (
558 runningTurnHasReasoning ||
559 shouldReleaseTimelineAnchorForToolActivity({
560 anchorMessageId: timelineAnchorMessageId,
561 liveFollowEnabled: timelineLiveFollowEnabled,
562 runningTurnId: activeRunningTurnId,
563 timelineEntries,
564 })
565 ) {
566 scrollToEndStable();
567 }
568 }, [
569 activeRunningTurnId,
570 runningTurnHasReasoning,
571 scrollToEndStable,
572 timelineAnchorMessageId,
573 timelineEntries,
574 timelineLiveFollowEnabled,
575 ]);
576​
577 /** Arms the anchor for a message the user just sent, before its run exists. */
578 const anchorNewTurn = (threadKey: string, messageId: MessageId) => {
579 followStore.dispatch(visit, { type: "followEnd" });
580 visitScroll().showScrollDebouncer.cancel();
581 setShowScrollToBottom(false);
582 setTimelineAnchor({ threadKey, messageId });
583 };
584​
585 return {
586 showScrollToBottom,
587 timelineLiveFollowEnabled,
588 isTimelineAtLogicalEndStable,
589 onComposerPageScrollKeyDownStable,
590 onComposerPageScrollKeyUpStable,
591 onComposerPageScrollReleaseStable,
592 scrollToEnd,
593 onTimelineAnchorReadyStable,
594 onTimelineAnchorSizeChangedStable,
595 onToolOutputCollapsedAtEndStable,
596 onTimelineFooterGrowStable,
597 onIsAtEndChangeStable,
598 anchorNewTurn,
599 attachTimelineViewport,
600 attachComposerOverlay: followStore.attachComposerOverlay,
601 };