The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): timeline row derivation, position restore and find reader live in hooks (#22682)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 01:12 UTC
bef9142f8b9685dab9e1d13cc6c6750a7c78b2d3
5 files changed
+391
-285
apps/web/src/components/chat/MessagesTimeline.logic.ts
+27
-1
@@ -8,6 +8,7 @@ import {
8
collectAssistantCitations,
9
} from "@t3tools/shared/assistantCitations";
10
import { shallow } from "zustand/vanilla/shallow";
11
+import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
12
import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives";
13
import {
14
commandDisplayText,
@@ -2011,7 +2012,7 @@ function attachCreatedThreadSummaries(
2012
2013
const WORKTREE_SETUP_ROW_ID = "worktree-setup-row";
2014
2014
-type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
2015
+export type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
2016
2017
export interface MessagesTimelineRowsProjection {
2018
readonly input: MessagesTimelineRowsInput;
@@ -2314,3 +2315,28 @@ export function shouldCollapseUserMessage(text: string): boolean {
2315
visible.split("\n").length > MAX_COLLAPSED_USER_MESSAGE_LINES
2316
);
2317
}
2318
+
2319
+export function handoffRunsSignature(runs: ReadonlyArray<HandoffTimelineRun>): string {
2320
+ return runs
2321
+ .map(
2322
+ (run) =>
2323
+ `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
2324
+ )
2325
+ .join("\n");
2326
+}
2327
+
2328
+// Expanded-id sets can be rebuilt during render; comparing them by content keeps
2329
+// the render-time state update in useIncrementalTimelineRows from repeating forever.
2330
+export function sameRowsInput(
2331
+ left: MessagesTimelineRowsInput,
2332
+ right: MessagesTimelineRowsInput,
2333
+): boolean {
2334
+ for (const key of Object.keys(right) as Array<keyof MessagesTimelineRowsInput>) {
2335
+ const previous = left[key];
2336
+ const next = right[key];
2337
+ if (Object.is(previous, next)) continue;
2338
+ if (previous instanceof Set && next instanceof Set && shallow(previous, next)) continue;
2339
+ return false;
2340
+ }
2341
+ return Object.keys(left).length === Object.keys(right).length;
2342
+}
apps/web/src/components/chat/MessagesTimeline.tsx
+20
-284
@@ -1,5 +1,4 @@
1
import { ThreadFindTimelineContext } from "./ThreadFindProvider";
2
-import { shallow } from "zustand/vanilla/shallow";
2
import { MarkdownFindContext } from "./markdownFindContext";
3
import { useChatCanvas } from "./ChatCanvasContext";
4
import { WorkLogBlock } from "./WorkLog";
@@ -60,9 +59,6 @@ import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection
59
import { type AssistantCitationRequest } from "./AssistantCitationSource";
60
import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
61
import {
63
- computeStableMessagesTimelineRows,
64
- deriveMessagesTimelineRowsWithState,
65
- type MessagesTimelineRowsProjection,
62
resolveTimelineIsAtEnd,
63
resolveTimelineMinimapHasPersistentGutter,
64
resolveTimelineMinimapCurrentIndex,
@@ -71,13 +67,11 @@ import {
67
resolveTimelineMinimapHitStripWidth,
68
timelineTurnFoldRunIdsByEntryId,
69
worktreeSetupAgentStarted,
74
- type StableMessagesTimelineRowsState,
70
type MessagesTimelineRow,
71
type TimelineLatestRun,
72
} from "./MessagesTimeline.logic";
73
import { type ThreadFindMatch } from "./threadFind";
74
import { useThreadFindNavigation } from "./useThreadFindNavigation";
80
-import { readThreadFindPosition } from "./threadFindPosition";
75
import type { ThreadFindPositionReader } from "./threadFind";
76
import { TooltipScrollDismissArea } from "../ui/tooltip";
77
import { WorktreeSetupCard } from "./WorktreeSetupCard";
@@ -116,6 +110,9 @@ import {
110
McpAppTimelineRow,
111
} from "./TimelineAssistantRows";
112
import { V2EventTimelineRow } from "./TimelineV2EventRow";
113
+import { useTimelinePositionRestore } from "./useTimelinePositionRestore";
114
+import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
115
+import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
116
117
function timelineListStateFor(identity: string): {
118
readonly identity: string;
@@ -163,7 +160,6 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END = {
160
layout: true,
161
},
162
} as const satisfies MaintainScrollAtEndOptions;
166
-const EMPTY_TIMELINE_RUNS: ReadonlyArray<HandoffTimelineRun> = [];
163
const EMPTY_RUN_IDS: ReadonlySet<RunId> = new Set();
164
const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = {
165
...TIMELINE_MAINTAIN_SCROLL_AT_END,
@@ -609,145 +605,23 @@ const ConversationTimeline = memo(function ConversationTimeline({
605
const runs = useStableHandoffRuns(runsProp);
606
const minimapItems = deriveTimelineMinimapItems(rows);
607
const minimapRowIndices = minimapItems.map((item) => item.rowIndex);
612
- // Preserve initialScrollAtEnd's measured target until the list is reused
613
- // for another thread; scrollToEnd would replace it with an estimated offset.
614
- const listOpenedOnRef = useRef<{
615
- readonly list: LegendListRef;
616
- identity: string | null;
617
- } | null>(null);
618
- useLayoutEffect(() => {
619
- const list = listRef.current;
620
- const opened = listOpenedOnRef.current;
621
- if (!list) return;
622
- if (opened?.list !== list) {
623
- listOpenedOnRef.current = { list, identity: listIdentityKey };
624
- } else if (opened.identity !== listIdentityKey) {
625
- opened.identity = null;
626
- }
627
- });
608
const restoreRowIndex =
609
restoringThreadPosition && rememberedPosition?.atEnd === false
610
? rows.findIndex((row) => row.id === rememberedPosition.rowId)
611
: -1;
612
const restoringAlwaysRender =
613
restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
634
- useLayoutEffect(() => {
635
- if (!restoringThreadPosition || rows.length === 0) return;
636
- const list = listRef.current;
637
- if (!list) return;
638
- if (citationRequest !== null) {
639
- // oxlint-disable-next-line react/set-state-in-effect -- The citation scroll owns positioning once the list has mounted.
640
- setPositionedThreadKey(listIdentityKey);
641
- return;
642
- }
643
- let cancelled = false;
644
- let settleFrame: number | null = null;
645
- const viewport: HTMLElement | null = list.getScrollableNode();
646
- const cancelRestoration = () => {
647
- if (cancelled) return;
648
- cancelled = true;
649
- if (settleFrame !== null) cancelAnimationFrame(settleFrame);
650
- if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
651
- setPositionedThreadKey(listIdentityKey);
652
- };
653
- const cancelForNavigation = () => {
654
- cancelRestoration();
655
- onManualNavigation();
656
- };
657
- const onScrollKey = (event: globalThis.KeyboardEvent) => {
658
- if (
659
- ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key) &&
660
- !(
661
- event.target instanceof Element &&
662
- event.target.closest("input, textarea, [contenteditable=true]")
663
- )
664
- )
665
- cancelForNavigation();
666
- };
667
- viewport?.addEventListener("wheel", cancelForNavigation, { passive: true });
668
- viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });
669
- viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });
670
- viewport?.ownerDocument.addEventListener("keydown", onScrollKey);
671
- const position = rememberedPosition;
672
- const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
673
- if (position?.atEnd === false) onManualNavigation();
674
- if (cancelPositionRestoreRef) cancelPositionRestoreRef.current = cancelRestoration;
675
- const scrolling =
676
- position?.atEnd === false
677
- ? index >= 0
678
- ? list.scrollToIndex({
679
- index,
680
- animated: false,
681
- viewPosition: 0,
682
- viewOffset: -position.offsetWithinRow,
683
- })
684
- : list.scrollToOffset({ offset: position.scrollOffset, animated: false })
685
- : listOpenedOnRef.current?.identity === listIdentityKey
686
- ? undefined
687
- : list.scrollToEnd({ animated: false });
688
- void Promise.resolve(scrolling).then(() => {
689
- if (cancelled) return;
690
- if (position?.atEnd !== false || index < 0) {
691
- setPositionedThreadKey(listIdentityKey);
692
- return;
693
- }
694
- // Index scrolling starts from estimates. Keep the saved row mounted
695
- // until its measured position and the DOM agree for two layout frames.
696
- let stableFrames = 0;
697
- const reconcile = () => {
698
- if (cancelled) return;
699
- const state = list.getState();
700
- const rowIndex = state.indexByKey(position.rowId);
701
- const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
702
- const element = list.getScrollableNode();
703
- if (!row || !element) return;
704
- const offset = Math.max(
705
- 0,
706
- Math.min(
707
- element.scrollTop +
708
- row.getBoundingClientRect().top -
709
- element.getBoundingClientRect().top +
710
- position.offsetWithinRow,
711
- element.scrollHeight - element.clientHeight,
712
- ),
713
- );
714
- if (Math.abs(element.scrollTop - offset) > 1) {
715
- stableFrames = 0;
716
- void list.scrollToOffset({ offset, animated: false }).then(() => {
717
- if (!cancelled) settleFrame = requestAnimationFrame(reconcile);
718
- });
719
- return;
720
- }
721
- stableFrames += 1;
722
- if (stableFrames >= 2) {
723
- setPositionedThreadKey(listIdentityKey);
724
- } else {
725
- settleFrame = requestAnimationFrame(reconcile);
726
- }
727
- };
728
- settleFrame = requestAnimationFrame(reconcile);
729
- });
730
- return () => {
731
- cancelled = true;
732
- if (cancelPositionRestoreRef?.current === cancelRestoration) {
733
- cancelPositionRestoreRef.current = null;
734
- }
735
- if (settleFrame !== null) cancelAnimationFrame(settleFrame);
736
- viewport?.removeEventListener("wheel", cancelForNavigation);
737
- viewport?.removeEventListener("touchmove", cancelForNavigation);
738
- viewport?.removeEventListener("pointerdown", cancelForNavigation);
739
- viewport?.ownerDocument.removeEventListener("keydown", onScrollKey);
740
- };
741
- }, [
742
- citationRequest,
743
- cancelPositionRestoreRef,
744
- listIdentityKey,
614
+ useTimelinePositionRestore({
615
listRef,
746
- onManualNavigation,
747
- rememberedPosition,
616
+ listIdentityKey,
617
restoringThreadPosition,
618
+ rememberedPosition,
619
rows,
750
- ]);
620
+ citationRequest,
621
+ cancelPositionRestoreRef,
622
+ onManualNavigation,
623
+ onPositioned: setPositionedThreadKey,
624
+ });
625
626
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
627
null,
@@ -1112,70 +986,18 @@ const ConversationTimeline = memo(function ConversationTimeline({
986
registerTimeline?.(list?.getScrollableNode() ?? null);
987
};
988
1115
- useLayoutEffect(() => {
1116
- if (!findPositionReaderRef || !timelineViewportElement) return;
1117
- const read: ThreadFindPositionReader = (query) => {
1118
- const foldRunIds =
1119
- findFoldRunIds ??
1120
- timelineTurnFoldRunIdsByEntryId({
1121
- timelineEntries,
1122
- latestRun,
1123
- runningRunId,
1124
- isWorking,
1125
- runlessWorkActive,
1126
- });
1127
- const entryById = new Map(timelineEntries.map((entry) => [entry.id, entry]));
1128
- return readThreadFindPosition(
1129
- timelineViewportElement,
1130
- query,
1131
- (rowId) => {
1132
- const rowIndex = rows.findIndex((row) => row.id === rowId);
1133
- for (const row of rows.slice(Math.max(0, rowIndex))) {
1134
- if (row.kind !== "turn-fold" && row.kind !== "attempt-fold") {
1135
- const entry = entryById.get(row.kind === "assistant-meta" ? row.message.id : row.id);
1136
- if (entry && (entry.kind === "message" || entry.kind === "proposed-plan"))
1137
- return entry.id;
1138
- continue;
1139
- }
1140
- const entry = timelineEntries.find((entry) => {
1141
- const runId =
1142
- row.kind === "turn-fold"
1143
- ? foldRunIds.get(entry.id)
1144
- : entry.kind === "message"
1145
- ? entry.message.runId
1146
- : entry.kind === "proposed-plan"
1147
- ? entry.proposedPlan.runId
1148
- : null;
1149
- return (
1150
- runId === row.runId &&
1151
- (entry.kind !== "message" || entry.message.role === "assistant") &&
1152
- (row.kind !== "attempt-fold" || entry.attempt?.id === row.attemptId)
1153
- );
1154
- });
1155
- if (entry && (entry.kind === "message" || entry.kind === "proposed-plan"))
1156
- return entry.id;
1157
- }
1158
- return undefined;
1159
- },
1160
- contentInsetEndAdjustment,
1161
- );
1162
- };
1163
- findPositionReaderRef.current = read;
1164
- return () => {
1165
- if (findPositionReaderRef.current === read) findPositionReaderRef.current = null;
1166
- };
1167
- }, [
1168
- contentInsetEndAdjustment,
1169
- findFoldRunIds,
989
+ useThreadFindPositionReader({
990
findPositionReaderRef,
1171
- isWorking,
991
+ timelineViewportElement,
992
+ findFoldRunIds,
993
+ timelineEntries,
994
latestRun,
1173
- rows,
1174
- runlessWorkActive,
995
runningRunId,
1176
- timelineEntries,
1177
- timelineViewportElement,
1178
- ]);
996
+ isWorking,
997
+ runlessWorkActive,
998
+ rows,
999
+ contentInsetEndAdjustment,
1000
+ });
1001
1002
useThreadFindNavigation({
1003
listReady: findListReady,
@@ -1556,89 +1378,3 @@ function AttemptFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "at
1378
</button>
1379
);
1380
}
1559
-
1560
-function handoffRunsSignature(runs: ReadonlyArray<HandoffTimelineRun>): string {
1561
- return runs
1562
- .map(
1563
- (run) =>
1564
- `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
1565
- )
1566
- .join("\n");
1567
-}
1568
-
1569
-function useStableHandoffRuns(
1570
- runs: ReadonlyArray<HandoffTimelineRun>,
1571
-): ReadonlyArray<HandoffTimelineRun> {
1572
- const [state, setState] = useState<{
1573
- readonly source: ReadonlyArray<HandoffTimelineRun> | null;
1574
- readonly signature: string;
1575
- readonly value: ReadonlyArray<HandoffTimelineRun>;
1576
- }>({ source: null, signature: "", value: EMPTY_TIMELINE_RUNS });
1577
- if (state.source === runs) return state.value;
1578
- const signature = handoffRunsSignature(runs);
1579
- const value =
1580
- signature === state.signature
1581
- ? state.value
1582
- : runs.map((run) => ({
1583
- id: run.id,
1584
- ordinal: run.ordinal,
1585
- providerInstanceId: run.providerInstanceId,
1586
- modelSelection: run.modelSelection,
1587
- }));
1588
- setState({ source: runs, signature, value });
1589
- return value;
1590
-}
1591
-
1592
-type MessagesTimelineRowsInput = MessagesTimelineRowsProjection["input"];
1593
-
1594
-// Expanded-id sets can be rebuilt during render; comparing them by content keeps
1595
-// the render-time state update below from repeating forever.
1596
-function sameRowsInput(left: MessagesTimelineRowsInput, right: MessagesTimelineRowsInput): boolean {
1597
- for (const key of Object.keys(right) as Array<keyof MessagesTimelineRowsInput>) {
1598
- const previous = left[key];
1599
- const next = right[key];
1600
- if (Object.is(previous, next)) continue;
1601
- if (previous instanceof Set && next instanceof Set && shallow(previous, next)) continue;
1602
- return false;
1603
- }
1604
- return Object.keys(left).length === Object.keys(right).length;
1605
-}
1606
-
1607
-/**
1608
- * Rows derived from the previous projection of the same list, so a streamed
1609
- * text update patches its message rows instead of deriving every row again.
1610
- */
1611
-function useIncrementalTimelineRows(
1612
- identity: string,
1613
- input: MessagesTimelineRowsInput,
1614
-): MessagesTimelineRow[] {
1615
- const [state, setState] = useState(() => ({
1616
- identity,
1617
- input,
1618
- projection: deriveMessagesTimelineRowsWithState(input),
1619
- }));
1620
- if (state.identity === identity && sameRowsInput(state.input, input)) {
1621
- return state.projection.rows;
1622
- }
1623
- const projection = deriveMessagesTimelineRowsWithState(
1624
- input,
1625
- state.identity === identity ? state.projection : null,
1626
- );
1627
- setState({ identity, input, projection });
1628
- return projection.rows;
1629
-}
1630
-
1631
-function useStableRows(rows: MessagesTimelineRow[], identity: string): MessagesTimelineRow[] {
1632
- const [state, setState] = useState<{
1633
- readonly identity: string;
1634
- readonly source: MessagesTimelineRow[] | null;
1635
- readonly stable: StableMessagesTimelineRowsState;
1636
- }>({ identity, source: null, stable: { byId: new Map(), result: [] } });
1637
- if (state.identity === identity && state.source === rows) return state.stable.result;
1638
- const stable = computeStableMessagesTimelineRows(
1639
- rows,
1640
- state.identity === identity ? state.stable : { byId: new Map(), result: [] },
1641
- );
1642
- setState({ identity, source: rows, stable });
1643
- return stable.result;
1644
-}
apps/web/src/components/chat/useThreadFindPositionReader.ts
new
+100
@@ -0,0 +1,100 @@
1
+import { useLayoutEffect } from "react";
2
+import type { RunId } from "@t3tools/contracts";
3
+import type { TimelineEntry } from "../../session-logic";
4
+import {
5
+ timelineTurnFoldRunIdsByEntryId,
6
+ type MessagesTimelineRow,
7
+ type TimelineLatestRun,
8
+} from "./MessagesTimeline.logic";
9
+import type { ThreadFindPositionReader } from "./threadFind";
10
+import { readThreadFindPosition } from "./threadFindPosition";
11
+
12
+/** Publishes how to read the find position of the timeline's current viewport. */
13
+export function useThreadFindPositionReader({
14
+ findPositionReaderRef,
15
+ timelineViewportElement,
16
+ findFoldRunIds,
17
+ timelineEntries,
18
+ latestRun,
19
+ runningRunId,
20
+ isWorking,
21
+ runlessWorkActive,
22
+ rows,
23
+ contentInsetEndAdjustment,
24
+}: {
25
+ readonly findPositionReaderRef: React.RefObject<ThreadFindPositionReader | null> | undefined;
26
+ readonly timelineViewportElement: HTMLDivElement | null;
27
+ readonly findFoldRunIds: ReadonlyMap<string, RunId> | null;
28
+ readonly timelineEntries: ReadonlyArray<TimelineEntry>;
29
+ readonly latestRun: TimelineLatestRun | null;
30
+ readonly runningRunId: RunId | null;
31
+ readonly isWorking: boolean;
32
+ readonly runlessWorkActive: boolean;
33
+ readonly rows: MessagesTimelineRow[];
34
+ readonly contentInsetEndAdjustment: number;
35
+}) {
36
+ useLayoutEffect(() => {
37
+ if (!findPositionReaderRef || !timelineViewportElement) return;
38
+ const read: ThreadFindPositionReader = (query) => {
39
+ const foldRunIds =
40
+ findFoldRunIds ??
41
+ timelineTurnFoldRunIdsByEntryId({
42
+ timelineEntries,
43
+ latestRun,
44
+ runningRunId,
45
+ isWorking,
46
+ runlessWorkActive,
47
+ });
48
+ const entryById = new Map(timelineEntries.map((entry) => [entry.id, entry]));
49
+ return readThreadFindPosition(
50
+ timelineViewportElement,
51
+ query,
52
+ (rowId) => {
53
+ const rowIndex = rows.findIndex((row) => row.id === rowId);
54
+ for (const row of rows.slice(Math.max(0, rowIndex))) {
55
+ if (row.kind !== "turn-fold" && row.kind !== "attempt-fold") {
56
+ const entry = entryById.get(row.kind === "assistant-meta" ? row.message.id : row.id);
57
+ if (entry && (entry.kind === "message" || entry.kind === "proposed-plan"))
58
+ return entry.id;
59
+ continue;
60
+ }
61
+ const entry = timelineEntries.find((entry) => {
62
+ const runId =
63
+ row.kind === "turn-fold"
64
+ ? foldRunIds.get(entry.id)
65
+ : entry.kind === "message"
66
+ ? entry.message.runId
67
+ : entry.kind === "proposed-plan"
68
+ ? entry.proposedPlan.runId
69
+ : null;
70
+ return (
71
+ runId === row.runId &&
72
+ (entry.kind !== "message" || entry.message.role === "assistant") &&
73
+ (row.kind !== "attempt-fold" || entry.attempt?.id === row.attemptId)
74
+ );
75
+ });
76
+ if (entry && (entry.kind === "message" || entry.kind === "proposed-plan"))
77
+ return entry.id;
78
+ }
79
+ return undefined;
80
+ },
81
+ contentInsetEndAdjustment,
82
+ );
83
+ };
84
+ findPositionReaderRef.current = read;
85
+ return () => {
86
+ if (findPositionReaderRef.current === read) findPositionReaderRef.current = null;
87
+ };
88
+ }, [
89
+ contentInsetEndAdjustment,
90
+ findFoldRunIds,
91
+ findPositionReaderRef,
92
+ isWorking,
93
+ latestRun,
94
+ rows,
95
+ runlessWorkActive,
96
+ runningRunId,
97
+ timelineEntries,
98
+ timelineViewportElement,
99
+ ]);
100
+}
apps/web/src/components/chat/useTimelinePositionRestore.ts
new
+166
@@ -0,0 +1,166 @@
1
+import { useLayoutEffect, useRef } from "react";
2
+import type { LegendListRef } from "@legendapp/list/react";
3
+import type { AssistantCitationRequest } from "./AssistantCitationSource";
4
+import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
5
+import type { RememberedTimelinePosition } from "./timelineScrollAnchoring";
6
+
7
+/**
8
+ * Scrolls a newly shown thread back to where the user left it, or to its end,
9
+ * and reports the thread positioned once the saved row settles.
10
+ */
11
+export function useTimelinePositionRestore({
12
+ listRef,
13
+ listIdentityKey,
14
+ restoringThreadPosition,
15
+ rememberedPosition,
16
+ rows,
17
+ citationRequest,
18
+ cancelPositionRestoreRef,
19
+ onManualNavigation,
20
+ onPositioned,
21
+}: {
22
+ readonly listRef: React.RefObject<LegendListRef | null>;
23
+ readonly listIdentityKey: string;
24
+ readonly restoringThreadPosition: boolean;
25
+ readonly rememberedPosition: RememberedTimelinePosition | undefined;
26
+ readonly rows: MessagesTimelineRow[];
27
+ readonly citationRequest: AssistantCitationRequest | null;
28
+ readonly cancelPositionRestoreRef: React.RefObject<(() => void) | null> | undefined;
29
+ readonly onManualNavigation: () => void;
30
+ readonly onPositioned: (identity: string) => void;
31
+}) {
32
+ // Preserve initialScrollAtEnd's measured target until the list is reused
33
+ // for another thread; scrollToEnd would replace it with an estimated offset.
34
+ const listOpenedOnRef = useRef<{
35
+ readonly list: LegendListRef;
36
+ identity: string | null;
37
+ } | null>(null);
38
+ useLayoutEffect(() => {
39
+ const list = listRef.current;
40
+ const opened = listOpenedOnRef.current;
41
+ if (!list) return;
42
+ if (opened?.list !== list) {
43
+ listOpenedOnRef.current = { list, identity: listIdentityKey };
44
+ } else if (opened.identity !== listIdentityKey) {
45
+ opened.identity = null;
46
+ }
47
+ });
48
+ useLayoutEffect(() => {
49
+ if (!restoringThreadPosition || rows.length === 0) return;
50
+ const list = listRef.current;
51
+ if (!list) return;
52
+ if (citationRequest !== null) {
53
+ // The citation scroll owns positioning once the list has mounted.
54
+ onPositioned(listIdentityKey);
55
+ return;
56
+ }
57
+ let cancelled = false;
58
+ let settleFrame: number | null = null;
59
+ const viewport: HTMLElement | null = list.getScrollableNode();
60
+ const cancelRestoration = () => {
61
+ if (cancelled) return;
62
+ cancelled = true;
63
+ if (settleFrame !== null) cancelAnimationFrame(settleFrame);
64
+ if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
65
+ onPositioned(listIdentityKey);
66
+ };
67
+ const cancelForNavigation = () => {
68
+ cancelRestoration();
69
+ onManualNavigation();
70
+ };
71
+ const onScrollKey = (event: globalThis.KeyboardEvent) => {
72
+ if (
73
+ ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key) &&
74
+ !(
75
+ event.target instanceof Element &&
76
+ event.target.closest("input, textarea, [contenteditable=true]")
77
+ )
78
+ )
79
+ cancelForNavigation();
80
+ };
81
+ viewport?.addEventListener("wheel", cancelForNavigation, { passive: true });
82
+ viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });
83
+ viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });
84
+ viewport?.ownerDocument.addEventListener("keydown", onScrollKey);
85
+ const position = rememberedPosition;
86
+ const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
87
+ if (position?.atEnd === false) onManualNavigation();
88
+ if (cancelPositionRestoreRef) cancelPositionRestoreRef.current = cancelRestoration;
89
+ const scrolling =
90
+ position?.atEnd === false
91
+ ? index >= 0
92
+ ? list.scrollToIndex({
93
+ index,
94
+ animated: false,
95
+ viewPosition: 0,
96
+ viewOffset: -position.offsetWithinRow,
97
+ })
98
+ : list.scrollToOffset({ offset: position.scrollOffset, animated: false })
99
+ : listOpenedOnRef.current?.identity === listIdentityKey
100
+ ? undefined
101
+ : list.scrollToEnd({ animated: false });
102
+ void Promise.resolve(scrolling).then(() => {
103
+ if (cancelled) return;
104
+ if (position?.atEnd !== false || index < 0) {
105
+ onPositioned(listIdentityKey);
106
+ return;
107
+ }
108
+ // Index scrolling starts from estimates. Keep the saved row mounted
109
+ // until its measured position and the DOM agree for two layout frames.
110
+ let stableFrames = 0;
111
+ const reconcile = () => {
112
+ if (cancelled) return;
113
+ const state = list.getState();
114
+ const rowIndex = state.indexByKey(position.rowId);
115
+ const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
116
+ const element = list.getScrollableNode();
117
+ if (!row || !element) return;
118
+ const offset = Math.max(
119
+ 0,
120
+ Math.min(
121
+ element.scrollTop +
122
+ row.getBoundingClientRect().top -
123
+ element.getBoundingClientRect().top +
124
+ position.offsetWithinRow,
125
+ element.scrollHeight - element.clientHeight,
126
+ ),
127
+ );
128
+ if (Math.abs(element.scrollTop - offset) > 1) {
129
+ stableFrames = 0;
130
+ void list.scrollToOffset({ offset, animated: false }).then(() => {
131
+ if (!cancelled) settleFrame = requestAnimationFrame(reconcile);
132
+ });
133
+ return;
134
+ }
135
+ stableFrames += 1;
136
+ if (stableFrames >= 2) {
137
+ onPositioned(listIdentityKey);
138
+ } else {
139
+ settleFrame = requestAnimationFrame(reconcile);
140
+ }
141
+ };
142
+ settleFrame = requestAnimationFrame(reconcile);
143
+ });
144
+ return () => {
145
+ cancelled = true;
146
+ if (cancelPositionRestoreRef?.current === cancelRestoration) {
147
+ cancelPositionRestoreRef.current = null;
148
+ }
149
+ if (settleFrame !== null) cancelAnimationFrame(settleFrame);
150
+ viewport?.removeEventListener("wheel", cancelForNavigation);
151
+ viewport?.removeEventListener("touchmove", cancelForNavigation);
152
+ viewport?.removeEventListener("pointerdown", cancelForNavigation);
153
+ viewport?.ownerDocument.removeEventListener("keydown", onScrollKey);
154
+ };
155
+ }, [
156
+ citationRequest,
157
+ cancelPositionRestoreRef,
158
+ listIdentityKey,
159
+ listRef,
160
+ onManualNavigation,
161
+ onPositioned,
162
+ rememberedPosition,
163
+ restoringThreadPosition,
164
+ rows,
165
+ ]);
166
+}
apps/web/src/components/chat/useTimelineRows.ts
new
+78
@@ -0,0 +1,78 @@
1
+import { useState } from "react";
2
+import {
3
+ computeStableMessagesTimelineRows,
4
+ handoffRunsSignature,
5
+ type MessagesTimelineRowsInput,
6
+ sameRowsInput,
7
+ deriveMessagesTimelineRowsWithState,
8
+ type StableMessagesTimelineRowsState,
9
+ type MessagesTimelineRow,
10
+} from "./MessagesTimeline.logic";
11
+import { type HandoffTimelineRun } from "./V2LifecycleRow";
12
+
13
+const EMPTY_TIMELINE_RUNS: ReadonlyArray<HandoffTimelineRun> = [];
14
+
15
+export function useStableHandoffRuns(
16
+ runs: ReadonlyArray<HandoffTimelineRun>,
17
+): ReadonlyArray<HandoffTimelineRun> {
18
+ const [state, setState] = useState<{
19
+ readonly source: ReadonlyArray<HandoffTimelineRun> | null;
20
+ readonly signature: string;
21
+ readonly value: ReadonlyArray<HandoffTimelineRun>;
22
+ }>({ source: null, signature: "", value: EMPTY_TIMELINE_RUNS });
23
+ if (state.source === runs) return state.value;
24
+ const signature = handoffRunsSignature(runs);
25
+ const value =
26
+ signature === state.signature
27
+ ? state.value
28
+ : runs.map((run) => ({
29
+ id: run.id,
30
+ ordinal: run.ordinal,
31
+ providerInstanceId: run.providerInstanceId,
32
+ modelSelection: run.modelSelection,
33
+ }));
34
+ setState({ source: runs, signature, value });
35
+ return value;
36
+}
37
+
38
+/**
39
+ * Rows derived from the previous projection of the same list, so a streamed
40
+ * text update patches its message rows instead of deriving every row again.
41
+ */
42
+export function useIncrementalTimelineRows(
43
+ identity: string,
44
+ input: MessagesTimelineRowsInput,
45
+): MessagesTimelineRow[] {
46
+ const [state, setState] = useState(() => ({
47
+ identity,
48
+ input,
49
+ projection: deriveMessagesTimelineRowsWithState(input),
50
+ }));
51
+ if (state.identity === identity && sameRowsInput(state.input, input)) {
52
+ return state.projection.rows;
53
+ }
54
+ const projection = deriveMessagesTimelineRowsWithState(
55
+ input,
56
+ state.identity === identity ? state.projection : null,
57
+ );
58
+ setState({ identity, input, projection });
59
+ return projection.rows;
60
+}
61
+
62
+export function useStableRows(
63
+ rows: MessagesTimelineRow[],
64
+ identity: string,
65
+): MessagesTimelineRow[] {
66
+ const [state, setState] = useState<{
67
+ readonly identity: string;
68
+ readonly source: MessagesTimelineRow[] | null;
69
+ readonly stable: StableMessagesTimelineRowsState;
70
+ }>({ identity, source: null, stable: { byId: new Map(), result: [] } });
71
+ if (state.identity === identity && state.source === rows) return state.stable.result;
72
+ const stable = computeStableMessagesTimelineRows(
73
+ rows,
74
+ state.identity === identity ? state.stable : { byId: new Map(), result: [] },
75
+ );
76
+ setState({ identity, source: rows, stable });
77
+ return stable.result;
78
+}