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.

♻️ refactor(local-file-shell): sink desktop search modules into shared package (#14972)

Arvin Xu1a340deb75ac
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index a3e9b39a707..43c995d5e4c 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -43,17 +43,18 @@ import {
import {
editLocalFile,
expandTilde,
+ type FileResult,
listLocalFiles,
moveLocalFiles,
readLocalFile,
renameLocalFile,
+ type SearchOptions,
writeLocalFile,
} from '@lobechat/local-file-shell';
import { dialog, shell } from 'electron';
import { execa } from 'execa';
import { unzipSync } from 'fflate';
-import { type FileResult, type SearchOptions } from '@/modules/fileSearch';
import ContentSearchService from '@/services/contentSearchSrv';
import FileSearchService from '@/services/fileSearchSrv';
import { createLogger } from '@/utils/logger';
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/linux.ts b/apps/desktop/src/main/modules/fileSearch/impl/linux.ts
deleted file mode 100644
index 5844bf7aa55..00000000000
--- a/apps/desktop/src/main/modules/fileSearch/impl/linux.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
-import type { FileResult, SearchOptions } from '../types';
-import type { UnixSearchTool } from './unix';
-import { UnixFileSearch } from './unix';
-
-const logger = createLogger('module:FileSearch:linux');
-
-/**
- * Linux file search implementation
- * Uses fd > find > fast-glob fallback strategy
- */
-export class LinuxSearchServiceImpl extends UnixFileSearch {
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
- }
-
- /**
- * Perform file search
- * @param options Search options
- * @returns Promise of search result list
- */
- async search(options: SearchOptions): Promise<FileResult[]> {
- // Determine the best available tool on first search
- if (this.currentTool === null) {
- this.currentTool = await this.determineBestUnixTool();
- logger.info(`Using file search tool: ${this.currentTool}`);
- }
-
- return this.searchWithUnixTool(this.currentTool as UnixSearchTool, options);
- }
-
- /**
- * Check search service status
- * @returns Promise indicating if service is available (always true for Linux)
- */
- async checkSearchServiceStatus(): Promise<boolean> {
- // At minimum, fast-glob is always available
- return true;
- }
-
- /**
- * Update search index
- * Linux doesn't have a system-wide search index like Spotlight
- * @returns Promise indicating operation result (always false for Linux)
- */
- async updateSearchIndex(): Promise<boolean> {
- logger.warn('updateSearchIndex is not supported on Linux (no system-wide index)');
- return false;
- }
-}
diff --git a/apps/desktop/src/main/modules/fileSearch/index.ts b/apps/desktop/src/main/modules/fileSearch/index.ts
deleted file mode 100644
index 39bfef06ffe..00000000000
--- a/apps/desktop/src/main/modules/fileSearch/index.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { platform } from 'node:os';
-
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-
-import { LinuxSearchServiceImpl } from './impl/linux';
-import { MacOSSearchServiceImpl } from './impl/macOS';
-import { WindowsSearchServiceImpl } from './impl/windows';
-
-export { BaseFileSearch } from './base';
-export type { FileResult, SearchOptions } from './types';
-
-export const createFileSearchModule = (toolDetectorManager?: ToolDetectorManager) => {
- const currentPlatform = platform();
-
- switch (currentPlatform) {
- case 'darwin': {
- return new MacOSSearchServiceImpl(toolDetectorManager);
- }
- case 'win32': {
- return new WindowsSearchServiceImpl(toolDetectorManager);
- }
- case 'linux': {
- return new LinuxSearchServiceImpl(toolDetectorManager);
- }
- default: {
- // Fallback to Linux implementation (uses fast-glob, no external dependencies)
- console.warn(`Unsupported platform: ${currentPlatform}, using Linux fallback`);
- return new LinuxSearchServiceImpl(toolDetectorManager);
- }
- }
-};
diff --git a/apps/desktop/src/main/modules/fileSearch/types.ts b/apps/desktop/src/main/modules/fileSearch/types.ts
deleted file mode 100644
index addff5ee75f..00000000000
--- a/apps/desktop/src/main/modules/fileSearch/types.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-export interface FileResult {
- contentType?: string;
- createdTime: Date;
- // Search engine used to find this file (e.g., 'mdfind', 'fd', 'find', 'fast-glob')
- engine?: string;
- isDirectory: boolean;
- lastAccessTime: Date;
- // Spotlight specific metadata
- metadata?: {
- [key: string]: any;
- };
- modifiedTime: Date;
- name: string;
- path: string;
- size: number;
- type: string;
-}
-
-export interface SearchOptions {
- // Directory options
- // Content options
- contentContains?: string;
- // Created after specific date
- createdAfter?: Date;
-
- // Created before specific date
- createdBefore?: Date;
- // Whether to return detailed results
- detailed?: boolean;
-
- // Limit search to specific directories
- exclude?: string[]; // Files containing specific content
-
- // File type options
- fileTypes?: string[];
-
- // Basic options
- keywords: string;
- limit?: number;
- // Created before specific date
- // Advanced options
- liveUpdate?: boolean;
- // File type filters, like "public.image", "public.movie"
- // Time options
- modifiedAfter?: Date;
-
- // Modified after specific date
- modifiedBefore?: Date;
- // Path options
- onlyIn?: string; // Whether to return detailed metadata
- sortBy?: 'name' | 'date' | 'size'; // Result sorting
- sortDirection?: 'asc' | 'desc'; // Sort direction
-}
diff --git a/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts b/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
index 910b79261d3..2f6999da7d8 100644
--- a/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
@@ -1,12 +1,12 @@
+import type { FileResult, SearchOptions } from '@lobechat/local-file-shell';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
-import type { FileResult, SearchOptions } from '@/modules/fileSearch';
import FileSearchService from '../fileSearchSrv';
// Mock the fileSearch module
-vi.mock('@/modules/fileSearch', () => {
+vi.mock('@lobechat/local-file-shell', () => {
const MockFileSearchImpl = vi.fn().mockImplementation(() => ({
search: vi.fn(),
checkSearchServiceStatus: vi.fn(),
diff --git a/apps/desktop/src/main/services/contentSearchSrv.ts b/apps/desktop/src/main/services/contentSearchSrv.ts
index 87baebd04cf..8f9d5b2aa10 100644
--- a/apps/desktop/src/main/services/contentSearchSrv.ts
+++ b/apps/desktop/src/main/services/contentSearchSrv.ts
@@ -1,31 +1,31 @@
-import type { GrepContentParams, GrepContentResult } from '@lobechat/electron-client-ipc';
-
-import type { BaseContentSearch} from '@/modules/contentSearch';
-import { createContentSearchImpl } from '@/modules/contentSearch';
+import {
+ type BaseContentSearch,
+ createContentSearchImpl,
+ type GrepContentParams,
+ type GrepContentResult,
+} from '@lobechat/local-file-shell';
import { ServiceModule } from './index';
/**
* Content Search Service
* Provides content search functionality using platform-specific implementations
+ * sunk into the shared `@lobechat/local-file-shell` package.
*/
export default class ContentSearchService extends ServiceModule {
private impl: BaseContentSearch = createContentSearchImpl();
- /**
- * Perform content search (grep)
- */
async grep(params: GrepContentParams): Promise<GrepContentResult> {
- // Ensure toolDetectorManager is set
+ // Lazily wire the desktop ToolDetectorManager so we don't hit the
+ // class-field init-before-super-constructor gotcha. The manager already
+ // satisfies the minimal `ToolDetector` contract (only `getBestTool` is
+ // consumed by the search impls).
if (this.app?.toolDetectorManager) {
- this.impl.setToolDetectorManager(this.app.toolDetectorManager);
+ this.impl.setToolDetector(this.app.toolDetectorManager);
}
return this.impl.grep(params);
}
- /**
- * Check if a specific tool is available
- */
async checkToolAvailable(tool: string): Promise<boolean> {
return this.impl.checkToolAvailable(tool);
}
diff --git a/apps/desktop/src/main/services/fileSearchSrv.ts b/apps/desktop/src/main/services/fileSearchSrv.ts
index 51dc397d358..c8e84b0f7ca 100644
--- a/apps/desktop/src/main/services/fileSearchSrv.ts
+++ b/apps/desktop/src/main/services/fileSearchSrv.ts
@@ -1,54 +1,44 @@
-import type { GlobFilesParams, GlobFilesResult } from '@lobechat/electron-client-ipc';
-
-import type {
- BaseFileSearch,
- FileResult,
- SearchOptions} from '@/modules/fileSearch';
import {
- createFileSearchModule
-} from '@/modules/fileSearch';
+ type BaseFileSearch,
+ createFileSearchModule,
+ type FileResult,
+ type GlobFilesParams,
+ type GlobFilesResult,
+ type SearchOptions,
+} from '@lobechat/local-file-shell';
import { ServiceModule } from './index';
/**
* File Search Service
- * Main service class that uses platform-specific implementations internally
+ * Main service class that delegates to platform-specific implementations from
+ * `@lobechat/local-file-shell`.
*/
export default class FileSearchService extends ServiceModule {
private impl: BaseFileSearch = createFileSearchModule();
- /**
- * Perform file search
- */
async search(
query: string,
options: Omit<SearchOptions, 'keywords'> = {},
): Promise<FileResult[]> {
+ if (this.app?.toolDetectorManager) {
+ this.impl.setToolDetector(this.app.toolDetectorManager);
+ }
return this.impl.search({ ...options, keywords: query });
}
- /**
- * Check search service status
- */
async checkSearchServiceStatus(): Promise<boolean> {
return this.impl.checkSearchServiceStatus();
}
- /**
- * Update search index
- * @param path Optional specified path
- * @returns Promise indicating operation success
- */
async updateSearchIndex(path?: string): Promise<boolean> {
return this.impl.updateSearchIndex(path);
}
- /**
- * Perform glob pattern matching
- * @param params Glob parameters
- * @returns Promise of glob result
- */
async glob(params: GlobFilesParams): Promise<GlobFilesResult> {
+ if (this.app?.toolDetectorManager) {
+ this.impl.setToolDetector(this.app.toolDetectorManager);
+ }
return this.impl.glob(params);
}
}
diff --git a/apps/desktop/src/main/utils/logger.ts b/apps/desktop/src/main/utils/logger.ts
index 000a9c722af..59f41cc2af8 100644
--- a/apps/desktop/src/main/utils/logger.ts
+++ b/apps/desktop/src/main/utils/logger.ts
@@ -1,3 +1,4 @@
+import { setLoggerFactory } from '@lobechat/local-file-shell';
import debug from 'debug';
import electronLog from 'electron-log';
@@ -46,3 +47,9 @@ export const createLogger = (namespace: string) => {
},
};
};
+
+// Route @lobechat/local-file-shell logs through desktop's electron-log +
+// debug pipeline so search failures from the sunk contentSearch / fileSearch
+// modules land in the same production log file users attach for support
+// (regression introduced when the modules moved out of the desktop tree).
+setLoggerFactory(createLogger);
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 11071adfeec..62a0cf6eb52 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -254,7 +254,10 @@ export interface KillCommandResult {
success: boolean;
}
-// Grep types
+// Grep types — declared locally to keep this package leaf-only (no reverse
+// dependency on `@lobechat/local-file-shell`). The shape mirrors the
+// definition in `local-file-shell/types`; the two must stay in sync, but
+// they're structurally compatible by design.
export interface GrepContentParams {
'-A'?: number;
'-B'?: number;
@@ -264,14 +267,14 @@ export interface GrepContentParams {
'glob'?: string;
'head_limit'?: number;
'multiline'?: boolean;
- 'output_mode'?: 'content' | 'files_with_matches' | 'count';
+ 'output_mode'?: 'content' | 'count' | 'files_with_matches';
/** Legacy alias for `scope`. Takes precedence when set; prefer `scope` (the manifest-documented name) for new callers. */
'path'?: string;
'pattern': string;
/** Working directory scope. Limits the search to this directory. Defaults to `process.cwd()`. */
'scope'?: string;
/** Preferred search tool: 'rg' | 'ag' | 'grep' */
- 'tool'?: 'rg' | 'ag' | 'grep';
+ 'tool'?: 'ag' | 'grep' | 'rg';
'type'?: string;
}
@@ -284,7 +287,7 @@ export interface GrepContentResult {
total_matches: number;
}
-// Glob types
+// Glob types — same rationale as Grep above.
export interface GlobFilesParams {
pattern: string;
/** Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory. */
diff --git a/packages/local-file-shell/package.json b/packages/local-file-shell/package.json
index 8918d28f13c..1797495c92d 100644
--- a/packages/local-file-shell/package.json
+++ b/packages/local-file-shell/package.json
@@ -7,7 +7,12 @@
"types": "./src/index.ts",
"dependencies": {
"@lobechat/file-loaders": "workspace:*",
+ "debug": "^4.4.3",
"diff": "^8.0.2",
+ "execa": "^9.6.1",
"fast-glob": "^3.3.3"
+ },
+ "devDependencies": {
+ "@types/debug": "^4.1.12"
}
}
diff --git a/packages/local-file-shell/src/__tests__/logger.test.ts b/packages/local-file-shell/src/__tests__/logger.test.ts
new file mode 100644
index 00000000000..f281846f3c7
--- /dev/null
+++ b/packages/local-file-shell/src/__tests__/logger.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createDefaultLogger, createLogger, setLoggerFactory } from '../logger';
+
+describe('logger', () => {
+ afterEach(() => {
+ // Restore default factory so other tests aren't poisoned.
+ setLoggerFactory(createDefaultLogger);
+ });
+
+ it('routes calls through the current factory at call time, not creation time', () => {
+ // Module-level pattern: a long-lived logger is created BEFORE the host
+ // (e.g. desktop) gets a chance to install its own factory. The proxy must
+ // still pick up the override on subsequent method calls.
+ const logger = createLogger('contentSearch:base');
+
+ const earlyFactory = vi.fn((ns: string) => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }));
+ setLoggerFactory(earlyFactory);
+
+ logger.warn('first');
+ expect(earlyFactory).toHaveBeenCalledWith('contentSearch:base');
+
+ // Now the desktop bootstrap fires and swaps the factory. The pre-existing
+ // `logger` reference must start dispatching to the new factory.
+ const desktopWarn = vi.fn();
+ const desktopFactory = vi.fn(() => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: desktopWarn,
+ }));
+ setLoggerFactory(desktopFactory);
+
+ logger.warn('second');
+ expect(desktopFactory).toHaveBeenCalledWith('contentSearch:base');
+ expect(desktopWarn).toHaveBeenCalledWith('second');
+ });
+
+ it('caches the concrete logger per namespace within one factory generation', () => {
+ const factory = vi.fn((ns: string) => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }));
+ setLoggerFactory(factory);
+
+ const logger = createLogger('contentSearch:unix');
+ logger.warn('a');
+ logger.warn('b');
+ logger.error('c');
+
+ // Three method calls on one namespace should only construct one underlying logger.
+ expect(factory).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/modules/contentSearch/__tests__/base.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/base.test.ts
similarity index 96%
rename from apps/desktop/src/main/modules/contentSearch/__tests__/base.test.ts
rename to packages/local-file-shell/src/contentSearch/__tests__/base.test.ts
index 24562f089ab..96ddb6f20c1 100644
--- a/apps/desktop/src/main/modules/contentSearch/__tests__/base.test.ts
+++ b/packages/local-file-shell/src/contentSearch/__tests__/base.test.ts
@@ -1,10 +1,10 @@
-import type { GrepContentParams, GrepContentResult } from '@lobechat/electron-client-ipc';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { GrepContentParams, GrepContentResult } from '../../types';
import { BaseContentSearch } from '../base';
// Mock logger
-vi.mock('@/utils/logger', () => ({
+vi.mock('../../logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
@@ -344,13 +344,13 @@ describe('BaseContentSearch', () => {
});
});
- describe('setToolDetectorManager', () => {
+ describe('setToolDetector', () => {
it('should set the tool detector manager', () => {
const mockManager = {} as any;
- contentSearch.setToolDetectorManager(mockManager);
+ contentSearch.setToolDetector(mockManager);
- expect((contentSearch as any).toolDetectorManager).toBe(mockManager);
+ expect((contentSearch as any).toolDetector).toBe(mockManager);
});
});
});
diff --git a/apps/desktop/src/main/modules/contentSearch/__tests__/index.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/index.test.ts
similarity index 85%
rename from apps/desktop/src/main/modules/contentSearch/__tests__/index.test.ts
rename to packages/local-file-shell/src/contentSearch/__tests__/index.test.ts
index 43d6fcc50b0..2777e5ba809 100644
--- a/apps/desktop/src/main/modules/contentSearch/__tests__/index.test.ts
+++ b/packages/local-file-shell/src/contentSearch/__tests__/index.test.ts
@@ -13,7 +13,7 @@ vi.mock('node:os', () => ({
}));
// Mock logger
-vi.mock('@/utils/logger', () => ({
+vi.mock('../../logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
@@ -55,12 +55,12 @@ describe('createContentSearchImpl', () => {
expect(impl).toBeInstanceOf(LinuxContentSearchImpl);
});
- it('should pass toolDetectorManager to implementation', () => {
+ it('should pass toolDetector to implementation', () => {
vi.mocked(os.platform).mockReturnValue('linux');
- const mockManager = {} as any;
+ const mockDetector = { getBestTool: async () => null } as any;
- const impl = createContentSearchImpl(mockManager);
+ const impl = createContentSearchImpl(mockDetector);
- expect((impl as any).toolDetectorManager).toBe(mockManager);
+ expect((impl as any).toolDetector).toBe(mockDetector);
});
});
diff --git a/apps/desktop/src/main/modules/contentSearch/base.ts b/packages/local-file-shell/src/contentSearch/base.ts
similarity index 80%
rename from apps/desktop/src/main/modules/contentSearch/base.ts
rename to packages/local-file-shell/src/contentSearch/base.ts
index 00326f76c50..327749a4bda 100644
--- a/apps/desktop/src/main/modules/contentSearch/base.ts
+++ b/packages/local-file-shell/src/contentSearch/base.ts
@@ -1,67 +1,54 @@
import { readFile, stat } from 'node:fs/promises';
-import type { GrepContentParams, GrepContentResult } from '@lobechat/electron-client-ipc';
import fg from 'fast-glob';
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
+import { createLogger } from '../logger';
+import type { ToolDetector } from '../toolDetector';
+import type { GrepContentParams, GrepContentResult } from '../types';
-const logger = createLogger('module:ContentSearch:base');
+const logger = createLogger('contentSearch:base');
/**
* Content search tool type
*/
-export type ContentSearchTool = 'rg' | 'ag' | 'grep' | 'nodejs';
+export type ContentSearchTool = 'ag' | 'grep' | 'nodejs' | 'rg';
/**
* Content Search Service Implementation Abstract Class
* Defines the interface that different platform content search implementations need to implement
*/
export abstract class BaseContentSearch {
- protected toolDetectorManager?: ToolDetectorManager;
+ protected toolDetector?: ToolDetector;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- this.toolDetectorManager = toolDetectorManager;
+ constructor(toolDetector?: ToolDetector) {
+ this.toolDetector = toolDetector;
}
- /**
- * Set the tool detector manager
- * @param manager ToolDetectorManager instance
- */
- setToolDetectorManager(manager: ToolDetectorManager): void {
- this.toolDetectorManager = manager;
+ setToolDetector(detector: ToolDetector): void {
+ this.toolDetector = detector;
}
- /**
- * Perform content search (grep)
- * @param params Grep parameters
- * @returns Promise of grep result
- */
abstract grep(params: GrepContentParams): Promise<GrepContentResult>;
- /**
- * Check if a specific tool is available
- * @param tool Tool name to check
- * @returns Promise indicating if tool is available
- */
abstract checkToolAvailable(tool: string): Promise<boolean>;
/**
* Resolve the directory to run the search in.
*
- * The builtin-tool manifest documents `scope`, while the legacy IPC type also accepts
- * `path`. Read both so an agent calling with `scope` (per the manifest) doesn't silently
- * fall through to `process.cwd()` — which in a packaged Electron app isn't the project
- * root and therefore has no `.gitignore` for ripgrep to honor.
+ * The builtin-tool manifest documents `scope`, while the legacy type also accepts
+ * `path` / `cwd`. Read all so an agent calling with `scope` (per the manifest)
+ * doesn't silently fall through to `process.cwd()` — which in a packaged
+ * Electron app isn't the project root and therefore has no `.gitignore` for
+ * ripgrep to honor.
*/
protected resolveSearchPath(params: GrepContentParams): string {
- return params.path ?? params.scope ?? process.cwd();
+ return params.path ?? params.scope ?? params.cwd ?? process.cwd();
}
/**
* Build command-line arguments for grep tools
*/
- protected buildGrepArgs(tool: 'rg' | 'ag' | 'grep', params: GrepContentParams): string[] {
+ protected buildGrepArgs(tool: 'ag' | 'grep' | 'rg', params: GrepContentParams): string[] {
const { pattern, output_mode = 'files_with_matches' } = params;
const args: string[] = [];
@@ -73,7 +60,6 @@ export abstract class BaseContentSearch {
switch (tool) {
case 'rg': {
- // ripgrep arguments
if (params['-i']) args.push('-i');
if (params['-n']) args.push('-n');
if (params['-A']) args.push('-A', String(params['-A']));
@@ -84,7 +70,6 @@ export abstract class BaseContentSearch {
if (params.glob) args.push('-g', params.glob);
if (params.type) args.push('-t', params.type);
- // Output mode
switch (output_mode) {
case 'files_with_matches': {
args.push('-l');
@@ -96,13 +81,11 @@ export abstract class BaseContentSearch {
}
}
- // Ignore common directories (use **/ prefix to match nested paths)
args.push('--glob', '!**/node_modules/**', '--glob', '!**/.git/**', pattern, '.');
break;
}
case 'ag': {
- // Silver Searcher arguments
if (params['-i']) args.push('-i');
if (params['-A']) args.push('-A', String(params['-A']));
if (params['-B']) args.push('-B', String(params['-B']));
@@ -110,7 +93,6 @@ export abstract class BaseContentSearch {
if (wantsHidden) args.push('--hidden');
if (params.glob) args.push('-G', params.glob);
- // Output mode
switch (output_mode) {
case 'files_with_matches': {
args.push('-l');
@@ -127,8 +109,7 @@ export abstract class BaseContentSearch {
}
case 'grep': {
- // GNU grep arguments
- args.push('-r'); // recursive
+ args.push('-r');
if (params['-i']) args.push('-i');
if (params['-n']) args.push('-n');
if (params['-A']) args.push('-A', String(params['-A']));
@@ -137,7 +118,6 @@ export abstract class BaseContentSearch {
if (params.glob) args.push('--include', params.glob);
if (params.type) args.push('--include', `*.${params.type}`);
- // Output mode
switch (output_mode) {
case 'files_with_matches': {
args.push('-l');
@@ -168,14 +148,12 @@ export abstract class BaseContentSearch {
const flags = `${params['-i'] ? 'i' : ''}${params.multiline ? 's' : ''}`;
const regex = new RegExp(pattern, flags);
- // Determine files to search
let filesToSearch: string[];
const stats = await stat(searchPath);
if (stats.isFile()) {
filesToSearch = [searchPath];
} else {
- // Use glob pattern if provided, otherwise search all files
let globPattern = params.glob || '**/*';
if (params.glob && !params.glob.includes('/') && !params.glob.startsWith('**')) {
globPattern = `**/${params.glob}`;
@@ -188,7 +166,6 @@ export abstract class BaseContentSearch {
ignore: this.getDefaultIgnorePatterns(),
});
- // Filter by type if provided
if (params.type) {
const ext = `.${params.type}`;
filesToSearch = filesToSearch.filter((file) => file.endsWith(ext));
diff --git a/apps/desktop/src/main/modules/contentSearch/impl/linux.ts b/packages/local-file-shell/src/contentSearch/impl/linux.ts
similarity index 56%
rename from apps/desktop/src/main/modules/contentSearch/impl/linux.ts
rename to packages/local-file-shell/src/contentSearch/impl/linux.ts
index 5f41ebf4ca3..d205499c0ad 100644
--- a/apps/desktop/src/main/modules/contentSearch/impl/linux.ts
+++ b/packages/local-file-shell/src/contentSearch/impl/linux.ts
@@ -1,23 +1,19 @@
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
+import { createLogger } from '../../logger';
+import type { ToolDetector } from '../../toolDetector';
import { UnixContentSearch } from './unix';
-const logger = createLogger('module:ContentSearch:linux');
+const logger = createLogger('contentSearch:linux');
/**
* Linux content search implementation
* Inherits from UnixContentSearch with Linux-specific optimizations
*/
export class LinuxContentSearchImpl extends UnixContentSearch {
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
logger.debug('LinuxContentSearchImpl initialized');
}
- /**
- * Get Linux-specific ignore patterns
- */
protected override getDefaultIgnorePatterns(): string[] {
return [...super.getDefaultIgnorePatterns(), '**/.cache/**', '**/snap/**'];
}
diff --git a/apps/desktop/src/main/modules/contentSearch/impl/macOS.ts b/packages/local-file-shell/src/contentSearch/impl/macOS.ts
similarity index 55%
rename from apps/desktop/src/main/modules/contentSearch/impl/macOS.ts
rename to packages/local-file-shell/src/contentSearch/impl/macOS.ts
index 4dcf5a52035..11748b8feab 100644
--- a/apps/desktop/src/main/modules/contentSearch/impl/macOS.ts
+++ b/packages/local-file-shell/src/contentSearch/impl/macOS.ts
@@ -1,24 +1,19 @@
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
+import { createLogger } from '../../logger';
+import type { ToolDetector } from '../../toolDetector';
import { UnixContentSearch } from './unix';
-const logger = createLogger('module:ContentSearch:macOS');
+const logger = createLogger('contentSearch:macOS');
/**
* macOS content search implementation
* Inherits from UnixContentSearch with macOS-specific optimizations
*/
export class MacOSContentSearchImpl extends UnixContentSearch {
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
logger.debug('MacOSContentSearchImpl initialized');
}
- /**
- * Get macOS-specific ignore patterns
- * Includes Library/Caches which is specific to macOS
- */
protected override getDefaultIgnorePatterns(): string[] {
return [
...super.getDefaultIgnorePatterns(),
diff --git a/apps/desktop/src/main/modules/contentSearch/impl/unix.ts b/packages/local-file-shell/src/contentSearch/impl/unix.ts
similarity index 75%
rename from apps/desktop/src/main/modules/contentSearch/impl/unix.ts
rename to packages/local-file-shell/src/contentSearch/impl/unix.ts
index 050fa0d746c..4833d0b3abe 100644
--- a/apps/desktop/src/main/modules/contentSearch/impl/unix.ts
+++ b/packages/local-file-shell/src/contentSearch/impl/unix.ts
@@ -1,38 +1,29 @@
-import type { GrepContentParams, GrepContentResult } from '@lobechat/electron-client-ipc';
import { execa } from 'execa';
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
+import { createLogger } from '../../logger';
+import type { ToolDetector } from '../../toolDetector';
+import type { GrepContentParams, GrepContentResult } from '../../types';
import { BaseContentSearch } from '../base';
-const logger = createLogger('module:ContentSearch:unix');
+const logger = createLogger('contentSearch:unix');
/**
* Unix content search tool type
* Priority: rg (1) > ag (2) > grep (3)
*/
-export type UnixContentSearchTool = 'rg' | 'ag' | 'grep' | 'nodejs';
+export type UnixContentSearchTool = 'ag' | 'grep' | 'nodejs' | 'rg';
/**
* Unix content search base class
* Provides common search implementations for macOS and Linux
*/
export abstract class UnixContentSearch extends BaseContentSearch {
- /**
- * Current tool being used
- */
protected currentTool: UnixContentSearchTool | null = null;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
}
- /**
- * Check if a tool is available using 'which' command
- * @param tool Tool name to check
- * @returns Promise indicating if tool is available
- */
async checkToolAvailable(tool: string): Promise<boolean> {
try {
await execa('which', [tool], { timeout: 3000 });
@@ -42,14 +33,9 @@ export abstract class UnixContentSearch extends BaseContentSearch {
}
}
- /**
- * Determine the best available Unix tool based on priority
- * Priority: rg > ag > grep > nodejs
- * @returns The best available tool
- */
protected async determineBestUnixTool(): Promise<UnixContentSearchTool> {
- if (this.toolDetectorManager) {
- const bestTool = await this.toolDetectorManager.getBestTool('content-search');
+ if (this.toolDetector) {
+ const bestTool = await this.toolDetector.getBestTool('content-search');
if (bestTool && ['rg', 'ag', 'grep'].includes(bestTool)) {
return bestTool as UnixContentSearchTool;
}
@@ -70,11 +56,6 @@ export abstract class UnixContentSearch extends BaseContentSearch {
return 'nodejs';
}
- /**
- * Fallback to the next available tool
- * @param currentTool Current tool that failed
- * @returns Next tool to try
- */
protected async fallbackToNextTool(
currentTool: UnixContentSearchTool,
): Promise<UnixContentSearchTool> {
@@ -84,7 +65,7 @@ export abstract class UnixContentSearch extends BaseContentSearch {
for (let i = currentIndex + 1; i < priority.length; i++) {
const nextTool = priority[i];
if (nextTool === 'nodejs') {
- return 'nodejs'; // Always available
+ return 'nodejs';
}
if (await this.checkToolAvailable(nextTool)) {
return nextTool;
@@ -94,21 +75,16 @@ export abstract class UnixContentSearch extends BaseContentSearch {
return 'nodejs';
}
- /**
- * Perform content search (grep)
- */
async grep(params: GrepContentParams): Promise<GrepContentResult> {
const { tool: preferredTool } = params;
const logPrefix = `[grepContent: ${params.pattern}]`;
try {
- // If user specified a grep tool, try to use it
if (preferredTool && ['rg', 'ag', 'grep'].includes(preferredTool)) {
logger.debug(`${logPrefix} Using preferred tool: ${preferredTool}`);
return this.grepWithTool(preferredTool as UnixContentSearchTool, params);
}
- // Determine the best available tool on first search
if (this.currentTool === null) {
this.currentTool = await this.determineBestUnixTool();
logger.info(`Using content search tool: ${this.currentTool}`);
@@ -127,9 +103,6 @@ export abstract class UnixContentSearch extends BaseContentSearch {
}
}
- /**
- * Search using the specified tool
- */
protected async grepWithTool(
tool: UnixContentSearchTool,
params: GrepContentParams,
@@ -150,32 +123,20 @@ export abstract class UnixContentSearch extends BaseContentSearch {
}
}
- /**
- * Grep using ripgrep (rg)
- */
protected async grepWithRipgrep(params: GrepContentParams): Promise<GrepContentResult> {
return this.grepWithExternalTool('rg', params);
}
- /**
- * Grep using The Silver Searcher (ag)
- */
protected async grepWithAg(params: GrepContentParams): Promise<GrepContentResult> {
return this.grepWithExternalTool('ag', params);
}
- /**
- * Grep using GNU grep
- */
protected async grepWithGrep(params: GrepContentParams): Promise<GrepContentResult> {
return this.grepWithExternalTool('grep', params);
}
- /**
- * Grep using external tools (rg, ag, grep)
- */
protected async grepWithExternalTool(
- tool: 'rg' | 'ag' | 'grep',
+ tool: 'ag' | 'grep' | 'rg',
params: GrepContentParams,
): Promise<GrepContentResult> {
const { output_mode = 'files_with_matches' } = params;
@@ -188,10 +149,9 @@ export abstract class UnixContentSearch extends BaseContentSearch {
const { stdout, stderr, exitCode } = await execa(tool, args, {
cwd: searchPath,
- reject: false, // Don't throw on non-zero exit code
+ reject: false,
});
- // ripgrep returns 1 when no matches found, which is not an error
if (exitCode !== 0 && exitCode !== 1 && stderr) {
logger.warn(`${logPrefix} Tool exited with code ${exitCode}: ${stderr}`);
}
@@ -208,11 +168,8 @@ export abstract class UnixContentSearch extends BaseContentSearch {
}
case 'content': {
matches = lines;
- // When context lines are used, lines.length includes context lines
- // We need to get the actual match count separately
const hasContext = params['-A'] || params['-B'] || params['-C'];
if (hasContext) {
- // Run a separate count query to get accurate match count
totalMatches = await this.getActualMatchCount(tool, params);
} else {
totalMatches = lines.length;
@@ -220,7 +177,6 @@ export abstract class UnixContentSearch extends BaseContentSearch {
break;
}
case 'count': {
- // Parse count output (file:count format)
for (const line of lines) {
const match = line.match(/:(\d+)$/);
if (match) {
@@ -232,7 +188,6 @@ export abstract class UnixContentSearch extends BaseContentSearch {
}
}
- // Apply head_limit
if (params.head_limit && matches.length > params.head_limit) {
matches = matches.slice(0, params.head_limit);
}
@@ -250,18 +205,14 @@ export abstract class UnixContentSearch extends BaseContentSearch {
};
} catch (error) {
logger.warn(`${logPrefix} External tool failed, falling back to next tool:`, error);
- // Fallback to next tool
this.currentTool = await this.fallbackToNextTool(tool as UnixContentSearchTool);
logger.info(`Falling back to: ${this.currentTool}`);
return this.grepWithTool(this.currentTool, params);
}
}
- /**
- * Get actual match count for content mode when context lines are used
- */
protected async getActualMatchCount(
- tool: 'rg' | 'ag' | 'grep',
+ tool: 'ag' | 'grep' | 'rg',
params: GrepContentParams,
): Promise<number> {
const countParams = { ...params, '-A': undefined, '-B': undefined, '-C': undefined };
diff --git a/apps/desktop/src/main/modules/contentSearch/impl/windows.ts b/packages/local-file-shell/src/contentSearch/impl/windows.ts
similarity index 79%
rename from apps/desktop/src/main/modules/contentSearch/impl/windows.ts
rename to packages/local-file-shell/src/contentSearch/impl/windows.ts
index 4551d865125..5a18d105540 100644
--- a/apps/desktop/src/main/modules/contentSearch/impl/windows.ts
+++ b/packages/local-file-shell/src/contentSearch/impl/windows.ts
@@ -1,39 +1,30 @@
-import type { GrepContentParams, GrepContentResult } from '@lobechat/electron-client-ipc';
import { execa } from 'execa';
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
+import { createLogger } from '../../logger';
+import type { ToolDetector } from '../../toolDetector';
+import type { GrepContentParams, GrepContentResult } from '../../types';
import { BaseContentSearch } from '../base';
-const logger = createLogger('module:ContentSearch:windows');
+const logger = createLogger('contentSearch:windows');
/**
* Windows content search tool type
* Priority: rg > findstr/powershell > nodejs
*/
-type WindowsContentSearchTool = 'rg' | 'findstr' | 'nodejs';
+type WindowsContentSearchTool = 'findstr' | 'nodejs' | 'rg';
/**
* Windows content search implementation
* Uses rg > findstr > nodejs fallback strategy
*/
export class WindowsContentSearchImpl extends BaseContentSearch {
- /**
- * Current tool being used
- */
private currentTool: WindowsContentSearchTool | null = null;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
logger.debug('WindowsContentSearchImpl initialized');
}
- /**
- * Check if a tool is available using 'where' command (Windows equivalent of 'which')
- * @param tool Tool name to check
- * @returns Promise indicating if tool is available
- */
async checkToolAvailable(tool: string): Promise<boolean> {
try {
await execa('where', [tool], { timeout: 3000 });
@@ -43,13 +34,9 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- /**
- * Determine the best available tool based on priority
- * Priority: rg > findstr > nodejs
- */
private async determineBestTool(): Promise<WindowsContentSearchTool> {
- if (this.toolDetectorManager) {
- const bestTool = await this.toolDetectorManager.getBestTool('content-search');
+ if (this.toolDetector) {
+ const bestTool = await this.toolDetector.getBestTool('content-search');
if (bestTool === 'rg') {
return 'rg';
}
@@ -63,9 +50,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
return 'findstr';
}
- /**
- * Fallback to the next available tool
- */
private async fallbackToNextTool(
currentTool: WindowsContentSearchTool,
): Promise<WindowsContentSearchTool> {
@@ -75,7 +59,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
for (let i = currentIndex + 1; i < priority.length; i++) {
const nextTool = priority[i];
if (nextTool === 'nodejs' || nextTool === 'findstr') {
- return nextTool; // Always available
+ return nextTool;
}
if (await this.checkToolAvailable(nextTool)) {
return nextTool;
@@ -85,15 +69,11 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
return 'nodejs';
}
- /**
- * Perform content search (grep)
- */
async grep(params: GrepContentParams): Promise<GrepContentResult> {
const { tool: preferredTool } = params;
const logPrefix = `[grepContent: ${params.pattern}]`;
try {
- // If user specified ripgrep, try to use it
if (preferredTool === 'rg') {
if (await this.checkToolAvailable('rg')) {
logger.debug(`${logPrefix} Using preferred tool: rg`);
@@ -102,7 +82,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
logger.warn(`${logPrefix} ripgrep (rg) not available, falling back to other tools`);
}
- // Determine the best available tool on first search
if (this.currentTool === null) {
this.currentTool = await this.determineBestTool();
logger.info(`Using content search tool: ${this.currentTool}`);
@@ -121,9 +100,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- /**
- * Search using the specified tool
- */
private async grepWithTool(
tool: WindowsContentSearchTool,
params: GrepContentParams,
@@ -141,9 +117,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- /**
- * Grep using ripgrep (rg) - cross-platform
- */
private async grepWithRipgrep(params: GrepContentParams): Promise<GrepContentResult> {
const { output_mode = 'files_with_matches' } = params;
const searchPath = this.resolveSearchPath(params);
@@ -158,7 +131,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
reject: false,
});
- // ripgrep returns 1 when no matches found, which is not an error
if (exitCode !== 0 && exitCode !== 1 && stderr) {
logger.warn(`${logPrefix} rg exited with code ${exitCode}: ${stderr}`);
}
@@ -195,7 +167,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- // Apply head_limit
if (params.head_limit && matches.length > params.head_limit) {
matches = matches.slice(0, params.head_limit);
}
@@ -218,9 +189,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- /**
- * Get actual match count using ripgrep
- */
private async getActualMatchCount(params: GrepContentParams): Promise<number> {
const countParams = { ...params, '-A': undefined, '-B': undefined, '-C': undefined };
const args = this.buildGrepArgs('rg', {
@@ -247,31 +215,25 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- /**
- * Grep using Windows findstr command
- * Note: findstr has limited functionality compared to ripgrep
- */
private async grepWithFindstr(params: GrepContentParams): Promise<GrepContentResult> {
const { pattern, output_mode = 'files_with_matches' } = params;
const searchPath = this.resolveSearchPath(params);
const logPrefix = `[grepContent:findstr]`;
try {
- const args: string[] = ['/S']; // Recursive search
+ const args: string[] = ['/S'];
if (params['-i']) {
- args.push('/I'); // Case insensitive
+ args.push('/I');
}
if (params['-n']) {
- args.push('/N'); // Line numbers
+ args.push('/N');
}
- // Pattern
- args.push('/R'); // Regex
+ args.push('/R');
args.push(`"${pattern}"`);
- // Search files pattern
const filePattern = params.glob || params.type ? `*.${params.type || '*'}` : '*.*';
args.push(filePattern);
@@ -282,7 +244,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
reject: false,
});
- // findstr returns 1 when no matches found
if (exitCode !== 0 && exitCode !== 1) {
logger.warn(`${logPrefix} findstr exited with code ${exitCode}`);
}
@@ -293,7 +254,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
switch (output_mode) {
case 'files_with_matches': {
- // Extract unique file names from output
const files = new Set<string>();
for (const line of lines) {
const match = line.match(/^([^:]+):/);
@@ -301,7 +261,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
files.add(match[1]);
}
}
- matches = Array.from(files);
+ matches = [...files];
totalMatches = matches.length;
break;
}
@@ -311,7 +271,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
break;
}
case 'count': {
- // Count matches per file
const fileCounts = new Map<string, number>();
for (const line of lines) {
const match = line.match(/^([^:]+):/);
@@ -319,13 +278,12 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
fileCounts.set(match[1], (fileCounts.get(match[1]) || 0) + 1);
}
}
- matches = Array.from(fileCounts.entries()).map(([file, count]) => `${file}:${count}`);
+ matches = [...fileCounts.entries()].map(([file, count]) => `${file}:${count}`);
totalMatches = lines.length;
break;
}
}
- // Apply head_limit
if (params.head_limit && matches.length > params.head_limit) {
matches = matches.slice(0, params.head_limit);
}
@@ -348,9 +306,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {
}
}
- /**
- * Get Windows-specific ignore patterns
- */
protected override getDefaultIgnorePatterns(): string[] {
return [
...super.getDefaultIgnorePatterns(),
diff --git a/apps/desktop/src/main/modules/contentSearch/index.ts b/packages/local-file-shell/src/contentSearch/index.ts
similarity index 56%
rename from apps/desktop/src/main/modules/contentSearch/index.ts
rename to packages/local-file-shell/src/contentSearch/index.ts
index 642cbe46016..84b7494db77 100644
--- a/apps/desktop/src/main/modules/contentSearch/index.ts
+++ b/packages/local-file-shell/src/contentSearch/index.ts
@@ -1,7 +1,6 @@
import * as os from 'node:os';
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-
+import type { ToolDetector } from '../toolDetector';
import type { BaseContentSearch } from './base';
import { LinuxContentSearchImpl } from './impl/linux';
import { MacOSContentSearchImpl } from './impl/macOS';
@@ -15,24 +14,19 @@ export { WindowsContentSearchImpl } from './impl/windows';
/**
* Create platform-specific content search implementation
- * @param toolDetectorManager Optional tool detector manager
- * @returns Platform-specific content search implementation
*/
-export function createContentSearchImpl(
- toolDetectorManager?: ToolDetectorManager,
-): BaseContentSearch {
+export function createContentSearchImpl(toolDetector?: ToolDetector): BaseContentSearch {
const platform = os.platform();
switch (platform) {
case 'darwin': {
- return new MacOSContentSearchImpl(toolDetectorManager);
+ return new MacOSContentSearchImpl(toolDetector);
}
case 'win32': {
- return new WindowsContentSearchImpl(toolDetectorManager);
+ return new WindowsContentSearchImpl(toolDetector);
}
default: {
- // Linux and other Unix-like systems
- return new LinuxContentSearchImpl(toolDetectorManager);
+ return new LinuxContentSearchImpl(toolDetector);
}
}
}
diff --git a/packages/local-file-shell/src/file/glob.ts b/packages/local-file-shell/src/file/glob.ts
index 13fa316b2eb..834471b0fdb 100644
--- a/packages/local-file-shell/src/file/glob.ts
+++ b/packages/local-file-shell/src/file/glob.ts
@@ -4,28 +4,45 @@ import type { GlobFilesParams, GlobFilesResult } from '../types';
import { expandTilde } from './expandTilde';
import { hasHiddenSegment } from './hasHiddenSegment';
-export async function globLocalFiles({ pattern, cwd }: GlobFilesParams): Promise<GlobFilesResult> {
+/**
+ * Lightweight glob — backed by `fast-glob` only. For the platform-aware
+ * version that prefers `fd` / `find` / `mdfind` when present, use
+ * `createFileSearchModule()` from `@lobechat/local-file-shell/fileSearch`.
+ */
+export async function globLocalFiles({
+ pattern,
+ cwd,
+ scope,
+}: GlobFilesParams): Promise<GlobFilesResult> {
try {
- // When the pattern explicitly references a dot-prefixed segment (e.g.
- // `.github/workflows/*.yml`), the caller clearly wants to traverse a
- // hidden directory — auto-enable hidden matching so it doesn't silently
- // return zero results.
const wantsHidden = hasHiddenSegment(pattern);
-
const files = await fg(pattern, {
- cwd: expandTilde(cwd) || process.cwd(),
+ cwd: expandTilde(scope ?? cwd) || process.cwd(),
dot: wantsHidden,
ignore: ['**/node_modules/**', '**/.git/**'],
});
+ const base: GlobFilesResult = {
+ engine: 'fast-glob',
+ files,
+ success: true,
+ total_files: files.length,
+ };
+
if (wantsHidden) {
return {
- files,
+ ...base,
hint: `Auto-enabled hidden-file matching because pattern contains a dot-prefixed segment.`,
};
}
- return { files };
+ return base;
} catch (error) {
- return { error: (error as Error).message, files: [] };
+ return {
+ engine: 'fast-glob',
+ error: (error as Error).message,
+ files: [],
+ success: false,
+ total_files: 0,
+ };
}
}
diff --git a/packages/local-file-shell/src/file/grep.ts b/packages/local-file-shell/src/file/grep.ts
index 5256a5db7e6..c77900c419a 100644
--- a/packages/local-file-shell/src/file/grep.ts
+++ b/packages/local-file-shell/src/file/grep.ts
@@ -4,15 +4,17 @@ import type { GrepContentParams, GrepContentResult } from '../types';
import { expandTilde } from './expandTilde';
import { hasHiddenSegment } from './hasHiddenSegment';
+/**
+ * Lightweight grep — spawns `rg` directly and returns the raw `--json`
+ * events. For the platform-aware fallback chain (rg → ag → grep → nodejs)
+ * with rich `output_mode` / `-A/-B/-C` support, use
+ * `createContentSearchImpl()` from `@lobechat/local-file-shell/contentSearch`.
+ */
export async function grepContent({
pattern,
cwd,
filePattern,
}: GrepContentParams): Promise<GrepContentResult> {
- // When the filePattern explicitly references a dot-prefixed segment, the
- // caller wants to scan inside a hidden directory — pass `--hidden` to rg so
- // it doesn't silently skip these paths. We still rely on rg's built-in
- // `.git/` exclusion via .gitignore semantics, plus add an explicit guard.
const wantsHidden = hasHiddenSegment(filePattern);
const hint = wantsHidden
? `Auto-enabled hidden-file matching because filePattern contains a dot-prefixed segment.`
@@ -38,7 +40,7 @@ export async function grepContent({
child.on('close', (code) => {
if (code !== 0 && code !== 1) {
- resolve({ hint, matches: [], success: false });
+ resolve({ engine: 'rg', hint, matches: [], success: false, total_matches: 0 });
return;
}
@@ -55,14 +57,20 @@ export async function grepContent({
})
.filter(Boolean);
- resolve({ hint, matches, success: true });
+ resolve({
+ engine: 'rg',
+ hint,
+ matches,
+ success: true,
+ total_matches: matches.length,
+ });
} catch {
- resolve({ hint, matches: [], success: true });
+ resolve({ engine: 'rg', hint, matches: [], success: true, total_matches: 0 });
}
});
child.on('error', () => {
- resolve({ hint, matches: [], success: false });
+ resolve({ engine: 'rg', hint, matches: [], success: false, total_matches: 0 });
});
});
}
diff --git a/packages/local-file-shell/src/file/search.ts b/packages/local-file-shell/src/file/search.ts
index d29a137a2a1..370e6450f17 100644
--- a/packages/local-file-shell/src/file/search.ts
+++ b/packages/local-file-shell/src/file/search.ts
@@ -6,14 +6,21 @@ import fg from 'fast-glob';
import type { SearchFilesParams, SearchFilesResult } from '../types';
import { expandTilde } from './expandTilde';
+/**
+ * Lightweight filename search — backed by `fast-glob` only. For the
+ * platform-aware version that prefers Spotlight (`mdfind`) on macOS and
+ * `fd` / `find` elsewhere, use `createFileSearchModule()` from
+ * `@lobechat/local-file-shell/fileSearch`.
+ */
export async function searchLocalFiles({
keywords,
directory,
+ onlyIn,
contentContains,
limit = 30,
}: SearchFilesParams): Promise<SearchFilesResult[]> {
try {
- const cwd = expandTilde(directory) || process.cwd();
+ const cwd = expandTilde(onlyIn ?? directory) || process.cwd();
// If the caller is searching for a dot-prefixed name (e.g. `.env`, `.github`),
// auto-enable hidden matching so the file/directory is actually reachable.
const wantsHidden = keywords.startsWith('.');
@@ -23,10 +30,13 @@ export async function searchLocalFiles({
ignore: ['**/node_modules/**', '**/.git/**'],
});
- let results = files.map((f) => ({ name: path.basename(f), path: path.join(cwd, f) }));
+ let results: SearchFilesResult[] = files.map((f) => ({
+ name: path.basename(f),
+ path: path.join(cwd, f),
+ }));
if (contentContains) {
- const filtered: typeof results = [];
+ const filtered: SearchFilesResult[] = [];
for (const file of results) {
try {
const content = await readFile(file.path, 'utf8');
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/base.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts
similarity index 96%
rename from apps/desktop/src/main/modules/fileSearch/__tests__/base.test.ts
rename to packages/local-file-shell/src/fileSearch/__tests__/base.test.ts
index 7963ce9711e..ca211018415 100644
--- a/apps/desktop/src/main/modules/fileSearch/__tests__/base.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/base.test.ts
@@ -1,11 +1,10 @@
-import type { GlobFilesParams, GlobFilesResult } from '@lobechat/electron-client-ipc';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { FileResult, GlobFilesParams, GlobFilesResult, SearchOptions } from '../../types';
import { BaseFileSearch } from '../base';
-import type { FileResult, SearchOptions } from '../types';
// Mock logger
-vi.mock('@/utils/logger', () => ({
+vi.mock('../../logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
@@ -279,13 +278,13 @@ describe('BaseFileSearch', () => {
});
});
- describe('setToolDetectorManager', () => {
+ describe('setToolDetector', () => {
it('should set the tool detector manager', () => {
const mockManager = {} as any;
- fileSearch.setToolDetectorManager(mockManager);
+ fileSearch.setToolDetector(mockManager);
- expect((fileSearch as any).toolDetectorManager).toBe(mockManager);
+ expect((fileSearch as any).toolDetector).toBe(mockManager);
});
});
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/index.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/index.test.ts
similarity index 85%
rename from apps/desktop/src/main/modules/fileSearch/__tests__/index.test.ts
rename to packages/local-file-shell/src/fileSearch/__tests__/index.test.ts
index d40cb37a35d..d30930a0de8 100644
--- a/apps/desktop/src/main/modules/fileSearch/__tests__/index.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/index.test.ts
@@ -14,7 +14,7 @@ vi.mock('node:os', () => ({
}));
// Mock logger
-vi.mock('@/utils/logger', () => ({
+vi.mock('../../logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
@@ -56,12 +56,12 @@ describe('createFileSearchModule', () => {
expect(impl).toBeInstanceOf(LinuxSearchServiceImpl);
});
- it('should pass toolDetectorManager to implementation', () => {
+ it('should pass toolDetector to implementation', () => {
vi.mocked(platform).mockReturnValue('linux');
- const mockManager = {} as any;
+ const mockDetector = { getBestTool: async () => null } as any;
- const impl = createFileSearchModule(mockManager);
+ const impl = createFileSearchModule(mockDetector);
- expect((impl as any).toolDetectorManager).toBe(mockManager);
+ expect((impl as any).toolDetector).toBe(mockDetector);
});
});
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/macOS.integration.test.ts
similarity index 99%
rename from apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts
rename to packages/local-file-shell/src/fileSearch/__tests__/macOS.integration.test.ts
index 89c0b710865..c2331b06e11 100644
--- a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.integration.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/macOS.integration.test.ts
@@ -20,14 +20,14 @@ describe.skipIf(process.platform !== 'darwin')('MacOSSearchServiceImpl Integrati
const searchService = new MacOSSearchServiceImpl();
const ensureResults = (results: unknown[], context: string) => {
if (results.length > 0) return true;
-
+
console.warn(`⚠️ Spotlight returned 0 results for ${context} - indexing may be incomplete`);
return false;
};
const ensureResultsOrSkipAssertions = (results: unknown[], hint: string) => {
if (results.length > 0) return true;
-
+
console.warn(
`⚠️ Spotlight returned 0 results for "${hint}". This usually means indexing is incomplete/disabled. Skipping strict assertions.`,
);
@@ -107,7 +107,6 @@ describe.skipIf(process.platform !== 'darwin')('MacOSSearchServiceImpl Integrati
expect(result.path).toContain('apps/desktop');
});
} else {
-
console.warn(
'⚠️ No results found in apps/desktop - Spotlight indexing may not be complete',
);
@@ -373,6 +372,5 @@ describe.skipIf(process.platform !== 'darwin')('MacOSSearchServiceImpl Integrati
// Skip message for non-macOS platforms
if (process.platform !== 'darwin') {
-
console.log('⏭️ Skipping macOS integration tests on', process.platform, '(only runs on darwin)');
}
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/macOS.test.ts
similarity index 98%
rename from apps/desktop/src/main/modules/fileSearch/__tests__/macOS.test.ts
rename to packages/local-file-shell/src/fileSearch/__tests__/macOS.test.ts
index 47ee1cd7b38..8ea7f33e6db 100644
--- a/apps/desktop/src/main/modules/fileSearch/__tests__/macOS.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/macOS.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { buildFilenameKeywordExpression } from '../impl/macOS';
-vi.mock('@/utils/logger', () => ({
+vi.mock('../../logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
diff --git a/apps/desktop/src/main/modules/fileSearch/__tests__/unix.test.ts b/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
similarity index 98%
rename from apps/desktop/src/main/modules/fileSearch/__tests__/unix.test.ts
rename to packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
index 5bb5fcdaab4..b811378139a 100644
--- a/apps/desktop/src/main/modules/fileSearch/__tests__/unix.test.ts
+++ b/packages/local-file-shell/src/fileSearch/__tests__/unix.test.ts
@@ -7,7 +7,7 @@ vi.mock('node:os', () => ({
platform: vi.fn().mockReturnValue('linux'),
}));
-vi.mock('@/utils/logger', () => ({
+vi.mock('../../logger', () => ({
createLogger: () => ({
debug: vi.fn(),
error: vi.fn(),
diff --git a/apps/desktop/src/main/modules/fileSearch/base.ts b/packages/local-file-shell/src/fileSearch/base.ts
similarity index 64%
rename from apps/desktop/src/main/modules/fileSearch/base.ts
rename to packages/local-file-shell/src/fileSearch/base.ts
index ee3d90970a5..d201d0ea9ed 100644
--- a/apps/desktop/src/main/modules/fileSearch/base.ts
+++ b/packages/local-file-shell/src/fileSearch/base.ts
@@ -1,79 +1,67 @@
import { stat } from 'node:fs/promises';
import path from 'node:path';
-import type { GlobFilesParams, GlobFilesResult } from '@lobechat/electron-client-ipc';
-
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-
-import type { FileResult, SearchOptions } from './types';
+import type { ToolDetector } from '../toolDetector';
+import type { FileResult, GlobFilesParams, GlobFilesResult, SearchFilesParams } from '../types';
/**
* Content type mapping for common file extensions
*/
const CONTENT_TYPE_MAP: Record<string, string> = {
- // Archive
'7z': 'archive',
- 'gz': 'archive',
- 'rar': 'archive',
- 'tar': 'archive',
- 'zip': 'archive',
- // Audio
'aac': 'audio',
- 'mp3': 'audio',
- 'ogg': 'audio',
- 'wav': 'audio',
- // Video
+ 'app': 'application',
'avi': 'video',
- 'mkv': 'video',
- 'mov': 'video',
- 'mp4': 'video',
- // Image
- 'gif': 'image',
- 'heic': 'image',
- 'ico': 'image',
- 'jpeg': 'image',
- 'jpg': 'image',
- 'png': 'image',
- 'svg': 'image',
- 'webp': 'image',
- // Document
- 'doc': 'document',
- 'docx': 'document',
- 'pdf': 'document',
- 'rtf': 'text',
- 'txt': 'text',
- // Spreadsheet
- 'xls': 'spreadsheet',
- 'xlsx': 'spreadsheet',
- // Presentation
- 'ppt': 'presentation',
- 'pptx': 'presentation',
- // Code
'bat': 'code',
'c': 'code',
'cmd': 'code',
'cpp': 'code',
'cs': 'code',
'css': 'code',
+ 'deb': 'package',
+ 'dmg': 'disk-image',
+ 'doc': 'document',
+ 'docx': 'document',
+ 'exe': 'application',
+ 'gif': 'image',
+ 'gz': 'archive',
+ 'heic': 'image',
'html': 'code',
+ 'ico': 'image',
+ 'iso': 'disk-image',
'java': 'code',
+ 'jpeg': 'image',
+ 'jpg': 'image',
'js': 'code',
'json': 'code',
+ 'mkv': 'video',
+ 'mov': 'video',
+ 'mp3': 'audio',
+ 'mp4': 'video',
+ 'msi': 'installer',
+ 'ogg': 'audio',
+ 'pdf': 'document',
+ 'png': 'image',
+ 'ppt': 'presentation',
+ 'pptx': 'presentation',
'ps1': 'code',
'py': 'code',
+ 'rar': 'archive',
+ 'rpm': 'package',
+ 'rtf': 'text',
'sh': 'code',
+ 'svg': 'image',
'swift': 'code',
+ 'tar': 'archive',
'ts': 'code',
'tsx': 'code',
+ 'txt': 'text',
'vbs': 'code',
- // Application/Installer (platform-specific)
- 'app': 'application',
- 'deb': 'package',
- 'dmg': 'disk-image',
- 'exe': 'application',
- 'iso': 'disk-image',
- 'msi': 'installer',
- 'rpm': 'package',
+ 'wav': 'audio',
+ 'webp': 'image',
+ 'xls': 'spreadsheet',
+ 'xlsx': 'spreadsheet',
+ 'zip': 'archive',
};
/**
@@ -81,33 +69,22 @@ const CONTENT_TYPE_MAP: Record<string, string> = {
* Defines the interface that different platform file search implementations need to implement
*/
export abstract class BaseFileSearch {
- protected toolDetectorManager?: ToolDetectorManager;
+ protected toolDetector?: ToolDetector;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- this.toolDetectorManager = toolDetectorManager;
+ constructor(toolDetector?: ToolDetector) {
+ this.toolDetector = toolDetector;
}
- /**
- * Set the tool detector manager
- * @param manager ToolDetectorManager instance
- */
- setToolDetectorManager(manager: ToolDetectorManager): void {
- this.toolDetectorManager = manager;
+ setToolDetector(detector: ToolDetector): void {
+ this.toolDetector = detector;
}
- /**
- * Determine content type from file extension
- * @param extension File extension (without dot)
- * @returns Content type description
- */
protected determineContentType(extension: string): string {
return CONTENT_TYPE_MAP[extension.toLowerCase()] || 'unknown';
}
/**
* Escape special glob characters in the search pattern
- * @param pattern The pattern to escape
- * @returns Escaped pattern safe for glob matching
*/
protected escapeGlobPattern(pattern: string): string {
return pattern.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
@@ -115,14 +92,10 @@ export abstract class BaseFileSearch {
/**
* Process file paths and return FileResult objects
- * @param filePaths Array of file path strings
- * @param options Search options
- * @param engine Optional search engine identifier
- * @returns Formatted file result list
*/
protected async processFilePaths(
filePaths: string[],
- options: SearchOptions,
+ options: SearchFilesParams,
engine?: string,
): Promise<FileResult[]> {
const results: FileResult[] = [];
@@ -153,16 +126,9 @@ export abstract class BaseFileSearch {
return this.sortResults(results, options.sortBy, options.sortDirection);
}
- /**
- * Sort results based on options
- * @param results Result list
- * @param sortBy Sort field
- * @param direction Sort direction
- * @returns Sorted result list
- */
protected sortResults(
results: FileResult[],
- sortBy?: 'name' | 'date' | 'size',
+ sortBy?: 'date' | 'name' | 'size',
direction: 'asc' | 'desc' = 'asc',
): FileResult[] {
if (!sortBy) return results;
@@ -187,30 +153,11 @@ export abstract class BaseFileSearch {
});
}
- /**
- * Perform file search
- * @param options Search options
- * @returns Promise of search result list
- */
- abstract search(options: SearchOptions): Promise<FileResult[]>;
+ abstract search(options: SearchFilesParams): Promise<FileResult[]>;
- /**
- * Perform glob pattern matching
- * @param params Glob parameters
- * @returns Promise of glob result
- */
abstract glob(params: GlobFilesParams): Promise<GlobFilesResult>;
- /**
- * Check search service status
- * @returns Promise indicating if service is available
- */
abstract checkSearchServiceStatus(): Promise<boolean>;
- /**
- * Update search index
- * @param path Optional specified path
- * @returns Promise indicating operation success
- */
abstract updateSearchIndex(path?: string): Promise<boolean>;
}
diff --git a/packages/local-file-shell/src/fileSearch/impl/linux.ts b/packages/local-file-shell/src/fileSearch/impl/linux.ts
new file mode 100644
index 00000000000..5957bf85315
--- /dev/null
+++ b/packages/local-file-shell/src/fileSearch/impl/linux.ts
@@ -0,0 +1,34 @@
+import { createLogger } from '../../logger';
+import type { ToolDetector } from '../../toolDetector';
+import type { FileResult, SearchFilesParams } from '../../types';
+import { UnixFileSearch, type UnixSearchTool } from './unix';
+
+const logger = createLogger('fileSearch:linux');
+
+/**
+ * Linux file search implementation
+ * Uses fd > find > fast-glob fallback strategy
+ */
+export class LinuxSearchServiceImpl extends UnixFileSearch {
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
+ }
+
+ async search(options: SearchFilesParams): Promise<FileResult[]> {
+ if (this.currentTool === null) {
+ this.currentTool = await this.determineBestUnixTool();
+ logger.info(`Using file search tool: ${this.currentTool}`);
+ }
+
+ return this.searchWithUnixTool(this.currentTool as UnixSearchTool, options);
+ }
+
+ async checkSearchServiceStatus(): Promise<boolean> {
+ return true;
+ }
+
+ async updateSearchIndex(): Promise<boolean> {
+ logger.warn('updateSearchIndex is not supported on Linux (no system-wide index)');
+ return false;
+ }
+}
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts b/packages/local-file-shell/src/fileSearch/impl/macOS.ts
similarity index 76%
rename from apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
rename to packages/local-file-shell/src/fileSearch/impl/macOS.ts
index 1460fd35f17..d95c3f205ce 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/macOS.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/macOS.ts
@@ -4,14 +4,12 @@ import path from 'node:path';
import { execa } from 'execa';
-import type { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
+import { createLogger } from '../../logger';
+import type { ToolDetector } from '../../toolDetector';
+import type { FileResult, SearchFilesParams } from '../../types';
+import { UnixFileSearch, type UnixSearchTool } from './unix';
-import type { FileResult, SearchOptions } from '../types';
-import type { UnixSearchTool } from './unix';
-import { UnixFileSearch } from './unix';
-
-const logger = createLogger('module:FileSearch:macOS');
+const logger = createLogger('fileSearch:macOS');
/**
* Build the kMDItemFSName expression for a free-form keyword string.
@@ -19,8 +17,6 @@ const logger = createLogger('module:FileSearch:macOS');
* 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
@@ -43,28 +39,14 @@ export const buildFilenameKeywordExpression = (keywords: string): string => {
type MacOSSearchTool = 'mdfind' | UnixSearchTool;
export class MacOSSearchServiceImpl extends UnixFileSearch {
- /**
- * Cache for Spotlight availability status
- * null = not checked, true = available, false = not available
- */
private spotlightAvailable: boolean | null = null;
-
- /**
- * Current tool being used (macOS specific, includes mdfind)
- */
private macOSCurrentTool: MacOSSearchTool | null = null;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
}
- /**
- * Perform file search
- * @param options Search options
- * @returns Promise of search result list
- */
- async search(options: SearchOptions): Promise<FileResult[]> {
- // Determine the best available tool on first search
+ async search(options: SearchFilesParams): Promise<FileResult[]> {
if (this.macOSCurrentTool === null) {
this.macOSCurrentTool = await this.determineBestTool();
logger.info(`Using file search tool: ${this.macOSCurrentTool}`);
@@ -73,13 +55,9 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
return this.searchWithTool(this.macOSCurrentTool, options);
}
- /**
- * Determine the best available tool based on priority
- * Priority: mdfind > fd > find > fast-glob
- */
private async determineBestTool(): Promise<MacOSSearchTool> {
- if (this.toolDetectorManager) {
- const bestTool = await this.toolDetectorManager.getBestTool('file-search');
+ if (this.toolDetector) {
+ const bestTool = await this.toolDetector.getBestTool('file-search');
if (bestTool && ['mdfind', 'fd', 'find'].includes(bestTool)) {
return bestTool as MacOSSearchTool;
}
@@ -89,40 +67,26 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
return 'mdfind';
}
- // Fallback to Unix tool detection
return this.determineBestUnixTool();
}
- /**
- * Search using the specified tool
- */
private async searchWithTool(
tool: MacOSSearchTool,
- options: SearchOptions,
+ options: SearchFilesParams,
): Promise<FileResult[]> {
if (tool === 'mdfind') {
return this.searchWithSpotlight(options);
}
- // Use parent class Unix tool implementation
return this.searchWithUnixTool(tool, options);
}
- /**
- * Fallback to the next available tool (macOS specific)
- */
private async fallbackFromMdfind(): Promise<MacOSSearchTool> {
return this.determineBestUnixTool();
}
- /**
- * Search using Spotlight (mdfind)
- */
- private async searchWithSpotlight(options: SearchOptions): Promise<FileResult[]> {
+ private async searchWithSpotlight(options: SearchFilesParams): Promise<FileResult[]> {
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 [];
@@ -146,7 +110,6 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
.split('\n')
.filter((line) => line.trim());
- // If exited with error code and we have stderr and no results, fallback
if (exitCode !== 0 && stderr && results.length === 0) {
if (!stderr.includes('Index is unavailable') && !stderr.includes('kMD')) {
logger.warn(
@@ -163,7 +126,6 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
}
}
- // Apply limit
const limitedResults =
options.limit && results.length > options.limit ? results.slice(0, options.limit) : results;
@@ -177,34 +139,19 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
}
}
- /**
- * Get macOS-specific ignore patterns including Library/Caches
- */
protected override getDefaultIgnorePatterns(): string[] {
return [...super.getDefaultIgnorePatterns(), '**/Library/Caches/**'];
}
- /**
- * Check search service status
- * @returns Promise indicating if Spotlight service is available
- */
async checkSearchServiceStatus(): Promise<boolean> {
return this.checkSpotlightStatus();
}
- /**
- * Update search index
- * @param path Optional specified path
- * @returns Promise indicating operation success
- */
async updateSearchIndex(updatePath?: string): Promise<boolean> {
return this.updateSpotlightIndex(updatePath);
}
- /**
- * Build mdfind command string
- */
- private buildSearchCommand(options: SearchOptions): {
+ private buildSearchCommand(options: SearchFilesParams): {
args: string[];
cmd: string;
commandString: string;
@@ -213,8 +160,9 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
const cmd = 'mdfind';
const args: string[] = [];
- if (options.onlyIn) {
- args.push('-onlyin', options.onlyIn);
+ const onlyIn = options.onlyIn || options.directory;
+ if (onlyIn) {
+ args.push('-onlyin', onlyIn);
}
if (options.liveUpdate) {
@@ -236,30 +184,25 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
let queryExpression = '';
if (options.keywords) {
- if (!options.keywords.includes('kMDItem')) {
- queryExpression = buildFilenameKeywordExpression(options.keywords);
- } else {
+ if (options.keywords.includes('kMDItem')) {
queryExpression = options.keywords;
+ } else {
+ queryExpression = buildFilenameKeywordExpression(options.keywords);
}
}
if (options.contentContains) {
- if (queryExpression) {
- queryExpression = `${queryExpression} && kMDItemTextContent == "*${options.contentContains}*"cd`;
- } else {
- queryExpression = `kMDItemTextContent == "*${options.contentContains}*"cd`;
- }
+ const contentTerm = `kMDItemTextContent == "*${options.contentContains}*"cd`;
+ queryExpression = queryExpression ? `${queryExpression} && ${contentTerm}` : contentTerm;
}
if (options.fileTypes && options.fileTypes.length > 0) {
const typeConditions = options.fileTypes
.map((type) => `kMDItemContentType == "${type}"`)
.join(' || ');
- if (queryExpression) {
- queryExpression = `${queryExpression} && (${typeConditions})`;
- } else {
- queryExpression = `(${typeConditions})`;
- }
+ queryExpression = queryExpression
+ ? `${queryExpression} && (${typeConditions})`
+ : `(${typeConditions})`;
}
if (options.modifiedAfter || options.modifiedBefore) {
@@ -276,11 +219,9 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
dateCondition += `kMDItemFSContentChangeDate <= $time.iso(${dateString})`;
}
- if (queryExpression) {
- queryExpression = `${queryExpression} && (${dateCondition})`;
- } else {
- queryExpression = dateCondition;
- }
+ queryExpression = queryExpression
+ ? `${queryExpression} && (${dateCondition})`
+ : dateCondition;
}
if (options.createdAfter || options.createdBefore) {
@@ -297,11 +238,9 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
dateCondition += `kMDItemFSCreationDate <= $time.iso(${dateString})`;
}
- if (queryExpression) {
- queryExpression = `${queryExpression} && (${dateCondition})`;
- } else {
- queryExpression = dateCondition;
- }
+ queryExpression = queryExpression
+ ? `${queryExpression} && (${dateCondition})`
+ : dateCondition;
}
const hasQuery = Boolean(queryExpression);
@@ -315,12 +254,9 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
return { args, cmd, commandString, hasQuery };
}
- /**
- * Process Spotlight search results with optional metadata
- */
private async processSpotlightResults(
filePaths: string[],
- options: SearchOptions,
+ options: SearchFilesParams,
engine?: string,
): Promise<FileResult[]> {
const resultPromises = filePaths.map(async (filePath): Promise<FileResult | null> => {
@@ -369,14 +305,11 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
return results;
}
- /**
- * Get detailed metadata for a file using mdls
- */
- private async getDetailedMetadata(filePath: string): Promise<Record<string, any>> {
+ private async getDetailedMetadata(filePath: string): Promise<Record<string, unknown>> {
try {
const { stdout } = await execa('mdls', [filePath]);
- const metadata: Record<string, any> = {};
+ const metadata: Record<string, unknown> = {};
const lines = stdout.split('\n');
let currentKey = '';
@@ -417,10 +350,7 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
}
}
- /**
- * Parse metadata value from mdls output
- */
- private parseMetadataValue(input: string): any {
+ private parseMetadataValue(input: string): unknown {
let value = input;
if (value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
@@ -445,9 +375,6 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
return value;
}
- /**
- * Check Spotlight service status
- */
private async checkSpotlightStatus(): Promise<boolean> {
if (this.spotlightAvailable !== null) {
return this.spotlightAvailable;
@@ -476,9 +403,6 @@ export class MacOSSearchServiceImpl extends UnixFileSearch {
}
}
- /**
- * Update Spotlight index
- */
private async updateSpotlightIndex(updatePath?: string): Promise<boolean> {
try {
await execa('mdutil', ['-E', updatePath || '/']);
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/unix.ts b/packages/local-file-shell/src/fileSearch/impl/unix.ts
similarity index 73%
rename from apps/desktop/src/main/modules/fileSearch/impl/unix.ts
rename to packages/local-file-shell/src/fileSearch/impl/unix.ts
index 95bbc31a71c..352bcd2198d 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/unix.ts
@@ -2,43 +2,33 @@ import { type Stats } from 'node:fs';
import { stat } from 'node:fs/promises';
import * as os from 'node:os';
-import { type GlobFilesParams, type GlobFilesResult } from '@lobechat/electron-client-ipc';
import { execa } from 'execa';
import fg from 'fast-glob';
-import { type ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
+import { createLogger } from '../../logger';
+import { type ToolDetector } from '../../toolDetector';
+import type { FileResult, GlobFilesParams, GlobFilesResult, SearchFilesParams } from '../../types';
import { BaseFileSearch } from '../base';
-import { type FileResult, type SearchOptions } from '../types';
-const logger = createLogger('module:FileSearch:unix');
+const logger = createLogger('fileSearch:unix');
/**
* Fallback tool type for Unix file search
* Priority: fd > find > fast-glob
*/
-export type UnixSearchTool = 'fd' | 'find' | 'fast-glob';
+export type UnixSearchTool = 'fast-glob' | 'fd' | 'find';
/**
* Unix file search base class
* Provides common search implementations for macOS and Linux
*/
export abstract class UnixFileSearch extends BaseFileSearch {
- /**
- * Current fallback tool being used
- */
protected currentTool: UnixSearchTool | null = null;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
}
- /**
- * Check if a tool is available using 'which' command
- * @param tool Tool name to check
- * @returns Promise indicating if tool is available
- */
protected async checkToolAvailable(tool: string): Promise<boolean> {
try {
await execa('which', [tool], { timeout: 3000 });
@@ -48,14 +38,9 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Determine the best available Unix tool based on priority
- * Priority: fd > find > fast-glob
- * @returns The best available tool
- */
protected async determineBestUnixTool(): Promise<UnixSearchTool> {
- if (this.toolDetectorManager) {
- const bestTool = await this.toolDetectorManager.getBestTool('file-search');
+ if (this.toolDetector) {
+ const bestTool = await this.toolDetector.getBestTool('file-search');
if (bestTool && ['fd', 'find'].includes(bestTool)) {
return bestTool as UnixSearchTool;
}
@@ -72,11 +57,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
return 'fast-glob';
}
- /**
- * Fallback to the next available tool
- * @param currentTool Current tool that failed
- * @returns Next tool to try
- */
protected async fallbackToNextTool(currentTool: UnixSearchTool): Promise<UnixSearchTool> {
const priority: UnixSearchTool[] = ['fd', 'find', 'fast-glob'];
const currentIndex = priority.indexOf(currentTool);
@@ -84,7 +64,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
for (let i = currentIndex + 1; i < priority.length; i++) {
const nextTool = priority[i];
if (nextTool === 'fast-glob') {
- return 'fast-glob'; // Always available
+ return 'fast-glob';
}
if (await this.checkToolAvailable(nextTool)) {
return nextTool;
@@ -94,15 +74,9 @@ export abstract class UnixFileSearch extends BaseFileSearch {
return 'fast-glob';
}
- /**
- * Search using the specified Unix tool
- * @param tool Tool to use for search
- * @param options Search options
- * @returns Search results
- */
protected async searchWithUnixTool(
tool: UnixSearchTool,
- options: SearchOptions,
+ options: SearchFilesParams,
): Promise<FileResult[]> {
switch (tool) {
case 'fd': {
@@ -117,13 +91,8 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Search using fd (fast find alternative)
- * @param options Search options
- * @returns Search results
- */
- protected async searchWithFd(options: SearchOptions): Promise<FileResult[]> {
- const searchDir = options.onlyIn || os.homedir() || '/';
+ protected async searchWithFd(options: SearchFilesParams): Promise<FileResult[]> {
+ const searchDir = options.onlyIn || options.directory || os.homedir() || '/';
const limit = options.limit || 30;
logger.debug('Performing fd search', { keywords: options.keywords, searchDir });
@@ -131,14 +100,12 @@ export abstract class UnixFileSearch extends BaseFileSearch {
try {
const args: string[] = [];
- // Pattern matching
if (options.keywords) {
args.push(options.keywords);
} else {
- args.push('.'); // Match all files
+ args.push('.');
}
- // Search directory and options
args.push(searchDir, '--type', 'f', '--hidden', '--ignore-case', '--max-depth', '10');
args.push(
'--max-results',
@@ -178,13 +145,8 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Search using find (Unix standard tool)
- * @param options Search options
- * @returns Search results
- */
- protected async searchWithFind(options: SearchOptions): Promise<FileResult[]> {
- const searchDir = options.onlyIn || os.homedir() || '/';
+ protected async searchWithFind(options: SearchFilesParams): Promise<FileResult[]> {
+ const searchDir = options.onlyIn || options.directory || os.homedir() || '/';
const limit = options.limit || 30;
logger.debug('Performing find search', { keywords: options.keywords, searchDir });
@@ -210,9 +172,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
'-o',
];
- // Limit depth and exclude common directories
-
- // Pattern matching
if (options.keywords) {
args.push('-iname', `*${options.keywords}*`);
}
@@ -247,19 +206,13 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Search using fast-glob (pure Node.js implementation)
- * @param options Search options
- * @returns Search results
- */
- protected async searchWithFastGlob(options: SearchOptions): Promise<FileResult[]> {
- const searchDir = options.onlyIn || os.homedir() || '/';
+ protected async searchWithFastGlob(options: SearchFilesParams): Promise<FileResult[]> {
+ const searchDir = options.onlyIn || options.directory || os.homedir() || '/';
const limit = options.limit || 30;
logger.debug('Performing fast-glob search', { keywords: options.keywords, searchDir });
try {
- // Build glob pattern from keywords
const pattern = options.keywords
? `**/*${this.escapeGlobPattern(options.keywords)}*`
: '**/*';
@@ -268,7 +221,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
absolute: true,
caseSensitiveMatch: false,
cwd: searchDir,
- deep: 10, // Limit depth for performance
+ deep: 10,
dot: true,
ignore: this.getDefaultIgnorePatterns(),
onlyFiles: true,
@@ -285,11 +238,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Get default ignore patterns for fast-glob
- * Can be overridden by subclasses for platform-specific patterns
- * @returns Array of ignore patterns
- */
protected getDefaultIgnorePatterns(): string[] {
return ['**/node_modules/**', '**/.git/**', '**/.*cache*/**'];
}
@@ -297,23 +245,14 @@ export abstract class UnixFileSearch extends BaseFileSearch {
/**
* Perform glob pattern matching
* Uses fd > find > fast-glob fallback strategy
- * @param params Glob parameters
- * @returns Promise of glob result
*/
async glob(params: GlobFilesParams): Promise<GlobFilesResult> {
- // Determine the best available tool
const tool = await this.determineBestUnixTool();
logger.info(`Using glob tool: ${tool}`);
return this.globWithUnixTool(tool, params);
}
- /**
- * Glob using the specified Unix tool
- * @param tool Tool to use for glob
- * @param params Glob parameters
- * @returns Glob results
- */
protected async globWithUnixTool(
tool: UnixSearchTool,
params: GlobFilesParams,
@@ -331,13 +270,8 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Glob using fd
- * @param params Glob parameters
- * @returns Glob results
- */
protected async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || os.homedir() || process.cwd();
+ const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -350,6 +284,10 @@ export abstract class UnixFileSearch extends BaseFileSearch {
'--absolute-path',
'--hidden',
'--no-ignore',
+ '--exclude',
+ 'node_modules',
+ '--exclude',
+ '.git',
];
const { stdout, exitCode } = await execa('fd', args, {
@@ -367,7 +305,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
.split('\n')
.filter((line) => line.trim());
- // Get stats for sorting by mtime
const filesWithStats = await this.getFilesWithStats(files);
const sortedFiles = filesWithStats.sort((a, b) => b.mtime - a.mtime).map((f) => f.path);
@@ -386,30 +323,19 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Glob using find
- * Note: find has limited glob support, converts pattern to -name/-path
- * @param params Glob parameters
- * @returns Glob results
- */
protected async globWithFind(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || os.homedir() || process.cwd();
+ const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
const logPrefix = `[glob:find: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting find glob`, { searchPath });
try {
- // Convert glob pattern to find -name pattern
- // find doesn't support full glob, so we do basic conversion
const pattern = params.pattern;
const args: string[] = [searchPath];
- // Check if pattern contains directory separators
if (pattern.includes('/')) {
- // Use -path for patterns with directories
args.push('-path', pattern);
} else {
- // Use -name for simple patterns
args.push('-name', pattern);
}
@@ -430,7 +356,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
.split('\n')
.filter((line) => line.trim());
- // Get stats for sorting by mtime
const filesWithStats = await this.getFilesWithStats(files);
const sortedFiles = filesWithStats.sort((a, b) => b.mtime - a.mtime).map((f) => f.path);
@@ -449,13 +374,8 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Glob using fast-glob (Node.js fallback)
- * @param params Glob parameters
- * @returns Glob results
- */
protected async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || os.homedir() || process.cwd();
+ const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
@@ -465,11 +385,11 @@ export abstract class UnixFileSearch extends BaseFileSearch {
absolute: true,
cwd: searchPath,
dot: true,
+ ignore: ['**/node_modules/**', '**/.git/**'],
onlyFiles: false,
stats: true,
});
- // Sort by modification time (most recent first)
const sortedFiles = (files as unknown as Array<{ path: string; stats: Stats }>)
.sort((a, b) => b.stats.mtime.getTime() - a.stats.mtime.getTime())
.map((f) => f.path);
@@ -494,11 +414,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
}
}
- /**
- * Get file stats for sorting
- * @param files File paths
- * @returns Files with mtime
- */
private async getFilesWithStats(
files: string[],
): Promise<Array<{ mtime: number; path: string }>> {
@@ -509,7 +424,6 @@ export abstract class UnixFileSearch extends BaseFileSearch {
const stats = await stat(filePath);
results.push({ mtime: stats.mtime.getTime(), path: filePath });
} catch {
- // Skip files that can't be stat'd
results.push({ mtime: 0, path: filePath });
}
}
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/windows.ts b/packages/local-file-shell/src/fileSearch/impl/windows.ts
similarity index 71%
rename from apps/desktop/src/main/modules/fileSearch/impl/windows.ts
rename to packages/local-file-shell/src/fileSearch/impl/windows.ts
index 83d9ee346d1..0fb1c662037 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
+++ b/packages/local-file-shell/src/fileSearch/impl/windows.ts
@@ -2,45 +2,34 @@ import { type Stats } from 'node:fs';
import { stat } from 'node:fs/promises';
import * as os from 'node:os';
-import { type GlobFilesParams, type GlobFilesResult } from '@lobechat/electron-client-ipc';
import { execa } from 'execa';
import fg from 'fast-glob';
-import { type ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
-import { createLogger } from '@/utils/logger';
-
+import { createLogger } from '../../logger';
+import { type ToolDetector } from '../../toolDetector';
+import type { FileResult, GlobFilesParams, GlobFilesResult, SearchFilesParams } from '../../types';
import { BaseFileSearch } from '../base';
-import { type FileResult, type SearchOptions } from '../types';
-const logger = createLogger('module:FileSearch:windows');
+const logger = createLogger('fileSearch:windows');
/**
* Fallback tool type for Windows file search
* Priority: fd > powershell > fast-glob
*/
-type WindowsFallbackTool = 'fd' | 'powershell' | 'fast-glob';
+type WindowsFallbackTool = 'fast-glob' | 'fd' | 'powershell';
/**
* Windows file search implementation
* Uses fd > PowerShell > fast-glob fallback strategy
*/
export class WindowsSearchServiceImpl extends BaseFileSearch {
- /**
- * Current fallback tool being used
- */
private currentTool: WindowsFallbackTool | null = null;
- constructor(toolDetectorManager?: ToolDetectorManager) {
- super(toolDetectorManager);
+ constructor(toolDetector?: ToolDetector) {
+ super(toolDetector);
}
- /**
- * Perform file search
- * @param options Search options
- * @returns Promise of search result list
- */
- async search(options: SearchOptions): Promise<FileResult[]> {
- // Determine the best available tool on first search
+ async search(options: SearchFilesParams): Promise<FileResult[]> {
if (this.currentTool === null) {
this.currentTool = await this.determineBestTool();
logger.info(`Using file search tool: ${this.currentTool}`);
@@ -49,13 +38,9 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
return this.searchWithTool(this.currentTool, options);
}
- /**
- * Determine the best available tool based on priority
- * Priority: fd > powershell > fast-glob
- */
private async determineBestTool(): Promise<WindowsFallbackTool> {
- if (this.toolDetectorManager) {
- const bestTool = await this.toolDetectorManager.getBestTool('file-search');
+ if (this.toolDetector) {
+ const bestTool = await this.toolDetector.getBestTool('file-search');
if (bestTool && ['fd', 'powershell'].includes(bestTool)) {
return bestTool as WindowsFallbackTool;
}
@@ -65,15 +50,9 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
return 'fd';
}
- // PowerShell is always available on Windows
return 'powershell';
}
- /**
- * Check if a tool is available using 'where' command (Windows equivalent of 'which')
- * @param tool Tool name to check
- * @returns Promise indicating if tool is available
- */
private async checkToolAvailable(tool: string): Promise<boolean> {
try {
await execa('where', [tool], { timeout: 3000 });
@@ -83,12 +62,9 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Search using the specified tool
- */
private async searchWithTool(
tool: WindowsFallbackTool,
- options: SearchOptions,
+ options: SearchFilesParams,
): Promise<FileResult[]> {
switch (tool) {
case 'fd': {
@@ -103,9 +79,6 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Fallback to the next available tool
- */
private async fallbackToNextTool(currentTool: WindowsFallbackTool): Promise<WindowsFallbackTool> {
const priority: WindowsFallbackTool[] = ['fd', 'powershell', 'fast-glob'];
const currentIndex = priority.indexOf(currentTool);
@@ -113,7 +86,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
for (let i = currentIndex + 1; i < priority.length; i++) {
const nextTool = priority[i];
if (nextTool === 'fast-glob' || nextTool === 'powershell') {
- return nextTool; // Always available
+ return nextTool;
}
if (await this.checkToolAvailable(nextTool)) {
return nextTool;
@@ -123,13 +96,8 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
return 'fast-glob';
}
- /**
- * Search using fd (cross-platform fast find alternative)
- * @param options Search options
- * @returns Search results
- */
- private async searchWithFd(options: SearchOptions): Promise<FileResult[]> {
- const searchDir = options.onlyIn || os.homedir() || 'C:\\';
+ private async searchWithFd(options: SearchFilesParams): Promise<FileResult[]> {
+ const searchDir = options.onlyIn || options.directory || os.homedir() || 'C:\\';
const limit = options.limit || 30;
logger.debug('Performing fd search', { keywords: options.keywords, searchDir });
@@ -137,14 +105,12 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
try {
const args: string[] = [];
- // Pattern matching
if (options.keywords) {
args.push(options.keywords);
} else {
- args.push('.'); // Match all files
+ args.push('.');
}
- // Search directory and options
args.push(searchDir, '--type', 'f', '--hidden', '--ignore-case', '--max-depth', '10');
args.push(
'--max-results',
@@ -184,26 +150,15 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Search using PowerShell Get-ChildItem
- * @param options Search options
- * @returns Search results
- */
- private async searchWithPowerShell(options: SearchOptions): Promise<FileResult[]> {
- const searchDir = options.onlyIn || os.homedir() || 'C:\\';
+ private async searchWithPowerShell(options: SearchFilesParams): Promise<FileResult[]> {
+ const searchDir = options.onlyIn || options.directory || os.homedir() || 'C:\\';
const limit = options.limit || 30;
logger.debug('Performing PowerShell search', { keywords: options.keywords, searchDir });
try {
- // Build PowerShell command
const filter = options.keywords ? `*${options.keywords}*` : '*';
- // PowerShell command to search files
- // -Recurse: recursive search
- // -File: only files
- // -Depth: limit search depth
- // -ErrorAction SilentlyContinue: ignore permission errors
const psCommand = `
Get-ChildItem -Path '${searchDir}' -Filter '${filter}' -Recurse -File -Depth 10 -ErrorAction SilentlyContinue |
Where-Object {
@@ -246,19 +201,13 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Search using fast-glob (pure Node.js implementation)
- * @param options Search options
- * @returns Search results
- */
- private async searchWithFastGlob(options: SearchOptions): Promise<FileResult[]> {
- const searchDir = options.onlyIn || os.homedir() || 'C:\\';
+ private async searchWithFastGlob(options: SearchFilesParams): Promise<FileResult[]> {
+ const searchDir = options.onlyIn || options.directory || os.homedir() || 'C:\\';
const limit = options.limit || 30;
logger.debug('Performing fast-glob search', { keywords: options.keywords, searchDir });
try {
- // Build glob pattern from keywords
const pattern = options.keywords
? `**/*${this.escapeGlobPattern(options.keywords)}*`
: '**/*';
@@ -268,7 +217,8 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
caseSensitiveMatch: false,
cwd: searchDir,
deep: 10,
- dot: false, // Windows hidden files use attributes, not dot prefix
+ // Windows hidden files use attributes, not dot prefix
+ dot: false,
ignore: [
'**/node_modules/**',
'**/.git/**',
@@ -293,33 +243,16 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Check search service status
- * @returns Promise indicating if service is available (always true)
- */
async checkSearchServiceStatus(): Promise<boolean> {
- // At minimum, fast-glob is always available
return true;
}
- /**
- * Update search index
- * Windows Search index is managed by the OS
- * @returns Promise indicating operation result (always false)
- */
async updateSearchIndex(): Promise<boolean> {
logger.warn('updateSearchIndex is not supported (using fast-glob instead of Windows Search)');
return false;
}
- /**
- * Perform glob pattern matching
- * Uses fd > fast-glob fallback strategy
- * @param params Glob parameters
- * @returns Promise of glob result
- */
async glob(params: GlobFilesParams): Promise<GlobFilesResult> {
- // Check if fd is available
if (await this.checkToolAvailable('fd')) {
logger.info('Using glob tool: fd');
return this.globWithFd(params);
@@ -329,13 +262,8 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
return this.globWithFastGlob(params);
}
- /**
- * Glob using fd
- * @param params Glob parameters
- * @returns Glob results
- */
private async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || os.homedir() || process.cwd();
+ const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -348,6 +276,10 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
'--absolute-path',
'--hidden',
'--no-ignore',
+ '--exclude',
+ 'node_modules',
+ '--exclude',
+ '.git',
];
const { stdout, exitCode } = await execa('fd', args, {
@@ -362,10 +294,9 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
const files = stdout
.trim()
- .split('\r\n') // Windows uses \r\n
+ .split('\r\n')
.filter((line) => line.trim());
- // Get stats for sorting by mtime
const filesWithStats = await this.getFilesWithStats(files);
const sortedFiles = filesWithStats.sort((a, b) => b.mtime - a.mtime).map((f) => f.path);
@@ -384,13 +315,8 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Glob using fast-glob (Node.js fallback)
- * @param params Glob parameters
- * @returns Glob results
- */
private async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.scope || os.homedir() || process.cwd();
+ const searchPath = params.scope || params.cwd || os.homedir() || process.cwd();
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
@@ -399,12 +325,13 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
const files = await fg(params.pattern, {
absolute: true,
cwd: searchPath,
- dot: false, // Windows hidden files use attributes, not dot prefix
+ // Windows hidden files use attributes, not dot prefix
+ dot: false,
+ ignore: ['**/node_modules/**', '**/.git/**'],
onlyFiles: false,
stats: true,
});
- // Sort by modification time (most recent first)
const sortedFiles = (files as unknown as Array<{ path: string; stats: Stats }>)
.sort((a, b) => b.stats.mtime.getTime() - a.stats.mtime.getTime())
.map((f) => f.path);
@@ -429,11 +356,6 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
}
}
- /**
- * Get file stats for sorting
- * @param files File paths
- * @returns Files with mtime
- */
private async getFilesWithStats(
files: string[],
): Promise<Array<{ mtime: number; path: string }>> {
@@ -444,7 +366,6 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
const stats = await stat(filePath);
results.push({ mtime: stats.mtime.getTime(), path: filePath });
} catch {
- // Skip files that can't be stat'd
results.push({ mtime: 0, path: filePath });
}
}
diff --git a/packages/local-file-shell/src/fileSearch/index.ts b/packages/local-file-shell/src/fileSearch/index.ts
new file mode 100644
index 00000000000..434d6dc5486
--- /dev/null
+++ b/packages/local-file-shell/src/fileSearch/index.ts
@@ -0,0 +1,31 @@
+import { platform } from 'node:os';
+
+import { createLogger } from '../logger';
+import type { ToolDetector } from '../toolDetector';
+import { LinuxSearchServiceImpl } from './impl/linux';
+import { MacOSSearchServiceImpl } from './impl/macOS';
+import { WindowsSearchServiceImpl } from './impl/windows';
+
+const logger = createLogger('fileSearch:factory');
+
+export { BaseFileSearch } from './base';
+
+export const createFileSearchModule = (toolDetector?: ToolDetector) => {
+ const currentPlatform = platform();
+
+ switch (currentPlatform) {
+ case 'darwin': {
+ return new MacOSSearchServiceImpl(toolDetector);
+ }
+ case 'win32': {
+ return new WindowsSearchServiceImpl(toolDetector);
+ }
+ case 'linux': {
+ return new LinuxSearchServiceImpl(toolDetector);
+ }
+ default: {
+ logger.warn(`Unsupported platform: ${currentPlatform}, using Linux fallback`);
+ return new LinuxSearchServiceImpl(toolDetector);
+ }
+ }
+};
diff --git a/packages/local-file-shell/src/fileSearch/types.ts b/packages/local-file-shell/src/fileSearch/types.ts
new file mode 100644
index 00000000000..871abe67604
--- /dev/null
+++ b/packages/local-file-shell/src/fileSearch/types.ts
@@ -0,0 +1,6 @@
+/**
+ * Re-export the shared file-search types. Kept here so legacy desktop callers
+ * that imported them from the `fileSearch/types` path keep compiling after the
+ * sink-in to `@lobechat/local-file-shell`.
+ */
+export type { FileResult, SearchFilesParams as SearchOptions } from '../types';
diff --git a/packages/local-file-shell/src/index.ts b/packages/local-file-shell/src/index.ts
index 9ae9a5c38b7..35b077c45fc 100644
--- a/packages/local-file-shell/src/index.ts
+++ b/packages/local-file-shell/src/index.ts
@@ -1,3 +1,7 @@
+export * from './contentSearch';
export * from './file';
+export * from './fileSearch';
+export { createLogger, type Logger, type LoggerFactory, setLoggerFactory } from './logger';
export * from './shell';
+export type { ToolCategory, ToolDetector } from './toolDetector';
export * from './types';
diff --git a/packages/local-file-shell/src/logger.ts b/packages/local-file-shell/src/logger.ts
new file mode 100644
index 00000000000..14cd35a713b
--- /dev/null
+++ b/packages/local-file-shell/src/logger.ts
@@ -0,0 +1,81 @@
+import debug from 'debug';
+
+/**
+ * Minimal logger interface. Each level is variadic — the first arg is a
+ * message string and the rest are formatter arguments (matches the shape
+ * agreed across LobeHub packages).
+ */
+export interface Logger {
+ debug: (message: unknown, ...args: unknown[]) => void;
+ error: (message: unknown, ...args: unknown[]) => void;
+ info: (message: unknown, ...args: unknown[]) => void;
+ verbose?: (message: unknown, ...args: unknown[]) => void;
+ warn: (message: unknown, ...args: unknown[]) => void;
+}
+
+export type LoggerFactory = (namespace: string) => Logger;
+
+const DEFAULT_NAMESPACE_PREFIX = 'lobe-local-file-shell';
+
+/**
+ * Default logger factory backed by the `debug` package — enabled at runtime
+ * via the standard `DEBUG=lobe-local-file-shell:*` env var. `error` always
+ * surfaces via `console.error` so genuine failures aren't swallowed even when
+ * debug logging is off.
+ */
+export const createDefaultLogger: LoggerFactory = (namespace) => {
+ const fullNamespace = namespace.startsWith(DEFAULT_NAMESPACE_PREFIX)
+ ? namespace
+ : `${DEFAULT_NAMESPACE_PREFIX}:${namespace}`;
+ const debugLogger = debug(fullNamespace);
+
+ return {
+ debug: (message, ...args) => debugLogger(message as string, ...args),
+ error: (message, ...args) => {
+ console.error(`[${fullNamespace}]`, message, ...args);
+ },
+ info: (message, ...args) => debugLogger(`INFO: ${message}`, ...args),
+ verbose: (message, ...args) => debugLogger(`VERBOSE: ${message}`, ...args),
+ warn: (message, ...args) => debugLogger(`WARN: ${message}`, ...args),
+ };
+};
+
+let currentFactory: LoggerFactory = createDefaultLogger;
+const cache = new Map<string, Logger>();
+
+/**
+ * Replace the package-wide logger factory. Call this once at host startup
+ * (e.g. desktop bootstrap) to route logs through electron-log + namespaced
+ * debug. CLI and sandbox can leave it unset and rely on the `debug` default.
+ *
+ * Safe to call after `createLogger(namespace)` has already been invoked at
+ * module load — the returned logger is a lazy proxy that re-resolves the
+ * current factory on every method call.
+ */
+export const setLoggerFactory = (factory: LoggerFactory): void => {
+ currentFactory = factory;
+ // Invalidate cached concrete loggers so subsequent calls see the new factory.
+ cache.clear();
+};
+
+const resolveLogger = (namespace: string): Logger => {
+ const cached = cache.get(namespace);
+ if (cached) return cached;
+ const logger = currentFactory(namespace);
+ cache.set(namespace, logger);
+ return logger;
+};
+
+/**
+ * Return a {@link Logger} bound to `namespace`. The returned object is a thin
+ * proxy that dispatches each call through the **current** factory, so calling
+ * {@link setLoggerFactory} after module-level `createLogger(...)` invocations
+ * still takes effect.
+ */
+export const createLogger: LoggerFactory = (namespace) => ({
+ debug: (message, ...args) => resolveLogger(namespace).debug(message, ...args),
+ error: (message, ...args) => resolveLogger(namespace).error(message, ...args),
+ info: (message, ...args) => resolveLogger(namespace).info(message, ...args),
+ verbose: (message, ...args) => resolveLogger(namespace).verbose?.(message, ...args),
+ warn: (message, ...args) => resolveLogger(namespace).warn(message, ...args),
+});
diff --git a/packages/local-file-shell/src/toolDetector.ts b/packages/local-file-shell/src/toolDetector.ts
new file mode 100644
index 00000000000..8953ceccaea
--- /dev/null
+++ b/packages/local-file-shell/src/toolDetector.ts
@@ -0,0 +1,15 @@
+/**
+ * Tool categories the search modules consult when picking the best available
+ * binary on the host.
+ */
+export type ToolCategory = 'content-search' | 'file-search';
+
+/**
+ * Minimal contract the search modules need from a tool detector. Desktop
+ * injects its full ToolDetectorManager (which also handles registration and
+ * caching); CLI / sandbox can leave it unset, in which case each impl falls
+ * back to its own `which`-based detection.
+ */
+export interface ToolDetector {
+ getBestTool: (category: ToolCategory) => Promise<string | null>;
+}
diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.ts
index b7489485713..0afd411ad9b 100644
--- a/packages/local-file-shell/src/types.ts
+++ b/packages/local-file-shell/src/types.ts
@@ -117,29 +117,78 @@ export interface ListFilesResult {
}
export interface GlobFilesParams {
+ /** Legacy alias for `scope`. Honored when set; prefer `scope` for new callers. */
cwd?: string;
pattern: string;
+ /** Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory. */
+ scope?: string;
}
export interface GlobFilesResult {
+ /** Search engine used: 'fd' | 'find' | 'fast-glob' */
+ engine?: string;
error?: string;
files: string[];
/** Diagnostic note returned when the engine had to adjust behavior, e.g. auto-enabling hidden-file matching. */
hint?: string;
+ success: boolean;
+ total_files: number;
+}
+
+export interface FileResult {
+ contentType?: string;
+ createdTime: Date;
+ /** Search engine used to find this file (e.g. 'mdfind', 'fd', 'find', 'fast-glob'). */
+ engine?: string;
+ isDirectory: boolean;
+ lastAccessTime: Date;
+ /** Engine-specific metadata (e.g. Spotlight attributes). */
+ metadata?: Record<string, unknown>;
+ modifiedTime: Date;
+ name: string;
+ path: string;
+ size: number;
+ type: string;
}
export interface SearchFilesParams {
contentContains?: string;
+ createdAfter?: Date;
+ createdBefore?: Date;
+ detailed?: boolean;
+ /** Legacy alias for `onlyIn`. */
directory?: string;
+ exclude?: string[];
+ fileTypes?: string[];
keywords: string;
limit?: number;
+ liveUpdate?: boolean;
+ modifiedAfter?: Date;
+ modifiedBefore?: Date;
+ onlyIn?: string;
+ sortBy?: 'date' | 'name' | 'size';
+ sortDirection?: 'asc' | 'desc';
}
+/**
+ * Lightweight search result for the thin wrapper API ({@link searchLocalFiles}).
+ * The factory-based API ({@link createFileSearchModule}) returns the richer
+ * {@link FileResult} instead.
+ */
export interface SearchFilesResult {
+ createdTime?: Date;
+ isDirectory?: boolean;
+ lastAccessTime?: Date;
+ modifiedTime?: Date;
name: string;
path: string;
+ size?: number;
+ type?: string;
}
+/** Alias for {@link SearchFilesParams} kept for the legacy `SearchOptions` import path. */
+export type SearchOptions = SearchFilesParams;
+
export interface MoveFileItem {
newPath: string;
oldPath: string;
@@ -168,15 +217,42 @@ export interface RenameFileResult {
}
export interface GrepContentParams {
- cwd?: string;
- filePattern?: string;
- pattern: string;
+ '-A'?: number;
+ '-B'?: number;
+ '-C'?: number;
+ '-i'?: boolean;
+ '-n'?: boolean;
+ /** Legacy alias for `scope`. */
+ 'cwd'?: string;
+ /** Legacy alias for `glob`. Set this for the simple wrapper API. */
+ 'filePattern'?: string;
+ /** ripgrep-style glob filter on file paths. */
+ 'glob'?: string;
+ 'head_limit'?: number;
+ 'multiline'?: boolean;
+ 'output_mode'?: 'content' | 'count' | 'files_with_matches';
+ /** Legacy alias for `scope`. Takes precedence when set; prefer `scope`. */
+ 'path'?: string;
+ 'pattern': string;
+ /** Working directory scope. Limits the search to this directory. Defaults to `process.cwd()`. */
+ 'scope'?: string;
+ /** Preferred search tool: 'rg' | 'ag' | 'grep' */
+ 'tool'?: 'ag' | 'grep' | 'rg';
+ 'type'?: string;
}
export interface GrepContentResult {
+ /** Search engine used: 'rg' | 'ag' | 'grep' | 'nodejs' */
+ engine?: string;
error?: string;
/** Diagnostic note returned when the engine had to adjust behavior, e.g. auto-enabling hidden-file matching. */
hint?: string;
+ /**
+ * Match payload. For the simple wrapper API this is the raw rg --json
+ * objects; for the factory-based API it's an array of string lines whose
+ * format depends on `output_mode`.
+ */
matches: any[];
success: boolean;
+ total_matches: number;
}