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