π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(desktop): run lh commands through the regular command runner (#19988)
Arvin Xu74bcf4f4821e
diff --git a/apps/desktop/src/main/controllers/CliCtr.ts b/apps/desktop/src/main/controllers/CliCtr.tsindex f99a61ea4d9..7d0727c5cdd 100644--- a/apps/desktop/src/main/controllers/CliCtr.ts+++ b/apps/desktop/src/main/controllers/CliCtr.ts@@ -18,14 +18,27 @@ function normalizeServerUrl(url: string): string {export default class CliCtr extends ControllerModule {static override readonly groupName = 'cli';- @IpcMethod()- async runCliCommand(args: string): Promise<{ exitCode: number; stderr: string; stdout: string }> {- const execAsync = promisify(exec);- const wrapperDir = getCliWrapperDir();- const cmd = process.platform === 'win32' ? 'lobehub.cmd' : 'lobehub';- const wrapperPath = path.join(wrapperDir, cmd);+ /**+ * Environment for running the embedded CLI: the caller's own variables, the+ * wrapper directory first on `PATH` (so `lh` / `lobe` / `lobehub` resolve to+ * the bundled CLI rather than whatever else is installed), and β when the+ * app is signed in β the credentials the CLI authenticates with.+ *+ * Returned as overrides layered on top of `process.env` by the runner.+ */+ async buildCliEnv(baseEnv: Record<string, string> = {}): Promise<Record<string, string>> {+ const env: Record<string, string> = { ...baseEnv };- const env = { ...process.env };+ // Windows spells it `Path`, and a second, differently-cased key next to it+ // would leave which one the child sees up to chance β reuse the existing key.+ const pathKey =+ Object.keys(baseEnv).find((key) => key.toUpperCase() === 'PATH') ??+ Object.keys(process.env).find((key) => key.toUpperCase() === 'PATH') ??+ 'PATH';+ const currentPath = baseEnv[pathKey] ?? process.env[pathKey];+ env[pathKey] = currentPath+ ? `${getCliWrapperDir()}${path.delimiter}${currentPath}`+ : getCliWrapperDir();const remoteCtr = this.app.getController(RemoteServerConfigCtr);if (remoteCtr) {@@ -41,6 +54,23 @@ export default class CliCtr extends ControllerModule {}}+ return env;+ }++ /**+ * Quick CLI invocation for the settings page's "test CLI" box. Agent+ * `runCommand` calls do not come through here β they run in the regular+ * command runner (see `ShellCommandCtr.handleRunCommand`).+ */+ @IpcMethod()+ async runCliCommand(args: string): Promise<{ exitCode: number; stderr: string; stdout: string }> {+ const execAsync = promisify(exec);+ const wrapperDir = getCliWrapperDir();+ const cmd = process.platform === 'win32' ? 'lobehub.cmd' : 'lobehub';+ const wrapperPath = path.join(wrapperDir, cmd);++ const env = { ...process.env, ...(await this.buildCliEnv()) };+try {const { stdout, stderr } = await execAsync(`"${wrapperPath}" ${args}`, {env,diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.tsindex 046d9a904b1..bfad7d2f7c4 100644--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts@@ -40,7 +40,7 @@ const processManager = new ShellProcessManager();*/const safeSegment = (value: string): string => value.replaceAll(/[^\w-]/g, '') || 'default';-/** Prefix for a simple `lh`/`lobe`/`lobehub` invocation (keyword + boundary, args via slice). */+/** A command that starts with an `lh`/`lobe`/`lobehub` invocation (keyword + boundary). */const SIMPLE_LH_PREFIX = /^\s*(?:lh|lobe|lobehub)(?=\s|$)/;export default class ShellCommandCtr extends ControllerModule {@@ -241,8 +241,7 @@ export default class ShellCommandCtr extends ControllerModule {@IpcMethod()async handleRunCommand(params: RunCommandParams): Promise<RunCommandResult> {- const prefixMatch = SIMPLE_LH_PREFIX.exec(params.command);- if (prefixMatch) {+ if (SIMPLE_LH_PREFIX.test(params.command)) {const cliCtr = this.app.getController(CliCtr);if (cliCtr) {// Deliberate carve-out: `lh` keeps its in-app route even for a@@ -252,16 +251,16 @@ export default class ShellCommandCtr extends ControllerModule {// would not harden anything the model can reach through it; it would// just break agent self-management. The sandbox's promise is about// model-authored shell commands, and this is not one.- const args = params.command.slice(prefixMatch[0].length).trim();- logger.debug('Routing lh command to CliCtr.runCliCommand:', args);- const result = await cliCtr.runCliCommand(args);- return {- exit_code: result.exitCode,- output: result.stdout + result.stderr,- stderr: result.stderr,- stdout: result.stdout,- success: result.exitCode === 0,- };+ //+ // Otherwise it is an ordinary command: same shell (PowerShell on+ // Windows), the caller's `cwd` / `env` / `timeout`, and the same result+ // shape β a non-zero exit carries its output, and a command still+ // running at the deadline is reported as running, not killed. Only the+ // environment differs: the bundled CLI first on `PATH`, plus the+ // credentials it authenticates with.+ logger.debug('Running lh command with the embedded CLI environment');+ const env = await cliCtr.buildCliEnv(params.env);+ return runCommand({ ...params, env }, { logger, processManager });}}diff --git a/apps/desktop/src/main/controllers/__tests__/CliCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/CliCtr.test.tsnew file mode 100644index 00000000000..4e714154e0e--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/CliCtr.test.ts@@ -0,0 +1,78 @@+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import CliCtr from '../CliCtr';+import RemoteServerConfigCtr from '../RemoteServerConfigCtr';++vi.mock('electron', () => ({+ ipcMain: { handle: vi.fn() },+}));++vi.mock('@/modules/cliEmbedding', () => ({+ getCliWrapperDir: () => '/app/userData/bin',+}));++vi.mock('../RemoteServerConfigCtr', () => ({+ default: class RemoteServerConfigCtr {},+}));++const mockRemoteCtr = {+ getAccessToken: vi.fn(),+ getRemoteServerUrl: vi.fn(),+};++const mockApp = {+ getController: vi.fn((c: unknown) => (c === RemoteServerConfigCtr ? mockRemoteCtr : undefined)),+} as unknown as App;++describe('CliCtr.buildCliEnv', () => {+ let ctr: CliCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ mockRemoteCtr.getAccessToken.mockResolvedValue('jwt-token');+ mockRemoteCtr.getRemoteServerUrl.mockResolvedValue('https://app.example.com/');+ ctr = new CliCtr(mockApp);+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('keeps the caller env and injects the credentials', async () => {+ const env = await ctr.buildCliEnv({ DS_KEY: 'sk-real-secret' });++ expect(env).toMatchObject({+ DS_KEY: 'sk-real-secret',+ LOBEHUB_JWT: 'jwt-token',+ LOBEHUB_SERVER: 'https://app.example.com',+ });+ });++ it('puts the bundled CLI first on PATH so lh resolves to it', async () => {+ vi.stubEnv('PATH', `/usr/local/bin${path.delimiter}/usr/bin`);++ const env = await ctr.buildCliEnv();++ expect(env.PATH).toBe(`/app/userData/bin${path.delimiter}/usr/local/bin${path.delimiter}/usr/bin`);+ });++ it('prepends to a PATH the caller overrode instead of discarding it', async () => {+ const env = await ctr.buildCliEnv({ PATH: '/custom/bin' });++ expect(env.PATH).toBe(`/app/userData/bin${path.delimiter}/custom/bin`);+ });++ it('does not inject credentials when the app is not signed in', async () => {+ mockRemoteCtr.getAccessToken.mockResolvedValue(null);++ const env = await ctr.buildCliEnv({ FOO: 'bar' });++ expect(env.FOO).toBe('bar');+ expect(env).not.toHaveProperty('LOBEHUB_JWT');+ expect(env).not.toHaveProperty('LOBEHUB_SERVER');+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.tsindex 14d7c44646a..d4b5c279c83 100644--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts@@ -1,7 +1,8 @@-import { existsSync, rmSync, writeSync } from 'node:fs';-import { homedir } from 'node:os';-import { join, relative } from 'node:path';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, writeSync } from 'node:fs';+import { homedir, tmpdir } from 'node:os';+import { delimiter, dirname, join, relative } from 'node:path';+import { resetShellDetectionCache } from '@lobechat/local-file-shell/shell';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -55,6 +56,12 @@ vi.mock('@lobechat/device-sandbox', () => ({}));const mockCliCtr = {+ buildCliEnv: vi.fn(async (env: Record<string, string> = {}) => ({+ ...env,+ LOBEHUB_JWT: 'jwt-token',+ LOBEHUB_SERVER: 'https://app.example.com',+ PATH: `/cli/bin${delimiter}${process.env.PATH ?? ''}`,+ })),runCliCommand: vi.fn().mockResolvedValue({ exitCode: 0, stderr: '', stdout: 'cli output\n' }),};@@ -176,26 +183,115 @@ describe('ShellCommandCtr (thin wrapper)', () => {expect(mockChildProcess.kill).toHaveBeenCalled();});- it('should route lh commands to CliCtr.runCliCommand', async () => {- const result = await ctr.handleRunCommand({- command: 'lh status --json',- description: 'lh status',+ describe('lh commands', () => {+ // Exit only once the child has been spawned: shell detection runs first+ // and can outlast a fixed delay on a busy machine.+ const exitWith = (code: number) => {+ const spawnChild = mockSpawn.getMockImplementation();+ mockSpawn.mockImplementationOnce((...args: unknown[]) => {+ const child = spawnChild(...args);+ setTimeout(() => {+ mockChildProcess.exitCode = code;+ emitChildProcess('exit', code);+ emitChildProcess('close', code);+ }, 10);+ return child;+ });+ };++ it('runs through the shared runner with the caller env, cwd and the injected CLI env', async () => {+ mockProcessOutput = 'ok\n';+ exitWith(0);++ const command = 'lh provider config deepseek --api-key "$DS_KEY"';+ const result = await ctr.handleRunCommand({+ command,+ cwd: '/work/project',+ env: { DS_KEY: 'sk-real-secret' },+ });++ expect(mockCliCtr.buildCliEnv).toHaveBeenCalledWith({ DS_KEY: 'sk-real-secret' });+ expect(mockCliCtr.runCliCommand).not.toHaveBeenCalled();+ expect(mockSpawn).toHaveBeenCalledTimes(1);+ const [cmd, args, options] = mockSpawn.mock.calls[0];+ // The same shell as every other command β the command string is handed+ // over untouched so the shell expands the caller's variables.+ expect(cmd).toBe('/bin/sh');+ expect(args).toEqual(['-c', command]);+ expect(options.cwd).toBe('/work/project');+ expect(options.env).toMatchObject({+ DS_KEY: 'sk-real-secret',+ LOBEHUB_JWT: 'jwt-token',+ LOBEHUB_SERVER: 'https://app.example.com',+ });+ expect(options.env.PATH.split(delimiter)[0]).toBe('/cli/bin');+ expect(result.success).toBe(true);+ expect(result.output).toContain('ok');});- expect(mockCliCtr.runCliCommand).toHaveBeenCalledWith('status --json');- expect(result.success).toBe(true);- expect(result.output).toContain('cli output');- expect(mockSpawn).not.toHaveBeenCalled();- });+ it('runs in PowerShell on Windows, not cmd.exe', async () => {+ const programFiles = mkdtempSync(join(tmpdir(), 'lh-pwsh-'));+ const pwshPath = join(programFiles, 'PowerShell', '7', 'pwsh.exe');+ mkdirSync(dirname(pwshPath), { recursive: true });+ writeFileSync(pwshPath, '');+ vi.stubEnv('ProgramFiles', programFiles);+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;+ Object.defineProperty(process, 'platform', { value: 'win32' });+ resetShellDetectionCache();++ try {+ exitWith(0);+ await ctr.handleRunCommand({+ command: 'lh bot add qq --app-secret $env:QQ_BOT_SECRET',+ env: { QQ_BOT_SECRET: 'real-secret' },+ });- it('should route lobehub commands to CliCtr.runCliCommand', async () => {- const result = await ctr.handleRunCommand({- command: 'lobehub search test',- description: 'lobehub search',+ expect(mockSpawn).toHaveBeenCalledTimes(1);+ const [cmd, , options] = mockSpawn.mock.calls[0];+ expect(cmd).toBe(pwshPath);+ expect(cmd).not.toMatch(/cmd\.exe$/i);+ expect(options.env).toMatchObject({ QQ_BOT_SECRET: 'real-secret' });+ } finally {+ Object.defineProperty(process, 'platform', platform);+ vi.unstubAllEnvs();+ resetShellDetectionCache();+ rmSync(programFiles, { force: true, recursive: true });+ }});- expect(mockCliCtr.runCliCommand).toHaveBeenCalledWith('search test');- expect(result.success).toBe(true);+ it('returns the output of a non-zero exit as a normal command result', async () => {+ mockProcessOutput = 'β Provider deepseek check failed\nError: InvalidProviderAPIKey\n';+ exitWith(1);++ const result = await ctr.handleRunCommand({ command: 'lh provider test deepseek' });++ expect(result.success).toBe(true);+ expect(result.exit_code).toBe(1);+ expect(result.stdout).toContain('Error: InvalidProviderAPIKey');+ });++ it('reports a command that outlives the timeout as still running instead of killing it', async () => {+ const result = await ctr.handleRunCommand({+ command: 'lobehub bot add qq',+ timeout: 100,+ });++ expect(result.success).toBe(true);+ expect((result as { running?: boolean }).running).toBe(true);+ expect(result.exit_code).toBeUndefined();+ expect(result.shell_id).toBeTruthy();+ expect(mockChildProcess.kill).not.toHaveBeenCalled();+ });++ it('keeps lh out of the sandbox so the injected credentials still reach it', async () => {+ exitWith(0);++ await ctr.handleRunCommand({ command: 'lh status', cwd: '/repo', sandbox: true });++ expect(mockProbeSandboxCapability).not.toHaveBeenCalled();+ expect(mockCreateSandboxLaunchPlan).not.toHaveBeenCalled();+ expect(mockSpawn.mock.calls[0][2].env).toMatchObject({ LOBEHUB_JWT: 'jwt-token' });+ });});describe('local sandbox', () => {diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.tsindex a1867f5af82..f2c6007e42c 100644--- a/packages/tool-runtime/src/ComputerRuntime.ts+++ b/packages/tool-runtime/src/ComputerRuntime.ts@@ -642,12 +642,14 @@ export abstract class ComputerRuntime {// 2. JSON.stringify(result.error) (non-Error error objects)// 3. state.stderr (e.g. git commit failure β exit β 0, error in stderr)// 4. state.error (runtime-level error message)- // 5. [UNKNOWN_EXEC_ERROR] Tool execution failed (last-resort fallback)+ // 5. state.stdout (CLIs that print their failure on stdout and exit β 0)+ // 6. [UNKNOWN_EXEC_ERROR] Tool execution failed (last-resort fallback)const errorText =result.error?.message ||(result.error !== undefined ? JSON.stringify(result.error) : undefined) ||(typeof state?.stderr === 'string' ? state.stderr : undefined) ||(typeof state?.error === 'string' ? state.error : undefined) ||+ (typeof state?.stdout === 'string' ? state.stdout : undefined) ||'[UNKNOWN_EXEC_ERROR] Tool execution failed';return {diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.tsindex 3118c90adf7..d2117df503a 100644--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts@@ -752,6 +752,28 @@ describe('LocalSystemExecutionRuntime.runCommand', () => {expect(output.content).not.toContain('UNKNOWN_EXEC_ERROR');});+ it('keeps stdout when a failed command reports neither an error nor stderr', async () => {+ // A CLI that prints its failure on stdout and exits non-zero, reported+ // with `success: false` and nothing else to explain it. The generic+ // fallback used to replace the only diagnostic the model could act on.+ const service = createService({+ runCommand: vi.fn().mockResolvedValue({+ exit_code: 1,+ stderr: '',+ stdout: 'β Provider deepseek check failed\nError: InvalidProviderAPIKey\n',+ success: false,+ }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.executeToolCall('runCommand', {+ command: 'lh provider test deepseek',+ });++ expect(output?.content).toContain('Error: InvalidProviderAPIKey');+ expect(output?.content).not.toContain('UNKNOWN_EXEC_ERROR');+ });+it('reports whether the command was actually sandboxed', async () => {const service = createService({runCommand: vi.fn().mockResolvedValue({