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): forward all search params and guard empty mdfind (#14355)

Arvin Xudc3c48e469f2
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 88d8b041f4c..167927c16d3 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -38,6 +38,7 @@ import {
} from '@lobechat/electron-client-ipc';
import {
editLocalFile,
+ expandTilde,
listLocalFiles,
moveLocalFiles,
readLocalFile,
@@ -574,7 +575,7 @@ export default class LocalFileCtr extends ControllerModule {
*/
@IpcMethod()
async handleLocalFilesSearch(params: LocalSearchFilesParams): Promise<FileResult[]> {
- const effectiveDirectory = params.directory ?? params.scope;
+ const effectiveDirectory = expandTilde(params.directory ?? params.scope);
logger.debug('Received file search request:', {
directory: params.directory,
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts b/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
index 2a42880435f..527613786b2 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
+++ b/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
@@ -95,7 +95,16 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
* Search using Spotlight (mdfind)
*/
private async searchWithSpotlight(options: SearchOptions): Promise<FileResult[]> {
- const { cmd, args, commandString } = this.buildSearchCommand(options);
+ const { cmd, args, commandString, hasQuery } = this.buildSearchCommand(options);
+
+ // Spotlight (mdfind) requires a query expression; running it with only flags
+ // (e.g. -onlyin) makes mdfind print its usage to stdout and we'd treat each
+ // line as a fake file. Short-circuit to an empty result instead.
+ if (!hasQuery) {
+ logger.warn('Skipping mdfind: no keywords/contentContains/fileTypes/date filter provided');
+ return [];
+ }
+
logger.debug(`Executing command: ${commandString}`);
try {
@@ -176,6 +185,7 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
args: string[];
cmd: string;
commandString: string;
+ hasQuery: boolean;
} {
const cmd = 'mdfind';
const args: string[] = [];
@@ -271,13 +281,15 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
}
}
- if (queryExpression) {
+ const hasQuery = Boolean(queryExpression);
+
+ if (hasQuery) {
args.push(queryExpression);
}
const commandString = `${cmd} ${args.map((arg) => (arg.includes(' ') || arg.includes('*') ? `"${arg}"` : arg)).join(' ')}`;
- return { args, cmd, commandString };
+ return { args, cmd, commandString, hasQuery };
}
/**
@@ -288,7 +300,7 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
options: SearchOptions,
engine?: string,
): Promise<FileResult[]> {
- const resultPromises = filePaths.map(async (filePath) => {
+ const resultPromises = filePaths.map(async (filePath): Promise<FileResult | null> => {
try {
const stats = await stat(filePath);
@@ -313,23 +325,15 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
return result;
} catch (error) {
- logger.warn(`Error processing file stats for ${filePath}: ${(error as Error).message}`);
- return {
- contentType: 'unknown',
- createdTime: new Date(),
- engine,
- isDirectory: false,
- lastAccessTime: new Date(),
- modifiedTime: new Date(),
- name: path.basename(filePath),
- path: filePath,
- size: 0,
- type: path.extname(filePath).toLowerCase().replace('.', ''),
- };
+ // Drop the row instead of fabricating a 0-byte placeholder. mdfind
+ // occasionally returns non-path lines (e.g. usage text when the query
+ // is malformed) which would otherwise render as phantom files.
+ logger.warn(`Dropping unstattable search hit ${filePath}: ${(error as Error).message}`);
+ return null;
}
});
- let results = await Promise.all(resultPromises);
+ let results = (await Promise.all(resultPromises)).filter((r): r is FileResult => r !== null);
if (options.sortBy) {
results = this.sortResults(results, options.sortBy, options.sortDirection);
diff --git a/packages/builtin-tool-local-system/src/client/Render/ListFiles/Result.tsx b/packages/builtin-tool-local-system/src/client/Render/ListFiles/Result.tsx
index 647387ebe74..0f21817983c 100644
--- a/packages/builtin-tool-local-system/src/client/Render/ListFiles/Result.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/ListFiles/Result.tsx
@@ -1,7 +1,9 @@
import { useToolRenderCapabilities } from '@lobechat/shared-tool-ui';
import type { ChatMessagePluginError } from '@lobechat/types';
-import { Flexbox, Skeleton } from '@lobehub/ui';
+import { Block, Empty, Flexbox, Skeleton } from '@lobehub/ui';
+import { FolderOpenIcon } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import FileItem from '../../components/FileItem';
@@ -13,6 +15,7 @@ interface SearchFilesProps {
const SearchFiles = memo<SearchFilesProps>(({ listResults = [], messageId }) => {
const { isLoading } = useToolRenderCapabilities();
+ const { t } = useTranslation('tool');
const loading = isLoading?.(messageId);
if (loading) {
@@ -26,6 +29,14 @@ const SearchFiles = memo<SearchFilesProps>(({ listResults = [], messageId }) =>
);
}
+ if (listResults.length === 0) {
+ return (
+ <Block variant={'outlined'}>
+ <Empty description={t('localFiles.listFiles.emptyDirectory')} icon={FolderOpenIcon} />
+ </Block>
+ );
+ }
+
return (
<Flexbox gap={2} style={{ maxHeight: 140, overflow: 'scroll' }}>
{listResults.map((item) => (
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 c2805767c81..69c79d6920f 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
@@ -1,7 +1,9 @@
import { useToolRenderCapabilities } from '@lobechat/shared-tool-ui';
import type { ChatMessagePluginError } from '@lobechat/types';
-import { Flexbox, Skeleton } from '@lobehub/ui';
+import { Block, Empty, Flexbox, Skeleton } from '@lobehub/ui';
+import { SearchIcon } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import FileItem from '../../components/FileItem';
@@ -13,6 +15,7 @@ interface SearchFilesProps {
const SearchFiles = memo<SearchFilesProps>(({ searchResults = [], messageId }) => {
const { isLoading } = useToolRenderCapabilities();
+ const { t } = useTranslation('tool');
const loading = isLoading?.(messageId);
if (loading) {
@@ -26,6 +29,14 @@ const SearchFiles = memo<SearchFilesProps>(({ searchResults = [], messageId }) =
);
}
+ if (searchResults.length === 0) {
+ return (
+ <Block variant={'outlined'}>
+ <Empty description={t('search.emptyResult')} icon={SearchIcon} />
+ </Block>
+ );
+ }
+
return (
<Flexbox gap={2} style={{ maxHeight: 140, overflow: 'scroll' }}>
{searchResults.map((item) => (
diff --git a/packages/builtin-tool-local-system/src/executor/index.ts b/packages/builtin-tool-local-system/src/executor/index.ts
index 4612ec758e1..c1d2ed35919 100644
--- a/packages/builtin-tool-local-system/src/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/executor/index.ts
@@ -112,6 +112,7 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
try {
const resolvedParams = resolveArgsWithScope(params, 'directory');
const result = await this.runtime.searchFiles({
+ ...resolvedParams,
directory: resolvedParams.directory || '',
});
return this.toResult(result);
diff --git a/packages/local-file-shell/src/file/__tests__/file.test.ts b/packages/local-file-shell/src/file/__tests__/file.test.ts
index 8f6e43e3b9e..b982820116b 100644
--- a/packages/local-file-shell/src/file/__tests__/file.test.ts
+++ b/packages/local-file-shell/src/file/__tests__/file.test.ts
@@ -302,6 +302,15 @@ describe('file operations', () => {
expect(dir!.isDirectory).toBe(true);
expect(dir!.type).toBe('directory');
});
+
+ it('should expand leading ~ to the user home directory', async () => {
+ const home = os.homedir();
+ const homeListing = await listLocalFiles({ path: home });
+ const tildeListing = await listLocalFiles({ path: '~' });
+
+ expect(tildeListing.totalCount).toBe(homeListing.totalCount);
+ expect(tildeListing.totalCount).toBeGreaterThan(0);
+ });
});
// ─── moveLocalFiles ───
diff --git a/packages/local-file-shell/src/file/edit.ts b/packages/local-file-shell/src/file/edit.ts
index 632cef01c93..bad4b26f77d 100644
--- a/packages/local-file-shell/src/file/edit.ts
+++ b/packages/local-file-shell/src/file/edit.ts
@@ -3,13 +3,15 @@ import { readFile, writeFile } from 'node:fs/promises';
import { createPatch } from 'diff';
import type { EditFileParams, EditFileResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function editLocalFile({
- file_path: filePath,
+ file_path: rawPath,
old_string,
new_string,
replace_all = false,
}: EditFileParams): Promise<EditFileResult> {
+ const filePath = expandTilde(rawPath) ?? rawPath;
try {
const content = await readFile(filePath, 'utf8');
diff --git a/packages/local-file-shell/src/file/expandTilde.ts b/packages/local-file-shell/src/file/expandTilde.ts
new file mode 100644
index 00000000000..1085762c23c
--- /dev/null
+++ b/packages/local-file-shell/src/file/expandTilde.ts
@@ -0,0 +1,17 @@
+import os from 'node:os';
+import path from 'node:path';
+
+/**
+ * Expand a leading `~` (or `~/...`, `~\...`) to the user's home directory.
+ * Pass-through for any other input β€” the shell normally handles `~` expansion,
+ * but Node fs APIs do not, so paths supplied by the LLM (or pasted by users)
+ * would otherwise fail with ENOENT.
+ */
+export const expandTilde = (input: string | undefined): string | undefined => {
+ if (!input) return input;
+ if (input === '~') return os.homedir();
+ if (input.startsWith('~/') || input.startsWith('~\\')) {
+ return path.join(os.homedir(), input.slice(2));
+ }
+ return input;
+};
diff --git a/packages/local-file-shell/src/file/glob.ts b/packages/local-file-shell/src/file/glob.ts
index b61f324b1ad..d09ad9990d2 100644
--- a/packages/local-file-shell/src/file/glob.ts
+++ b/packages/local-file-shell/src/file/glob.ts
@@ -1,11 +1,12 @@
import fg from 'fast-glob';
import type { GlobFilesParams, GlobFilesResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function globLocalFiles({ pattern, cwd }: GlobFilesParams): Promise<GlobFilesResult> {
try {
const files = await fg(pattern, {
- cwd: cwd || process.cwd(),
+ cwd: expandTilde(cwd) || process.cwd(),
dot: false,
ignore: ['**/node_modules/**', '**/.git/**'],
});
diff --git a/packages/local-file-shell/src/file/grep.ts b/packages/local-file-shell/src/file/grep.ts
index 12cca0768fb..510b3c0db7f 100644
--- a/packages/local-file-shell/src/file/grep.ts
+++ b/packages/local-file-shell/src/file/grep.ts
@@ -1,6 +1,7 @@
import { spawn } from 'node:child_process';
import type { GrepContentParams, GrepContentResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function grepContent({
pattern,
@@ -12,7 +13,7 @@ export async function grepContent({
if (filePattern) args.push('--glob', filePattern);
args.push(pattern);
- const child = spawn('rg', args, { cwd: cwd || process.cwd() });
+ const child = spawn('rg', args, { cwd: expandTilde(cwd) || process.cwd() });
let stdout = '';
child.stdout?.on('data', (data) => {
diff --git a/packages/local-file-shell/src/file/index.ts b/packages/local-file-shell/src/file/index.ts
index 25300c79f55..cefcf9ebbd8 100644
--- a/packages/local-file-shell/src/file/index.ts
+++ b/packages/local-file-shell/src/file/index.ts
@@ -1,4 +1,5 @@
export { editLocalFile } from './edit';
+export { expandTilde } from './expandTilde';
export { globLocalFiles } from './glob';
export { grepContent } from './grep';
export type { ListFilesOptions } from './list';
diff --git a/packages/local-file-shell/src/file/list.ts b/packages/local-file-shell/src/file/list.ts
index 954ae7a0d13..0ab81df44fe 100644
--- a/packages/local-file-shell/src/file/list.ts
+++ b/packages/local-file-shell/src/file/list.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import { SYSTEM_FILES_TO_IGNORE } from '@lobechat/file-loaders';
import type { FileEntry, ListFilesParams, ListFilesResult } from '../types';
+import { expandTilde } from './expandTilde';
export interface ListFilesOptions {
/** Whether to filter out system files like .DS_Store, Thumbs.db, etc. */
@@ -11,10 +12,11 @@ export interface ListFilesOptions {
}
export async function listLocalFiles(
- { path: dirPath, sortBy = 'modifiedTime', sortOrder = 'desc', limit = 100 }: ListFilesParams,
+ { path: rawPath, sortBy = 'modifiedTime', sortOrder = 'desc', limit = 100 }: ListFilesParams,
options?: ListFilesOptions,
): Promise<ListFilesResult> {
const { ignoreSystemFiles = true } = options || {};
+ const dirPath = expandTilde(rawPath) ?? rawPath;
try {
const entries = await readdir(dirPath);
diff --git a/packages/local-file-shell/src/file/move.ts b/packages/local-file-shell/src/file/move.ts
index a486a3a9a3f..0f0bcbf124b 100644
--- a/packages/local-file-shell/src/file/move.ts
+++ b/packages/local-file-shell/src/file/move.ts
@@ -3,6 +3,7 @@ import { access, mkdir, rename } from 'node:fs/promises';
import path from 'node:path';
import type { MoveFileResultItem, MoveFilesParams } from '../types';
+import { expandTilde } from './expandTilde';
export async function moveLocalFiles({ items }: MoveFilesParams): Promise<MoveFileResultItem[]> {
const results: MoveFileResultItem[] = [];
@@ -12,7 +13,8 @@ export async function moveLocalFiles({ items }: MoveFilesParams): Promise<MoveFi
}
for (const item of items) {
- const { oldPath: sourcePath, newPath } = item;
+ const sourcePath = expandTilde(item.oldPath) ?? item.oldPath;
+ const newPath = expandTilde(item.newPath) ?? item.newPath;
const resultItem: MoveFileResultItem = {
newPath: undefined,
sourcePath,
diff --git a/packages/local-file-shell/src/file/read.ts b/packages/local-file-shell/src/file/read.ts
index 669396b611f..2b1e3a526ba 100644
--- a/packages/local-file-shell/src/file/read.ts
+++ b/packages/local-file-shell/src/file/read.ts
@@ -4,12 +4,14 @@ import path from 'node:path';
import { loadFile } from '@lobechat/file-loaders';
import type { ReadFileParams, ReadFileResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function readLocalFile({
- path: filePath,
+ path: rawPath,
loc,
fullContent,
}: ReadFileParams): Promise<ReadFileResult> {
+ const filePath = expandTilde(rawPath) ?? rawPath;
const effectiveLoc = fullContent ? undefined : (loc ?? [0, 200]);
try {
diff --git a/packages/local-file-shell/src/file/rename.ts b/packages/local-file-shell/src/file/rename.ts
index b80a063c5d5..e5aa1ba6f18 100644
--- a/packages/local-file-shell/src/file/rename.ts
+++ b/packages/local-file-shell/src/file/rename.ts
@@ -2,15 +2,18 @@ import { rename } from 'node:fs/promises';
import path from 'node:path';
import type { RenameFileParams, RenameFileResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function renameLocalFile({
- path: currentPath,
+ path: rawPath,
newName,
}: RenameFileParams): Promise<RenameFileResult> {
- if (!currentPath || !newName) {
+ if (!rawPath || !newName) {
return { error: 'Both path and newName are required.', newPath: '', success: false };
}
+ const currentPath = expandTilde(rawPath) ?? rawPath;
+
// Prevent path traversal or invalid characters
if (
newName.includes('/') ||
diff --git a/packages/local-file-shell/src/file/search.ts b/packages/local-file-shell/src/file/search.ts
index 46f5f49d9ae..93c2c8aa4bf 100644
--- a/packages/local-file-shell/src/file/search.ts
+++ b/packages/local-file-shell/src/file/search.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import fg from 'fast-glob';
import type { SearchFilesParams, SearchFilesResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function searchLocalFiles({
keywords,
@@ -12,7 +13,7 @@ export async function searchLocalFiles({
limit = 30,
}: SearchFilesParams): Promise<SearchFilesResult[]> {
try {
- const cwd = directory || process.cwd();
+ const cwd = expandTilde(directory) || process.cwd();
const files = await fg(`**/*${keywords}*`, {
cwd,
dot: false,
diff --git a/packages/local-file-shell/src/file/write.ts b/packages/local-file-shell/src/file/write.ts
index 9ecda7b0e4d..9d484e155a3 100644
--- a/packages/local-file-shell/src/file/write.ts
+++ b/packages/local-file-shell/src/file/write.ts
@@ -2,14 +2,17 @@ import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { WriteFileParams, WriteFileResult } from '../types';
+import { expandTilde } from './expandTilde';
export async function writeLocalFile({
- path: filePath,
+ path: rawPath,
content,
}: WriteFileParams): Promise<WriteFileResult> {
- if (!filePath) return { error: 'Path cannot be empty', success: false };
+ if (!rawPath) return { error: 'Path cannot be empty', success: false };
if (content === undefined) return { error: 'Content cannot be empty', success: false };
+ const filePath = expandTilde(rawPath) ?? rawPath;
+
try {
const dirname = path.dirname(filePath);
await mkdir(dirname, { recursive: true });
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index 4e7b3f0db8e..29c24eb52bc 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -25,6 +25,10 @@ export async function runCommand(
}: RunCommandParams,
{ processManager, logger }: RunCommandOptions,
): Promise<RunCommandResult> {
+ if (!command) {
+ return { error: 'command is required', success: false };
+ }
+
const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;
logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 55fc2b31e52..1992b9bf4c1 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -36,11 +36,25 @@ export interface EditFileParams {
}
export interface SearchFilesParams {
+ contentContains?: string;
+ createdAfter?: string;
+ createdBefore?: string;
+ detailed?: boolean;
directory: string;
+ exclude?: string[];
+ /** @deprecated Prefer `fileTypes` (plural). Retained for cloud sandbox back-compat. */
fileType?: string;
+ fileTypes?: string[];
+ /** @deprecated Prefer `keywords` (plural). Retained for cloud sandbox back-compat. */
keyword?: string;
+ keywords?: string;
+ limit?: number;
+ liveUpdate?: boolean;
modifiedAfter?: string;
modifiedBefore?: string;
+ scope?: string;
+ sortBy?: 'name' | 'date' | 'size';
+ sortDirection?: 'asc' | 'desc';
}
export interface MoveFilesParams {
diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.ts
index bba9aa68bc0..9aedd53c37f 100644
--- a/src/locales/default/tool.ts
+++ b/src/locales/default/tool.ts
@@ -109,6 +109,7 @@ export default {
'localFiles.grepContent.glob': 'File filter',
'localFiles.grepContent.pattern': 'Search pattern',
'localFiles.grepContent.type': 'File type',
+ 'localFiles.listFiles.emptyDirectory': 'This directory is empty',
'localFiles.moveFiles.itemsMoved': '{{count}} item(s) moved:',
'localFiles.moveFiles.itemsMoved_one': '{{count}} item moved:',
'localFiles.moveFiles.itemsMoved_other': '{{count}} items moved:',
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
index e4294436658..6c7a18c0411 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.desktop.ts
@@ -20,7 +20,12 @@ const runtime = new SkillsExecutionRuntime({
const cwd = await desktopSkillRuntimeService.resolveExecutionDirectory(
options.activatedSkills,
);
- const result = await localFileService.runCommand({ command, cwd, timeout: undefined });
+ const result = await localFileService.runCommand({
+ command,
+ cwd,
+ description: options.description,
+ timeout: undefined,
+ });
return {
exitCode: result.exit_code ?? 1,
output: result.stdout || result.output || '',