Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Stabilize chat scroll anchoring after send (#3564)

Julius Marminge24abab789ec6
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 565ce2ae5..a82e7c49c 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -74,7 +74,7 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
-import { ThreadWorkLog } from "./thread-work-log";
+import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
@@ -655,7 +655,6 @@ function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
readonly copiedRowId: string | null;
- readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>;
readonly terminalAssistantMessageIds: ReadonlySet<string>;
readonly unsettledTurnId: TurnId | null;
@@ -698,6 +697,18 @@ function renderFeedEntry(
);
}
+ if (entry.type === "work-toggle") {
+ return (
+ <ThreadWorkGroupToggle
+ expanded={entry.expanded}
+ hiddenCount={entry.hiddenCount}
+ iconSubtleColor={iconSubtleColor}
+ onlyToolActivities={entry.onlyToolActivities}
+ onToggle={() => props.onToggleWorkGroup(entry.groupId)}
+ />
+ );
+ }
+
if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
@@ -825,11 +836,9 @@ function renderFeedEntry(
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
- expanded={props.expandedWorkGroups[entry.id] ?? false}
expandedRows={props.expandedWorkRows}
iconSubtleColor={iconSubtleColor}
onCopyRow={props.onCopyWorkRow}
- onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
onToggleRow={props.onToggleWorkRow}
/>
);
@@ -1110,9 +1119,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const foldSettleFrameRef = useRef<number | null>(null);
const foldSettleSecondFrameRef = useRef<number | null>(null);
+ const disclosureAnchorKeyRef = useRef<string | null>(null);
const previousLatestTurnRef = useRef(props.latestTurn);
const { width: viewportWidth } = useWindowDimensions();
- const [foldToggleSettling, setFoldToggleSettling] = useState(false);
+ const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1173,7 +1183,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = useMemo(
() => ({
copiedRowId,
- expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1182,7 +1191,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
- expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1190,9 +1198,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
userBubbleColor,
],
);
+ const expandedWorkGroupIds = useMemo(() => {
+ const ids = new Set<string>();
+ for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
+ if (expanded) {
+ ids.add(groupId);
+ }
+ }
+ return ids;
+ }, [expandedWorkGroups]);
const presentedFeed = useMemo(
- () => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
- [expandedTurnIds, props.feed, props.latestTurn],
+ () =>
+ deriveThreadFeedPresentation(
+ props.feed,
+ props.latestTurn,
+ expandedTurnIds,
+ expandedWorkGroupIds,
+ ),
+ [expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
const anchoredEndSpace = useMemo(
() =>
@@ -1259,6 +1282,39 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
};
}, []);
+ const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
+ disclosureAnchorKeyRef.current = anchorKey;
+ setDisclosureToggleSettling(true);
+ if (foldSettleFrameRef.current !== null) {
+ cancelAnimationFrame(foldSettleFrameRef.current);
+ }
+ if (foldSettleSecondFrameRef.current !== null) {
+ cancelAnimationFrame(foldSettleSecondFrameRef.current);
+ }
+ foldSettleFrameRef.current = requestAnimationFrame(() => {
+ foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
+ disclosureAnchorKeyRef.current = null;
+ setDisclosureToggleSettling(false);
+ foldSettleFrameRef.current = null;
+ foldSettleSecondFrameRef.current = null;
+ });
+ });
+ }, []);
+
+ const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
+ const disclosureAnchorKey = disclosureAnchorKeyRef.current;
+ return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
+ }, []);
+
+ const maintainVisibleContentPosition = useMemo(
+ () => ({
+ data: true,
+ size: true,
+ shouldRestorePosition: shouldRestoreVisibleContentPosition,
+ }),
+ [shouldRestoreVisibleContentPosition],
+ );
+
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
copyTextWithHaptic(value, {
target: "thread-work-row",
@@ -1276,51 +1332,49 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, 1200);
}, []);
- const onToggleWorkGroup = useCallback((groupId: string) => {
- setInteractionState((current) => ({
- ...current,
- expandedWorkGroups: {
- ...current.expandedWorkGroups,
- [groupId]: !(current.expandedWorkGroups[groupId] ?? false),
- },
- }));
- }, []);
+ const onToggleWorkGroup = useCallback(
+ (groupId: string) => {
+ suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
+ setInteractionState((current) => ({
+ ...current,
+ expandedWorkGroups: {
+ ...current.expandedWorkGroups,
+ [groupId]: !(current.expandedWorkGroups[groupId] ?? false),
+ },
+ }));
+ },
+ [suspendEndScrollMaintenanceForDisclosure],
+ );
- const onToggleWorkRow = useCallback((rowId: string) => {
- setInteractionState((current) => ({
- ...current,
- expandedWorkRows: {
- ...current.expandedWorkRows,
- [rowId]: !(current.expandedWorkRows[rowId] ?? false),
- },
- }));
- }, []);
+ const onToggleWorkRow = useCallback(
+ (rowId: string) => {
+ suspendEndScrollMaintenanceForDisclosure(rowId);
+ setInteractionState((current) => ({
+ ...current,
+ expandedWorkRows: {
+ ...current.expandedWorkRows,
+ [rowId]: !(current.expandedWorkRows[rowId] ?? false),
+ },
+ }));
+ },
+ [suspendEndScrollMaintenanceForDisclosure],
+ );
- const onToggleTurnFold = useCallback((turnId: TurnId) => {
- setFoldToggleSettling(true);
- if (foldSettleFrameRef.current !== null) {
- cancelAnimationFrame(foldSettleFrameRef.current);
- }
- if (foldSettleSecondFrameRef.current !== null) {
- cancelAnimationFrame(foldSettleSecondFrameRef.current);
- }
- setInteractionState((current) => {
- const next = new Set(current.expandedTurnIds);
- if (next.has(turnId)) {
- next.delete(turnId);
- } else {
- next.add(turnId);
- }
- return { ...current, expandedTurnIds: next };
- });
- foldSettleFrameRef.current = requestAnimationFrame(() => {
- foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
- setFoldToggleSettling(false);
- foldSettleFrameRef.current = null;
- foldSettleSecondFrameRef.current = null;
+ const onToggleTurnFold = useCallback(
+ (turnId: TurnId) => {
+ suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
+ setInteractionState((current) => {
+ const next = new Set(current.expandedTurnIds);
+ if (next.has(turnId)) {
+ next.delete(turnId);
+ } else {
+ next.add(turnId);
+ }
+ return { ...current, expandedTurnIds: next };
});
- });
- }, []);
+ },
+ [suspendEndScrollMaintenanceForDisclosure],
+ );
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
setExpandedImage({ uri, headers });
@@ -1331,7 +1385,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
renderFeedEntry(info, {
environmentId: props.environmentId,
copiedRowId,
- expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1351,7 +1404,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
- expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1410,7 +1462,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
- foldToggleSettling
+ disclosureToggleSettling
? false
: {
animated: false,
@@ -1421,7 +1473,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
},
}
}
- maintainVisibleContentPosition
+ maintainVisibleContentPosition={maintainVisibleContentPosition}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx
index 707e1a24f..a788f8a40 100644
--- a/apps/mobile/src/features/threads/thread-work-log.tsx
+++ b/apps/mobile/src/features/threads/thread-work-log.tsx
@@ -6,7 +6,6 @@ import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
-const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
@@ -72,11 +71,9 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
- readonly expanded: boolean;
readonly expandedRows: Readonly<Record<string, boolean>>;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onCopyRow: (rowId: string, value: string) => void;
- readonly onToggleGroup: () => void;
readonly onToggleRow: (rowId: string) => void;
}) {
const colorScheme = useColorScheme();
@@ -89,14 +86,10 @@ export function ThreadWorkLog(props: {
return null;
}
- const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
- const visibleRows =
- hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
- const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
return (
- <View className="-mx-1 mb-3 px-1 py-0.5">
+ <View className="-mx-1 mb-1 px-1 py-0">
{!onlyToolRows ? (
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
work log
@@ -104,7 +97,7 @@ export function ThreadWorkLog(props: {
) : null}
<View className="gap-px">
- {visibleRows.map((row) => {
+ {rows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.fullDetail !== null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
@@ -132,13 +125,13 @@ export function ThreadWorkLog(props: {
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
- className="rounded-md px-0.5 py-0.5"
+ className="rounded-md px-0.5 py-0"
>
- <View className="min-h-9 flex-row items-center gap-1.5">
- <View className="h-5 w-5 shrink-0 items-center justify-center">
+ <View className="min-h-8 flex-row items-center gap-1.5">
+ <View className="h-[18px] w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
- size={14}
+ size={13}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
@@ -146,7 +139,7 @@ export function ThreadWorkLog(props: {
</View>
<Text
- className="min-w-0 flex-1 text-xs leading-5 text-foreground"
+ className="min-w-0 flex-1 text-xs leading-4 text-foreground"
numberOfLines={1}
>
<Text
@@ -199,7 +192,7 @@ export function ThreadWorkLog(props: {
</Pressable>
{expanded && row.fullDetail ? (
- <View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
+ <View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
directionalLockEnabled
@@ -221,41 +214,59 @@ export function ThreadWorkLog(props: {
);
})}
</View>
+ </View>
+ );
+}
- {hasOverflow ? (
- <Pressable
- accessibilityRole="button"
- accessibilityState={{ expanded: props.expanded }}
- accessibilityLabel={
- props.expanded
- ? "Show fewer tool calls"
- : `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
- }
- hitSlop={4}
- onPress={() => {
- triggerDisclosureFeedback();
- props.onToggleGroup();
- }}
- style={({ pressed }) => ({
- backgroundColor: pressed ? pressedBackground : "transparent",
- })}
- className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
- >
- <View className="h-5 w-5 items-center justify-center">
- <SymbolView
- name={props.expanded ? "chevron.up" : "chevron.down"}
- size={13}
- tintColor={props.iconSubtleColor}
- type="monochrome"
- />
- </View>
- <Text className="font-t3-medium text-xs text-foreground opacity-80">
- {props.expanded
- ? "Show fewer tool calls"
- : `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
- </Text>
- </Pressable>
- ) : null}
+export function ThreadWorkGroupToggle(props: {
+ readonly expanded: boolean;
+ readonly hiddenCount: number;
+ readonly iconSubtleColor: import("react-native").ColorValue;
+ readonly onlyToolActivities: boolean;
+ readonly onToggle: () => void;
+}) {
+ const colorScheme = useColorScheme();
+ const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
+ const noun = props.onlyToolActivities
+ ? props.hiddenCount === 1
+ ? "tool call"
+ : "tool calls"
+ : props.hiddenCount === 1
+ ? "log entry"
+ : "log entries";
+ const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
+ const expandedLabel = props.onlyToolActivities
+ ? "Show fewer tool calls"
+ : "Show fewer log entries";
+
+ return (
+ <View className="-mx-1 mb-1 px-1 py-0">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ expanded: props.expanded }}
+ accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
+ hitSlop={4}
+ onPress={() => {
+ void Haptics.selectionAsync();
+ props.onToggle();
+ }}
+ style={({ pressed }) => ({
+ backgroundColor: pressed ? pressedBackground : "transparent",
+ })}
+ className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
+ >
+ <View className="h-[18px] w-5 items-center justify-center">
+ <SymbolView
+ name={props.expanded ? "chevron.up" : "chevron.down"}
+ size={12}
+ tintColor={props.iconSubtleColor}
+ type="monochrome"
+ />
+ </View>
+ <Text className="font-t3-medium text-xs text-foreground opacity-80">
+ {props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
+ </Text>
+ </Pressable>
</View>
);
}
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
index e093acee3..23b47fc62 100644
--- a/apps/mobile/src/lib/threadActivity.test.ts
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -11,7 +11,12 @@ import {
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
-import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
+import {
+ buildThreadFeed,
+ deriveThreadFeedPresentation,
+ type ThreadFeedActivity,
+ type ThreadFeedEntry,
+} from "./threadActivity";
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
@@ -406,4 +411,58 @@ describe("buildThreadFeed", () => {
activities: [{ status: "failure" }],
});
});
+
+ it("models work-log overflow as list rows", () => {
+ const activity = (
+ id: string,
+ createdAt: string,
+ status: ThreadFeedActivity["status"] = "success",
+ ): ThreadFeedActivity => ({
+ id,
+ createdAt,
+ turnId: null,
+ summary: `Tool ${id}`,
+ detail: null,
+ fullDetail: null,
+ copyText: id,
+ icon: "command",
+ toolLike: true,
+ status,
+ });
+ const feed: ThreadFeedEntry[] = [
+ {
+ type: "activity-group",
+ id: "work-group-1",
+ createdAt: "2026-04-01T00:00:01.000Z",
+ turnId: null,
+ activities: [
+ activity("activity-1", "2026-04-01T00:00:01.000Z"),
+ activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
+ activity("activity-2", "2026-04-01T00:00:03.000Z"),
+ activity("activity-3", "2026-04-01T00:00:04.000Z"),
+ ],
+ },
+ ];
+
+ const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
+ expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
+ expect(collapsed[1]).toMatchObject({
+ type: "work-toggle",
+ groupId: "work-group-1",
+ hiddenCount: 2,
+ expanded: false,
+ });
+
+ const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
+ expect(expanded.map((entry) => entry.id)).toEqual([
+ "activity-1",
+ "activity-2",
+ "activity-3",
+ "work-toggle:work-group-1",
+ ]);
+ expect(expanded.at(-1)).toMatchObject({
+ type: "work-toggle",
+ expanded: true,
+ });
+ });
});
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index f6008057a..9f79a9055 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -55,6 +55,8 @@ export interface ThreadFeedActivity {
readonly status: "success" | "failure" | "neutral" | null;
}
+const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
+
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
interface WorkLogEntry {
@@ -103,6 +105,16 @@ export type ThreadFeedEntry =
readonly turnId: TurnId | null;
readonly activities: ReadonlyArray<ThreadFeedActivity>;
}
+ | {
+ readonly type: "work-toggle";
+ readonly id: string;
+ readonly createdAt: string;
+ readonly turnId: TurnId | null;
+ readonly groupId: string;
+ readonly hiddenCount: number;
+ readonly expanded: boolean;
+ readonly onlyToolActivities: boolean;
+ }
| {
readonly type: "turn-fold";
readonly id: string;
@@ -1092,8 +1104,11 @@ export function deriveThreadFeedPresentation(
feed: ReadonlyArray<ThreadFeedEntry>,
latestTurn: ThreadFeedLatestTurn | null,
expandedTurnIds: ReadonlySet<TurnId>,
+ expandedWorkGroupIds: ReadonlySet<string> = new Set(),
): ThreadFeedEntry[] {
- const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold");
+ const sourceFeed = feed.filter(
+ (entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
+ );
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
const collapsedEntryIds = new Set<string>();
for (const fold of foldsByAnchorId.values()) {
@@ -1118,12 +1133,62 @@ export function deriveThreadFeedPresentation(
});
}
if (!collapsedEntryIds.has(entry.id)) {
- result.push(entry);
+ appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
}
}
return result;
}
+function appendPresentedFeedEntry(
+ result: ThreadFeedEntry[],
+ entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
+ expandedWorkGroupIds: ReadonlySet<string>,
+): void {
+ if (entry.type !== "activity-group") {
+ result.push(entry);
+ return;
+ }
+
+ const activities = entry.activities.filter(
+ (activity) => !(activity.toolLike && activity.status === "neutral"),
+ );
+ if (activities.length === 0) {
+ return;
+ }
+ if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
+ result.push({
+ ...entry,
+ activities,
+ });
+ return;
+ }
+
+ const groupId = entry.id;
+ const expanded = expandedWorkGroupIds.has(groupId);
+ const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
+ const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
+
+ for (const activity of visibleActivities) {
+ result.push({
+ type: "activity-group",
+ id: activity.id,
+ createdAt: activity.createdAt,
+ turnId: activity.turnId,
+ activities: [activity],
+ });
+ }
+ result.push({
+ type: "work-toggle",
+ id: `work-toggle:${groupId}`,
+ createdAt: entry.createdAt,
+ turnId: entry.turnId,
+ groupId,
+ hiddenCount,
+ expanded,
+ onlyToolActivities: activities.every((activity) => activity.toolLike),
+ });
+}
+
export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index d9ae6e481..4f99fb5d5 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -36,6 +36,7 @@ import {
createModelSelection,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
+import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
@@ -3147,10 +3148,83 @@ function ChatViewContent(props: ChatViewProps) {
],
);
- // Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
+ // Scrolling is explicit so streamed timeline updates never take control away
+ // from the user after the newly sent row has been positioned once.
const scrollToEnd = useCallback((animated = false) => {
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
+ const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
+ const settledTimelineAnchorRef = useRef<MessageId | null>(null);
+ const pendingAnchorScrollRestoreRef = useRef<{
+ readonly messageId: MessageId;
+ readonly offset: number;
+ } | null>(null);
+ const anchorScrollRestoreFrameRef = useRef<number | null>(null);
+ const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
+ if (positionedTimelineAnchorRef.current === messageId) {
+ return;
+ }
+ positionedTimelineAnchorRef.current = messageId;
+ settledTimelineAnchorRef.current = null;
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ if (positionedTimelineAnchorRef.current !== messageId) {
+ return;
+ }
+ const list = legendListRef.current;
+ if (!list) {
+ return;
+ }
+ const scrollNode = list.getScrollableNode();
+ let finished = false;
+ const finishAnimatedPositioning = () => {
+ if (finished) {
+ return;
+ }
+ finished = true;
+ window.clearTimeout(fallbackTimer);
+ scrollNode.removeEventListener("scrollend", finishAnimatedPositioning);
+ if (positionedTimelineAnchorRef.current !== messageId) {
+ return;
+ }
+ const scrollOffset = list.getState().scroll;
+ void list.scrollToOffset({ offset: scrollOffset, animated: false });
+ settledTimelineAnchorRef.current = messageId;
+ };
+ const fallbackTimer = window.setTimeout(finishAnimatedPositioning, 750);
+ scrollNode.addEventListener("scrollend", finishAnimatedPositioning, { once: true });
+ void list.scrollToIndex({
+ index: anchorIndex,
+ animated: true,
+ viewPosition: 0,
+ viewOffset: CHAT_LIST_ANCHOR_OFFSET,
+ });
+ });
+ });
+ }, []);
+ const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
+ if (settledTimelineAnchorRef.current !== messageId) {
+ return;
+ }
+ const scrollOffset = legendListRef.current?.getState().scroll;
+ if (scrollOffset === undefined) {
+ return;
+ }
+ if (pendingAnchorScrollRestoreRef.current === null) {
+ pendingAnchorScrollRestoreRef.current = { messageId, offset: scrollOffset };
+ }
+ if (anchorScrollRestoreFrameRef.current !== null) {
+ return;
+ }
+ anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
+ anchorScrollRestoreFrameRef.current = null;
+ const pending = pendingAnchorScrollRestoreRef.current;
+ pendingAnchorScrollRestoreRef.current = null;
+ if (pending && settledTimelineAnchorRef.current === pending.messageId) {
+ void legendListRef.current?.scrollToOffset({ offset: pending.offset, animated: false });
+ }
+ });
+ }, []);
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
// thread switches. LegendList fires scroll events with isAtEnd=false while
@@ -3751,8 +3825,6 @@ function ChatViewContent(props: ChatViewProps) {
streaming: false,
},
]);
- void legendListRef.current?.scrollToEnd?.({ animated: false });
-
setThreadError(threadIdForSend, null);
if (expiredTerminalContextCount > 0) {
const toastCopy = buildExpiredTerminalContextToastCopy(
@@ -4165,11 +4237,14 @@ function ChatViewContent(props: ChatViewProps) {
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
- // Scroll to the current end *before* adding the optimistic message.
+ // Position this sent row once LegendList has measured the anchored tail.
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
- await legendListRef.current?.scrollToEnd?.({ animated: false });
+ setTimelineAnchor({
+ threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
+ messageId: messageIdForSend,
+ });
setOptimisticUserMessages((existing) => [
...existing,
@@ -4789,6 +4864,8 @@ function ChatViewContent(props: ChatViewProps) {
workspaceRoot={activeWorkspaceRoot}
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
anchorMessageId={timelineAnchorMessageId}
+ onAnchorReady={onTimelineAnchorReady}
+ onAnchorSizeChanged={onTimelineAnchorSizeChanged}
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
/>
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 1676d2d7c..6d74204bc 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -940,6 +940,77 @@ describe("deriveMessagesTimelineRows", () => {
expect(assistantRow?.showAssistantMeta).toBe(false);
expect(assistantRow?.showAssistantCopyButton).toBe(false);
});
+
+ it("models work log overflow expansion as inserted list rows", () => {
+ const timelineEntries = [
+ {
+ id: "work-entry-1",
+ kind: "work" as const,
+ createdAt: "2026-01-01T00:00:01Z",
+ entry: {
+ id: "work-1",
+ createdAt: "2026-01-01T00:00:01Z",
+ label: "read",
+ detail: "Reading package.json",
+ tone: "tool" as const,
+ },
+ },
+ {
+ id: "work-entry-2",
+ kind: "work" as const,
+ createdAt: "2026-01-01T00:00:02Z",
+ entry: {
+ id: "work-2",
+ createdAt: "2026-01-01T00:00:02Z",
+ label: "edit",
+ detail: "Editing MessagesTimeline.tsx",
+ tone: "tool" as const,
+ },
+ },
+ {
+ id: "work-entry-3",
+ kind: "work" as const,
+ createdAt: "2026-01-01T00:00:03Z",
+ entry: {
+ id: "work-3",
+ createdAt: "2026-01-01T00:00:03Z",
+ label: "test",
+ detail: "Running tests",
+ tone: "tool" as const,
+ },
+ },
+ ];
+
+ const baseInput = {
+ timelineEntries,
+ isWorking: false,
+ activeTurnStartedAt: null,
+ turnDiffSummaryByAssistantMessageId: new Map(),
+ revertTurnCountByUserMessageId: new Map(),
+ };
+ const collapsedRows = deriveMessagesTimelineRows(baseInput);
+ const expandedRows = deriveMessagesTimelineRows({
+ ...baseInput,
+ expandedWorkGroupIds: new Set(["work-group:work-entry-1"]),
+ });
+
+ expect(collapsedRows.map((row) => row.id)).toEqual(["work-3", "work-toggle:work-entry-1"]);
+ expect(collapsedRows.find((row) => row.kind === "work-toggle")).toMatchObject({
+ groupId: "work-group:work-entry-1",
+ hiddenCount: 2,
+ expanded: false,
+ onlyToolEntries: true,
+ });
+ expect(expandedRows.map((row) => row.id)).toEqual([
+ "work-1",
+ "work-2",
+ "work-3",
+ "work-toggle:work-entry-1",
+ ]);
+ expect(expandedRows.find((row) => row.kind === "work-toggle")).toMatchObject({
+ expanded: true,
+ });
+ });
});
describe("computeStableMessagesTimelineRows", () => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index 86212576f..d93ec0d03 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -1,5 +1,11 @@
import * as Equal from "effect/Equal";
-import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
+import {
+ formatDuration,
+ workEntryIndicatesToolNeutralStatus,
+ workLogEntryIsToolLike,
+ type TimelineEntry,
+ type WorkLogEntry,
+} from "../../session-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
@@ -42,6 +48,15 @@ export type MessagesTimelineRow =
createdAt: string;
groupedEntries: WorkLogEntry[];
}
+ | {
+ kind: "work-toggle";
+ id: string;
+ createdAt: string;
+ groupId: string;
+ hiddenCount: number;
+ expanded: boolean;
+ onlyToolEntries: boolean;
+ }
| {
kind: "turn-fold";
id: string;
@@ -300,6 +315,7 @@ export function deriveMessagesTimelineRows(input: {
latestTurn?: TimelineLatestTurn | null;
runningTurnId?: TurnId | null;
expandedTurnIds?: ReadonlySet<TurnId>;
+ expandedWorkGroupIds?: ReadonlySet<string>;
isWorking: boolean;
activeTurnStartedAt: string | null;
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
@@ -367,12 +383,44 @@ export function deriveMessagesTimelineRows(input: {
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
- nextRows.push({
- kind: "work",
- id: timelineEntry.id,
- createdAt: timelineEntry.createdAt,
- groupedEntries,
- });
+ const visibleGroupedEntries = groupedEntries.filter(
+ (entry) => !workEntryIndicatesToolNeutralStatus(entry),
+ );
+ if (visibleGroupedEntries.length > 0) {
+ if (visibleGroupedEntries.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
+ nextRows.push({
+ kind: "work",
+ id: timelineEntry.id,
+ createdAt: timelineEntry.createdAt,
+ groupedEntries: visibleGroupedEntries,
+ });
+ } else {
+ const groupId = `work-group:${timelineEntry.id}`;
+ const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
+ const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
+ const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
+ const renderedEntries = expanded ? [...hiddenEntries, ...visibleEntries] : visibleEntries;
+
+ for (const workEntry of renderedEntries) {
+ nextRows.push({
+ kind: "work",
+ id: workEntry.id,
+ createdAt: workEntry.createdAt,
+ groupedEntries: [workEntry],
+ });
+ }
+
+ nextRows.push({
+ kind: "work-toggle",
+ id: `work-toggle:${timelineEntry.id}`,
+ createdAt: timelineEntry.createdAt,
+ groupId,
+ hiddenCount: hiddenEntries.length,
+ expanded,
+ onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),
+ });
+ }
+ }
index = cursor - 1;
continue;
}
@@ -473,6 +521,17 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "work":
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
+ case "work-toggle": {
+ const bw = b as typeof a;
+ return (
+ a.createdAt === bw.createdAt &&
+ a.groupId === bw.groupId &&
+ a.hiddenCount === bw.hiddenCount &&
+ a.expanded === bw.expanded &&
+ a.onlyToolEntries === bw.onlyToolEntries
+ );
+ }
+
case "message": {
const bm = b as typeof a;
return (
diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx
index a69ce17c7..55ef6bfd5 100644
--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx
@@ -17,24 +17,59 @@ vi.mock("@legendapp/list/react", async () => {
anchorIndex: number;
anchorMaxSize?: number;
anchorOffset?: number;
+ onReady?: (info: { anchorIndex: number }) => void;
+ onSizeChanged?: (size: number) => void;
};
contentInsetEndAdjustment?: number;
+ className?: string;
+ maintainScrollAtEnd?: boolean;
+ maintainVisibleContentPosition?:
+ | boolean
+ | {
+ data?: boolean;
+ size?: boolean;
+ shouldRestorePosition?: (item: { id: string }) => boolean;
+ };
ref?: Ref<LegendListRef>;
- }) => (
- <div
- data-testid={legendListTestId}
- data-anchor-index={props.anchoredEndSpace?.anchorIndex}
- data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
- data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
- data-content-inset-end={props.contentInsetEndAdjustment}
- >
- {props.ListHeaderComponent}
- {props.data.map((item) => (
- <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
- ))}
- {props.ListFooterComponent}
- </div>
- );
+ }) => {
+ if (props.anchoredEndSpace) {
+ props.anchoredEndSpace.onSizeChanged?.(240);
+ props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
+ }
+ return (
+ <div
+ data-testid={legendListTestId}
+ data-anchor-index={props.anchoredEndSpace?.anchorIndex}
+ data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
+ data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
+ data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
+ data-content-inset-end={props.contentInsetEndAdjustment}
+ data-class-name={props.className}
+ data-maintain-scroll-at-end={props.maintainScrollAtEnd}
+ data-maintain-visible-content-position={
+ typeof props.maintainVisibleContentPosition === "object"
+ ? "object"
+ : props.maintainVisibleContentPosition
+ }
+ data-maintain-visible-content-position-data={
+ typeof props.maintainVisibleContentPosition === "object"
+ ? props.maintainVisibleContentPosition.data
+ : undefined
+ }
+ data-maintain-visible-content-position-size={
+ typeof props.maintainVisibleContentPosition === "object"
+ ? props.maintainVisibleContentPosition.size
+ : undefined
+ }
+ >
+ {props.ListHeaderComponent}
+ {props.data.map((item) => (
+ <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
+ ))}
+ {props.ListFooterComponent}
+ </div>
+ );
+ };
return { LegendList };
});
@@ -123,6 +158,8 @@ function buildProps() {
timestampFormat: "locale" as const,
workspaceRoot: undefined,
anchorMessageId: null,
+ onAnchorReady: () => {},
+ onAnchorSizeChanged: () => {},
contentInsetEndAdjustment: 0,
onIsAtEndChange: () => {},
};
@@ -154,6 +191,8 @@ function buildUserTimelineEntry(text: string) {
describe("MessagesTimeline", () => {
it("anchors a sent attachment message using its measured height", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
+ const onAnchorReady = vi.fn();
+ const onAnchorSizeChanged = vi.fn();
const firstEntry = buildUserTimelineEntry("First prompt.");
const secondEntry = {
...buildUserTimelineEntry("Newest prompt."),
@@ -177,6 +216,8 @@ describe("MessagesTimeline", () => {
<MessagesTimeline
{...buildProps()}
anchorMessageId={secondEntry.message.id}
+ onAnchorReady={onAnchorReady}
+ onAnchorSizeChanged={onAnchorSizeChanged}
contentInsetEndAdjustment={144}
timelineEntries={[firstEntry, secondEntry]}
/>,
@@ -184,8 +225,17 @@ describe("MessagesTimeline", () => {
expect(markup).toContain('data-anchor-index="1"');
expect(markup).toContain('data-anchor-offset="16"');
+ expect(markup).toContain('data-anchor-on-ready="true"');
expect(markup).not.toContain("data-anchor-max-size=");
expect(markup).toContain('data-content-inset-end="144"');
+ expect(markup).toContain("[overflow-anchor:none]");
+ expect(markup).not.toContain("data-maintain-scroll-at-end=");
+ expect(markup).toContain('data-maintain-visible-content-position="object"');
+ expect(markup).toContain('data-maintain-visible-content-position-data="true"');
+ expect(markup).toContain('data-maintain-visible-content-position-size="false"');
+ expect(onAnchorReady).toHaveBeenCalledOnce();
+ expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
+ expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
});
it("renders collapse controls for long user messages", async () => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index cf8224d51..0134f5493 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -14,13 +14,13 @@ import {
use,
useCallback,
useEffect,
- useLayoutEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
+import { flushSync } from "react-dom";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { FileDiff } from "@pierre/diffs/react";
import {
@@ -43,7 +43,6 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
- ChevronUpIcon,
CircleAlertIcon,
EyeIcon,
GlobeIcon,
@@ -67,7 +66,6 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
- MAX_VISIBLE_WORK_LOG_ENTRIES,
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
@@ -128,6 +126,7 @@ interface TimelineRowSharedState {
onImageExpand: (preview: ExpandedImagePreview) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
+ onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;
}
interface TimelineRowActivityState {
@@ -168,6 +167,8 @@ interface MessagesTimelineProps {
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
anchorMessageId: MessageId | null;
+ onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
+ onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
}
@@ -198,20 +199,15 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
anchorMessageId,
+ onAnchorReady,
+ onAnchorSizeChanged,
contentInsetEndAdjustment,
onIsAtEndChange,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
+ const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
- // Toggling a fold inserts/removes rows between the fold row and the final
- // message — everything above the trigger is unchanged, so the trigger stays
- // put as long as the list doesn't re-anchor. maintainScrollAtEnd would do
- // exactly that (pin the bottom content when row data changes while scrolled
- // to the end), yanking the trigger out of view. Suppress it for the frames
- // in which the toggle's data change and item measurements settle.
- const [foldToggleSettling, setFoldToggleSettling] = useState(false);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
- setFoldToggleSettling(true);
setExpandedTurnIds((existing) => {
const next = new Set(existing);
if (next.has(turnId)) {
@@ -222,23 +218,39 @@ export const MessagesTimeline = memo(function MessagesTimeline({
return next;
});
}, []);
- useEffect(() => {
- if (!foldToggleSettling) {
- return;
- }
- let secondFrameId: number | null = null;
- const firstFrameId = window.requestAnimationFrame(() => {
- secondFrameId = window.requestAnimationFrame(() => {
- setFoldToggleSettling(false);
+ const onToggleWorkGroup = useCallback(
+ (groupId: string, anchorElement?: HTMLElement) => {
+ const anchorBottomBeforeToggle = anchorElement?.getBoundingClientRect().bottom ?? null;
+
+ flushSync(() => {
+ setExpandedWorkGroupIds((existing) => {
+ const next = new Set(existing);
+ if (next.has(groupId)) {
+ next.delete(groupId);
+ } else {
+ next.add(groupId);
+ }
+ return next;
+ });
});
- });
- return () => {
- window.cancelAnimationFrame(firstFrameId);
- if (secondFrameId !== null) {
- window.cancelAnimationFrame(secondFrameId);
+
+ if (anchorBottomBeforeToggle === null || !anchorElement) {
+ return;
}
- };
- }, [foldToggleSettling]);
+
+ const delta = anchorElement.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
+ if (Math.abs(delta) < 0.5) {
+ return;
+ }
+
+ const list = listRef.current;
+ const currentScroll = list?.getState?.().scroll;
+ if (list && typeof currentScroll === "number") {
+ list.scrollToOffset({ offset: currentScroll + delta, animated: false });
+ }
+ },
+ [listRef],
+ );
// An in-session interrupt leaves its turn expanded so the user keeps their
// place; the next turn (or a reload, since this is local state) folds it.
@@ -276,6 +288,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
latestTurn,
runningTurnId,
expandedTurnIds,
+ expandedWorkGroupIds,
isWorking,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
@@ -286,6 +299,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
latestTurn,
runningTurnId,
expandedTurnIds,
+ expandedWorkGroupIds,
isWorking,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
@@ -293,13 +307,30 @@ export const MessagesTimeline = memo(function MessagesTimeline({
],
);
const rows = useStableRows(rawRows);
- const anchoredEndSpace = useMemo(
- () =>
- resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
- row.kind === "message" ? row.message.id : null,
- ),
- [anchorMessageId, rows],
+ const handleAnchorReady = useCallback(
+ (info: { anchorIndex: number | undefined }) => {
+ if (anchorMessageId !== null && info.anchorIndex !== undefined) {
+ onAnchorReady(anchorMessageId, info.anchorIndex);
+ }
+ },
+ [anchorMessageId, onAnchorReady],
+ );
+ const handleAnchorSizeChanged = useCallback(
+ (size: number) => {
+ if (anchorMessageId !== null) {
+ onAnchorSizeChanged(anchorMessageId, size);
+ }
+ },
+ [anchorMessageId, onAnchorSizeChanged],
);
+ const anchoredEndSpace = useMemo(() => {
+ const config = resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
+ row.kind === "message" ? row.message.id : null,
+ );
+ return config
+ ? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged }
+ : undefined;
+ }, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]);
const handleScroll = useCallback(() => {
const state = listRef.current?.getState?.();
@@ -322,6 +353,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onImageExpand,
onOpenTurnDiff,
onToggleTurnFold,
+ onToggleWorkGroup,
}),
[
timestampFormat,
@@ -335,6 +367,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onImageExpand,
onOpenTurnDiff,
onToggleTurnFold,
+ onToggleWorkGroup,
],
);
const activityState = useMemo<TimelineRowActivityState>(
@@ -380,11 +413,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
- maintainScrollAtEnd={!foldToggleSettling}
- maintainScrollAtEndThreshold={0.1}
- maintainVisibleContentPosition
+ maintainVisibleContentPosition={{
+ data: true,
+ size: false,
+ }}
onScroll={handleScroll}
- className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
+ 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}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
@@ -417,7 +451,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
// Commentary (non-terminal assistant) rows carry no metadata row, so
// they sit closer to the work that follows them.
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
- row.kind === "work"
+ row.kind === "work" ||
+ row.kind === "work-toggle"
? "pb-2"
: "pb-4",
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
@@ -428,6 +463,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
data-message-role={row.kind === "message" ? row.message.role : undefined}
>
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
+ {row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "assistant" ? (
@@ -720,26 +756,17 @@ function WorkingTimer({ createdAt }: { createdAt: string }) {
// re-render only the affected row, not the entire list.
// ---------------------------------------------------------------------------
-/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */
+/** Renders one or more already-derived work log rows. Overflow expansion is modeled as LegendList data. */
const WorkGroupSection = memo(function WorkGroupSection({
groupedEntries,
}: {
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
}) {
const { workspaceRoot } = use(TimelineRowCtx);
- const [isExpanded, setIsExpanded] = useState(false);
- const sectionRef = useRef<HTMLElement>(null);
- const anchorBottomBeforeToggleRef = useRef<number | null>(null);
const nonEmptyEntries = useMemo(
() => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)),
[groupedEntries],
);
- const hasOverflow = nonEmptyEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
- const visibleEntries =
- hasOverflow && !isExpanded
- ? nonEmptyEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
- : nonEmptyEntries;
- const hiddenCount = nonEmptyEntries.length - visibleEntries.length;
const onlyToolEntries = nonEmptyEntries.every((entry) => workLogEntryIsToolLike(entry));
const groupLabel = onlyToolEntries
? nonEmptyEntries.length === 1
@@ -747,49 +774,17 @@ const WorkGroupSection = memo(function WorkGroupSection({
: `${nonEmptyEntries.length} tool calls`
: "Work Log";
- useLayoutEffect(() => {
- const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
- anchorBottomBeforeToggleRef.current = null;
-
- if (anchorBottomBeforeToggle === null) {
- return;
- }
-
- const section = sectionRef.current;
- if (!section) {
- return;
- }
-
- const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
- if (Math.abs(delta) < 0.5) {
- return;
- }
-
- const scroller = findNearestVerticalScroller(section);
- if (scroller) {
- scroller.scrollTop += delta;
- } else {
- window.scrollBy(0, delta);
- }
- }, [isExpanded]);
-
- const toggleExpanded = () => {
- anchorBottomBeforeToggleRef.current =
- sectionRef.current?.getBoundingClientRect().bottom ?? null;
- setIsExpanded((v) => !v);
- };
-
if (nonEmptyEntries.length === 0) return null;
return (
- <section ref={sectionRef} className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
+ <section className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
{!onlyToolEntries && (
<p className="px-0.5 pb-0.5 font-medium text-[11px] text-muted-foreground/65">
{groupLabel}
</p>
)}
<div className="space-y-px">
- {visibleEntries.map((workEntry) => (
+ {nonEmptyEntries.map((workEntry) => (
<SimpleWorkEntryRow
key={workEntry.id}
workEntry={workEntry}
@@ -797,45 +792,49 @@ const WorkGroupSection = memo(function WorkGroupSection({
/>
))}
</div>
- {hasOverflow && (
- <button
- type="button"
- className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
- onClick={toggleExpanded}
- >
- <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
- {isExpanded ? (
- <ChevronUpIcon className="size-3.5 shrink-0 opacity-70" />
- ) : (
- <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
- )}
- </span>
- {isExpanded ? (
- <span className="font-medium text-foreground/82">Show fewer tool calls</span>
- ) : (
- <span className="font-medium text-foreground/82">
- +{hiddenCount} previous tool {hiddenCount === 1 ? "call" : "calls"}
- </span>
- )}
- </button>
- )}
</section>
);
});
-function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null {
- let parent = element.parentElement;
- while (parent) {
- const { overflowY } = window.getComputedStyle(parent);
- if (
- (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") &&
- parent.scrollHeight > parent.clientHeight
- ) {
- return parent;
- }
- parent = parent.parentElement;
- }
- return null;
+function WorkGroupToggleTimelineRow({
+ row,
+}: {
+ row: Extract<TimelineRow, { kind: "work-toggle" }>;
+}) {
+ const ctx = use(TimelineRowCtx);
+ const labelNoun = row.onlyToolEntries ? "tool call" : "log entry";
+
+ return (
+ <button
+ type="button"
+ className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
+ aria-expanded={row.expanded}
+ onClick={(event) => {
+ const anchorElement =
+ event.currentTarget.closest<HTMLElement>("[data-timeline-row-id]") ?? event.currentTarget;
+ ctx.onToggleWorkGroup(row.groupId, anchorElement);
+ }}
+ >
+ <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
+ <ChevronDownIcon
+ className={cn(
+ "size-3.5 shrink-0 opacity-70 transition-transform duration-200",
+ row.expanded && "rotate-180",
+ )}
+ />
+ </span>
+ {row.expanded ? (
+ <span className="font-medium text-foreground/82">
+ Show fewer {row.onlyToolEntries ? "tool calls" : "log entries"}
+ </span>
+ ) : (
+ <span className="font-medium text-foreground/82">
+ +{row.hiddenCount} previous {labelNoun}
+ {row.hiddenCount === 1 ? "" : "s"}
+ </span>
+ )}
+ </button>
+ );
}
/** Subscribes directly to the UI state store for expand/collapse state,