🤯 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: share project indexing and deduplicate ignored directories (#19269)
Arvin Xuc589e1f9b9ef
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex d3a712f1343..a581d7eac3d 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -4,6 +4,10 @@ import { access, readFile, realpath, stat } from 'node:fs/promises';import path from 'node:path';import type { SkillDirectoryDeps } from '@lobechat/device-control';+import {+ defaultGetProjectFileIndex,+ defaultSearchProjectFiles,+} from '@lobechat/device-control/project-file-index';import {type AuditSafePathsParams,type AuditSafePathsResult,@@ -30,7 +34,6 @@ import {type PickFileResult,type PrepareSkillDirectoryParams,type PrepareSkillDirectoryResult,- type ProjectFileIndexEntry,type ProjectFileIndexParams,type ProjectFileIndexResult,type ProjectFileSearchParams,@@ -70,7 +73,6 @@ import { ControllerModule, IpcMethod } from './index';const logger = createLogger('controllers:LocalFileCtr');const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;-const PROJECT_FILE_GLOB_LIMIT = 5000;/*** Image extensions `readFile` uploads to file storage instead of refusing as@@ -132,8 +134,6 @@ const resolveNearestExistingRealPath = async (targetPath: string): Promise<strin}};-const toPosixRelativePath = (filePath: string) => filePath.split(path.sep).join('/');-const normalizeContentType = (contentType: string): string =>contentType.split(';')[0].trim().toLowerCase();@@ -216,50 +216,6 @@ const serializePreviewFile = ({return { contentType: normalizedContentType, type: 'binary' };};-const createProjectFileEntry = (- root: string,- absolutePath: string,- isDirectory: boolean,- gitIgnored?: boolean,-): ProjectFileIndexEntry => {- const relativePath = toPosixRelativePath(path.relative(root, absolutePath));-- return {- ...(gitIgnored ? { gitIgnored: true } : {}),- isDirectory,- name: path.basename(absolutePath),- path: absolutePath,- relativePath: isDirectory ? `${relativePath}/` : relativePath,- };-};--const collectProjectDirectories = (files: string[], root: string): ProjectFileIndexEntry[] => {- const directories = new Set<string>();-- for (const filePath of files) {- let current = path.dirname(filePath);- while (current && current !== root && current.startsWith(`${root}${path.sep}`)) {- if (directories.has(current)) break;- directories.add(current);- current = path.dirname(current);- }- }-- return [...directories].map((directory) => createProjectFileEntry(root, directory, true));-};--const createDetectedProjectFileEntry = async (- root: string,- absolutePath: string,-): Promise<ProjectFileIndexEntry> => {- try {- const stats = await stat(absolutePath);- return createProjectFileEntry(root, absolutePath, stats.isDirectory());- } catch {- return createProjectFileEntry(root, absolutePath, false);- }-};-const resolveSafePathRealPrefixes = async (): Promise<string[]> => {const prefixes = new Set<string>(SAFE_PATH_PREFIXES);@@ -687,166 +643,24 @@ export default class LocalFileCtr extends ControllerModule {@IpcMethod()async getProjectFileIndex(params: ProjectFileIndexParams = {}): Promise<ProjectFileIndexResult> {- const { execa } = await import('execa');- const requestedScope = params.scope || process.cwd();const startedAt = Date.now();+ const result = await defaultGetProjectFileIndex(params);- try {- const rootResult = await execa(- 'git',- ['-C', requestedScope, 'rev-parse', '--show-toplevel'],- {- reject: false,- timeout: 5000,- },- );- const root = rootResult.exitCode === 0 ? rootResult.stdout.trim() : requestedScope;-- if (rootResult.exitCode === 0) {- const [trackedResult, untrackedResult, ignoredResult] = await Promise.all([- execa(- 'git',- ['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],- {- reject: false,- timeout: 10_000,- },- ),- execa(- 'git',- [- '-C',- root,- '-c',- 'core.quotepath=false',- 'ls-files',- '--others',- '--exclude-standard',- ],- { reject: false, timeout: 10_000 },- ),- execa(- 'git',- [- '-C',- root,- '-c',- 'core.quotepath=false',- 'ls-files',- '--others',- '--ignored',- '--exclude-standard',- '--directory',- ],- { reject: false, timeout: 10_000 },- ),- ]);-- if (trackedResult.exitCode !== 0) {- throw new Error(trackedResult.stderr || 'git ls-files failed');- }-- const files = [- ...trackedResult.stdout.split('\n'),- ...(untrackedResult.exitCode === 0 ? untrackedResult.stdout.split('\n') : []),- ]- .map((item) => item.trim())- .filter(Boolean)- .map((relativePath) => path.resolve(root, relativePath));-- const ignoredEntries =- ignoredResult.exitCode === 0- ? ignoredResult.stdout- .split('\n')- .map((item) => item.trim())- .filter(Boolean)- .map((relativePath) => {- const isDirectory = relativePath.endsWith('/');- const normalizedPath = isDirectory ? relativePath.slice(0, -1) : relativePath;- return createProjectFileEntry(- root,- path.resolve(root, normalizedPath),- isDirectory,- true,- );- })- : [];-- const seen = new Set<string>();- const fileEntries = files- .filter((filePath) => {- if (seen.has(filePath)) return false;- seen.add(filePath);- return true;- })- .map((filePath) => createProjectFileEntry(root, filePath, false));-- const uniqueIgnoredEntries = ignoredEntries.filter((entry) => {- if (seen.has(entry.path)) return false;- seen.add(entry.path);- return true;- });- const indexedPaths = [...fileEntries, ...uniqueIgnoredEntries].map((entry) => entry.path);- const entries = [- ...collectProjectDirectories(indexedPaths, root),- ...fileEntries,- ...uniqueIgnoredEntries,- ];- logger.debug('Project file index built from git', {- duration: Date.now() - startedAt,- entries: entries.length,- files: fileEntries.length,- ignored: uniqueIgnoredEntries.length,- requestedScope,- root,- });- await this.approveProjectRootForPreview(root);-- return {- entries,- indexedAt: new Date().toISOString(),- root,- source: 'git',- };- }- } catch (error) {- logger.debug('Git project file index failed, falling back to glob', {- error,- requestedScope,- });- }-- const fallback = await this.searchService.glob({- limit: PROJECT_FILE_GLOB_LIMIT,- pattern: '**/*',- scope: requestedScope,- });- const files = fallback.files.map((filePath) => path.resolve(filePath));- const entries = await Promise.all(- files.map((filePath) => createDetectedProjectFileEntry(requestedScope, filePath)),- );-- logger.debug('Project file index built from glob', {+ logger.debug('Project file index completed', {duration: Date.now() - startedAt,- entries: entries.length,- engine: fallback.engine,- requestedScope,+ entries: result.entries.length,+ requestedScope: params.scope,+ root: result.root,+ source: result.source,});- await this.approveProjectRootForPreview(requestedScope);+ await this.approveProjectRootForPreview(result.root);- return {- entries,- indexedAt: new Date().toISOString(),- root: requestedScope,- source: 'glob',- };+ return result;}@IpcMethod()async searchProjectFiles(params: ProjectFileSearchParams): Promise<ProjectFileSearchResult> {const startedAt = Date.now();- const { defaultSearchProjectFiles } =- await import('@lobechat/device-control/project-file-index');const result = await defaultSearchProjectFiles(params);logger.debug('Project file search completed', {diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.tsindex e5433c5fc2f..18e4a2199d5 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts@@ -7,8 +7,8 @@ import { type App } from '@/core/App';import LocalFileCtr from '../LocalFileCtr';-const { execaMock, ipcMainHandleMock, fetchMock } = vi.hoisted(() => ({- execaMock: vi.fn(),+const { getProjectFileIndexMock, ipcMainHandleMock, fetchMock } = vi.hoisted(() => ({+ getProjectFileIndexMock: vi.fn(),ipcMainHandleMock: vi.fn(),fetchMock: vi.fn(),}));@@ -17,8 +17,8 @@ vi.mock('@/utils/net-fetch', () => ({netFetch: fetchMock,}));-vi.mock('execa', () => ({- execa: execaMock,+vi.mock('@lobechat/device-control/project-file-index', () => ({+ defaultGetProjectFileIndex: getProjectFileIndexMock,}));// Mock file-loaders@@ -781,109 +781,52 @@ describe('LocalFileCtr', () => {});describe('getProjectFileIndex', () => {- it('should build a project file index from git files', async () => {- execaMock- .mockResolvedValueOnce({ exitCode: 0, stdout: '/workspace/project' })- .mockResolvedValueOnce({- exitCode: 0,- stdout: 'src/index.ts\nsrc/components/Button.tsx',- })- .mockResolvedValueOnce({ exitCode: 0, stdout: 'tmp/local.ts' })- .mockResolvedValueOnce({ exitCode: 0, stdout: '.env.local\ncache/' });-- const result = await localFileCtr.getProjectFileIndex({ scope: '/workspace/project' });-- expect(result.source).toBe('git');- expect(result.root).toBe('/workspace/project');- expect(result.entries).toEqual(- expect.arrayContaining([- expect.objectContaining({- isDirectory: true,- path: '/workspace/project/src',- relativePath: 'src/',- }),- expect.objectContaining({- isDirectory: false,- path: '/workspace/project/src/index.ts',- relativePath: 'src/index.ts',- }),- expect.objectContaining({- isDirectory: false,- path: '/workspace/project/tmp/local.ts',- relativePath: 'tmp/local.ts',- }),- expect.objectContaining({- gitIgnored: true,- isDirectory: false,- path: '/workspace/project/.env.local',- relativePath: '.env.local',- }),- expect.objectContaining({- gitIgnored: true,- isDirectory: true,- path: '/workspace/project/cache',- relativePath: 'cache/',- }),- ]),- );- expect(result).not.toHaveProperty('totalCount');- });+ it.each(['git', 'glob'] as const)(+ 'returns the shared %s index and authorizes its root for previews',+ async (source) => {+ const index = {+ entries: [+ {+ gitIgnored: true,+ isDirectory: true,+ name: '.husky',+ path: '/workspace/project/.husky',+ relativePath: '.husky/',+ },+ ],+ indexedAt: '2026-09-08T00:00:00.000Z',+ root: '/workspace/project',+ source,+ };+ getProjectFileIndexMock.mockResolvedValueOnce(index);- it('should fall back to glob when git indexing fails', async () => {- execaMock.mockResolvedValueOnce({ exitCode: 1, stdout: '' });- mockSearchService.glob.mockResolvedValue({- engine: 'fast-glob',- files: ['/workspace/project/src', '/workspace/project/src/index.ts'],- success: true,- total_files: 2,- });- vi.mocked(mockFsPromises.stat).mockImplementation(async (filePath: string) => ({- isDirectory: () => filePath === '/workspace/project/src',- }));+ const result = await localFileCtr.getProjectFileIndex({ scope: '/workspace/project/src' });- const result = await localFileCtr.getProjectFileIndex({ scope: '/workspace/project' });+ expect(result).toEqual(index);+ expect(getProjectFileIndexMock).toHaveBeenCalledWith({ scope: '/workspace/project/src' });+ expect(+ mockLocalFileProtocolManager.approveIndexedProjectRoot,+ ).toHaveBeenCalledExactlyOnceWith('/workspace/project');+ },+ );- expect(mockSearchService.glob).toHaveBeenCalledWith({- limit: 5000,- pattern: '**/*',- scope: '/workspace/project',- });- expect(result.source).toBe('glob');- expect(result.entries).toEqual([- expect.objectContaining({- isDirectory: true,- path: '/workspace/project/src',- relativePath: 'src/',- }),- expect.objectContaining({- isDirectory: false,- path: '/workspace/project/src/index.ts',- relativePath: 'src/index.ts',- }),- ]);- expect(result).not.toHaveProperty('totalCount');- });+ it('does not authorize a preview root when indexing fails', async () => {+ getProjectFileIndexMock.mockRejectedValueOnce(new Error('Index unavailable'));- it('should mark glob entries as files when stat fails', async () => {- execaMock.mockResolvedValueOnce({ exitCode: 1, stdout: '' });- mockSearchService.glob.mockResolvedValue({- engine: 'fast-glob',- files: ['/workspace/project/src/index.ts'],- success: true,- total_files: 1,- });- vi.mocked(mockFsPromises.stat).mockRejectedValue(new Error('missing'));+ await expect(+ localFileCtr.getProjectFileIndex({ scope: '/workspace/project' }),+ ).rejects.toThrow('Index unavailable');+ expect(mockLocalFileProtocolManager.approveIndexedProjectRoot).not.toHaveBeenCalled();+ });- const result = await localFileCtr.getProjectFileIndex({ scope: '/workspace/project' });+ it('returns the index even when preview authorization fails', async () => {+ const index = { entries: [], indexedAt: '', root: '/workspace/project', source: 'git' };+ getProjectFileIndexMock.mockResolvedValueOnce(index);+ mockLocalFileProtocolManager.approveIndexedProjectRoot.mockRejectedValueOnce(+ new Error('Authorization unavailable'),+ );- expect(result.source).toBe('glob');- expect(result.entries).toEqual([- expect.objectContaining({- isDirectory: false,- path: '/workspace/project/src/index.ts',- relativePath: 'src/index.ts',- }),- ]);+ await expect(localFileCtr.getProjectFileIndex()).resolves.toEqual(index);});});diff --git a/packages/device-control/src/__tests__/projectFileIndex.test.ts b/packages/device-control/src/__tests__/projectFileIndex.test.tsindex 21f0016abb6..94c304de58d 100644--- a/packages/device-control/src/__tests__/projectFileIndex.test.ts+++ b/packages/device-control/src/__tests__/projectFileIndex.test.ts@@ -1,7 +1,8 @@-import { execFileSync } from 'node:child_process';+import { execFile, execFileSync } from 'node:child_process';import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';+import { promisify } from 'node:util';import { afterEach, describe, expect, it } from 'vitest';@@ -56,11 +57,37 @@ describe('defaultGetProjectFileIndex', () => {expect(result).not.toHaveProperty('totalCount');});+ it('keeps ignored directories unique when git also lists their descendants', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-index-ignored-parents-'));+ cleanup.push(dir);+ const git = promisify(execFile);+ await git('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });+ await mkdir(path.join(dir, '.husky', '_'), { recursive: true });+ await writeFile(path.join(dir, '.husky', '_', '.gitignore'), '**\n');+ await writeFile(path.join(dir, '.husky', '_', 'hook'), 'hook\n');++ const result = await defaultGetProjectFileIndex({ scope: dir });+ const paths = result.entries.map((entry) => entry.relativePath);++ expect(result.source).toBe('git');+ expect(new Set(paths).size).toBe(paths.length);+ for (const relativePath of ['.husky/', '.husky/_/']) {+ expect(result.entries.filter((entry) => entry.relativePath === relativePath)).toEqual([+ expect.objectContaining({ gitIgnored: true, isDirectory: true }),+ ]);+ }+ expect(paths).toContain('.husky/_/hook');+ });+it('falls back to a glob walk when the scope is not a git repo', async () => {const dir = await mkdtemp(path.join(tmpdir(), 'dc-index-glob-'));cleanup.push(dir);await mkdir(path.join(dir, 'nested', 'deep'), { recursive: true });await mkdir(path.join(dir, '.agents'), { recursive: true });+ await mkdir(path.join(dir, 'empty'));+ await mkdir(path.join(dir, '.hidden-empty'));+ await mkdir(path.join(dir, 'node_modules', 'dependency'), { recursive: true });+ await writeFile(path.join(dir, 'node_modules', 'dependency', 'index.js'), 'ignored');await writeFile(path.join(dir, 'one.txt'), '1\n');await writeFile(path.join(dir, 'nested', 'deep', 'two.txt'), '2\n');await writeFile(path.join(dir, '.agents', 'config.md'), '# cfg\n');@@ -68,7 +95,12 @@ describe('defaultGetProjectFileIndex', () => {const result = await defaultGetProjectFileIndex({ scope: dir });expect(result.source).toBe('glob');+ const rels = result.entries.map((entry) => entry.relativePath);const byRel = Object.fromEntries(result.entries.map((e) => [e.relativePath, e]));+ expect(new Set(rels).size).toBe(rels.length);+ expect(byRel['empty/']?.isDirectory).toBe(true);+ expect(byRel['.hidden-empty/']?.isDirectory).toBe(true);+ expect(rels.some((relativePath) => relativePath.startsWith('node_modules/'))).toBe(false);// Nested files are present and attached to synthesized directory entries.expect(byRel['nested/deep/two.txt']?.isDirectory).toBe(false);diff --git a/packages/device-control/src/projectFileIndex.ts b/packages/device-control/src/projectFileIndex.tsindex eda6e356ef8..20a80a80487 100644--- a/packages/device-control/src/projectFileIndex.ts+++ b/packages/device-control/src/projectFileIndex.ts@@ -85,34 +85,48 @@ const buildEntries = (return true;});- const indexedPaths = [...fileEntries, ...ignoredEntries].map((entry) => entry.path);+ return addMissingParentDirectories([...fileEntries, ...ignoredEntries], root);+};++const addMissingParentDirectories = (+ entries: ProjectFileIndexEntry[],+ root: string,+): ProjectFileIndexEntry[] => {+ const indexedPaths = entries.map((entry) => entry.path);+ const seen = new Set(indexedPaths);+ // Explicit entries carry ignore metadata; only synthesize missing parents.+ const directories = collectProjectDirectories(indexedPaths, root).filter(+ (entry) => !seen.has(entry.path),+ );- return [...collectProjectDirectories(indexedPaths, root), ...fileEntries, ...ignoredEntries];+ return [...directories, ...entries];};-const collectGlobFilePaths = async (scope: string): Promise<string[]> => {- const files: string[] = [];+const collectGlobEntries = async (scope: string): Promise<ProjectFileIndexEntry[]> => {+ const entries: ProjectFileIndexEntry[] = [];const stream = fg.stream('**/*', {cwd: scope,dot: true,ignore: ['**/node_modules/**', '**/.git/**'],- onlyFiles: true,+ objectMode: true,+ onlyFiles: false,});- for await (const relativePath of stream as AsyncIterable<string>) {- files.push(path.resolve(scope, relativePath));- if (files.length >= PROJECT_FILE_GLOB_LIMIT) break;+ for await (const entry of stream as AsyncIterable<fg.Entry>) {+ entries.push(+ createProjectFileEntry(scope, path.resolve(scope, entry.path), entry.dirent.isDirectory()),+ );+ if (entries.length >= PROJECT_FILE_GLOB_LIMIT) break;}- return files;+ return addMissingParentDirectories(entries, scope);};/**- * Portable project file index for the CLI (and any non-desktop device). Prefers+ * Shared project file index for desktop and CLI devices. Prefers* `git ls-files` (tracked + untracked + collapsed ignored entries,* submodule-aware) to enumerate the repo, falling back to a `fast-glob` walk- * when the scope is not a git repo. Mirrors the desktop- * `LocalFileCtr.getProjectFileIndex` output shape.+ * when the scope is not a git repo. Platform adapters own preview authorization.*/export const defaultGetProjectFileIndex = async (params: ProjectFileIndexParams = {},@@ -180,11 +194,8 @@ export const defaultGetProjectFileIndex = async (// fall through to glob}- // Non-git scope: walk with fast-glob. `dot: true` keeps dot-directories (e.g.- // `.agents`) that the git path would surface via `ls-files`, and `onlyFiles`- // leaves directory entries to `buildEntries` so nesting matches the git path.- const files = await collectGlobFilePaths(requestedScope);- const entries = buildEntries(files, requestedScope);+ // Include hidden and empty directories consistently across desktop and CLI.+ const entries = await collectGlobEntries(requestedScope);return {entries,