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.

fix: stabilize messages timeline virtualization (#1664)

Julius Marminge867cf4cf091b
diff --git a/apps/web/src/components/chat/ChangedFilesTree.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.test.tsx
new file mode 100644
index 000000000..5b72fd237
--- /dev/null
+++ b/apps/web/src/components/chat/ChangedFilesTree.test.tsx
@@ -0,0 +1,116 @@
+import { TurnId } from "@t3tools/contracts";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+
+import { ChangedFilesTree } from "./ChangedFilesTree";
+
+describe("ChangedFilesTree", () => {
+ it.each([
+ {
+ name: "a compacted single-chain directory",
+ files: [
+ { path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
+ { path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
+ ],
+ visibleLabels: ["apps/web/src"],
+ hiddenLabels: ["index.ts", "main.ts"],
+ },
+ {
+ name: "a branch point after a compacted prefix",
+ files: [
+ { path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
+ { path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
+ ],
+ visibleLabels: ["apps/server/src"],
+ hiddenLabels: ["git", "provider", "GitCore.ts", "CodexAdapter.ts"],
+ },
+ {
+ name: "mixed root files and nested compacted directories",
+ files: [
+ { path: "README.md", additions: 1, deletions: 0 },
+ { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
+ { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
+ ],
+ visibleLabels: ["README.md", "packages"],
+ hiddenLabels: ["shared/src", "contracts/src", "git.ts", "orchestration.ts"],
+ },
+ ])(
+ "renders $name collapsed on the first render when collapse-all is active",
+ ({ files, visibleLabels, hiddenLabels }) => {
+ const markup = renderToStaticMarkup(
+ <ChangedFilesTree
+ turnId={TurnId.makeUnsafe("turn-1")}
+ files={files}
+ allDirectoriesExpanded={false}
+ resolvedTheme="light"
+ onOpenTurnDiff={() => {}}
+ />,
+ );
+
+ for (const label of visibleLabels) {
+ expect(markup).toContain(label);
+ }
+ for (const label of hiddenLabels) {
+ expect(markup).not.toContain(label);
+ }
+ },
+ );
+
+ it.each([
+ {
+ name: "a compacted single-chain directory",
+ files: [
+ { path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
+ { path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
+ ],
+ visibleLabels: ["apps/web/src", "index.ts", "main.ts"],
+ },
+ {
+ name: "a branch point after a compacted prefix",
+ files: [
+ { path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
+ { path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
+ ],
+ visibleLabels: [
+ "apps/server/src",
+ "git/Layers",
+ "provider/Layers",
+ "GitCore.ts",
+ "CodexAdapter.ts",
+ ],
+ },
+ {
+ name: "mixed root files and nested compacted directories",
+ files: [
+ { path: "README.md", additions: 1, deletions: 0 },
+ { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
+ { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
+ ],
+ visibleLabels: [
+ "README.md",
+ "packages",
+ "shared/src",
+ "contracts/src",
+ "git.ts",
+ "orchestration.ts",
+ ],
+ },
+ ])(
+ "renders $name expanded on the first render when expand-all is active",
+ ({ files, visibleLabels }) => {
+ const markup = renderToStaticMarkup(
+ <ChangedFilesTree
+ turnId={TurnId.makeUnsafe("turn-1")}
+ files={files}
+ allDirectoriesExpanded
+ resolvedTheme="light"
+ onOpenTurnDiff={() => {}}
+ />,
+ );
+
+ for (const label of visibleLabels) {
+ expect(markup).toContain(label);
+ }
+ },
+ );
+});
diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx
index a13ddad30..29bd96ea0 100644
--- a/apps/web/src/components/chat/ChangedFilesTree.tsx
+++ b/apps/web/src/components/chat/ChangedFilesTree.tsx
@@ -1,5 +1,5 @@
import { type TurnId } from "@t3tools/contracts";
-import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import { memo, useCallback, useMemo, useState } from "react";
import { type TurnDiffFileChange } from "../../types";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
@@ -7,6 +7,8 @@ import { cn } from "~/lib/utils";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { VscodeEntryIcon } from "./VscodeEntryIcon";
+const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
+
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
@@ -20,32 +22,39 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
() => collectDirectoryPaths(treeNodes).join("\u0000"),
[treeNodes],
);
- const allDirectoryExpansionState = useMemo(
- () =>
- buildDirectoryExpansionState(
- directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
- allDirectoriesExpanded,
- ),
- [allDirectoriesExpanded, directoryPathsKey],
- );
- const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(() =>
- buildDirectoryExpansionState(directoryPathsKey ? directoryPathsKey.split("\u0000") : [], true),
- );
- useEffect(() => {
- setExpandedDirectories(allDirectoryExpansionState);
- }, [allDirectoryExpansionState]);
+ const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
+ const [directoryExpansionState, setDirectoryExpansionState] = useState<{
+ key: string;
+ overrides: Record<string, boolean>;
+ }>(() => ({
+ key: expansionStateKey,
+ overrides: {},
+ }));
+ const expandedDirectories =
+ directoryExpansionState.key === expansionStateKey
+ ? directoryExpansionState.overrides
+ : EMPTY_DIRECTORY_OVERRIDES;
- const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
- setExpandedDirectories((current) => ({
- ...current,
- [pathValue]: !(current[pathValue] ?? fallbackExpanded),
- }));
- }, []);
+ const toggleDirectory = useCallback(
+ (pathValue: string) => {
+ setDirectoryExpansionState((current) => {
+ const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
+ return {
+ key: expansionStateKey,
+ overrides: {
+ ...nextOverrides,
+ [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
+ },
+ };
+ });
+ },
+ [allDirectoriesExpanded, expansionStateKey],
+ );
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
- const isExpanded = expandedDirectories[node.path] ?? depth === 0;
+ const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
return (
<div key={`dir:${node.path}`}>
<button
@@ -53,7 +62,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
- onClick={() => toggleDirectory(node.path, depth === 0)}
+ onClick={() => toggleDirectory(node.path)}
>
<ChevronRightIcon
aria-hidden="true"
@@ -124,14 +133,3 @@ function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[]
}
return paths;
}
-
-function buildDirectoryExpansionState(
- directoryPaths: ReadonlyArray<string>,
- expanded: boolean,
-): Record<string, boolean> {
- const expandedState: Record<string, boolean> = {};
- for (const directoryPath of directoryPaths) {
- expandedState[directoryPath] = expanded;
- }
- return expandedState;
-}
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index 726d61888..16b02ea9b 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -1,3 +1,11 @@
+import { type MessageId } from "@t3tools/contracts";
+import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
+import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
+import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
+import { estimateTimelineMessageHeight } from "../timelineHeight";
+
+export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
+
export interface TimelineDurationMessage {
id: string;
role: "user" | "assistant" | "system";
@@ -5,6 +13,29 @@ export interface TimelineDurationMessage {
completedAt?: string | undefined;
}
+export type MessagesTimelineRow =
+ | {
+ kind: "work";
+ id: string;
+ createdAt: string;
+ groupedEntries: WorkLogEntry[];
+ }
+ | {
+ kind: "message";
+ id: string;
+ createdAt: string;
+ message: ChatMessage;
+ durationStart: string;
+ showCompletionDivider: boolean;
+ }
+ | {
+ kind: "proposed-plan";
+ id: string;
+ createdAt: string;
+ proposedPlan: ProposedPlan;
+ }
+ | { kind: "working"; id: string; createdAt: string | null };
+
export function computeMessageDurationStart(
messages: ReadonlyArray<TimelineDurationMessage>,
): Map<string, string> {
@@ -27,3 +58,142 @@ export function computeMessageDurationStart(
export function normalizeCompactToolLabel(value: string): string {
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
}
+
+export function deriveMessagesTimelineRows(input: {
+ timelineEntries: ReadonlyArray<TimelineEntry>;
+ completionDividerBeforeEntryId: string | null;
+ isWorking: boolean;
+ activeTurnStartedAt: string | null;
+}): MessagesTimelineRow[] {
+ const nextRows: MessagesTimelineRow[] = [];
+ const durationStartByMessageId = computeMessageDurationStart(
+ input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
+ );
+
+ for (let index = 0; index < input.timelineEntries.length; index += 1) {
+ const timelineEntry = input.timelineEntries[index];
+ if (!timelineEntry) {
+ continue;
+ }
+
+ if (timelineEntry.kind === "work") {
+ const groupedEntries = [timelineEntry.entry];
+ let cursor = index + 1;
+ while (cursor < input.timelineEntries.length) {
+ const nextEntry = input.timelineEntries[cursor];
+ if (!nextEntry || nextEntry.kind !== "work") break;
+ groupedEntries.push(nextEntry.entry);
+ cursor += 1;
+ }
+ nextRows.push({
+ kind: "work",
+ id: timelineEntry.id,
+ createdAt: timelineEntry.createdAt,
+ groupedEntries,
+ });
+ index = cursor - 1;
+ continue;
+ }
+
+ if (timelineEntry.kind === "proposed-plan") {
+ nextRows.push({
+ kind: "proposed-plan",
+ id: timelineEntry.id,
+ createdAt: timelineEntry.createdAt,
+ proposedPlan: timelineEntry.proposedPlan,
+ });
+ continue;
+ }
+
+ nextRows.push({
+ kind: "message",
+ id: timelineEntry.id,
+ createdAt: timelineEntry.createdAt,
+ message: timelineEntry.message,
+ durationStart:
+ durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
+ showCompletionDivider:
+ timelineEntry.message.role === "assistant" &&
+ input.completionDividerBeforeEntryId === timelineEntry.id,
+ });
+ }
+
+ if (input.isWorking) {
+ nextRows.push({
+ kind: "working",
+ id: "working-indicator-row",
+ createdAt: input.activeTurnStartedAt,
+ });
+ }
+
+ return nextRows;
+}
+
+export function estimateMessagesTimelineRowHeight(
+ row: MessagesTimelineRow,
+ input: {
+ timelineWidthPx: number | null;
+ expandedWorkGroups?: Readonly<Record<string, boolean>>;
+ turnDiffSummaryByAssistantMessageId?: ReadonlyMap<MessageId, TurnDiffSummary>;
+ },
+): number {
+ switch (row.kind) {
+ case "work":
+ return estimateWorkRowHeight(row, input);
+ case "proposed-plan":
+ return estimateTimelineProposedPlanHeight(row.proposedPlan);
+ case "working":
+ return 40;
+ case "message": {
+ let estimate = estimateTimelineMessageHeight(row.message, {
+ timelineWidthPx: input.timelineWidthPx,
+ });
+ const turnDiffSummary = input.turnDiffSummaryByAssistantMessageId?.get(row.message.id);
+ if (turnDiffSummary && turnDiffSummary.files.length > 0) {
+ estimate += estimateChangedFilesCardHeight(turnDiffSummary);
+ }
+ return estimate;
+ }
+ }
+}
+
+function estimateWorkRowHeight(
+ row: Extract<MessagesTimelineRow, { kind: "work" }>,
+ input: {
+ expandedWorkGroups?: Readonly<Record<string, boolean>>;
+ },
+): number {
+ const isExpanded = input.expandedWorkGroups?.[row.id] ?? false;
+ const hasOverflow = row.groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
+ const visibleEntries =
+ hasOverflow && !isExpanded ? MAX_VISIBLE_WORK_LOG_ENTRIES : row.groupedEntries.length;
+ const onlyToolEntries = row.groupedEntries.every((entry) => entry.tone === "tool");
+ const showHeader = hasOverflow || !onlyToolEntries;
+
+ // Card chrome, optional header, and one compact work-entry row per visible entry.
+ return 28 + (showHeader ? 26 : 0) + visibleEntries * 32;
+}
+
+function estimateTimelineProposedPlanHeight(proposedPlan: ProposedPlan): number {
+ const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
+ return 120 + Math.min(estimatedLines * 22, 880);
+}
+
+function estimateChangedFilesCardHeight(turnDiffSummary: TurnDiffSummary): number {
+ const treeNodes = buildTurnDiffTree(turnDiffSummary.files);
+ const visibleNodeCount = countTurnDiffTreeNodes(treeNodes);
+
+ // Card chrome: top/bottom padding, header row, and tree spacing.
+ return 60 + visibleNodeCount * 25;
+}
+
+function countTurnDiffTreeNodes(nodes: ReadonlyArray<TurnDiffTreeNode>): number {
+ let count = 0;
+ for (const node of nodes) {
+ count += 1;
+ if (node.kind === "directory") {
+ count += countTurnDiffTreeNodes(node.children);
+ }
+ }
+ return count;
+}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 9e0b89591..8cb8b8968 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -35,13 +35,18 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { clamp } from "effect/Number";
-import { estimateTimelineMessageHeight } from "../timelineHeight";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
-import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
+import {
+ MAX_VISIBLE_WORK_LOG_ENTRIES,
+ deriveMessagesTimelineRows,
+ estimateMessagesTimelineRowHeight,
+ normalizeCompactToolLabel,
+ type MessagesTimelineRow,
+} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import {
deriveDisplayedUserMessageState,
@@ -56,7 +61,6 @@ import {
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
-const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
interface MessagesTimelineProps {
@@ -81,6 +85,17 @@ interface MessagesTimelineProps {
resolvedTheme: "light" | "dark";
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
+ onVirtualizerSnapshot?: (snapshot: {
+ totalSize: number;
+ measurements: ReadonlyArray<{
+ id: string;
+ kind: MessagesTimelineRow["kind"];
+ index: number;
+ size: number;
+ start: number;
+ end: number;
+ }>;
+ }) => void;
}
export const MessagesTimeline = memo(function MessagesTimeline({
@@ -105,6 +120,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
timestampFormat,
workspaceRoot,
+ onVirtualizerSnapshot,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
@@ -134,70 +150,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
};
}, [hasMessages, isWorking]);
- const rows = useMemo<TimelineRow[]>(() => {
- const nextRows: TimelineRow[] = [];
- const durationStartByMessageId = computeMessageDurationStart(
- timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
- );
-
- for (let index = 0; index < timelineEntries.length; index += 1) {
- const timelineEntry = timelineEntries[index];
- if (!timelineEntry) {
- continue;
- }
-
- if (timelineEntry.kind === "work") {
- const groupedEntries = [timelineEntry.entry];
- let cursor = index + 1;
- while (cursor < timelineEntries.length) {
- const nextEntry = timelineEntries[cursor];
- if (!nextEntry || nextEntry.kind !== "work") break;
- groupedEntries.push(nextEntry.entry);
- cursor += 1;
- }
- nextRows.push({
- kind: "work",
- id: timelineEntry.id,
- createdAt: timelineEntry.createdAt,
- groupedEntries,
- });
- index = cursor - 1;
- continue;
- }
-
- if (timelineEntry.kind === "proposed-plan") {
- nextRows.push({
- kind: "proposed-plan",
- id: timelineEntry.id,
- createdAt: timelineEntry.createdAt,
- proposedPlan: timelineEntry.proposedPlan,
- });
- continue;
- }
-
- nextRows.push({
- kind: "message",
- id: timelineEntry.id,
- createdAt: timelineEntry.createdAt,
- message: timelineEntry.message,
- durationStart:
- durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
- showCompletionDivider:
- timelineEntry.message.role === "assistant" &&
- completionDividerBeforeEntryId === timelineEntry.id,
- });
- }
-
- if (isWorking) {
- nextRows.push({
- kind: "working",
- id: "working-indicator-row",
- createdAt: activeTurnStartedAt,
- });
- }
-
- return nextRows;
- }, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
+ const rows = useMemo(
+ () =>
+ deriveMessagesTimelineRows({
+ timelineEntries,
+ completionDividerBeforeEntryId,
+ isWorking,
+ activeTurnStartedAt,
+ }),
+ [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt],
+ );
const firstUnvirtualizedRowIndex = useMemo(() => {
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
@@ -241,19 +203,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({
minimum: 0,
maximum: rows.length,
});
+ const virtualMeasurementScopeKey =
+ timelineWidthPx === null ? "width:unknown" : `width:${Math.round(timelineWidthPx)}`;
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainer,
- // Use stable row ids so virtual measurements do not leak across thread switches.
- getItemKey: (index: number) => rows[index]?.id ?? index,
+ // Scope cached row measurements to the current timeline width so offscreen
+ // rows do not keep stale heights after wrapping changes.
+ getItemKey: (index: number) => {
+ const rowId = rows[index]?.id ?? String(index);
+ return `${virtualMeasurementScopeKey}:${rowId}`;
+ },
estimateSize: (index: number) => {
const row = rows[index];
if (!row) return 96;
- if (row.kind === "work") return 112;
- if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan);
- if (row.kind === "working") return 40;
- return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
+ return estimateMessagesTimelineRowHeight(row, {
+ expandedWorkGroups,
+ timelineWidthPx,
+ turnDiffSummaryByAssistantMessageId,
+ });
},
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
@@ -295,6 +264,32 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
};
}, []);
+ useLayoutEffect(() => {
+ if (!onVirtualizerSnapshot) {
+ return;
+ }
+ onVirtualizerSnapshot({
+ totalSize: rowVirtualizer.getTotalSize(),
+ measurements: rowVirtualizer.measurementsCache
+ .slice(0, virtualizedRowCount)
+ .flatMap((measurement) => {
+ const row = rows[measurement.index];
+ if (!row) {
+ return [];
+ }
+ return [
+ {
+ id: row.id,
+ kind: row.kind,
+ index: measurement.index,
+ size: measurement.size,
+ start: measurement.start,
+ end: measurement.end,
+ },
+ ];
+ }),
+ });
+ }, [onVirtualizerSnapshot, rowVirtualizer, rows, virtualizedRowCount]);
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
@@ -311,6 +306,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const renderRowContent = (row: TimelineRow) => (
<div
className="pb-4"
+ data-timeline-row-id={row.id}
data-timeline-row-kind={row.kind}
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
@@ -585,6 +581,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div
key={`virtual-row:${row.id}`}
data-index={virtualRow.index}
+ data-virtual-row-id={row.id}
+ data-virtual-row-kind={row.kind}
+ data-virtual-row-size={virtualRow.size}
+ data-virtual-row-start={virtualRow.start}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 w-full"
style={{ transform: `translateY(${virtualRow.start}px)` }}
@@ -605,35 +605,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
-type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
-type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
-type TimelineRow =
- | {
- kind: "work";
- id: string;
- createdAt: string;
- groupedEntries: TimelineWorkEntry[];
- }
- | {
- kind: "message";
- id: string;
- createdAt: string;
- message: TimelineMessage;
- durationStart: string;
- showCompletionDivider: boolean;
- }
- | {
- kind: "proposed-plan";
- id: string;
- createdAt: string;
- proposedPlan: TimelineProposedPlan;
- }
- | { kind: "working"; id: string; createdAt: string | null };
-
-function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
- const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
- return 120 + Math.min(estimatedLines * 22, 880);
-}
+type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
+type TimelineRow = MessagesTimelineRow;
function formatWorkingTimer(startIso: string, endIso: string): string | null {
const startedAtMs = Date.parse(startIso);
diff --git a/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx b/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx
new file mode 100644
index 000000000..1e947a3c8
--- /dev/null
+++ b/apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx
@@ -0,0 +1,1037 @@
+import "../../index.css";
+
+import { MessageId, type TurnId } from "@t3tools/contracts";
+import { page } from "vitest/browser";
+import { useCallback, useState, type ComponentProps } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { render } from "vitest-browser-react";
+
+import { deriveTimelineEntries, type WorkLogEntry } from "../../session-logic";
+import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
+import { MessagesTimeline } from "./MessagesTimeline";
+import {
+ deriveMessagesTimelineRows,
+ estimateMessagesTimelineRowHeight,
+} from "./MessagesTimeline.logic";
+
+const DEFAULT_VIEWPORT = {
+ width: 960,
+ height: 1_100,
+};
+const MARKDOWN_CWD = "/repo/project";
+
+interface RowMeasurement {
+ actualHeightPx: number;
+ estimatedHeightPx: number;
+ timelineWidthPx: number;
+ virtualizerSizePx: number;
+ renderedInVirtualizedRegion: boolean;
+}
+
+interface VirtualizationScenario {
+ name: string;
+ targetRowId: string;
+ props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">;
+ maxEstimateDeltaPx: number;
+}
+
+interface VirtualizerSnapshot {
+ totalSize: number;
+ measurements: ReadonlyArray<{
+ id: string;
+ kind: string;
+ index: number;
+ size: number;
+ start: number;
+ end: number;
+ }>;
+}
+
+function MessagesTimelineBrowserHarness(
+ props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">,
+) {
+ const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(null);
+ const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>(
+ () => props.expandedWorkGroups,
+ );
+ const handleToggleWorkGroup = useCallback(
+ (groupId: string) => {
+ setExpandedWorkGroups((current) => ({
+ ...current,
+ [groupId]: !(current[groupId] ?? false),
+ }));
+ props.onToggleWorkGroup(groupId);
+ },
+ [props],
+ );
+
+ return (
+ <div
+ ref={setScrollContainer}
+ data-testid="messages-timeline-scroll-container"
+ className="h-full overflow-y-auto overscroll-y-contain"
+ >
+ <MessagesTimeline
+ {...props}
+ scrollContainer={scrollContainer}
+ expandedWorkGroups={expandedWorkGroups}
+ onToggleWorkGroup={handleToggleWorkGroup}
+ />
+ </div>
+ );
+}
+
+function isoAt(offsetSeconds: number): string {
+ return new Date(Date.UTC(2026, 2, 17, 19, 12, 28) + offsetSeconds * 1_000).toISOString();
+}
+
+function createMessage(input: {
+ id: string;
+ role: ChatMessage["role"];
+ text: string;
+ offsetSeconds: number;
+ attachments?: ChatMessage["attachments"];
+}): ChatMessage {
+ return {
+ id: MessageId.makeUnsafe(input.id),
+ role: input.role,
+ text: input.text,
+ ...(input.attachments ? { attachments: input.attachments } : {}),
+ createdAt: isoAt(input.offsetSeconds),
+ ...(input.role === "assistant" ? { completedAt: isoAt(input.offsetSeconds + 1) } : {}),
+ streaming: false,
+ };
+}
+
+function createToolWorkEntry(input: {
+ id: string;
+ offsetSeconds: number;
+ label?: string;
+ detail?: string;
+}): WorkLogEntry {
+ return {
+ id: input.id,
+ createdAt: isoAt(input.offsetSeconds),
+ label: input.label ?? "exec_command completed",
+ ...(input.detail ? { detail: input.detail } : {}),
+ tone: "tool",
+ toolTitle: "exec_command",
+ };
+}
+
+function createPlan(input: {
+ id: string;
+ offsetSeconds: number;
+ planMarkdown: string;
+}): ProposedPlan {
+ return {
+ id: input.id as ProposedPlan["id"],
+ turnId: null,
+ planMarkdown: input.planMarkdown,
+ implementedAt: null,
+ implementationThreadId: null,
+ createdAt: isoAt(input.offsetSeconds),
+ updatedAt: isoAt(input.offsetSeconds + 1),
+ };
+}
+
+function createBaseTimelineProps(input: {
+ messages?: ChatMessage[];
+ proposedPlans?: ProposedPlan[];
+ workEntries?: WorkLogEntry[];
+ expandedWorkGroups?: Record<string, boolean>;
+ completionDividerBeforeEntryId?: string | null;
+ turnDiffSummaryByAssistantMessageId?: Map<MessageId, TurnDiffSummary>;
+ onVirtualizerSnapshot?: ComponentProps<typeof MessagesTimeline>["onVirtualizerSnapshot"];
+}): Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer"> {
+ return {
+ hasMessages: true,
+ isWorking: false,
+ activeTurnInProgress: false,
+ activeTurnStartedAt: null,
+ timelineEntries: deriveTimelineEntries(
+ input.messages ?? [],
+ input.proposedPlans ?? [],
+ input.workEntries ?? [],
+ ),
+ completionDividerBeforeEntryId: input.completionDividerBeforeEntryId ?? null,
+ completionSummary: null,
+ turnDiffSummaryByAssistantMessageId: input.turnDiffSummaryByAssistantMessageId ?? new Map(),
+ nowIso: isoAt(10_000),
+ expandedWorkGroups: input.expandedWorkGroups ?? {},
+ onToggleWorkGroup: () => {},
+ onOpenTurnDiff: () => {},
+ revertTurnCountByUserMessageId: new Map(),
+ onRevertUserMessage: () => {},
+ isRevertingCheckpoint: false,
+ onImageExpand: () => {},
+ markdownCwd: MARKDOWN_CWD,
+ resolvedTheme: "light",
+ timestampFormat: "locale",
+ workspaceRoot: MARKDOWN_CWD,
+ ...(input.onVirtualizerSnapshot ? { onVirtualizerSnapshot: input.onVirtualizerSnapshot } : {}),
+ };
+}
+
+function createFillerMessages(input: {
+ prefix: string;
+ startOffsetSeconds: number;
+ pairCount: number;
+}): ChatMessage[] {
+ const messages: ChatMessage[] = [];
+ for (let index = 0; index < input.pairCount; index += 1) {
+ const baseOffset = input.startOffsetSeconds + index * 4;
+ messages.push(
+ createMessage({
+ id: `${input.prefix}-user-${index}`,
+ role: "user",
+ text: `filler user message ${index}`,
+ offsetSeconds: baseOffset,
+ }),
+ );
+ messages.push(
+ createMessage({
+ id: `${input.prefix}-assistant-${index}`,
+ role: "assistant",
+ text: `filler assistant message ${index}`,
+ offsetSeconds: baseOffset + 1,
+ }),
+ );
+ }
+ return messages;
+}
+
+function createChangedFilesSummary(
+ targetMessageId: MessageId,
+ files: TurnDiffSummary["files"],
+): Map<MessageId, TurnDiffSummary> {
+ return new Map([
+ [
+ targetMessageId,
+ {
+ turnId: "turn-changed-files" as TurnId,
+ completedAt: isoAt(10),
+ assistantMessageId: targetMessageId,
+ files,
+ },
+ ],
+ ]);
+}
+
+function createChangedFilesScenario(input: {
+ name: string;
+ rowId: string;
+ files: TurnDiffSummary["files"];
+ maxEstimateDeltaPx?: number;
+}): VirtualizationScenario {
+ const beforeMessages = createFillerMessages({
+ prefix: `${input.rowId}-before`,
+ startOffsetSeconds: 0,
+ pairCount: 2,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: `${input.rowId}-after`,
+ startOffsetSeconds: 40,
+ pairCount: 8,
+ });
+ const changedFilesMessage = createMessage({
+ id: input.rowId,
+ role: "assistant",
+ text: "Validation passed on the merged tree.",
+ offsetSeconds: 12,
+ });
+
+ return {
+ name: input.name,
+ targetRowId: changedFilesMessage.id,
+ props: createBaseTimelineProps({
+ messages: [...beforeMessages, changedFilesMessage, ...afterMessages],
+ turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(
+ changedFilesMessage.id,
+ input.files,
+ ),
+ }),
+ maxEstimateDeltaPx: input.maxEstimateDeltaPx ?? 72,
+ };
+}
+
+function createAssistantMessageScenario(input: {
+ name: string;
+ rowId: string;
+ text: string;
+ maxEstimateDeltaPx?: number;
+}): VirtualizationScenario {
+ const beforeMessages = createFillerMessages({
+ prefix: `${input.rowId}-before`,
+ startOffsetSeconds: 0,
+ pairCount: 2,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: `${input.rowId}-after`,
+ startOffsetSeconds: 40,
+ pairCount: 8,
+ });
+ const assistantMessage = createMessage({
+ id: input.rowId,
+ role: "assistant",
+ text: input.text,
+ offsetSeconds: 12,
+ });
+
+ return {
+ name: input.name,
+ targetRowId: assistantMessage.id,
+ props: createBaseTimelineProps({
+ messages: [...beforeMessages, assistantMessage, ...afterMessages],
+ }),
+ maxEstimateDeltaPx: input.maxEstimateDeltaPx ?? 16,
+ };
+}
+
+function buildStaticScenarios(): VirtualizationScenario[] {
+ const beforeMessages = createFillerMessages({
+ prefix: "before",
+ startOffsetSeconds: 0,
+ pairCount: 2,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: "after",
+ startOffsetSeconds: 40,
+ pairCount: 8,
+ });
+
+ const longUserMessage = createMessage({
+ id: "target-user-long",
+ role: "user",
+ text: "x".repeat(3_200),
+ offsetSeconds: 12,
+ });
+ const workEntries = Array.from({ length: 4 }, (_, index) =>
+ createToolWorkEntry({
+ id: `target-work-${index}`,
+ offsetSeconds: 12 + index,
+ detail: `tool output line ${index + 1}`,
+ }),
+ );
+ const moderatePlan = createPlan({
+ id: "target-plan",
+ offsetSeconds: 12,
+ planMarkdown: [
+ "# Stabilize virtualization",
+ "",
+ "- Gather baseline measurements",
+ "- Add browser harness coverage",
+ "- Compare estimated and rendered heights",
+ "- Fix the broken rows without broad refactors",
+ "- Re-run lint and typecheck",
+ ].join("\n"),
+ });
+ return [
+ {
+ name: "long user message",
+ targetRowId: longUserMessage.id,
+ props: createBaseTimelineProps({
+ messages: [...beforeMessages, longUserMessage, ...afterMessages],
+ }),
+ maxEstimateDeltaPx: 56,
+ },
+ {
+ name: "grouped work log row",
+ targetRowId: workEntries[0]!.id,
+ props: createBaseTimelineProps({
+ messages: [...beforeMessages, ...afterMessages],
+ workEntries,
+ }),
+ maxEstimateDeltaPx: 56,
+ },
+ {
+ name: "expanded grouped work log row with show more enabled",
+ targetRowId: "target-work-expanded-0",
+ props: createBaseTimelineProps({
+ messages: [...beforeMessages, ...afterMessages],
+ workEntries: Array.from({ length: 10 }, (_, index) =>
+ createToolWorkEntry({
+ id: `target-work-expanded-${index}`,
+ offsetSeconds: 12 + index,
+ detail: `tool output line ${index + 1}`,
+ }),
+ ),
+ expandedWorkGroups: {
+ "target-work-expanded-0": true,
+ },
+ }),
+ maxEstimateDeltaPx: 72,
+ },
+ {
+ name: "proposed plan row",
+ targetRowId: moderatePlan.id,
+ props: createBaseTimelineProps({
+ messages: [...beforeMessages, ...afterMessages],
+ proposedPlans: [moderatePlan],
+ }),
+ maxEstimateDeltaPx: 96,
+ },
+ createAssistantMessageScenario({
+ name: "assistant single-paragraph row with plain prose",
+ rowId: "target-assistant-plain-prose",
+ text: [
+ "The host is still expanding to content somewhere in the grid layout.",
+ "I'm stripping it back further to a plain block container so the test width",
+ "is actually the timeline width.",
+ ].join(" "),
+ }),
+ createAssistantMessageScenario({
+ name: "assistant single-paragraph row with inline code",
+ rowId: "target-assistant-inline-code",
+ text: [
+ "Typecheck found one exact-optional-property issue in the browser harness:",
+ "I was always passing `onVirtualizerSnapshot`, including `undefined`.",
+ "I'm tightening that object construction and rerunning the checks.",
+ ].join(" "),
+ maxEstimateDeltaPx: 28,
+ }),
+ createChangedFilesScenario({
+ name: "assistant changed-files row with a compacted single-chain directory",
+ rowId: "target-assistant-changed-files-single-chain",
+ files: [
+ { path: "apps/web/src/components/chat/ChangedFilesTree.tsx", additions: 37, deletions: 45 },
+ {
+ path: "apps/web/src/components/chat/ChangedFilesTree.test.tsx",
+ additions: 0,
+ deletions: 26,
+ },
+ ],
+ }),
+ createChangedFilesScenario({
+ name: "assistant changed-files row with a branch after compaction",
+ rowId: "target-assistant-changed-files-branch-point",
+ files: [
+ { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 },
+ { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 },
+ {
+ path: "apps/server/src/provider/Layers/CodexAdapter.ts",
+ additions: 27,
+ deletions: 8,
+ },
+ {
+ path: "apps/server/src/provider/Layers/CodexAdapter.test.ts",
+ additions: 36,
+ deletions: 0,
+ },
+ ],
+ }),
+ createChangedFilesScenario({
+ name: "assistant changed-files row with mixed root and nested entries",
+ rowId: "target-assistant-changed-files-mixed-root",
+ files: [
+ { path: "README.md", additions: 5, deletions: 1 },
+ { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
+ { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
+ ],
+ }),
+ ];
+}
+
+async function nextFrame(): Promise<void> {
+ await new Promise<void>((resolve) => {
+ window.requestAnimationFrame(() => resolve());
+ });
+}
+
+async function waitForLayout(): Promise<void> {
+ await nextFrame();
+ await nextFrame();
+ await nextFrame();
+}
+
+async function setViewport(viewport: { width: number; height: number }): Promise<void> {
+ await page.viewport(viewport.width, viewport.height);
+ await waitForLayout();
+}
+
+async function waitForProductionStyles(): Promise<void> {
+ await vi.waitFor(
+ () => {
+ expect(
+ getComputedStyle(document.documentElement).getPropertyValue("--background").trim(),
+ ).not.toBe("");
+ expect(getComputedStyle(document.body).marginTop).toBe("0px");
+ },
+ { timeout: 4_000, interval: 16 },
+ );
+}
+
+async function waitForElement<T extends Element>(
+ query: () => T | null,
+ errorMessage: string,
+): Promise<T> {
+ let element: T | null = null;
+ await vi.waitFor(
+ () => {
+ element = query();
+ expect(element, errorMessage).toBeTruthy();
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ if (!element) {
+ throw new Error(errorMessage);
+ }
+ return element;
+}
+
+async function measureTimelineRow(input: {
+ host: HTMLElement;
+ props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">;
+ targetRowId: string;
+}): Promise<RowMeasurement> {
+ const scrollContainer = await waitForElement(
+ () =>
+ input.host.querySelector<HTMLDivElement>(
+ '[data-testid="messages-timeline-scroll-container"]',
+ ),
+ "Unable to find MessagesTimeline scroll container.",
+ );
+
+ const rowSelector = `[data-timeline-row-id="${input.targetRowId}"]`;
+ const virtualRowSelector = `[data-virtual-row-id="${input.targetRowId}"]`;
+
+ let timelineWidthPx = 0;
+ let actualHeightPx = 0;
+ let virtualizerSizePx = 0;
+ let renderedInVirtualizedRegion = false;
+
+ await vi.waitFor(
+ async () => {
+ scrollContainer.scrollTop = 0;
+ scrollContainer.dispatchEvent(new Event("scroll"));
+ await waitForLayout();
+
+ const rowElement = input.host.querySelector<HTMLElement>(rowSelector);
+ const virtualRowElement = input.host.querySelector<HTMLElement>(virtualRowSelector);
+ const timelineRoot = input.host.querySelector<HTMLElement>('[data-timeline-root="true"]');
+
+ expect(rowElement, "Unable to locate target timeline row.").toBeTruthy();
+ expect(virtualRowElement, "Unable to locate target virtualized wrapper.").toBeTruthy();
+ expect(timelineRoot, "Unable to locate MessagesTimeline root.").toBeTruthy();
+
+ timelineWidthPx = timelineRoot!.getBoundingClientRect().width;
+ actualHeightPx = rowElement!.getBoundingClientRect().height;
+ virtualizerSizePx = Number.parseFloat(virtualRowElement!.dataset.virtualRowSize ?? "0");
+ renderedInVirtualizedRegion = virtualRowElement!.hasAttribute("data-index");
+
+ expect(timelineWidthPx).toBeGreaterThan(0);
+ expect(actualHeightPx).toBeGreaterThan(0);
+ expect(virtualizerSizePx).toBeGreaterThan(0);
+ expect(renderedInVirtualizedRegion).toBe(true);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const rows = deriveMessagesTimelineRows({
+ timelineEntries: input.props.timelineEntries,
+ completionDividerBeforeEntryId: input.props.completionDividerBeforeEntryId,
+ isWorking: input.props.isWorking,
+ activeTurnStartedAt: input.props.activeTurnStartedAt,
+ });
+ const targetRow = rows.find((row) => row.id === input.targetRowId);
+ expect(targetRow, `Unable to derive target row ${input.targetRowId}.`).toBeTruthy();
+
+ return {
+ actualHeightPx,
+ estimatedHeightPx: estimateMessagesTimelineRowHeight(targetRow!, {
+ expandedWorkGroups: input.props.expandedWorkGroups,
+ timelineWidthPx,
+ turnDiffSummaryByAssistantMessageId: input.props.turnDiffSummaryByAssistantMessageId,
+ }),
+ timelineWidthPx,
+ virtualizerSizePx,
+ renderedInVirtualizedRegion,
+ };
+}
+
+async function mountMessagesTimeline(input: {
+ props: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">;
+ viewport?: { width: number; height: number };
+}) {
+ const viewport = input.viewport ?? DEFAULT_VIEWPORT;
+ await setViewport(viewport);
+ await waitForProductionStyles();
+
+ const host = document.createElement("div");
+ host.style.width = `${viewport.width}px`;
+ host.style.minWidth = `${viewport.width}px`;
+ host.style.maxWidth = `${viewport.width}px`;
+ host.style.height = `${viewport.height}px`;
+ host.style.minHeight = `${viewport.height}px`;
+ host.style.maxHeight = `${viewport.height}px`;
+ host.style.display = "block";
+ host.style.overflow = "hidden";
+ document.body.append(host);
+
+ const screen = await render(<MessagesTimelineBrowserHarness {...input.props} />, {
+ container: host,
+ });
+ await waitForLayout();
+
+ return {
+ host,
+ rerender: async (
+ nextProps: Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer">,
+ ) => {
+ await screen.rerender(<MessagesTimelineBrowserHarness {...nextProps} />);
+ await waitForLayout();
+ },
+ setContainerSize: async (nextViewport: { width: number; height: number }) => {
+ await setViewport(nextViewport);
+ host.style.width = `${nextViewport.width}px`;
+ host.style.minWidth = `${nextViewport.width}px`;
+ host.style.maxWidth = `${nextViewport.width}px`;
+ host.style.height = `${nextViewport.height}px`;
+ host.style.minHeight = `${nextViewport.height}px`;
+ host.style.maxHeight = `${nextViewport.height}px`;
+ await waitForLayout();
+ },
+ cleanup: async () => {
+ await screen.unmount();
+ host.remove();
+ },
+ };
+}
+
+async function measureRenderedRowActualHeight(input: {
+ host: HTMLElement;
+ targetRowId: string;
+}): Promise<number> {
+ const rowElement = await waitForElement(
+ () => input.host.querySelector<HTMLElement>(`[data-timeline-row-id="${input.targetRowId}"]`),
+ `Unable to locate rendered row ${input.targetRowId}.`,
+ );
+ return rowElement.getBoundingClientRect().height;
+}
+
+describe("MessagesTimeline virtualization harness", () => {
+ beforeEach(async () => {
+ document.body.innerHTML = "";
+ await setViewport(DEFAULT_VIEWPORT);
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it.each(buildStaticScenarios())("keeps the $name estimate within tolerance", async (scenario) => {
+ const mounted = await mountMessagesTimeline({ props: scenario.props });
+
+ try {
+ const measurement = await measureTimelineRow({
+ host: mounted.host,
+ props: scenario.props,
+ targetRowId: scenario.targetRowId,
+ });
+
+ expect(
+ Math.abs(measurement.actualHeightPx - measurement.estimatedHeightPx),
+ `estimate delta for ${scenario.name}`,
+ ).toBeLessThanOrEqual(scenario.maxEstimateDeltaPx);
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("keeps the changed-files row virtualizer size in sync after collapsing directories", async () => {
+ const beforeMessages = createFillerMessages({
+ prefix: "before-collapse",
+ startOffsetSeconds: 0,
+ pairCount: 2,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: "after-collapse",
+ startOffsetSeconds: 40,
+ pairCount: 8,
+ });
+ const targetMessage = createMessage({
+ id: "target-assistant-collapse",
+ role: "assistant",
+ text: "Validation passed on the merged tree.",
+ offsetSeconds: 12,
+ });
+ const props = createBaseTimelineProps({
+ messages: [...beforeMessages, targetMessage, ...afterMessages],
+ turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(targetMessage.id, [
+ { path: ".plans/effect-atom.md", additions: 89, deletions: 0 },
+ {
+ path: "apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts",
+ additions: 4,
+ deletions: 3,
+ },
+ {
+ path: "apps/server/src/checkpointing/Layers/CheckpointStore.ts",
+ additions: 131,
+ deletions: 128,
+ },
+ {
+ path: "apps/server/src/checkpointing/Layers/CheckpointStore.test.ts",
+ additions: 1,
+ deletions: 1,
+ },
+ { path: "apps/server/src/checkpointing/Errors.ts", additions: 1, deletions: 1 },
+ {
+ path: "apps/server/src/git/Layers/ClaudeTextGeneration.ts",
+ additions: 106,
+ deletions: 112,
+ },
+ { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 },
+ { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 },
+ {
+ path: "apps/web/src/components/chat/MessagesTimeline.tsx",
+ additions: 52,
+ deletions: 7,
+ },
+ {
+ path: "apps/web/src/components/chat/ChangedFilesTree.tsx",
+ additions: 32,
+ deletions: 4,
+ },
+ { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
+ { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
+ ]),
+ });
+ const mounted = await mountMessagesTimeline({
+ props,
+ viewport: { width: 320, height: 700 },
+ });
+
+ try {
+ const beforeCollapse = await measureTimelineRow({
+ host: mounted.host,
+ props,
+ targetRowId: targetMessage.id,
+ });
+ const targetRowElement = mounted.host.querySelector<HTMLElement>(
+ `[data-timeline-row-id="${targetMessage.id}"]`,
+ );
+ expect(targetRowElement, "Unable to locate target changed-files row.").toBeTruthy();
+
+ const collapseAllButton =
+ Array.from(targetRowElement!.querySelectorAll<HTMLButtonElement>("button")).find(
+ (button) => button.textContent?.trim() === "Collapse all",
+ ) ?? null;
+ expect(collapseAllButton, 'Unable to find "Collapse all" button.').toBeTruthy();
+
+ collapseAllButton!.click();
+
+ await vi.waitFor(
+ async () => {
+ const afterCollapse = await measureTimelineRow({
+ host: mounted.host,
+ props,
+ targetRowId: targetMessage.id,
+ });
+ expect(afterCollapse.actualHeightPx).toBeLessThan(beforeCollapse.actualHeightPx - 24);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const afterCollapse = await measureTimelineRow({
+ host: mounted.host,
+ props,
+ targetRowId: targetMessage.id,
+ });
+ expect(
+ Math.abs(afterCollapse.actualHeightPx - afterCollapse.virtualizerSizePx),
+ ).toBeLessThanOrEqual(8);
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("keeps the work-log row virtualizer size in sync after show more expands the group", async () => {
+ const beforeMessages = createFillerMessages({
+ prefix: "before-worklog-expand",
+ startOffsetSeconds: 0,
+ pairCount: 2,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: "after-worklog-expand",
+ startOffsetSeconds: 40,
+ pairCount: 8,
+ });
+ const workEntries = Array.from({ length: 10 }, (_, index) =>
+ createToolWorkEntry({
+ id: `target-work-toggle-${index}`,
+ offsetSeconds: 12 + index,
+ detail: `tool output line ${index + 1}`,
+ }),
+ );
+ const props = createBaseTimelineProps({
+ messages: [...beforeMessages, ...afterMessages],
+ workEntries,
+ });
+ const mounted = await mountMessagesTimeline({ props });
+
+ try {
+ const beforeExpand = await measureTimelineRow({
+ host: mounted.host,
+ props,
+ targetRowId: workEntries[0]!.id,
+ });
+ const targetRowElement = mounted.host.querySelector<HTMLElement>(
+ `[data-timeline-row-id="${workEntries[0]!.id}"]`,
+ );
+ expect(targetRowElement, "Unable to locate target work-log row.").toBeTruthy();
+
+ const showMoreButton =
+ Array.from(targetRowElement!.querySelectorAll<HTMLButtonElement>("button")).find((button) =>
+ button.textContent?.includes("Show 4 more"),
+ ) ?? null;
+ expect(showMoreButton, 'Unable to find "Show more" button.').toBeTruthy();
+
+ showMoreButton!.click();
+
+ await vi.waitFor(
+ async () => {
+ const afterExpand = await measureTimelineRow({
+ host: mounted.host,
+ props,
+ targetRowId: workEntries[0]!.id,
+ });
+ expect(afterExpand.actualHeightPx).toBeGreaterThan(beforeExpand.actualHeightPx + 72);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const afterExpand = await measureTimelineRow({
+ host: mounted.host,
+ props,
+ targetRowId: workEntries[0]!.id,
+ });
+ expect(
+ Math.abs(afterExpand.actualHeightPx - afterExpand.virtualizerSizePx),
+ ).toBeLessThanOrEqual(8);
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("preserves measured tail row heights when rows transition into virtualization", async () => {
+ const beforeMessages = createFillerMessages({
+ prefix: "tail-transition-before",
+ startOffsetSeconds: 0,
+ pairCount: 1,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: "tail-transition-after",
+ startOffsetSeconds: 40,
+ pairCount: 3,
+ });
+ const targetMessage = createMessage({
+ id: "target-tail-transition",
+ role: "assistant",
+ text: "Validation passed on the merged tree.",
+ offsetSeconds: 12,
+ });
+ let latestSnapshot: VirtualizerSnapshot | null = null;
+ const initialProps = createBaseTimelineProps({
+ messages: [...beforeMessages, targetMessage, ...afterMessages],
+ turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(targetMessage.id, [
+ { path: ".plans/effect-atom.md", additions: 89, deletions: 0 },
+ {
+ path: "apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts",
+ additions: 4,
+ deletions: 3,
+ },
+ {
+ path: "apps/server/src/checkpointing/Layers/CheckpointStore.ts",
+ additions: 131,
+ deletions: 128,
+ },
+ {
+ path: "apps/server/src/checkpointing/Layers/CheckpointStore.test.ts",
+ additions: 1,
+ deletions: 1,
+ },
+ { path: "apps/server/src/checkpointing/Errors.ts", additions: 1, deletions: 1 },
+ {
+ path: "apps/server/src/git/Layers/ClaudeTextGeneration.ts",
+ additions: 106,
+ deletions: 112,
+ },
+ { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 },
+ { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 },
+ {
+ path: "apps/web/src/components/chat/MessagesTimeline.tsx",
+ additions: 52,
+ deletions: 7,
+ },
+ {
+ path: "apps/web/src/components/chat/ChangedFilesTree.tsx",
+ additions: 32,
+ deletions: 4,
+ },
+ { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
+ { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
+ ]),
+ onVirtualizerSnapshot: (snapshot) => {
+ latestSnapshot = {
+ totalSize: snapshot.totalSize,
+ measurements: snapshot.measurements,
+ };
+ },
+ });
+
+ const mounted = await mountMessagesTimeline({ props: initialProps });
+
+ try {
+ const initiallyRenderedHeight = await measureRenderedRowActualHeight({
+ host: mounted.host,
+ targetRowId: targetMessage.id,
+ });
+
+ const appendedProps = createBaseTimelineProps({
+ messages: [
+ ...beforeMessages,
+ targetMessage,
+ ...afterMessages,
+ ...createFillerMessages({
+ prefix: "tail-transition-extra",
+ startOffsetSeconds: 120,
+ pairCount: 8,
+ }),
+ ],
+ turnDiffSummaryByAssistantMessageId: initialProps.turnDiffSummaryByAssistantMessageId,
+ onVirtualizerSnapshot: initialProps.onVirtualizerSnapshot,
+ });
+ await mounted.rerender(appendedProps);
+
+ const scrollContainer = await waitForElement(
+ () =>
+ mounted.host.querySelector<HTMLDivElement>(
+ '[data-testid="messages-timeline-scroll-container"]',
+ ),
+ "Unable to find MessagesTimeline scroll container.",
+ );
+ scrollContainer.scrollTop = scrollContainer.scrollHeight;
+ scrollContainer.dispatchEvent(new Event("scroll"));
+ await waitForLayout();
+
+ await vi.waitFor(
+ () => {
+ const measurement = latestSnapshot?.measurements.find(
+ (entry) => entry.id === targetMessage.id,
+ );
+ expect(
+ measurement,
+ "Expected target row to transition into virtualizer cache.",
+ ).toBeTruthy();
+ expect(Math.abs((measurement?.size ?? 0) - initiallyRenderedHeight)).toBeLessThanOrEqual(
+ 8,
+ );
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("preserves measured tail image row heights when rows transition into virtualization", async () => {
+ const beforeMessages = createFillerMessages({
+ prefix: "tail-image-before",
+ startOffsetSeconds: 0,
+ pairCount: 1,
+ });
+ const afterMessages = createFillerMessages({
+ prefix: "tail-image-after",
+ startOffsetSeconds: 40,
+ pairCount: 3,
+ });
+ const targetMessage = createMessage({
+ id: "target-tail-image-transition",
+ role: "user",
+ text: "Here is a narrow screenshot.",
+ offsetSeconds: 12,
+ attachments: [
+ {
+ type: "image",
+ id: "target-tail-image",
+ name: "narrow.svg",
+ mimeType: "image/svg+xml",
+ sizeBytes: 512,
+ previewUrl:
+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='72'%3E%3Crect width='240' height='72' fill='%23dbeafe'/%3E%3C/svg%3E",
+ },
+ ],
+ });
+ let latestSnapshot: VirtualizerSnapshot | null = null;
+ const initialProps = createBaseTimelineProps({
+ messages: [...beforeMessages, targetMessage, ...afterMessages],
+ onVirtualizerSnapshot: (snapshot) => {
+ latestSnapshot = {
+ totalSize: snapshot.totalSize,
+ measurements: snapshot.measurements,
+ };
+ },
+ });
+ const mounted = await mountMessagesTimeline({ props: initialProps });
+
+ try {
+ await vi.waitFor(
+ () => {
+ const image = mounted.host.querySelector<HTMLImageElement>(
+ `[data-timeline-row-id="${targetMessage.id}"] img`,
+ );
+ expect(image?.naturalHeight ?? 0).toBeGreaterThan(0);
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const initiallyRenderedHeight = await measureRenderedRowActualHeight({
+ host: mounted.host,
+ targetRowId: targetMessage.id,
+ });
+ const appendedProps = createBaseTimelineProps({
+ messages: [
+ ...beforeMessages,
+ targetMessage,
+ ...afterMessages,
+ ...createFillerMessages({
+ prefix: "tail-image-extra",
+ startOffsetSeconds: 120,
+ pairCount: 8,
+ }),
+ ],
+ onVirtualizerSnapshot: initialProps.onVirtualizerSnapshot,
+ });
+ await mounted.rerender(appendedProps);
+
+ const scrollContainer = await waitForElement(
+ () =>
+ mounted.host.querySelector<HTMLDivElement>(
+ '[data-testid="messages-timeline-scroll-container"]',
+ ),
+ "Unable to find MessagesTimeline scroll container.",
+ );
+ scrollContainer.scrollTop = scrollContainer.scrollHeight;
+ scrollContainer.dispatchEvent(new Event("scroll"));
+ await waitForLayout();
+
+ await vi.waitFor(
+ () => {
+ const measurement = latestSnapshot?.measurements.find(
+ (entry) => entry.id === targetMessage.id,
+ );
+ expect(
+ measurement,
+ "Expected target image row to transition into virtualizer cache.",
+ ).toBeTruthy();
+ expect(Math.abs((measurement?.size ?? 0) - initiallyRenderedHeight)).toBeLessThanOrEqual(
+ 8,
+ );
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+});
diff --git a/apps/web/src/components/timelineHeight.test.ts b/apps/web/src/components/timelineHeight.test.ts
index 9b1331a9d..df2a21dab 100644
--- a/apps/web/src/components/timelineHeight.test.ts
+++ b/apps/web/src/components/timelineHeight.test.ts
@@ -11,7 +11,7 @@ describe("estimateTimelineMessageHeight", () => {
role: "assistant",
text: "a".repeat(144),
}),
- ).toBe(122);
+ ).toBe(86.5);
});
it("uses assistant sizing rules for system messages", () => {
@@ -20,7 +20,7 @@ describe("estimateTimelineMessageHeight", () => {
role: "system",
text: "a".repeat(144),
}),
- ).toBe(122);
+ ).toBe(86.5);
});
it("adds one attachment row for one or two user attachments", () => {
@@ -132,7 +132,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "a".repeat(200),
};
- expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
- expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
+ expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(154.75);
+ expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(86.5);
});
});
diff --git a/apps/web/src/components/timelineHeight.ts b/apps/web/src/components/timelineHeight.ts
index 998a2a0b7..57a15f26e 100644
--- a/apps/web/src/components/timelineHeight.ts
+++ b/apps/web/src/components/timelineHeight.ts
@@ -3,8 +3,12 @@ import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContex
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
const USER_CHARS_PER_LINE_FALLBACK = 56;
-const LINE_HEIGHT_PX = 22;
-const ASSISTANT_BASE_HEIGHT_PX = 78;
+const USER_LINE_HEIGHT_PX = 22;
+const ASSISTANT_LINE_HEIGHT_PX = 22.75;
+// Assistant rows render as markdown content plus a compact timestamp meta line.
+// The DOM baseline is much smaller than the user bubble chrome, so model it
+// separately instead of reusing the old shared constant.
+const ASSISTANT_BASE_HEIGHT_PX = 41;
const USER_BASE_HEIGHT_PX = 96;
const ATTACHMENTS_PER_ROW = 2;
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
@@ -73,7 +77,7 @@ export function estimateTimelineMessageHeight(
if (message.role === "assistant") {
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
- return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
+ return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
}
if (message.role === "user") {
@@ -92,12 +96,12 @@ export function estimateTimelineMessageHeight(
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
- return USER_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX + attachmentHeight;
+ return USER_BASE_HEIGHT_PX + estimatedLines * USER_LINE_HEIGHT_PX + attachmentHeight;
}
// `system` messages are not rendered in the chat timeline, but keep a stable
// explicit branch in case they are present in timeline data.
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
- return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
+ return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
}
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index d186a7c9c..ded4915ad 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -21,6 +21,7 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { readNativeApi } from "../nativeApi";
import {
+ getServerConfigUpdatedNotification,
type ServerConfigUpdateSource,
useServerConfig,
useServerConfigUpdatedSubscription,
@@ -206,7 +207,7 @@ function EventRouter() {
const pathname = useLocation({ select: (loc) => loc.pathname });
const pathnameRef = useRef(pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
- const handledConfigReplayRef = useRef(false);
+ const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
const disposedRef = useRef(false);
const bootstrapFromSnapshotRef = useRef<() => Promise<void>>(async () => undefined);
const serverConfig = useServerConfig();
@@ -243,15 +244,19 @@ function EventRouter() {
const handleServerConfigUpdated = useEffectEvent(
({
+ id,
payload,
source,
}: {
+ readonly id: number;
readonly payload: import("@t3tools/contracts").ServerConfigUpdatedPayload;
readonly source: ServerConfigUpdateSource;
}) => {
- const isReplay = !handledConfigReplayRef.current;
- handledConfigReplayRef.current = true;
- if (isReplay || source !== "keybindingsUpdated") {
+ if (id <= seenServerConfigUpdateIdRef.current) {
+ return;
+ }
+ seenServerConfigUpdateIdRef.current = id;
+ if (source !== "keybindingsUpdated") {
return;
}
diff --git a/apps/web/src/rpc/serverState.ts b/apps/web/src/rpc/serverState.ts
index ba4dcba17..ff2719039 100644
--- a/apps/web/src/rpc/serverState.ts
+++ b/apps/web/src/rpc/serverState.ts
@@ -18,6 +18,7 @@ import { appAtomRegistry, resetAppAtomRegistryForTests } from "./atomRegistry";
export type ServerConfigUpdateSource = ServerConfigStreamEvent["type"];
export interface ServerConfigUpdatedNotification {
+ readonly id: number;
readonly payload: ServerConfigUpdatedPayload;
readonly source: ServerConfigUpdateSource;
}
@@ -71,6 +72,10 @@ export function getServerConfig(): ServerConfig | null {
return appAtomRegistry.get(serverConfigAtom);
}
+export function getServerConfigUpdatedNotification(): ServerConfigUpdatedNotification | null {
+ return appAtomRegistry.get(serverConfigUpdatedAtom);
+}
+
export function setServerConfigSnapshot(config: ServerConfig): void {
resolveServerConfig(config);
emitProvidersUpdated({ providers: config.providers });
@@ -194,8 +199,11 @@ export function startServerStateSync(client: ServerStateClient): () => void {
export function resetServerStateForTests() {
resetAppAtomRegistryForTests();
+ nextServerConfigUpdatedNotificationId = 1;
}
+let nextServerConfigUpdatedNotificationId = 1;
+
function resolveServerConfig(config: ServerConfig): void {
appAtomRegistry.set(serverConfigAtom, config);
}
@@ -208,7 +216,11 @@ function emitServerConfigUpdated(
payload: ServerConfigUpdatedPayload,
source: ServerConfigUpdateSource,
): void {
- appAtomRegistry.set(serverConfigUpdatedAtom, { payload, source });
+ appAtomRegistry.set(serverConfigUpdatedAtom, {
+ id: nextServerConfigUpdatedNotificationId++,
+ payload,
+ source,
+ });
}
function subscribeLatest<A>(