@devries-cameron20 / t3code-1 / commits / f36dadb782
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(web): virtualize large changed-file trees (#21482)

Yash Singh committed Oct 18, 2026 at 23:36 UTC f36dadb782b8c167724801221a2b196d5ef4c0db
2 files changed +377 -36
apps/web/src/components/chat/ChangedFilesTree.browser.test.tsx
+193 -1
@@ -1,5 +1,8 @@
1 +import "~/index.css";
2 +
3 import { RunId } from "@t3tools/contracts";
2 -import { act, type ReactNode } from "react";
4 +import { LegendList } from "@legendapp/list/react";
5 +import { act, type ReactNode, useState } from "react";
6 import { createRoot, type Root } from "react-dom/client";
7 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8
@@ -40,6 +43,14 @@ function buttonWithText(label: string) {
43 return button!;
44 }
45
46 +async function scrollTo(element: HTMLElement, top: number) {
47 + await act(async () => {
48 + element.scrollTop = top;
49 + element.dispatchEvent(new Event("scroll"));
50 + await new Promise(requestAnimationFrame);
51 + });
52 +}
53 +
54 describe("ChangedFilesCard", () => {
55 it("summarizes a single file with a singular label", async () => {
56 await render(
@@ -92,6 +103,187 @@ describe("ChangedFilesCard", () => {
103 });
104
105 describe("ChangedFilesTree", () => {
106 + const manyFiles = Array.from({ length: 16_185 }, (_, index) =>
107 + file(`src/file-${index.toString().padStart(5, "0")}.ts`),
108 + );
109 +
110 + it("virtualizes above 250 expanded files and disables it when folders collapse below that count", async () => {
111 + await render(
112 + <div style={{ height: 280, overflowY: "auto" }}>
113 + <ChangedFilesTree
114 + runId={RunId.make("run-1")}
115 + files={[...manyFiles.slice(0, 250), file("extra/overflow.ts")]}
116 + allDirectoriesExpanded={false}
117 + resolvedTheme="light"
118 + onOpenTurnDiff={() => {}}
119 + />
120 + </div>,
121 + );
122 + expect(container.querySelectorAll("button").length).toBe(2);
123 +
124 + await act(async () => buttonWithText("src").click());
125 + expect(container.querySelectorAll("button").length).toBe(252);
126 + expect(text()).toContain("file-00249.ts");
127 + expect(text()).not.toContain("overflow.ts");
128 +
129 + await act(async () => buttonWithText("extra").click());
130 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
131 + expect(text()).not.toContain("file-00249.ts");
132 +
133 + await act(async () => buttonWithText("extra").click());
134 + expect(container.querySelectorAll("button").length).toBe(252);
135 + expect(text()).toContain("file-00249.ts");
136 + expect(text()).not.toContain("overflow.ts");
137 + });
138 +
139 + it("keeps expand-all bounded and opens files after scrolling the surrounding viewport", async () => {
140 + const onOpenTurnDiff = vi.fn();
141 + const onFileContextMenu = vi.fn();
142 + function Card() {
143 + const [expanded, setExpanded] = useState(false);
144 + return (
145 + <ChangedFilesCard
146 + runId={RunId.make("run-1")}
147 + files={manyFiles}
148 + allDirectoriesExpanded={expanded}
149 + resolvedTheme="light"
150 + onToggleAllDirectories={() => setExpanded(!expanded)}
151 + onOpenTurnDiff={onOpenTurnDiff}
152 + onFileContextMenu={onFileContextMenu}
153 + />
154 + );
155 + }
156 + await render(
157 + <div style={{ height: 280, overflowY: "auto" }}>
158 + <div style={{ height: 420 }} />
159 + <Card />
160 + </div>,
161 + );
162 + const viewport = container.firstElementChild as HTMLElement;
163 + await scrollTo(viewport, 420);
164 + const collapsedHeight = viewport.scrollHeight;
165 + await act(async () =>
166 + container.querySelector<HTMLButtonElement>('[aria-label="Expand all folders"]')!.click(),
167 + );
168 +
169 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
170 + expect(viewport.scrollHeight).toBeGreaterThan(collapsedHeight + 400_000);
171 + expect(text()).toContain("file-00000.ts");
172 + expect(text()).not.toContain("file-08000.ts");
173 +
174 + await scrollTo(viewport, 420 + 8_001 * 28);
175 + expect(text()).toContain("file-08000.ts");
176 + expect(text()).not.toContain("file-00000.ts");
177 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
178 +
179 + await scrollTo(viewport, viewport.scrollHeight);
180 + expect(text()).toContain("file-16184.ts");
181 + await act(async () => buttonWithText("file-16184.ts").click());
182 + expect(onOpenTurnDiff).toHaveBeenCalledWith(RunId.make("run-1"), "src/file-16184.ts");
183 + await act(async () =>
184 + buttonWithText("file-16184.ts").dispatchEvent(
185 + new MouseEvent("contextmenu", { bubbles: true, cancelable: true }),
186 + ),
187 + );
188 + expect(onFileContextMenu).toHaveBeenCalledWith("src/file-16184.ts", expect.anything());
189 +
190 + await act(async () =>
191 + container.querySelector<HTMLButtonElement>('[aria-label="Collapse all folders"]')!.click(),
192 + );
193 + expect(viewport.scrollHeight).toBe(collapsedHeight);
194 + expect(text()).not.toContain("file-16184.ts");
195 + });
196 +
197 + it("virtualizes a single expanded folder inside a LegendList timeline item", async () => {
198 + await render(
199 + <LegendList
200 + data={["message", "files"]}
201 + keyExtractor={(item) => item}
202 + estimatedItemSize={280}
203 + style={{ height: 280 }}
204 + renderItem={({ item }) =>
205 + item === "message" ? (
206 + <div style={{ height: 420 }}>Earlier message</div>
207 + ) : (
208 + <ChangedFilesTree
209 + runId={RunId.make("run-1")}
210 + files={manyFiles}
211 + allDirectoriesExpanded={false}
212 + resolvedTheme="light"
213 + onOpenTurnDiff={() => {}}
214 + />
215 + )
216 + }
217 + />,
218 + );
219 + const viewport = container.firstElementChild as HTMLElement;
220 + await scrollTo(viewport, 420);
221 + await act(async () => buttonWithText("src").click());
222 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
223 +
224 + await scrollTo(viewport, 420 + 8_001 * 28);
225 + expect(text()).toContain("file-08000.ts");
226 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
227 +
228 + await scrollTo(viewport, viewport.scrollHeight);
229 + expect(text()).toContain("file-16184.ts");
230 + await scrollTo(viewport, 420);
231 + await act(async () => buttonWithText("src").click());
232 + expect(text()).not.toContain("file-00000.ts");
233 + expect(container.querySelectorAll("button").length).toBe(1);
234 + });
235 +
236 + it("keeps a focused file mounted when scrolling it out of view", async () => {
237 + await render(
238 + <div style={{ height: 280, overflowY: "auto" }}>
239 + <ChangedFilesTree
240 + runId={RunId.make("run-1")}
241 + files={manyFiles}
242 + allDirectoriesExpanded
243 + resolvedTheme="light"
244 + onOpenTurnDiff={() => {}}
245 + />
246 + </div>,
247 + );
248 + const viewport = container.firstElementChild as HTMLElement;
249 + const focusedFile = buttonWithText("file-00000.ts");
250 + await act(async () => focusedFile.focus());
251 + await scrollTo(viewport, 8_001 * 28);
252 + expect(text()).toContain("file-08000.ts");
253 + expect(document.activeElement).toBe(focusedFile);
254 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
255 +
256 + await act(async () => focusedFile.blur());
257 + expect(text()).not.toContain("file-00000.ts");
258 + });
259 +
260 + it("remeasures the visible rows when the viewport or preceding content resizes", async () => {
261 + const content = (height: number, precedingHeight: number) => (
262 + <div style={{ height, overflowY: "auto" }}>
263 + <div>
264 + <div style={{ height: precedingHeight }} />
265 + <ChangedFilesTree
266 + runId={RunId.make("run-1")}
267 + files={manyFiles}
268 + allDirectoriesExpanded
269 + resolvedTheme="light"
270 + onOpenTurnDiff={() => {}}
271 + />
272 + </div>
273 + </div>
274 + );
275 + await render(content(140, 0));
276 + const viewport = container.firstElementChild as HTMLElement;
277 + await scrollTo(viewport, 8_001 * 28);
278 + const beforeResize = container.querySelectorAll("button").length;
279 + await render(content(560, 560));
280 + await expect
281 + .poll(() => container.querySelectorAll("button").length)
282 + .toBeGreaterThan(beforeResize);
283 + expect(text()).toContain("file-07980.ts");
284 + expect(container.querySelectorAll("button").length).toBeLessThan(60);
285 + });
286 +
287 const cases = [
288 {
289 name: "a compacted single-chain directory",
apps/web/src/components/chat/ChangedFilesTree.tsx
+184 -35
@@ -1,5 +1,5 @@
1 import { type RunId } from "@t3tools/contracts";
2 -import { type MouseEvent, memo, useState } from "react";
2 +import { type MouseEvent, type ReactNode, memo, useLayoutEffect, useRef, useState } from "react";
3 import { type TurnDiffFileChange } from "../../types";
4 import {
5 buildTurnDiffTree,
@@ -15,8 +15,16 @@ import { Button } from "../ui/button";
15 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
16 import { MiddleTruncate } from "../ui/middle-truncate";
17 import { MorphIcon } from "~/components/MorphIcon";
18 +import { observeResize } from "~/lib/observeResize";
19
20 const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
21 +const VIRTUALIZE_AFTER_FILES = 250;
22 +const ROW_OVERSCAN = 8;
23 +
24 +interface ChangedFileRow {
25 + node: TurnDiffTreeNode;
26 + depth: number;
27 +}
28
29 export type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void;
30
@@ -161,44 +169,45 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
169 });
170 };
171
164 - const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
172 + const rows = collectExpandedRows(treeNodes, expandedDirectories, allDirectoriesExpanded);
173 + const virtualized =
174 + rows.reduce((count, row) => count + (row.node.kind === "file" ? 1 : 0), 0) >
175 + VIRTUALIZE_AFTER_FILES;
176 +
177 + const renderRow = ({ node, depth }: ChangedFileRow) => {
178 const leftPadding = 8 + depth * 14;
179 if (node.kind === "directory") {
180 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
181 return (
169 - <div key={`dir:${node.path}`}>
170 - <button
171 - type="button"
172 - data-scroll-anchor-ignore
173 - aria-expanded={isExpanded}
174 - className="group flex w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
175 - style={{ paddingLeft: `${leftPadding}px` }}
176 - onClick={() => toggleDirectory(node.path)}
177 - >
178 - <ChevronRightIcon
179 - aria-hidden="true"
180 - className={cn(
181 - "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
182 - isExpanded && "rotate-90",
183 - )}
184 - />
185 - <MorphIcon
186 - className="size-3.5 shrink-0 text-muted-foreground/75"
187 - icon={isExpanded ? Folder : FolderClosed}
188 - />
189 - <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
190 - {node.name}
191 - </span>
192 - {hasNonZeroStat(node.stat) && (
193 - <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
194 - <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
195 - </span>
182 + <button
183 + key={`dir:${node.path}`}
184 + type="button"
185 + data-scroll-anchor-ignore
186 + aria-expanded={isExpanded}
187 + className="group flex h-7 w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
188 + style={{ paddingLeft: `${leftPadding}px` }}
189 + onClick={() => toggleDirectory(node.path)}
190 + >
191 + <ChevronRightIcon
192 + aria-hidden="true"
193 + className={cn(
194 + "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
195 + isExpanded && "rotate-90",
196 )}
197 - </button>
198 - {isExpanded && (
199 - <div>{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}</div>
197 + />
198 + <MorphIcon
199 + className="size-3.5 shrink-0 text-muted-foreground/75"
200 + icon={isExpanded ? Folder : FolderClosed}
201 + />
202 + <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
203 + {node.name}
204 + </span>
205 + {hasNonZeroStat(node.stat) && (
206 + <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
207 + <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
208 + </span>
209 )}
201 - </div>
210 + </button>
211 );
212 }
213
@@ -206,7 +215,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
215 <button
216 key={`file:${node.path}`}
217 type="button"
209 - className="group flex w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
218 + className="group flex h-7 w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
219 style={{ paddingLeft: `${leftPadding}px` }}
220 onClick={() => onOpenTurnDiff(runId, node.path)}
221 onContextMenu={
@@ -239,9 +248,149 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
248 );
249 };
250
242 - return <div className="p-2">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
251 + return <ChangedFilesRows rows={rows} renderRow={renderRow} virtualized={virtualized} />;
252 });
253
254 +function ChangedFilesRows({
255 + rows,
256 + renderRow,
257 + virtualized,
258 +}: {
259 + rows: ReadonlyArray<ChangedFileRow>;
260 + renderRow: (row: ChangedFileRow) => ReactNode;
261 + virtualized: boolean;
262 +}) {
263 + const containerRef = useRef<HTMLDivElement>(null);
264 + const rowSizeRef = useRef<HTMLDivElement>(null);
265 + const [range, setRange] = useState({ start: 0, end: 40, rowHeight: 28 });
266 + const [focusedPath, setFocusedPath] = useState<string | null>(null);
267 +
268 + useLayoutEffect(() => {
269 + const container = containerRef.current;
270 + const rowSize = rowSizeRef.current;
271 + if (!virtualized || !container || !rowSize) return;
272 +
273 + // The card is inside a virtualized timeline item, so its own scrollTop is always zero.
274 + // Observe its ancestors too: streaming text and timeline layout can move the card.
275 + const ancestors: HTMLElement[] = [container, rowSize];
276 + let scrollElement: HTMLElement | null = null;
277 + for (let parent = container.parentElement; parent; parent = parent.parentElement) {
278 + ancestors.push(parent);
279 + if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) {
280 + scrollElement = parent;
281 + break;
282 + }
283 + }
284 +
285 + const measure = () => {
286 + const rowHeight = rowSize.getBoundingClientRect().height;
287 + if (rowHeight <= 0) return;
288 + const listTop = container.getBoundingClientRect().top;
289 + const viewportTop = scrollElement
290 + ? scrollElement.getBoundingClientRect().top + scrollElement.clientTop
291 + : 0;
292 + const viewportHeight = scrollElement?.clientHeight ?? document.documentElement.clientHeight;
293 + const start = Math.max(
294 + 0,
295 + Math.min(rows.length, Math.floor((viewportTop - listTop) / rowHeight) - ROW_OVERSCAN),
296 + );
297 + const end = Math.max(
298 + start,
299 + Math.min(
300 + rows.length,
301 + Math.ceil((viewportTop + viewportHeight - listTop) / rowHeight) + ROW_OVERSCAN,
302 + ),
303 + );
304 + setRange((current) =>
305 + current.start === start && current.end === end && current.rowHeight === rowHeight
306 + ? current
307 + : { start, end, rowHeight },
308 + );
309 + };
310 + measure();
311 + const scrollTarget = scrollElement ?? globalThis.window;
312 + let frame = 0;
313 + const onScroll = () => {
314 + if (frame) return;
315 + frame = requestAnimationFrame(() => {
316 + frame = 0;
317 + measure();
318 + });
319 + };
320 + scrollTarget.addEventListener("scroll", onScroll, { passive: true });
321 + globalThis.window.addEventListener("resize", onScroll);
322 + const stopObserving = observeResize(ancestors, measure);
323 + return () => {
324 + scrollTarget.removeEventListener("scroll", onScroll);
325 + globalThis.window.removeEventListener("resize", onScroll);
326 + if (frame) cancelAnimationFrame(frame);
327 + stopObserving();
328 + };
329 + }, [virtualized, rows.length]);
330 +
331 + const focusedIndex =
332 + focusedPath === null ? -1 : rows.findIndex((row) => row.node.path === focusedPath);
333 + const start = virtualized ? range.start : 0;
334 + const end = virtualized ? Math.min(rows.length, range.end) : rows.length;
335 + const indices = Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index);
336 + // Keep keyboard focus on its row when mouse scrolling moves it outside the render window.
337 + if (focusedIndex >= 0 && focusedIndex < start) indices.unshift(focusedIndex);
338 + if (focusedIndex >= end) indices.push(focusedIndex);
339 + return (
340 + <div className="p-2">
341 + <div
342 + ref={containerRef}
343 + className="relative"
344 + style={virtualized ? { height: rows.length * range.rowHeight } : undefined}
345 + onFocusCapture={(event) => {
346 + const row = event.target.closest<HTMLElement>("[data-changed-file-row]");
347 + setFocusedPath(row?.dataset.changedFileRow ?? null);
348 + }}
349 + onBlurCapture={(event) => {
350 + if (!event.currentTarget.contains(event.relatedTarget)) setFocusedPath(null);
351 + }}
352 + >
353 + {virtualized && (
354 + <div
355 + ref={rowSizeRef}
356 + aria-hidden="true"
357 + className="pointer-events-none invisible absolute h-7"
358 + />
359 + )}
360 + {indices.map((index) => {
361 + const row = rows[index]!;
362 + return (
363 + <div
364 + key={`${row.node.kind}:${row.node.path}`}
365 + data-changed-file-row={row.node.path}
366 + className={virtualized ? "absolute inset-x-0" : undefined}
367 + style={virtualized ? { top: index * range.rowHeight } : undefined}
368 + >
369 + {renderRow(row)}
370 + </div>
371 + );
372 + })}
373 + </div>
374 + </div>
375 + );
376 +}
377 +
378 +function collectExpandedRows(
379 + nodes: ReadonlyArray<TurnDiffTreeNode>,
380 + overrides: Readonly<Record<string, boolean>>,
381 + allDirectoriesExpanded: boolean,
382 + depth = 0,
383 + rows: ChangedFileRow[] = [],
384 +): ChangedFileRow[] {
385 + for (const node of nodes) {
386 + rows.push({ node, depth });
387 + if (node.kind === "directory" && (overrides[node.path] ?? allDirectoriesExpanded)) {
388 + collectExpandedRows(node.children, overrides, allDirectoriesExpanded, depth + 1, rows);
389 + }
390 + }
391 + return rows;
392 +}
393 +
394 function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
395 const paths: string[] = [];
396 for (const node of nodes) {