Open History to see the last commit
1import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
2
3import type { OrchestrationThreadActivity } from "@t3tools/contracts";
4
5import { liveWindowOldestActivityId, oldestActivityByChronology } from "./threadReducer.ts";
6
7const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
8
9/**
10 * Pagination cursor for a thread's older activities. Sequenced rows page by
11 * `beforeSequence`; legacy/unsequenced rows (the common case — `sequence` is
12 * absent on most real rows) page by the `(createdAt, activityId)` keyset.
13 */
14export type OlderActivitiesCursor =
15 | { readonly beforeSequence: number }
16 | {
17 readonly beforeCreatedAt: OrchestrationThreadActivity["createdAt"];
18 readonly beforeActivityId: OrchestrationThreadActivity["id"];
19 };
20
21export interface OlderActivitiesPage {
22 readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
23 readonly hasMore: boolean;
24}
25
26export interface UseOlderThreadActivitiesOptions {
27 /**
28 * Identity of the thread the live window belongs to (e.g.
29 * `${environmentId}\0${threadId}`); null when no thread is selected.
30 * Changing it resets the lazy-loaded pages.
31 */
32 readonly threadKey: string | null;
33 /** The server-windowed live activity set from the thread detail. */
34 readonly liveActivities: ReadonlyArray<OrchestrationThreadActivity>;
35 /** The server's `hasMoreActivities` flag from the detail snapshot. */
36 readonly hasMoreLiveActivities: boolean;
37 /**
38 * Fetch the page immediately older than the cursor. Resolve `null` to skip
39 * the page silently (a failure the caller already surfaced, or an
40 * interrupted command) — `hasMore` is left true so the user can retry.
41 * MUST be referentially stable (useCallback) for the load callback to be.
42 */
43 readonly loadPage: (cursor: OlderActivitiesCursor) => Promise<OlderActivitiesPage | null>;
44}
45
46export interface UseOlderThreadActivitiesResult {
47 /** Lazy-loaded older pages + the live window, oldest first. */
48 readonly mergedActivities: ReadonlyArray<OrchestrationThreadActivity>;
49 /** Whether older history exists beyond everything loaded. */
50 readonly hasMoreOlder: boolean;
51 readonly loadingOlder: boolean;
52 /** Dispatch a load of the next older page (no-op while one is in flight). */
53 readonly loadOlder: () => void;
54}
55
56// ── Pure decision kernel (exported for unit tests) ──────────────────────────
57
58export interface LiveWindowShape {
59 readonly key: string | null;
60 /** Chronological-oldest activity id (an identity sentinel, not a lookup key). */
61 readonly oldest: string | null;
62 readonly count: number;
63}
64
65/**
66 * Whether the live window was RESHAPED rather than purely appended-to: a
67 * different thread, a re-snapshot (reconnect) that changes the window's
68 * chronological-oldest row, or a checkpoint revert that shrinks it. A pure
69 * append (same thread, same oldest, count not smaller) is NOT a reshape.
70 */
71export function didLiveWindowReshape(previous: LiveWindowShape, next: LiveWindowShape): boolean {
72 return (
73 next.key !== previous.key || next.oldest !== previous.oldest || next.count < previous.count
74 );
75}
76
77/**
78 * The cursor for the page immediately older than `oldest`: sequenced rows page
79 * by `beforeSequence`; unsequenced rows (the common case) by the
80 * `(createdAt, activityId)` keyset.
81 */
82export function olderActivitiesCursorFor(
83 oldest: OrchestrationThreadActivity,
84): OlderActivitiesCursor {
85 return oldest.sequence !== undefined
86 ? { beforeSequence: oldest.sequence }
87 : { beforeCreatedAt: oldest.createdAt, beforeActivityId: oldest.id };
88}
89
90/**
91 * The row the NEXT load should cursor from: the explicit cursor row already
92 * paged past when one exists (so an all-overlap page keeps advancing), else
93 * the chronologically-oldest loaded row — never index 0, which the reducer
94 * can fill with a newer row (unsequenced rows sort to the end).
95 */
96export function nextOlderActivitiesCursorRow(
97 pagedPast: OrchestrationThreadActivity | null,
98 merged: ReadonlyArray<OrchestrationThreadActivity>,
99): OrchestrationThreadActivity | null {
100 return pagedPast ?? oldestActivityByChronology(merged);
101}
102
103/**
104 * The page rows not already present in the loaded set (older pages + live
105 * window) — boundary overlap and mid-flight appends must never produce
106 * duplicate ids in the merged timeline.
107 */
108export function freshOlderActivities(
109 page: OlderActivitiesPage,
110 merged: ReadonlyArray<OrchestrationThreadActivity>,
111): ReadonlyArray<OrchestrationThreadActivity> {
112 const seen = new Set(merged.map((activity) => activity.id));
113 return page.activities.filter((activity) => !seen.has(activity.id));
114}
115
116/**
117 * The older-history lazy-load engine, shared by every client (web ChatView,
118 * the mobile composer, the TUI ChatView). The thread-detail snapshot windows
119 * activities to the most recent page; older pages are fetched on demand and
120 * prepended.
121 *
122 * One implementation holds all the hardening the per-client copies kept
123 * drifting on:
124 * - reset on live-window RESHAPE, not just thread switch: a reconnect
125 * re-snapshot changes the window's chronological-oldest row and a checkpoint
126 * revert shrinks it, but a plain append does neither (the reducer re-sorts
127 * unsequenced rows, so index 0 is not a stable boundary — the sentinel is
128 * {@link liveWindowOldestActivityId});
129 * - a generation guard so a load resolving after a reset can't repopulate the
130 * cleared state;
131 * - a synchronous in-flight key so scroll-triggered duplicate dispatches
132 * coalesce before the loading state commits;
133 * - an explicit advancing cursor (the oldest row paged PAST), so an
134 * all-overlap page keeps paging instead of dead-ending while the server
135 * still reports more — the server cursor is strict, so it strictly
136 * decreases and paging cannot loop;
137 * - dedup against the LATEST merged set via a ref, so a live append or a
138 * prior prepend settling mid-flight can't produce duplicate ids;
139 * - `hasMore` stays true on a failed/skipped page (the history still exists;
140 * scrolling back retries).
141 */
142export function useOlderThreadActivities(
143 options: UseOlderThreadActivitiesOptions,
144): UseOlderThreadActivitiesResult {
145 const { threadKey, liveActivities, hasMoreLiveActivities, loadPage } = options;
146
147 const [olderActivities, setOlderActivities] = useState<
148 ReadonlyArray<OrchestrationThreadActivity>
149 >([]);
150 const [olderLoaded, setOlderLoaded] = useState(false);
151 const [olderHasMore, setOlderHasMore] = useState(false);
152 const [loadingOlder, setLoadingOlder] = useState(false);
153
154 // Order-independent oldest boundary: `liveActivities[0]` shifts when the
155 // reducer re-sorts unsequenced rows on the first live append, which would
156 // otherwise make a plain append look like a window reshape.
157 const liveOldestActivityId = useMemo(
158 () => liveWindowOldestActivityId(liveActivities),
159 [liveActivities],
160 );
161 const liveActivityCount = liveActivities.length;
162
163 // Bumps on every reset so a late in-flight load can't repopulate the
164 // freshly-cleared state (the thread key alone doesn't change on a
165 // same-thread window reshape).
166 const generationRef = useRef(0);
167 // The thread key of an in-flight load — coalesces the duplicate dispatches a
168 // fast scroll fires before the loading state updates.
169 const inFlightKeyRef = useRef<string | null>(null);
170 // The oldest row we've paged past; advances even when a page dedupes to
171 // nothing. Reset on reshape.
172 const cursorRef = useRef<OrchestrationThreadActivity | null>(null);
173 const windowRef = useRef({
174 key: threadKey,
175 oldest: liveOldestActivityId,
176 count: liveActivityCount,
177 });
178
179 // useLayoutEffect (not useEffect) so the cleared state commits before paint:
180 // otherwise a thread switch renders one frame with the previous thread's
181 // lazy-loaded pages still merged in, flashing stale rows.
182 useLayoutEffect(() => {
183 const previous = windowRef.current;
184 windowRef.current = {
185 key: threadKey,
186 oldest: liveOldestActivityId,
187 count: liveActivityCount,
188 };
189 if (!didLiveWindowReshape(previous, windowRef.current)) {
190 return;
191 }
192 generationRef.current += 1;
193 inFlightKeyRef.current = null;
194 cursorRef.current = null;
195 setOlderActivities([]);
196 setOlderLoaded(false);
197 setOlderHasMore(false);
198 setLoadingOlder(false);
199 }, [threadKey, liveOldestActivityId, liveActivityCount]);
200
201 const mergedActivities = useMemo(
202 () => (olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities),
203 [olderActivities, liveActivities],
204 );
205 // Latest merged set, read inside the async load handler so dedup runs
206 // against current state, not the snapshot captured at dispatch time.
207 const mergedActivitiesRef = useRef(mergedActivities);
208 useLayoutEffect(() => {
209 mergedActivitiesRef.current = mergedActivities;
210 }, [mergedActivities]);
211
212 // Before any page is loaded the server flag is authoritative; afterwards
213 // the latest page's `hasMore` is.
214 const hasMoreOlder = olderLoaded ? olderHasMore : threadKey !== null && hasMoreLiveActivities;
215
216 const loadOlder = useCallback(() => {
217 if (threadKey === null || !hasMoreOlder) {
218 return;
219 }
220 const oldest = nextOlderActivitiesCursorRow(cursorRef.current, mergedActivitiesRef.current);
221 if (!oldest) {
222 return;
223 }
224 if (inFlightKeyRef.current === threadKey) {
225 return; // a load for this thread is already in flight
226 }
227 const cursor = olderActivitiesCursorFor(oldest);
228 const generation = generationRef.current;
229 inFlightKeyRef.current = threadKey;
230 setLoadingOlder(true);
231 void loadPage(cursor)
232 .then((page) => {
233 // The window/thread was reset while this was in flight — drop the page
234 // so it can't repopulate state cleared by the reset.
235 if (generationRef.current !== generation) {
236 return;
237 }
238 if (page === null) {
239 // Failed or interrupted (already surfaced by the caller). Keep
240 // `hasMore` — the history still exists and retrying is valid.
241 return;
242 }
243 // Advance the cursor even when every row dedupes away — the server
244 // cursor is strict, so it strictly decreases and paging can't loop.
245 const pageOldest = page.activities[0];
246 if (pageOldest) {
247 cursorRef.current = pageOldest;
248 }
249 const fresh = freshOlderActivities(page, mergedActivitiesRef.current);
250 if (fresh.length > 0) {
251 setOlderActivities((previous) => [...fresh, ...previous]);
252 }
253 setOlderLoaded(true);
254 setOlderHasMore(page.hasMore);
255 })
256 .finally(() => {
257 if (generationRef.current === generation) {
258 inFlightKeyRef.current = null;
259 setLoadingOlder(false);
260 }
261 });
262 }, [threadKey, hasMoreOlder, loadPage]);
263
264 return {
265 mergedActivities: threadKey === null ? EMPTY_ACTIVITIES : mergedActivities,
266 hasMoreOlder,
267 loadingOlder,
268 loadOlder,
269 };
270}