Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(builtin-tool): fix local-system grep always returning 0 matches (#17388)

Arvin Xuf4cebaa56256
diff --git a/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts b/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts
index 71772e3a5f8..93af0b589df 100644
--- a/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts
+++ b/packages/builtin-tool-local-system/src/__tests__/grepContentForwarding.test.ts
@@ -118,6 +118,67 @@ describe('localSystemExecutor.grepContent β€” params forwarding', () => {
});
});
+describe('localSystemExecutor.grepContent β€” working directory default', () => {
+ const mockRuntime = () => {
+ const runtime = (localSystemExecutor as any).runtime as {
+ grepContent: (args: any) => Promise<unknown>;
+ };
+ return vi.spyOn(runtime, 'grepContent').mockResolvedValue({
+ content: 'Found 0 matches in 0 locations:',
+ state: { matches: [], pattern: 'foo', totalMatches: 0 },
+ success: true,
+ });
+ };
+
+ // The grep systemRole tells the model `scope` "defaults to the working
+ // directory". Without a fallback, an omitted/relative scope fell through to the
+ // Electron main process `process.cwd()` (`/` in a packaged app) β†’ 0 matches.
+ it('defaults an omitted scope to ctx.workingDirectory', async () => {
+ const spy = mockRuntime();
+
+ await localSystemExecutor.grepContent({ pattern: 'foo' }, {
+ messageId: 'm1',
+ workingDirectory: '/Users/me/project',
+ } as never);
+
+ expect((spy.mock.calls[0][0] as { path?: string }).path).toBe('/Users/me/project');
+ spy.mockRestore();
+ });
+
+ it('anchors a relative scope (".") onto ctx.workingDirectory', async () => {
+ const spy = mockRuntime();
+
+ await localSystemExecutor.grepContent({ 'pattern': 'foo', 'scope': '.' }, {
+ messageId: 'm1',
+ workingDirectory: '/Users/me/project',
+ } as never);
+
+ expect((spy.mock.calls[0][0] as { path?: string }).path).toBe('/Users/me/project');
+ spy.mockRestore();
+ });
+
+ it('keeps an absolute scope as-is even when a working directory is present', async () => {
+ const spy = mockRuntime();
+
+ await localSystemExecutor.grepContent({ 'pattern': 'foo', 'scope': '/abs/elsewhere' }, {
+ messageId: 'm1',
+ workingDirectory: '/Users/me/project',
+ } as never);
+
+ expect((spy.mock.calls[0][0] as { path?: string }).path).toBe('/abs/elsewhere');
+ spy.mockRestore();
+ });
+
+ it('leaves params untouched when no scope and no working directory (web)', async () => {
+ const spy = mockRuntime();
+
+ await localSystemExecutor.grepContent({ pattern: 'foo' }, { messageId: 'm1' } as never);
+
+ expect((spy.mock.calls[0][0] as { path?: string }).path).toBeUndefined();
+ spy.mockRestore();
+ });
+});
+
describe('localSystemExecutor.listFiles β€” limit forwarding', () => {
it('forwards the manifest-exposed `limit` to the runtime', async () => {
const runtime = (localSystemExecutor as any).runtime as {
diff --git a/packages/builtin-tool-local-system/src/client/executor/index.ts b/packages/builtin-tool-local-system/src/client/executor/index.ts
index 408741a9a09..c64ea287180 100644
--- a/packages/builtin-tool-local-system/src/client/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/client/executor/index.ts
@@ -13,13 +13,13 @@ import type {
WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
import { LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
-import type { BuiltinToolResult } from '@lobechat/types';
+import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
import { localFileService } from '@/services/electron/localFileService';
import { LocalSystemIdentifier } from '../../types';
-import { resolveArgsWithScope } from '../../utils/path';
+import { resolveArgsWithScope, resolvePathWithScope } from '../../utils/path';
const DEFAULT_FILE_SEARCH_LIMIT = 100;
@@ -215,9 +215,28 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
// ==================== Search & Find ====================
- grepContent = async (params: GrepContentParams): Promise<BuiltinToolResult> => {
+ grepContent = async (
+ params: GrepContentParams,
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
try {
- const resolvedParams = resolveArgsWithScope(params, 'path');
+ // Resolve the search root to an ABSOLUTE path anchored on the agent's
+ // effective working directory. The grep manifest/systemRole tell the model
+ // `scope` "defaults to the working directory", but without this the
+ // downstream `resolveSearchPath` drops to the Electron main process
+ // `process.cwd()` (`/` in a packaged app) β€” so a scope-less OR relative
+ // (e.g. `.`) scope made every grep return 0 matches. `ctx.workingDirectory`
+ // is sourced from the same place as the `{{workingDirectory}}` prompt
+ // placeholder, so what the search targets matches what the prompt promises.
+ // `resolvePathWithScope(scope, workingDir)` treats the model's `scope` as a
+ // path resolved against the working directory:
+ // - scope omitted β†’ working directory
+ // - scope relative (`.`, `src`) β†’ joined onto the working directory
+ // - scope absolute β†’ used as-is
+ // It only returns undefined when there is no working directory AND no scope
+ // (web / nothing configured) β€” then we leave params untouched.
+ const searchRoot = resolvePathWithScope(params.scope, ctx?.workingDirectory);
+ const resolvedParams = searchRoot ? { ...params, path: searchRoot } : params;
// Forward the full IPC params (glob / output_mode / -i / -A / -B / -C / -n /
// multiline / head_limit / type / tool) instead of stripping to {directory, pattern}.
// ComputerRuntime.callService passes args through unchanged, so the runtime type
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index ab1ae1c2bec..ba134d19c4e 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -139,11 +139,19 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
}
case 'grepContent': {
+ // Forward the FULL param set. The desktop content-search reads
+ // `path`/`scope`/`cwd` for the search root and
+ // `glob`/`type`/`-i`/`-n`/`-A`/`-B`/`-C`/`multiline`/`head_limit`/`output_mode`
+ // for filtering. Collapsing to a stripped `{cwd, filePattern, output_mode,
+ // pattern}` shape here silently dropped every filter flag and renamed
+ // `glob`β†’`filePattern` (a field the desktop `buildGrepArgs` never reads),
+ // so case-insensitive / typed / glob-scoped searches returned wrong or
+ // empty results β€” defeating the executor-level forwarding fix. Keep every
+ // field; only normalize the legacy search-root alias so `cwd`-only callers
+ // still work without shadowing an explicit `path`/`scope`.
return {
- cwd: params.directory ?? params.path ?? params.scope ?? params.cwd,
- filePattern: params.filePattern ?? params.glob,
- output_mode: params.output_mode,
- pattern: params.pattern,
+ ...params,
+ cwd: params.cwd ?? params.directory ?? params.path ?? params.scope,
};
}
diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
index 166a8fd7be2..476e81c3058 100644
--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
@@ -95,6 +95,62 @@ describe('LocalSystemExecutionRuntime.globFiles', () => {
});
});
+describe('LocalSystemExecutionRuntime.grepContent', () => {
+ // Regression: exercise the REAL callService β†’ denormalizeParams path (do NOT
+ // mock runtime.grepContent). Pre-fix, denormalizeParams collapsed grep args to
+ // `{cwd, filePattern, output_mode, pattern}` β€” dropping every filter flag and
+ // renaming `glob`β†’`filePattern` (which the desktop `buildGrepArgs` never reads),
+ // so `-i` / typed / glob-scoped searches silently returned 0 matches.
+ it('forwards the full param set (glob/type/flags/search-root) to the service', async () => {
+ const service = createService({
+ grepContent: vi.fn().mockResolvedValue({
+ engine: 'rg',
+ matches: [],
+ success: true,
+ total_matches: 0,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ await runtime.grepContent({
+ '-A': 3,
+ '-B': 2,
+ '-C': 1,
+ '-i': true,
+ '-n': true,
+ 'glob': '**/*.ts',
+ 'head_limit': 50,
+ 'multiline': true,
+ 'output_mode': 'content',
+ 'path': '/repo',
+ 'pattern': 'Foo',
+ 'type': 'ts',
+ } as never);
+
+ const forwarded = (service.grepContent as ReturnType<typeof vi.fn>).mock.calls[0][0];
+
+ // Every filter flag the LLM set MUST reach the desktop search β€” the
+ // desktop `buildGrepArgs` reads these exact keys.
+ expect(forwarded).toMatchObject({
+ '-A': 3,
+ '-B': 2,
+ '-C': 1,
+ '-i': true,
+ '-n': true,
+ 'glob': '**/*.ts',
+ 'head_limit': 50,
+ 'multiline': true,
+ 'output_mode': 'content',
+ 'pattern': 'Foo',
+ 'type': 'ts',
+ });
+ // Search root reaches the desktop `resolveSearchPath` via path/scope/cwd.
+ expect(forwarded.path ?? forwarded.scope ?? forwarded.cwd).toBe('/repo');
+ // `glob` must NOT be renamed to `filePattern` β€” the desktop never reads it.
+ expect(forwarded.filePattern).toBeUndefined();
+ });
+});
+
describe('LocalSystemExecutionRuntime.readFile', () => {
it('routes uploaded image results onto state.images', async () => {
const service = createService({
diff --git a/src/helpers/effectiveWorkingDirectory.ts b/src/helpers/effectiveWorkingDirectory.ts
new file mode 100644
index 00000000000..1bfadb39ff1
--- /dev/null
+++ b/src/helpers/effectiveWorkingDirectory.ts
@@ -0,0 +1,42 @@
+import { isDesktop } from '@lobechat/const';
+
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { type ChatStoreState } from '@/store/chat/initialState';
+import { topicSelectors } from '@/store/chat/selectors';
+import { getElectronStoreState } from '@/store/electron';
+
+/**
+ * Resolve the agent's effective working directory: topic override first, then
+ * the agent's per-device value. Returns an actual filesystem path, or
+ * `undefined` when nothing is configured (or off-desktop).
+ *
+ * This is the single source behind both the `{{workingDirectory}}` system-prompt
+ * placeholder and the working-directory handed to tools, so what the prompt
+ * promises matches what tools actually operate on.
+ *
+ * The chat state is passed IN rather than read from `useChatStore` so this stays
+ * importable from inside the chat store's own module graph (e.g. the agent-run
+ * transports). Importing the store instance there would create a cycle
+ * (chat store β†’ agentRun actions β†’ transport β†’ here β†’ chat store) and leave the
+ * action classes undefined at module-eval time.
+ *
+ * Pass `topicId` for async work (e.g. a streaming tool call) so the directory is
+ * bound to the topic that *started* the request, not whatever topic is active
+ * now β€” the user may switch topics mid-stream. Omit it (prompt-build time) to
+ * resolve against the active topic.
+ */
+export const resolveEffectiveWorkingDirectory = (
+ chatState: ChatStoreState,
+ topicId?: string | null,
+): string | undefined => {
+ if (!isDesktop) return undefined;
+
+ const topicWorkingDir = topicSelectors.getTopicWorkingDirectory(topicId)(chatState);
+ if (topicWorkingDir) return topicWorkingDir;
+
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ return (
+ agentSelectors.currentAgentWorkingDirectory(currentDeviceId)(getAgentStoreState()) ?? undefined
+ );
+};
diff --git a/src/helpers/parserPlaceholder/index.ts b/src/helpers/parserPlaceholder/index.ts
index 005a775a6ed..4071b576db8 100644
--- a/src/helpers/parserPlaceholder/index.ts
+++ b/src/helpers/parserPlaceholder/index.ts
@@ -4,15 +4,34 @@ import { uuid } from '@lobechat/utils';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { getElectronStoreState } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { resolveEffectiveWorkingDirectory } from '../effectiveWorkingDirectory';
import { globalAgentContextManager } from '../GlobalAgentContextManager';
const placeholderVariablesRegex = /\{\{(.*?)\}\}/g;
+const WORKING_DIRECTORY_UNSPECIFIED = '(not specified, use user Home directory as default)';
+
+/**
+ * The effective working directory as an actual filesystem path, or `undefined`
+ * when nothing is configured (or off-desktop). This is the SAME resolution the
+ * `{{workingDirectory}}` system-prompt placeholder shows the model β€” keep them
+ * sourced from here so what the prompt promises ("defaults to the working
+ * directory") matches what tools actually search. Unlike the placeholder, this
+ * returns `undefined` instead of a human-readable "(not specified…)" string, so
+ * callers can safely use it as a path / scope default.
+ *
+ * Pass `topicId` for async work (e.g. a streaming tool call) so the directory is
+ * bound to the topic that *started* the request, not whatever topic is active
+ * now β€” the user may have switched topics mid-stream, and reading global
+ * active-topic state would then search the wrong project. Omit it (prompt-build
+ * time) to resolve against the active topic.
+ */
+export const getEffectiveWorkingDirectoryPath = (topicId?: string | null): string | undefined =>
+ resolveEffectiveWorkingDirectory(useChatStore.getState(), topicId);
+
export const VARIABLE_GENERATORS = {
/**
* Time-related template variables
@@ -158,15 +177,7 @@ export const VARIABLE_GENERATORS = {
*/
workingDirectory: () => {
if (!isDesktop) return '';
-
- const topicWorkingDir = topicSelectors.currentTopicWorkingDirectory(useChatStore.getState());
- if (topicWorkingDir) return topicWorkingDir;
-
- const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
- const agentWorkingDir = agentSelectors.currentAgentWorkingDirectory(currentDeviceId)(
- useAgentStore.getState(),
- );
- return agentWorkingDir ?? '(not specified, use user Home directory as default)';
+ return getEffectiveWorkingDirectoryPath() ?? WORKING_DIRECTORY_UNSPECIFIED;
},
} as Record<string, () => string>;
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
index 2249d1bd153..cf42fa132ad 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
@@ -3,6 +3,10 @@ import { type BuiltinToolContext } from '@lobechat/types';
import debug from 'debug';
import { produce } from 'immer';
+// Import the state-taking resolver, NOT `@/helpers/parserPlaceholder` β€” that
+// module imports `useChatStore`, which would close a cycle back into this store
+// and leave the action classes undefined at module-eval time.
+import { resolveEffectiveWorkingDirectory } from '@/helpers/effectiveWorkingDirectory';
import { mcpService } from '@/services/mcp';
import { type ChatStore } from '@/store/chat/store';
import { hasExecutor, invokeExecutor } from '@/store/tool/slices/builtin/executors';
@@ -169,6 +173,20 @@ export class ClientToolExecutionActionImpl {
topicId: topicId ?? operation?.context?.topicId,
toolCallId,
toolMessageId,
+ // Effective working directory (topic override > agent per-device value),
+ // resolved from the SAME source as the `{{workingDirectory}}` system
+ // prompt placeholder and the intervention path-scope audit. Tools like
+ // local-system grep/search use this as the default scope so the search
+ // actually runs where the prompt promises β€” not the Electron main
+ // process `process.cwd()` (which is `/` in a packaged app β†’ 0 matches).
+ // Bind to THIS run's topic (captured at request time), not the global
+ // active topic: a response that started in topic A may have its tool
+ // call arrive after the user switched to topic B, and resolving against
+ // the active topic would search B's project instead of A's.
+ workingDirectory: resolveEffectiveWorkingDirectory(
+ this.#get(),
+ topicId ?? operation?.context?.topicId,
+ ),
};
log('[ClientToolCall] execute:start', {
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 21f38241596..2b3e999c97d 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -173,6 +173,44 @@ describe('topicSelectors', () => {
});
});
+ describe('getTopicWorkingDirectory', () => {
+ // Two topics with distinct working directories; A is the active topic.
+ const wdTopics = [
+ { id: 'topicA', metadata: { workingDirectory: '/project-a' }, name: 'A' },
+ { id: 'topicB', metadata: { workingDirectory: '/project-b' }, name: 'B' },
+ ];
+ const wdState = merge(initialStore, {
+ activeAgentId: 'test',
+ activeTopicId: 'topicA',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'test' })]: {
+ currentPage: 0,
+ hasMore: false,
+ items: wdTopics,
+ pageSize: 20,
+ total: wdTopics.length,
+ },
+ },
+ }) as ChatStore;
+
+ // Regression: while topic A is active, a tool call captured for topic B must
+ // resolve B's directory β€” not A's β€” so a mid-stream topic switch can't make
+ // grep search the wrong project.
+ it('binds to the requested topic id, not the active topic', () => {
+ expect(topicSelectors.getTopicWorkingDirectory('topicB')(wdState)).toBe('/project-b');
+ expect(topicSelectors.getTopicWorkingDirectory('topicA')(wdState)).toBe('/project-a');
+ });
+
+ it('falls back to the active topic when no id is given', () => {
+ expect(topicSelectors.getTopicWorkingDirectory()(wdState)).toBe('/project-a');
+ expect(topicSelectors.getTopicWorkingDirectory(null)(wdState)).toBe('/project-a');
+ });
+
+ it('returns undefined for an unknown topic id', () => {
+ expect(topicSelectors.getTopicWorkingDirectory('nope')(wdState)).toBeUndefined();
+ });
+ });
+
describe('groupedTopicsSelector', () => {
it('should return empty array if there are no topics', () => {
const state = merge(initialStore, { activeAgentId: 'test' });
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 4aee9430822..180147e2d6a 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -83,13 +83,12 @@ const currentActiveTopicSummary = (s: ChatStoreState): ChatTopicSummary | undefi
const currentTopicMetadata = (s: ChatStoreState) => currentActiveTopic(s)?.metadata;
/**
- * Get current active topic's working directory.
+ * Extract a topic's working directory from its metadata.
* On desktop: local filesystem path.
* On web (cloud): primary GitHub repo URL (repos[0]), or workingDirectory if set directly.
*/
-const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined => {
- const activeTopic = currentActiveTopic(s);
- if (!activeTopic) return;
+const extractTopicWorkingDirectory = (topic: ChatTopic | undefined): string | undefined => {
+ if (!topic) return;
// Route the raw `workingDirectory` through the extractor too: it is typed as a
// string, but a malformed legacy topic may have persisted a `WorkingDirConfig`
@@ -97,18 +96,36 @@ const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>
// and this selector's declared `string | undefined` must hold at runtime.
if (isDesktop) {
return getWorkingDirEffectivePath(
- activeTopic.metadata?.workingDirectoryConfig ?? activeTopic.metadata?.workingDirectory,
+ topic.metadata?.workingDirectoryConfig ?? topic.metadata?.workingDirectory,
);
}
// Web: return primary repo from repos list, or workingDirectory if set directly
- const meta = activeTopic.metadata;
+ const meta = topic.metadata;
return (
meta?.repos?.[0] ??
getWorkingDirEffectivePath(meta?.workingDirectoryConfig ?? meta?.workingDirectory)
);
};
+/**
+ * Get a topic's working directory by id, falling back to the active topic when
+ * no id is given. Prefer the explicit-id form for async work (e.g. a streaming
+ * tool call): the executing topic is captured at request time, so reading the
+ * *active* topic here would return the wrong project if the user switched topics
+ * mid-stream.
+ */
+const getTopicWorkingDirectory =
+ (id?: string | null) =>
+ (s: ChatStoreState): string | undefined =>
+ extractTopicWorkingDirectory(id ? getTopicById(id)(s) : currentActiveTopic(s));
+
+/**
+ * Get current active topic's working directory.
+ */
+const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>
+ extractTopicWorkingDirectory(currentActiveTopic(s));
+
const isCreatingTopic = (s: ChatStoreState) => s.creatingTopic;
/**
@@ -287,6 +304,7 @@ export const topicSelectors = {
displayTopics,
displayTopicsForSidebar,
getTopicById,
+ getTopicWorkingDirectory,
getTopicsByAgentId,
groupedTopicsForSidebar,
groupedTopicsSelector,