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(local-system): tokenize mdfind keywords, scope glob to home, align tool prompts (#14358)

Arvin Xu8c3b83f8b3cc
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.test.ts b/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.test.ts
new file mode 100644
index 00000000000..47ee1cd7b38
--- /dev/null
+++ b/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildFilenameKeywordExpression } from '../impl/macOS';
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+}));
+
+describe('buildFilenameKeywordExpression', () => {
+ it('produces a single substring term for one keyword', () => {
+ expect(buildFilenameKeywordExpression('package.json')).toBe(
+ 'kMDItemFSName == "*package.json*"cd',
+ );
+ });
+
+ it('splits whitespace-separated keywords into AND-ed substring terms', () => {
+ // Critical fix: a free-form keyword string from the LLM (e.g. "LobeHub
+ // Financial Statement") used to require that exact phrase to appear in the
+ // filename. Real files reorder words and use _/-/. as separators, so the
+ // literal phrase almost never matched. AND-ing per-token substrings keeps
+ // each token literal but removes the order constraint.
+ expect(buildFilenameKeywordExpression('LobeHub Financial Statement')).toBe(
+ '(kMDItemFSName == "*LobeHub*"cd && kMDItemFSName == "*Financial*"cd && kMDItemFSName == "*Statement*"cd)',
+ );
+ });
+
+ it('collapses repeated whitespace and trims surrounding spaces', () => {
+ expect(buildFilenameKeywordExpression(' foo \t\n bar ')).toBe(
+ '(kMDItemFSName == "*foo*"cd && kMDItemFSName == "*bar*"cd)',
+ );
+ });
+
+ it('escapes embedded double quotes in each token', () => {
+ expect(buildFilenameKeywordExpression('foo "bar" baz')).toBe(
+ '(kMDItemFSName == "*foo*"cd && kMDItemFSName == "*\\"bar\\"*"cd && kMDItemFSName == "*baz*"cd)',
+ );
+ });
+
+ it('returns an empty string when keywords are blank', () => {
+ expect(buildFilenameKeywordExpression('')).toBe('');
+ expect(buildFilenameKeywordExpression(' \t ')).toBe('');
+ });
+});
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/unix.test.ts b/apps/desktop/src/main/modules/fileSearch/__tests__/unix.test.ts
new file mode 100644
index 00000000000..5bb5fcdaab4
--- /dev/null
+++ b/apps/desktop/src/main/modules/fileSearch/__tests__/unix.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LinuxSearchServiceImpl } from '../impl/linux';
+
+vi.mock('node:os', () => ({
+ homedir: vi.fn().mockReturnValue('/Users/test-home'),
+ platform: vi.fn().mockReturnValue('linux'),
+}));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+}));
+
+const fgMock = vi.fn();
+vi.mock('fast-glob', () => ({
+ default: (...args: unknown[]) => fgMock(...args),
+}));
+
+const execaMock = vi.fn();
+vi.mock('execa', () => ({
+ execa: (...args: unknown[]) => execaMock(...args),
+}));
+
+vi.mock('node:fs/promises', () => ({
+ stat: vi.fn().mockResolvedValue({
+ atime: new Date(),
+ birthtime: new Date(),
+ isDirectory: () => false,
+ mtime: new Date(),
+ size: 0,
+ }),
+}));
+
+describe('UnixFileSearch glob fallback root', () => {
+ beforeEach(() => {
+ fgMock.mockReset();
+ execaMock.mockReset();
+ // Force the Unix tool selection to fall through to fast-glob so we
+ // don't have to mock fd/find availability checks.
+ execaMock.mockRejectedValue(new Error('command not found'));
+ fgMock.mockResolvedValue([]);
+ });
+
+ it('runs glob inside the user home directory when no scope is provided', async () => {
+ // Regression: previously fell back to process.cwd(), which inside a
+ // packaged Electron app is the bundle path β€” making `**/*foo*` searches
+ // effectively look at nothing user-visible.
+ const impl = new LinuxSearchServiceImpl();
+ await impl.glob({ pattern: '**/*report*' });
+
+ expect(fgMock).toHaveBeenCalledTimes(1);
+ const [pattern, options] = fgMock.mock.calls[0] as [string, { cwd: string }];
+ expect(pattern).toBe('**/*report*');
+ expect(options.cwd).toBe('/Users/test-home');
+ });
+
+ it('honors an explicit scope over the home-directory fallback', async () => {
+ const impl = new LinuxSearchServiceImpl();
+ await impl.glob({ pattern: '**/*.ts', scope: '/Users/test-home/Downloads' });
+
+ const [, options] = fgMock.mock.calls[0] as [string, { cwd: string }];
+ expect(options.cwd).toBe('/Users/test-home/Downloads');
+ });
+});
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts b/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
index 527613786b2..1460fd35f17 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
+++ b/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
@@ -13,6 +13,29 @@ import { UnixFileSearch } from './unix';
const logger = createLogger('module:FileSearch:macOS');
+/**
+ * Build the kMDItemFSName expression for a free-form keyword string.
+ *
+ * Splits on whitespace and ANDs each token as a case/diacritic-insensitive
+ * substring match, so "Foo Bar" matches both `Bar_Foo.pdf` and `Foo Bar.pdf`
+ * β€” instead of requiring the literal phrase "Foo Bar" to appear.
+ *
+ * Returns an empty string when the keywords contain no usable token.
+ */
+export const buildFilenameKeywordExpression = (keywords: string): string => {
+ const tokens = keywords
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean)
+ .map((token) => token.replaceAll('"', '\\"'));
+
+ if (tokens.length === 0) return '';
+
+ const term = (token: string) => `kMDItemFSName == "*${token}*"cd`;
+ if (tokens.length === 1) return term(tokens[0]);
+ return `(${tokens.map(term).join(' && ')})`;
+};
+
/**
* Fallback tool type for macOS file search
* Priority: mdfind > fd > find > fast-glob
@@ -214,7 +237,7 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
if (options.keywords) {
if (!options.keywords.includes('kMDItem')) {
- queryExpression = `kMDItemFSName == "*${options.keywords.replaceAll('"', '\\"')}*"cd`;
+ queryExpression = buildFilenameKeywordExpression(options.keywords);
} else {
queryExpression = options.keywords;
}
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/unix.ts b/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
index 25a74eb4a67..95bbc31a71c 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
+++ b/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
@@ -337,7 +337,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
* @returns Glob results
*/
protected async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || process.cwd();
+ const searchPath = params.scope || os.homedir() || process.cwd();
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -393,7 +393,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
* @returns Glob results
*/
protected async globWithFind(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || process.cwd();
+ const searchPath = params.scope || os.homedir() || process.cwd();
const logPrefix = `[glob:find: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting find glob`, { searchPath });
@@ -455,7 +455,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
* @returns Glob results
*/
protected async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || process.cwd();
+ const searchPath = params.scope || os.homedir() || process.cwd();
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/windows.ts b/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
index 7b34a1927f6..83d9ee346d1 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
+++ b/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
@@ -335,7 +335,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
* @returns Glob results
*/
private async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || process.cwd();
+ const searchPath = params.scope || os.homedir() || process.cwd();
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -390,7 +390,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
* @returns Glob results
*/
private async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || process.cwd();
+ const searchPath = params.scope || os.homedir() || process.cwd();
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
diff --git a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
index 70abe2df5e0..84a339aeb1e 100644
--- a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts
@@ -202,6 +202,9 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
case 'grepContent': {
return {
+ // Surface raw.error so ComputerRuntime.errorOutput has a real message
+ // to render instead of `JSON.stringify(undefined)` β†’ undefined content.
+ error: raw.error ? { message: String(raw.error) } : undefined,
result: {
matches: raw.matches,
totalMatches: raw.total_matches,
@@ -212,6 +215,12 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
case 'globLocalFiles': {
return {
+ // Surface raw.error so ComputerRuntime.errorOutput has a real message
+ // to render instead of `JSON.stringify(undefined)` β†’ undefined content.
+ // Without this, a fast-glob throw (e.g. EACCES traversing a protected
+ // dir under the wrong cwd) leaves the tool message with state set but
+ // content stuck at "" β€” see "Glob search files Response η©Ί" report.
+ error: raw.error ? { message: String(raw.error) } : undefined,
result: {
files: raw.files,
totalCount: raw.total_files,
diff --git a/packages/builtin-tool-local-system/src/client/Render/SearchFiles/Result.tsx b/packages/builtin-tool-local-system/src/client/Render/SearchFiles/Result.tsx
index 69c79d6920f..7101287ad78 100644
--- a/packages/builtin-tool-local-system/src/client/Render/SearchFiles/Result.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/SearchFiles/Result.tsx
@@ -38,7 +38,7 @@ const SearchFiles = memo<SearchFilesProps>(({ searchResults = [], messageId }) =
}
return (
- <Flexbox gap={2} style={{ maxHeight: 140, overflow: 'scroll' }}>
+ <Flexbox gap={2} style={{ maxHeight: 220, overflow: 'auto' }}>
{searchResults.map((item) => (
<FileItem key={item.path} {...item} />
))}
diff --git a/packages/builtin-tool-local-system/src/client/components/FileItem.tsx b/packages/builtin-tool-local-system/src/client/components/FileItem.tsx
index ab36548a47c..d4fdcdffbd3 100644
--- a/packages/builtin-tool-local-system/src/client/components/FileItem.tsx
+++ b/packages/builtin-tool-local-system/src/client/components/FileItem.tsx
@@ -3,7 +3,8 @@ import { ActionIcon, Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import dayjs from 'dayjs';
import { FolderOpen } from 'lucide-react';
-import React, { memo, useState } from 'react';
+import nodePath from 'path-browserify-esm';
+import React, { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
@@ -19,27 +20,40 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillTertiary};
}
`,
- path: css`
+ dir: css`
overflow: hidden;
- font-size: 10px;
- line-height: 1;
- color: ${cssVar.colorTextDescription};
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ line-height: 1.3;
+ color: ${cssVar.colorTextTertiary};
text-overflow: ellipsis;
white-space: nowrap;
`,
size: css`
- min-width: 50px;
+ flex-shrink: 0;
+
+ min-width: 56px;
font-family: ${cssVar.fontFamilyCode};
- font-size: 10px;
+ font-size: 11px;
color: ${cssVar.colorTextTertiary};
text-align: end;
`,
+ time: css`
+ overflow: hidden;
+
+ font-size: 11px;
+ line-height: 1;
+ color: ${cssVar.colorTextDescription};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
title: css`
overflow: hidden;
display: block;
+ line-height: 1.3;
color: inherit;
text-overflow: ellipsis;
white-space: nowrap;
@@ -59,17 +73,29 @@ interface FileItemProps {
const FileItem = memo<FileItemProps>(
({ isDirectory, name: nameProp, path, size, type, showTime = false, createdTime }) => {
const { t } = useTranslation('tool');
- const [isHovering, setIsHovering] = useState(false);
- const { openFile, openFolder } = useToolRenderCapabilities();
+ const { openFile, openFolder, displayRelativePath } = useToolRenderCapabilities();
const name = nameProp || path?.split('/').pop() || '';
- const handleClick = () => {
+ // Display the parent directory only β€” the filename is already shown above,
+ // and the full path repeats it. Collapse $HOME to "~" when we have access
+ // to the desktop state, so paths like `/Users/foo/Downloads/x` render as
+ // `~/Downloads/x` and stay legible.
+ const parentDir = useMemo(() => {
+ if (!path || isDirectory) return '';
+ const dir = nodePath.dirname(path);
+ if (!dir || dir === '.' || dir === '/') return dir;
+ return displayRelativePath?.(dir) ?? dir;
+ }, [path, isDirectory, displayRelativePath]);
+
+ const handleRowClick = () => {
if (!path) return;
- if (isDirectory) {
- openFolder?.(path);
- } else {
- openFile?.(path);
- }
+ if (isDirectory) openFolder?.(path);
+ else openFile?.(path);
+ };
+
+ const handleOpenFolder = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ if (path) openFolder?.(path);
};
return (
@@ -78,51 +104,40 @@ const FileItem = memo<FileItemProps>(
align={'center'}
className={styles.container}
gap={12}
- padding={'2px 8px'}
+ padding={'4px 8px'}
style={{
cursor: openFile || openFolder ? 'pointer' : 'default',
fontSize: 12,
width: '100%',
}}
- onClick={handleClick}
- onMouseEnter={() => setIsHovering(true)}
- onMouseLeave={() => setIsHovering(false)}
+ onClick={handleRowClick}
>
<FileIcon
fileName={name || ''}
fileType={type}
isDirectory={isDirectory}
- size={16}
+ size={20}
variant={'raw'}
/>
- <Flexbox
- horizontal
- align={'baseline'}
- gap={4}
- style={{ overflow: 'hidden', width: '100%' }}
- >
+ <Flexbox flex={1} gap={2} style={{ overflow: 'hidden', minWidth: 0 }}>
<div className={styles.title}>{name}</div>
- {showTime && createdTime ? (
- <div className={styles.path}>{dayjs(createdTime).format('MMM DD hh:mm')}</div>
- ) : (
- <div className={styles.path}>{path}</div>
- )}
+ {showTime ? (
+ createdTime && (
+ <div className={styles.time}>{dayjs(createdTime).format('MMM DD hh:mm')}</div>
+ )
+ ) : parentDir ? (
+ <div className={styles.dir}>{parentDir}</div>
+ ) : null}
</Flexbox>
- {isHovering && openFolder ? (
- <Flexbox direction={'horizontal-reverse'} gap={8} style={{ minWidth: 50 }}>
- <ActionIcon
- icon={FolderOpen}
- size={'small'}
- style={{ height: 16, width: 16 }}
- title={t('localFiles.openFolder')}
- onClick={(e) => {
- e.stopPropagation();
- if (path) openFolder(path);
- }}
- />
- </Flexbox>
- ) : (
- <span className={styles.size}>{size !== undefined ? formatSize(size) : ''}</span>
+ {size !== undefined && <span className={styles.size}>{formatSize(size)}</span>}
+ {!isDirectory && openFolder && path && (
+ <ActionIcon
+ icon={FolderOpen}
+ size={'small'}
+ style={{ height: 24, width: 24 }}
+ title={t('localFiles.openFolder')}
+ onClick={handleOpenFolder}
+ />
)}
</Flexbox>
);
diff --git a/packages/builtin-tool-local-system/src/executor/index.test.ts b/packages/builtin-tool-local-system/src/executor/index.test.ts
index d8dba80db65..a510a924a03 100644
--- a/packages/builtin-tool-local-system/src/executor/index.test.ts
+++ b/packages/builtin-tool-local-system/src/executor/index.test.ts
@@ -35,5 +35,83 @@ describe('LocalSystemExecutor', () => {
scope: '/tmp/images',
});
});
+
+ it('returns formatted "Found N files" content on success', async () => {
+ globFilesMock.mockResolvedValue({
+ engine: 'fast-glob',
+ files: ['/Users/me/Downloads/a.pdf', '/Users/me/Downloads/b.pdf'],
+ success: true,
+ total_files: 2,
+ });
+
+ const result = await localSystemExecutor.globLocalFiles({
+ pattern: '**/*.pdf',
+ scope: '/Users/me/Downloads',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Found 2 files');
+ expect(result.state).toEqual({
+ files: ['/Users/me/Downloads/a.pdf', '/Users/me/Downloads/b.pdf'],
+ pattern: '**/*.pdf',
+ totalCount: 2,
+ });
+ });
+
+ it('falls back to a meaningful content + preserves state when IPC reports failure with no error message', async () => {
+ // Defense in depth: even if normalizeResult ever forgets to forward
+ // `raw.error`, toResult should still produce a non-empty content
+ // ("Tool execution failed") so the Response panel and the LLM never see
+ // an empty string. State must also survive into the failure result so
+ // any renderer can still draw partial output.
+ globFilesMock.mockResolvedValue({
+ engine: 'fast-glob',
+ files: [],
+ success: false,
+ total_files: 0,
+ });
+
+ const result = await localSystemExecutor.globLocalFiles({
+ pattern: '**/*never-matches*',
+ });
+
+ expect(result.content).toBeTruthy();
+ expect(result.content).not.toBe('');
+ expect(result.state).toEqual({
+ files: [],
+ pattern: '**/*never-matches*',
+ totalCount: 0,
+ });
+ });
+
+ it('surfaces the underlying error in content when the IPC reports failure', async () => {
+ // Regression: a fast-glob throw used to come back as
+ // { result: {files:[], totalCount:0}, success: false }
+ // with the error stripped. ComputerRuntime.errorOutput then did
+ // `JSON.stringify(undefined)` and produced `content: undefined`,
+ // which the chat store coerced to "" β€” leaving Glob tool messages
+ // with state set but Response panel blank. Verify we now keep the
+ // error message all the way into `content`.
+ globFilesMock.mockResolvedValue({
+ engine: 'fast-glob',
+ error: "EACCES: permission denied, scandir '/System/Volumes/Data'",
+ files: [],
+ success: false,
+ total_files: 0,
+ });
+
+ const result = await localSystemExecutor.globLocalFiles({
+ pattern: '**/*Financial*Statement*',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toBeTruthy();
+ expect(result.content).toContain('EACCES');
+ expect(result.state).toEqual({
+ files: [],
+ pattern: '**/*Financial*Statement*',
+ totalCount: 0,
+ });
+ });
});
});
diff --git a/packages/builtin-tool-local-system/src/executor/index.ts b/packages/builtin-tool-local-system/src/executor/index.ts
index c1d2ed35919..c8dbfa9d8a7 100644
--- a/packages/builtin-tool-local-system/src/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/executor/index.ts
@@ -51,7 +51,14 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
private runtime = new LocalSystemExecutionRuntime(localFileService);
/**
- * Convert BuiltinServerRuntimeOutput to BuiltinToolResult
+ * Convert BuiltinServerRuntimeOutput to BuiltinToolResult.
+ *
+ * Single funnel for every executor return β€” keep it strict:
+ * - never propagate an undefined `content` (would collapse downstream into
+ * `''` and leave the Debug "Response" pane blank while pluginState was
+ * still saved β€” see globLocalFiles regression);
+ * - always preserve `state` when the runtime produced one, regardless of
+ * `success`, so renderers can keep displaying partial outputs on failure.
*/
private toResult(output: {
content: string;
@@ -59,16 +66,21 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
state?: any;
success: boolean;
}): BuiltinToolResult {
+ const errorMessage =
+ typeof output.error?.message === 'string' ? output.error.message : undefined;
+ const safeContent = output.content || errorMessage || 'Tool execution failed';
+
if (!output.success) {
return {
- content: output.content,
+ content: safeContent,
error: output.error
- ? { body: output.error, message: output.content, type: 'PluginServerError' }
+ ? { body: output.error, message: errorMessage ?? safeContent, type: 'PluginServerError' }
: undefined,
+ state: output.state,
success: false,
};
}
- return { content: output.content, state: output.state, success: true };
+ return { content: safeContent, state: output.state, success: true };
}
// ==================== File Operations ====================
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 91a2890c3ad..9e18dd94829 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -62,12 +62,12 @@ You have access to a set of tools to interact with the user's local file system:
- 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
- If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').
- To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
-- For searching files: Use 'searchFiles' with the 'query' parameter (search string). You can optionally add the following filter parameters to narrow down the search:
+- For searching files: Use 'searchLocalFiles' with the 'keywords' parameter (search string). 'keywords' is split on whitespace and every token must appear as a substring of the filename (case- and diacritic-insensitive, order-independent). Pass only the discriminating words β€” long phrases full of optional words will return nothing. You can optionally add the following filter parameters to narrow down the search:
- 'contentContains': Find files whose content includes specific text.
- 'createdAfter' / 'createdBefore': Filter by creation date.
- 'modifiedAfter' / 'modifiedBefore': Filter by modification date.
- 'fileTypes': Filter by file type (e.g., "public.image", "txt").
- - 'onlyIn': Limit the search to a specific directory.
+ - 'scope': Limit the search to a specific directory. **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.
- 'exclude': Exclude specific files or directories.
- 'limit': Limit the number of results returned.
- 'sortBy' / 'sortDirection': Sort the results.
@@ -99,7 +99,7 @@ You have access to a set of tools to interact with the user's local file system:
- For killing background commands: Use 'killCommand' with 'shell_id'.
- For searching content in files: Use 'grepContent'. Provide:
- 'pattern': The regex pattern to search for.
- - 'path' (Optional): File or directory to search.
+ - 'scope' (Optional): Directory to search in. Defaults to the working directory if omitted.
- 'output_mode' (Optional): "content" (matching lines), "files_with_matches" (file paths, default), "count" (match counts).
- 'glob' (Optional): Glob pattern to filter files (e.g., "*.js", "*.{ts,tsx}").
- '-i' (Optional): Case insensitive search.
@@ -108,7 +108,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 'globLocalFiles'. Provide:
- 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").
- - 'path' (Optional): Directory to search in.
+ - 'scope' (Optional): Directory to search in. **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*".
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.ts
index ddc6bcc6426..bda59021c3b 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -51,12 +51,12 @@ You have access to a set of tools to interact with the user's local file system:
- 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
- If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').
- To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
-- For searching files: Use 'searchFiles' with the 'query' parameter (search string). You can optionally add the following filter parameters to narrow down the search:
+- For searching files: Use 'searchLocalFiles' with the 'keywords' parameter (search string). 'keywords' is split on whitespace and every token must appear as a substring of the filename (case- and diacritic-insensitive, order-independent). Pass only the discriminating words β€” long phrases full of optional words will return nothing. You can optionally add the following filter parameters to narrow down the search:
- 'contentContains': Find files whose content includes specific text.
- 'createdAfter' / 'createdBefore': Filter by creation date.
- 'modifiedAfter' / 'modifiedBefore': Filter by modification date.
- 'fileTypes': Filter by file type (e.g., "public.image", "txt").
- - 'onlyIn': Limit the search to a specific directory.
+ - 'scope': Limit the search to a specific directory. Without 'scope' the search spans the entire Spotlight index and is much slower.
- 'exclude': Exclude specific files or directories.
- 'limit': Limit the number of results returned.
- 'sortBy' / 'sortDirection': Sort the results.
@@ -88,7 +88,7 @@ You have access to a set of tools to interact with the user's local file system:
- For killing background commands: Use 'killCommand' with 'shell_id'.
- For searching content in files: Use 'grepContent'. Provide:
- 'pattern': The regex pattern to search for.
- - 'path' (Optional): File or directory to search.
+ - 'scope' (Optional): Directory to search in. Defaults to the working directory if omitted.
- 'output_mode' (Optional): "content" (matching lines), "files_with_matches" (file paths, default), "count" (match counts).
- 'glob' (Optional): Glob pattern to filter files (e.g., "*.js", "*.{ts,tsx}").
- '-i' (Optional): Case insensitive search.
@@ -97,7 +97,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 'globLocalFiles'. Provide:
- 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").
- - 'path' (Optional): Directory to search in.
+ - 'scope' (Optional): Directory to search in. **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*".
Returns files sorted by modification time (most recent first).
</tool_usage_guidelines>
`;
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 45f01a11845..b750af98dd0 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -464,8 +464,16 @@ export abstract class ComputerRuntime {
}
private errorOutput(result: ServiceResult, state: any): BuiltinServerRuntimeOutput {
+ // Defensive fallback: when a service reports success: false without an
+ // error object, JSON.stringify(undefined) returns the value `undefined`
+ // (not the string "undefined"), which collapsed downstream into an empty
+ // tool-message content while pluginState still got persisted.
+ const errorText =
+ result.error?.message ||
+ (result.error !== undefined ? JSON.stringify(result.error) : undefined) ||
+ 'Tool execution failed';
return {
- content: result.error?.message || JSON.stringify(result.error),
+ content: errorText,
state,
success: true,
};
diff --git a/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts b/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts
index 0752224829d..e534cbd25ca 100644
--- a/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts
+++ b/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts
@@ -870,20 +870,35 @@ const toolRenderFixtures: Record<string, ToolRenderFixture> = {
},
},
[keyOf('lobe-local-system', 'searchLocalFiles')]: {
- args: { directory: '/workspace/src', keyword: 'devtools' },
+ args: { keywords: 'quarterly report sample' },
pluginState: {
results: [
{
isDirectory: false,
- name: 'index.tsx',
- path: '/workspace/src/routes/(main)/devtools/index.tsx',
+ name: 'sample-quarterly-report-q1.xlsx',
+ path: '/Users/sample-user/Downloads/sample-quarterly-report-q1.xlsx',
+ size: 9_400,
},
{
isDirectory: false,
- name: 'desktopRouter.config.tsx',
- path: '/workspace/src/spa/router/desktopRouter.config.tsx',
+ name: 'sample_quarterly_report_q2_draft.xlsx',
+ path: '/Users/sample-user/Downloads/sample_quarterly_report_q2_draft.xlsx',
+ size: 35_600,
+ },
+ {
+ isDirectory: false,
+ name: 'sample-quarterly-report-q3.xlsx',
+ path: '/Users/sample-user/Documents/reports/sample-quarterly-report-q3.xlsx',
+ size: 8_300,
+ },
+ {
+ isDirectory: false,
+ name: 'sample-quarterly-report-archived.xlsx',
+ path: '/Users/sample-user/Documents/archive/2024/sample-quarterly-report-archived.xlsx',
+ size: 16_200,
},
],
+ totalCount: 4,
},
},
[keyOf('lobe-local-system', 'writeLocalFile')]: {