fix: stabilize messages timeline virtualization (#1664)
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
ae6f9715c6
commit
867cf4cf09
9 files changed
+1465
-150
No files matched your search
@@ -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);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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>(
|
||||
|
||||
Reference in new issue
Block a user