refactor(client): extract the shared older-history lazy-load engine

The lazy-load state machine (~160 lines each) was hand-copied in the web
ChatView and the mobile composer, and every review-round fix had to be
applied to both — half the review churn on this PR was the copies drifting.

One shared hook, `useOlderThreadActivities` in client-runtime, now owns all
of the hardened behavior: reshape-sentinel reset, generation guard,
synchronous in-flight coalescing, the advancing cursor (all-overlap pages
keep paging), dedup against the latest merged set, and hasMore-preserving
failure handling. Clients pass a `loadPage` transport wrapper and keep only
their platform scroll trigger and error surfacing.

The decision kernel (reshape detection, cursor selection, page dedup) is
exported as pure functions with unit tests; react becomes an optional peer
dependency of client-runtime, scoped to the new subpath.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
olafuraandClaude Opus 4.8 authored and Julius Marminge committed 2026-07-20 17:27:49 +02:00
1 parent 5e805ec7f8
commit a279bca0f8
7 files changed
+384 -316

No files matched your search

@@ -1781,7 +1781,26 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}}
/>
</View>
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
{props.feed.length === 0 && hasMoreOlder ? (
// The window can derive zero visible entries while older history
// exists — without scrollable content `onStartReached` can never
// fire, so give the user an explicit affordance instead of the
// empty-state placeholder.
<View style={StyleSheet.absoluteFill}>
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
{loadingOlder ? (
<ActivityIndicator />
) : (
<TouchableOpacity accessibilityRole="button" onPress={() => onLoadOlder?.()}>
<Text className="text-sm text-muted-foreground">Load older history</Text>
</TouchableOpacity>
)}
</View>
</View>
) : null}
{props.feed.length === 0 &&
!hasMoreOlder &&
props.contentPresentation.kind === "ready" ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
<ThreadFeedPlaceholder
title="No conversation yet"
@@ -92,12 +92,15 @@ export function useSelectedThreadRequests(
() => (requestActivities ? derivePendingApprovals(requestActivities) : []),
[requestActivities],
);
const activePendingApproval = activePendingApprovals[0] ?? null;
// The derivations sort ascending by createdAt; surface the NEWEST open
// request. With lazy-loaded older pages in the set, index 0 could be an
// ancient dangling request hijacking the prompt for the current one.
const activePendingApproval = activePendingApprovals.at(-1) ?? null;
const activePendingUserInputs = useMemo(
() => (requestActivities ? derivePendingUserInputs(requestActivities) : []),
[requestActivities],
);
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInput = activePendingUserInputs.at(-1) ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedThreadShell
? (userInputDraftsByRequestKey[
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
CommandId,
@@ -14,9 +14,9 @@ import {
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import {
liveWindowOldestActivityId,
oldestActivityByChronology,
} from "@t3tools/client-runtime/state/thread-reducer";
useOlderThreadActivities,
type OlderActivitiesCursor,
} from "@t3tools/client-runtime/state/older-thread-activities";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
@@ -100,167 +100,49 @@ export function useThreadComposerState() {
[queuedMessagesByThreadKey, selectedThreadKey],
);
// ── Older-history lazy-load (mirrors web ChatView) ──────────────────────────
// ── Older-history lazy-load (shared engine; see useOlderThreadActivities) ──
// The detail snapshot windows activities to the most recent page (the server
// sets `hasMoreActivities`); older pages are fetched on demand and prepended.
const [olderActivities, setOlderActivities] = useState<
ReadonlyArray<OrchestrationThreadActivity>
>([]);
const [olderLoaded, setOlderLoaded] = useState(false);
const [olderHasMore, setOlderHasMore] = useState(false);
const [loadingOlderActivities, setLoadingOlderActivities] = useState(false);
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
reportFailure: false,
});
const activityRequestKey = selectedThreadShell
? `${selectedThreadShell.environmentId}\u0000${selectedThreadShell.id}`
: null;
const liveActivities = selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES;
// Order-independent oldest boundary: `activities[0]` shifts when the reducer
// re-sorts unsequenced rows on the first live append, which would otherwise
// make a plain append look like a window reshape. See helper docs.
const liveOldestActivityId = useMemo(
() => liveWindowOldestActivityId(liveActivities),
[liveActivities],
);
const liveActivityCount = liveActivities.length;
// Bumps on every lazy-load reset so a late in-flight load can't repopulate the
// freshly-cleared state (the thread key alone doesn't change on a same-thread
// window reshape).
const olderActivitiesGenRef = useRef(0);
// The request key of an in-flight older-history load — coalesces the duplicate
// dispatches the list fires before the loading state updates.
const inFlightOlderKeyRef = useRef<string | null>(null);
// The oldest row we've paged past. Advancing this (not re-deriving from the
// merged set) lets an all-overlap page keep paging when the server still
// reports `hasMore`, without re-requesting the same cursor. Reset on reshape.
const olderCursorRef = useRef<OrchestrationThreadActivity | null>(null);
// Reset the lazy-loaded older pages when the live window is *reshaped* rather
// than purely appended-to: a different thread or a re-snapshot (reconnect)
// changes its oldest row, and a checkpoint revert removes rows so the count
// shrinks. A pure append (same thread, same oldest, larger count) keeps them.
const olderWindowRef = useRef({
key: activityRequestKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
});
// useLayoutEffect (not useEffect) so the cleared state commits before the new
// thread paints; otherwise the previous thread's lazy-loaded pages stay merged
// in for one frame, flashing stale feed rows.
useLayoutEffect(() => {
const prev = olderWindowRef.current;
olderWindowRef.current = {
key: activityRequestKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
};
const reshaped =
activityRequestKey !== prev.key ||
liveOldestActivityId !== prev.oldest ||
liveActivityCount < prev.count;
if (!reshaped) {
return;
}
olderActivitiesGenRef.current += 1;
inFlightOlderKeyRef.current = null;
olderCursorRef.current = null;
setOlderActivities([]);
setOlderLoaded(false);
setOlderHasMore(false);
setLoadingOlderActivities(false);
}, [activityRequestKey, liveOldestActivityId, liveActivityCount]);
const mergedActivities = useMemo(
() =>
olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities,
[olderActivities, liveActivities],
);
// Latest merged set, read inside the async load handler so dedup runs against
// the current state, not the snapshot captured when the load was dispatched.
const mergedActivitiesRef = useRef(mergedActivities);
mergedActivitiesRef.current = mergedActivities;
// Before any page is loaded, the server tells us whether older history exists.
const hasMoreOlderActivities = olderLoaded
? olderHasMore
: (selectedThreadDetail?.hasMoreActivities ?? false);
const onLoadOlderActivities = useCallback(() => {
if (!selectedThreadShell || !hasMoreOlderActivities) {
return;
}
// Page from the explicit cursor (oldest row already paged past) or, before
// any page, the chronologically-oldest loaded row (matches the reshape
// sentinel): the reducer sorts unsequenced rows to the end, so index 0 can be
// a newer sequenced row whose cursor would skip older unsequenced history.
const oldestActivity = olderCursorRef.current ?? oldestActivityByChronology(mergedActivities);
if (!oldestActivity || !activityRequestKey) {
return;
}
if (inFlightOlderKeyRef.current === activityRequestKey) {
return;
}
const cursorInput =
oldestActivity.sequence !== undefined
? { beforeSequence: oldestActivity.sequence }
: { beforeCreatedAt: oldestActivity.createdAt, beforeActivityId: oldestActivity.id };
const requestKey = activityRequestKey;
const gen = olderActivitiesGenRef.current;
inFlightOlderKeyRef.current = requestKey;
setLoadingOlderActivities(true);
void loadThreadActivities({
environmentId: selectedThreadShell.environmentId,
input: { threadId: selectedThreadShell.id, ...cursorInput },
})
.then((result) => {
// Window/thread reset while in flight — drop the page so it can't
// repopulate state cleared by the reset.
if (olderActivitiesGenRef.current !== gen) {
return;
}
if (result._tag !== "Success") {
// Keep `hasMore` true — the history still exists and scrolling back to
// the top retries — but tell the user the fetch failed rather than
// silently showing a spinner that quietly gave up.
if (!isAtomCommandInterrupted(result)) {
setPendingConnectionError("Could not load older thread history.");
}
return;
}
const page = result.value;
// Advance the cursor to this page's oldest row (pages are ascending) even
// if every row dedupes away — the server cursor is strict, so the cursor
// strictly decreases and paging can't loop, while an all-overlap page no
// longer terminates paging the server says has more.
const pageOldest = page.activities[0];
if (pageOldest) {
olderCursorRef.current = pageOldest;
}
// Dedup against the LATEST merged set (via ref) so a live append or a
// prior prepend that settled mid-flight can't leave duplicate ids.
const seen = new Set(mergedActivitiesRef.current.map((activity) => activity.id));
const fresh = page.activities.filter((activity) => !seen.has(activity.id));
if (fresh.length === 0) {
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
return;
}
setOlderActivities((prev) => [...fresh, ...prev]);
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
})
.finally(() => {
if (olderActivitiesGenRef.current === gen) {
inFlightOlderKeyRef.current = null;
setLoadingOlderActivities(false);
}
const selectedEnvironmentIdForActivities = selectedThreadShell?.environmentId ?? null;
const selectedThreadIdForActivities = selectedThreadShell?.id ?? null;
const loadOlderActivitiesPage = useCallback(
async (cursor: OlderActivitiesCursor) => {
if (selectedEnvironmentIdForActivities === null || selectedThreadIdForActivities === null) {
return null;
}
const result = await loadThreadActivities({
environmentId: selectedEnvironmentIdForActivities,
input: { threadId: selectedThreadIdForActivities, ...cursor },
});
}, [
selectedThreadShell,
hasMoreOlderActivities,
if (result._tag !== "Success") {
// Surface real failures (a spinner that quietly gives up reads as
// missing history); keep `hasMore` so scrolling back retries.
if (!isAtomCommandInterrupted(result)) {
setPendingConnectionError("Could not load older thread history.");
}
return null;
}
return result.value;
},
[selectedEnvironmentIdForActivities, selectedThreadIdForActivities, loadThreadActivities],
);
const {
mergedActivities,
activityRequestKey,
loadThreadActivities,
]);
hasMoreOlder: hasMoreOlderActivities,
loadingOlder: loadingOlderActivities,
loadOlder: onLoadOlderActivities,
} = useOlderThreadActivities({
threadKey: selectedThreadShell
? `${selectedThreadShell.environmentId}\u0000${selectedThreadShell.id}`
: null,
liveActivities: selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES,
hasMoreLiveActivities: selectedThreadDetail?.hasMoreActivities ?? false,
loadPage: loadOlderActivitiesPage,
});
const selectedThreadFeed = useMemo(
() =>
+34 -155
View File
@@ -64,9 +64,9 @@ import {
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
liveWindowOldestActivityId,
oldestActivityByChronology,
} from "@t3tools/client-runtime/state/thread-reducer";
useOlderThreadActivities,
type OlderActivitiesCursor,
} from "@t3tools/client-runtime/state/older-thread-activities";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { isElectron } from "../env";
@@ -1869,162 +1869,41 @@ function ChatViewContent(props: ChatViewProps) {
// ── Older-history lazy-load ────────────────────────────────────────────────
// The detail snapshot windows activities to the most recent page (the server
// sets `hasMoreActivities` when older ones exist); older pages are fetched on
// demand (infinite scroll-up) and prepended. Messages aren't windowed
// server-side, so this just back-fills the older tool activity.
const [olderActivities, setOlderActivities] = useState<
ReadonlyArray<OrchestrationThreadActivity>
>([]);
const [olderLoaded, setOlderLoaded] = useState(false);
const [olderHasMore, setOlderHasMore] = useState(false);
const [loadingOlderActivities, setLoadingOlderActivities] = useState(false);
// demand (infinite scroll-up) and prepended by the shared engine. Messages
// aren't windowed server-side, so this just back-fills the older tool
// activity.
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
reportFailure: false,
});
const activeThreadActivityRequestKey = activeThread
? `${activeThread.environmentId}\u0000${activeThread.id}`
: null;
const liveThreadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
// Order-independent oldest boundary: `activities[0]` shifts when the reducer
// re-sorts unsequenced rows on the first live append, which would otherwise
// make a plain append look like a window reshape. See helper docs.
const liveOldestActivityId = useMemo(
() => liveWindowOldestActivityId(liveThreadActivities),
[liveThreadActivities],
);
const liveActivityCount = liveThreadActivities.length;
// Bumps on every lazy-load reset so a late in-flight load can't repopulate the
// freshly-cleared state (the thread key alone doesn't change on a same-thread
// window reshape).
const olderActivitiesGenRef = useRef(0);
// The request key of an in-flight older-history load — coalesces the duplicate
// dispatches a fast scroll-to-top fires before the loading state updates.
const inFlightOlderKeyRef = useRef<string | null>(null);
// The oldest row we've paged past. Advancing this (not re-deriving from the
// merged set) lets an all-overlap page keep paging when the server still
// reports `hasMore` — without it a page that dedupes to nothing would either
// terminate paging early or re-request the same cursor forever. Reset on reshape.
const olderCursorRef = useRef<OrchestrationThreadActivity | null>(null);
// Reset the lazy-loaded older pages when the live window is *reshaped* rather
// than purely appended-to: a different thread or a re-snapshot (reconnect)
// changes its oldest row, and a checkpoint revert removes rows so the count
// shrinks. A pure append (same thread, same oldest, larger count) keeps them.
const olderWindowRef = useRef({
key: activeThreadActivityRequestKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
});
// useLayoutEffect (not useEffect) so the cleared state commits before paint:
// otherwise the new thread renders one frame with the previous thread's
// lazy-loaded pages still merged in, flashing stale work-log/approval rows.
useLayoutEffect(() => {
const prev = olderWindowRef.current;
olderWindowRef.current = {
key: activeThreadActivityRequestKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
};
const reshaped =
activeThreadActivityRequestKey !== prev.key ||
liveOldestActivityId !== prev.oldest ||
liveActivityCount < prev.count;
if (!reshaped) {
return;
}
olderActivitiesGenRef.current += 1;
inFlightOlderKeyRef.current = null;
olderCursorRef.current = null;
setOlderActivities([]);
setOlderLoaded(false);
setOlderHasMore(false);
setLoadingOlderActivities(false);
}, [activeThreadActivityRequestKey, liveOldestActivityId, liveActivityCount]);
const threadActivities = useMemo(
() =>
olderActivities.length > 0
? [...olderActivities, ...liveThreadActivities]
: liveThreadActivities,
[olderActivities, liveThreadActivities],
);
// Latest merged set, read inside the async load handler so dedup runs against
// the current state, not the snapshot captured when the load was dispatched.
const threadActivitiesRef = useRef(threadActivities);
threadActivitiesRef.current = threadActivities;
// Before any page is loaded, the server tells us whether older history exists
// beyond the windowed snapshot; afterwards the page `hasMore` is authoritative.
const hasMoreOlderActivities = olderLoaded
? olderHasMore
: (activeThread?.hasMoreActivities ?? false);
const loadOlderActivities = useCallback(() => {
if (!activeThread || !hasMoreOlderActivities) {
return;
}
// Page from the explicit cursor (the oldest row we've already paged past) or,
// before any page, the chronologically-oldest loaded row — not
// `threadActivities[0]`: the reducer sorts unsequenced rows to the end, so
// index 0 can be a newer sequenced row whose `beforeSequence` cursor would
// skip older unsequenced history. This matches the reshape sentinel.
const oldestActivity = olderCursorRef.current ?? oldestActivityByChronology(threadActivities);
if (!oldestActivity || !activeThreadActivityRequestKey) {
return;
}
if (inFlightOlderKeyRef.current === activeThreadActivityRequestKey) {
return; // a load for this thread is already in flight
}
const cursorInput =
oldestActivity.sequence !== undefined
? { beforeSequence: oldestActivity.sequence }
: { beforeCreatedAt: oldestActivity.createdAt, beforeActivityId: oldestActivity.id };
const requestKey = activeThreadActivityRequestKey;
const gen = olderActivitiesGenRef.current;
inFlightOlderKeyRef.current = requestKey;
setLoadingOlderActivities(true);
void loadThreadActivities({
environmentId: activeThread.environmentId,
input: { threadId: activeThread.id, ...cursorInput },
})
.then((result) => {
// The window/thread was reset while this was in flight — drop the page
// so it can't repopulate state cleared by the reset.
if (olderActivitiesGenRef.current !== gen) {
return;
}
if (result._tag !== "Success") {
return;
}
const page = result.value;
// Advance the cursor to this page's oldest row (pages are ascending, so
// [0] is oldest) even if every row dedupes away — the server cursor is
// strict, so the cursor strictly decreases and paging can't loop, while
// an all-overlap page no longer terminates paging that the server says
// has more.
const pageOldest = page.activities[0];
if (pageOldest) {
olderCursorRef.current = pageOldest;
}
// Dedup against the LATEST merged set (via ref) so a live append or a
// prior prepend that settled mid-flight can't leave duplicate ids.
const seen = new Set(threadActivitiesRef.current.map((activity) => activity.id));
const fresh = page.activities.filter((activity) => !seen.has(activity.id));
if (fresh.length > 0) {
setOlderActivities((prev) => [...fresh, ...prev]);
}
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
})
.finally(() => {
if (olderActivitiesGenRef.current === gen) {
inFlightOlderKeyRef.current = null;
setLoadingOlderActivities(false);
}
const activeThreadEnvironmentIdForActivities = activeThread?.environmentId ?? null;
const activeThreadIdForActivities = activeThread?.id ?? null;
const loadOlderActivitiesPage = useCallback(
async (cursor: OlderActivitiesCursor) => {
if (activeThreadEnvironmentIdForActivities === null || activeThreadIdForActivities === null) {
return null;
}
const result = await loadThreadActivities({
environmentId: activeThreadEnvironmentIdForActivities,
input: { threadId: activeThreadIdForActivities, ...cursor },
});
}, [
activeThread,
activeThreadActivityRequestKey,
hasMoreOlderActivities,
threadActivities,
loadThreadActivities,
]);
// Failures stay silent on web (the "Load older history" affordance itself
// is the retry surface); returning null keeps `hasMore` for the retry.
return result._tag === "Success" ? result.value : null;
},
[activeThreadEnvironmentIdForActivities, activeThreadIdForActivities, loadThreadActivities],
);
const {
mergedActivities: threadActivities,
hasMoreOlder: hasMoreOlderActivities,
loadingOlder: loadingOlderActivities,
loadOlder: loadOlderActivities,
} = useOlderThreadActivities({
threadKey: activeThread ? `${activeThread.environmentId}\u0000${activeThread.id}` : null,
liveActivities: activeThread?.activities ?? EMPTY_ACTIVITIES,
hasMoreLiveActivities: activeThread?.hasMoreActivities ?? false,
loadPage: loadOlderActivitiesPage,
});
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const pendingApprovals = useMemo(
+14
View File
@@ -127,6 +127,10 @@
"types": "./src/state/threadReducer.ts",
"default": "./src/state/threadReducer.ts"
},
"./state/older-thread-activities": {
"types": "./src/state/olderThreadActivities.ts",
"default": "./src/state/olderThreadActivities.ts"
},
"./state/thread-sort": {
"types": "./src/state/threadSort.ts",
"default": "./src/state/threadSort.ts"
@@ -145,8 +149,18 @@
"@t3tools/shared": "workspace:*",
"effect": "catalog:"
},
"peerDependencies": {
"react": "^19.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/react": "~19.2.14",
"react": "19.2.6",
"vite-plus": "catalog:"
}
}
@@ -0,0 +1,271 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
import { liveWindowOldestActivityId, oldestActivityByChronology } from "./threadReducer.ts";
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
/**
* Pagination cursor for a thread's older activities. Sequenced rows page by
* `beforeSequence`; legacy/unsequenced rows (the common case — `sequence` is
* absent on most real rows) page by the `(createdAt, activityId)` keyset.
*/
export type OlderActivitiesCursor =
| { readonly beforeSequence: number }
| {
readonly beforeCreatedAt: OrchestrationThreadActivity["createdAt"];
readonly beforeActivityId: OrchestrationThreadActivity["id"];
};
export interface OlderActivitiesPage {
readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
readonly hasMore: boolean;
}
export interface UseOlderThreadActivitiesOptions {
/**
* Identity of the thread the live window belongs to (e.g.
* `${environmentId}\0${threadId}`); null when no thread is selected.
* Changing it resets the lazy-loaded pages.
*/
readonly threadKey: string | null;
/** The server-windowed live activity set from the thread detail. */
readonly liveActivities: ReadonlyArray<OrchestrationThreadActivity>;
/** The server's `hasMoreActivities` flag from the detail snapshot. */
readonly hasMoreLiveActivities: boolean;
/**
* Fetch the page immediately older than the cursor. Resolve `null` to skip
* the page silently (a failure the caller already surfaced, or an
* interrupted command) — `hasMore` is left true so the user can retry.
* MUST be referentially stable (useCallback) for the load callback to be.
*/
readonly loadPage: (cursor: OlderActivitiesCursor) => Promise<OlderActivitiesPage | null>;
}
export interface UseOlderThreadActivitiesResult {
/** Lazy-loaded older pages + the live window, oldest first. */
readonly mergedActivities: ReadonlyArray<OrchestrationThreadActivity>;
/** Whether older history exists beyond everything loaded. */
readonly hasMoreOlder: boolean;
readonly loadingOlder: boolean;
/** Dispatch a load of the next older page (no-op while one is in flight). */
readonly loadOlder: () => void;
}
// ── Pure decision kernel (exported for unit tests) ──────────────────────────
export interface LiveWindowShape {
readonly key: string | null;
/** Chronological-oldest activity id (an identity sentinel, not a lookup key). */
readonly oldest: string | null;
readonly count: number;
}
/**
* Whether the live window was RESHAPED rather than purely appended-to: a
* different thread, a re-snapshot (reconnect) that changes the window's
* chronological-oldest row, or a checkpoint revert that shrinks it. A pure
* append (same thread, same oldest, count not smaller) is NOT a reshape.
*/
export function didLiveWindowReshape(previous: LiveWindowShape, next: LiveWindowShape): boolean {
return (
next.key !== previous.key || next.oldest !== previous.oldest || next.count < previous.count
);
}
/**
* The cursor for the page immediately older than `oldest`: sequenced rows page
* by `beforeSequence`; unsequenced rows (the common case) by the
* `(createdAt, activityId)` keyset.
*/
export function olderActivitiesCursorFor(
oldest: OrchestrationThreadActivity,
): OlderActivitiesCursor {
return oldest.sequence !== undefined
? { beforeSequence: oldest.sequence }
: { beforeCreatedAt: oldest.createdAt, beforeActivityId: oldest.id };
}
/**
* The row the NEXT load should cursor from: the explicit cursor row already
* paged past when one exists (so an all-overlap page keeps advancing), else
* the chronologically-oldest loaded row — never index 0, which the reducer
* can fill with a newer row (unsequenced rows sort to the end).
*/
export function nextOlderActivitiesCursorRow(
pagedPast: OrchestrationThreadActivity | null,
merged: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity | null {
return pagedPast ?? oldestActivityByChronology(merged);
}
/**
* The page rows not already present in the loaded set (older pages + live
* window) — boundary overlap and mid-flight appends must never produce
* duplicate ids in the merged timeline.
*/
export function freshOlderActivities(
page: OlderActivitiesPage,
merged: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const seen = new Set(merged.map((activity) => activity.id));
return page.activities.filter((activity) => !seen.has(activity.id));
}
/**
* The older-history lazy-load engine, shared by every client (web ChatView,
* the mobile composer, the TUI ChatView). The thread-detail snapshot windows
* activities to the most recent page; older pages are fetched on demand and
* prepended.
*
* One implementation holds all the hardening the per-client copies kept
* drifting on:
* - reset on live-window RESHAPE, not just thread switch: a reconnect
* re-snapshot changes the window's chronological-oldest row and a checkpoint
* revert shrinks it, but a plain append does neither (the reducer re-sorts
* unsequenced rows, so index 0 is not a stable boundary — the sentinel is
* {@link liveWindowOldestActivityId});
* - a generation guard so a load resolving after a reset can't repopulate the
* cleared state;
* - a synchronous in-flight key so scroll-triggered duplicate dispatches
* coalesce before the loading state commits;
* - an explicit advancing cursor (the oldest row paged PAST), so an
* all-overlap page keeps paging instead of dead-ending while the server
* still reports more — the server cursor is strict, so it strictly
* decreases and paging cannot loop;
* - dedup against the LATEST merged set via a ref, so a live append or a
* prior prepend settling mid-flight can't produce duplicate ids;
* - `hasMore` stays true on a failed/skipped page (the history still exists;
* scrolling back retries).
*/
export function useOlderThreadActivities(
options: UseOlderThreadActivitiesOptions,
): UseOlderThreadActivitiesResult {
const { threadKey, liveActivities, hasMoreLiveActivities, loadPage } = options;
const [olderActivities, setOlderActivities] = useState<
ReadonlyArray<OrchestrationThreadActivity>
>([]);
const [olderLoaded, setOlderLoaded] = useState(false);
const [olderHasMore, setOlderHasMore] = useState(false);
const [loadingOlder, setLoadingOlder] = useState(false);
// Order-independent oldest boundary: `liveActivities[0]` shifts when the
// reducer re-sorts unsequenced rows on the first live append, which would
// otherwise make a plain append look like a window reshape.
const liveOldestActivityId = useMemo(
() => liveWindowOldestActivityId(liveActivities),
[liveActivities],
);
const liveActivityCount = liveActivities.length;
// Bumps on every reset so a late in-flight load can't repopulate the
// freshly-cleared state (the thread key alone doesn't change on a
// same-thread window reshape).
const generationRef = useRef(0);
// The thread key of an in-flight load — coalesces the duplicate dispatches a
// fast scroll fires before the loading state updates.
const inFlightKeyRef = useRef<string | null>(null);
// The oldest row we've paged past; advances even when a page dedupes to
// nothing. Reset on reshape.
const cursorRef = useRef<OrchestrationThreadActivity | null>(null);
const windowRef = useRef({
key: threadKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
});
// useLayoutEffect (not useEffect) so the cleared state commits before paint:
// otherwise a thread switch renders one frame with the previous thread's
// lazy-loaded pages still merged in, flashing stale rows.
useLayoutEffect(() => {
const previous = windowRef.current;
windowRef.current = {
key: threadKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
};
if (!didLiveWindowReshape(previous, windowRef.current)) {
return;
}
generationRef.current += 1;
inFlightKeyRef.current = null;
cursorRef.current = null;
setOlderActivities([]);
setOlderLoaded(false);
setOlderHasMore(false);
setLoadingOlder(false);
}, [threadKey, liveOldestActivityId, liveActivityCount]);
const mergedActivities = useMemo(
() =>
olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities,
[olderActivities, liveActivities],
);
// Latest merged set, read inside the async load handler so dedup runs
// against current state, not the snapshot captured at dispatch time.
const mergedActivitiesRef = useRef(mergedActivities);
mergedActivitiesRef.current = mergedActivities;
// Before any page is loaded the server flag is authoritative; afterwards
// the latest page's `hasMore` is.
const hasMoreOlder = olderLoaded
? olderHasMore
: threadKey !== null && hasMoreLiveActivities;
const loadOlder = useCallback(() => {
if (threadKey === null || !hasMoreOlder) {
return;
}
const oldest = nextOlderActivitiesCursorRow(cursorRef.current, mergedActivitiesRef.current);
if (!oldest) {
return;
}
if (inFlightKeyRef.current === threadKey) {
return; // a load for this thread is already in flight
}
const cursor = olderActivitiesCursorFor(oldest);
const generation = generationRef.current;
inFlightKeyRef.current = threadKey;
setLoadingOlder(true);
void loadPage(cursor)
.then((page) => {
// The window/thread was reset while this was in flight — drop the page
// so it can't repopulate state cleared by the reset.
if (generationRef.current !== generation) {
return;
}
if (page === null) {
// Failed or interrupted (already surfaced by the caller). Keep
// `hasMore` — the history still exists and retrying is valid.
return;
}
// Advance the cursor even when every row dedupes away — the server
// cursor is strict, so it strictly decreases and paging can't loop.
const pageOldest = page.activities[0];
if (pageOldest) {
cursorRef.current = pageOldest;
}
const fresh = freshOlderActivities(page, mergedActivitiesRef.current);
if (fresh.length > 0) {
setOlderActivities((previous) => [...fresh, ...previous]);
}
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
})
.finally(() => {
if (generationRef.current === generation) {
inFlightKeyRef.current = null;
setLoadingOlder(false);
}
});
}, [threadKey, hasMoreOlder, loadPage]);
return {
mergedActivities: threadKey === null ? EMPTY_ACTIVITIES : mergedActivities,
hasMoreOlder,
loadingOlder,
loadOlder,
};
}