Skip to content

🤯 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.

✨ feat(device-control): add project file search with fuzzy matching and gateway integration (#16526)

Innei287b8bb2288b
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 6df82122444..b04bcd8078d 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -5,6 +5,7 @@ import path from 'node:path';
import {
defaultGetLocalFilePreview,
defaultGetProjectFileIndex,
+ defaultSearchProjectFiles,
type DeviceControlDeps,
executeDeviceRpc,
} from '@lobechat/device-control';
@@ -356,6 +357,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const deviceControlDeps: DeviceControlDeps = {
getLocalFilePreview: defaultGetLocalFilePreview,
getProjectFileIndex: defaultGetProjectFileIndex,
+ searchProjectFiles: defaultSearchProjectFiles,
};
client.on('rpc_request', async (request: RpcRequestMessage) => {
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 374a54520cb..cb045095610 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -383,6 +383,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
},
getLocalFilePreview: (params) => this.localFileCtr.getLocalFilePreview(params),
getProjectFileIndex: (params) => this.localFileCtr.getProjectFileIndex(params),
+ searchProjectFiles: (params) => this.localFileCtr.searchProjectFiles(params),
};
}
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 2bf2af3ddc1..bf076433a53 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -2,6 +2,7 @@ import { constants } from 'node:fs';
import { access, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
+import { defaultSearchProjectFiles } from '@lobechat/device-control';
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
@@ -30,6 +31,8 @@ import {
type ProjectFileIndexEntry,
type ProjectFileIndexParams,
type ProjectFileIndexResult,
+ type ProjectFileSearchParams,
+ type ProjectFileSearchResult,
type RenameLocalFileResult,
type ResolveSkillResourcePathParams,
type ResolveSkillResourcePathResult,
@@ -65,6 +68,7 @@ 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;
const TEXT_PREVIEW_MIME_TYPES = new Set([
'application/graphql',
@@ -659,7 +663,6 @@ export default class LocalFileCtr extends ControllerModule {
indexedAt: new Date().toISOString(),
root,
source: 'git',
- totalCount: entries.length,
};
}
} catch (error) {
@@ -669,7 +672,11 @@ export default class LocalFileCtr extends ControllerModule {
});
}
- const fallback = await this.searchService.glob({ pattern: '**/*', scope: 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)),
@@ -688,10 +695,27 @@ export default class LocalFileCtr extends ControllerModule {
indexedAt: new Date().toISOString(),
root: requestedScope,
source: 'glob',
- totalCount: entries.length,
};
}
+ @IpcMethod()
+ async searchProjectFiles(params: ProjectFileSearchParams): Promise<ProjectFileSearchResult> {
+ const startedAt = Date.now();
+ const result = await defaultSearchProjectFiles(params);
+
+ logger.debug('Project file search completed', {
+ duration: Date.now() - startedAt,
+ entries: result.entries.length,
+ query: params.query,
+ requestedScope: params.scope,
+ root: result.root,
+ source: result.source,
+ });
+ await this.approveProjectRootForPreview(result.root);
+
+ return result;
+ }
+
/**
* Handle IPC event for local file search
*/
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index b7a66103ec5..7e067490762 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -729,7 +729,7 @@ describe('LocalFileCtr', () => {
}),
]),
);
- expect(result.totalCount).toBe(result.entries.length);
+ expect(result).not.toHaveProperty('totalCount');
});
it('should fall back to glob when git indexing fails', async () => {
@@ -746,6 +746,11 @@ describe('LocalFileCtr', () => {
const result = await localFileCtr.getProjectFileIndex({ scope: '/workspace/project' });
+ expect(mockSearchService.glob).toHaveBeenCalledWith({
+ limit: 5000,
+ pattern: '**/*',
+ scope: '/workspace/project',
+ });
expect(result.source).toBe('glob');
expect(result.entries).toEqual([
expect.objectContaining({
@@ -759,6 +764,7 @@ describe('LocalFileCtr', () => {
relativePath: 'src/index.ts',
}),
]);
+ expect(result).not.toHaveProperty('totalCount');
});
it('should mark glob entries as files when stat fails', async () => {
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index b3cbbc8b112..0c088c1c1d7 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -405,6 +405,31 @@ export const deviceRouter = router({
return result ?? null;
}),
+ /**
+ * Search project files on a remote device. The device performs the match and
+ * returns only the result subtree needed by the UI.
+ */
+ searchProjectFiles: deviceProcedure
+ .input(
+ z.object({
+ deviceId: z.string(),
+ limit: z.number().int().positive().max(500).optional(),
+ query: z.string(),
+ scope: z.string(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const result = await deviceGateway.searchProjectFiles({
+ deviceId: input.deviceId,
+ limit: input.limit,
+ query: input.query,
+ scope: input.scope,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ return result ?? null;
+ }),
+
/**
* Read-only local file preview for a file on a remote device. The web client
* receives render data, not a `localfile://` URL; saving remains unsupported.
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 83d34ee3fe2..974a41c5b5f 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -31,6 +31,7 @@ import type {
DeviceMoveProjectFileItem,
DeviceMoveProjectFileResultItem,
DeviceProjectFileIndexResult,
+ DeviceProjectFileSearchResult,
DeviceRenameProjectFileResult,
DeviceWriteProjectFileResult,
ProjectSkillMeta,
@@ -619,6 +620,42 @@ export class DeviceGateway {
}
}
+ /**
+ * Project file search for a directory on a remote device via the
+ * `searchProjectFiles` device RPC. The device performs matching and returns a
+ * compact tree subset with ancestor directories.
+ */
+ async searchProjectFiles(params: {
+ deviceId: string;
+ limit?: number;
+ query: string;
+ scope: string;
+ timeout?: number;
+ userId: string;
+ workspaceId?: string;
+ }): Promise<DeviceProjectFileSearchResult | undefined> {
+ const { userId, deviceId, limit, query, scope, timeout = 30_000, workspaceId } = params;
+ const client = this.getClient();
+ if (!client) return undefined;
+
+ try {
+ const result = await client.invokeRpc<DeviceProjectFileSearchResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'searchProjectFiles', params: { limit, query, scope } },
+ );
+
+ if (!result.success || !result.data) {
+ log('searchProjectFiles: failed for deviceId=%s — %s', deviceId, result.error);
+ return undefined;
+ }
+
+ return result.data;
+ } catch (error) {
+ log('searchProjectFiles: error for deviceId=%s — %O', deviceId, error);
+ return undefined;
+ }
+ }
+
/**
* Read a preview payload for a file on a remote device. This is read-only and
* deliberately mirrors the desktop local-file preview contract without
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 43b0fda28b4..3634249f85b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1159,11 +1159,10 @@
"workingPanel.documents.unsaved": "Unsaved changes",
"workingPanel.files.copyAbsolutePath": "Copy Path",
"workingPanel.files.copyRelativePath": "Copy Relative Path",
- "workingPanel.files.count_one": "{{count}} file",
- "workingPanel.files.count_other": "{{count}} files",
"workingPanel.files.empty": "No files in this workspace",
+ "workingPanel.files.noSearchResults": "No matching files",
"workingPanel.files.open": "Open File",
- "workingPanel.files.refresh": "Refresh",
+ "workingPanel.files.searchPlaceholder": "Filter files...",
"workingPanel.files.showInReview": "Show in Review",
"workingPanel.files.showInSystem": "Reveal in Folder",
"workingPanel.files.title": "Files",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 615054f0563..ffe4fe9dd54 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1159,11 +1159,10 @@
"workingPanel.documents.unsaved": "有未保存的变更",
"workingPanel.files.copyAbsolutePath": "复制路径",
"workingPanel.files.copyRelativePath": "复制相对路径",
- "workingPanel.files.count_one": "{{count}} 个文件",
- "workingPanel.files.count_other": "{{count}} 个文件",
"workingPanel.files.empty": "此工作区中没有文件",
+ "workingPanel.files.noSearchResults": "没有匹配的文件",
"workingPanel.files.open": "打开文件",
- "workingPanel.files.refresh": "刷新",
+ "workingPanel.files.searchPlaceholder": "筛选文件...",
"workingPanel.files.showInReview": "在审查中查看",
"workingPanel.files.showInSystem": "在文件夹中显示",
"workingPanel.files.title": "文件",
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index a6933152f3f..777016f0996 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -31,7 +31,12 @@ const makeDeps = (): DeviceControlDeps => ({
indexedAt: '',
root: '',
source: 'glob' as const,
- totalCount: 0,
+ })),
+ searchProjectFiles: vi.fn(async () => ({
+ entries: [],
+ root: '',
+ searchedAt: '',
+ source: 'glob' as const,
})),
});
@@ -94,11 +99,14 @@ describe('executeDeviceRpc', () => {
expect(result.isDirectory).toBe(true);
});
- it('delegates getProjectFileIndex and getLocalFilePreview to injected deps', async () => {
+ it('delegates project file and preview methods to injected deps', async () => {
const deps = makeDeps();
await executeDeviceRpc('getProjectFileIndex', { scope: root }, deps);
expect(deps.getProjectFileIndex).toHaveBeenCalledWith({ scope: root });
+ await executeDeviceRpc('searchProjectFiles', { query: 'agent', scope: root }, deps);
+ expect(deps.searchProjectFiles).toHaveBeenCalledWith({ query: 'agent', scope: root });
+
const previewParams = { path: path.join(root, 'AGENTS.md'), workingDirectory: root };
await executeDeviceRpc('getLocalFilePreview', previewParams, deps);
expect(deps.getLocalFilePreview).toHaveBeenCalledWith(previewParams);
diff --git a/packages/device-control/src/__tests__/projectFileIndex.test.ts b/packages/device-control/src/__tests__/projectFileIndex.test.ts
index 78f246ab84d..e3f76844aa9 100644
--- a/packages/device-control/src/__tests__/projectFileIndex.test.ts
+++ b/packages/device-control/src/__tests__/projectFileIndex.test.ts
@@ -5,7 +5,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
-import { defaultGetProjectFileIndex } from '../projectFileIndex';
+import { defaultGetProjectFileIndex, defaultSearchProjectFiles } from '../projectFileIndex';
const cleanup: string[] = [];
@@ -38,7 +38,7 @@ describe('defaultGetProjectFileIndex', () => {
expect(rels).toContain('scratch.txt');
// The intermediate directory is surfaced as its own entry.
expect(result.entries.find((e) => e.relativePath === 'src/')?.isDirectory).toBe(true);
- expect(result.totalCount).toBe(result.entries.length);
+ expect(result).not.toHaveProperty('totalCount');
});
it('falls back to a glob walk when the scope is not a git repo', async () => {
@@ -64,6 +64,65 @@ describe('defaultGetProjectFileIndex', () => {
expect(byRel['.agents/']?.isDirectory).toBe(true);
expect(byRel['.agents/config.md']?.isDirectory).toBe(false);
- expect(result.totalCount).toBe(result.entries.length);
+ expect(result).not.toHaveProperty('totalCount');
+ });
+});
+
+describe('defaultSearchProjectFiles', () => {
+ it('searches a git repo and returns matching files with ancestor directories', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-git-'));
+ cleanup.push(dir);
+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: dir });
+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: dir });
+ execFileSync('git', ['config', 'commit.gpgsign', 'false'], { cwd: dir });
+ await mkdir(path.join(dir, 'src', 'components'), { recursive: true });
+ await writeFile(
+ path.join(dir, 'src', 'components', 'Button.tsx'),
+ 'export const Button = 1;\n',
+ );
+ await writeFile(path.join(dir, 'src', 'components', 'Input.tsx'), 'export const Input = 1;\n');
+ execFileSync('git', ['add', '.'], { cwd: dir });
+ execFileSync('git', ['commit', '-m', 'init'], { cwd: dir });
+
+ const result = await defaultSearchProjectFiles({ query: 'button', scope: dir });
+
+ expect(result.source).toBe('git');
+ const relativePaths = result.entries.map((entry) => entry.relativePath);
+ expect(relativePaths).toEqual(
+ expect.arrayContaining(['src/', 'src/components/', 'src/components/Button.tsx']),
+ );
+ expect(relativePaths).not.toContain('src/components/Input.tsx');
+ });
+
+ it('caps non-git glob search results while preserving matching ancestors', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-glob-'));
+ cleanup.push(dir);
+ await mkdir(path.join(dir, 'nested', 'deep'), { recursive: true });
+ await writeFile(path.join(dir, 'nested', 'deep', 'target-file.ts'), 'target\n');
+ await writeFile(path.join(dir, 'nested', 'deep', 'other.ts'), 'other\n');
+
+ const result = await defaultSearchProjectFiles({ limit: 1, query: 'target', scope: dir });
+
+ expect(result.source).toBe('glob');
+ const relativePaths = result.entries.map((entry) => entry.relativePath);
+ expect(relativePaths).toEqual(
+ expect.arrayContaining(['nested/', 'nested/deep/', 'nested/deep/target-file.ts']),
+ );
+ expect(relativePaths).not.toContain('nested/deep/other.ts');
+ });
+
+ it('searches hidden project directories in non-git scopes', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'dc-search-hidden-'));
+ cleanup.push(dir);
+ await mkdir(path.join(dir, '.agents', 'skills'), { recursive: true });
+ await writeFile(path.join(dir, '.agents', 'skills', 'target-skill.md'), 'skill\n');
+
+ const result = await defaultSearchProjectFiles({ query: 'target-skill', scope: dir });
+
+ const relativePaths = result.entries.map((entry) => entry.relativePath);
+ expect(relativePaths).toEqual(
+ expect.arrayContaining(['.agents/', '.agents/skills/', '.agents/skills/target-skill.md']),
+ );
});
});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 9504c2c9586..75f334d8e4f 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -25,6 +25,7 @@ import type {
ListProjectSkillsParams,
LocalFilePreviewUrlParams,
ProjectFileIndexParams,
+ ProjectFileSearchParams,
} from './types';
import { initWorkspace, listProjectSkills, statPath } from './workspace';
@@ -39,6 +40,7 @@ export const DEVICE_RPC_METHODS = [
'listProjectSkills',
'statPath',
'getProjectFileIndex',
+ 'searchProjectFiles',
'getLocalFilePreview',
'moveLocalFiles',
'renameLocalFile',
@@ -95,6 +97,10 @@ export const executeDeviceRpc = async (
return deps.getProjectFileIndex(params as ProjectFileIndexParams);
}
+ case 'searchProjectFiles': {
+ return deps.searchProjectFiles(params as ProjectFileSearchParams);
+ }
+
case 'getLocalFilePreview': {
return deps.getLocalFilePreview(params as LocalFilePreviewUrlParams);
}
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 093c2d3d4e9..36f010303dc 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -1,5 +1,5 @@
export { DEVICE_RPC_METHODS, type DeviceRpcMethod, executeDeviceRpc } from './dispatch';
export { defaultGetLocalFilePreview } from './filePreview';
-export { defaultGetProjectFileIndex } from './projectFileIndex';
+export { defaultGetProjectFileIndex, defaultSearchProjectFiles } from './projectFileIndex';
export * from './types';
export { initWorkspace, listProjectSkills, statPath } from './workspace';
diff --git a/packages/device-control/src/projectFileIndex.ts b/packages/device-control/src/projectFileIndex.ts
index 7039acbed90..92fc77d9fed 100644
--- a/packages/device-control/src/projectFileIndex.ts
+++ b/packages/device-control/src/projectFileIndex.ts
@@ -4,13 +4,18 @@ import { promisify } from 'node:util';
import fg from 'fast-glob';
+import { projectFileSearchManager } from './projectFileSearchManager';
import type {
ProjectFileIndexEntry,
ProjectFileIndexParams,
ProjectFileIndexResult,
+ ProjectFileSearchParams,
+ ProjectFileSearchResult,
} from './types';
const execFileAsync = promisify(execFile);
+const PROJECT_FILE_GLOB_LIMIT = 5000;
+const PROJECT_FILE_SEARCH_DEFAULT_LIMIT = 100;
const toPosixRelativePath = (filePath: string) => filePath.split(path.sep).join('/');
@@ -60,6 +65,23 @@ const buildEntries = (files: string[], root: string): ProjectFileIndexEntry[] =>
return [...collectProjectDirectories(files, root), ...fileEntries];
};
+const collectGlobFilePaths = async (scope: string): Promise<string[]> => {
+ const files: string[] = [];
+ const stream = fg.stream('**/*', {
+ cwd: scope,
+ dot: true,
+ ignore: ['**/node_modules/**', '**/.git/**'],
+ onlyFiles: true,
+ });
+
+ for await (const relativePath of stream as AsyncIterable<string>) {
+ files.push(path.resolve(scope, relativePath));
+ if (files.length >= PROJECT_FILE_GLOB_LIMIT) break;
+ }
+
+ return files;
+};
+
/**
* Portable project file index for the CLI (and any non-desktop device). Prefers
* `git ls-files` (tracked + untracked, submodule-aware) to enumerate the repo,
@@ -107,7 +129,6 @@ export const defaultGetProjectFileIndex = async (
indexedAt: new Date().toISOString(),
root,
source: 'git',
- totalCount: entries.length,
};
}
} catch {
@@ -117,13 +138,7 @@ export const defaultGetProjectFileIndex = async (
// 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 relFiles = await fg('**/*', {
- cwd: requestedScope,
- dot: true,
- ignore: ['**/node_modules/**', '**/.git/**'],
- onlyFiles: true,
- });
- const files = relFiles.map((relativePath) => path.resolve(requestedScope, relativePath));
+ const files = await collectGlobFilePaths(requestedScope);
const entries = buildEntries(files, requestedScope);
return {
@@ -131,6 +146,63 @@ export const defaultGetProjectFileIndex = async (
indexedAt: new Date().toISOString(),
root: requestedScope,
source: 'glob',
- totalCount: entries.length,
+ };
+};
+
+export const defaultSearchProjectFiles = async (
+ params: ProjectFileSearchParams,
+): Promise<ProjectFileSearchResult> => {
+ const requestedScope = params.scope || process.cwd();
+ const limit = Math.max(1, params.limit ?? PROJECT_FILE_SEARCH_DEFAULT_LIMIT);
+
+ try {
+ const rootResult = await execFileAsync(
+ 'git',
+ ['-C', requestedScope, 'rev-parse', '--show-toplevel'],
+ { timeout: 5000 },
+ ).catch((error) => error);
+ const exitCode = rootResult?.code ?? rootResult?.exitCode;
+ const root =
+ rootResult?.stdout && !exitCode ? rootResult.stdout.trim() || requestedScope : requestedScope;
+
+ if (rootResult?.stdout && !exitCode) {
+ const [trackedResult, untrackedResult] = await Promise.all([
+ execFileAsync(
+ 'git',
+ ['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--recurse-submodules'],
+ { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
+ ),
+ execFileAsync(
+ 'git',
+ ['-C', root, '-c', 'core.quotepath=false', 'ls-files', '--others', '--exclude-standard'],
+ { maxBuffer: 64 * 1024 * 1024, timeout: 10_000 },
+ ).catch(() => ({ stdout: '' })),
+ ]);
+
+ const files = [...trackedResult.stdout.split('\n'), ...untrackedResult.stdout.split('\n')]
+ .map((item) => item.trim())
+ .filter(Boolean)
+ .map((relativePath) => path.resolve(root, relativePath));
+ const entries = buildEntries(files, root);
+
+ return {
+ entries: projectFileSearchManager.selectEntries(entries, params.query, limit),
+ root,
+ searchedAt: new Date().toISOString(),
+ source: 'git',
+ };
+ }
+ } catch {
+ // fall through to glob
+ }
+
+ const files = await projectFileSearchManager.collectNonGitFilePaths(requestedScope);
+ const entries = buildEntries(files, requestedScope);
+
+ return {
+ entries: projectFileSearchManager.selectEntries(entries, params.query, limit),
+ root: requestedScope,
+ searchedAt: new Date().toISOString(),
+ source: 'glob',
};
};
diff --git a/packages/device-control/src/projectFileSearchManager.ts b/packages/device-control/src/projectFileSearchManager.ts
new file mode 100644
index 00000000000..8815c5e134e
--- /dev/null
+++ b/packages/device-control/src/projectFileSearchManager.ts
@@ -0,0 +1,255 @@
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+
+import fg from 'fast-glob';
+
+import type { ProjectFileIndexEntry } from './types';
+
+const PROJECT_FILE_SEARCH_SCAN_LIMIT = 5000;
+const PROJECT_FILE_SEARCH_COMMAND_TIMEOUT_MS = 10_000;
+
+interface FileFinderCommand {
+ args: string[];
+ command: string;
+}
+
+class ProjectFileSearchManager {
+ private createFileFinderCommands(scope: string): FileFinderCommand[] {
+ return [
+ {
+ args: [
+ '--type',
+ 'f',
+ '--color',
+ 'never',
+ '--hidden',
+ '--exclude',
+ '.git',
+ '--exclude',
+ 'node_modules',
+ ],
+ command: 'fd',
+ },
+ {
+ args: [
+ '--type',
+ 'f',
+ '--color',
+ 'never',
+ '--hidden',
+ '--exclude',
+ '.git',
+ '--exclude',
+ 'node_modules',
+ ],
+ command: 'fdfind',
+ },
+ {
+ args: [
+ '--files',
+ '--color',
+ 'never',
+ '--hidden',
+ '--glob',
+ '!.git/**',
+ '--glob',
+ '!node_modules/**',
+ ],
+ command: 'rg',
+ },
+ {
+ args: ['.', '-type', 'f', '-not', '-path', '*/.git/*', '-not', '-path', '*/node_modules/*'],
+ command: 'find',
+ },
+ {
+ args: ['/r', scope, '*'],
+ command: 'where',
+ },
+ ];
+ }
+
+ async collectNonGitFilePaths(scope: string): Promise<string[]> {
+ for (const finder of this.createFileFinderCommands(scope)) {
+ const files = await this.tryCollectCommandFilePaths(scope, finder);
+ if (files.length > 0) return files;
+ }
+
+ return this.collectFastGlobFilePaths(scope);
+ }
+
+ selectEntries(
+ entries: ProjectFileIndexEntry[],
+ query: string,
+ limit: number,
+ ): ProjectFileIndexEntry[] {
+ const normalizedQuery = this.normalizeSearchText(query);
+ if (!normalizedQuery) return [];
+
+ const entryByPath = new Map(entries.map((entry) => [entry.relativePath, entry]));
+ const scoredEntries = entries
+ .filter((entry) => !entry.isDirectory)
+ .map((entry) => ({ entry, score: this.scoreProjectFileEntry(entry, normalizedQuery) }))
+ .filter(
+ (result): result is { entry: ProjectFileIndexEntry; score: number } =>
+ result.score !== null,
+ )
+ .sort((a, b) => a.score - b.score || a.entry.relativePath.localeCompare(b.entry.relativePath))
+ .slice(0, limit);
+
+ const visiblePaths = new Set<string>();
+ for (const { entry } of scoredEntries) {
+ visiblePaths.add(entry.relativePath);
+ let current = path.dirname(entry.relativePath);
+ while (current && current !== '.') {
+ const directoryPath = `${this.toPosixRelativePath(current)}/`;
+ if (entryByPath.has(directoryPath)) visiblePaths.add(directoryPath);
+ current = path.dirname(current);
+ }
+ }
+
+ return entries.filter((entry) => visiblePaths.has(entry.relativePath));
+ }
+
+ private async collectCommandFilePaths(
+ scope: string,
+ finder: FileFinderCommand,
+ limit: number,
+ ): Promise<string[]> {
+ const child = spawn(finder.command, finder.args, {
+ cwd: scope,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ const files: string[] = [];
+ const seen = new Set<string>();
+ let pending = '';
+ let settled = false;
+
+ const cleanup = (timer: NodeJS.Timeout) => {
+ settled = true;
+ clearTimeout(timer);
+ child.stdout.removeAllListeners();
+ child.removeAllListeners();
+ };
+
+ return new Promise((resolve, reject) => {
+ const addLine = (line: string) => {
+ const filePath = this.normalizeFinderOutputPath(scope, line);
+ if (!filePath || seen.has(filePath)) return;
+ seen.add(filePath);
+ files.push(filePath);
+ if (files.length >= limit && !child.killed) child.kill();
+ };
+
+ const flushChunk = (chunk: Buffer) => {
+ pending += chunk.toString('utf8');
+ const lines = pending.split(/\r?\n/);
+ pending = lines.pop() ?? '';
+ for (const line of lines) addLine(line);
+ };
+
+ const timer = setTimeout(() => {
+ if (!child.killed) child.kill();
+ }, PROJECT_FILE_SEARCH_COMMAND_TIMEOUT_MS);
+
+ child.stdout.on('data', flushChunk);
+ child.on('error', (error) => {
+ if (settled) return;
+ cleanup(timer);
+ reject(error);
+ });
+ child.on('close', (code, signal) => {
+ if (settled) return;
+ if (pending) addLine(pending);
+ cleanup(timer);
+
+ if (files.length > 0 || code === 0) {
+ resolve(files);
+ return;
+ }
+
+ reject(new Error(`${finder.command} exited with code ${code ?? signal ?? 'unknown'}`));
+ });
+ });
+ }
+
+ private async collectFastGlobFilePaths(scope: string): Promise<string[]> {
+ const files: string[] = [];
+ const stream = fg.stream('**/*', {
+ cwd: scope,
+ dot: true,
+ ignore: ['**/node_modules/**', '**/.git/**'],
+ onlyFiles: true,
+ });
+
+ for await (const relativePath of stream as AsyncIterable<string>) {
+ files.push(path.resolve(scope, relativePath));
+ if (files.length >= PROJECT_FILE_SEARCH_SCAN_LIMIT) break;
+ }
+
+ return files;
+ }
+
+ private fuzzySequenceScore(candidate: string, query: string): number | null {
+ let queryIndex = 0;
+ let firstMatch = -1;
+ let lastMatch = -1;
+
+ for (let i = 0; i < candidate.length && queryIndex < query.length; i++) {
+ if (candidate[i] !== query[queryIndex]) continue;
+ if (firstMatch < 0) firstMatch = i;
+ lastMatch = i;
+ queryIndex++;
+ }
+
+ if (queryIndex !== query.length) return null;
+ return 50 + firstMatch + Math.max(0, lastMatch - firstMatch - query.length);
+ }
+
+ private normalizeFinderOutputPath(scope: string, outputPath: string): string | undefined {
+ const trimmed = outputPath.trim();
+ if (!trimmed) return;
+
+ const withoutLeadingDot = trimmed.startsWith(`.${path.sep}`)
+ ? trimmed.slice(2)
+ : trimmed.startsWith('./')
+ ? trimmed.slice(2)
+ : trimmed;
+
+ return path.resolve(scope, withoutLeadingDot);
+ }
+
+ private normalizeSearchText(value: string) {
+ return value.trim().toLocaleLowerCase();
+ }
+
+ private scoreProjectFileEntry(entry: ProjectFileIndexEntry, query: string): number | null {
+ const name = this.normalizeSearchText(entry.name);
+ const relativePath = this.normalizeSearchText(entry.relativePath);
+
+ if (name === query) return 0;
+ if (relativePath === query) return 1;
+ if (name.startsWith(query)) return 5 + name.length - query.length;
+ if (relativePath.startsWith(query)) return 10 + relativePath.length - query.length;
+ if (name.includes(query)) return 20 + name.indexOf(query);
+ if (relativePath.includes(query)) return 30 + relativePath.indexOf(query);
+
+ return this.fuzzySequenceScore(relativePath, query);
+ }
+
+ private toPosixRelativePath(filePath: string) {
+ return filePath.split(path.sep).join('/');
+ }
+
+ private async tryCollectCommandFilePaths(
+ scope: string,
+ finder: FileFinderCommand,
+ ): Promise<string[]> {
+ try {
+ return await this.collectCommandFilePaths(scope, finder, PROJECT_FILE_SEARCH_SCAN_LIMIT);
+ } catch {
+ return [];
+ }
+ }
+}
+
+export const projectFileSearchManager = new ProjectFileSearchManager();
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 1c96d27144f..9da3a2a1498 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -114,7 +114,18 @@ export interface ProjectFileIndexResult {
indexedAt: string;
root: string;
source: 'git' | 'glob';
- totalCount: number;
+}
+
+export interface ProjectFileSearchParams extends ProjectFileIndexParams {
+ limit?: number;
+ query: string;
+}
+
+export interface ProjectFileSearchResult {
+ entries: ProjectFileIndexEntry[];
+ root: string;
+ searchedAt: string;
+ source: 'git' | 'glob';
}
/**
@@ -145,4 +156,6 @@ export interface DeviceControlDeps extends WorkspaceScanDeps {
getLocalFilePreview: (params: LocalFilePreviewUrlParams) => Promise<LocalFilePreviewResult>;
/** Build the project file index. */
getProjectFileIndex: (params: ProjectFileIndexParams) => Promise<ProjectFileIndexResult>;
+ /** Search project files without shipping the whole index to the caller. */
+ searchProjectFiles: (params: ProjectFileSearchParams) => Promise<ProjectFileSearchResult>;
}
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 073da0eefc7..3f28ea4dc45 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -248,7 +248,18 @@ export interface ProjectFileIndexResult {
indexedAt: string;
root: string;
source: 'git' | 'glob';
- totalCount: number;
+}
+
+export interface ProjectFileSearchParams extends ProjectFileIndexParams {
+ limit?: number;
+ query: string;
+}
+
+export interface ProjectFileSearchResult {
+ entries: ProjectFileIndexEntry[];
+ root: string;
+ searchedAt: string;
+ source: 'git' | 'glob';
}
export interface OpenLocalFileParams {
diff --git a/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
index ce9a5967a20..0e89a222ee9 100644
--- a/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
@@ -18,9 +18,12 @@ vi.mock('../../logger', () => ({
}));
const fgMock = vi.fn();
-vi.mock('fast-glob', () => ({
- default: (...args: unknown[]) => fgMock(...args),
-}));
+const fgStreamMock = () => (fgMock as unknown as { stream: ReturnType<typeof vi.fn> }).stream;
+vi.mock('fast-glob', () => {
+ const defaultExport = (...args: unknown[]) => fgMock(...args);
+ Object.defineProperty(defaultExport, 'stream', { get: () => fgStreamMock() });
+ return { default: defaultExport };
+});
const execaMock = vi.fn();
vi.mock('execa', () => ({
@@ -40,6 +43,7 @@ vi.mock('node:fs/promises', () => ({
describe('UnixFileSearch glob fallback root', () => {
beforeEach(() => {
fgMock.mockReset();
+ (fgMock as unknown as { stream: ReturnType<typeof vi.fn> }).stream = vi.fn();
execaMock.mockReset();
// Force the Unix tool selection to fall through to fast-glob so we
// don't have to mock fd/find availability checks.
@@ -120,4 +124,25 @@ describe('UnixFileSearch glob fallback root', () => {
const [, args] = execaMock.mock.calls[0] as [string, string[]];
expect(args).not.toContain('--max-results');
});
+
+ it('streams fast-glob results when the caller provides a glob limit', async () => {
+ fgStreamMock().mockReturnValue(
+ (async function* () {
+ yield { path: '/repo/packages/b.ts', stats: { mtime: new Date('2026-01-02') } };
+ yield { path: '/repo/packages/a.ts', stats: { mtime: new Date('2026-01-01') } };
+ yield { path: '/repo/packages/c.ts', stats: { mtime: new Date('2026-01-03') } };
+ })(),
+ );
+
+ const impl = new LinuxSearchServiceImpl();
+ const result = await impl.glob({ limit: 2, pattern: '**/*.ts', scope: '/repo/packages' });
+
+ expect(fgMock).not.toHaveBeenCalled();
+ expect(fgStreamMock()).toHaveBeenCalledWith(
+ '**/*.ts',
+ expect.objectContaining({ cwd: '/repo/packages', stats: true }),
+ );
+ expect(result.files).toEqual(['/repo/packages/b.ts', '/repo/packages/a.ts']);
+ expect(result.total_files).toBe(2);
+ });
});
diff --git a/packages/local-file-shell/src/fileSearch/impl/unix.ts b/packages/local-file-shell/src/fileSearch/impl/unix.ts
index 63159f58fe4..e5096b79b7e 100644
--- a/packages/local-file-shell/src/fileSearch/impl/unix.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/unix.ts
@@ -18,6 +18,8 @@ const logger = createLogger('fileSearch:unix');
*/
export type UnixSearchTool = 'fast-glob' | 'fd' | 'find';
+type FastGlobStatsEntry = { path: string; stats: Stats };
+
/**
* Unix file search base class
* Provides common search implementations for macOS and Linux
@@ -385,21 +387,26 @@ export abstract class UnixFileSearch extends BaseFileSearch {
protected async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
+ const limit = this.normalizePositiveLimit(params.limit);
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
try {
- const files = await fg(params.pattern, {
+ const options = {
absolute: true,
cwd: searchPath,
dot: true,
ignore: ['**/node_modules/**', '**/.git/**'],
onlyFiles: false,
stats: true,
- });
+ };
+
+ const files = limit
+ ? await this.collectLimitedFastGlobEntries(params.pattern, options, limit)
+ : ((await fg(params.pattern, options)) as unknown as FastGlobStatsEntry[]);
- const sortedFiles = (files as unknown as Array<{ path: string; stats: Stats }>)
+ const sortedFiles = files
.sort((a, b) => b.stats.mtime.getTime() - a.stats.mtime.getTime())
.map((f) => f.path);
@@ -423,6 +430,22 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
+ private async collectLimitedFastGlobEntries(
+ pattern: string,
+ options: Parameters<typeof fg.stream>[1],
+ limit: number,
+ ): Promise<FastGlobStatsEntry[]> {
+ const entries: FastGlobStatsEntry[] = [];
+ const stream = fg.stream(pattern, options);
+
+ for await (const entry of stream as AsyncIterable<FastGlobStatsEntry>) {
+ entries.push(entry);
+ if (entries.length >= limit) break;
+ }
+
+ return entries;
+ }
+
private async getFilesWithStats(
files: string[],
): Promise<Array<{ mtime: number; path: string }>> {
diff --git a/packages/local-file-shell/src/fileSearch/impl/windows.ts b/packages/local-file-shell/src/fileSearch/impl/windows.ts
index dd5f2257fc7..6715a868e9f 100644
--- a/packages/local-file-shell/src/fileSearch/impl/windows.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/windows.ts
@@ -17,6 +17,7 @@ const logger = createLogger('fileSearch:windows');
* Priority: fd > powershell > fast-glob
*/
type WindowsFallbackTool = 'fast-glob' | 'fd' | 'powershell';
+type FastGlobStatsEntry = { path: string; stats: Stats };
/**
* Windows file search implementation
@@ -323,12 +324,13 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
private async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
+ const limit = this.normalizePositiveLimit(params.limit);
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
try {
- const files = await fg(params.pattern, {
+ const options = {
absolute: true,
cwd: searchPath,
// Windows hidden files use attributes, not dot prefix
@@ -336,9 +338,13 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
ignore: ['**/node_modules/**', '**/.git/**'],
onlyFiles: false,
stats: true,
- });
+ };
+
+ const files = limit
+ ? await this.collectLimitedFastGlobEntries(params.pattern, options, limit)
+ : ((await fg(params.pattern, options)) as unknown as FastGlobStatsEntry[]);
- const sortedFiles = (files as unknown as Array<{ path: string; stats: Stats }>)
+ const sortedFiles = files
.sort((a, b) => b.stats.mtime.getTime() - a.stats.mtime.getTime())
.map((f) => f.path);
@@ -362,6 +368,22 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
+ private async collectLimitedFastGlobEntries(
+ pattern: string,
+ options: Parameters<typeof fg.stream>[1],
+ limit: number,
+ ): Promise<FastGlobStatsEntry[]> {
+ const entries: FastGlobStatsEntry[] = [];
+ const stream = fg.stream(pattern, options);
+
+ for await (const entry of stream as AsyncIterable<FastGlobStatsEntry>) {
+ entries.push(entry);
+ if (entries.length >= limit) break;
+ }
+
+ return entries;
+ }
+
private async getFilesWithStats(
files: string[],
): Promise<Array<{ mtime: number; path: string }>> {
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 730e4e3ccf9..76cce5f2fa1 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1296,13 +1296,12 @@ export default {
'workingPanel.skills.section.project': 'Project skills',
'workingPanel.skills.section.user': 'User skills',
'workingPanel.skills.title': 'Skills',
- 'workingPanel.files.count_one': '{{count}} file',
- 'workingPanel.files.count_other': '{{count}} files',
'workingPanel.files.copyAbsolutePath': 'Copy Path',
'workingPanel.files.copyRelativePath': 'Copy Relative Path',
'workingPanel.files.empty': 'No files in this workspace',
+ 'workingPanel.files.noSearchResults': 'No matching files',
'workingPanel.files.open': 'Open File',
- 'workingPanel.files.refresh': 'Refresh',
+ 'workingPanel.files.searchPlaceholder': 'Filter files...',
'workingPanel.files.showInReview': 'Show in Review',
'workingPanel.files.showInSystem': 'Reveal in Folder',
'workingPanel.files.title': 'Files',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index cb3ca273f8e..fb5e869db36 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -366,7 +366,13 @@ export interface DeviceProjectFileIndexResult {
indexedAt: string;
root: string;
source: 'git' | 'glob';
- totalCount: number;
+}
+
+export interface DeviceProjectFileSearchResult {
+ entries: DeviceProjectFileIndexEntry[];
+ root: string;
+ searchedAt: string;
+ source: 'git' | 'glob';
}
export interface DeviceLocalFilePreviewText {
diff --git a/src/features/ChatInput/InputEditor/localFileMentionIndex.test.ts b/src/features/ChatInput/InputEditor/localFileMentionIndex.test.ts
deleted file mode 100644
index 464cc1836cc..00000000000
--- a/src/features/ChatInput/InputEditor/localFileMentionIndex.test.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const { getProjectFileIndexMock } = vi.hoisted(() => ({
- getProjectFileIndexMock: vi.fn(),
-}));
-
-vi.mock('@/services/electron/localFileService', () => ({
- localFileService: {
- getProjectFileIndex: getProjectFileIndexMock,
- },
-}));
-
-describe('localFileMentionIndex', () => {
- beforeEach(() => {
- vi.resetModules();
- getProjectFileIndexMock.mockReset();
- });
-
- it('should reuse the project file index across keyword searches', async () => {
- getProjectFileIndexMock.mockResolvedValue({
- entries: [
- {
- isDirectory: false,
- name: 'index.ts',
- path: '/workspace/project/src/index.ts',
- relativePath: 'src/index.ts',
- },
- {
- isDirectory: false,
- name: 'Button.tsx',
- path: '/workspace/project/src/components/Button.tsx',
- relativePath: 'src/components/Button.tsx',
- },
- ],
- indexedAt: '2026-04-28T00:00:00.000Z',
- root: '/workspace/project',
- source: 'git',
- totalCount: 2,
- });
-
- const { searchProjectFileMentionIndex } = await import('./localFileMentionIndex');
-
- await searchProjectFileMentionIndex('/workspace/project', 'src', 20);
- const secondResult = await searchProjectFileMentionIndex('/workspace/project', 'button', 20);
-
- expect(getProjectFileIndexMock).toHaveBeenCalledTimes(1);
- expect(secondResult).toEqual([
- expect.objectContaining({
- path: '/workspace/project/src/components/Button.tsx',
- }),
- ]);
- });
-});
diff --git a/src/features/ChatInput/InputEditor/localFileMentionIndex.ts b/src/features/ChatInput/InputEditor/localFileMentionIndex.ts
deleted file mode 100644
index f469f364c87..00000000000
--- a/src/features/ChatInput/InputEditor/localFileMentionIndex.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
-import debug from 'debug';
-import Fuse from 'fuse.js';
-
-import { localFileService } from '@/services/electron/localFileService';
-
-const log = debug('chat-input:local-file-mention:index');
-
-const INDEX_REFRESH_INTERVAL = 5000;
-
-interface LocalFileMentionIndex {
- entries: ProjectFileIndexEntry[];
- fuse: Fuse<ProjectFileIndexEntry>;
- indexedAt: number;
- root: string;
-}
-
-interface LocalFileMentionIndexCache {
- index?: LocalFileMentionIndex;
- refreshPromise?: Promise<LocalFileMentionIndex>;
-}
-
-const cache = new Map<string, LocalFileMentionIndexCache>();
-
-const buildIndex = async (scope: string): Promise<LocalFileMentionIndex> => {
- const startedAt = Date.now();
- const result = await localFileService.getProjectFileIndex({ scope });
- const fuse = new Fuse(result.entries, {
- ignoreLocation: true,
- keys: ['relativePath', 'name', 'path'],
- threshold: 0.35,
- });
-
- log('Built project file mention index', {
- duration: Date.now() - startedAt,
- entries: result.entries.length,
- root: result.root,
- source: result.source,
- });
-
- return {
- entries: result.entries,
- fuse,
- indexedAt: Date.now(),
- root: result.root,
- };
-};
-
-const refreshIndex = (scope: string, entry: LocalFileMentionIndexCache) => {
- if (entry.refreshPromise) return entry.refreshPromise;
-
- entry.refreshPromise = buildIndex(scope)
- .then((index) => {
- entry.index = index;
- return index;
- })
- .finally(() => {
- entry.refreshPromise = undefined;
- });
-
- return entry.refreshPromise;
-};
-
-const getCacheEntry = (scope: string) => {
- const existing = cache.get(scope);
- if (existing) return existing;
-
- const entry: LocalFileMentionIndexCache = {};
- cache.set(scope, entry);
- return entry;
-};
-
-export const warmProjectFileMentionIndex = (scope: string | undefined) => {
- if (!scope) return;
-
- const entry = getCacheEntry(scope);
- if (entry.index || entry.refreshPromise) return;
-
- void refreshIndex(scope, entry);
-};
-
-export const searchProjectFileMentionIndex = async (
- scope: string | undefined,
- query: string,
- limit: number,
-): Promise<ProjectFileIndexEntry[]> => {
- if (!scope) return [];
-
- const entry = getCacheEntry(scope);
- const isStale = !entry.index || Date.now() - entry.index.indexedAt > INDEX_REFRESH_INTERVAL;
-
- if (!entry.index) {
- await refreshIndex(scope, entry);
- } else if (isStale) {
- void refreshIndex(scope, entry);
- }
-
- const index = entry.index;
- if (!index) return [];
-
- return index.fuse.search(query, { limit }).map((result) => result.item);
-};
diff --git a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.test.ts b/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.test.ts
new file mode 100644
index 00000000000..8088e71d673
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.test.ts
@@ -0,0 +1,150 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useLocalFileMention } from './useLocalFileMention.desktop';
+
+const { agentState, chatState, electronState, searchProjectFilesMock } = vi.hoisted(() => ({
+ agentState: {
+ agencyConfig: undefined as
+ | {
+ boundDeviceId?: string;
+ executionTarget?: 'device' | 'local';
+ heterogeneousProvider?: { type: string };
+ }
+ | undefined,
+ isLocalSystemEnabled: true,
+ workingDirectory: '/local/repo',
+ },
+ chatState: {
+ topicWorkingDirectory: undefined as string | undefined,
+ },
+ electronState: {
+ currentDeviceId: 'local-device',
+ },
+ searchProjectFilesMock: vi.fn(),
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: {
+ searchProjectFiles: searchProjectFilesMock,
+ },
+}));
+
+vi.mock('../hooks/useAgentId', () => ({
+ useAgentId: () => 'agent-1',
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: <T>(selector: (state: typeof agentState) => T) => selector(agentState),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => (state: typeof agentState) => state.agencyConfig,
+ getAgentWorkingDirectoryById: () => (state: typeof agentState) => state.workingDirectory,
+ },
+ chatConfigByIdSelectors: {
+ isLocalSystemEnabledById: () => (state: typeof agentState) => state.isLocalSystemEnabled,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: <T>(selector: (state: typeof chatState) => T) => selector(chatState),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ currentTopicWorkingDirectory: (state: typeof chatState) => state.topicWorkingDirectory,
+ },
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: <T>(selector: (state: { gatewayDeviceInfo?: { deviceId: string } }) => T) =>
+ selector({ gatewayDeviceInfo: { deviceId: electronState.currentDeviceId } }),
+}));
+
+vi.mock('./MentionMenu/LocalFileIcon', () => ({
+ default: () => null,
+}));
+
+describe('useLocalFileMention.desktop', () => {
+ beforeEach(() => {
+ agentState.agencyConfig = undefined;
+ agentState.isLocalSystemEnabled = true;
+ agentState.workingDirectory = '/local/repo';
+ chatState.topicWorkingDirectory = undefined;
+ electronState.currentDeviceId = 'local-device';
+ searchProjectFilesMock.mockReset();
+ searchProjectFilesMock.mockResolvedValue({
+ entries: [],
+ root: '/local/repo',
+ searchedAt: '2026-07-01T00:00:00.000Z',
+ source: 'git',
+ });
+ });
+
+ it('does not pass the local gateway device id for local desktop file search', async () => {
+ const { result } = renderHook(() => useLocalFileMention());
+
+ await result.current.searchLocalFiles('button');
+
+ expect(searchProjectFilesMock).toHaveBeenCalledWith({
+ deviceId: undefined,
+ limit: 20,
+ query: 'button',
+ scope: '/local/repo',
+ });
+ });
+
+ it('adds the relative directory tail to the menu description slot', async () => {
+ searchProjectFilesMock.mockResolvedValueOnce({
+ entries: [
+ {
+ isDirectory: false,
+ name: 'README.md',
+ path: '/local/repo/packages/editor/README.md',
+ relativePath: 'packages/editor/README.md',
+ },
+ ],
+ root: '/local/repo',
+ searchedAt: '2026-07-01T00:00:00.000Z',
+ source: 'git',
+ });
+
+ const { result } = renderHook(() => useLocalFileMention());
+
+ const items = await result.current.searchLocalFiles('readme');
+
+ expect(items[0]).toMatchObject({
+ key: 'local-file-/local/repo/packages/editor/README.md',
+ label: 'README.md',
+ metadata: {
+ description: 'packages/editor/',
+ name: 'README.md',
+ path: '/local/repo/packages/editor/README.md',
+ relativePath: 'packages/editor/README.md',
+ type: 'localFile',
+ },
+ });
+ });
+
+ it('passes a remote bound device id for remote file search', async () => {
+ agentState.agencyConfig = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+ agentState.workingDirectory = '/remote/repo';
+
+ const { result } = renderHook(() => useLocalFileMention());
+
+ await result.current.searchLocalFiles('button');
+
+ expect(searchProjectFilesMock).toHaveBeenCalledWith({
+ deviceId: 'remote-device',
+ limit: 20,
+ query: 'button',
+ scope: '/remote/repo',
+ });
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts b/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
index be277cdac9b..d610a33acd3 100644
--- a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
+++ b/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
@@ -1,7 +1,9 @@
import type { ISlashMenuOption } from '@lobehub/editor';
import debug from 'debug';
-import { createElement, useCallback, useEffect } from 'react';
+import { createElement, useCallback } from 'react';
+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
+import { projectFileService } from '@/services/projectFile';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -9,10 +11,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useElectronStore } from '@/store/electron';
import { useAgentId } from '../hooks/useAgentId';
-import {
- searchProjectFileMentionIndex,
- warmProjectFileMentionIndex,
-} from './localFileMentionIndex';
+import { compactDirectoryTail, compactFileName } from './MentionMenu/localFileDisplay';
import LocalFileIcon from './MentionMenu/LocalFileIcon';
const MAX_LOCAL_FILE_MENTION_ITEMS = 20;
@@ -25,9 +24,8 @@ export interface UseLocalFileMentionResult {
export const useLocalFileMention = (): UseLocalFileMentionResult => {
const agentId = useAgentId();
- const heterogeneousType = useAgentStore(
- (s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.type,
- );
+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ const heterogeneousType = agencyConfig?.heterogeneousProvider?.type;
const isLocalSystemEnabled = useAgentStore(
chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),
);
@@ -37,14 +35,12 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
);
const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
const workingDirectory = topicWorkingDirectory || agentWorkingDirectory;
+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
+ const searchDeviceId =
+ targetDeviceId && targetDeviceId !== currentDeviceId ? targetDeviceId : undefined;
const enableLocalFileMention = !!heterogeneousType || isLocalSystemEnabled;
- useEffect(() => {
- if (!enableLocalFileMention) return;
- warmProjectFileMentionIndex(workingDirectory);
- }, [enableLocalFileMention, workingDirectory]);
-
const searchLocalFiles = useCallback(
async (matchingString: string): Promise<ISlashMenuOption[]> => {
const keywords = matchingString.trim();
@@ -64,11 +60,15 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
limit: MAX_LOCAL_FILE_MENTION_ITEMS,
workingDirectory,
});
- const files = await searchProjectFileMentionIndex(
- workingDirectory,
- keywords,
- MAX_LOCAL_FILE_MENTION_ITEMS,
- );
+ if (!workingDirectory) return [];
+
+ const result = await projectFileService.searchProjectFiles({
+ deviceId: searchDeviceId,
+ limit: MAX_LOCAL_FILE_MENTION_ITEMS,
+ query: keywords,
+ scope: workingDirectory,
+ });
+ const files = result?.entries.filter((entry) => !entry.isDirectory) ?? [];
log('Search indexed local files completed', {
count: files.length,
@@ -77,31 +77,40 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
name: file.name,
path: file.path,
})),
+ root: result?.root,
+ source: result?.source,
workingDirectory,
});
- return files.map((file) => ({
- icon: createElement(LocalFileIcon, {
- isDirectory: file.isDirectory,
- name: file.name,
- }),
- key: `local-file-${file.path}`,
- label: file.name || file.path,
- metadata: {
- isDirectory: file.isDirectory,
- name: file.name || file.path.split('/').pop() || file.path,
- path: file.path,
- relativePath: file.relativePath,
- timestamp: 0,
- type: 'localFile' as const,
- },
- }));
+ return files.map((file) => {
+ const name = file.name || file.path.split('/').pop() || file.path;
+ const displayPath = file.relativePath || file.path;
+ const description = compactDirectoryTail(displayPath, name, file.isDirectory);
+
+ return {
+ icon: createElement(LocalFileIcon, {
+ isDirectory: file.isDirectory,
+ name,
+ }),
+ key: `local-file-${file.path}`,
+ label: compactFileName(name),
+ metadata: {
+ ...(description ? { description } : {}),
+ isDirectory: file.isDirectory,
+ name,
+ path: file.path,
+ relativePath: file.relativePath,
+ timestamp: 0,
+ type: 'localFile' as const,
+ },
+ };
+ });
} catch (error) {
console.error('[useLocalFileMention] Failed to search local files:', error);
return [];
}
},
- [enableLocalFileMention, workingDirectory],
+ [enableLocalFileMention, searchDeviceId, workingDirectory],
);
return { enableLocalFileMention, searchLocalFiles };
diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsx
index 3989698dee7..8c3c69747d2 100644
--- a/src/features/Portal/LocalFile/Body.test.tsx
+++ b/src/features/Portal/LocalFile/Body.test.tsx
@@ -77,7 +77,6 @@ vi.mock('@/services/projectFile', () => ({
vi.mock('@/utils/skillMarkdown', () => ({
parseSkillMarkdownFrontmatter: (content: string) => ({ body: content }),
- parseSkillMarkdownFrontmatterFields: () => ({}),
parseSkillMarkdownMetadata: () => [],
}));
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index a792e1fffb1..280aa14a582 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -18,7 +18,6 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import { createLocalFileTabId } from '@/store/chat/slices/portal/helpers';
import {
parseSkillMarkdownFrontmatter,
- parseSkillMarkdownFrontmatterFields,
parseSkillMarkdownMetadata,
type SkillMarkdownMetadataItem,
} from '@/utils/skillMarkdown';
@@ -122,6 +121,31 @@ type TextPreviewMode = 'render' | 'raw';
const NO_TOPIC_KEY = '__no_topic__';
+const floatingControlsStyles = createStaticStyles(({ css }) => ({
+ container: css`
+ position: absolute;
+ z-index: 2;
+ inset-block-start: 8px;
+ inset-inline-end: 12px;
+
+ padding: 4px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ opacity: 0.55;
+ background: ${cssVar.colorBgElevated};
+ backdrop-filter: blur(8px);
+ box-shadow: ${cssVar.boxShadowTertiary};
+
+ transition: opacity 0.15s ease;
+
+ &:hover,
+ &:focus-within {
+ opacity: 1;
+ }
+ `,
+}));
+
interface TextPreviewPaneProps {
activeTopicId?: string | null;
content: string;
@@ -211,17 +235,10 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
() => (isMarkdown ? parseSkillMarkdownFrontmatter(editingValue) : { body: editingValue }),
[isMarkdown, editingValue],
);
- const frontmatterFields = useMemo(
- () => (frontmatter ? parseSkillMarkdownFrontmatterFields(frontmatter) : {}),
- [frontmatter],
- );
const frontmatterMetadata = useMemo(
() => (frontmatter ? parseSkillMarkdownMetadata(frontmatter) : []),
[frontmatter],
);
- const previewTitle = isMarkdown
- ? (frontmatterFields.name ?? '')
- : (filePath.split('/').at(-1) ?? filePath);
const markdownComponents = useMemo(
() =>
({
@@ -254,19 +271,13 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
}, [onReload]);
return (
- <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
+ <Flexbox
+ flex={1}
+ height={'100%'}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
+ >
{canRender && (
- <Flexbox
- horizontal
- align={'center'}
- gap={8}
- paddingBlock={6}
- paddingInline={12}
- style={{ flexShrink: 0 }}
- >
- <Text ellipsis style={{ flex: 1, fontSize: 13, fontWeight: 500, minWidth: 0 }}>
- {previewTitle}
- </Text>
+ <Flexbox horizontal align={'center'} className={floatingControlsStyles.container} gap={4}>
{isHtml && (
<ActionIcon
icon={RefreshCwIcon}
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index f0e2a021531..9e0a477986b 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -1,4 +1,4 @@
-import { render } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode, Ref } from 'react';
import { useImperativeHandle } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -27,6 +27,7 @@ const gitFilesMock = vi.hoisted(() => ({
},
}));
const openLocalFileMock = vi.hoisted(() => vi.fn());
+const searchProjectFilesMock = vi.hoisted(() => vi.fn());
// ─── mocks ────────────────────────────────────────────────────────────────────
@@ -86,7 +87,6 @@ vi.mock('../useProjectFiles', () => ({
indexedAt: '2026-01-01',
root: '/repo',
source: 'git',
- totalCount: 2,
},
isLoading: false,
isValidating: false,
@@ -94,6 +94,12 @@ vi.mock('../useProjectFiles', () => ({
}),
}));
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: {
+ searchProjectFiles: searchProjectFilesMock,
+ },
+}));
+
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
selector({ openLocalFile: openLocalFileMock }),
@@ -112,11 +118,26 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => <button type="button" onClick={onClick} />,
Center: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
copyToClipboard: vi.fn(),
Empty: ({ description }: { description?: ReactNode }) => <div>{description}</div>,
Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ SearchBar: ({
+ onChange,
+ placeholder,
+ value,
+ }: {
+ onChange?: (e: { target: { value: string } }) => void;
+ placeholder?: string;
+ value?: string;
+ }) => (
+ <input
+ placeholder={placeholder}
+ value={value}
+ onChange={(e) => onChange?.({ target: { value: e.target.value } })}
+ />
+ ),
+ stopPropagation: vi.fn(),
}));
vi.mock('antd-style', () => ({
@@ -147,6 +168,7 @@ beforeEach(() => {
handleSpies.setExpanded.mockClear();
messageSpy.warning.mockClear();
openLocalFileMock.mockClear();
+ searchProjectFilesMock.mockReset();
useGlobalStore.setState({
...initialState,
status: { ...initialState.status, workingSidebarRevealRequest: undefined },
@@ -218,6 +240,57 @@ describe('Files — reveal request integration', () => {
});
});
+ it('filters file tree nodes while retaining ancestor directories', async () => {
+ searchProjectFilesMock.mockResolvedValueOnce({
+ entries: [
+ { isDirectory: true, name: 'src', path: '/repo/src', relativePath: 'src/' },
+ { isDirectory: true, name: 'foo', path: '/repo/src/foo', relativePath: 'src/foo/' },
+ {
+ isDirectory: false,
+ name: 'bar.ts',
+ path: '/repo/src/foo/bar.ts',
+ relativePath: 'src/foo/bar.ts',
+ },
+ ],
+ root: '/repo',
+ searchedAt: '2026-01-01',
+ source: 'git',
+ });
+ render(<Files workingDirectory="/repo" />);
+
+ fireEvent.change(screen.getByPlaceholderText('workingPanel.files.searchPlaceholder'), {
+ target: { value: 'bar' },
+ });
+
+ await waitFor(() => {
+ expect(searchProjectFilesMock).toHaveBeenCalledWith({
+ deviceId: undefined,
+ limit: 200,
+ query: 'bar',
+ scope: '/repo',
+ });
+ expect((explorerTreeProps.current?.nodes as { id: string }[]).map((node) => node.id)).toEqual(
+ ['src/', 'src/foo/', 'src/foo/bar.ts'],
+ );
+ });
+ });
+
+ it('shows a no-results state when the file filter has no matches', async () => {
+ searchProjectFilesMock.mockResolvedValueOnce({
+ entries: [],
+ root: '/repo',
+ searchedAt: '2026-01-01',
+ source: 'git',
+ });
+ render(<Files workingDirectory="/repo" />);
+
+ fireEvent.change(screen.getByPlaceholderText('workingPanel.files.searchPlaceholder'), {
+ target: { value: 'missing' },
+ });
+
+ expect(await screen.findByText('workingPanel.files.noSearchResults')).toBeInTheDocument();
+ });
+
it('(a) reveals existing path: calls setExpanded with ancestors, then select and focus', async () => {
render(<Files workingDirectory="/repo" />);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
index 4827c4944bb..02238b6eb18 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -1,11 +1,11 @@
'use client';
import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';
-import { ActionIcon, Center, copyToClipboard, Empty, Flexbox } from '@lobehub/ui';
+import { Center, copyToClipboard, Empty, Flexbox, SearchBar, stopPropagation } from '@lobehub/ui';
import type { MenuProps } from 'antd';
import { message } from 'antd';
import { createStaticStyles } from 'antd-style';
-import { FileIcon, RefreshCwIcon } from 'lucide-react';
+import { FileIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,6 +19,7 @@ import {
} from '@/features/ExplorerTree';
import type { ExplorerTreeHandle } from '@/features/ExplorerTree/types';
import { localFileService } from '@/services/electron/localFileService';
+import { projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
@@ -54,26 +55,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
min-height: 0;
`,
subheader: css`
- display: flex;
flex-shrink: 0;
- gap: 8px;
- align-items: center;
- justify-content: space-between;
-
- padding-block: 4px 8px;
- padding-inline: 14px 6px;
- `,
- count: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextTertiary};
+ padding-block: 6px 8px;
+ padding-inline: 12px;
`,
}));
const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
const FILE_TREE_UNSAFE_CSS = `${FOLDER_ICON_CSS}\n${HIDE_POINTER_FOCUS_RING_CSS}`;
+const FILE_SEARCH_DEBOUNCE_MS = 180;
+const PROJECT_FILE_TREE_SEARCH_LIMIT = 200;
const getParentRelativePath = (relativePath: string): string | null => {
const cleaned = stripTrailingSlash(relativePath);
@@ -114,7 +106,7 @@ const getAncestorIds = (filePath: string): string[] => {
const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const { t } = useTranslation('chat');
const isRemote = !!deviceId;
- const { data, isLoading, isValidating, mutate } = useProjectFiles(deviceId, workingDirectory);
+ const { data, isLoading } = useProjectFiles(deviceId, workingDirectory);
const { data: gitFiles } = useGitWorkingTreeFiles(
deviceId,
workingDirectory,
@@ -123,14 +115,27 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const projectRoot = data?.root ?? workingDirectory;
const entries = useMemo(() => data?.entries ?? [], [data]);
- const nodes = useMemo(() => buildTreeNodes(entries), [entries]);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [debouncedQuery, setDebouncedQuery] = useState('');
+ const [searchEntries, setSearchEntries] = useState<ProjectFileIndexEntry[] | undefined>();
+ const [isSearching, setIsSearching] = useState(false);
+ const normalizedDebouncedQuery = debouncedQuery.trim();
+ const isFiltering = normalizedDebouncedQuery.length > 0;
+ const displayEntries = useMemo(
+ () => (isFiltering ? (searchEntries ?? []) : entries),
+ [entries, isFiltering, searchEntries],
+ );
+ const nodes = useMemo(() => buildTreeNodes(displayEntries), [displayEntries]);
const gitStatus = useMemo(() => buildGitStatusEntries(gitFiles), [gitFiles]);
const dirtyFilePaths = useMemo(() => new Set(gitStatus.map((entry) => entry.path)), [gitStatus]);
// Pre-expand top-level directories so the user sees something useful on first
// paint without having to click through every folder.
const defaultExpandedIds = useMemo(
- () => nodes.filter((node) => node.isFolder && node.parentId == null).map((node) => node.id),
- [nodes],
+ () =>
+ nodes
+ .filter((node) => node.isFolder && (isFiltering || node.parentId == null))
+ .map((node) => node.id),
+ [isFiltering, nodes],
);
const treeStyleVars = useMemo(
() => getExplorerTreeStyleVars({ reserveChevronSlot: nodes.some((node) => node.isFolder) }),
@@ -139,6 +144,47 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const [expandedIds, setExpandedIds] = useState<string[]>([]);
+ useEffect(() => {
+ const timer = setTimeout(() => setDebouncedQuery(searchQuery), FILE_SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [searchQuery]);
+
+ useEffect(() => {
+ if (!normalizedDebouncedQuery) {
+ setIsSearching(false);
+ setSearchEntries(undefined);
+ return;
+ }
+
+ let cancelled = false;
+ setIsSearching(true);
+ setSearchEntries(undefined);
+
+ void projectFileService
+ .searchProjectFiles({
+ deviceId,
+ limit: PROJECT_FILE_TREE_SEARCH_LIMIT,
+ query: normalizedDebouncedQuery,
+ scope: workingDirectory,
+ })
+ .then((result) => {
+ if (cancelled) return;
+ setSearchEntries(result?.entries ?? []);
+ })
+ .catch((error) => {
+ if (cancelled) return;
+ console.error('[Files] Failed to search project files:', error);
+ setSearchEntries([]);
+ })
+ .finally(() => {
+ if (!cancelled) setIsSearching(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [deviceId, normalizedDebouncedQuery, workingDirectory]);
+
// Skip resyncs when defaultExpandedIds is structurally unchanged so the user's expansions survive re-renders.
const prevDefaultRef = useRef<string[]>([]);
useEffect(() => {
@@ -151,6 +197,11 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
const treeRef = useRef<ExplorerTreeHandle>(null);
+ useEffect(() => {
+ if (!isFiltering) return;
+ treeRef.current?.setExpanded(defaultExpandedIds);
+ }, [defaultExpandedIds, isFiltering]);
+
const revealRequest = useGlobalStore((s) => s.status.workingSidebarRevealRequest);
const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
@@ -255,7 +306,6 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
[dirtyFilePaths, isRemote, openNode, setWorkingSidebarTab, t],
);
- const fileCount = data?.totalCount ?? entries.filter((e) => !e.isDirectory).length;
const isEmpty = nodes.length === 0;
if (!data && isLoading) {
@@ -269,18 +319,31 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
return (
<Flexbox height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>
<div className={styles.subheader}>
- <span className={styles.count}>{t('workingPanel.files.count', { count: fileCount })}</span>
- <ActionIcon
- icon={RefreshCwIcon}
- loading={isValidating}
+ <SearchBar
+ allowClear
+ placeholder={t('workingPanel.files.searchPlaceholder')}
size={'small'}
- title={t('workingPanel.files.refresh')}
- onClick={() => void mutate()}
+ style={{ width: '100%' }}
+ styles={{ input: { width: '100%' } }}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyDown={stopPropagation}
/>
</div>
- {isEmpty ? (
+ {isEmpty && isFiltering && isSearching ? (
+ <Center flex={1}>
+ <NeuralNetworkLoading size={32} />
+ </Center>
+ ) : isEmpty ? (
<Center flex={1} gap={8} paddingBlock={24}>
- <Empty description={t('workingPanel.files.empty')} icon={FileIcon} />
+ <Empty
+ icon={FileIcon}
+ description={t(
+ isFiltering && debouncedQuery === searchQuery
+ ? 'workingPanel.files.noSearchResults'
+ : 'workingPanel.files.empty',
+ )}
+ />
</Center>
) : (
<div className={styles.tree} style={treeStyleVars}>
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 718badbb657..cefaf74cdf4 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -18,7 +18,6 @@ import {
type ListProjectSkillsResult,
type LocalFileItem,
type LocalFilePreviewUrlParams,
- type LocalFilePreviewUrlResult,
type LocalMoveFilesResultItem,
type LocalReadFileParams,
type LocalReadFileResult,
@@ -31,6 +30,8 @@ import {
type PrepareSkillDirectoryResult,
type ProjectFileIndexParams,
type ProjectFileIndexResult,
+ type ProjectFileSearchParams,
+ type ProjectFileSearchResult,
type RenameLocalFileParams,
type ResolveSkillResourcePathParams,
type ResolveSkillResourcePathResult,
@@ -139,6 +140,10 @@ class LocalFileService {
return ensureElectronIpc().localSystem.getProjectFileIndex(params);
}
+ async searchProjectFiles(params: ProjectFileSearchParams): Promise<ProjectFileSearchResult> {
+ return ensureElectronIpc().localSystem.searchProjectFiles(params);
+ }
+
async listProjectSkills(params: ListProjectSkillsParams): Promise<ListProjectSkillsResult> {
// Project-skill scanning lives in the main-process WorkspaceCtr ('workspace'
// group), split out of LocalFileCtr — hence the namespace differs from the
@@ -170,14 +175,8 @@ class LocalFileService {
return ensureElectronIpc().localSystem.auditSafePaths(params);
}
- async getLocalFilePreviewUrl(
- params: LocalFilePreviewUrlParams,
- ): Promise<LocalFilePreviewUrlResult> {
- return ensureElectronIpc().localSystem.getLocalFilePreviewUrl(params);
- }
-
async getLocalFilePreview(params: LocalFilePreviewUrlParams): Promise<LocalFilePreview> {
- const result = await this.getLocalFilePreviewUrl(params);
+ const result = await ensureElectronIpc().localSystem.getLocalFilePreviewUrl(params);
if (!result.success || !result.url) {
throw new Error(result.error || 'Missing local file preview URL');
diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.ts
index b5b8067bac5..fa85238aa7d 100644
--- a/src/services/projectFile.test.ts
+++ b/src/services/projectFile.test.ts
@@ -3,11 +3,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
const mockDeviceClient = vi.hoisted(() => ({
getLocalFilePreview: { query: vi.fn() },
getProjectFileIndex: { query: vi.fn() },
+ searchProjectFiles: { query: vi.fn() },
}));
const mockLocalFileService = vi.hoisted(() => ({
getLocalFilePreview: vi.fn(),
getProjectFileIndex: vi.fn(),
+ searchProjectFiles: vi.fn(),
}));
vi.mock('@lobechat/const', async (importOriginal) => ({
@@ -138,4 +140,52 @@ describe('projectFileService', () => {
type: 'text',
});
});
+
+ it('searches remote project files through device RPC', async () => {
+ const { projectFileService } = await import('./projectFile');
+ mockDeviceClient.searchProjectFiles.query.mockResolvedValue({
+ entries: [],
+ root: '/repo',
+ searchedAt: '2026-07-01T00:00:00.000Z',
+ source: 'git',
+ });
+
+ await projectFileService.searchProjectFiles({
+ deviceId: 'device-1',
+ limit: 20,
+ query: 'button',
+ scope: '/repo',
+ });
+
+ expect(mockDeviceClient.searchProjectFiles.query).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ limit: 20,
+ query: 'button',
+ scope: '/repo',
+ });
+ expect(mockLocalFileService.searchProjectFiles).not.toHaveBeenCalled();
+ });
+
+ it('searches local project files through localFileService', async () => {
+ const { projectFileService } = await import('./projectFile');
+ mockLocalFileService.searchProjectFiles.mockResolvedValue({
+ entries: [],
+ root: '/repo',
+ searchedAt: '2026-07-01T00:00:00.000Z',
+ source: 'git',
+ });
+
+ await projectFileService.searchProjectFiles({
+ limit: 20,
+ query: 'button',
+ scope: '/repo',
+ });
+
+ expect(mockLocalFileService.searchProjectFiles).toHaveBeenCalledWith({
+ limit: 20,
+ query: 'button',
+ scope: '/repo',
+ });
+ expect(mockDeviceClient.searchProjectFiles.query).not.toHaveBeenCalled();
+ });
});
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index 404853aab4e..2d39545d4dc 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -3,6 +3,7 @@ import type {
LocalMoveFilesResultItem,
MoveLocalFileParams,
ProjectFileIndexResult,
+ ProjectFileSearchResult,
RenameLocalFileResult,
} from '@lobechat/electron-client-ipc';
import type { DeviceLocalFilePreview } from '@lobechat/types';
@@ -61,6 +62,24 @@ class ProjectFileService {
: localFileService.getProjectFileIndex({ scope });
}
+ /** Search files within a project working directory. Matching runs on the file host. */
+ async searchProjectFiles({
+ deviceId,
+ limit,
+ query,
+ scope,
+ }: {
+ deviceId?: string;
+ limit?: number;
+ query: string;
+ scope: string;
+ }): Promise<ProjectFileSearchResult | undefined> {
+ return deviceId
+ ? ((await lambdaClient.device.searchProjectFiles.query({ deviceId, limit, query, scope })) ??
+ undefined)
+ : localFileService.searchProjectFiles({ limit, query, scope });
+ }
+
/** File preview payload for a file in a project working directory. */
async getLocalFilePreview({
deviceId,