From db34a1585901074136972839b824a7570014471e Mon Sep 17 00:00:00 2001 From: Type-Delta Date: Tue, 24 Nov 2026 20:38:35 +0700 Subject: [PATCH] feat(chat): load earlier thread history on scroll Long threads required a click for each older page. Prefetch near the start of the loaded history, preserve the viewport and open tool groups, and show loading feedback for slow requests. Built with GPT-6.2 Sol in Codex. --- FORK.md | 10 ++ .../features/threads/ThreadDetailScreen.tsx | 1 + .../src/features/threads/ThreadFeed.tsx | 96 +++++++++--- .../features/threads/ThreadRouteScreen.tsx | 8 +- apps/mobile/src/lib/threadActivity.test.ts | 24 +++ apps/mobile/src/lib/threadActivity.ts | 22 ++- apps/web/src/components/ChatView.tsx | 1 + .../chat/MessagesTimeline.browser.test.tsx | 140 ++++++++++++++++++ .../chat/MessagesTimeline.logic.test.ts | 25 ++++ .../components/chat/MessagesTimeline.logic.ts | 1 + .../src/components/chat/MessagesTimeline.tsx | 96 +++++++++--- .../src/components/chat/citationProcedure.ts | 2 +- .../guest/GuestPage.browser.test.tsx | 52 +++++++ apps/web/src/components/guest/GuestPage.tsx | 15 +- .../src/components/guest/guestStream.logic.ts | 2 +- 15 files changed, 437 insertions(+), 58 deletions(-) diff --git a/FORK.md b/FORK.md index aa8f9f4f8a1c4..f3be06b65e176 100644 --- a/FORK.md +++ b/FORK.md @@ -1071,6 +1071,16 @@ On macOS, a new self-signed fork build asked for keychain access to the "T3 Code **Last updated:** 2026-11-24 +### DL067 — Scroll to load earlier thread turns + +Thread timelines keep the bounded initial history window and fetch earlier pages as the reader approaches its start. Web, desktop and guest timelines observe the top of the loaded history. The native feed uses its virtual list's start threshold. Both keep the visible rows anchored as pages are prepended and show a delayed loading label or a retry action when a page fails. While a work group is open, earlier tools stay in a separate group so the open header and detail rows keep their scroll anchors. + +**Implementation evidence:** `apps/web/src/components/chat/MessagesTimeline.tsx`, `apps/web/src/components/chat/MessagesTimeline.browser.test.tsx`, and `apps/mobile/src/features/threads/ThreadFeed.tsx`. + +**Recorded validation:** Chromium tests cover delayed status across cursor changes, retry, an empty bounded window after switching threads, and paging after a guest reconnect. Web and native row tests cover an expanded work group when a history page prepends tools from the same run. Real-server runs in Chromium, Electron, and Android reached the oldest turn in the same fixture of replayed messages, plans, and tool activity. Chromium and Electron observed two page requests. Chromium also verified prefetch before the top and preserved the visible row when a delayed page arrived. Android also exercised a separate thread with short and wrapped messages. + +**Last updated:** 2026-11-24 + ## Sync Checklist Project-specific checks every upstream sync runs, in addition to the full test suite, lint, typecheck, builds, and a smoke test of upstream and fork features. diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 25b8894cc8040..ea49d0e23b6ee 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1501,6 +1501,7 @@ function ThreadDetailBody( freeze={freeze} anchorMessageId={anchorMessageId} jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null} + historyJumpPending={jumpMessageId !== null} onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)} contentInsetEndAdjustment={combinedContentInsetEndAdjustment} keyboardOffset={composerKeyboardOffset} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 2a173816d9981..de011678ade79 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -104,6 +104,7 @@ import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { textDirection } from "@t3tools/shared/textDirection"; import { useFocusEffect, useIsFocused, useNavigation } from "@react-navigation/native"; import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns"; +import { useDelayedStatus } from "../../lib/useDelayedStatus"; import { useDeviceType } from "../../native/native-layout-metrics"; import { isDuoDevice } from "../../lib/device-type"; import { @@ -322,10 +323,11 @@ function isFreshTimestamp(input: string): boolean { } export interface ThreadFeedHistoryControls { + readonly cursor: string | null; readonly hasMoreHistory: boolean; readonly loading: boolean; readonly error: string | null; - readonly onLoadEarlier: () => void; + readonly onLoadEarlier: () => Promise; /** Loads earlier history down to the entry, in one request. */ readonly onLoadThrough: (entryId: string) => void; } @@ -355,6 +357,7 @@ export interface ThreadFeedProps { readonly anchorMessageId: MessageId | null; /** A message to scroll to once it is in the feed; see `onJumpedToMessage`. */ readonly jumpToMessageId?: MessageId | null; + readonly historyJumpPending?: boolean; readonly onJumpedToMessage?: () => void; readonly contentInsetEndAdjustment: SharedValue; readonly keyboardOffset: number; @@ -3522,6 +3525,49 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ? setupAnchorIndex : undefined, }); + const history = props.historyControls; + const historyCursor = history?.cursor; + const canPrefetchHistory = + focused && + !props.historyJumpPending && + loadedListKey === feedThreadKey && + history?.hasMoreHistory === true && + !history.loading && + history.error === null; + const requestedHistory = useRef<{ + threadKey: string; + cursor: string; + rowCount: number; + } | null>(null); + const prefetchHistory = () => { + if (!canPrefetchHistory || !history || !historyCursor) return; + if ( + requestedHistory.current?.threadKey === feedThreadKey && + requestedHistory.current.cursor === historyCursor + ) { + return; + } + requestedHistory.current = { + threadKey: feedThreadKey, + cursor: historyCursor, + rowCount: groupedFeed.length, + }; + return history.onLoadEarlier(); + }; + const prefetchUnchangedHistory = useEffectEvent(() => { + const previous = requestedHistory.current; + if ( + groupedFeed.length === 0 || + ((previous?.threadKey !== feedThreadKey || previous.rowCount === groupedFeed.length) && + listRef.current?.getState().isNearStart) + ) { + void prefetchHistory(); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rechecks the viewport when a page advances without changing the visible row count + useEffect(() => { + if (canPrefetchHistory && historyCursor) prefetchUnchangedHistory(); + }, [canPrefetchHistory, historyCursor]); const { contentInsetEndAdjustment } = props; const attachList = (list: LegendListRef | null) => { listRef.current = list; @@ -3983,6 +4029,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onLayout={handleMetricsChange} onItemSizeChanged={handleItemSizeChanged} onScroll={handleScroll} + onStartReached={canPrefetchHistory ? prefetchHistory : undefined} + onStartReachedThreshold={0.6} scrollEventThrottle={16} ListHeaderComponent={ <> @@ -3993,7 +4041,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : null} {props.historyControls ? ( - + ) : null} } @@ -4040,32 +4088,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ); }); -function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) { +function ThreadFeedHistoryStatus(props: ThreadFeedHistoryControls) { const theme = useUniwindTheme(); const mutedColor = theme["--color-icon-subtle"]; + const loadingLabel = useDelayedStatus( + props.loading ? "loading" : "idle", + props.loading ? "Loading earlier activity…" : null, + ); if (!props.hasMoreHistory && props.error === null) { return null; } return ( - - {props.hasMoreHistory ? ( - - - ) : null} +
+
{props.error !== null ? ( -

- {props.error} -

- ) : null} + <> + {props.error} + {props.hasMoreHistory ? ( + + ) : null} + + ) : ( + {loadingLabel} + )}
); diff --git a/apps/web/src/components/chat/citationProcedure.ts b/apps/web/src/components/chat/citationProcedure.ts index 2d77a468e67d7..31a10c0be68c4 100644 --- a/apps/web/src/components/chat/citationProcedure.ts +++ b/apps/web/src/components/chat/citationProcedure.ts @@ -41,7 +41,7 @@ const COULD_NOT_LOAD = { _tag: "failed", title: "Could not load the cited response", description: - "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.", + "Scroll up to load earlier turns, then click the citation to try again. Your saved quote is unchanged.", } as const; const UNAVAILABLE = { diff --git a/apps/web/src/components/guest/GuestPage.browser.test.tsx b/apps/web/src/components/guest/GuestPage.browser.test.tsx index 6abab1cb01271..b728e70d77ec6 100644 --- a/apps/web/src/components/guest/GuestPage.browser.test.tsx +++ b/apps/web/src/components/guest/GuestPage.browser.test.tsx @@ -1,6 +1,7 @@ import { EventId, GUEST_COMMAND_OUTPUT_ROUTE, + GUEST_HISTORY_ROUTE, GUEST_RENDER_ROUTE, GuestMessageId, GuestShareId, @@ -11,6 +12,7 @@ import { TurnItemId, type GuestShareView, type OrchestrationV2Run, + OrchestrationV2ThreadHistoryPage, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -26,6 +28,7 @@ import { GuestPage } from "./GuestPage"; const SHARE_ID = "share-1"; const encodeEvent = Schema.encodeSync(Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent))); +const encodeHistoryPage = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage)); const fixture = makeThreadProjectionFixture(); const threadId = fixture.thread.id; @@ -216,6 +219,55 @@ function visit(path: string): Disposable { } describe("GuestPage", () => { + it("can reload the same history page after a reconnect restores the bounded window", async () => { + using _page = visit(`/guest?share=${SHARE_ID}`); + const oldReply = reply("older", 0, "Earlier reply", "run-old"); + const historyPage = encodeHistoryPage({ + snapshotSequence: 1, + hasMoreHistory: false, + nextCursor: null, + items: [ + { + position: 0, + visibility: "local", + sourceThreadId: threadId, + sourceItemId: oldReply.id, + item: oldReply, + }, + ], + }); + const historyUrl = `${GUEST_HISTORY_ROUTE}?share=${SHARE_ID}&cursor=earlier`; + using fetchSpy = vi + .spyOn(window, "fetch") + .mockImplementation(async (url) => + url === historyUrl ? Response.json(historyPage) : new Response(null, { status: 204 }), + ); + const sources: Array = []; + const [share, thread] = opening( + [run("run-old", 1, "completed"), run("run-1", 2, "completed")], + [reply("recent", 1, "Recent reply")], + ); + if (!share || thread?.type !== "thread" || thread.item.kind !== "snapshot") + throw new Error("Missing guest fixture snapshot."); + const bounded = { + ...thread, + item: { ...thread.item, hasMoreHistory: true, historyCursor: "earlier" }, + } satisfies GuestStreamEvent; + using _stream = vi + .spyOn(window, "EventSource") + .mockImplementation(fakeEventSource([share, bounded], sources) as never); + const container = document.createElement("div"); + container.style.cssText = "height: 600px; width: 900px; display: flex; flex-direction: column;"; + await using screen = await render(, { container }); + await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledWith(historyUrl)); + await expect.element(screen.getByText("Earlier reply")).toBeVisible(); + sources[0]!.dispatchEvent(new MessageEvent("message", { data: encodeEvent(bounded) })); + await vi.waitFor(() => + expect(fetchSpy.mock.calls.filter(([url]) => url === historyUrl)).toHaveLength(2), + ); + await expect.element(screen.getByText("Earlier reply")).toBeVisible(); + }); + it("shows the shared thread in the real timeline without opening an environment connection", async () => { using _page = visit(`/guest?share=${SHARE_ID}`); using _session = vi diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsx index 7ac90687b227c..6ac2dd093e20e 100644 --- a/apps/web/src/components/guest/GuestPage.tsx +++ b/apps/web/src/components/guest/GuestPage.tsx @@ -279,15 +279,24 @@ function GuestSession({ shareId }: { readonly shareId: string }) { const historyError = currentLoad?.error ?? null; const loadEarlier = async () => { if (historyCursor === null || loadingHistory) return; - setHistoryLoad({ cursor: historyCursor, error: null }); + const request = { cursor: historyCursor, error: null }; + setHistoryLoad(request); const result = await fetchGuestHistoryPage(shareId, historyCursor); - if (typeof result === "string") setHistoryLoad({ cursor: historyCursor, error: result }); - else dispatch({ type: "history-page", cursor: historyCursor, page: result }); + setHistoryLoad((current) => + current !== request + ? current + : typeof result === "string" + ? { ...request, error: result } + : null, + ); + if (typeof result !== "string") + dispatch({ type: "history-page", cursor: historyCursor, page: result }); }; const historyControls: MessagesTimelineHistoryControls | undefined = historyCursor === null ? undefined : { + cursor: historyCursor, hasMoreHistory: true, loading: loadingHistory, error: historyError, diff --git a/apps/web/src/components/guest/guestStream.logic.ts b/apps/web/src/components/guest/guestStream.logic.ts index 2c0e6f31fce41..24d7e039ac94c 100644 --- a/apps/web/src/components/guest/guestStream.logic.ts +++ b/apps/web/src/components/guest/guestStream.logic.ts @@ -27,7 +27,7 @@ export interface GuestStreamState { readonly sequence: number; /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */ readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null; - /** Where "Load earlier turns" continues, or null once the whole thread is loaded. */ + /** Where older history continues, or null once the whole thread is loaded. */ readonly historyCursor: string | null; readonly ended: boolean; /**