Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions FORK.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1501,6 +1501,7 @@ function ThreadDetailBody(
freeze={freeze}
anchorMessageId={anchorMessageId}
jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
historyJumpPending={jumpMessageId !== null}
onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
keyboardOffset={composerKeyboardOffset}
Expand Down
96 changes: 76 additions & 20 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<unknown>;
/** Loads earlier history down to the entry, in one request. */
readonly onLoadThrough: (entryId: string) => void;
}
Expand Down Expand Up @@ -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<number>;
readonly keyboardOffset: number;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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={
<>
Expand All @@ -3993,7 +4041,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
<WorktreePreparingHeader />
) : null}
{props.historyControls ? (
<ThreadFeedLoadEarlierControl {...props.historyControls} />
<ThreadFeedHistoryStatus key={feedThreadKey} {...props.historyControls} />
) : null}
</>
}
Expand Down Expand Up @@ -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 (
<View className="mb-3 items-center gap-1.5 px-2">
{props.hasMoreHistory ? (
<View className="self-center">
<Button
label={props.loading ? "Loading earlier activity…" : "Load earlier activity"}
tone="secondary"
accessibilityLabel="Load earlier activity"
disabled={props.loading}
onPress={props.onLoadEarlier}
icon="chevron.up"
loading={props.loading}
/>
</View>
) : null}
<View className="min-h-6 items-center justify-center gap-1.5 px-2">
{props.error !== null ? (
<Text className="text-center text-xs" style={{ color: mutedColor }}>
{props.error}
<>
<Text
accessibilityLiveRegion="polite"
className="text-center text-xs"
style={{ color: mutedColor }}
>
{props.error}
</Text>
{props.hasMoreHistory ? (
<Button label="Retry" tone="secondary" onPress={() => void props.onLoadEarlier()} />
) : null}
</>
) : (
<Text
accessibilityLiveRegion="polite"
className="text-center text-xs"
style={{ color: mutedColor }}
>
{loadingLabel}
</Text>
) : null}
)}
</View>
);
}
Expand Down
8 changes: 4 additions & 4 deletions apps/mobile/src/features/threads/ThreadRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -434,15 +434,15 @@ function ThreadRouteContent(
return undefined;
}
return {
cursor: history.historyCursor,
hasMoreHistory: history.hasMoreHistory,
loading: history.loading,
error: history.error,
onLoadEarlier: () => {
void loadEarlierHistory({
onLoadEarlier: () =>
loadEarlierHistory({
environmentId: selectedThread.environmentId,
input: { threadId: selectedThread.id },
});
},
}),
onLoadThrough: (throughEntryId: string) => {
void loadEarlierHistory({
environmentId: selectedThread.environmentId,
Expand Down
24 changes: 24 additions & 0 deletions apps/mobile/src/lib/threadActivity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2161,6 +2161,30 @@ describe("streamed feed updates", () => {
});
});

it("keeps an expanded work group anchored when earlier tools load", () => {
const commands = ["older", "first", "second"].map((id, index) =>
projected({ ...command(), id: TurnItemId.make(id), ordinal: index + 1 }, index + 1),
);
const render = (items: typeof commands, expandedWorkGroupIds = new Set<string>()) =>
deriveThreadFeedPresentation(
buildThreadFeed(items),
null,
new Set([runId]),
expandedWorkGroupIds,
"2026-06-20T00:00:02.000Z",
);
const recent = commands.slice(1);
const toggle = render(recent).find((row) => row.type === "work-toggle")!;
const expanded = new Set([toggle.groupId]);
const before = render(recent, expanded);
const after = render(commands, expanded);
expect(after.find((row) => row.id === toggle.id)).toMatchObject({ expanded: true });
const detail = before.find((row) => row.type === "activity-group")!;
expect(after.find((row) => row.id === detail.id)).toMatchObject({
activities: detail.activities.map(({ id }) => expect.objectContaining({ id })),
});
});

it.each([false, true])(
"caps live approval headers while preserving the prompt (grouped: %s)",
(grouped) => {
Expand Down
22 changes: 17 additions & 5 deletions apps/mobile/src/lib/threadActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ const presentedActivityGroupsCache = new WeakMap<
readonly activeRunId: RunId | null;
readonly isWorking: boolean;
readonly activeTail: boolean;
readonly expandedWorkGroupIds: ReadonlySet<string>;
readonly rows: ReadonlyArray<ThreadFeedEntry>;
}
>();
Expand Down Expand Up @@ -2002,13 +2003,15 @@ function appendPresentedFeedEntry(
cached.activeRunId !== activeRunId ||
cached.isWorking !== isWorking ||
cached.activeTail !== activeTail ||
cached.rows.some(
(row) => row.type === "work-toggle" && expandedWorkGroupIds.has(row.groupId) !== row.expanded,
)
(cached.expandedWorkGroupIds !== expandedWorkGroupIds &&
entry.activities.some(({ id }) => {
const key = `work-group:${id}`;
return cached!.expandedWorkGroupIds.has(key) !== expandedWorkGroupIds.has(key);
}))
) {
const rows: ThreadFeedEntry[] = [];
appendActivityGroupRows(rows, entry, expandedWorkGroupIds, activeRunId, isWorking, activeTail);
cached = { activeRunId, isWorking, activeTail, rows };
cached = { activeRunId, isWorking, activeTail, expandedWorkGroupIds, rows };
presentedActivityGroupsCache.set(entry, cached);
}
for (const row of cached.rows) {
Expand All @@ -2032,7 +2035,9 @@ function appendActivityGroupRows(
groupAnchorId = null;
continue;
}
groupAnchorId ??= activity.id;
if (groupAnchorId === null || expandedWorkGroupIds.has(`work-group:${activity.id}`)) {
groupAnchorId = activity.id;
}
groupAnchorIdByActivityId.set(activity.id, groupAnchorId);
}
const activities = entry.activities.filter(
Expand Down Expand Up @@ -2074,6 +2079,13 @@ function appendActivityGroupRows(
const item = activity.projectedItem.item;
const severeProviderError = item.type === "error" && item.status === "failed";
if (!activity.prominent && !severeProviderError && item.type !== "notification") {
const first = groupableRun[0];
if (
first &&
groupAnchorIdByActivityId.get(first.id) !== groupAnchorIdByActivityId.get(activity.id)
) {
flushGroupableRun(false);
}
groupableRun.push(activity);
continue;
}
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,7 @@ export default function ChatView(props: ChatViewProps) {
return undefined;
}
return {
cursor: serverThreadHistory.historyCursor,
hasMoreHistory: serverThreadHistory.hasMoreHistory,
loading: serverThreadHistory.loading,
error: serverThreadHistory.error,
Expand Down
Loading
Loading