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(agent): track git side effects of native runCommand calls (#19102)

Arvin Xua82904ccd34a
diff --git a/src/store/tool/slices/builtin/executors/__tests__/localSystem.test.ts b/src/store/tool/slices/builtin/executors/__tests__/localSystem.test.ts
new file mode 100644
index 00000000000..d465beba047
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/__tests__/localSystem.test.ts
@@ -0,0 +1,191 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { localSystemExecutorWithGitEffects } from '../localSystem';
+
+const detectMocks = vi.hoisted(() => ({
+ recordGitCommandEffects: vi.fn(),
+}));
+
+vi.mock('../worktreeDetection', () => ({
+ recordGitCommandEffects: detectMocks.recordGitCommandEffects,
+}));
+
+const localSystemMocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+}));
+
+vi.mock('@lobechat/builtin-tool-local-system/client/executor', () => ({
+ localSystemExecutor: {
+ getApiNames: () => [
+ 'editFile',
+ 'getCommandOutput',
+ 'globFiles',
+ 'grepContent',
+ 'killCommand',
+ 'listFiles',
+ 'moveFiles',
+ 'readFile',
+ 'readFiles',
+ 'runCommand',
+ 'searchFiles',
+ 'writeFile',
+ ],
+ hasApi: (apiName: string) =>
+ [
+ 'editFile',
+ 'getCommandOutput',
+ 'globFiles',
+ 'grepContent',
+ 'killCommand',
+ 'listFiles',
+ 'moveFiles',
+ 'readFile',
+ 'readFiles',
+ 'runCommand',
+ 'searchFiles',
+ 'writeFile',
+ ].includes(apiName),
+ identifier: 'local-system',
+ invoke: localSystemMocks.invoke,
+ },
+}));
+
+/**
+ * Production result shape for a completed native `runCommand`: the runtime
+ * reports top-level `success: true` once the device answered β€” even for a
+ * nonzero exit β€” and the command's terminal outcome rides in `state`.
+ */
+const runResult = (over: Record<string, any> = {}) => ({
+ content: '',
+ state: { exitCode: 0, isBackground: false, success: true },
+ success: true,
+ ...over,
+});
+
+const call = (over: Record<string, any> = {}) => ({
+ apiName: 'runCommand',
+ identifier: 'local-system',
+ params: { command: 'git worktree add /wt' },
+ result: runResult(),
+ topicId: 't1',
+ ...over,
+});
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('localSystemExecutorWithGitEffects', () => {
+ it('delegates invocation and API introspection to the package executor', async () => {
+ expect(localSystemExecutorWithGitEffects.identifier).toBe('local-system');
+ expect(localSystemExecutorWithGitEffects.hasApi('runCommand')).toBe(true);
+ expect(localSystemExecutorWithGitEffects.hasApi('nope')).toBe(false);
+ expect(localSystemExecutorWithGitEffects.getApiNames()).toContain('runCommand');
+
+ const result = { content: 'ok', success: true };
+ localSystemMocks.invoke.mockResolvedValue(result);
+ await expect(
+ localSystemExecutorWithGitEffects.invoke('runCommand', { command: 'ls' }, {
+ messageId: 'm1',
+ } as any),
+ ).resolves.toBe(result);
+ expect(localSystemMocks.invoke).toHaveBeenCalledWith('runCommand', { command: 'ls' }, {
+ messageId: 'm1',
+ } as any);
+ });
+
+ it('records the worktree for a successful runCommand, keyed by the run topic', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(call());
+ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({
+ command: 'git worktree add /wt',
+ resultContent: '',
+ topicId: 't1',
+ });
+ });
+
+ it('passes shell output through so `gh pr create` and push refs are detectable', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({
+ params: { command: 'gh pr create --title "fix thing"' },
+ result: runResult({ content: 'https://github.com/lobehub/lobehub/pull/19082' }),
+ }),
+ );
+
+ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({
+ command: 'gh pr create --title "fix thing"',
+ resultContent: 'https://github.com/lobehub/lobehub/pull/19082',
+ topicId: 't1',
+ });
+ });
+
+ it('skips a failed dispatch β€” the command never ran', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({ result: { content: 'fatal: not a git repository', success: false } }),
+ );
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('skips a command that exited nonzero β€” top-level success only covers dispatch', async () => {
+ // `git switch missing-branch` fails, yet the runtime still answers
+ // `success: true` with the failure nested in state. Recording it would
+ // rewrite the topic branch and drop its upstream/PR binding.
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({
+ params: { command: 'git switch missing-branch' },
+ result: runResult({
+ content: 'fatal: invalid reference: missing-branch\n\nExit code: 1',
+ state: { exitCode: 1, isBackground: false, success: true },
+ }),
+ }),
+ );
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('skips a background command β€” its terminal status is unknown at dispatch', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({
+ result: runResult({
+ state: { commandId: 'shell-1', isBackground: true, success: true },
+ }),
+ }),
+ );
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('skips when the result carries no command state at all', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({ result: { content: '', success: true } }),
+ );
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('skips when the run has no topic', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(call({ topicId: undefined }));
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('is constrained to runCommand β€” ignores the file tools', async () => {
+ // A file tool whose params happen to carry a `command`-shaped field.
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({ apiName: 'writeFile', params: { command: 'git worktree add /wt' } }),
+ );
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('reads only command/cmd, never content', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(
+ call({ params: { content: 'git worktree add /wt' } }),
+ );
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('skips when params carry no command at all', async () => {
+ await localSystemExecutorWithGitEffects.onAfterCall!(call({ params: {} }));
+ expect(detectMocks.recordGitCommandEffects).not.toHaveBeenCalled();
+ });
+
+ it('propagates nothing when recordGitCommandEffects throws β€” hooks are fire-and-forget upstream', async () => {
+ detectMocks.recordGitCommandEffects.mockRejectedValueOnce(new Error('store gone'));
+ await expect(localSystemExecutorWithGitEffects.onAfterCall!(call())).rejects.toThrow(
+ 'store gone',
+ );
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
index 7a8e078cc0c..95be705a4df 100644
--- a/src/store/tool/slices/builtin/executors/catalog.ts
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -10,7 +10,6 @@ import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management
import { imageGenerationExecutor } from '@lobechat/builtin-tool-image-generation/executor';
import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/client/executor';
import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client/executor';
-import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/client/executor';
import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';
@@ -40,6 +39,7 @@ import { topicReferenceExecutor } from './lobe-topic-reference';
import { userInteractionExecutor } from './lobe-user-interaction';
import { webBrowsing } from './lobe-web-browsing';
import { webOnboardingExecutor } from './lobe-web-onboarding';
+import { localSystemExecutorWithGitEffects } from './localSystem';
export const builtinToolExecutors = [
// Hook-only executors for heterogeneous CLI agents β€”
@@ -68,7 +68,7 @@ export const builtinToolExecutors = [
imageGenerationExecutor,
knowledgeBaseExecutor,
browserExecutor,
- localSystemExecutor,
+ localSystemExecutorWithGitEffects,
memoryExecutor,
messageExecutor,
notebookExecutor,
diff --git a/src/store/tool/slices/builtin/executors/localSystem.ts b/src/store/tool/slices/builtin/executors/localSystem.ts
new file mode 100644
index 00000000000..cf16b03965b
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/localSystem.ts
@@ -0,0 +1,78 @@
+import type { RunCommandState } from '@lobechat/builtin-tool-local-system';
+import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/client/executor';
+import type { ToolAfterCallContext } from '@lobechat/types';
+
+import { recordGitCommandEffects } from './worktreeDetection';
+
+/**
+ * Pull the shell command out of `runCommand`'s parsed params. Only reads
+ * `command`/`cmd` β€” never `content` β€” so a file-write tool can't be mistaken
+ * for a shell command. Same contract as the heterogeneous CLI executors'
+ * `readShellCommand`; `runCommand` always ships a string, but accepting the
+ * argv-array form keeps the two paths uniform at zero cost.
+ */
+const readShellCommand = (params: unknown): string | string[] | undefined => {
+ if (!params || typeof params !== 'object') return undefined;
+ const raw = (params as { cmd?: unknown; command?: unknown }).command ?? (params as any).cmd;
+ if (typeof raw === 'string') return raw;
+ if (Array.isArray(raw) && raw.every((t) => typeof t === 'string')) return raw as string[];
+ return undefined;
+};
+
+/**
+ * `result.success` on a native `runCommand` only says the invocation was
+ * dispatched: `ComputerRuntime.runCommand` returns top-level success once the
+ * device answered, even when the spawned command exited nonzero β€” and the shell
+ * layer's own nested `success` bit means merely "no spawn error". The one
+ * signal that proves the command ran to completion and succeeded is a zero
+ * exit code in the nested {@link RunCommandState}, so require exactly that.
+ * Background commands (spawned, terminal status unknown β€” no exit code yet)
+ * and timed-out ones fail closed here: recording a `git switch` that never
+ * happened would overwrite the topic's branch and drop its upstream/PR
+ * binding, which is worse than missing a recording.
+ */
+const commandExitedCleanly = (state: unknown): boolean =>
+ !!state && typeof state === 'object' && (state as RunCommandState).exitCode === 0;
+
+/**
+ * Local System executor wrapped with the shell side-effect recorder.
+ *
+ * The package's own executor handles invocation; this adds the renderer-side
+ * `onAfterCall` hook the dispatcher (`gatewayEventHandler.dispatchOnAfterCall`)
+ * resolves by identifier, so a native agent's `runCommand` calls get the same
+ * git/gh side-effect tracking (`git worktree add` / `git switch` / `git push` /
+ * `gh pr create` β†’ topic metadata) heterogeneous CLI shell calls already have.
+ * Without this hook the topic's branch/PR binding silently misses every worktree
+ * or PR created inside a native-agent run.
+ */
+class LocalSystemExecutorWithGitEffects {
+ readonly identifier = localSystemExecutor.identifier;
+
+ invoke = localSystemExecutor.invoke.bind(localSystemExecutor);
+
+ getApiNames = localSystemExecutor.getApiNames.bind(localSystemExecutor);
+
+ hasApi = localSystemExecutor.hasApi.bind(localSystemExecutor);
+
+ onAfterCall = async ({
+ apiName,
+ params,
+ result,
+ topicId,
+ }: ToolAfterCallContext): Promise<void> => {
+ // Constrain to a `runCommand` bound to a run topic whose command is KNOWN to
+ // have exited zero. The hetero CLI executors get away with `result.success`
+ // alone because their CLIs report the command's outcome there; the native
+ // result reports only dispatch, so the exit code carries the gate here.
+ if (!result.success || !topicId) return;
+ if (apiName !== 'runCommand') return;
+ if (!commandExitedCleanly(result.state)) return;
+
+ const command = readShellCommand(params);
+ if (command === undefined) return;
+
+ await recordGitCommandEffects({ command, resultContent: result.content, topicId });
+ };
+}
+
+export const localSystemExecutorWithGitEffects = new LocalSystemExecutorWithGitEffects();