Migrate chat scrolling and branch lists to LegendList (#1953)

Co-authored-by: Cursor Agent <[email protected]>
This commit is contained in:
Julius MarmingeandCursor Agent authored and GitHub committed 2026-04-12 23:23:14 -07:00
1 parent 94d13a2b75
commit 96c9306dbd
15 files changed
+898 -2675

No files matched your search

+1 -1
View File
@@ -21,6 +21,7 @@
"@dnd-kit/utilities": "^3.2.2",
"@effect/atom-react": "catalog:",
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "3.0.0-beta.44",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/client-runtime": "workspace:*",
@@ -29,7 +30,6 @@
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
-62
View File
@@ -1,62 +0,0 @@
import { describe, expect, it } from "vitest";
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
describe("isScrollContainerNearBottom", () => {
it("returns true when already at bottom", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 600,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(true);
});
it("returns true when within the auto-scroll threshold", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 540,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(true);
});
it("returns false when the user is meaningfully above the bottom", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 520,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(false);
});
it("clamps negative thresholds to zero", () => {
expect(
isScrollContainerNearBottom(
{
scrollTop: 539,
clientHeight: 400,
scrollHeight: 1_000,
},
-1,
),
).toBe(false);
});
it("falls back to the default threshold for non-finite values", () => {
expect(
isScrollContainerNearBottom(
{
scrollTop: 540,
clientHeight: 400,
scrollHeight: 1_000,
},
Number.NaN,
),
).toBe(true);
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
});
});
-24
View File
@@ -1,24 +0,0 @@
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
interface ScrollPosition {
scrollTop: number;
clientHeight: number;
scrollHeight: number;
}
export function isScrollContainerNearBottom(
position: ScrollPosition,
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
): boolean {
const threshold = Number.isFinite(thresholdPx)
? Math.max(0, thresholdPx)
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
const { scrollTop, clientHeight, scrollHeight } = position;
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
return true;
}
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
return distanceFromBottom <= threshold;
}
@@ -1,10 +1,9 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon } from "lucide-react";
import {
type CSSProperties,
useCallback,
useDeferredValue,
useEffect,
@@ -38,6 +37,7 @@ import {
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxListVirtualized,
ComboboxPopup,
ComboboxStatus,
ComboboxTrigger,
@@ -390,7 +390,7 @@ export function BranchToolbarBranchSelector({
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
// ---------------------------------------------------------------------------
// Combobox / virtualizer plumbing
// Combobox / list plumbing
// ---------------------------------------------------------------------------
const handleOpenChange = useCallback(
(open: boolean) => {
@@ -425,49 +425,22 @@ export function BranchToolbarBranchSelector({
void fetchNextPage().catch(() => undefined);
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
const branchListVirtualizer = useVirtualizer({
count: filteredBranchPickerItems.length,
estimateSize: (index) =>
filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28,
getScrollElement: () => branchListScrollElementRef.current,
overscan: 12,
enabled: isBranchMenuOpen && shouldVirtualizeBranchList,
initialRect: {
height: 224,
width: 0,
},
});
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
const setBranchListRef = useCallback(
(element: HTMLDivElement | null) => {
branchListScrollElementRef.current =
(element?.parentElement as HTMLDivElement | null) ?? null;
if (element) {
branchListVirtualizer.measure();
}
},
[branchListVirtualizer],
);
useEffect(() => {
if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return;
queueMicrotask(() => {
branchListVirtualizer.measure();
});
}, [
branchListVirtualizer,
filteredBranchPickerItems.length,
isBranchMenuOpen,
shouldVirtualizeBranchList,
]);
const branchListRef = useRef<LegendListRef | null>(null);
const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
}, []);
useEffect(() => {
if (!isBranchMenuOpen) {
return;
}
branchListScrollElementRef.current?.scrollTo({ top: 0 });
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
if (shouldVirtualizeBranchList) {
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
} else {
branchListScrollElementRef.current?.scrollTo({ top: 0 });
}
}, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
useEffect(() => {
const scrollElement = branchListScrollElementRef.current;
@@ -487,8 +460,9 @@ export function BranchToolbarBranchSelector({
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
useEffect(() => {
if (shouldVirtualizeBranchList) return;
maybeFetchNextBranchPage();
}, [branches.length, maybeFetchNextBranchPage]);
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
@@ -496,7 +470,7 @@ export function BranchToolbarBranchSelector({
resolvedActiveBranch,
});
function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) {
function renderPickerItem(itemValue: string, index: number) {
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
return (
<ComboboxItem
@@ -504,7 +478,6 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
style={style}
onClick={() => {
if (!prReference || !onCheckoutPullRequestRequest) {
return;
@@ -529,7 +502,6 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
style={style}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch &quot;{trimmedBranchQuery}&quot;</span>
@@ -557,7 +529,6 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
style={style}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
@@ -575,8 +546,13 @@ export function BranchToolbarBranchSelector({
autoHighlight
virtualized={shouldVirtualizeBranchList}
onItemHighlighted={(_value, eventDetails) => {
if (!isBranchMenuOpen || eventDetails.index < 0) return;
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
return;
}
branchListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
}}
onOpenChange={handleOpenChange}
open={isBranchMenuOpen}
@@ -604,30 +580,30 @@ export function BranchToolbarBranchSelector({
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList ref={setBranchListRef} className="max-h-56">
{shouldVirtualizeBranchList ? (
<div
className="relative"
style={{
height: `${branchListVirtualizer.getTotalSize()}px`,
{shouldVirtualizeBranchList ? (
<ComboboxListVirtualized>
<LegendList<string>
ref={branchListRef}
data={filteredBranchPickerItems}
keyExtractor={(item) => item}
renderItem={({ item, index }) => renderPickerItem(item, index)}
estimatedItemSize={28}
drawDistance={336}
onEndReached={() => {
if (hasNextPage && !isFetchingNextPage) {
void fetchNextPage().catch(() => undefined);
}
}}
>
{virtualBranchRows.map((virtualRow) => {
const itemValue = filteredBranchPickerItems[virtualRow.index];
if (!itemValue) return null;
return renderPickerItem(itemValue, virtualRow.index, {
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${virtualRow.start}px)`,
});
})}
</div>
) : (
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
)}
</ComboboxList>
style={{ maxHeight: "14rem" }}
/>
</ComboboxListVirtualized>
) : (
<ComboboxList ref={setBranchListRef} className="max-h-56">
{filteredBranchPickerItems.map((itemValue, index) =>
renderPickerItem(itemValue, index),
)}
</ComboboxList>
)}
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
</ComboboxPopup>
</Combobox>
+103 -280
View File
@@ -47,7 +47,7 @@ import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
vi.mock("../lib/gitStatusState", () => ({
@@ -112,28 +112,9 @@ const COMPACT_FOOTER_VIEWPORT: ViewportSpec = {
textTolerancePx: 56,
attachmentTolerancePx: 56,
};
const TEXT_VIEWPORT_MATRIX = [
DEFAULT_VIEWPORT,
{ name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 },
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
] as const satisfies readonly ViewportSpec[];
const ATTACHMENT_VIEWPORT_MATRIX = [
{ ...DEFAULT_VIEWPORT, attachmentTolerancePx: 120 },
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 120 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 120 },
] as const satisfies readonly ViewportSpec[];
interface UserRowMeasurement {
measuredRowHeightPx: number;
timelineWidthMeasuredPx: number;
renderedInVirtualizedRegion: boolean;
}
interface MountedChatView {
[Symbol.asyncDispose]: () => Promise<void>;
cleanup: () => Promise<void>;
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
setViewport: (viewport: ViewportSpec) => Promise<void>;
setContainerSize: (viewport: Pick<ViewportSpec, "width" | "height">) => Promise<void>;
router: ReturnType<typeof getRouter>;
@@ -1378,91 +1359,6 @@ async function waitForCommandPaletteShortcutLabel(): Promise<void> {
);
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
const images = Array.from(scope.querySelectorAll("img"));
if (images.length === 0) {
return;
}
await Promise.all(
images.map(
(image) =>
new Promise<void>((resolve) => {
if (image.complete) {
resolve();
return;
}
image.addEventListener("load", () => resolve(), { once: true });
image.addEventListener("error", () => resolve(), { once: true });
}),
),
);
await waitForLayout();
}
async function measureUserRow(options: {
host: HTMLElement;
targetMessageId: MessageId;
}): Promise<UserRowMeasurement> {
const { host, targetMessageId } = options;
const rowSelector = `[data-message-id="${targetMessageId}"][data-message-role="user"]`;
const scrollContainer = await waitForElement(
() => host.querySelector<HTMLDivElement>("div.overflow-y-auto.overscroll-y-contain"),
"Unable to find ChatView message scroll container.",
);
let row: HTMLElement | null = null;
await vi.waitFor(
async () => {
scrollContainer.scrollTop = 0;
scrollContainer.dispatchEvent(new Event("scroll"));
await waitForLayout();
row = host.querySelector<HTMLElement>(rowSelector);
expect(row, "Unable to locate targeted user message row.").toBeTruthy();
},
{
timeout: 8_000,
interval: 16,
},
);
await waitForImagesToLoad(row!);
scrollContainer.scrollTop = 0;
scrollContainer.dispatchEvent(new Event("scroll"));
await nextFrame();
const timelineRoot =
row!.closest<HTMLElement>('[data-timeline-root="true"]') ??
host.querySelector<HTMLElement>('[data-timeline-root="true"]');
if (!(timelineRoot instanceof HTMLElement)) {
throw new Error("Unable to locate timeline root container.");
}
let timelineWidthMeasuredPx = 0;
let measuredRowHeightPx = 0;
let renderedInVirtualizedRegion = false;
await vi.waitFor(
async () => {
scrollContainer.scrollTop = 0;
scrollContainer.dispatchEvent(new Event("scroll"));
await nextFrame();
const measuredRow = host.querySelector<HTMLElement>(rowSelector);
expect(measuredRow, "Unable to measure targeted user row height.").toBeTruthy();
timelineWidthMeasuredPx = timelineRoot.getBoundingClientRect().width;
measuredRowHeightPx = measuredRow!.getBoundingClientRect().height;
renderedInVirtualizedRegion = measuredRow!.closest("[data-index]") instanceof HTMLElement;
expect(timelineWidthMeasuredPx, "Unable to measure timeline width.").toBeGreaterThan(0);
expect(measuredRowHeightPx, "Unable to measure targeted user row height.").toBeGreaterThan(0);
},
{
timeout: 4_000,
interval: 16,
},
);
return { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion };
}
async function mountChatView(options: {
viewport: ViewportSpec;
snapshot: OrchestrationReadModel;
@@ -1515,7 +1411,6 @@ async function mountChatView(options: {
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
setViewport: async (viewport: ViewportSpec) => {
await setViewport(viewport);
await waitForProductionStyles();
@@ -1529,23 +1424,6 @@ async function mountChatView(options: {
};
}
async function measureUserRowAtViewport(options: {
snapshot: OrchestrationReadModel;
targetMessageId: MessageId;
viewport: ViewportSpec;
}): Promise<UserRowMeasurement> {
const mounted = await mountChatView({
viewport: options.viewport,
snapshot: options.snapshot,
});
try {
return await mounted.measureUserRow(options.targetMessageId);
} finally {
await mounted.cleanup();
}
}
describe("ChatView timeline estimator parity (full app)", () => {
beforeAll(async () => {
fixture = buildFixture(
@@ -1633,39 +1511,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
document.body.innerHTML = "";
});
it.each(TEXT_VIEWPORT_MATRIX)(
"keeps long user message estimate close at the $name viewport",
async (viewport) => {
const userText = "x".repeat(3_200);
const targetMessageId = `msg-user-target-long-${viewport.name}` as MessageId;
const mounted = await mountChatView({
viewport,
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
}),
});
try {
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
await mounted.measureUserRow(targetMessageId);
expect(renderedInVirtualizedRegion).toBe(true);
const estimatedHeightPx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: timelineWidthMeasuredPx },
);
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
viewport.textTolerancePx,
);
} finally {
await mounted.cleanup();
}
},
);
it("re-expands the bootstrap project using its scoped key", async () => {
useUiStateStore.setState({
projectExpandedById: {
@@ -1695,130 +1540,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
const userText = "x".repeat(3_200);
const targetMessageId = "msg-user-target-resize" as MessageId;
const mounted = await mountChatView({
viewport: TEXT_VIEWPORT_MATRIX[0],
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
}),
});
try {
const measurements: Array<
UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }
> = [];
for (const viewport of TEXT_VIEWPORT_MATRIX) {
await mounted.setViewport(viewport);
const measurement = await mounted.measureUserRow(targetMessageId);
const estimatedHeightPx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: measurement.timelineWidthMeasuredPx },
);
expect(measurement.renderedInVirtualizedRegion).toBe(true);
expect(Math.abs(measurement.measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
viewport.textTolerancePx,
);
measurements.push({ ...measurement, viewport, estimatedHeightPx });
}
expect(
new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx)))
.size,
).toBeGreaterThanOrEqual(3);
const byMeasuredWidth = measurements.toSorted(
(left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,
);
const narrowest = byMeasuredWidth[0]!;
const widest = byMeasuredWidth.at(-1)!;
expect(narrowest.timelineWidthMeasuredPx).toBeLessThan(widest.timelineWidthMeasuredPx);
expect(narrowest.measuredRowHeightPx).toBeGreaterThan(widest.measuredRowHeightPx);
expect(narrowest.estimatedHeightPx).toBeGreaterThan(widest.estimatedHeightPx);
} finally {
await mounted.cleanup();
}
});
it("tracks additional rendered wrapping when ChatView width narrows between desktop and mobile viewports", async () => {
const userText = "x".repeat(2_400);
const targetMessageId = "msg-user-target-wrap" as MessageId;
const snapshot = createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
});
const desktopMeasurement = await measureUserRowAtViewport({
viewport: TEXT_VIEWPORT_MATRIX[0],
snapshot,
targetMessageId,
});
const mobileMeasurement = await measureUserRowAtViewport({
viewport: TEXT_VIEWPORT_MATRIX[2],
snapshot,
targetMessageId,
});
const estimatedDesktopPx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: desktopMeasurement.timelineWidthMeasuredPx },
);
const estimatedMobilePx = estimateTimelineMessageHeight(
{ role: "user", text: userText, attachments: [] },
{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },
);
const measuredDeltaPx =
mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;
const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;
expect(measuredDeltaPx).toBeGreaterThan(0);
expect(estimatedDeltaPx).toBeGreaterThan(0);
const ratio = estimatedDeltaPx / measuredDeltaPx;
expect(ratio).toBeGreaterThan(0.65);
expect(ratio).toBeLessThan(1.35);
});
it.each(ATTACHMENT_VIEWPORT_MATRIX)(
"keeps user attachment estimate close at the $name viewport",
async (viewport) => {
const targetMessageId = `msg-user-target-attachments-${viewport.name}` as MessageId;
const userText = "message with image attachments";
const mounted = await mountChatView({
viewport,
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
targetAttachmentCount: 2,
}),
});
try {
const { measuredRowHeightPx, timelineWidthMeasuredPx, renderedInVirtualizedRegion } =
await mounted.measureUserRow(targetMessageId);
expect(renderedInVirtualizedRegion).toBe(true);
const estimatedHeightPx = estimateTimelineMessageHeight(
{
role: "user",
text: userText,
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }],
},
{ timelineWidthPx: timelineWidthMeasuredPx },
);
expect(Math.abs(measuredRowHeightPx - estimatedHeightPx)).toBeLessThanOrEqual(
viewport.attachmentTolerancePx,
);
} finally {
await mounted.cleanup();
}
},
);
it("shows an explicit empty state for projects without threads in the sidebar", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -2771,6 +2492,108 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps the new worktree branch picker anchored at the top when opening with a preselected branch", async () => {
const draftId = DraftId.make("draft-branch-picker-scroll-regression");
const branches = [
{
name: "feature/current",
current: true,
isDefault: false,
worktreePath: null,
},
{
name: "main",
current: false,
isDefault: true,
worktreePath: null,
},
...Array.from({ length: 48 }, (_, index) => ({
name: `feature/${String(index).padStart(2, "0")}`,
current: false,
isDefault: false,
worktreePath: null,
})),
{
name: "feature/selected",
current: false,
isDefault: false,
worktreePath: null,
},
];
useComposerDraftStore.setState({
draftThreadsByThreadKey: {
[draftId]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/selected",
worktreePath: null,
envMode: "worktree",
},
},
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: draftId,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
initialPath: `/draft/${draftId}`,
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitListBranches) {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: branches.length,
branches,
};
}
return undefined;
},
});
try {
const branchButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "From feature/selected",
) as HTMLButtonElement | null,
'Unable to find branch selector button with "From feature/selected".',
);
branchButton.click();
await waitForElement(
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
"Unable to find branch search input.",
);
const popup = await waitForElement(
() => document.querySelector<HTMLElement>('[data-slot="combobox-popup"]'),
"Unable to find the branch picker popup.",
);
await vi.waitFor(
() => {
const popupSpans = Array.from(popup.querySelectorAll("span"));
expect(
popupSpans.some((element) => element.textContent?.trim() === "feature/current"),
).toBe(true);
expect(popupSpans.some((element) => element.textContent?.trim() === "main")).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("surrounds selected plain text and preserves the inner selection for repeated wrapping", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
+81 -276
View File
@@ -28,7 +28,8 @@ import {
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Debouncer } from "@tanstack/react-pacer";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import { useGitStatus } from "~/lib/gitStatusState";
@@ -57,7 +58,7 @@ import {
isLatestTurnSettled,
formatElapsed,
} from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll";
import { type LegendListRef } from "@legendapp/list/react";
import {
buildPendingUserInputAnswers,
derivePendingUserInputProgress,
@@ -174,7 +175,6 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT =
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROPOSED_PLANS: Thread["proposedPlans"] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_CHANGED_FILES_EXPANDED_BY_TURN_ID: Record<string, boolean> = {};
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
@@ -590,18 +590,9 @@ export default function ChatView(props: ChatViewProps) {
);
const setStoreThreadError = useStore((store) => store.setError);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const setThreadChangedFilesExpanded = useUiStateStore(
(store) => store.setThreadChangedFilesExpanded,
);
const activeThreadLastVisitedAt = useUiStateStore((store) =>
routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,
);
const changedFilesExpandedByTurnId = useUiStateStore((store) =>
routeKind === "server"
? (store.threadChangedFilesExpandedById[routeThreadKey] ??
EMPTY_CHANGED_FILES_EXPANDED_BY_TURN_ID)
: EMPTY_CHANGED_FILES_EXPANDED_BY_TURN_ID,
);
const settings = useSettings();
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
@@ -673,14 +664,12 @@ export default function ChatView(props: ChatViewProps) {
>({});
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
// When set, the thread-change reset effect will open the sidebar instead of closing it.
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
const planSidebarOpenOnNextThreadRef = useRef(false);
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
@@ -695,27 +684,12 @@ export default function ChatView(props: ChatViewProps) {
{},
LastInvokedScriptByProjectSchema,
);
const messagesScrollRef = useRef<HTMLDivElement>(null);
const [messagesScrollElement, setMessagesScrollElement] = useState<HTMLDivElement | null>(null);
const shouldAutoScrollRef = useRef(true);
const lastKnownScrollTopRef = useRef(0);
const isPointerScrollActiveRef = useRef(false);
const lastTouchClientYRef = useRef<number | null>(null);
const pendingUserScrollUpIntentRef = useRef(false);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const pendingInteractionAnchorRef = useRef<{
element: HTMLElement;
top: number;
} | null>(null);
const pendingInteractionAnchorFrameRef = useRef<number | null>(null);
const legendListRef = useRef<LegendListRef | null>(null);
const isAtEndRef = useRef(true);
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
const sendInFlightRef = useRef(false);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
const setMessagesScrollContainerRef = useCallback((element: HTMLDivElement | null) => {
messagesScrollRef.current = element;
setMessagesScrollElement(element);
}, []);
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef),
@@ -995,16 +969,6 @@ export default function ChatView(props: ChatViewProps) {
[openOrReuseProjectDraftThread],
);
const handleSetChangedFilesExpanded = useCallback(
(turnId: TurnId, expanded: boolean) => {
if (routeKind !== "server") {
return;
}
setThreadChangedFilesExpanded(routeThreadKey, turnId, expanded);
},
[routeKind, routeThreadKey, setThreadChangedFilesExpanded],
);
useEffect(() => {
if (!serverThread?.id) return;
if (!latestTurnSettled) return;
@@ -1144,7 +1108,6 @@ export default function ChatView(props: ChatViewProps) {
threadError: activeThread?.error,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
@@ -1970,169 +1933,33 @@ export default function ChatView(props: ChatViewProps) {
[environmentId, serverThread],
);
// Auto-scroll on new messages
const messageCount = timelineMessages.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
shouldAutoScrollRef.current = true;
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
const scrollToEnd = useCallback((animated = false) => {
legendListRef.current?.scrollToEnd?.({ animated });
}, []);
const cancelPendingStickToBottom = useCallback(() => {
const pendingFrame = pendingAutoScrollFrameRef.current;
if (pendingFrame === null) return;
pendingAutoScrollFrameRef.current = null;
window.cancelAnimationFrame(pendingFrame);
}, []);
const cancelPendingInteractionAnchorAdjustment = useCallback(() => {
const pendingFrame = pendingInteractionAnchorFrameRef.current;
if (pendingFrame === null) return;
pendingInteractionAnchorFrameRef.current = null;
window.cancelAnimationFrame(pendingFrame);
}, []);
const scheduleStickToBottom = useCallback(() => {
if (pendingAutoScrollFrameRef.current !== null) return;
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
pendingAutoScrollFrameRef.current = null;
scrollMessagesToBottom();
});
}, [scrollMessagesToBottom]);
const onMessagesClickCapture = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer || !(event.target instanceof Element)) return;
const trigger = event.target.closest<HTMLElement>(
"button, summary, [role='button'], [data-scroll-anchor-target]",
);
if (!trigger || !scrollContainer.contains(trigger)) return;
if (trigger.closest("[data-scroll-anchor-ignore]")) return;
pendingInteractionAnchorRef.current = {
element: trigger,
top: trigger.getBoundingClientRect().top,
};
cancelPendingInteractionAnchorAdjustment();
pendingInteractionAnchorFrameRef.current = window.requestAnimationFrame(() => {
pendingInteractionAnchorFrameRef.current = null;
const anchor = pendingInteractionAnchorRef.current;
pendingInteractionAnchorRef.current = null;
const activeScrollContainer = messagesScrollRef.current;
if (!anchor || !activeScrollContainer) return;
if (!anchor.element.isConnected || !activeScrollContainer.contains(anchor.element)) return;
const nextTop = anchor.element.getBoundingClientRect().top;
const delta = nextTop - anchor.top;
if (Math.abs(delta) < 0.5) return;
activeScrollContainer.scrollTop += delta;
lastKnownScrollTopRef.current = activeScrollContainer.scrollTop;
});
},
[cancelPendingInteractionAnchorAdjustment],
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
// thread switches. LegendList fires scroll events with isAtEnd=false while
// initialScrollAtEnd is settling; hiding is always immediate.
const showScrollDebouncer = useRef(
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
);
const forceStickToBottom = useCallback(() => {
cancelPendingStickToBottom();
scrollMessagesToBottom();
scheduleStickToBottom();
}, [cancelPendingStickToBottom, scheduleStickToBottom, scrollMessagesToBottom]);
const onMessagesScroll = useCallback(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
const currentScrollTop = scrollContainer.scrollTop;
const isNearBottom = isScrollContainerNearBottom(scrollContainer);
if (!shouldAutoScrollRef.current && isNearBottom) {
shouldAutoScrollRef.current = true;
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
} else if (shouldAutoScrollRef.current && !isNearBottom) {
// Catch-all for keyboard/assistive scroll interactions.
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
shouldAutoScrollRef.current = false;
}
}
setShowScrollToBottom(!shouldAutoScrollRef.current);
lastKnownScrollTopRef.current = currentScrollTop;
}, []);
const onMessagesWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
if (event.deltaY < 0) {
pendingUserScrollUpIntentRef.current = true;
const onIsAtEndChange = useCallback((isAtEnd: boolean) => {
if (isAtEndRef.current === isAtEnd) return;
isAtEndRef.current = isAtEnd;
if (isAtEnd) {
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
} else {
showScrollDebouncer.current.maybeExecute();
}
}, []);
const onMessagesPointerDown = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
isPointerScrollActiveRef.current = true;
}, []);
const onMessagesPointerUp = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
isPointerScrollActiveRef.current = false;
}, []);
const onMessagesPointerCancel = useCallback((_event: React.PointerEvent<HTMLDivElement>) => {
isPointerScrollActiveRef.current = false;
}, []);
const onMessagesTouchStart = useCallback((event: React.TouchEvent<HTMLDivElement>) => {
const touch = event.touches[0];
if (!touch) return;
lastTouchClientYRef.current = touch.clientY;
}, []);
const onMessagesTouchMove = useCallback((event: React.TouchEvent<HTMLDivElement>) => {
const touch = event.touches[0];
if (!touch) return;
const previousTouchY = lastTouchClientYRef.current;
if (previousTouchY !== null && touch.clientY > previousTouchY + 1) {
pendingUserScrollUpIntentRef.current = true;
}
lastTouchClientYRef.current = touch.clientY;
}, []);
const onMessagesTouchEnd = useCallback((_event: React.TouchEvent<HTMLDivElement>) => {
lastTouchClientYRef.current = null;
}, []);
useEffect(() => {
return () => {
cancelPendingStickToBottom();
cancelPendingInteractionAnchorAdjustment();
};
}, [cancelPendingInteractionAnchorAdjustment, cancelPendingStickToBottom]);
useLayoutEffect(() => {
if (!activeThread?.id) return;
shouldAutoScrollRef.current = true;
scheduleStickToBottom();
const timeout = window.setTimeout(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
if (isScrollContainerNearBottom(scrollContainer)) return;
scheduleStickToBottom();
}, 96);
return () => {
window.clearTimeout(timeout);
};
}, [activeThread?.id, scheduleStickToBottom]);
useEffect(() => {
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
}, [messageCount, scheduleStickToBottom]);
useEffect(() => {
if (phase !== "running") return;
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
}, [phase, scheduleStickToBottom, timelineEntries]);
useEffect(() => {
setExpandedWorkGroups({});
setPullRequestDialogState(null);
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
setPlanSidebarOpen(true);
@@ -2290,16 +2117,6 @@ export default function ChatView(props: ChatViewProps) {
terminalState.terminalOpen,
]);
useEffect(() => {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
return () => {
window.clearInterval(timer);
};
}, [phase]);
useEffect(() => {
if (!activeThreadKey) return;
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
@@ -2575,6 +2392,14 @@ export default function ChatView(props: ChatViewProps) {
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
// Scroll to the current end *before* adding the optimistic message.
// This sets LegendList's internal isAtEnd=true so maintainScrollAtEnd
// automatically pins to the new item when the data changes.
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
await legendListRef.current?.scrollToEnd?.({ animated: false });
setOptimisticUserMessages((existing) => [
...existing,
{
@@ -2586,9 +2411,6 @@ export default function ChatView(props: ChatViewProps) {
streaming: false,
},
]);
// Sending a message should always bring the latest user turn into view.
shouldAutoScrollRef.current = true;
forceStickToBottom();
setThreadError(threadIdForSend, null);
if (expiredTerminalContextCount > 0) {
@@ -2969,6 +2791,13 @@ export default function ChatView(props: ChatViewProps) {
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
// Scroll to the current end *before* adding the optimistic message.
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
await legendListRef.current?.scrollToEnd?.({ animated: false });
setOptimisticUserMessages((existing) => [
...existing,
{
@@ -2979,8 +2808,6 @@ export default function ChatView(props: ChatViewProps) {
streaming: false,
},
]);
shouldAutoScrollRef.current = true;
forceStickToBottom();
try {
await persistThreadSettingsForNextTurn({
@@ -3046,7 +2873,6 @@ export default function ChatView(props: ChatViewProps) {
activeThread,
activeProposedPlan,
beginLocalDispatch,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
@@ -3241,12 +3067,6 @@ export default function ChatView(props: ChatViewProps) {
],
);
const onToggleWorkGroup = useCallback((groupId: string) => {
setExpandedWorkGroups((existing) => ({
...existing,
[groupId]: !existing[groupId],
}));
}, []);
const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {
setExpandedImage(preview);
}, []);
@@ -3272,16 +3092,19 @@ export default function ChatView(props: ChatViewProps) {
},
[environmentId, isServerThread, navigate, onDiffPanelOpen, threadId],
);
const onRevertUserMessage = useCallback(
(messageId: MessageId) => {
const targetTurnCount = revertTurnCountByUserMessageId.get(messageId);
if (typeof targetTurnCount !== "number") {
return;
}
void onRevertToTurnCount(targetTurnCount);
},
[onRevertToTurnCount, revertTurnCountByUserMessageId],
);
// Both the Map and the revert handler are read from refs at call-time so
// the callback reference is fully stable and never busts context identity.
const revertTurnCountRef = useRef(revertTurnCountByUserMessageId);
revertTurnCountRef.current = revertTurnCountByUserMessageId;
const onRevertToTurnCountRef = useRef(onRevertToTurnCount);
onRevertToTurnCountRef.current = onRevertToTurnCount;
const onRevertUserMessage = useCallback((messageId: MessageId) => {
const targetTurnCount = revertTurnCountRef.current.get(messageId);
if (typeof targetTurnCount !== "number") {
return;
}
void onRevertToTurnCountRef.current(targetTurnCount);
}, []);
// Empty state: no active thread
if (!activeThread) {
@@ -3338,57 +3161,39 @@ export default function ChatView(props: ChatViewProps) {
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
{/* Messages Wrapper */}
<div className="relative flex min-h-0 flex-1 flex-col">
{/* Messages */}
<div
ref={setMessagesScrollContainerRef}
className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain px-3 py-3 sm:px-5 sm:py-4"
onScroll={onMessagesScroll}
onClickCapture={onMessagesClickCapture}
onWheel={onMessagesWheel}
onPointerDown={onMessagesPointerDown}
onPointerUp={onMessagesPointerUp}
onPointerCancel={onMessagesPointerCancel}
onTouchStart={onMessagesTouchStart}
onTouchMove={onMessagesTouchMove}
onTouchEnd={onMessagesTouchEnd}
onTouchCancel={onMessagesTouchEnd}
>
<MessagesTimeline
key={activeThread.id}
hasMessages={timelineEntries.length > 0}
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestTurnSettled}
activeTurnId={activeLatestTurn?.turnId ?? null}
activeTurnStartedAt={activeWorkStartedAt}
scrollContainer={messagesScrollElement}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
nowIso={nowIso}
activeThreadEnvironmentId={activeThread.environmentId}
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={onToggleWorkGroup}
changedFilesExpandedByTurnId={changedFilesExpandedByTurnId}
onSetChangedFilesExpanded={handleSetChangedFilesExpanded}
onOpenTurnDiff={onOpenTurnDiff}
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
onRevertUserMessage={onRevertUserMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={activeWorkspaceRoot}
/>
</div>
{/* Messages — LegendList handles virtualization and scrolling internally */}
<MessagesTimeline
key={activeThread.id}
hasMessages={timelineEntries.length > 0}
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestTurnSettled}
activeTurnId={activeLatestTurn?.turnId ?? null}
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
activeThreadEnvironmentId={activeThread.environmentId}
routeThreadKey={routeThreadKey}
onOpenTurnDiff={onOpenTurnDiff}
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
onRevertUserMessage={onRevertUserMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={activeWorkspaceRoot}
onIsAtEndChange={onIsAtEndChange}
/>
{/* scroll to bottom pill — shown when user has scrolled away from the bottom */}
{showScrollToBottom && (
<div className="pointer-events-none absolute bottom-1 left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5">
<button
type="button"
onClick={() => scrollMessagesToBottom("smooth")}
onClick={() => scrollToEnd(true)}
className="pointer-events-auto flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-3 py-1 text-muted-foreground text-xs shadow-sm transition-colors hover:border-border hover:text-foreground hover:cursor-pointer"
>
<ChevronDownIcon className="size-3.5" />
@@ -3443,8 +3248,8 @@ export default function ChatView(props: ChatViewProps) {
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
shouldAutoScrollRef={shouldAutoScrollRef}
scheduleStickToBottom={scheduleStickToBottom}
shouldAutoScrollRef={isAtEndRef}
scheduleStickToBottom={scrollToEnd}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
computeStableMessagesTimelineRows,
computeMessageDurationStart,
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
@@ -252,6 +253,8 @@ describe("deriveMessagesTimelineRows", () => {
completionDividerBeforeEntryId: "assistant-final-entry",
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const assistantRows = rows.filter(
@@ -264,4 +267,169 @@ describe("deriveMessagesTimelineRows", () => {
expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
});
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
const assistantTurnDiffSummary = {
turnId: "turn-1" as never,
completedAt: "2026-01-01T00:00:30Z",
assistantMessageId: "assistant-1" as never,
checkpointTurnCount: 2,
files: [{ path: "src/index.ts", additions: 3, deletions: 1 }],
};
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "user-entry",
kind: "message",
createdAt: "2026-01-01T00:00:00Z",
message: {
id: "user-1" as never,
role: "user",
text: "Do the thing",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
},
},
{
id: "assistant-entry",
kind: "message",
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-1" as never,
role: "assistant",
text: "Done",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:30Z",
streaming: false,
},
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map([
["assistant-1" as never, assistantTurnDiffSummary],
]),
revertTurnCountByUserMessageId: new Map([["user-1" as never, 1]]),
});
const userRow = rows.find(
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
row.kind === "message" && row.message.role === "user",
);
const assistantRow = rows.find(
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
row.kind === "message" && row.message.role === "assistant",
);
expect(userRow?.revertTurnCount).toBe(1);
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
});
});
describe("computeStableMessagesTimelineRows", () => {
it("returns the previous result when row order and content are unchanged", () => {
const firstUserMessage = {
id: "user-1" as never,
role: "user" as const,
text: "First",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
};
const secondUserMessage = {
id: "user-2" as never,
role: "user" as const,
text: "Second",
turnId: null,
createdAt: "2026-01-01T00:00:10Z",
streaming: false,
};
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "entry-user-1",
kind: "message",
createdAt: firstUserMessage.createdAt,
message: firstUserMessage,
},
{
id: "entry-user-2",
kind: "message",
createdAt: secondUserMessage.createdAt,
message: secondUserMessage,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const initial = computeStableMessagesTimelineRows(rows, {
byId: new Map(),
result: [],
});
const repeated = computeStableMessagesTimelineRows(rows, initial);
expect(repeated).toBe(initial);
expect(repeated.result).toBe(initial.result);
});
it("returns a new result when row order changes without content changes", () => {
const firstUserMessage = {
id: "user-1" as never,
role: "user" as const,
text: "First",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
};
const secondUserMessage = {
id: "user-2" as never,
role: "user" as const,
text: "Second",
turnId: null,
createdAt: "2026-01-01T00:00:10Z",
streaming: false,
};
const firstRows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "entry-user-1",
kind: "message",
createdAt: firstUserMessage.createdAt,
message: firstUserMessage,
},
{
id: "entry-user-2",
kind: "message",
createdAt: secondUserMessage.createdAt,
message: secondUserMessage,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const initial = computeStableMessagesTimelineRows(firstRows, {
byId: new Map(),
result: [],
});
const reordered = computeStableMessagesTimelineRows([firstRows[1]!, firstRows[0]!], initial);
expect(reordered).not.toBe(initial);
expect(reordered.result).toEqual([initial.result[1], initial.result[0]]);
});
});
@@ -1,8 +1,6 @@
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";
import { type MessageId } from "@t3tools/contracts";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
@@ -28,6 +26,8 @@ export type MessagesTimelineRow =
durationStart: string;
showCompletionDivider: boolean;
showAssistantCopyButton: boolean;
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
revertTurnCount?: number | undefined;
}
| {
kind: "proposed-plan";
@@ -37,6 +37,11 @@ export type MessagesTimelineRow =
}
| { kind: "working"; id: string; createdAt: string | null };
export interface StableMessagesTimelineRowsState {
byId: Map<string, MessagesTimelineRow>;
result: MessagesTimelineRow[];
}
export function computeMessageDurationStart(
messages: ReadonlyArray<TimelineDurationMessage>,
): Map<string, string> {
@@ -107,6 +112,8 @@ export function deriveMessagesTimelineRows(input: {
completionDividerBeforeEntryId: string | null;
isWorking: boolean;
activeTurnStartedAt: string | null;
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
}): MessagesTimelineRow[] {
const nextRows: MessagesTimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
@@ -162,6 +169,14 @@ export function deriveMessagesTimelineRows(input: {
showAssistantCopyButton:
timelineEntry.message.role === "assistant" &&
terminalAssistantMessageIds.has(timelineEntry.message.id),
assistantTurnDiffSummary:
timelineEntry.message.role === "assistant"
? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
: undefined,
revertTurnCount:
timelineEntry.message.role === "user"
? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
: undefined,
});
}
@@ -176,71 +191,50 @@ export function deriveMessagesTimelineRows(input: {
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);
export function computeStableMessagesTimelineRows(
rows: MessagesTimelineRow[],
previous: StableMessagesTimelineRowsState,
): StableMessagesTimelineRowsState {
const next = new Map<string, MessagesTimelineRow>();
let anyChanged = rows.length !== previous.byId.size;
const result = rows.map((row, index) => {
const prevRow = previous.byId.get(row.id);
const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
next.set(row.id, nextRow);
if (!anyChanged && previous.result[index] !== nextRow) {
anyChanged = true;
}
return nextRow;
});
return anyChanged ? { byId: next, result } : previous;
}
/** Shallow field comparison per row variant — avoids deep equality cost. */
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
if (a.kind !== b.kind || a.id !== b.id) return false;
switch (a.kind) {
case "working":
return 40;
return a.createdAt === (b as typeof a).createdAt;
case "proposed-plan":
return a.proposedPlan === (b as typeof a).proposedPlan;
case "work":
return a.groupedEntries === (b as typeof a).groupedEntries;
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;
const bm = b as typeof a;
return (
a.message === bm.message &&
a.durationStart === bm.durationStart &&
a.showCompletionDivider === bm.showCompletionDivider &&
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
a.revertTurnCount === bm.revertTurnCount
);
}
}
}
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;
}
@@ -1,151 +0,0 @@
import { MessageId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeAll, describe, expect, it, vi } from "vitest";
function matchMedia() {
return {
matches: false,
addEventListener: () => {},
removeEventListener: () => {},
};
}
beforeAll(() => {
const classList = {
add: () => {},
remove: () => {},
toggle: () => {},
contains: () => false,
};
vi.stubGlobal("localStorage", {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
clear: () => {},
});
vi.stubGlobal("window", {
matchMedia,
addEventListener: () => {},
removeEventListener: () => {},
desktopBridge: undefined,
});
vi.stubGlobal("document", {
documentElement: {
classList,
offsetHeight: 0,
},
});
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
callback(0);
return 0;
});
});
const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never;
describe("MessagesTimeline", () => {
it("renders inline terminal labels with the composer chip UI", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
hasMessages
isWorking={false}
activeTurnInProgress={false}
activeTurnStartedAt={null}
scrollContainer={null}
timelineEntries={[
{
id: "entry-1",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-2"),
role: "user",
text: [
"yoo what's @terminal-1:1-5 mean",
"",
"<terminal_context>",
"- Terminal 1 lines 1-5:",
" 1 | julius@mac effect-http-ws-cli % bun i",
" 2 | bun install v1.3.9 (cf6cdbbb)",
"</terminal_context>",
].join("\n"),
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
]}
completionDividerBeforeEntryId={null}
completionSummary={null}
turnDiffSummaryByAssistantMessageId={new Map()}
nowIso="2026-03-17T19:12:30.000Z"
expandedWorkGroups={{}}
onToggleWorkGroup={() => {}}
changedFilesExpandedByTurnId={{}}
onSetChangedFilesExpanded={() => {}}
onOpenTurnDiff={() => {}}
revertTurnCountByUserMessageId={new Map()}
onRevertUserMessage={() => {}}
isRevertingCheckpoint={false}
onImageExpand={() => {}}
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
markdownCwd={undefined}
resolvedTheme="light"
timestampFormat="locale"
workspaceRoot={undefined}
/>,
);
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
}, 10_000);
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
hasMessages
isWorking={false}
activeTurnInProgress={false}
activeTurnStartedAt={null}
scrollContainer={null}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Context compacted",
tone: "info",
},
},
]}
completionDividerBeforeEntryId={null}
completionSummary={null}
turnDiffSummaryByAssistantMessageId={new Map()}
nowIso="2026-03-17T19:12:30.000Z"
expandedWorkGroups={{}}
onToggleWorkGroup={() => {}}
changedFilesExpandedByTurnId={{}}
onSetChangedFilesExpanded={() => {}}
onOpenTurnDiff={() => {}}
revertTurnCountByUserMessageId={new Map()}
onRevertUserMessage={() => {}}
isRevertingCheckpoint={false}
onImageExpand={() => {}}
activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
markdownCwd={undefined}
resolvedTheme="light"
timestampFormat="locale"
workspaceRoot={undefined}
/>,
);
expect(markup).toContain("Context compacted");
expect(markup).toContain("Work log");
});
});
+421 -387
View File
@@ -1,21 +1,17 @@
import { type EnvironmentId, type MessageId, type TurnId } from "@t3tools/contracts";
import {
createContext,
memo,
use,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import {
measureElement as measureVirtualElement,
type VirtualItem,
useVirtualizer,
} from "@tanstack/react-virtual";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX } from "../../chat-scroll";
import { type TurnDiffSummary } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import ChatMarkdown from "../ChatMarkdown";
@@ -34,18 +30,18 @@ import {
ZapIcon,
} from "lucide-react";
import { Button } from "../ui/button";
import { clamp } from "effect/Number";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
MAX_VISIBLE_WORK_LOG_ENTRIES,
deriveMessagesTimelineRows,
estimateMessagesTimelineRowHeight,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
type StableMessagesTimelineRowsState,
type MessagesTimelineRow,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
@@ -55,6 +51,7 @@ import {
type ParsedTerminalContextEntry,
} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
import { useUiStateStore } from "~/uiStateStore";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { formatTimestamp } from "../../timestampFormat";
@@ -64,7 +61,35 @@ import {
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
// ---------------------------------------------------------------------------
// Context — shared state consumed by every row component via useContext.
// Propagates through LegendList's memo boundaries for shared callbacks and
// non-row-scoped state. `nowIso` is intentionally excluded — self-ticking
// components (WorkingTimer, LiveElapsed) handle it.
// ---------------------------------------------------------------------------
interface TimelineRowSharedState {
activeTurnInProgress: boolean;
activeTurnId: TurnId | null | undefined;
isWorking: boolean;
isRevertingCheckpoint: boolean;
completionSummary: string | null;
timestampFormat: TimestampFormat;
routeThreadKey: string;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
workspaceRoot: string | undefined;
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
// ---------------------------------------------------------------------------
// Props (public API)
// ---------------------------------------------------------------------------
interface MessagesTimelineProps {
hasMessages: boolean;
@@ -72,16 +97,12 @@ interface MessagesTimelineProps {
activeTurnInProgress: boolean;
activeTurnId?: TurnId | null;
activeTurnStartedAt: string | null;
scrollContainer: HTMLDivElement | null;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
nowIso: string;
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
changedFilesExpandedByTurnId: Record<string, boolean>;
onSetChangedFilesExpanded: (turnId: TurnId, expanded: boolean) => void;
routeThreadKey: string;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
revertTurnCountByUserMessageId: Map<MessageId, number>;
onRevertUserMessage: (messageId: MessageId) => void;
@@ -92,35 +113,25 @@ 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;
onIsAtEndChange: (isAtEnd: boolean) => void;
}
// ---------------------------------------------------------------------------
// MessagesTimeline — list owner
// ---------------------------------------------------------------------------
export const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
activeTurnInProgress,
activeTurnId,
activeTurnStartedAt,
scrollContainer,
listRef,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
turnDiffSummaryByAssistantMessageId,
nowIso,
expandedWorkGroups,
onToggleWorkGroup,
changedFilesExpandedByTurnId,
onSetChangedFilesExpanded,
routeThreadKey,
onOpenTurnDiff,
revertTurnCountByUserMessageId,
onRevertUserMessage,
@@ -131,181 +142,132 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
timestampFormat,
workspaceRoot,
onVirtualizerSnapshot,
onIsAtEndChange,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
useLayoutEffect(() => {
const timelineRoot = timelineRootRef.current;
if (!timelineRoot) return;
const updateWidth = (nextWidth: number) => {
setTimelineWidthPx((previousWidth) => {
if (previousWidth !== null && Math.abs(previousWidth - nextWidth) < 0.5) {
return previousWidth;
}
return nextWidth;
});
};
updateWidth(timelineRoot.getBoundingClientRect().width);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
updateWidth(timelineRoot.getBoundingClientRect().width);
});
observer.observe(timelineRoot);
return () => {
observer.disconnect();
};
}, [hasMessages, isWorking]);
const rows = useMemo(
const rawRows = useMemo(
() =>
deriveMessagesTimelineRows({
timelineEntries,
completionDividerBeforeEntryId,
isWorking,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
}),
[timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt],
[
timelineEntries,
completionDividerBeforeEntryId,
isWorking,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
],
);
const rows = useStableRows(rawRows);
const handleScroll = useCallback(() => {
const state = listRef.current?.getState?.();
if (state) {
onIsAtEndChange(state.isAtEnd);
}
}, [listRef, onIsAtEndChange]);
// Memoised context value — only changes on state transitions, NOT on
// every streaming chunk. Callbacks from ChatView are useCallback-stable.
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
activeTurnInProgress,
activeTurnId: activeTurnId ?? null,
isWorking,
isRevertingCheckpoint,
completionSummary,
timestampFormat,
routeThreadKey,
markdownCwd,
resolvedTheme,
workspaceRoot,
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
onOpenTurnDiff,
}),
[
activeTurnInProgress,
activeTurnId,
isWorking,
isRevertingCheckpoint,
completionSummary,
timestampFormat,
routeThreadKey,
markdownCwd,
resolvedTheme,
workspaceRoot,
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
onOpenTurnDiff,
],
);
const firstUnvirtualizedRowIndex = useMemo(() => {
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
if (!activeTurnInProgress) return firstTailRowIndex;
// Stable renderItem — no closure deps. Row components read shared state
// from TimelineRowCtx, which propagates through LegendList's memo.
const renderItem = useCallback(
({ item }: { item: MessagesTimelineRow }) => (
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden" data-timeline-root="true">
<TimelineRowContent row={item} />
</div>
),
[],
);
const turnStartedAtMs =
typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN;
let firstCurrentTurnRowIndex = -1;
if (!Number.isNaN(turnStartedAtMs)) {
firstCurrentTurnRowIndex = rows.findIndex((row) => {
if (row.kind === "working") return true;
if (!row.createdAt) return false;
const rowCreatedAtMs = Date.parse(row.createdAt);
return !Number.isNaN(rowCreatedAtMs) && rowCreatedAtMs >= turnStartedAtMs;
});
}
if (!hasMessages && !isWorking) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
);
}
if (firstCurrentTurnRowIndex < 0) {
firstCurrentTurnRowIndex = rows.findIndex(
(row) => row.kind === "message" && row.message.streaming,
);
}
return (
<TimelineRowCtx.Provider value={sharedState}>
<LegendList<MessagesTimelineRow>
ref={listRef}
data={rows}
keyExtractor={keyExtractor}
renderItem={renderItem}
estimatedItemSize={90}
initialScrollAtEnd
maintainScrollAtEnd
maintainScrollAtEndThreshold={0.1}
maintainVisibleContentPosition
onScroll={handleScroll}
className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
ListHeaderComponent={<div className="h-3 sm:h-4" />}
ListFooterComponent={<div className="h-3 sm:h-4" />}
/>
</TimelineRowCtx.Provider>
);
});
if (firstCurrentTurnRowIndex < 0) return firstTailRowIndex;
function keyExtractor(item: MessagesTimelineRow) {
return item.id;
}
for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) {
const previousRow = rows[index];
if (!previousRow || previousRow.kind !== "message") continue;
if (previousRow.message.role === "user") {
return Math.min(index, firstTailRowIndex);
}
if (previousRow.message.role === "assistant" && !previousRow.message.streaming) {
break;
}
}
// ---------------------------------------------------------------------------
// TimelineRowContent — the actual row component
// ---------------------------------------------------------------------------
return Math.min(firstCurrentTurnRowIndex, firstTailRowIndex);
}, [activeTurnInProgress, activeTurnStartedAt, rows]);
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
type TimelineRow = MessagesTimelineRow;
const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, {
minimum: 0,
maximum: rows.length,
});
const virtualMeasurementScopeKey =
timelineWidthPx === null ? "width:unknown" : `width:${Math.round(timelineWidthPx)}`;
function TimelineRowContent({ row }: { row: TimelineRow }) {
const ctx = use(TimelineRowCtx);
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainer,
// 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;
return estimateMessagesTimelineRowHeight(row, {
expandedWorkGroups,
timelineWidthPx,
turnDiffSummaryByAssistantMessageId,
});
},
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
overscan: 8,
});
useEffect(() => {
if (timelineWidthPx === null) return;
rowVirtualizer.measure();
}, [rowVirtualizer, timelineWidthPx]);
useEffect(() => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
const viewportHeight = instance.scrollRect?.height ?? 0;
const scrollOffset = instance.scrollOffset ?? 0;
const itemIntersectsViewport =
item.end > scrollOffset && item.start < scrollOffset + viewportHeight;
if (itemIntersectsViewport) {
return false;
}
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
};
return () => {
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined;
};
}, [rowVirtualizer]);
const pendingMeasureFrameRef = useRef<number | null>(null);
const onTimelineImageLoad = useCallback(() => {
if (pendingMeasureFrameRef.current !== null) return;
pendingMeasureFrameRef.current = window.requestAnimationFrame(() => {
pendingMeasureFrameRef.current = null;
rowVirtualizer.measure();
});
}, [rowVirtualizer]);
useEffect(() => {
return () => {
const frame = pendingMeasureFrameRef.current;
if (frame !== null) {
window.cancelAnimationFrame(frame);
}
};
}, []);
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);
const renderRowContent = (row: TimelineRow) => (
return (
<div
className={cn(
"pb-4",
@@ -316,47 +278,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
>
{row.kind === "work" &&
(() => {
const groupId = row.id;
const groupedEntries = row.groupedEntries;
const isExpanded = expandedWorkGroups[groupId] ?? false;
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const showHeader = hasOverflow || !onlyToolEntries;
const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
return (
<div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
{showHeader && (
<div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
<p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
{groupLabel} ({groupedEntries.length})
</p>
{hasOverflow && (
<button
type="button"
className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
onClick={() => onToggleWorkGroup(groupId)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
)}
<div className="space-y-0.5">
{visibleEntries.map((workEntry) => (
<SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
))}
</div>
</div>
);
})()}
{row.kind === "work" && <WorkGroupSection groupedEntries={row.groupedEntries} />}
{row.kind === "message" &&
row.message.role === "user" &&
@@ -364,7 +286,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const userImages = row.message.attachments ?? [];
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
const terminalContexts = displayedUserMessage.contexts;
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
const canRevertAgentWork = typeof row.revertTurnCount === "number";
return (
<div className="flex justify-end">
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
@@ -384,15 +306,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onClick={() => {
const preview = buildExpandedImagePreview(userImages, image.id);
if (!preview) return;
onImageExpand(preview);
ctx.onImageExpand(preview);
}}
>
<img
src={image.previewUrl}
alt={image.name}
className="block h-auto max-h-[220px] w-full object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
/>
</button>
) : (
@@ -422,8 +342,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type="button"
size="xs"
variant="outline"
disabled={isRevertingCheckpoint || isWorking}
onClick={() => onRevertUserMessage(row.message.id)}
disabled={ctx.isRevertingCheckpoint || ctx.isWorking}
onClick={() => ctx.onRevertUserMessage(row.message.id)}
title="Revert to this message"
>
<Undo2Icon className="size-3" />
@@ -431,7 +351,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
)}
</div>
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, timestampFormat)}
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
</p>
</div>
</div>
@@ -444,10 +364,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
(() => {
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
const assistantTurnStillInProgress =
activeTurnInProgress &&
activeTurnId !== null &&
activeTurnId !== undefined &&
row.message.turnId === activeTurnId;
ctx.activeTurnInProgress &&
ctx.activeTurnId !== null &&
ctx.activeTurnId !== undefined &&
row.message.turnId === ctx.activeTurnId;
const assistantCopyState = resolveAssistantMessageCopyState({
text: row.message.text ?? null,
showCopyButton: row.showAssistantCopyButton,
@@ -459,7 +379,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
{ctx.completionSummary ? `Response • ${ctx.completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
@@ -467,76 +387,29 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div className="min-w-0 px-1 py-0.5">
<ChatMarkdown
text={messageText}
cwd={markdownCwd}
cwd={ctx.markdownCwd}
isStreaming={Boolean(row.message.streaming)}
/>
{(() => {
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
if (!turnSummary) return null;
const checkpointFiles = turnSummary.files;
if (checkpointFiles.length === 0) return null;
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const changedFileCountLabel = String(checkpointFiles.length);
const allDirectoriesExpanded =
changedFilesExpandedByTurnId[turnSummary.turnId] ?? true;
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
<span>Changed files ({changedFileCountLabel})</span>
{hasNonZeroStat(summaryStat) && (
<>
<span className="mx-1">•</span>
<DiffStatLabel
additions={summaryStat.additions}
deletions={summaryStat.deletions}
/>
</>
)}
</p>
<div className="flex items-center gap-1.5">
<Button
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={() =>
onSetChangedFilesExpanded(turnSummary.turnId, !allDirectoriesExpanded)
}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
}
>
View diff
</Button>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
);
})()}
<AssistantChangedFilesSection
turnSummary={row.assistantTurnDiffSummary}
routeThreadKey={ctx.routeThreadKey}
resolvedTheme={ctx.resolvedTheme}
onOpenTurnDiff={ctx.onOpenTurnDiff}
/>
<div className="mt-1.5 flex items-center gap-2">
<p className="text-[10px] text-muted-foreground/30">
{formatMessageMeta(
row.message.createdAt,
row.message.streaming
? formatElapsed(row.durationStart, nowIso)
: formatElapsed(row.durationStart, row.message.completedAt),
timestampFormat,
{row.message.streaming ? (
<LiveMessageMeta
createdAt={row.message.createdAt}
durationStart={row.durationStart}
timestampFormat={ctx.timestampFormat}
/>
) : (
formatMessageMeta(
row.message.createdAt,
formatElapsed(row.durationStart, row.message.completedAt),
ctx.timestampFormat,
)
)}
</p>
{assistantCopyState.visible ? (
@@ -559,9 +432,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div className="min-w-0 px-1 py-0.5">
<ProposedPlanCard
planMarkdown={row.proposedPlan.planMarkdown}
environmentId={activeThreadEnvironmentId}
cwd={markdownCwd}
workspaceRoot={workspaceRoot}
environmentId={ctx.activeThreadEnvironmentId}
cwd={ctx.markdownCwd}
workspaceRoot={ctx.workspaceRoot}
/>
</div>
)}
@@ -575,100 +448,205 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
<span>
{row.createdAt
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
: "Working..."}
{row.createdAt ? (
<>
Working for <WorkingTimer createdAt={row.createdAt} />
</>
) : (
"Working..."
)}
</span>
</div>
</div>
)}
</div>
);
}
if (!hasMessages && !isWorking) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
);
}
// ---------------------------------------------------------------------------
// Self-ticking components — bypass LegendList memoisation entirely.
// Each owns a `nowMs` state value consumed in the render output so the
// React Compiler cannot elide the re-render as a no-op.
// ---------------------------------------------------------------------------
/** Live "Working for Xs" label. */
function WorkingTimer({ createdAt }: { createdAt: string }) {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNowMs(Date.now()), 1000);
return () => clearInterval(id);
}, [createdAt]);
return <>{formatWorkingTimer(createdAt, new Date(nowMs).toISOString()) ?? "0s"}</>;
}
/** Live timestamp + elapsed duration for a streaming assistant message. */
function LiveMessageMeta({
createdAt,
durationStart,
timestampFormat,
}: {
createdAt: string;
durationStart: string | null | undefined;
timestampFormat: TimestampFormat;
}) {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNowMs(Date.now()), 1000);
return () => clearInterval(id);
}, [durationStart]);
const elapsed = durationStart
? formatElapsed(durationStart, new Date(nowMs).toISOString())
: null;
return <>{formatMessageMeta(createdAt, elapsed, timestampFormat)}</>;
}
// ---------------------------------------------------------------------------
// Extracted row sections — own their state / store subscriptions so changes
// re-render only the affected row, not the entire list.
// ---------------------------------------------------------------------------
/** Owns its own expand/collapse state so toggling re-renders only this row.
* State resets on unmount which is fine — work groups start collapsed. */
const WorkGroupSection = memo(function WorkGroupSection({
groupedEntries,
}: {
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
}) {
const [isExpanded, setIsExpanded] = useState(false);
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const showHeader = hasOverflow || !onlyToolEntries;
const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
return (
<div
ref={timelineRootRef}
data-timeline-root="true"
className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
>
{virtualizedRowCount > 0 && (
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
{virtualRows.map((virtualRow: VirtualItem) => {
const row = rows[virtualRow.index];
if (!row) return null;
return (
<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)` }}
>
{renderRowContent(row)}
</div>
);
})}
<div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
{showHeader && (
<div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
<p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
{groupLabel} ({groupedEntries.length})
</p>
{hasOverflow && (
<button
type="button"
className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
onClick={() => setIsExpanded((v) => !v)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
)}
{nonVirtualizedRows.map((row) => (
<div key={`non-virtual-row:${row.id}`}>{renderRowContent(row)}</div>
))}
<div className="space-y-0.5">
{visibleEntries.map((workEntry) => (
<SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
))}
</div>
</div>
);
});
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
type TimelineRow = MessagesTimelineRow;
/** Subscribes directly to the UI state store for expand/collapse state,
* so toggling re-renders only this component — not the entire list. */
const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({
turnSummary,
routeThreadKey,
resolvedTheme,
onOpenTurnDiff,
}: {
turnSummary: TurnDiffSummary | undefined;
routeThreadKey: string;
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
if (!turnSummary) return null;
const checkpointFiles = turnSummary.files;
if (checkpointFiles.length === 0) return null;
function formatWorkingTimer(startIso: string, endIso: string): string | null {
const startedAtMs = Date.parse(startIso);
const endedAtMs = Date.parse(endIso);
if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
return null;
}
return (
<AssistantChangedFilesSectionInner
turnSummary={turnSummary}
checkpointFiles={checkpointFiles}
routeThreadKey={routeThreadKey}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
);
});
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
if (elapsedSeconds < 60) {
return `${elapsedSeconds}s`;
}
/** Inner component that only mounts when there are actual changed files,
* so the store subscription is unconditional (no hooks after early return). */
function AssistantChangedFilesSectionInner({
turnSummary,
checkpointFiles,
routeThreadKey,
resolvedTheme,
onOpenTurnDiff,
}: {
turnSummary: TurnDiffSummary;
checkpointFiles: TurnDiffSummary["files"];
routeThreadKey: string;
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const allDirectoriesExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
);
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const changedFileCountLabel = String(checkpointFiles.length);
const hours = Math.floor(elapsedSeconds / 3600);
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
const seconds = elapsedSeconds % 60;
if (hours > 0) {
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
}
return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
<span>Changed files ({changedFileCountLabel})</span>
{hasNonZeroStat(summaryStat) && (
<>
<span className="mx-1">•</span>
<DiffStatLabel additions={summaryStat.additions} deletions={summaryStat.deletions} />
</>
)}
</p>
<div className="flex items-center gap-1.5">
<Button
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={() => setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
>
View diff
</Button>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
);
}
function formatMessageMeta(
createdAt: string,
duration: string | null,
timestampFormat: TimestampFormat,
): string {
if (!duration) return formatTimestamp(createdAt, timestampFormat);
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
}
// ---------------------------------------------------------------------------
// Leaf components
// ---------------------------------------------------------------------------
const UserMessageTerminalContextInlineLabel = memo(
function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
@@ -774,6 +752,62 @@ const UserMessageBody = memo(function UserMessageBody(props: {
);
});
// ---------------------------------------------------------------------------
// Structural sharing — reuse old row references when data hasn't changed
// so LegendList (and React) can skip re-rendering unchanged items.
// ---------------------------------------------------------------------------
/** Returns a structurally-shared copy of `rows`: for each row whose content
* hasn't changed since last call, the previous object reference is reused. */
function useStableRows(rows: MessagesTimelineRow[]): MessagesTimelineRow[] {
const prevState = useRef<StableMessagesTimelineRowsState>({
byId: new Map<string, MessagesTimelineRow>(),
result: [],
});
return useMemo(() => {
const nextState = computeStableMessagesTimelineRows(rows, prevState.current);
prevState.current = nextState;
return nextState.result;
}, [rows]);
}
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
function formatWorkingTimer(startIso: string, endIso: string): string | null {
const startedAtMs = Date.parse(startIso);
const endedAtMs = Date.parse(endIso);
if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
return null;
}
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
if (elapsedSeconds < 60) {
return `${elapsedSeconds}s`;
}
const hours = Math.floor(elapsedSeconds / 3600);
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
const seconds = elapsedSeconds % 60;
if (hours > 0) {
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
}
return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
}
function formatMessageMeta(
createdAt: string,
duration: string | null,
timestampFormat: TimestampFormat,
): string {
if (!duration) return formatTimestamp(createdAt, timestampFormat);
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
}
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
icon: LucideIcon;
className: string;
File diff suppressed because it is too large. Load diff
@@ -1,151 +0,0 @@
import { describe, expect, it } from "vitest";
import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
import { estimateTimelineMessageHeight } from "./timelineHeight";
describe("estimateTimelineMessageHeight", () => {
it("uses assistant sizing rules for assistant messages", () => {
expect(
estimateTimelineMessageHeight({
role: "assistant",
text: "a".repeat(144),
}),
).toBe(86.5);
});
it("uses assistant sizing rules for system messages", () => {
expect(
estimateTimelineMessageHeight({
role: "system",
text: "a".repeat(144),
}),
).toBe(86.5);
});
it("adds one attachment row for one or two user attachments", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }],
}),
).toBe(234);
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }, { id: "2" }],
}),
).toBe(234);
});
it("adds a second attachment row for three or four user attachments", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
}),
).toBe(350);
expect(
estimateTimelineMessageHeight({
role: "user",
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
}),
).toBe(350);
});
it("does not cap long user message estimates", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "a".repeat(56 * 120),
}),
).toBe(2736);
});
it("counts explicit newlines for user message estimates", () => {
expect(
estimateTimelineMessageHeight({
role: "user",
text: "first\nsecond\nthird",
}),
).toBe(162);
});
it("adds terminal context chrome without counting the hidden block as message text", () => {
const prompt = appendTerminalContextsToPrompt("Investigate this", [
{
terminalId: "default",
terminalLabel: "Terminal 1",
lineStart: 40,
lineEnd: 43,
text: [
"git status",
"M apps/web/src/components/chat/MessagesTimeline.tsx",
"?? tmp",
"",
].join("\n"),
},
]);
expect(
estimateTimelineMessageHeight({
role: "user",
text: prompt,
}),
).toBe(
estimateTimelineMessageHeight({
role: "user",
text: `${buildInlineTerminalContextText([{ header: "Terminal 1 lines 40-43" }])} Investigate this`,
}),
);
});
it("uses narrower width to increase user line wrapping", () => {
const message = {
role: "user" as const,
text: "a".repeat(52),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(140);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(118);
});
it("does not clamp user wrapping too aggressively on very narrow layouts", () => {
const message = {
role: "user" as const,
text: "a".repeat(20),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 100 })).toBe(184);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(118);
});
it("uses narrower width to increase assistant line wrapping", () => {
const message = {
role: "assistant" as const,
text: "a".repeat(200),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(154.75);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(86.5);
});
it("treats inline code as wider when estimating assistant markdown wrapping", () => {
const message = {
role: "assistant" as const,
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(" "),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(109.25);
});
});
-131
View File
@@ -1,131 +0,0 @@
import { deriveDisplayedUserMessageState } from "../lib/terminalContext";
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
const USER_CHARS_PER_LINE_FALLBACK = 56;
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;
// Full-app browser measurements land closer to a ~116px attachment row once
// the bubble shrinks to content width, so calibrate the estimate to that DOM.
const USER_ATTACHMENT_ROW_HEIGHT_PX = 116;
const USER_BUBBLE_WIDTH_RATIO = 0.8;
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
const USER_MONO_AVG_CHAR_WIDTH_PX = 8.4;
const ASSISTANT_AVG_CHAR_WIDTH_PX = 7.2;
const MIN_USER_CHARS_PER_LINE = 4;
const MIN_ASSISTANT_CHARS_PER_LINE = 20;
const ASSISTANT_INLINE_CODE_WIDTH_MULTIPLIER = 1.2;
const ASSISTANT_INLINE_CODE_WRAP_OVERHEAD_CHARS = 2;
const INLINE_CODE_SPAN_REGEX = /`([^`\n]+)`/g;
interface TimelineMessageHeightInput {
role: "user" | "assistant" | "system";
text: string;
attachments?: ReadonlyArray<{ id: string }>;
}
interface TimelineHeightEstimateLayout {
timelineWidthPx: number | null;
}
function estimateWrappedLineCount(text: string, charsPerLine: number): number {
if (text.length === 0) return 1;
// Avoid allocating via split for long logs; iterate once and count wrapped lines.
let lines = 0;
let currentLineLength = 0;
for (let index = 0; index < text.length; index += 1) {
if (text.charCodeAt(index) === 10) {
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
currentLineLength = 0;
continue;
}
currentLineLength += 1;
}
lines += Math.max(1, Math.ceil(currentLineLength / charsPerLine));
return lines;
}
function isFinitePositiveNumber(value: number | null | undefined): value is number {
return typeof value === "number" && Number.isFinite(value) && value > 0;
}
function estimateCharsPerLineForUser(timelineWidthPx: number | null): number {
if (!isFinitePositiveNumber(timelineWidthPx)) return USER_CHARS_PER_LINE_FALLBACK;
const bubbleWidthPx = timelineWidthPx * USER_BUBBLE_WIDTH_RATIO;
const textWidthPx = Math.max(bubbleWidthPx - USER_BUBBLE_HORIZONTAL_PADDING_PX, 0);
return Math.max(MIN_USER_CHARS_PER_LINE, Math.floor(textWidthPx / USER_MONO_AVG_CHAR_WIDTH_PX));
}
function estimateCharsPerLineForAssistant(timelineWidthPx: number | null): number {
if (!isFinitePositiveNumber(timelineWidthPx)) return ASSISTANT_CHARS_PER_LINE_FALLBACK;
const textWidthPx = Math.max(timelineWidthPx - ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX, 0);
return Math.max(
MIN_ASSISTANT_CHARS_PER_LINE,
Math.floor(textWidthPx / ASSISTANT_AVG_CHAR_WIDTH_PX),
);
}
function expandAssistantInlineCodeForEstimate(text: string) {
return text.replace(INLINE_CODE_SPAN_REGEX, (_match, code: string) =>
"x".repeat(
Math.max(
code.length + 2,
Math.ceil(
code.length * ASSISTANT_INLINE_CODE_WIDTH_MULTIPLIER +
ASSISTANT_INLINE_CODE_WRAP_OVERHEAD_CHARS,
),
),
),
);
}
export function estimateTimelineMessageHeight(
message: TimelineMessageHeightInput,
layout: TimelineHeightEstimateLayout = { timelineWidthPx: null },
): number {
if (message.role === "assistant") {
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(
expandAssistantInlineCodeForEstimate(message.text),
charsPerLine,
);
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
}
if (message.role === "user") {
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
const displayedUserMessage = deriveDisplayedUserMessageState(message.text);
const renderedText =
displayedUserMessage.contexts.length > 0
? [
buildInlineTerminalContextText(displayedUserMessage.contexts),
displayedUserMessage.visibleText,
]
.filter((part) => part.length > 0)
.join(" ")
: displayedUserMessage.visibleText;
const estimatedLines = estimateWrappedLineCount(renderedText, charsPerLine);
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 * 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(
expandAssistantInlineCodeForEstimate(message.text),
charsPerLine,
);
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
}
+15
View File
@@ -275,6 +275,20 @@ function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
);
}
/**
* A variant of `ComboboxList` without `ScrollArea`, for use when
* an external virtualizer (e.g. LegendList) owns the scroll container.
*/
function ComboboxListVirtualized({ className, ...props }: ComboboxPrimitive.List.Props) {
return (
<ComboboxPrimitive.List
className={cn("not-empty:px-1 not-empty:py-1", className)}
data-slot="combobox-list"
{...props}
/>
);
}
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
return <ComboboxPrimitive.Clear className={className} data-slot="combobox-clear" {...props} />;
}
@@ -371,6 +385,7 @@ export {
ComboboxEmpty,
ComboboxValue,
ComboboxList,
ComboboxListVirtualized,
ComboboxClear,
ComboboxStatus,
ComboboxRow,
+3 -5
View File
@@ -80,6 +80,7 @@
"@dnd-kit/utilities": "^3.2.2",
"@effect/atom-react": "catalog:",
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "3.0.0-beta.44",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/client-runtime": "workspace:*",
@@ -88,7 +89,6 @@
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
@@ -462,6 +462,8 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@legendapp/list": ["@legendapp/[email protected]", "", { "dependencies": { "use-sync-external-store": "^1.5.0" }, "peerDependencies": { "react": "*" } }, "sha512-loGRve78NuZ5k8Z54ZSDNOtv3dVBM1SeBCRtm1EYtZiDIZ8SyMVcYpUGgFpGuNKk71+9/NuM9hvScrgf7+4E+A=="],
"@lexical/clipboard": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/html": "0.41.0", "@lexical/list": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-Ex5lPkb4NBBX1DCPzOAIeHBJFH1bJcmATjREaqpnTfxCbuOeQkt44wchezUA0oDl+iAxNZ3+pLLWiUju9icoSA=="],
"@lexical/code": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "lexical": "0.41.0", "prismjs": "^1.30.0" } }, "sha512-0hoNi1KC9/N3SBOGcOcFqnT0OpwmcRRAhfxTKMGqfCtCvAMzULVwZ8RWc9/NV9bKYESgBTW5D9xkDANP2mspHg=="],
@@ -740,8 +742,6 @@
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.8.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XItJt+rG8c5Wn/2L/bnxys85rBpm0BfMbhb4zmPVLXAKY9POrp1xd6IbU4PKoOI+jSEGc3vntPRfLGSgXfE2Ig=="],
"@tanstack/react-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.13.23" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XnMRnHQ23piOVj2bzJqHrRrLg4r+F86fuBcwteKfbIjJrtGxb4z7tIvPVAe4B+4UVwo9G4Giuz5fmapcrnZ0OQ=="],
"@tanstack/router-core": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/history": "1.161.6", "@tanstack/store": "^0.9.1", "cookie-es": "^2.0.0", "seroval": "^1.4.2", "seroval-plugins": "^1.4.2", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" } }, "sha512-M/CxrTGKk1fsySJjd+Pzpbi3YLDz+cJSutDjSTMy12owWlOgHV/I6kzR0UxyaBlHraM6XgMHNA0XdgsS1fa4Nw=="],
"@tanstack/router-generator": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/router-core": "1.167.3", "@tanstack/router-utils": "1.161.6", "@tanstack/virtual-file-routes": "1.161.6", "prettier": "^3.5.0", "recast": "^0.23.11", "source-map": "^0.7.4", "tsx": "^4.19.2", "zod": "^3.24.2" } }, "sha512-Q/49wxURbft1oNOvo/eVAWZq/lNLK3nBGlavqhLToAYXY6LCzfMtRlE/y3XPHzYC9pZc09u5jvBR1k1E4hyGDQ=="],
@@ -752,8 +752,6 @@
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-K013lUJEFJK2ofFQ/hZKJUmCnpcV00ebLyOyFOWQvyQHUOZp/iYO84BM6aOGiV81JzwbX0APTVmW8YI7yiG5oA=="],
"@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-zSz2Z2HNyLjCplANTDyl3BcdQJc2k1+yyFoKhNRmCr7V7dY8o8q5m8uFTI1/Pg1kL+Hgrz6u3Xo6eFUB7l66cg=="],
"@tanstack/virtual-file-routes": ["@tanstack/[email protected]", "", {}, "sha512-EGWs9yvJA821pUkwkiZLQW89CzUumHyJy8NKq229BubyoWXfDw1oWnTJYSS/hhbLiwP9+KpopjeF5wWwnCCyeQ=="],
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],