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