From ae2610b8c12e6c481427116199fc5a7a8247d3d2 Mon Sep 17 00:00:00 2001 From: olafura Date: Mon, 22 Jun 2026 20:52:53 +0200 Subject: [PATCH] feat(web): lazy-load older thread history on scroll-up The server windows thread detail to the most recent 500 activities and reports `hasMoreActivities`. The web timeline now fetches older pages on demand via the getThreadActivities RPC: - client-runtime: loadThreadActivities command on orchestrationEnvironment. - ChatView keeps per-thread older pages in local state, prepends them ahead of the live window, and derives hasMore from the server flag (no client-side window-size constant). A thread-keyed in-flight ref coalesces the duplicate dispatches a fast scroll-to-top would otherwise fire, and a request-key guard discards results after a thread switch. - MessagesTimeline triggers a load on reaching the top (maintainVisibleContentPosition anchors the viewport on prepend) with a "Load older history" header and loading indicator. Co-Authored-By: Claude Opus 4.8 --- apps/web/src/components/ChatView.tsx | 104 +++++++++++++++++- .../components/chat/MessagesTimeline.test.tsx | 33 ++++++ .../src/components/chat/MessagesTimeline.tsx | 38 ++++++- .../client-runtime/src/state/orchestration.ts | 7 +- 4 files changed, 178 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c296c71706..d73960f903 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -190,6 +190,7 @@ import { primaryServerKeybindingsAtom, serverEnvironment, } from "../state/server"; +import { orchestrationEnvironment } from "../state/orchestration"; import { terminalEnvironment } from "../state/terminal"; import { threadEnvironment } from "../state/threads"; import { vcsEnvironment } from "../state/vcs"; @@ -1860,7 +1861,105 @@ function ChatViewContent(props: ChatViewProps) { ); const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; const phase = derivePhase(activeThread?.session ?? null); - const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; + + // ── 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 + >([]); + const [olderLoaded, setOlderLoaded] = useState(false); + const [olderHasMore, setOlderHasMore] = useState(false); + const [loadingOlderActivities, setLoadingOlderActivities] = useState(false); + const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, { + reportFailure: false, + }); + const activeThreadActivityRequestKey = activeThread + ? `${activeThread.environmentId}\u0000${activeThread.id}` + : null; + const activeThreadActivityRequestKeyRef = useRef(activeThreadActivityRequestKey); + activeThreadActivityRequestKeyRef.current = activeThreadActivityRequestKey; + useEffect(() => { + setOlderActivities([]); + setOlderLoaded(false); + setOlderHasMore(false); + setLoadingOlderActivities(false); + }, [activeThreadActivityRequestKey]); + + const liveThreadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; + const threadActivities = useMemo( + () => + olderActivities.length > 0 + ? [...olderActivities, ...liveThreadActivities] + : liveThreadActivities, + [olderActivities, liveThreadActivities], + ); + // 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); + // Tracks the request key of an in-flight older-history load. The scroll + // handler fires onLoadOlder on every frame while at the top, but the loading + // *state* only updates on the next render — without a synchronous guard a fast + // scroll-to-top dispatches several duplicate requests for the same cursor. + const inFlightOlderKeyRef = useRef(null); + const loadOlderActivities = useCallback(() => { + if (!activeThread || !hasMoreOlderActivities) { + return; + } + const oldestActivity = threadActivities[0]; + 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; + inFlightOlderKeyRef.current = requestKey; + setLoadingOlderActivities(true); + void loadThreadActivities({ + environmentId: activeThread.environmentId, + input: { threadId: activeThread.id, ...cursorInput }, + }) + .then((result) => { + if (activeThreadActivityRequestKeyRef.current !== requestKey) { + return; + } + if (result._tag !== "Success") { + return; + } + const page = result.value; + setOlderActivities((prev) => { + const seen = new Set(prev.map((activity) => 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 (activeThreadActivityRequestKeyRef.current === requestKey) { + setLoadingOlderActivities(false); + } + }); + }, [ + activeThread, + activeThreadActivityRequestKey, + hasMoreOlderActivities, + threadActivities, + loadThreadActivities, + ]); + const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]); const pendingApprovals = useMemo( () => derivePendingApprovals(threadActivities), @@ -5256,6 +5355,9 @@ function ChatViewContent(props: ChatViewProps) { activeTurnStartedAt={activeWorkStartedAt} listRef={legendListRef} timelineEntries={timelineEntries} + hasMoreOlder={hasMoreOlderActivities} + loadingOlder={loadingOlderActivities} + onLoadOlder={loadOlderActivities} latestTurn={activeLatestTurn} runningTurnId={ activeThread.session?.status === "running" diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index b340a248fb..38e461edf4 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -640,4 +640,37 @@ describe("MessagesTimeline", () => { expect(markup).toContain("lucide-x"); expect(markup).toContain('aria-label="Tool call failed"'); }); + + it("offers a 'Load older history' control when older activity remains", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + expect(markup).toContain("Load older history"); + }); + + it("shows a loading indicator while older history is being fetched", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + expect(markup).toContain("Loading older history"); + }); + + it("renders no older-history control when none remains", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + expect(markup).not.toContain("older history"); + }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index f759aa150b..62416603ed 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -185,6 +185,10 @@ interface MessagesTimelineProps { onIsAtEndChange: (isAtEnd: boolean) => void; onManualNavigation: () => void; hideEmptyPlaceholder?: boolean; + /** Older history beyond the live activity window can be lazy-loaded. */ + hasMoreOlder?: boolean; + loadingOlder?: boolean; + onLoadOlder?: () => void; } // --------------------------------------------------------------------------- @@ -219,6 +223,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onIsAtEndChange, onManualNavigation, hideEmptyPlaceholder = false, + hasMoreOlder = false, + loadingOlder = false, + onLoadOlder, }: MessagesTimelineProps) { const [expandedTurnIds, setExpandedTurnIds] = useState>(new Set()); const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState>(new Set()); @@ -361,6 +368,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({ if (isAtEnd !== undefined) { onIsAtEndChange(isAtEnd); } + // Reaching the top lazy-loads older history; maintainVisibleContentPosition + // (set on the list) keeps the viewport anchored when rows prepend. + if (state?.isAtStart && hasMoreOlder && !loadingOlder) { + onLoadOlder?.(); + } if (!state || minimapItems.length === 0) { return; } @@ -383,7 +395,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ strip.dataset.inView = inView ? "true" : "false"; } - }, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]); + }, [listRef, minimapItems, minimapStripMap, onIsAtEndChange, hasMoreOlder, loadingOlder, onLoadOlder]); useEffect(() => { const frame = requestAnimationFrame(handleScroll); @@ -415,6 +427,28 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }; }, [timelineViewportElement, rows.length]); + const listHeader = useMemo(() => { + if (loadingOlder) { + return ( +
+ Loading older history… +
+ ); + } + if (hasMoreOlder) { + return ( + + ); + } + return TIMELINE_LIST_HEADER; + }, [loadingOlder, hasMoreOlder, onLoadOlder]); + const sharedState = useMemo( () => ({ timestampFormat, @@ -511,7 +545,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }} onScroll={handleScroll} className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5" - ListHeaderComponent={TIMELINE_LIST_HEADER} + ListHeaderComponent={listHeader} ListFooterComponent={TIMELINE_LIST_FOOTER} /> ( @@ -12,6 +12,11 @@ export function createOrchestrationEnvironmentAtoms( label: "environment-data:orchestration:turn-diff", tag: ORCHESTRATION_WS_METHODS.getTurnDiff, }), + // Imperative lazy-load of older thread activities (infinite scroll-up). + loadThreadActivities: createEnvironmentRpcCommand(runtime, { + label: "environment-data:orchestration:thread-activities", + tag: ORCHESTRATION_WS_METHODS.getThreadActivities, + }), fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:full-thread-diff", tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,