π€― 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): use embedded CLI for gateway agent runs (#17379)
AmAzing-ec8aec806db4
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex fbc603e38b5..afcb5f971ba 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -51,6 +51,14 @@ jobs:- name: Install depsrun: pnpm install+ - name: Install CLI deps+ run: pnpm install+ working-directory: apps/cli++ - name: Test CLI build configuration+ run: bunx vitest run --config vitest.config.mts --silent='passed-only' tsdown.config.test.ts+ working-directory: apps/cli+- name: Test packages with coveragerun: |for package in $PACKAGES; dodiff --git a/apps/cli/tsdown.config.test.ts b/apps/cli/tsdown.config.test.tsnew file mode 100644index 00000000000..15bda81b077--- /dev/null+++ b/apps/cli/tsdown.config.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from 'vitest';++import config from './tsdown.config';++describe('CLI build configuration', () => {+ it('bundles ws so the desktop-embedded CLI runs without node_modules', () => {+ expect(config).toEqual(+ expect.objectContaining({+ deps: expect.objectContaining({ alwaysBundle: expect.arrayContaining(['ws']) }),+ }),+ );+ });+});diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.tsindex cbe2b912360..3b3505e7be1 100644--- a/apps/cli/tsdown.config.ts+++ b/apps/cli/tsdown.config.ts@@ -4,6 +4,11 @@ export default defineConfig({banner: { js: '#!/usr/bin/env node' },clean: true,deps: {+ // The desktop app executes this bundle directly from Resources/bin, where+ // the published package's node_modules tree does not exist. Keep the only+ // production dependency inside the bundle so the embedded CLI is truly+ // self-contained instead of failing at startup with ERR_MODULE_NOT_FOUND.+ alwaysBundle: ['ws'],neverBundle: ['@napi-rs/canvas'],},entry: ['src/index.ts'],diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex d5fb2f893ee..8d4a28c2f8c 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -323,10 +323,11 @@ export default class GatewayConnectionCtr extends ControllerModule {const accessToken = await this.remoteServerConfigCtr.getAccessToken();const jwt = accessToken || request.jwt;- // Fire-and-forget: lh hetero exec handles spawn -> adapt ->- // BatchIngester -> heteroIngest/heteroFinish -> server -> Gateway -> clients.- // Same command as spawnHeteroSandbox() on the server side.- this.heterogeneousAgentCtr.spawnLhHeteroExec({+ // The embedded CLI handles spawn -> adapt -> BatchIngester ->+ // heteroIngest/heteroFinish -> server -> Gateway -> clients. Wait until+ // the process has actually spawned (or emitted an early error) before+ // acknowledging the server request.+ return await this.heterogeneousAgentCtr.spawnLhHeteroExec({agentType: request.agentType,args: request.args,cwd: request.cwd,@@ -339,8 +340,6 @@ export default class GatewayConnectionCtr extends ControllerModule {systemContext: request.systemContext,topicId: request.topicId,});-- return { status: 'accepted' };} catch (err) {const reason = err instanceof Error ? err.message : String(err);return { reason, status: 'rejected' };diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex c8e9aadeda9..ef7ee18def4 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -1,7 +1,7 @@import type { ChildProcess } from 'node:child_process';import { spawn } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { unlinkSync } from 'node:fs';+import { existsSync, unlinkSync } from 'node:fs';import { access, appendFile, mkdir, unlink, writeFile } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';@@ -53,6 +53,7 @@ import { app as electronApp, BrowserWindow } from 'electron';import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';import { detectHeterogeneousCliCommand } from '@/modules/binaries';+import { resolveCliScript } from '@/modules/cliEmbedding';import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';import { buildBrowserMcpTools } from '@/modules/heterogeneousAgent/browserMcpTools';import { fetchClaudeCodeQuota } from '@/modules/heterogeneousAgent/claudeCodeQuota';@@ -1899,10 +1900,14 @@ export default class HeterogeneousAgentCtr extends ControllerModule {}/**- * Spawn `lh hetero exec` for gateway-driven agent runs.- * The `lh` CLI handles everything downstream β no local+ * Spawn the embedded CLI's `hetero exec` for gateway-driven agent runs.+ * The bundled CLI handles everything downstream β no local* AgentStreamPipeline or IPC broadcast needed. Mirrors* `spawnHeteroSandbox()` on the server side.+ *+ * Resolves only after the child either starts or fails to start. Node reports+ * failures such as an inaccessible cwd asynchronously through `error`, so an+ * eager accepted ack would strand the server operation without a producer.*/spawnLhHeteroExec(params: {agentType: string;@@ -1918,7 +1923,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {serverUrl: string;systemContext?: string;topicId: string;- }): void {+ }): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {const {agentType,args: extraArgs,@@ -1962,35 +1967,75 @@ export default class HeterogeneousAgentCtr extends ControllerModule {...(extraArgs ?? []),];+ const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });+ const cliScript = resolveCliScript();+ if (!existsSync(cliScript)) {+ return Promise.resolve({+ reason: `Embedded CLI not found at ${cliScript}`,+ status: 'rejected',+ });+ }+const env = {...process.env,...buildProxyEnv(this.app.storeManager.get('networkProxy')),+ ELECTRON_RUN_AS_NODE: '1',LOBEHUB_JWT: jwt,LOBEHUB_SERVER: serverUrl,};logger.info('spawnLhHeteroExec: type=%s op=%s topic=%s', agentType, operationId, topicId);- const child = spawn('lh', args, {+ // Execute the CLI shipped with this desktop build. A bare `lh` would prefer+ // an older global install earlier on PATH, letting model discovery report a+ // capability that the actual execution runtime does not support.+ const child = spawn(process.execPath, [cliScript, ...args], {cwd: workDir,env,stdio: ['pipe', 'inherit', 'inherit'],});- // systemContext / image attachments turn the payload into a content-block- // array so CC sees the context block first, then the user's message, then- // the images β mirrors spawnHeteroSandbox. lh handles both shapes via- // coerceJsonPrompt, so no lh changes are required.- const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });- child.stdin.write(stdinPayload);- child.stdin.end();-- child.on('error', (err) => {- logger.error('spawnLhHeteroExec: spawn failed β %s', err.message);- });-child.on('exit', (code, signal) => {logger.info('spawnLhHeteroExec: exited β op=%s code=%s signal=%s', operationId, code, signal);});++ return new Promise((resolve) => {+ let settled = false;+ const settle = (result: { reason?: string; status: 'accepted' | 'rejected' }) => {+ if (settled) return;+ settled = true;+ resolve(result);+ };++ child.stdin.once('error', (err) => {+ logger.error(+ 'spawnLhHeteroExec: stdin write failed β op=%s error=%s',+ operationId,+ err.message,+ );+ settle({ reason: err.message, status: 'rejected' });+ });++ child.once('spawn', () => {+ try {+ child.stdin.write(stdinPayload);+ child.stdin.end();+ settle({ status: 'accepted' });+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ logger.error(+ 'spawnLhHeteroExec: stdin write threw β op=%s error=%s',+ operationId,+ reason,+ );+ settle({ reason, status: 'rejected' });+ }+ });++ child.once('error', (err) => {+ logger.error('spawnLhHeteroExec: spawn failed β %s', err.message);+ settle({ reason: err.message, status: 'rejected' });+ });+ });}}diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 6894b3ecf6e..cb46adb2b5e 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -244,7 +244,7 @@ const mockShellCommandCtr = {const mockHeterogeneousAgentCtr = {sendPrompt: vi.fn().mockResolvedValue(undefined),- spawnLhHeteroExec: vi.fn(),+ spawnLhHeteroExec: vi.fn().mockResolvedValue({ status: 'accepted' }),startSession: vi.fn().mockResolvedValue({ sessionId: 'mock-session-id' }),} as unknown as HeterogeneousAgentCtr;@@ -834,7 +834,7 @@ describe('GatewayConnectionCtr', () => {vi.mocked(mockHeterogeneousAgentCtr.spawnLhHeteroExec).mockClear();});- it.each(['openclaw', 'hermes', 'codex', 'claude-code'] as const)(+ it.each(['openclaw', 'hermes', 'codex', 'claude-code', 'opencode'] as const)('forwards agentType "%s" to spawnLhHeteroExec',async (agentType) => {const client = await connectAndOpen();@@ -958,6 +958,23 @@ describe('GatewayConnectionCtr', () => {status: 'rejected',});});++ it('forwards an asynchronous spawn rejection instead of acknowledging accepted', async () => {+ vi.mocked(mockHeterogeneousAgentCtr.spawnLhHeteroExec).mockResolvedValueOnce({+ reason: 'spawn EACCES',+ status: 'rejected',+ });++ const client = await connectAndOpen();+ client.simulateAgentRunRequest('opencode', 'op-spawn-fail');+ await vi.advanceTimersByTimeAsync(0);++ expect(client.sendAgentRunAck).toHaveBeenCalledWith({+ operationId: 'op-spawn-fail',+ reason: 'spawn EACCES',+ status: 'rejected',+ });+ });});// βββ runHeteroTask βββdiff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex a55663c3bce..4e7b09842d2 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -1,4 +1,5 @@import { EventEmitter } from 'node:events';+import { existsSync } from 'node:fs';import { access, mkdtemp, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';import * as os from 'node:os';import path from 'node:path';@@ -18,6 +19,11 @@ vi.mock('node:os', async () => {return { ...actual, platform: vi.fn(() => 'linux') };});+vi.mock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return { ...actual, existsSync: vi.fn(() => true) };+});+const FAKE_DESKTOP_PATH = '/Users/fake/Desktop';const { mockGetAllWindows } = vi.hoisted(() => ({@@ -1332,6 +1338,131 @@ describe('HeterogeneousAgentCtr', () => {});});+ describe('spawnLhHeteroExec', () => {+ const params = {+ agentType: 'opencode',+ jwt: 'device-jwt',+ operationId: 'op-gateway',+ prompt: 'inspect the repository',+ serverUrl: 'https://server.example.com',+ topicId: 'topic-gateway',+ };++ const createGatewayCliProc = () => {+ const proc = new EventEmitter() as any;+ const stdin = new EventEmitter() as any;+ stdin.end = vi.fn();+ stdin.write = vi.fn(() => true);+ proc.stdin = stdin;+ return proc;+ };++ beforeEach(() => {+ vi.mocked(existsSync).mockReturnValue(true);+ spawnCalls.length = 0;+ nextFakeProc = null;+ });++ it('uses the self-contained embedded CLI instead of a global lh from PATH', async () => {+ const proc = createGatewayCliProc();+ nextFakeProc = proc;+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const ack = ctr.spawnLhHeteroExec(params);++ expect(spawnCalls).toHaveLength(1);+ const [spawnCall] = spawnCalls;+ expect(spawnCall.command).toBe(process.execPath);+ expect(spawnCall.args.slice(0, 7)).toEqual([+ '/fake/cli/dist/index.js',+ 'hetero',+ 'exec',+ '--type',+ 'opencode',+ '--operation-id',+ 'op-gateway',+ ]);+ expect(spawnCall.options.env).toEqual(+ expect.objectContaining({+ ELECTRON_RUN_AS_NODE: '1',+ LOBEHUB_JWT: 'device-jwt',+ LOBEHUB_SERVER: 'https://server.example.com',+ }),+ );+ expect(proc.stdin.write).not.toHaveBeenCalled();++ proc.emit('spawn');++ await expect(ack).resolves.toEqual({ status: 'accepted' });+ expect(proc.stdin.write).toHaveBeenCalledOnce();+ expect(proc.stdin.end).toHaveBeenCalledOnce();+ });++ it('rejects the gateway request when the embedded CLI cannot spawn', async () => {+ const proc = createGatewayCliProc();+ nextFakeProc = proc;+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const ack = ctr.spawnLhHeteroExec(params);+ proc.emit('error', new Error('spawn EACCES'));++ await expect(ack).resolves.toEqual({ reason: 'spawn EACCES', status: 'rejected' });+ expect(proc.stdin.write).not.toHaveBeenCalled();+ });++ it('rejects before spawn when the embedded CLI is missing', async () => {+ vi.mocked(existsSync).mockReturnValueOnce(false);+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ await expect(ctr.spawnLhHeteroExec(params)).resolves.toEqual({+ reason: 'Embedded CLI not found at /fake/cli/dist/index.js',+ status: 'rejected',+ });+ expect(spawnCalls).toHaveLength(0);+ });++ it('rejects a synchronous stdin write failure without throwing from the event handler', async () => {+ const proc = createGatewayCliProc();+ proc.stdin.write.mockImplementationOnce(() => {+ throw new Error('write EPIPE');+ });+ nextFakeProc = proc;+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const ack = ctr.spawnLhHeteroExec(params);+ expect(() => proc.emit('spawn')).not.toThrow();++ await expect(ack).resolves.toEqual({ reason: 'write EPIPE', status: 'rejected' });+ });++ it('handles a late stdin EPIPE after acceptance without an uncaught stream error', async () => {+ const proc = createGatewayCliProc();+ nextFakeProc = proc;+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const ack = ctr.spawnLhHeteroExec(params);+ proc.emit('spawn');+ await expect(ack).resolves.toEqual({ status: 'accepted' });++ expect(() => proc.stdin.emit('error', new Error('write EPIPE'))).not.toThrow();+ });+ });+/*** Node may emit `proc.on('exit')` BEFORE stdout fully drains (documented in* child_process docs as "stdio streams might still be open"). The phase 0