🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(working-sidebar): stop the Files view toggle from stalling on large projects (#23740)
AmAzing-8b604ba13f31
diff --git a/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts b/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.tsindex 3bed46af741..796436c3cec 100644--- a/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts+++ b/src/features/Conversation/WorkingSidebar/Files/fileFilter.test.ts@@ -65,6 +65,42 @@ describe('filterProjectFileEntries', () => {'src/index.ts',]);});++ it('filters a large project in linear time', () => {+ // 20,000 directories x 2 files. Scanning every file per directory took+ // seconds here; one pass over the files takes a few milliseconds.+ const large: ProjectFileIndexEntry[] = [];+ for (let dir = 0; dir < 20_000; dir += 1) {+ const directory = `pkg${dir}/`;+ large.push({+ isDirectory: true,+ name: `pkg${dir}`,+ path: `/repo/pkg${dir}`,+ relativePath: directory,+ });+ for (let file = 0; file < 2; file += 1) {+ const relativePath = `${directory}file${file}.ts`;+ large.push({+ gitIgnored: dir % 2 === 1,+ isDirectory: false,+ name: `file${file}.ts`,+ path: `/repo/${relativePath}`,+ relativePath,+ });+ }+ }++ const startedAt = performance.now();+ const result = filterProjectFileEntries(large, new Set(), {+ changedOnly: false,+ hideIgnored: true,+ });+ const elapsed = performance.now() - startedAt;++ // Half the directories hold only ignored files, so they drop out entirely.+ expect(result).toHaveLength(10_000 * 3);+ expect(elapsed).toBeLessThan(300);+ });});describe('mergeMissingDeletedEntries', () => {diff --git a/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts b/src/features/Conversation/WorkingSidebar/Files/fileFilter.tsindex 1998467734b..3f5b914e71e 100644--- a/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts+++ b/src/features/Conversation/WorkingSidebar/Files/fileFilter.ts@@ -6,9 +6,6 @@ export interface ProjectFileDisplayFilter {hideIgnored: boolean;}-const isPathInsideDirectory = (filePath: string, directoryPath: string) =>- filePath.startsWith(directoryPath);-const getDirectoryPaths = (relativePath: string): string[] => {const segments = relativePath.split('/');return segments.slice(0, -1).map((_, index) => `${segments.slice(0, index + 1).join('/')}/`);@@ -66,14 +63,29 @@ export const filterProjectFileEntries = (return !filter.changedOnly || dirtyFilePaths.has(entry.relativePath);});- const visibleFilePaths = new Set(matchingFiles.map((entry) => entry.relativePath));+ const visibleFilePaths = new Set<string>();+ // Every directory above a visible file, collected in one pass. Asking each+ // directory to scan every file instead is quadratic and stalls a large+ // project for most of a second per filter change.+ const visibleDirectoryPaths = new Set<string>();+ for (const { relativePath } of matchingFiles) {+ visibleFilePaths.add(relativePath);+ let end = relativePath.lastIndexOf('/');+ while (end > 0) {+ const directoryPath = relativePath.slice(0, end + 1);+ // An ancestor already recorded has had its own ancestors recorded too.+ if (visibleDirectoryPaths.has(directoryPath)) break;+ visibleDirectoryPaths.add(directoryPath);+ end = relativePath.lastIndexOf('/', end - 1);+ }+ }return entries.filter((entry) => {if (!entry.isDirectory) return visibleFilePaths.has(entry.relativePath);if (filter.hideIgnored && entry.gitIgnored) return false;- return matchingFiles.some((file) =>- isPathInsideDirectory(file.relativePath, entry.relativePath),+ return visibleDirectoryPaths.has(+ entry.relativePath.endsWith('/') ? entry.relativePath : `${entry.relativePath}/`,);});};diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsxindex 9dccc3b6e2c..1e8a2806092 100644--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx@@ -27,7 +27,7 @@ import {SearchIcon,XIcon,} from 'lucide-react';-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { SkeletonList } from '@/components/Skeleton/NavPanel/List';@@ -123,6 +123,8 @@ const PROJECT_FILE_TREE_SEARCH_LIMIT = 200;type FileViewMode = 'project' | 'changes';+const NO_DIRTY_FILE_PATHS: Set<string> = new Set();+const getProjectRootName = (root: string) => {const normalizedRoot = root.replace(/[\\/]+$/, '');return normalizedRoot.split(/[\\/]/).pop() || root;@@ -245,7 +247,10 @@ const Files = memo<FilesProps>(const projectRootName = getProjectRootName(projectRoot);const normalizedDebouncedQuery = debouncedQuery.trim();const isFiltering = normalizedDebouncedQuery.length > 0;- const changedOnly = viewMode === 'changes';+ // The buttons flip on `viewMode` at once; the tree, which a view change+ // rebuilds from scratch, follows in a deferred render so the click never+ // waits on it.+ const changedOnly = useDeferredValue(viewMode) === 'changes';const hasDisplayFilter = isFiltering || changedOnly || hideIgnored;const workingTreeGitStatus = useMemo(() => buildGitStatusEntries(gitFiles), [gitFiles]);const dirtyFilePaths = useMemo(@@ -311,7 +316,7 @@ const Files = memo<FilesProps>(const searchEntries = isSandbox ? sandboxMatches : remoteMatches;const isSearching = !isSandbox && !!normalizedDebouncedQuery && isSearchingRemote;- const displayEntries = useMemo(() => {+ const baseEntries = useMemo(() => {const indexedEntries = isFiltering? (searchEntries ?? []): [...entries, ...collapsedChildren];@@ -320,29 +325,40 @@ const Files = memo<FilesProps>(isFiltering ? [] : (gitFiles?.deleted ?? []),projectRoot,);- const visibleEntries = entriesWithDeleted.filter(- (entry) => !isExcludedProjectFileEntry(entry),- );- return filterProjectFileEntries(visibleEntries, dirtyFilePaths, {- changedOnly,- hideIgnored,- });- }, [- changedOnly,- collapsedChildren,- dirtyFilePaths,- entries,- gitFiles?.deleted,- hideIgnored,- isFiltering,- projectRoot,- searchEntries,- ]);- const nodes = useMemo(- () => buildTreeNodes(displayEntries, projectRootName),- [displayEntries, projectRootName],+ return entriesWithDeleted.filter((entry) => !isExcludedProjectFileEntry(entry));+ }, [collapsedChildren, entries, gitFiles?.deleted, isFiltering, projectRoot, searchEntries]);+ // The two views keep separate entries and nodes, so the project tree+ // survives a visit to Changes: switching back hands the tree the very same+ // nodes array, which it recognises instead of normalising every path again.+ const projectEntries = useMemo(+ () =>+ filterProjectFileEntries(baseEntries, NO_DIRTY_FILE_PATHS, {+ changedOnly: false,+ hideIgnored,+ }),+ [baseEntries, hideIgnored],+ );+ const changesEntries = useMemo(+ () =>+ changedOnly+ ? filterProjectFileEntries(baseEntries, dirtyFilePaths, {+ changedOnly: true,+ hideIgnored,+ })+ : undefined,+ [baseEntries, changedOnly, dirtyFilePaths, hideIgnored],+ );+ const displayEntries = changesEntries ?? projectEntries;+ const projectNodes = useMemo(+ () => buildTreeNodes(projectEntries, projectRootName),+ [projectEntries, projectRootName],+ );+ const changesNodes = useMemo(+ () => (changesEntries ? buildTreeNodes(changesEntries, projectRootName) : undefined),+ [changesEntries, projectRootName],);+ const nodes = changesNodes ?? projectNodes;const gitStatus = useMemo(() =>prefixGitStatusPaths(diff --git a/src/features/ExplorerTree/adapter/normalize.test.ts b/src/features/ExplorerTree/adapter/normalize.test.tsindex 855aaa9c688..b1a0ea6c773 100644--- a/src/features/ExplorerTree/adapter/normalize.test.ts+++ b/src/features/ExplorerTree/adapter/normalize.test.ts@@ -4,6 +4,22 @@ import type { ExplorerTreeNode } from '../types';import { isDescendantOf, normalizeTree, remapIdsToPaths, remapPathsToIds } from './normalize';describe('normalizeTree', () => {+ it('reuses the result for the same nodes array and rebuilds for a new one', () => {+ const nodes: ExplorerTreeNode[] = [+ { id: 'folder', isFolder: true, name: 'src', parentId: null },+ { id: 'file', name: 'index.ts', parentId: 'folder' },+ ];++ const first = normalizeTree(nodes);++ expect(normalizeTree(nodes)).toBe(first);++ const next = normalizeTree([...nodes, { id: 'other', name: 'README.md', parentId: null }]);++ expect(next).not.toBe(first);+ expect(next.paths).toEqual(['src/', 'src/index.ts', 'README.md']);+ });+it('keeps duplicate sibling names addressable by stable ids', () => {const nodes: ExplorerTreeNode[] = [{ id: 'folder-a', isFolder: true, name: 'Docs', parentId: null },diff --git a/src/features/ExplorerTree/adapter/normalize.ts b/src/features/ExplorerTree/adapter/normalize.tsindex 8b59bb00690..11bb30014ba 100644--- a/src/features/ExplorerTree/adapter/normalize.ts+++ b/src/features/ExplorerTree/adapter/normalize.ts@@ -44,7 +44,22 @@ const dedupeName = (taken: Set<string>, rawName: string, isFolder: boolean): strreturn fallback;};+// Normalising a large tree walks and re-keys every node. A host that toggles+// between two node arrays (a filtered view and the full one) hands the same+// array back, so remember the result per array instead of redoing the walk.+// Callers treat `nodes` as immutable; a changed tree is a new array.+const normalizedTreeCache = new WeakMap<object, NormalizedTree<unknown>>();+export const normalizeTree = <TData>(nodes: ExplorerTreeNode<TData>[]): NormalizedTree<TData> => {+ const cached = normalizedTreeCache.get(nodes) as NormalizedTree<TData> | undefined;+ if (cached) return cached;++ const normalized = buildNormalizedTree(nodes);+ normalizedTreeCache.set(nodes, normalized as NormalizedTree<unknown>);+ return normalized;+};++const buildNormalizedTree = <TData>(nodes: ExplorerTreeNode<TData>[]): NormalizedTree<TData> => {const pathById = new Map<string, string>();const idByPath = new Map<string, string>();const nodeById = new Map<string, ExplorerTreeNode<TData>>();diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsxindex 21c2c5a739b..763bd07dd33 100644--- a/src/features/ExplorerTree/view/ExplorerTree.tsx+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx@@ -69,6 +69,11 @@ export const buildFileAppearanceCSS = (paths: string[], declarations: string): s).join(',\n')} {\n${declarations}\n}`;+// Folder paths are the only ones ending in a slash (see buildSegment). Expansion+// scans skip the files up front: asking the model about every file of a large+// project costs tens of milliseconds per scan, on every expand and every reset.+const isDirectoryPath = (path: string): boolean => path.endsWith('/');+const getItemSafely = (model: FileTreeModel, path: string): FileTreeItemHandle | null => {try {return model.getItem(path);@@ -301,6 +306,7 @@ function ExplorerTreeInner<TData>(props: ExplorerTreeInnerProps<TData>) {const a = adapterRef.current;const expandedPaths: string[] = [];for (const path of a.paths) {+ if (!isDirectoryPath(path)) continue;if (asDirectory(getItemSafely(model, path))?.isExpanded()) expandedPaths.push(path);}const selectedPaths = model.getSelectedPaths().filter((path) => a.idByPath.has(path));@@ -349,6 +355,7 @@ function ExplorerTreeInner<TData>(props: ExplorerTreeInnerProps<TData>) {const a = adapterRef.current;const nextExpanded: string[] = [];for (const [id, path] of a.pathById) {+ if (!isDirectoryPath(path)) continue;const dir = asDirectory(getItemSafely(model, path));if (dir?.isExpanded()) nextExpanded.push(id);}@@ -396,6 +403,7 @@ function ExplorerTreeInner<TData>(props: ExplorerTreeInnerProps<TData>) {const nextExpandedIds: string[] = [];const directoryEntries: { dir: FileTreeDirectoryHandle; shouldExpand: boolean }[] = [];for (const [id, path] of a.pathById) {+ if (!isDirectoryPath(path)) continue;const dir = asDirectory(getItemSafely(model, path));if (!dir) continue;const shouldExpand = nextExpandedIdSet.has(id);@@ -450,6 +458,7 @@ function ExplorerTreeInner<TData>(props: ExplorerTreeInnerProps<TData>) {const nextExpandedIds: string[] = [];const directoryEntries: { dir: FileTreeDirectoryHandle; shouldExpand: boolean }[] = [];for (const [id, path] of next.pathById) {+ if (!isDirectoryPath(path)) continue;const dir = asDirectory(getItemSafely(model, path));if (!dir) continue;const shouldExpand = nextExpandedIdSet.has(id);@@ -473,6 +482,7 @@ function ExplorerTreeInner<TData>(props: ExplorerTreeInnerProps<TData>) {if (!nextExpandedIds) {nextExpandedIds = [];for (const [id, path] of prev.pathById) {+ if (!isDirectoryPath(path)) continue;const dir = asDirectory(getItemSafely(model, path));if (dir?.isExpanded()) nextExpandedIds.push(id);}@@ -612,6 +622,7 @@ function ExplorerTreeInner<TData>(props: ExplorerTreeInnerProps<TData>) {const want = new Set(ids);const a = adapterRef.current;for (const [nodeId, path] of a.pathById) {+ if (!isDirectoryPath(path)) continue;const dir = asDirectory(getItemSafely(model, path));if (!dir) continue;const shouldExpand = want.has(nodeId);