feat(mobile): lazy-load older thread history on scroll-up

Mobile consumed the windowed thread detail with no way to fetch older
activities, silently truncating history. Mirror the web lazy-load:

- useThreadComposerState: older-activity state + a thread-keyed in-flight ref
  guard, a reset effect on thread switch, and loadThreadActivities with the same
  union cursor. Older pages are deduped (against prior pages and the live window)
  and prepended into the feed; initial hasMore comes from the server's
  hasMoreActivities flag.
- ThreadFeed: onStartReached triggers the load, maintainVisibleContentPosition
  anchors the viewport on prepend, and the header shows a spinner while loading.
- Forward the values through ThreadRouteScreen → ThreadDetailScreen.

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:26:29 +02:00
1 parent ae2610b8c1
commit 21ca57b213
4 files changed
+146 -4

No files matched your search

@@ -65,6 +65,9 @@ export interface ThreadDetailScreenProps {
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
readonly activeThreadBusy: boolean;
readonly hasMoreOlderActivities: boolean;
readonly loadingOlderActivities: boolean;
readonly onLoadOlderActivities: () => void;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
@@ -422,6 +425,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
hasMoreOlder={props.hasMoreOlderActivities}
loadingOlder={props.loadingOlderActivities}
onLoadOlder={props.onLoadOlderActivities}
/>
</View>
) : (
@@ -139,6 +139,10 @@ export interface ThreadFeedProps {
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Older history beyond the live activity window can be lazy-loaded on scroll-up. */
readonly hasMoreOlder?: boolean;
readonly loadingOlder?: boolean;
readonly onLoadOlder?: () => void;
}
function MessageAttachmentImage(props: {
@@ -1459,6 +1463,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
? props.latestTurn.turnId
: null;
// Reaching the top (oldest) lazy-loads older history. The hook keys an
// in-flight guard by thread, so repeated fires during scroll coalesce.
const { hasMoreOlder, loadingOlder, onLoadOlder } = props;
const onStartReachedOlderHistory = useCallback(() => {
if (hasMoreOlder && !loadingOlder) {
onLoadOlder?.();
}
}, [hasMoreOlder, loadingOlder, onLoadOlder]);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = props.latestTurn;
@@ -1751,9 +1765,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
estimatedItemSize={180}
initialScrollAtEnd
onScroll={handleScroll}
onStartReached={onStartReachedOlderHistory}
onStartReachedThreshold={0.5}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
usesNativeAutomaticInsets && !loadingOlder ? null : (
<View style={{ height: usesNativeAutomaticInsets ? undefined : topContentInset }}>
{loadingOlder ? <ActivityIndicator style={{ marginTop: 8 }} /> : null}
</View>
)
}
contentContainerStyle={{
paddingTop: 12,
@@ -767,6 +767,9 @@ function ThreadRouteContent(
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
activeThreadBusy={composer.activeThreadBusy}
hasMoreOlderActivities={composer.hasMoreOlderActivities}
loadingOlderActivities={composer.loadingOlderActivities}
onLoadOlderActivities={composer.onLoadOlderActivities}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
@@ -1,11 +1,12 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
CommandId,
MessageId,
type EnvironmentId,
type ModelSelection,
type OrchestrationThreadActivity,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
@@ -36,11 +37,15 @@ import {
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
import { orchestrationEnvironment } from "../state/orchestration";
import { useSelectedThreadDetail } from "../state/use-thread-detail";
import { useThreadSelection } from "../state/use-thread-selection";
import { useAtomCommand } from "./use-atom-command";
import { enqueueThreadOutboxMessage } from "./thread-outbox";
import { useThreadOutboxMessages } from "./use-thread-outbox";
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
export function appendReviewCommentToDraft(input: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -89,9 +94,114 @@ export function useThreadComposerState() {
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
// ── Older-history lazy-load (mirrors web ChatView) ──────────────────────────
// 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 activityRequestKeyRef = useRef(activityRequestKey);
activityRequestKeyRef.current = activityRequestKey;
useEffect(() => {
setOlderActivities([]);
setOlderLoaded(false);
setOlderHasMore(false);
setLoadingOlderActivities(false);
}, [activityRequestKey]);
const liveActivities = selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES;
const mergedActivities = useMemo(
() =>
olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities,
[olderActivities, liveActivities],
);
// Before any page is loaded, the server tells us whether older history exists.
const hasMoreOlderActivities = olderLoaded
? olderHasMore
: (selectedThreadDetail?.hasMoreActivities ?? false);
// Synchronous in-flight guard keyed by thread: the list fires onLoadOlder
// repeatedly while pinned at the top, but loading *state* only updates next
// render, so without this a fast scroll dispatches duplicate same-cursor calls.
const inFlightOlderKeyRef = useRef<string | null>(null);
const onLoadOlderActivities = useCallback(() => {
if (!selectedThreadShell || !hasMoreOlderActivities) {
return;
}
const oldestActivity = mergedActivities[0];
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;
inFlightOlderKeyRef.current = requestKey;
setLoadingOlderActivities(true);
void loadThreadActivities({
environmentId: selectedThreadShell.environmentId,
input: { threadId: selectedThreadShell.id, ...cursorInput },
})
.then((result) => {
if (activityRequestKeyRef.current !== requestKey) {
return;
}
if (result._tag !== "Success") {
return;
}
const page = result.value;
setOlderActivities((prev) => {
// Dedup against both already-loaded older pages and the live window,
// since mobile merges everything into one array (duplicate ids would
// produce duplicate React keys in the feed).
const seen = new Set(prev.map((activity) => activity.id));
for (const activity of liveActivities) {
seen.add(activity.id);
}
const fresh = page.activities.filter((activity) => !seen.has(activity.id));
return [...fresh, ...prev];
});
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
})
.finally(() => {
if (inFlightOlderKeyRef.current === requestKey) {
inFlightOlderKeyRef.current = null;
}
if (activityRequestKeyRef.current === requestKey) {
setLoadingOlderActivities(false);
}
});
}, [
selectedThreadShell,
hasMoreOlderActivities,
mergedActivities,
activityRequestKey,
liveActivities,
loadThreadActivities,
]);
const selectedThreadFeed = useMemo(
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
() =>
selectedThreadDetail
? buildThreadFeed({ ...selectedThreadDetail, activities: mergedActivities })
: [],
[selectedThreadDetail, mergedActivities],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
@@ -299,6 +409,9 @@ export function useThreadComposerState() {
runtimeMode,
interactionMode,
activeThreadBusy,
hasMoreOlderActivities,
loadingOlderActivities,
onLoadOlderActivities,
onChangeDraftMessage,
onPickDraftImages,
onPasteIntoDraft,