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