π€― 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: resolve globFiles/searchFiles scope against user workspace on Windows (#17676)
Northword24fc237d89b2
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.tsindex 93649474d71..f78d978cc6d 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts@@ -232,6 +232,45 @@ describe('localSystemRuntime', () => {expect(parseArgs()).toEqual({ pattern: 'TODO', scope: '/Users/me/repo' });});+ it('injects scope into globFiles when omitted', async () => {+ const proxy = buildProxy('/Users/me/repo');+ await proxy[LocalSystemApiName.globFiles]({ pattern: '**/*.ts' });++ expect(parseArgs()).toEqual({ pattern: '**/*.ts', scope: '/Users/me/repo' });+ });++ it('replaces scope "." with workingDirectory for globFiles', async () => {+ const proxy = buildProxy('/Users/me/repo');+ await proxy[LocalSystemApiName.globFiles]({ pattern: '**/*.ts', scope: '.' });++ expect(parseArgs()).toEqual({ pattern: '**/*.ts', scope: '/Users/me/repo' });+ });++ it('replaces scope "." with workingDirectory for searchFiles', async () => {+ const proxy = buildProxy('/Users/me/repo');+ await proxy[LocalSystemApiName.searchFiles]({ keywords: 'foo', scope: '.' });++ expect(parseArgs()).toEqual({ keywords: 'foo', scope: '/Users/me/repo' });+ });++ it('replaces scope "." with Windows workingDirectory for search ops', async () => {+ const proxy = buildProxy('D:\\some-project');++ await proxy[LocalSystemApiName.globFiles]({ pattern: '**/*.ts', scope: '.' });+ expect(parseArgs()).toEqual({ pattern: '**/*.ts', scope: 'D:\\some-project' });++ mockExecuteToolCall.mockClear();+ await proxy[LocalSystemApiName.searchFiles]({ keywords: 'foo', scope: '.' });+ expect(parseArgs()).toEqual({ keywords: 'foo', scope: 'D:\\some-project' });+ });++ it('does not override an explicit absolute scope on search ops', async () => {+ const proxy = buildProxy('/Users/me/repo');+ await proxy[LocalSystemApiName.globFiles]({ pattern: '**/*.ts', scope: '/explicit' });++ expect(parseArgs()).toEqual({ pattern: '**/*.ts', scope: '/explicit' });+ });+it('does not override an explicit cwd/scope supplied by the model', async () => {const proxy = buildProxy('/Users/me/repo');await proxy[LocalSystemApiName.runCommand]({ command: 'ls', cwd: '/explicit' });diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.tsindex 042526391fa..6969e283927 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts@@ -63,10 +63,14 @@ export const localSystemRuntime: ServerRuntimeRegistration = {for (const api of LocalSystemManifest.api) {const workingDirArg = WORKING_DIR_ARG[api.name];proxy[api.name] = async (args: any) => {- // Inject the device-bound cwd/scope when the model didn't supply one.- // `??=` leaves an explicit per-call override possible for the future.+ // Inject the device-bound cwd/scope when the model didn't supply one+ // or explicitly passed `.` (a relative reference that resolves to+ // process.cwd() on the device side β the LobeHub install directory on+ // packaged desktop instead of the user's actual workspace).+ const scopeValue: unknown = workingDirArg ? args?.[workingDirArg] : undefined;+ const needsInjection = scopeValue == null || scopeValue === '.';const finalArgs =- workingDirArg && context.workingDirectory && args?.[workingDirArg] == null+ workingDirArg && context.workingDirectory && needsInjection? { ...args, [workingDirArg]: context.workingDirectory }: args;diff --git a/packages/builtin-tool-local-system/src/client/executor/index.test.ts b/packages/builtin-tool-local-system/src/client/executor/index.test.tsindex c40d713dde3..a59159f96a1 100644--- a/packages/builtin-tool-local-system/src/client/executor/index.test.ts+++ b/packages/builtin-tool-local-system/src/client/executor/index.test.ts@@ -2,13 +2,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { localSystemExecutor } from './index';-const { globFilesMock } = vi.hoisted(() => ({+const { globFilesMock, searchFilesMock } = vi.hoisted(() => ({globFilesMock: vi.fn(),+ searchFilesMock: vi.fn(),}));vi.mock('@/services/electron/localFileService', () => ({localFileService: {globFiles: globFilesMock,+ searchLocalFiles: searchFilesMock,},}));@@ -31,6 +33,7 @@ describe('LocalSystemExecutor', () => {});expect(globFilesMock).toHaveBeenCalledWith({+ limit: 100,pattern: '**/*.{png,jpg,jpeg,gif,webp}',scope: '/tmp/images',});@@ -113,5 +116,108 @@ describe('LocalSystemExecutor', () => {totalCount: 0,});});++ it('resolves omitted scope to ctx.workingDirectory', async () => {+ globFilesMock.mockResolvedValue({+ files: [],+ success: true,+ total_files: 0,+ });++ await localSystemExecutor.globFiles(+ { pattern: '**/*.ts' },+ { workingDirectory: '/home/user/project', messageId: 'msg-1' },+ );++ expect(globFilesMock).toHaveBeenCalledWith({+ limit: 100,+ pattern: '**/*.ts',+ scope: '/home/user/project',+ });+ });++ it('resolves scope "." to ctx.workingDirectory', async () => {+ globFilesMock.mockResolvedValue({+ files: [],+ success: true,+ total_files: 0,+ });++ await localSystemExecutor.globFiles(+ { pattern: '**/*.ts', scope: '.' },+ { workingDirectory: '/home/user/project', messageId: 'msg-1' },+ );++ expect(globFilesMock).toHaveBeenCalledWith({+ limit: 100,+ pattern: '**/*.ts',+ scope: '/home/user/project',+ });+ });++ it('preserves explicit absolute scope', async () => {+ globFilesMock.mockResolvedValue({+ files: [],+ success: true,+ total_files: 0,+ });++ await localSystemExecutor.globFiles(+ { pattern: '**/*.ts', scope: '/explicit/path' },+ { workingDirectory: '/home/user/project', messageId: 'msg-1' },+ );++ expect(globFilesMock).toHaveBeenCalledWith({+ limit: 100,+ pattern: '**/*.ts',+ scope: '/explicit/path',+ });+ });+ });++ describe('searchFiles', () => {+ it('resolves omitted scope to ctx.workingDirectory', async () => {+ searchFilesMock.mockResolvedValue([]);++ await localSystemExecutor.searchFiles(+ { keywords: 'test' },+ { workingDirectory: '/home/user/project', messageId: 'msg-1' },+ );++ expect(searchFilesMock).toHaveBeenCalledWith({+ keywords: 'test',+ directory: '/home/user/project',+ });+ });++ it('resolves scope "." to ctx.workingDirectory', async () => {+ searchFilesMock.mockResolvedValue([]);++ await localSystemExecutor.searchFiles(+ { keywords: 'test', scope: '.' },+ { workingDirectory: '/home/user/project', messageId: 'msg-1' },+ );++ expect(searchFilesMock).toHaveBeenCalledWith({+ keywords: 'test',+ scope: '.',+ directory: '/home/user/project',+ });+ });++ it('preserves explicit absolute scope', async () => {+ searchFilesMock.mockResolvedValue([]);++ await localSystemExecutor.searchFiles(+ { keywords: 'test', scope: '/explicit/path' },+ { workingDirectory: '/home/user/project', messageId: 'msg-1' },+ );++ expect(searchFilesMock).toHaveBeenCalledWith({+ keywords: 'test',+ scope: '/explicit/path',+ directory: '/explicit/path',+ });+ });});});diff --git a/packages/builtin-tool-local-system/src/client/executor/index.ts b/packages/builtin-tool-local-system/src/client/executor/index.tsindex c64ea287180..dfb1b2cfbdb 100644--- a/packages/builtin-tool-local-system/src/client/executor/index.ts+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts@@ -122,9 +122,12 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {}};- searchFiles = async (params: LocalSearchFilesParams): Promise<BuiltinToolResult> => {+ searchFiles = async (+ params: LocalSearchFilesParams,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {try {- const resolvedParams = resolveArgsWithScope(params, 'directory');+ const resolvedParams = resolveArgsWithScope(params, 'directory', ctx?.workingDirectory);const result = await this.runtime.searchFiles({...resolvedParams,directory: resolvedParams.directory || '',@@ -249,10 +252,14 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {}};- globFiles = async (params: GlobFilesParams): Promise<BuiltinToolResult> => {+ globFiles = async (+ params: GlobFilesParams,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {try {+ const resolvedScope = resolvePathWithScope(params.scope, ctx?.workingDirectory);const result = await this.runtime.globFiles({- directory: params.scope,+ directory: resolvedScope,limit:Number.isFinite(params.limit) && params.limit && params.limit > 0? Math.floor(params.limit)diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.tsindex e1ff4f5e34f..be450029f4b 100644--- a/packages/builtin-tool-local-system/src/manifest.ts+++ b/packages/builtin-tool-local-system/src/manifest.ts@@ -86,7 +86,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},scope: {description:- 'Working directory scope. Limits the search to this directory. If you are searching the current project or are unsure, use "." for the current working directory. Use a specific path when the user names one explicitly.',+ "Working directory scope. Limits the search to this directory. Omit to default to the user's workspace directory. Use a specific path when the user names one explicitly.",type: 'string',},limit: {@@ -390,7 +390,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},scope: {description:- 'Working directory scope. When `pattern` is relative, it is joined with this scope. If you are searching the current project or are unsure, use "." for the current working directory. Use a specific path when the user names one explicitly.',+ "Working directory scope. When `pattern` is relative, it is joined with this scope. Omit to default to the user's workspace directory. Use a specific path when the user names one explicitly.",type: 'string',},},diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.tsindex 4e590507632..5429edc5b66 100644--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts@@ -58,7 +58,7 @@ You have access to a set of tools to interact with the user's local file system:- 'createdAfter' / 'createdBefore': Filter by creation date.- 'modifiedAfter' / 'modifiedBefore': Filter by modification date.- 'fileTypes': Filter by file type (e.g., "public.image", "txt").- - 'scope': Limit the search to a specific directory. Use "." when searching the current working directory or when unsure. **Always set this to the user's relevant folder (e.g., {{downloadsPath}}) when they refer to a known location** β without 'scope' the search spans the entire Spotlight index and is much slower.+ - 'scope': Limit the search to a specific directory. Omit to default to the user's workspace directory. Set an explicit path when the user names one (e.g., {{downloadsPath}}).- 'exclude': Exclude specific files or directories.- 'limit': Limit the number of results returned.- 'sortBy' / 'sortDirection': Sort the results.@@ -104,7 +104,7 @@ You have access to a set of tools to interact with the user's local file system:- 'head_limit' (Optional): Limit results to first N matches.- For finding files by pattern: Use 'globFiles'. Provide:- 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").- - 'scope' (Optional): Directory to search in. Use "." when searching the current working directory or when unsure. **Always set this when looking inside a user folder** (e.g. {{downloadsPath}}) β when omitted it falls back to the user's home directory, which can be very slow for broad patterns like "**/*foo*".+ - 'scope' (Optional): Directory to search in. Omit to default to the user's workspace directory. Set an explicit path when the user names one (e.g. {{downloadsPath}}).Returns files sorted by modification time (most recent first).</tool_usage_guidelines>diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.tsindex 01aa4281126..b51add1dc2d 100644--- a/packages/builtin-tool-local-system/src/systemRole.ts+++ b/packages/builtin-tool-local-system/src/systemRole.ts@@ -47,7 +47,7 @@ You have access to a set of tools to interact with the user's local file system:- 'createdAfter' / 'createdBefore': Filter by creation date.- 'modifiedAfter' / 'modifiedBefore': Filter by modification date.- 'fileTypes': Filter by file type (e.g., "public.image", "txt").- - 'scope': Limit the search to a specific directory. Use "." when searching the current working directory or when unsure. Without 'scope' the search spans the entire Spotlight index and is much slower.+ - 'scope': Limit the search to a specific directory. Omit to default to the user's workspace directory.- 'exclude': Exclude specific files or directories.- 'limit': Limit the number of results returned.- 'sortBy' / 'sortDirection': Sort the results.@@ -93,7 +93,7 @@ You have access to a set of tools to interact with the user's local file system:- 'head_limit' (Optional): Limit results to first N matches.- For finding files by pattern: Use 'globFiles'. Provide:- 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").- - 'scope' (Optional): Directory to search in. Use "." when searching the current working directory or when unsure. **Always set this when looking inside a user folder** β when omitted it falls back to the user's home directory, which can be very slow for broad patterns like "**/*foo*".+ - 'scope' (Optional): Directory to search in. Omit to default to the user's workspace directory. Set an explicit path when the user names one (e.g. {{homePath}}/Downloads).Returns files sorted by modification time (most recent first).</tool_usage_guidelines>`;diff --git a/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts b/packages/builtin-tool-local-system/src/utils/__tests__/path.test.tsindex 3e87800250a..58c3a4534f6 100644--- a/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts+++ b/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts@@ -82,6 +82,24 @@ describe('resolvePathWithScope', () => {it('should return absolute glob pattern as-is', () => {expect(resolvePathWithScope('/absolute/**/*.ts', '/workspace')).toBe('/absolute/**/*.ts');});++ it('should preserve Windows drive-letter absolute path', () => {+ expect(resolvePathWithScope('D:\\photos', 'C:\\workspace')).toBe('D:\\photos');+ });++ it('should preserve Windows drive-letter path with forward slashes', () => {+ expect(resolvePathWithScope('D:/photos', 'C:/workspace')).toBe('D:/photos');+ });++ it('should preserve UNC path', () => {+ expect(resolvePathWithScope('\\\\server\\share\\dir', '/workspace')).toBe(+ '\\\\server\\share\\dir',+ );+ });++ it('should preserve Windows root-relative path', () => {+ expect(resolvePathWithScope('\\logs', 'C:\\workspace')).toBe('\\logs');+ });});describe('resolveArgsWithScope', () => {diff --git a/packages/builtin-tool-local-system/src/utils/path.ts b/packages/builtin-tool-local-system/src/utils/path.tsindex 51528a8afbb..24f4e33fb51 100644--- a/packages/builtin-tool-local-system/src/utils/path.ts+++ b/packages/builtin-tool-local-system/src/utils/path.ts@@ -23,6 +23,11 @@ export const normalizePathForScope = (input: string): string => {return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;};+const isAbsolutePath = (input: string): boolean => {+ if (path.isAbsolute(input)) return true;+ return /^[A-Z]:[/\\]/i.test(input) || input.startsWith('\\\\') || input.startsWith('\\');+};+/*** Resolve a path against a scope (CWD).* - No path provided β use scope as default@@ -36,7 +41,7 @@ export const resolvePathWithScope = (): string | undefined => {if (!scope) return inputPath;if (!inputPath) return scope;- if (path.isAbsolute(inputPath)) return inputPath;+ if (isAbsolutePath(inputPath)) return inputPath;return path.join(scope, inputPath);};@@ -85,7 +90,8 @@ export const resolveArgsWithScope = <T extends { scope?: string }>(pathField: string,fallbackScope?: string,): T => {- const scope = args.scope || fallbackScope;+ const resolvedScope = resolvePathWithScope(args.scope, fallbackScope);+ const scope = resolvedScope ?? args.scope ?? fallbackScope;const currentPath = (args as Record<string, any>)[pathField] as string | undefined;const resolved = resolvePathWithScope(currentPath, scope);if (resolved === currentPath) return args;