The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 14:45 UTC
fix(web): opening a very large folder no longer freezes the Files panel (#29996)
Co-authored-by: Nathan Wong <20381195+thelogicmatrix@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Nathan Wong committed
Nov 15, 2026 at 00:27 UTC
f05cd350d255c37525af11d5a2fb04c7e4a98617
4 files changed
+230
-5
apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
+120
-1
@@ -14,7 +14,15 @@ const entries: readonly ProjectEntry[] = [
14
{ path: "README.md", kind: "file" },
15
];
16
const loadingDirectories: ReadonlySet<string> = new Set();
17
-const directory = {
17
+const directory: {
18
+ entries: readonly ProjectEntry[];
19
+ load: () => Promise<void>;
20
+ refresh: () => void;
21
+ ready: boolean;
22
+ error: null;
23
+ isPending: boolean;
24
+ loadingDirectories: ReadonlySet<string>;
25
+} = {
26
entries,
27
load: () => Promise.resolve(),
28
refresh: () => {},
@@ -46,6 +54,15 @@ function findTreeRow(path: string): HTMLElement | null {
54
return null;
55
}
56
57
+function withDirectoryListing(listing: readonly ProjectEntry[]): Disposable {
58
+ directory.entries = listing;
59
+ return {
60
+ [Symbol.dispose]: () => {
61
+ directory.entries = entries;
62
+ },
63
+ };
64
+}
65
+
66
describe("FileBrowserPanel", () => {
67
it("copies with the pointer and returns to the row after keyboard dismissal", async () => {
68
await using _screen = await render(
@@ -118,6 +135,108 @@ describe("FileBrowserPanel", () => {
135
await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1));
136
});
137
138
+ it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => {
139
+ using _listing = withDirectoryListing(entries);
140
+ const renderPanel = () => (
141
+ <FileBrowserPanel
142
+ environmentId={EnvironmentId.make("env-files")}
143
+ cwd="/repo-large-folder-1"
144
+ projectName="repo"
145
+ selectedPath={null}
146
+ selectedPathRevealId={0}
147
+ onOpenFile={() => {}}
148
+ workspaceMutationId={null}
149
+ />
150
+ );
151
+ await using screen = await render(renderPanel());
152
+ await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
153
+ findTreeRow("src/")!.click();
154
+ await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
155
+
156
+ directory.entries = [
157
+ ...entries,
158
+ // Out of sort order, because inserting in order hides the cost of each insert.
159
+ ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
160
+ const name = String((index * 7_919) % 2_000).padStart(4, "0");
161
+ return { path: `src/generated-${name}`, kind: "directory" };
162
+ }),
163
+ ];
164
+ await screen.rerender(renderPanel());
165
+
166
+ await vi.waitFor(() => expect(findTreeRow("src/generated-0000/")).not.toBeNull());
167
+ expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true");
168
+ });
169
+
170
+ it("keeps the selected file through a very large listing without reopening it", async () => {
171
+ const onOpenFile = vi.fn();
172
+ const renderPanel = () => (
173
+ <FileBrowserPanel
174
+ environmentId={EnvironmentId.make("env-files")}
175
+ cwd="/repo-large-folder-2"
176
+ projectName="repo"
177
+ selectedPath="src/aaa.ts"
178
+ selectedPathRevealId={1}
179
+ onOpenFile={onOpenFile}
180
+ workspaceMutationId={null}
181
+ />
182
+ );
183
+ using _listing = withDirectoryListing([...entries, { path: "src/aaa.ts", kind: "file" }]);
184
+ await using screen = await render(renderPanel());
185
+ await vi.waitFor(() =>
186
+ expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true"),
187
+ );
188
+
189
+ directory.entries = [
190
+ ...directory.entries,
191
+ ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
192
+ const name = String((index * 7_919) % 2_000).padStart(4, "0");
193
+ return { path: `src/generated-${name}.ts`, kind: "file" };
194
+ }),
195
+ ];
196
+ await screen.rerender(renderPanel());
197
+
198
+ await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
199
+ expect(findTreeRow("src/aaa.ts")?.getAttribute("aria-selected")).toBe("true");
200
+ expect(findTreeRow("src/")?.getAttribute("aria-expanded")).toBe("true");
201
+ expect(onOpenFile).not.toHaveBeenCalled();
202
+ });
203
+
204
+ it("keeps an open search accurate when a very large folder listing arrives", async () => {
205
+ const renderPanel = () => (
206
+ <FileBrowserPanel
207
+ environmentId={EnvironmentId.make("env-files")}
208
+ cwd="/repo-large-folder-3"
209
+ projectName="repo"
210
+ selectedPath={null}
211
+ selectedPathRevealId={0}
212
+ onOpenFile={() => {}}
213
+ workspaceMutationId={null}
214
+ />
215
+ );
216
+ using _listing = withDirectoryListing([
217
+ ...entries,
218
+ { path: "lib", kind: "directory" },
219
+ { path: "lib/generated-existing.ts", kind: "file" },
220
+ ]);
221
+ await using screen = await render(renderPanel());
222
+ const search = page.getByRole("searchbox", { name: "Search repo files" });
223
+ await userEvent.fill(search, "generated-");
224
+ await vi.waitFor(() => expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull());
225
+
226
+ directory.entries = [
227
+ ...directory.entries,
228
+ ...Array.from({ length: 2_000 }, (_, index): ProjectEntry => {
229
+ const name = String((index * 7_919) % 2_000).padStart(4, "0");
230
+ return { path: `src/generated-${name}.ts`, kind: "file" };
231
+ }),
232
+ ];
233
+ await screen.rerender(renderPanel());
234
+
235
+ await vi.waitFor(() => expect(findTreeRow("src/generated-0000.ts")).not.toBeNull());
236
+ expect(findTreeRow("lib/generated-existing.ts")).not.toBeNull();
237
+ await expect.element(search).toHaveValue("generated-");
238
+ });
239
+
240
it("mod+f from a tree row, or the panel find command, focuses the file search", async () => {
241
await using _screen = await render(
242
<FileBrowserPanel
apps/web/src/components/files/FileBrowserPanel.tsx
+9
-1
@@ -35,7 +35,7 @@ import {
35
setAllDirectoriesExpanded,
36
writeExpandedDirectories,
37
} from "./fileTreeExpansion";
38
-import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";
38
+import { buildFileTreePathUpdates, shouldRebuildFileTree } from "./fileTreePathReconciliation";
39
import { loadFileAncestors } from "./loadFileAncestors";
40
import { useDirectoryEntries } from "./useDirectoryEntries";
41
import { useProjectPathSearch } from "~/state/queries";
@@ -438,6 +438,14 @@ export default function FileBrowserPanel({
438
return;
439
}
440
const updates = buildFileTreePathUpdates(previousTreePaths, treePaths);
441
+ if (shouldRebuildFileTree(previousTreePaths, treePaths, updates)) {
442
+ // A reset keeps old search matches, so search closes first and recomputes afterwards.
443
+ const activeSearch = model.isSearchOpen() ? model.getSearchValue() : null;
444
+ if (activeSearch !== null) model.closeSearch();
445
+ model.resetPaths(treePaths, { initialExpandedPaths: [...expandedPathsRef.current] });
446
+ if (activeSearch !== null) model.setSearch(activeSearch);
447
+ return;
448
+ }
449
if (updates.length > 0) model.batch(updates);
450
}, [ready, entryKinds, model, treePaths]);
451
apps/web/src/components/files/fileTreePathReconciliation.test.ts
new
+54
@@ -0,0 +1,54 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { buildFileTreePathUpdates, shouldRebuildFileTree } from "./fileTreePathReconciliation";
4
+
5
+const folder = (name: string, count: number) =>
6
+ Array.from({ length: count }, (_, index) => `${name}/entry-${index}`);
7
+
8
+const decide = (previous: readonly string[], next: readonly string[]) =>
9
+ shouldRebuildFileTree(previous, next, buildFileTreePathUpdates(previous, next));
10
+
11
+describe("buildFileTreePathUpdates", () => {
12
+ it("removes a folder once and skips the paths inside it", () => {
13
+ expect(
14
+ buildFileTreePathUpdates(["src/", "src/a/", "src/a/b/", "src/a/c.ts"], ["src/"]),
15
+ ).toEqual([{ type: "remove", path: "src/a/", recursive: true }]);
16
+ });
17
+
18
+ it("does not treat a sibling that shares a name prefix as inside a removed folder", () => {
19
+ expect(buildFileTreePathUpdates(["src/a/", "src/ab/", "src/a.ts"], [])).toEqual([
20
+ { type: "remove", path: "src/a/", recursive: true },
21
+ { type: "remove", path: "src/ab/", recursive: true },
22
+ { type: "remove", path: "src/a.ts" },
23
+ ]);
24
+ });
25
+});
26
+
27
+describe("shouldRebuildFileTree", () => {
28
+ it("rebuilds when many paths land in a folder that dominates the tree", () => {
29
+ const existing = folder("big", 50_000);
30
+ expect(decide(existing, [...existing, ...addTo("big", 301)])).toBe(true);
31
+ });
32
+
33
+ it("counts a folder's subfolders as siblings, whose paths end in a slash", () => {
34
+ const existing = folder("big", 50_000).map((path) => `${path}/`);
35
+ const added = addTo("big", 301).map((path) => `${path}/`);
36
+ expect(decide(existing, [...existing, ...added])).toBe(true);
37
+ expect(decide(existing, existing.slice(301))).toBe(true);
38
+ });
39
+
40
+ it("batches a few hundred paths into a small folder beside a large unrelated one", () => {
41
+ const existing = folder("big", 50_000);
42
+ expect(decide(existing, [...existing, ...folder("small", 301)])).toBe(false);
43
+ });
44
+
45
+ it("batches many operations spread thinly across many small folders", () => {
46
+ const existing = folder("big", 50_000);
47
+ const added = Array.from({ length: 1_000 }, (_, index) => `small-${index}/file.ts`);
48
+ expect(decide(existing, [...existing, ...added])).toBe(false);
49
+ });
50
+});
51
+
52
+function addTo(name: string, count: number) {
53
+ return Array.from({ length: count }, (_, index) => `${name}/added-${index}`);
54
+}
apps/web/src/components/files/fileTreePathReconciliation.ts
+47
-3
@@ -1,26 +1,70 @@
1
import type { FileTreeBatchOperation } from "@pierre/trees";
2
3
+// A batched operation reworks its folder's siblings, while a rebuild reworks every path. On flat
4
+// folders of 50,000 and 332,000 entries a rebuild won somewhere between 200 and 500 operations.
5
+const REBUILD_COST_IN_FOLDER_OPERATIONS = 300;
6
+
7
+function parentOf(path: string): string {
8
+ const end = path.endsWith("/") ? path.length - 1 : path.length;
9
+ return path.slice(0, Math.max(0, path.lastIndexOf("/", end - 1)));
10
+}
11
+
12
+function countByParent(paths: readonly string[]): Map<string, number> {
13
+ const counts = new Map<string, number>();
14
+ for (const path of paths) {
15
+ const parent = parentOf(path);
16
+ counts.set(parent, (counts.get(parent) ?? 0) + 1);
17
+ }
18
+ return counts;
19
+}
20
+
21
+export function shouldRebuildFileTree(
22
+ previousPaths: readonly string[],
23
+ nextPaths: readonly string[],
24
+ updates: readonly FileTreeBatchOperation[],
25
+): boolean {
26
+ // Up to this many operations, the estimate below can't exceed the rebuild, so skip counting.
27
+ if (updates.length <= REBUILD_COST_IN_FOLDER_OPERATIONS) return false;
28
+ const previousCounts = countByParent(previousPaths);
29
+ const nextCounts = countByParent(nextPaths);
30
+ let batchWork = 0;
31
+ for (const update of updates) {
32
+ if (update.type !== "add" && update.type !== "remove") continue;
33
+ const parent = parentOf(update.path);
34
+ batchWork += Math.max(previousCounts.get(parent) ?? 0, nextCounts.get(parent) ?? 0);
35
+ }
36
+ const rebuildWork = Math.max(previousPaths.length, nextPaths.length);
37
+ return batchWork > REBUILD_COST_IN_FOLDER_OPERATIONS * rebuildWork;
38
+}
39
+
40
function pathDepth(path: string): number {
41
return path.split("/").filter(Boolean).length;
42
}
43
44
+function isInsideRemovedDirectory(path: string, removedRoots: ReadonlySet<string>): boolean {
45
+ for (let slash = path.indexOf("/"); slash !== -1; slash = path.indexOf("/", slash + 1)) {
46
+ if (removedRoots.has(path.slice(0, slash + 1))) return true;
47
+ }
48
+ return false;
49
+}
50
+
51
export function buildFileTreePathUpdates(
52
previousPaths: readonly string[],
53
nextPaths: readonly string[],
54
): FileTreeBatchOperation[] {
55
const previous = new Set(previousPaths);
56
const next = new Set(nextPaths);
13
- const removedDirectoryRoots: string[] = [];
57
+ const removedDirectoryRoots = new Set<string>();
58
const updates: FileTreeBatchOperation[] = [];
59
60
const removedPaths = previousPaths
61
.filter((path) => !next.has(path))
62
.toSorted((left, right) => pathDepth(left) - pathDepth(right));
63
for (const path of removedPaths) {
20
- if (removedDirectoryRoots.some((directory) => path.startsWith(directory))) continue;
64
+ if (isInsideRemovedDirectory(path, removedDirectoryRoots)) continue;
65
const recursive = path.endsWith("/");
66
updates.push({ type: "remove", path, ...(recursive ? { recursive: true } : {}) });
23
- if (recursive) removedDirectoryRoots.push(path);
67
+ if (recursive) removedDirectoryRoots.add(path);
68
}
69
70
const addedPaths = nextPaths