diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index ae63c3406b..ecd803ffe5 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -194,7 +194,9 @@ function ThreadRouteContent( const composer = useThreadComposerState(); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); - const requests = useSelectedThreadRequests(); + // Derive pending requests from the FULL loaded set (older pages + live + // window) so a prompt the user scrolled back to load still surfaces. + const requests = useSelectedThreadRequests(composer.mergedActivities); const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt"); const navigation = useNavigation(); const params = props.route.params; diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts index c9e9db1253..8c934547c0 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -1,7 +1,11 @@ import { useAtomValue } from "@effect/atom-react"; import { useCallback, useMemo, useState } from "react"; -import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts"; +import { + ApprovalRequestId, + type OrchestrationThreadActivity, + type ProviderApprovalDecision, +} from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; import { threadEnvironment } from "../state/threads"; @@ -53,7 +57,20 @@ function setUserInputDraftCustomAnswer( }); } -export function useSelectedThreadRequests() { +/** + * Pending approval / user-input requests for the selected thread. + * + * `activities` should be the FULL loaded set (lazy-loaded older pages + the + * windowed live view, i.e. `useThreadComposerState().mergedActivities`): the + * detail snapshot windows activities to the most recent page, so deriving from + * `selectedThread.activities` alone would hide a prompt the user scrolled back + * to load. Falls back to the live window when not provided. Deriving from the + * merged set is sound — resolutions are always newer than their requests, so a + * loaded request whose resolution exists always has that resolution loaded too. + */ +export function useSelectedThreadRequests( + activities?: ReadonlyArray, +) { const respondToApproval = useAtomCommand( threadEnvironment.respondToApproval, "thread approval response", @@ -70,14 +87,15 @@ export function useSelectedThreadRequests() { null, ); + const requestActivities = activities ?? selectedThread?.activities ?? null; const activePendingApprovals = useMemo( - () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []), - [selectedThread], + () => (requestActivities ? derivePendingApprovals(requestActivities) : []), + [requestActivities], ); const activePendingApproval = activePendingApprovals[0] ?? null; const activePendingUserInputs = useMemo( - () => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []), - [selectedThread], + () => (requestActivities ? derivePendingUserInputs(requestActivities) : []), + [requestActivities], ); const activePendingUserInput = activePendingUserInputs[0] ?? null; const activePendingUserInputDrafts = diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 4e77fc668a..2666434ba3 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -1,5 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { CommandId, @@ -12,6 +12,11 @@ import { type ThreadId, } from "@t3tools/contracts"; 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"; import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming"; import { makeQueuedMessageMetadata } from "../lib/commandMetadata"; @@ -111,40 +116,83 @@ export function useThreadComposerState() { const activityRequestKey = selectedThreadShell ? `${selectedThreadShell.environmentId}\u0000${selectedThreadShell.id}` : null; - const activityRequestKeyRef = useRef(activityRequestKey); - activityRequestKeyRef.current = activityRequestKey; - const liveActivities = selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES; - // The live window's oldest activity is stable while new activities only - // append; it changes when the window is re-snapshotted (reconnect) or rows are - // removed (checkpoint revert), either of which can make prepended older pages - // stale or gappy — so reset the lazy-load state when it (or the thread) changes. - const liveOldestActivityId = liveActivities[0]?.id ?? null; - useEffect(() => { + // 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(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(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]); + }, [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); - // 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(null); const onLoadOlderActivities = useCallback(() => { if (!selectedThreadShell || !hasMoreOlderActivities) { return; } - const oldestActivity = mergedActivities[0]; + // 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; } @@ -156,6 +204,7 @@ export function useThreadComposerState() { ? { beforeSequence: oldestActivity.sequence } : { beforeCreatedAt: oldestActivity.createdAt, beforeActivityId: oldestActivity.id }; const requestKey = activityRequestKey; + const gen = olderActivitiesGenRef.current; inFlightOlderKeyRef.current = requestKey; setLoadingOlderActivities(true); void loadThreadActivities({ @@ -163,32 +212,45 @@ export function useThreadComposerState() { input: { threadId: selectedThreadShell.id, ...cursorInput }, }) .then((result) => { - if (activityRequestKeyRef.current !== requestKey) { + // 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; - 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]; - }); + // 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 (inFlightOlderKeyRef.current === requestKey) { + if (olderActivitiesGenRef.current === gen) { inFlightOlderKeyRef.current = null; - } - if (activityRequestKeyRef.current === requestKey) { setLoadingOlderActivities(false); } }); @@ -197,7 +259,6 @@ export function useThreadComposerState() { hasMoreOlderActivities, mergedActivities, activityRequestKey, - liveActivities, loadThreadActivities, ]); @@ -414,6 +475,10 @@ export function useThreadComposerState() { runtimeMode, interactionMode, activeThreadBusy, + // Lazy-loaded older pages + the live window — the full loaded activity set. + // Request derivations must run over this (not the windowed live set alone) + // so prompts pulled in by scroll-up still surface, matching web. + mergedActivities, hasMoreOlderActivities, loadingOlderActivities, onLoadOlderActivities, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 2e714bf179..2ad66b6546 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -1309,6 +1309,103 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { }), ); + it.effect( + "unsequenced cursor reaches all older rows without stranding sequenced ones", + () => + // Regression for the "unsequenced cursor hides sequenced history" concern: + // sequenced rows always sort newer than NULL-sequence (legacy) rows, so when + // the oldest loaded row is unsequenced every sequenced row is already in the + // window — the `sequence IS NULL` cursor can't strand sequenced rows. + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + yield* sql`DELETE FROM projection_projects`; + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_thread_activities`; + yield* sql`DELETE FROM projection_state`; + yield* sql` + INSERT INTO projection_projects ( + project_id, title, workspace_root, default_model_selection_json, + scripts_json, created_at, updated_at, deleted_at + ) VALUES ( + 'project-1', 'Project 1', '/tmp/project-1', + '{"provider":"codex","model":"gpt-5-codex"}', '[]', + '2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL + ) + `; + yield* sql` + INSERT INTO projection_threads ( + thread_id, project_id, title, model_selection_json, runtime_mode, + interaction_mode, branch, worktree_path, latest_turn_id, + latest_user_message_at, pending_approval_count, pending_user_input_count, + has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at + ) VALUES ( + 'thread-1', 'project-1', 'Thread 1', + '{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default', + NULL, NULL, NULL, NULL, 0, 0, 0, + '2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL + ) + `; + // 600 legacy unsequenced rows (older) + 3 sequenced rows (newer). The + // window keeps the 3 sequenced + the most-recent 497 unsequenced, so the + // oldest loaded row is unsequenced and 103 older unsequenced remain. + yield* Effect.forEach( + Array.from({ length: 600 }, (_u, index) => index + 1), + (n) => + sql` + INSERT INTO projection_thread_activities ( + activity_id, thread_id, turn_id, tone, kind, summary, payload_json, + sequence, created_at + ) VALUES ( + ${`unseq-${String(n).padStart(4, "0")}`}, 'thread-1', NULL, + 'info', 'runtime.note', ${`unseq-${n}`}, '{}', NULL, + ${`2026-04-01T00:00:01.${String(n).padStart(3, "0")}Z`} + ) + `, + { discard: true }, + ); + yield* Effect.forEach( + [1, 2, 3], + (seq) => + sql` + INSERT INTO projection_thread_activities ( + activity_id, thread_id, turn_id, tone, kind, summary, payload_json, + sequence, created_at + ) VALUES ( + ${`seq-${seq}`}, 'thread-1', NULL, 'info', 'runtime.note', + ${`seq-${seq}`}, '{}', ${seq}, ${`2026-04-01T09:00:0${seq}.000Z`} + ) + `, + { discard: true }, + ); + + const detail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1")); + assert.equal(detail._tag, "Some"); + if (detail._tag !== "Some") return; + const windowed = detail.value.activities; + assert.equal(windowed.length, 500); + // Sequenced rows are the newest (end of the ascending window); the oldest + // loaded row is unsequenced — exactly the case the concern is about. + assert.equal(windowed.at(-1)?.summary, "seq-3"); + assert.equal(windowed[0]?.sequence, undefined); + + // The client pages with the unsequenced cursor of the oldest loaded row. + const oldest = windowed[0]; + assert.ok(oldest); + const olderPage = yield* snapshotQuery.getThreadActivitiesPage({ + threadId: ThreadId.make("thread-1"), + beforeCreatedAt: oldest.createdAt, + beforeActivityId: oldest.id, + limit: 500, + }); + // The 103 older unsequenced rows come back, none are sequenced, and no + // sequenced row was stranded (all 3 are already in the window). + assert.equal(olderPage.activities.length, 103); + assert.equal(olderPage.hasMore, false); + assert.ok(olderPage.activities.every((a) => a.sequence === undefined)); + }), + ); + it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () => Effect.gen(function* () { const snapshotQuery = yield* ProjectionSnapshotQuery; diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index b719014e8e..bd2d494e5a 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -126,16 +126,22 @@ const ThreadIdLookupInput = Schema.Struct({ */ const THREAD_DETAIL_ACTIVITY_WINDOW = 500; +// `beforeSequence`/`limit` are NonNegativeInt (not bare Number) to match the +// contract: the WHERE clause `(sequence < beforeSequence OR sequence IS NULL)` +// is only equivalent to the old `COALESCE(sequence, -1) < beforeSequence` when +// `beforeSequence` is non-negative — a negative cursor would silently match no +// sequenced rows and return only unsequenced ones. Validating here (not just at +// the RPC boundary) keeps any future non-RPC caller honest. const ThreadActivitiesBeforeSequenceInput = Schema.Struct({ threadId: ThreadId, - beforeSequence: Schema.Number, - limit: Schema.Number, + beforeSequence: NonNegativeInt, + limit: NonNegativeInt, }); const ThreadActivitiesBeforeActivityInput = Schema.Struct({ threadId: ThreadId, beforeCreatedAt: IsoDateTime, beforeActivityId: EventId, - limit: Schema.Number, + limit: NonNegativeInt, }); const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema; const ProjectionThreadIdLookupRowSchema = Schema.Struct({ diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6eaa684e32..206be11292 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -63,6 +63,10 @@ import { squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; +import { + liveWindowOldestActivityId, + oldestActivityByChronology, +} from "@t3tools/client-runtime/state/thread-reducer"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/unstable/reactivity"; import { isElectron } from "../env"; @@ -1879,20 +1883,61 @@ function ChatViewContent(props: ChatViewProps) { const activeThreadActivityRequestKey = activeThread ? `${activeThread.environmentId}\u0000${activeThread.id}` : null; - const activeThreadActivityRequestKeyRef = useRef(activeThreadActivityRequestKey); - activeThreadActivityRequestKeyRef.current = activeThreadActivityRequestKey; const liveThreadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; - // The live window's oldest activity is stable while new activities only - // append; it changes when the window is re-snapshotted (reconnect) or rows are - // removed (checkpoint revert), either of which can make prepended older pages - // stale or gappy — so reset the lazy-load state when it (or the thread) changes. - const liveOldestActivityId = liveThreadActivities[0]?.id ?? null; - useEffect(() => { + // 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(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(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]); + }, [activeThreadActivityRequestKey, liveOldestActivityId, liveActivityCount]); const threadActivities = useMemo( () => @@ -1901,21 +1946,25 @@ function ChatViewContent(props: ChatViewProps) { : 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); - // 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]; + // 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; } @@ -1927,6 +1976,7 @@ function ChatViewContent(props: ChatViewProps) { ? { beforeSequence: oldestActivity.sequence } : { beforeCreatedAt: oldestActivity.createdAt, beforeActivityId: oldestActivity.id }; const requestKey = activeThreadActivityRequestKey; + const gen = olderActivitiesGenRef.current; inFlightOlderKeyRef.current = requestKey; setLoadingOlderActivities(true); void loadThreadActivities({ @@ -1934,32 +1984,37 @@ function ChatViewContent(props: ChatViewProps) { input: { threadId: activeThread.id, ...cursorInput }, }) .then((result) => { - if (activeThreadActivityRequestKeyRef.current !== requestKey) { + // 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; - setOlderActivities((prev) => { - // Dedup against both already-loaded older pages and the live window so - // an overlap at the window boundary can't leave duplicate ids (which - // would break timeline keys and work-log derivation). - const seen = new Set(prev.map((activity) => activity.id)); - for (const activity of liveThreadActivities) { - seen.add(activity.id); - } - const fresh = page.activities.filter((activity) => !seen.has(activity.id)); - return [...fresh, ...prev]; - }); + // 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 (inFlightOlderKeyRef.current === requestKey) { + if (olderActivitiesGenRef.current === gen) { inFlightOlderKeyRef.current = null; - } - if (activeThreadActivityRequestKeyRef.current === requestKey) { setLoadingOlderActivities(false); } }); @@ -1968,7 +2023,6 @@ function ChatViewContent(props: ChatViewProps) { activeThreadActivityRequestKey, hasMoreOlderActivities, threadActivities, - liveThreadActivities, loadThreadActivities, ]); @@ -5518,7 +5572,11 @@ function ChatViewContent(props: ChatViewProps) { providerStatuses={providerStatuses as ServerProvider[]} activeProjectDefaultModelSelection={activeProject?.defaultModelSelection} activeThreadModelSelection={activeThread?.modelSelection} - activeThreadActivities={activeThread?.activities} + // Merged set (older pages + live window), not the windowed + // live slice: the context meter scans for the latest + // context-window.updated event, which can sit in a + // lazy-loaded page on long threads. + activeThreadActivities={threadActivities} resolvedTheme={resolvedTheme} settings={settings} keybindings={keybindings} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 62416603ed..da9a168fc8 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -500,7 +500,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({ [], ); - if (rows.length === 0 && !isWorking) { + // Only short-circuit to the empty state when there is genuinely nothing to + // fetch: the window can derive zero VISIBLE rows (e.g. only tool-neutral work + // entries) while older history still exists — the list must render then so + // its "Load older history" header stays reachable. + if (rows.length === 0 && !isWorking && !hasMoreOlder && !loadingOlder) { if (hideEmptyPlaceholder) { return null; } diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d9e1988972..cddc1a678b 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -123,6 +123,10 @@ "types": "./src/state/threads.ts", "default": "./src/state/threads.ts" }, + "./state/thread-reducer": { + "types": "./src/state/threadReducer.ts", + "default": "./src/state/threadReducer.ts" + }, "./state/thread-sort": { "types": "./src/state/threadSort.ts", "default": "./src/state/threadSort.ts" diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts index 94eb1c6537..1709f5a2d0 100644 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ b/packages/client-runtime/src/state/threadReducer.test.ts @@ -9,9 +9,29 @@ import { ThreadId, TurnId, } from "@t3tools/contracts"; -import type { OrchestrationThread } from "@t3tools/contracts"; +import type { OrchestrationThread, OrchestrationThreadActivity } from "@t3tools/contracts"; -import { applyThreadDetailEvent } from "./threadReducer.ts"; +import { + applyThreadDetailEvent, + liveWindowOldestActivityId, + oldestActivityByChronology, +} from "./threadReducer.ts"; + +const activity = ( + id: string, + createdAt: string, + sequence?: number, +): OrchestrationThreadActivity => + ({ + id, + tone: "tool", + kind: "command", + summary: id, + payload: {}, + turnId: TurnId.make("turn-1"), + createdAt, + ...(sequence !== undefined ? { sequence } : {}), + }) as unknown as OrchestrationThreadActivity; const baseEventFields = { eventId: EventId.make("event-1"), @@ -697,4 +717,64 @@ describe("applyThreadDetailEvent", () => { expect(result.kind).toBe("unchanged"); }); }); + + describe("liveWindowOldestActivityId", () => { + it("returns null for an empty window", () => { + expect(liveWindowOldestActivityId([])).toBeNull(); + }); + + it("returns the chronologically-oldest id regardless of array position", () => { + // Reducer order places the unsequenced legacy row (oldest) LAST while the + // server snapshot would list it first; the helper picks it either way. + const window = [ + activity("seq-1", "2026-04-01T10:00:01.000Z", 1), + activity("seq-2", "2026-04-01T10:00:02.000Z", 2), + activity("legacy", "2026-04-01T09:00:00.000Z"), + ]; + expect(liveWindowOldestActivityId(window)).toBe("legacy"); + }); + + it("breaks createdAt ties by id", () => { + const window = [ + activity("b", "2026-04-01T10:00:00.000Z", 2), + activity("a", "2026-04-01T10:00:00.000Z", 1), + ]; + expect(liveWindowOldestActivityId(window)).toBe("a"); + }); + + it("is stable when a newer activity is appended (no false reshape)", () => { + const before = [ + activity("legacy", "2026-04-01T09:00:00.000Z"), + activity("seq-1", "2026-04-01T10:00:01.000Z", 1), + ]; + // A live append is the newest activity and is unsequenced in the payload; + // it must not change the detected oldest boundary. + const after = [ + ...before, + activity("appended", "2026-04-01T11:00:00.000Z"), + ]; + expect(liveWindowOldestActivityId(after)).toBe(liveWindowOldestActivityId(before)); + expect(liveWindowOldestActivityId(after)).toBe("legacy"); + }); + }); + + describe("oldestActivityByChronology", () => { + it("returns null for an empty set", () => { + expect(oldestActivityByChronology([])).toBeNull(); + }); + + it("returns the unsequenced legacy row so the pagination cursor agrees with the sentinel", () => { + // The reducer placed the legacy (unsequenced, oldest) row at the END; paging + // must cursor from it (createdAt cursor), not from index 0's sequenced row. + const merged = [ + activity("seq-5", "2026-04-01T10:00:05.000Z", 5), + activity("seq-6", "2026-04-01T10:00:06.000Z", 6), + activity("legacy", "2026-04-01T09:00:00.000Z"), + ]; + const oldest = oldestActivityByChronology(merged); + expect(oldest?.id).toBe("legacy"); + expect(oldest?.sequence).toBeUndefined(); // → drives the unsequenced cursor + expect(liveWindowOldestActivityId(merged)).toBe(oldest?.id); // sentinel agrees + }); + }); }); diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts index 670540fee7..37ae19b44d 100644 --- a/packages/client-runtime/src/state/threadReducer.ts +++ b/packages/client-runtime/src/state/threadReducer.ts @@ -35,6 +35,45 @@ const activityOrder = O.combineAll([ O.mapInput(O.String, (a) => a.id), ]); +/** + * The oldest activity in a set, by chronology (`createdAt`, then `id`) rather + * than array position. + * + * `activities[0]` is not a stable "oldest": {@link activityOrder} sorts + * unsequenced rows to the end (a missing `sequence` is treated as newest) while + * the server snapshot lists legacy unsequenced rows first, so the first live + * append re-sorts the array and shifts index 0. Both the lazy-load *reshape* + * sentinel ({@link liveWindowOldestActivityId}) and the lazy-load *pagination + * cursor* derive from this so they agree on which row is oldest regardless of + * the reducer's placement of unsequenced rows. Returns `null` when empty. + */ +export function oldestActivityByChronology( + activities: ReadonlyArray, +): OrchestrationThreadActivity | null { + let oldest: OrchestrationThreadActivity | null = null; + for (const activity of activities) { + if ( + oldest === null || + activity.createdAt < oldest.createdAt || + (activity.createdAt === oldest.createdAt && activity.id < oldest.id) + ) { + oldest = activity; + } + } + return oldest; +} + +/** + * The id of {@link oldestActivityByChronology}, used as the lazy-load reshape + * sentinel (a reconnect re-snapshot or checkpoint revert changes it; a plain + * append does not). Returns `null` when empty. + */ +export function liveWindowOldestActivityId( + activities: ReadonlyArray, +): OrchestrationThreadActivity["id"] | null { + return oldestActivityByChronology(activities)?.id ?? null; +} + /** * Apply a single orchestration event to an `OrchestrationThread`, returning * the updated thread, a deletion signal, or an "unchanged" marker when the