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.

🐛 fix(cli): cap local file search factory results (#16281)

Rylan Cai78d34d076e6b
diff --git a/apps/cli/src/tools/localSystemRuntime.test.ts b/apps/cli/src/tools/localSystemRuntime.test.ts
new file mode 100644
index 00000000000..ee124180b16
--- /dev/null
+++ b/apps/cli/src/tools/localSystemRuntime.test.ts
@@ -0,0 +1,89 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { fileSearchMock } = vi.hoisted(() => ({
+ fileSearchMock: {
+ glob: vi.fn(),
+ search: vi.fn(),
+ },
+}));
+
+vi.mock('@lobechat/local-file-shell', async () => {
+ const actual = await vi.importActual<typeof import('@lobechat/local-file-shell')>(
+ '@lobechat/local-file-shell',
+ );
+
+ return {
+ ...actual,
+ createFileSearchModule: vi.fn(() => fileSearchMock),
+ };
+});
+
+describe('runLocalSystemTool file search routing', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ fileSearchMock.glob.mockReset();
+ fileSearchMock.search.mockReset();
+ fileSearchMock.glob.mockResolvedValue({
+ files: ['/tmp/a.ts'],
+ success: true,
+ total_files: 1,
+ });
+ fileSearchMock.search.mockResolvedValue([
+ {
+ createdTime: new Date(),
+ isDirectory: false,
+ lastAccessTime: new Date(),
+ modifiedTime: new Date(),
+ name: 'a.ts',
+ path: '/tmp/a.ts',
+ size: 1,
+ type: 'ts',
+ },
+ ]);
+ });
+
+ it('routes globFiles through the fallback factory with the default limit', async () => {
+ const { runLocalSystemTool } = await import('./localSystemRuntime');
+
+ await runLocalSystemTool('globFiles', { pattern: '**/*.ts', scope: '/tmp' });
+
+ expect(fileSearchMock.glob).toHaveBeenCalledWith({
+ limit: 100,
+ pattern: '**/*.ts',
+ scope: '/tmp',
+ });
+ });
+
+ it('routes searchFiles through the fallback factory with an explicit limit', async () => {
+ const { runLocalSystemTool } = await import('./localSystemRuntime');
+
+ await runLocalSystemTool('searchFiles', {
+ directory: '/tmp',
+ keywords: 'a.ts',
+ limit: 12,
+ });
+
+ expect(fileSearchMock.search).toHaveBeenCalledWith({
+ directory: '/tmp',
+ keywords: 'a.ts',
+ limit: 12,
+ });
+ });
+
+ it('routes searchFiles through the fallback factory with the default limit and resolved scope', async () => {
+ const { runLocalSystemTool } = await import('./localSystemRuntime');
+
+ await runLocalSystemTool('searchFiles', {
+ directory: 'src',
+ keywords: 'a.ts',
+ scope: '/tmp',
+ });
+
+ expect(fileSearchMock.search).toHaveBeenCalledWith({
+ directory: '/tmp/src',
+ keywords: 'a.ts',
+ limit: 100,
+ scope: '/tmp',
+ });
+ });
+});
diff --git a/apps/cli/src/tools/localSystemRuntime.ts b/apps/cli/src/tools/localSystemRuntime.ts
index 2cba9f70c0e..e2a7ceb2fe9 100644
--- a/apps/cli/src/tools/localSystemRuntime.ts
+++ b/apps/cli/src/tools/localSystemRuntime.ts
@@ -1,6 +1,7 @@
import path from 'node:path';
import type {
+ BaseFileSearch,
EditFileParams,
GetCommandOutputParams,
GlobFilesParams,
@@ -12,15 +13,14 @@ import type {
SearchFilesParams,
WriteFileParams,
} from '@lobechat/local-file-shell';
+import { createFileSearchModule } from '@lobechat/local-file-shell';
import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
import {
editLocalFile,
- globLocalFiles,
grepContent,
listLocalFiles,
readLocalFile,
- searchLocalFiles,
writeLocalFile,
} from './file';
import { getCommandOutput, killCommand, runCommand } from './shell';
@@ -46,6 +46,19 @@ export interface LocalSystemToolOutput {
const unsupported = (method: string) => (): Promise<never> =>
Promise.reject(new Error(`${method} is not supported by the LobeHub CLI`));
+const DEFAULT_FILE_SEARCH_LIMIT = 100;
+
+const fileSearch: BaseFileSearch = createFileSearchModule();
+
+const normalizeLimit = (limit?: number) =>
+ Number.isFinite(limit) && limit && limit > 0 ? Math.floor(limit) : DEFAULT_FILE_SEARCH_LIMIT;
+
+const globLocalFiles = async (params: GlobFilesParams) =>
+ fileSearch.glob({ ...params, limit: normalizeLimit(params.limit) });
+
+const searchLocalFiles = async (params: SearchFilesParams) =>
+ fileSearch.search({ ...params, limit: normalizeLimit(params.limit) });
+
/**
* Adapter wiring the CLI's `@lobechat/local-file-shell` functions (file ops) and
* shell wrappers (with the shared `ShellProcessManager`) into the shape the
@@ -151,7 +164,11 @@ export async function runLocalSystemTool(
args as SearchFilesParams & { scope?: string },
'directory',
);
- return runtime.searchFiles({ ...resolved, directory: resolved.directory || '' } as never);
+ return runtime.searchFiles({
+ ...resolved,
+ directory: resolved.directory || '',
+ limit: normalizeLimit(resolved.limit),
+ } as never);
}
case 'grepContent': {
@@ -162,7 +179,11 @@ export async function runLocalSystemTool(
case 'globFiles': {
const p = args as GlobFilesParams;
// Honor both `scope` (current manifest) and the `cwd` legacy alias.
- return runtime.globFiles({ directory: p.scope ?? p.cwd, pattern: p.pattern });
+ return runtime.globFiles({
+ directory: p.scope ?? p.cwd,
+ limit: normalizeLimit(p.limit),
+ pattern: p.pattern,
+ });
}
case 'runCommand': {
diff --git a/packages/builtin-tool-local-system/src/client/executor/index.ts b/packages/builtin-tool-local-system/src/client/executor/index.ts
index 924735eec8e..408741a9a09 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts
@@ -21,6 +21,8 @@ import { localFileService } from '@/services/electron/localFileService';
import { LocalSystemIdentifier } from '../../types';
import { resolveArgsWithScope } from '../../utils/path';
+const DEFAULT_FILE_SEARCH_LIMIT = 100;
+
const LocalSystemApiEnum = {
editFile: 'editFile' as const,
getCommandOutput: 'getCommandOutput' as const,
@@ -232,6 +234,10 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
try {
const result = await this.runtime.globFiles({
directory: params.scope,
+ limit:
+ Number.isFinite(params.limit) && params.limit && params.limit > 0
+ ? Math.floor(params.limit)
+ : DEFAULT_FILE_SEARCH_LIMIT,
pattern: params.pattern,
});
return this.toResult(result);
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index f13f8ae3191..290626593d5 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -378,6 +378,11 @@ export const LocalSystemManifest: BuiltinToolManifest = {
name: LocalSystemApiName.globFiles,
parameters: {
properties: {
+ limit: {
+ description:
+ 'Maximum number of matches to collect during execution. When omitted, the runtime applies a conservative default limit.',
+ type: 'number',
+ },
pattern: {
description:
'The glob pattern to match files against (e.g. "**/*.js", "src/**/*.ts"). Relative patterns are resolved against the scope.',
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index d8fb46f6e58..6d6287d6c19 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -349,6 +349,8 @@ export interface GrepContentResult {
// Glob types — same rationale as Grep above.
export interface GlobFilesParams {
+ /** Maximum number of results to collect. When omitted, callers may apply their own default. */
+ limit?: number;
pattern: string;
/** Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory. */
scope?: string;
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 bdaff224e99..ce9a5967a20 100644
--- a/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
@@ -85,4 +85,39 @@ describe('UnixFileSearch glob fallback root', () => {
expect(options.ignore).toContain('**/node_modules/**');
expect(options.ignore).toContain('**/.git/**');
});
+
+ it('passes the execution limit through to fd glob', async () => {
+ const toolDetector: ToolDetector = {
+ getBestTool: vi.fn().mockResolvedValue('fd'),
+ };
+ execaMock.mockResolvedValue({
+ exitCode: 0,
+ stdout: '/repo/packages/a.ts\n/repo/packages/b.ts\n',
+ });
+
+ const impl = new LinuxSearchServiceImpl(toolDetector);
+ await impl.glob({ limit: 7, pattern: '**/*.ts', scope: '/repo/packages' });
+
+ expect(execaMock).toHaveBeenCalledWith(
+ 'fd',
+ expect.arrayContaining(['--max-results', '7']),
+ expect.anything(),
+ );
+ });
+
+ it('does not force a glob execution limit when the caller omits it', async () => {
+ const toolDetector: ToolDetector = {
+ getBestTool: vi.fn().mockResolvedValue('fd'),
+ };
+ execaMock.mockResolvedValue({
+ exitCode: 0,
+ stdout: '/repo/packages/a.ts\n',
+ });
+
+ const impl = new LinuxSearchServiceImpl(toolDetector);
+ await impl.glob({ pattern: '**/*.ts', scope: '/repo/packages' });
+
+ const [, args] = execaMock.mock.calls[0] as [string, string[]];
+ expect(args).not.toContain('--max-results');
+ });
});
diff --git a/packages/local-file-shell/src/fileSearch/base.ts b/packages/local-file-shell/src/fileSearch/base.ts
index d201d0ea9ed..7d06ac28b44 100644
--- a/packages/local-file-shell/src/fileSearch/base.ts
+++ b/packages/local-file-shell/src/fileSearch/base.ts
@@ -153,6 +153,11 @@ export abstract class BaseFileSearch {
});
}
+ protected normalizePositiveLimit(limit?: number): number | undefined {
+ if (!Number.isFinite(limit) || !limit || limit < 1) return undefined;
+ return Math.floor(limit);
+ }
+
abstract search(options: SearchFilesParams): Promise<FileResult[]>;
abstract glob(params: GlobFilesParams): Promise<GlobFilesResult>;
diff --git a/packages/local-file-shell/src/fileSearch/impl/unix.ts b/packages/local-file-shell/src/fileSearch/impl/unix.ts
index da71b8d4c22..63159f58fe4 100644
--- a/packages/local-file-shell/src/fileSearch/impl/unix.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/unix.ts
@@ -93,7 +93,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
protected async searchWithFd(options: SearchFilesParams): Promise<FileResult[]> {
const searchDir = options.onlyIn || options.directory || os.homedir() || '/';
- const limit = options.limit || 30;
+ const limit = this.normalizePositiveLimit(options.limit) ?? 30;
logger.debug('Performing fd search', { keywords: options.keywords, searchDir });
@@ -147,7 +147,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
protected async searchWithFind(options: SearchFilesParams): Promise<FileResult[]> {
const searchDir = options.onlyIn || options.directory || os.homedir() || '/';
- const limit = options.limit || 30;
+ const limit = this.normalizePositiveLimit(options.limit) ?? 30;
logger.debug('Performing find search', { keywords: options.keywords, searchDir });
@@ -208,7 +208,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
protected async searchWithFastGlob(options: SearchFilesParams): Promise<FileResult[]> {
const searchDir = options.onlyIn || options.directory || os.homedir() || '/';
- const limit = options.limit || 30;
+ const limit = this.normalizePositiveLimit(options.limit) ?? 30;
logger.debug('Performing fast-glob search', { keywords: options.keywords, searchDir });
@@ -273,6 +273,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
protected async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
+ const limit = this.normalizePositiveLimit(params.limit);
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -291,6 +292,10 @@ export abstract class UnixFileSearch extends BaseFileSearch {
'.git',
];
+ if (limit) {
+ args.push('--max-results', String(limit));
+ }
+
const { stdout, exitCode } = await execa('fd', args, {
reject: false,
timeout: 30_000,
@@ -305,8 +310,9 @@ export abstract class UnixFileSearch extends BaseFileSearch {
.trim()
.split('\n')
.filter((line) => line.trim());
+ const limitedFiles = limit ? files.slice(0, limit) : files;
- const filesWithStats = await this.getFilesWithStats(files);
+ const filesWithStats = await this.getFilesWithStats(limitedFiles);
const sortedFiles = filesWithStats.sort((a, b) => b.mtime - a.mtime).map((f) => f.path);
logger.info(`${logPrefix} Glob completed`, { fileCount: sortedFiles.length });
@@ -326,6 +332,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
protected async globWithFind(params: GlobFilesParams): Promise<GlobFilesResult> {
const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
+ const limit = this.normalizePositiveLimit(params.limit);
const logPrefix = `[glob:find: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting find glob`, { searchPath });
@@ -356,8 +363,9 @@ export abstract class UnixFileSearch extends BaseFileSearch {
.trim()
.split('\n')
.filter((line) => line.trim());
+ const limitedFiles = limit ? files.slice(0, limit) : files;
- const filesWithStats = await this.getFilesWithStats(files);
+ const filesWithStats = await this.getFilesWithStats(limitedFiles);
const sortedFiles = filesWithStats.sort((a, b) => b.mtime - a.mtime).map((f) => f.path);
logger.info(`${logPrefix} Glob completed`, { fileCount: sortedFiles.length });
diff --git a/packages/local-file-shell/src/fileSearch/impl/windows.ts b/packages/local-file-shell/src/fileSearch/impl/windows.ts
index 0fb1c662037..dd5f2257fc7 100644
--- a/packages/local-file-shell/src/fileSearch/impl/windows.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/windows.ts
@@ -98,7 +98,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
private async searchWithFd(options: SearchFilesParams): Promise<FileResult[]> {
const searchDir = options.onlyIn || options.directory || os.homedir() || 'C:\\';
- const limit = options.limit || 30;
+ const limit = this.normalizePositiveLimit(options.limit) ?? 30;
logger.debug('Performing fd search', { keywords: options.keywords, searchDir });
@@ -152,7 +152,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
private async searchWithPowerShell(options: SearchFilesParams): Promise<FileResult[]> {
const searchDir = options.onlyIn || options.directory || os.homedir() || 'C:\\';
- const limit = options.limit || 30;
+ const limit = this.normalizePositiveLimit(options.limit) ?? 30;
logger.debug('Performing PowerShell search', { keywords: options.keywords, searchDir });
@@ -203,7 +203,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
private async searchWithFastGlob(options: SearchFilesParams): Promise<FileResult[]> {
const searchDir = options.onlyIn || options.directory || os.homedir() || 'C:\\';
- const limit = options.limit || 30;
+ const limit = this.normalizePositiveLimit(options.limit) ?? 30;
logger.debug('Performing fast-glob search', { keywords: options.keywords, searchDir });
@@ -264,6 +264,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
private async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
+ const limit = this.normalizePositiveLimit(params.limit);
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -282,6 +283,10 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
'.git',
];
+ if (limit) {
+ args.push('--max-results', String(limit));
+ }
+
const { stdout, exitCode } = await execa('fd', args, {
reject: false,
timeout: 30_000,
@@ -296,8 +301,9 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
.trim()
.split('\r\n')
.filter((line) => line.trim());
+ const limitedFiles = limit ? files.slice(0, limit) : files;
- const filesWithStats = await this.getFilesWithStats(files);
+ const filesWithStats = await this.getFilesWithStats(limitedFiles);
const sortedFiles = filesWithStats.sort((a, b) => b.mtime - a.mtime).map((f) => f.path);
logger.info(`${logPrefix} Glob completed`, { fileCount: sortedFiles.length });
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index 56233edb9f8..f6064eb1b24 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -168,6 +168,8 @@ export interface ListFilesResult {
export interface GlobFilesParams {
/** Legacy alias for `scope`. Honored when set; prefer `scope` for new callers. */
cwd?: string;
+ /** Maximum number of results to collect. When omitted, callers may apply their own default. */
+ limit?: number;
pattern: string;
/** Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory. */
scope?: string;
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index a9e72bba9d9..540a6e7246a 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -132,6 +132,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
case 'globLocalFiles': {
return {
+ limit: params.limit,
pattern: params.pattern,
scope: params.directory,
};
diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
index b6f4128cec9..a4b74e849c6 100644
--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
@@ -69,3 +69,28 @@ describe('LocalSystemExecutionRuntime.editFile', () => {
expect(output.content).not.toContain('UNKNOWN_EXEC_ERROR');
});
});
+
+describe('LocalSystemExecutionRuntime.globFiles', () => {
+ it('forwards limit into the local-system service glob params', async () => {
+ const service = createService({
+ globFiles: vi.fn().mockResolvedValue({
+ files: ['/tmp/a.ts'],
+ success: true,
+ total_files: 1,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ await runtime.globFiles({
+ directory: '/tmp',
+ limit: 42,
+ pattern: '**/*.ts',
+ });
+
+ expect(service.globFiles).toHaveBeenCalledWith({
+ limit: 42,
+ pattern: '**/*.ts',
+ scope: '/tmp',
+ });
+ });
+});
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 70e951f0c0b..801be6cf5c2 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -71,6 +71,7 @@ export interface RenameFileParams {
export interface GlobFilesParams {
directory?: string;
+ limit?: number;
pattern: string;
}