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.

✨ feat(platform-agent): improve device selection UX with actionable guidance (#15111)

LiJiana35877f67698
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1
index c29cba4c59b..2f3e5a916dc 100644
--- a/apps/cli/man/man1/lh.1
+++ b/apps/cli/man/man1/lh.1
@@ -1,6 +1,6 @@
.\" Code generated by `npm run man:generate`; DO NOT EDIT.
.\" Manual command details come from the Commander command tree.
-.TH LH 1 "" "@lobehub/cli 0.0.18" "User Commands"
+.TH LH 1 "" "@lobehub/cli 0.0.20" "User Commands"
.SH NAME
lh \- LobeHub CLI \- manage and connect to LobeHub services
.SH SYNOPSIS
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 5e530716cf1..8ddd95be34f 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@lobehub/cli",
- "version": "0.0.18",
+ "version": "0.0.20",
"type": "module",
"bin": {
"lh": "./dist/index.js",
diff --git a/apps/cli/src/tools/__tests__/heteroTask.test.ts b/apps/cli/src/tools/__tests__/heteroTask.test.ts
new file mode 100644
index 00000000000..c2e6a775b45
--- /dev/null
+++ b/apps/cli/src/tools/__tests__/heteroTask.test.ts
@@ -0,0 +1,251 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { removeTask, saveTask } from '../../daemon/taskRegistry';
+import { runHeteroTask } from '../heteroTask';
+
+// ─── Mocks ───
+
+const spawnMock = vi.hoisted(() => vi.fn());
+const execFileSyncMock = vi.hoisted(() => vi.fn());
+
+vi.mock('node:child_process', () => ({
+ execFileSync: execFileSyncMock,
+ spawn: spawnMock,
+}));
+
+// task registry — use real implementation backed by a temporary in-memory map
+const taskStore: Record<string, any> = {};
+vi.mock('../../daemon/taskRegistry', () => ({
+ getTask: vi.fn((id: string) => taskStore[id]),
+ listTasks: vi.fn(() => Object.values(taskStore)),
+ removeTask: vi.fn((id: string) => {
+ delete taskStore[id];
+ }),
+ saveTask: vi.fn((entry: any) => {
+ taskStore[entry.taskId] = entry;
+ }),
+}));
+
+vi.mock('../../api/client', () => ({
+ getTrpcClient: vi.fn().mockResolvedValue({
+ agentNotify: {
+ notify: { mutate: vi.fn().mockResolvedValue(undefined) },
+ },
+ }),
+}));
+
+vi.mock('../../utils/logger', () => ({
+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+// ─── Helpers ───
+
+function makeMockChild(pid = 9999) {
+ const listeners: Record<string, Array<(...a: any[]) => void>> = {};
+ return {
+ on: vi.fn((event: string, cb: (...a: any[]) => void) => {
+ (listeners[event] ??= []).push(cb);
+ }),
+ pid,
+ unref: vi.fn(),
+ _emit: (event: string, ...args: any[]) => listeners[event]?.forEach((cb) => cb(...args)),
+ };
+}
+
+// ─── Tests ───
+
+describe('runHeteroTask (openclaw)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Clear task store
+ for (const key of Object.keys(taskStore)) delete taskStore[key];
+ execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('always injects buildNotifyProtocol into the prompt regardless of session history', async () => {
+ const child = makeMockChild();
+ spawnMock.mockReturnValue(child);
+
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'what time is it',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
+ const msgIdx = spawnArgs.indexOf('--message');
+ const messageArg = spawnArgs[msgIdx + 1];
+
+ expect(messageArg).toContain('what time is it');
+ expect(messageArg).toContain('lh notify');
+ expect(messageArg).toContain('MSG_ID');
+ });
+
+ it('always injects protocol even on the second turn of the same session', async () => {
+ const child1 = makeMockChild(1111);
+ const child2 = makeMockChild(2222);
+ spawnMock.mockReturnValueOnce(child1).mockReturnValueOnce(child2);
+
+ // First turn
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'hello',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ // Simulate process exit so task is removed
+ child1._emit('close', 0, null);
+
+ // Second turn (same topicId)
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-2',
+ prompt: 'follow up',
+ taskId: 'task-2',
+ topicId: 'topic-1',
+ });
+
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ for (const call of spawnMock.mock.calls) {
+ const args = call[1] as string[];
+ const msg = args[args.indexOf('--message') + 1];
+ expect(msg).toContain('lh notify');
+ }
+ });
+
+ it('kills an existing concurrent process for the same topicId before spawning', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const child1 = makeMockChild(1111);
+ spawnMock.mockReturnValueOnce(child1);
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'msg1',
+ taskId: 'task-1',
+ topicId: 'topic-same',
+ });
+ // task-1 is still "running" (close not fired)
+
+ const child2 = makeMockChild(2222);
+ spawnMock.mockReturnValueOnce(child2);
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-2',
+ prompt: 'msg2',
+ taskId: 'task-2',
+ topicId: 'topic-same',
+ });
+
+ expect(killSpy).toHaveBeenCalledWith(1111, 'SIGTERM');
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not kill processes for a different topicId', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const child1 = makeMockChild(3333);
+ spawnMock.mockReturnValueOnce(child1);
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'a',
+ taskId: 'task-a',
+ topicId: 'topic-A',
+ });
+
+ const child2 = makeMockChild(4444);
+ spawnMock.mockReturnValueOnce(child2);
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-2',
+ prompt: 'b',
+ taskId: 'task-b',
+ topicId: 'topic-B',
+ });
+
+ expect(killSpy).not.toHaveBeenCalled();
+ });
+
+ it('saves task entry with correct fields after spawn', async () => {
+ const child = makeMockChild(5555);
+ spawnMock.mockReturnValue(child);
+
+ await runHeteroTask({
+ agentId: 'agent-1',
+ agentType: 'openclaw',
+ operationId: 'op-x',
+ prompt: 'test',
+ taskId: 'task-x',
+ topicId: 'topic-x',
+ });
+
+ expect(saveTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentType: 'openclaw',
+ pid: 5555,
+ taskId: 'task-x',
+ topicId: 'topic-x',
+ }),
+ );
+ });
+
+ it('passes --session-id and --agent args to openclaw', async () => {
+ const child = makeMockChild();
+ spawnMock.mockReturnValue(child);
+
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'hello',
+ taskId: 'task-1',
+ topicId: 'my-topic-id',
+ });
+
+ const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
+ expect(spawnArgs).toContain('--session-id');
+ expect(spawnArgs[spawnArgs.indexOf('--session-id') + 1]).toBe('my-topic-id');
+ expect(spawnArgs).toContain('--agent');
+ expect(spawnArgs).toContain('--local');
+ });
+
+ it('removes task and ignores already-exited process when killing concurrent task', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw new Error('No such process');
+ });
+
+ const child1 = makeMockChild(7777);
+ spawnMock.mockReturnValueOnce(child1);
+ await runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'msg1',
+ taskId: 'task-1',
+ topicId: 'topic-gone',
+ });
+
+ const child2 = makeMockChild(8888);
+ spawnMock.mockReturnValueOnce(child2);
+ // Should not throw even though kill fails
+ await expect(
+ runHeteroTask({
+ agentType: 'openclaw',
+ operationId: 'op-2',
+ prompt: 'msg2',
+ taskId: 'task-2',
+ topicId: 'topic-gone',
+ }),
+ ).resolves.not.toThrow();
+
+ expect(removeTask).toHaveBeenCalledWith('task-1');
+ killSpy.mockRestore();
+ });
+});
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.ts
index a1b2219f6ef..99b61766dee 100644
--- a/apps/cli/src/tools/heteroTask.ts
+++ b/apps/cli/src/tools/heteroTask.ts
@@ -3,7 +3,7 @@ import { execFileSync, spawn } from 'node:child_process';
import type { RemoteHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import { getTrpcClient } from '../api/client';
-import { getTask, removeTask, saveTask } from '../daemon/taskRegistry';
+import { getTask, listTasks, removeTask, saveTask } from '../daemon/taskRegistry';
import { log } from '../utils/logger';
const DEFAULT_HERMES_PORT = 3456;
@@ -17,24 +17,6 @@ function resolveLhPath(): string {
}
}
-/**
- * Check whether an openclaw session already exists for the given topicId.
- * The session key format is `agent:<agentId>:explicit:<sessionId>`.
- * Returns false on any error so that callers default to injecting the full protocol.
- */
-function openclawSessionExists(agentId: string, topicId: string): boolean {
- try {
- const raw = execFileSync('openclaw', ['sessions', '--agent', agentId, '--json'], {
- encoding: 'utf8',
- });
- const data = JSON.parse(raw) as { sessions?: Array<{ key: string }> };
- const expectedKey = `agent:${agentId}:explicit:${topicId}`;
- return data.sessions?.some((s) => s.key === expectedKey) ?? false;
- } catch {
- return false;
- }
-}
-
export interface RunHeteroTaskParams {
agentId?: string;
agentType: RemoteHeterogeneousAgentType;
@@ -163,17 +145,30 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
const lhPath = resolveLhPath();
if (agentType === 'openclaw') {
- // openclaw agent --local runs the agent in-process and stays alive until
- // the agent finishes — giving us a real long-lived PID we can kill to cancel.
+ // openclaw agent --local is one-shot: each invocation processes one message and exits.
+ // The --session-id links turns into the same conversation history on disk.
// Requires the `openclaw` binary to be on PATH with Node >=22.19.
const openclawAgent = process.env.OPENCLAW_AGENT_ID ?? 'main';
- // Only inject the protocol on the first turn of this session. On subsequent
- // turns openclaw already has the instructions in its conversation history.
- const isNewSession = !openclawSessionExists(openclawAgent, topicId);
- const enrichedPrompt = isNewSession
- ? `${prompt}\n\n${buildNotifyProtocol(lhPath, topicId)}`
- : prompt;
+ // Always inject the notify protocol so openclaw knows how to report results
+ // back to the LobeHub UI — even if the previous turn failed and the session
+ // history was not cleanly committed.
+ const enrichedPrompt = `${prompt}\n\n${buildNotifyProtocol(lhPath, topicId)}`;
+
+ // Kill any existing openclaw process for this topicId before spawning a new one.
+ // openclaw serialises session writes; a concurrent process holding the session
+ // lock will cause the new one to exit with code 1.
+ for (const existing of listTasks()) {
+ if (existing.topicId === topicId && existing.agentType === 'openclaw') {
+ try {
+ process.kill(existing.pid, 'SIGTERM');
+ } catch {
+ // Already exited — nothing to do.
+ }
+ removeTask(existing.taskId);
+ }
+ }
+
const child = spawn(
'openclaw',
[
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index ce93c2fd1c1..d9382201a18 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -1,3 +1,7 @@
+import { execFileSync, execSync, spawn } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+
import type { AgentRunRequestMessage } from '@lobechat/device-gateway-client';
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
@@ -9,6 +13,48 @@ import LocalFileCtr from './LocalFileCtr';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
import ShellCommandCtr from './ShellCommandCtr';
+const DEFAULT_HERMES_PORT = 3456;
+
+/**
+ * Inject the lh-notify protocol into the first turn of a new hetero-agent session.
+ * Tells the agent binary how to push results back to the LobeHub chat UI via `lh notify`.
+ * Ported directly from apps/cli/src/tools/heteroTask.ts so desktop and CLI stay in sync.
+ */
+function buildNotifyProtocol(lhPath: string, topicId: string): string {
+ return (
+ `## Context: This task was dispatched by LobeHub\n\n` +
+ `This conversation / task was sent to you by the **LobeHub platform** on behalf of a user. You are running as a background agent; the user is waiting for your response inside the LobeHub chat interface.\n\n` +
+ `**When to call notify**: any time you have something meaningful to tell the user — a key finding, a decision you made, a result, a question, or your final answer.\n\n` +
+ `**What to hide**: internal work details such as tool call sequences, file reads, intermediate command output, retries, or low-level reasoning steps.\n\n` +
+ `## Sending messages back to the user\n\n` +
+ `Use the \`${lhPath} notify\` command. All your updates appear as a **single message bubble** in the UI — create it once and update it in place.\n\n` +
+ `**Step 1 — Open the bubble on your first meaningful update** (captures the messageId):\n` +
+ `\`\`\`\n` +
+ `MSG_ID=$(${lhPath} notify --topic ${topicId} --role assistant --content "Starting..." --json | grep -o '"messageId":"[^"]*"' | cut -d'"' -f4)\n` +
+ `\`\`\`\n\n` +
+ `**Step 2 — Update the same bubble as you make progress**:\n` +
+ `\`\`\`\n` +
+ `${lhPath} notify --topic ${topicId} --role assistant --message-id "$MSG_ID" --content "Still working..."\n` +
+ `\`\`\`\n\n` +
+ `**Step 3 — Replace with your complete, final response when done**:\n` +
+ `\`\`\`\n` +
+ `${lhPath} notify --topic ${topicId} --role assistant --message-id "$MSG_ID" --content "<your full response here>"\n` +
+ `\`\`\`\n\n` +
+ `Rules:\n` +
+ `- Always use \`--json\` on the first call and capture \`messageId\` from the output.\n` +
+ `- Always pass \`--message-id\` on every subsequent call so updates overwrite the same bubble.\n` +
+ `- Call notify at least once when the task is done, even if there were no intermediate updates.`
+ );
+}
+
+interface PlatformTaskEntry {
+ agentId?: string;
+ agentType: string;
+ operationId: string;
+ pid: number;
+ topicId: string;
+}
+
/**
* GatewayConnectionCtr
*
@@ -17,6 +63,9 @@ import ShellCommandCtr from './ShellCommandCtr';
export default class GatewayConnectionCtr extends ControllerModule {
static override readonly groupName = 'gatewayConnection';
+ /** In-memory registry for running platform agent tasks (openclaw / hermes). */
+ private readonly platformTasks = new Map<string, PlatformTaskEntry>();
+
// ─── Service Accessor ───
private get service() {
@@ -125,11 +174,15 @@ export default class GatewayConnectionCtr extends ControllerModule {
try {
const ctr = this.heterogeneousAgentCtr;
+ // Map agentType to binary name.
+ // claude-code → `claude` CLI; all other platforms use their type name as the binary.
+ const command = request.agentType === 'claude-code' ? 'claude' : request.agentType;
+
// Create a session for the hetero agent.
const { sessionId } = await ctr.startSession({
agentType: request.agentType,
args: [],
- command: request.agentType === 'codex' ? 'codex' : 'claude',
+ command,
cwd: request.cwd,
// Inject LOBEHUB_JWT so the CLI authenticates against heteroIngest.
env: { LOBEHUB_JWT: request.jwt },
@@ -192,6 +245,14 @@ export default class GatewayConnectionCtr extends ControllerModule {
renameLocalFile: () => this.localFileCtr.handleRenameFile(args),
searchLocalFiles: searchFiles,
writeLocalFile: writeFile,
+
+ // Platform agent capability probing
+ checkPlatformCapability: () => this.checkPlatformCapability(args),
+ getAgentProfile: () => this.getAgentProfile(args),
+
+ // Platform agent task execution (openclaw / hermes)
+ cancelHeteroTask: () => this.cancelHeteroTask(args),
+ runHeteroTask: () => this.runHeteroTask(args),
};
const handler = methodMap[apiName];
@@ -203,4 +264,331 @@ export default class GatewayConnectionCtr extends ControllerModule {
return handler();
}
+
+ // ─── Platform Capability Probing ───
+
+ private async checkPlatformCapability(args: {
+ platform: string;
+ }): Promise<{ available: boolean; reason?: string; version?: string }> {
+ const { platform } = args;
+
+ const binaryMap: Record<string, string> = {
+ hermes: 'hermes',
+ openclaw: 'openclaw',
+ };
+
+ const binary = binaryMap[platform];
+ if (!binary) {
+ return { available: false, reason: `Unknown platform: ${platform}` };
+ }
+
+ const whichCmd = process.platform === 'win32' ? `where ${binary}` : `which ${binary}`;
+
+ try {
+ execSync(whichCmd, { stdio: 'pipe' });
+ } catch {
+ return { available: false, reason: `${platform} is not installed on this device` };
+ }
+
+ try {
+ const raw = execSync(`${binary} --version`, {
+ encoding: 'utf8',
+ stdio: 'pipe',
+ }).trim();
+ return { available: true, version: raw };
+ } catch {
+ return { available: true };
+ }
+ }
+
+ private async getAgentProfile(args: { agentId?: string; platform: string }): Promise<{
+ avatar?: string;
+ description?: string;
+ title?: string;
+ }> {
+ const { platform, agentId } = args;
+
+ if (platform === 'openclaw') {
+ return this.getOpenClawProfile(agentId);
+ }
+
+ // hermes and unknown platforms: not yet implemented
+ return {};
+ }
+
+ private getOpenClawProfile(agentId?: string): {
+ avatar?: string;
+ description?: string;
+ title?: string;
+ } {
+ let output: string;
+ try {
+ output = execFileSync('openclaw', ['agents', 'list', '--json'], {
+ encoding: 'utf8',
+ timeout: 5000,
+ });
+ } catch {
+ return {};
+ }
+
+ let agents: Array<{
+ id: string;
+ identityEmoji?: string;
+ identityName?: string;
+ isDefault?: boolean;
+ workspace?: string;
+ }>;
+ try {
+ agents = JSON.parse(output) as typeof agents;
+ } catch {
+ return {};
+ }
+
+ const agent = agentId
+ ? agents.find((a) => a.id === agentId)
+ : (agents.find((a) => a.isDefault) ?? agents[0]);
+
+ if (!agent) return {};
+
+ const title = agent.identityName || undefined;
+ const avatar = agent.identityEmoji || '🦞';
+ const description = agent.workspace
+ ? this.readDescriptionFromWorkspace(agent.workspace)
+ : undefined;
+
+ return { avatar, description, title };
+ }
+
+ private readDescriptionFromWorkspace(workspacePath: string): string | undefined {
+ for (const filename of ['IDENTITY.md', 'SOUL.md']) {
+ const filePath = path.join(workspacePath, filename);
+ if (!fs.existsSync(filePath)) continue;
+
+ const content = fs.readFileSync(filePath, 'utf8');
+ const match = content.match(/\*{0,2}(?:Creature|Vibe|Description):?\*{0,2}\s*(.+)/i);
+ if (!match) continue;
+
+ const value = match[1].trim();
+ if (/^[_*((].*[))*_]$|^(?:tbd|todo|n\/?a|none|待定|未定)$/i.test(value)) continue;
+ return value;
+ }
+ }
+
+ // ─── Platform Agent Task Execution ───
+ //
+ // Ported from apps/cli/src/tools/heteroTask.ts so that devices connected via
+ // the desktop gateway can execute openclaw/hermes tasks without requiring `lh connect`.
+
+ private async runHeteroTask(args: {
+ agentId?: string;
+ agentType: string;
+ cwd?: string;
+ operationId: string;
+ prompt: string;
+ taskId: string;
+ topicId: string;
+ }): Promise<string> {
+ const { agentId, agentType, cwd, operationId, prompt, taskId, topicId } = args;
+ const workDir = cwd || process.cwd();
+
+ if (agentType === 'openclaw') {
+ const lhPath = this.resolveLhPath();
+ const openclawAgent = process.env['OPENCLAW_AGENT_ID'] ?? 'main';
+
+ // Always inject the notify protocol so openclaw knows how to report results
+ // back to the LobeHub UI — even if the previous turn failed and the session
+ // history was not cleanly committed.
+ const enrichedPrompt = `${prompt}\n\n${buildNotifyProtocol(lhPath, topicId)}`;
+
+ // Kill any existing openclaw process for this topicId before spawning a new one.
+ // openclaw serialises session writes; a concurrent process holding the session
+ // lock will cause the new one to exit with code 1.
+ for (const [existingTaskId, entry] of this.platformTasks) {
+ if (entry.topicId === topicId && entry.agentType === 'openclaw') {
+ try {
+ process.kill(entry.pid, 'SIGTERM');
+ } catch {
+ // Already exited — nothing to do.
+ }
+ this.platformTasks.delete(existingTaskId);
+ }
+ }
+
+ const child = spawn(
+ 'openclaw',
+ [
+ 'agent',
+ '--agent',
+ openclawAgent,
+ '--session-id',
+ topicId,
+ '--message',
+ enrichedPrompt,
+ '--local',
+ ],
+ { cwd: workDir, detached: true, env: { ...process.env }, stdio: 'ignore' },
+ );
+
+ const pid = child.pid;
+ if (pid === undefined) throw new Error('Failed to get PID for openclaw process');
+ child.unref();
+
+ this.platformTasks.set(taskId, { agentId, agentType, operationId, pid, topicId });
+
+ child.on('close', (code, signal) => {
+ this.platformTasks.delete(taskId);
+ if (code !== 0 || signal !== null) {
+ const text = signal
+ ? `Task cancelled (signal: ${signal})`
+ : `Task failed (exit code: ${code})`;
+ void this.sendNotify({ agentId, content: text, role: 'assistant', topicId }).finally(() =>
+ this.sendNotify({ agentId, content: '', done: true, role: 'assistant', topicId }),
+ );
+ } else {
+ void this.sendNotify({ agentId, content: '', done: true, role: 'assistant', topicId });
+ }
+ });
+
+ return JSON.stringify({ pid, taskId });
+ }
+
+ if (agentType === 'hermes') {
+ const port = this.getHermesPort();
+ if (!(await this.isHermesRunning(port))) {
+ await this.startHermesGateway(port);
+ }
+
+ const res = await fetch(`http://localhost:${port}/message`, {
+ body: JSON.stringify({ content: prompt, operationId }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+ if (!res.ok) throw new Error(`Hermes gateway returned ${res.status}: ${await res.text()}`);
+
+ this.platformTasks.set(taskId, { agentId, agentType, operationId, pid: 0, topicId });
+ return JSON.stringify({ operationId, taskId });
+ }
+
+ throw new Error(`Unsupported agentType: ${agentType}`);
+ }
+
+ private async cancelHeteroTask(args: { signal?: string; taskId: string }): Promise<string> {
+ const { signal = 'SIGINT', taskId } = args;
+ const entry = this.platformTasks.get(taskId);
+
+ if (!entry) {
+ return JSON.stringify({ message: `No task found with taskId: ${taskId}`, success: false });
+ }
+
+ if (entry.agentType === 'hermes') {
+ const port = this.getHermesPort();
+ try {
+ await fetch(`http://localhost:${port}/stop`, {
+ body: JSON.stringify({ operationId: entry.operationId }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+ } catch {
+ // Hermes gateway may already have stopped; ignore
+ }
+ this.platformTasks.delete(taskId);
+ await this.sendNotify({
+ agentId: entry.agentId,
+ content: 'Task cancelled',
+ role: 'assistant',
+ topicId: entry.topicId,
+ });
+ return JSON.stringify({ taskId });
+ }
+
+ // openclaw: kill by PID; the close handler sends the done signal.
+ try {
+ process.kill(entry.pid, signal);
+ } catch {
+ this.platformTasks.delete(taskId);
+ await this.sendNotify({
+ agentId: entry.agentId,
+ content: 'Task already completed or cancelled',
+ role: 'assistant',
+ topicId: entry.topicId,
+ });
+ }
+
+ return JSON.stringify({ pid: entry.pid, signal, taskId });
+ }
+
+ /**
+ * Send a notify message to the server so the frontend receives agent output or
+ * a completion signal. Uses the tRPC agentNotify.notify endpoint directly —
+ * this is the desktop counterpart to `lh notify` used by the CLI path.
+ */
+ private async sendNotify(params: {
+ agentId?: string;
+ content: string;
+ done?: boolean;
+ role: string;
+ topicId: string;
+ }): Promise<void> {
+ try {
+ const [serverUrl, token] = await Promise.all([
+ this.remoteServerConfigCtr.getRemoteServerUrl(),
+ this.remoteServerConfigCtr.getAccessToken(),
+ ]);
+ if (!serverUrl || !token) return;
+
+ await fetch(`${serverUrl}/trpc/agentNotify.notify`, {
+ body: JSON.stringify({ json: params }),
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ });
+ } catch {
+ // Fire-and-forget: openclaw's own `lh notify` calls are the primary channel.
+ }
+ }
+
+ // ─── Platform Agent Helpers ───
+
+ private resolveLhPath(): string {
+ try {
+ return execFileSync('which', ['lh'], { encoding: 'utf8' }).trim();
+ } catch {
+ return 'lh';
+ }
+ }
+
+ private getHermesPort(): number {
+ const env = process.env['HERMES_GATEWAY_PORT'];
+ if (env) {
+ const parsed = Number.parseInt(env, 10);
+ if (!Number.isNaN(parsed)) return parsed;
+ }
+ return DEFAULT_HERMES_PORT;
+ }
+
+ private async isHermesRunning(port: number): Promise<boolean> {
+ try {
+ return (await fetch(`http://localhost:${port}/health`)).ok;
+ } catch {
+ return false;
+ }
+ }
+
+ private async startHermesGateway(port: number): Promise<void> {
+ const child = spawn('hermes', ['gateway', 'start'], {
+ detached: true,
+ env: { ...process.env },
+ stdio: 'ignore',
+ });
+ child.unref();
+
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ await new Promise<void>((r) => setTimeout(r, 500));
+ if (await this.isHermesRunning(port)) return;
+ }
+ throw new Error(`Hermes gateway did not start within 10s on port ${port}`);
+ }
}
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 6b852b3d8d8..680e9bf65cf 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -1,9 +1,12 @@
+import type { execSync as ExecSyncType } from 'node:child_process';
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import GatewayConnectionCtr from '../GatewayConnectionCtr';
+import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';
import LocalFileCtr from '../LocalFileCtr';
import RemoteServerConfigCtr from '../RemoteServerConfigCtr';
import ShellCommandCtr from '../ShellCommandCtr';
@@ -31,6 +34,7 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {
});
sendToolCallResponse = vi.fn();
+ sendAgentRunAck = vi.fn();
constructor(options: any) {
super();
@@ -71,6 +75,22 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {
this.emit('error', new Error(message));
}
+ simulateAgentRunRequest(
+ agentType: string,
+ operationId = 'op-1',
+ prompt = 'hello',
+ jwt = 'mock-jwt',
+ ) {
+ this.emit('agent_run_request', {
+ agentType,
+ jwt,
+ operationId,
+ prompt,
+ topicId: 'topic-1',
+ type: 'agent_run_request',
+ });
+ }
+
simulateReconnecting(delay: number) {
this.connectionStatus = 'reconnecting';
this.emit('status_changed', 'reconnecting');
@@ -123,6 +143,15 @@ vi.mock('node:crypto', () => ({
randomUUID: vi.fn(() => 'mock-device-uuid'),
}));
+const execSyncMock = vi.hoisted(() => vi.fn());
+const execFileSyncMock = vi.hoisted(() => vi.fn());
+const spawnMock = vi.hoisted(() => vi.fn());
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<{ execSync: typeof ExecSyncType }>();
+ return { ...actual, execFileSync: execFileSyncMock, execSync: execSyncMock, spawn: spawnMock };
+});
+
vi.mock('node:os', () => ({
default: { hostname: vi.fn(() => 'mock-hostname') },
}));
@@ -131,6 +160,13 @@ vi.mock('@lobechat/device-gateway-client', () => ({
GatewayClient: MockGatewayClient,
}));
+vi.mock('execa', () => ({
+ execa: vi.fn().mockResolvedValue({ stdout: '', stderr: '' }),
+}));
+
+vi.mock('fast-glob', () => ({ default: vi.fn().mockResolvedValue([]) }));
+vi.mock('fflate', () => ({ unzipSync: vi.fn() }));
+
// ─── Mock Controllers ───
const mockLocalFileCtr = {
@@ -162,6 +198,11 @@ const mockShellCommandCtr = {
handleRunCommand: vi.fn().mockResolvedValue({ success: true, stdout: '' }),
} as unknown as ShellCommandCtr;
+const mockHeterogeneousAgentCtr = {
+ sendPrompt: vi.fn().mockResolvedValue(undefined),
+ startSession: vi.fn().mockResolvedValue({ sessionId: 'mock-session-id' }),
+} as unknown as HeterogeneousAgentCtr;
+
const mockRemoteServerConfigCtr = {
getAccessToken: vi.fn().mockResolvedValue('mock-access-token'),
isRemoteServerConfigured: vi.fn().mockResolvedValue(true),
@@ -178,6 +219,7 @@ const mockApp = {
if (Cls === RemoteServerConfigCtr) return mockRemoteServerConfigCtr;
if (Cls === LocalFileCtr) return mockLocalFileCtr;
if (Cls === ShellCommandCtr) return mockShellCommandCtr;
+ if (Cls === HeterogeneousAgentCtr) return mockHeterogeneousAgentCtr;
return null;
}),
getService: vi.fn((Cls) => {
@@ -577,6 +619,327 @@ describe('GatewayConnectionCtr', () => {
});
});
+ // ─── Agent Run Routing ───
+
+ describe('agent run routing', () => {
+ async function connectAndOpen() {
+ ctr.afterAppReady();
+ await vi.advanceTimersByTimeAsync(0);
+ const client = MockGatewayClient.lastInstance!;
+ client.simulateConnected();
+ return client;
+ }
+
+ beforeEach(() => {
+ vi.mocked(mockHeterogeneousAgentCtr.startSession).mockClear();
+ vi.mocked(mockHeterogeneousAgentCtr.sendPrompt).mockClear();
+ });
+
+ it.each([
+ ['openclaw', 'openclaw'],
+ ['hermes', 'hermes'],
+ ['codex', 'codex'],
+ ['claude-code', 'claude'],
+ ] as const)('uses command "%s" for agentType "%s"', async (agentType, expectedCommand) => {
+ const client = await connectAndOpen();
+ client.simulateAgentRunRequest(agentType);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(mockHeterogeneousAgentCtr.startSession).toHaveBeenCalledWith(
+ expect.objectContaining({ agentType, command: expectedCommand }),
+ );
+ });
+
+ it('sends accepted ack and fires sendPrompt', async () => {
+ const client = await connectAndOpen();
+ client.simulateAgentRunRequest('openclaw', 'op-xyz');
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendAgentRunAck).toHaveBeenCalledWith({
+ operationId: 'op-xyz',
+ status: 'accepted',
+ });
+ expect(mockHeterogeneousAgentCtr.sendPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-xyz', sessionId: 'mock-session-id' }),
+ );
+ });
+
+ it('sends rejected ack when startSession throws', async () => {
+ vi.mocked(mockHeterogeneousAgentCtr.startSession).mockRejectedValueOnce(
+ new Error('binary not found'),
+ );
+
+ const client = await connectAndOpen();
+ client.simulateAgentRunRequest('openclaw', 'op-fail');
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendAgentRunAck).toHaveBeenCalledWith({
+ operationId: 'op-fail',
+ reason: 'binary not found',
+ status: 'rejected',
+ });
+ });
+ });
+
+ // ─── runHeteroTask ───
+
+ describe('runHeteroTask', () => {
+ /** Creates a minimal mock child process returned by spawn(). */
+ function makeMockChild(pid = 9999) {
+ const listeners: Record<string, Array<(...a: any[]) => void>> = {};
+ return {
+ on: vi.fn((event: string, cb: (...a: any[]) => void) => {
+ listeners[event] = listeners[event] ?? [];
+ listeners[event].push(cb);
+ }),
+ pid,
+ unref: vi.fn(),
+ _emit: (event: string, ...args: any[]) => listeners[event]?.forEach((cb) => cb(...args)),
+ };
+ }
+
+ async function connectAndOpen() {
+ ctr.afterAppReady();
+ await vi.advanceTimersByTimeAsync(0);
+ const client = MockGatewayClient.lastInstance!;
+ client.simulateConnected();
+ return client;
+ }
+
+ beforeEach(() => {
+ execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ spawnMock.mockReset();
+ });
+
+ it('always injects buildNotifyProtocol into the prompt', async () => {
+ const child = makeMockChild();
+ spawnMock.mockReturnValue(child);
+
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'hello',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ },
+ 'req-run',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
+ const messageArg = spawnArgs[spawnArgs.indexOf('--message') + 1];
+ expect(messageArg).toContain('hello');
+ expect(messageArg).toContain('lh notify');
+ });
+
+ it('kills an existing concurrent openclaw process for the same topicId before spawning', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ // First task
+ const child1 = makeMockChild(1111);
+ spawnMock.mockReturnValueOnce(child1);
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'msg1',
+ taskId: 'task-1',
+ topicId: 'topic-same',
+ },
+ 'req-1',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Second task for same topicId — should kill task-1's pid first
+ const child2 = makeMockChild(2222);
+ spawnMock.mockReturnValueOnce(child2);
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-2',
+ prompt: 'msg2',
+ taskId: 'task-2',
+ topicId: 'topic-same',
+ },
+ 'req-2',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(killSpy).toHaveBeenCalledWith(1111, 'SIGTERM');
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+
+ killSpy.mockRestore();
+ });
+
+ it('does not kill processes for a different topicId', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const child1 = makeMockChild(3333);
+ spawnMock.mockReturnValueOnce(child1);
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-1',
+ prompt: 'a',
+ taskId: 'task-a',
+ topicId: 'topic-A',
+ },
+ 'req-a',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ const child2 = makeMockChild(4444);
+ spawnMock.mockReturnValueOnce(child2);
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-2',
+ prompt: 'b',
+ taskId: 'task-b',
+ topicId: 'topic-B',
+ },
+ 'req-b',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(killSpy).not.toHaveBeenCalled();
+
+ killSpy.mockRestore();
+ });
+ });
+
+ // ─── Platform Capability Probing ───
+
+ describe('platform capability probing', () => {
+ async function connectAndOpen() {
+ ctr.afterAppReady();
+ await vi.advanceTimersByTimeAsync(0);
+ const client = MockGatewayClient.lastInstance!;
+ client.simulateConnected();
+ return client;
+ }
+
+ beforeEach(() => {
+ execSyncMock.mockReset();
+ });
+
+ it('returns available:true with version when binary is installed', async () => {
+ execSyncMock.mockImplementation((cmd: string) => {
+ if (cmd.startsWith('which ') || cmd.startsWith('where '))
+ return '/usr/local/bin/openclaw\n';
+ if (cmd.includes('--version')) return 'openclaw 1.2.3\n';
+ return '';
+ });
+
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'checkPlatformCapability',
+ { platform: 'openclaw' },
+ 'req-cap',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-cap',
+ result: {
+ content: JSON.stringify({ available: true, version: 'openclaw 1.2.3' }),
+ success: true,
+ },
+ });
+ });
+
+ it('returns available:true without version when --version command fails', async () => {
+ execSyncMock.mockImplementation((cmd: string) => {
+ if (cmd.startsWith('which ') || cmd.startsWith('where '))
+ return '/usr/local/bin/openclaw\n';
+ throw new Error('version command failed');
+ });
+
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'checkPlatformCapability',
+ { platform: 'openclaw' },
+ 'req-cap-nover',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-cap-nover',
+ result: {
+ content: JSON.stringify({ available: true }),
+ success: true,
+ },
+ });
+ });
+
+ it('returns available:false when binary is not installed', async () => {
+ execSyncMock.mockImplementation(() => {
+ throw new Error('command not found');
+ });
+
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'checkPlatformCapability',
+ { platform: 'openclaw' },
+ 'req-missing',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-missing',
+ result: {
+ content: JSON.stringify({
+ available: false,
+ reason: 'openclaw is not installed on this device',
+ }),
+ success: true,
+ },
+ });
+ });
+
+ it('returns available:false for unknown platform', async () => {
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'checkPlatformCapability',
+ { platform: 'unknownBot' },
+ 'req-unknown-plat',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-unknown-plat',
+ result: {
+ content: JSON.stringify({ available: false, reason: 'Unknown platform: unknownBot' }),
+ success: true,
+ },
+ });
+ });
+
+ it('getAgentProfile returns empty object', async () => {
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest('getAgentProfile', { platform: 'openclaw' }, 'req-profile');
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-profile',
+ result: {
+ content: JSON.stringify({}),
+ success: true,
+ },
+ });
+ });
+ });
+
// ─── IPC Methods ───
describe('getConnectionStatus', () => {
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 52a8e2fee47..a2843b2b3f3 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -367,14 +367,17 @@
"platformAgent.create.comingSoon": "Coming Soon",
"platformAgent.create.create": "Create Agent",
"platformAgent.create.creating": "Creating...",
- "platformAgent.create.desc.hermes": "Run Hermes agents on your local machine",
- "platformAgent.create.desc.openclaw": "Run OpenClaw agents on your local machine",
+ "platformAgent.create.desc.hermes": "Connect to Hermes running on one of your devices",
+ "platformAgent.create.desc.openclaw": "Connect to OpenClaw running on one of your devices",
"platformAgent.create.descriptionPlaceholder": "Brief description (optional)",
+ "platformAgent.create.downloadDesktop": "Download Desktop App",
"platformAgent.create.fetchingProfile": "Fetching profile...",
"platformAgent.create.namePlaceholder": "e.g. My OpenClaw Agent",
"platformAgent.create.next": "Next",
"platformAgent.create.noDevices": "No devices connected",
- "platformAgent.create.noDevicesHint": "Run `lh connect` on the target machine first",
+ "platformAgent.create.noDevicesCliHint": "Or connect any machine via CLI, then click Refresh:",
+ "platformAgent.create.noDevicesCmd": "lh connect",
+ "platformAgent.create.noDevicesDesktopHint": "Install the Desktop App — it connects automatically after login",
"platformAgent.create.notInstalled": "{{name}} not installed on this device",
"platformAgent.create.refresh": "Refresh",
"platformAgent.create.selectDevice": "Select a device",
@@ -382,6 +385,9 @@
"platformAgent.create.step2": "Select Device",
"platformAgent.create.step3": "Configure Agent",
"platformAgent.create.title": "Add Platform Agent",
+ "platformAgent.create.upgradeCmd": "npm install -g @lobehub/cli",
+ "platformAgent.create.versionTooLow": "lh version is too low",
+ "platformAgent.create.versionTooLowHint": "Update lh to the latest version:",
"platformAgent.device.online": "Online",
"platformAgent.deviceGuard.configure": "Configure",
"platformAgent.deviceGuard.deviceOffline.desc": "The bound device is not connected. Run `lh connect` on that machine then refresh.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index eb835b1f0a6..6e4317babb1 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -367,14 +367,17 @@
"platformAgent.create.comingSoon": "即将推出",
"platformAgent.create.create": "创建 Agent",
"platformAgent.create.creating": "创建中...",
- "platformAgent.create.desc.hermes": "在本地机器上运行 Hermes Agent",
- "platformAgent.create.desc.openclaw": "在本地机器上运行 OpenClaw Agent",
+ "platformAgent.create.desc.hermes": "连接你某台设备上的 Hermes Agent",
+ "platformAgent.create.desc.openclaw": "连接你某台设备上的 OpenClaw Agent",
"platformAgent.create.descriptionPlaceholder": "简短描述(可选)",
+ "platformAgent.create.downloadDesktop": "下载桌面端",
"platformAgent.create.fetchingProfile": "正在读取配置...",
"platformAgent.create.namePlaceholder": "例:我的 OpenClaw Agent",
"platformAgent.create.next": "下一步",
"platformAgent.create.noDevices": "没有已连接的设备",
- "platformAgent.create.noDevicesHint": "请先在目标机器上运行 `lh connect`",
+ "platformAgent.create.noDevicesCliHint": "或在任意机器上通过 CLI 连接,然后点击刷新:",
+ "platformAgent.create.noDevicesCmd": "lh connect",
+ "platformAgent.create.noDevicesDesktopHint": "安装桌面端,登录后自动完成连接",
"platformAgent.create.notInstalled": "此设备未安装 {{name}}",
"platformAgent.create.refresh": "刷新",
"platformAgent.create.selectDevice": "选择设备",
@@ -382,6 +385,9 @@
"platformAgent.create.step2": "选择设备",
"platformAgent.create.step3": "配置 Agent",
"platformAgent.create.title": "添加平台 Agent",
+ "platformAgent.create.upgradeCmd": "npm install -g @lobehub/cli",
+ "platformAgent.create.versionTooLow": "lh 版本过低",
+ "platformAgent.create.versionTooLowHint": "请升级到最新版本:",
"platformAgent.device.online": "在线",
"platformAgent.deviceGuard.configure": "去配置",
"platformAgent.deviceGuard.deviceOffline.desc": "绑定的设备未连接,请在目标机器上运行 `lh connect` 后刷新。",
diff --git a/src/features/CreatePlatformAgent/index.tsx b/src/features/CreatePlatformAgent/index.tsx
index 1a3bb671879..ff5be166454 100644
--- a/src/features/CreatePlatformAgent/index.tsx
+++ b/src/features/CreatePlatformAgent/index.tsx
@@ -5,9 +5,16 @@ import {
type RemoteHeterogeneousAgentType,
} from '@lobechat/heterogeneous-agents';
import { Button, Flexbox, Icon } from '@lobehub/ui';
-import { Alert, Input, Modal, Select, Steps, Tag } from 'antd';
+import { Alert, Input, Modal, Select, Steps, Tag, Typography } from 'antd';
import { createStyles } from 'antd-style';
-import { BotIcon, CheckCircle2, MonitorSmartphone, RefreshCw, XCircle } from 'lucide-react';
+import {
+ BotIcon,
+ CheckCircle2,
+ Download,
+ MonitorSmartphone,
+ RefreshCw,
+ XCircle,
+} from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -284,6 +291,28 @@ const CreatePlatformAgentModal = memo<CreatePlatformAgentModalProps>(
</Flexbox>
);
}
+
+ // Detect outdated lh desktop version — the gateway returns this pattern when the
+ // tool is unknown to the running desktop build.
+ const isVersionTooLow = capabilityResult.reason?.includes('is not available on this device');
+ if (isVersionTooLow) {
+ return (
+ <Alert
+ showIcon
+ message={t('platformAgent.create.versionTooLow')}
+ type="warning"
+ description={
+ <Flexbox gap={4}>
+ <span>{t('platformAgent.create.versionTooLowHint')}</span>
+ <Typography.Text code copyable>
+ {t('platformAgent.create.upgradeCmd')}
+ </Typography.Text>
+ </Flexbox>
+ }
+ />
+ );
+ }
+
return (
<Flexbox horizontal align="center" gap={4}>
<Icon color="var(--ant-color-error)" icon={XCircle} size={14} />
@@ -351,9 +380,30 @@ const CreatePlatformAgentModal = memo<CreatePlatformAgentModalProps>(
<Flexbox gap={12}>
<Alert
showIcon
- description={t('platformAgent.create.noDevicesHint')}
message={t('platformAgent.create.noDevices')}
- type="warning"
+ type="info"
+ description={
+ <Flexbox gap={12}>
+ <Flexbox gap={6}>
+ <span>{t('platformAgent.create.noDevicesDesktopHint')}</span>
+ <a href="https://lobehub.com/downloads" rel="noreferrer" target="_blank">
+ <Button
+ icon={<Icon icon={Download} size={13} />}
+ size="small"
+ type="primary"
+ >
+ {t('platformAgent.create.downloadDesktop')}
+ </Button>
+ </a>
+ </Flexbox>
+ <Flexbox gap={4}>
+ <span>{t('platformAgent.create.noDevicesCliHint')}</span>
+ <Typography.Text code copyable>
+ {t('platformAgent.create.noDevicesCmd')}
+ </Typography.Text>
+ </Flexbox>
+ </Flexbox>
+ }
/>
{refreshButton}
</Flexbox>
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 91098e54721..d2a65db84ea 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -359,8 +359,8 @@ export default {
'newGroupChat': 'Create Group',
// Platform agent: per-platform descriptions shown in step 0 of the creation modal
- 'platformAgent.create.desc.openclaw': 'Run OpenClaw agents on your local machine',
- 'platformAgent.create.desc.hermes': 'Run Hermes agents on your local machine',
+ 'platformAgent.create.desc.openclaw': 'Connect to OpenClaw running on one of your devices',
+ 'platformAgent.create.desc.hermes': 'Connect to Hermes running on one of your devices',
// Platform agent: shared device status label (used in Select option labels)
'platformAgent.device.online': 'Online',
@@ -378,13 +378,20 @@ export default {
'platformAgent.create.descriptionPlaceholder': 'Brief description (optional)',
'platformAgent.create.fetchingProfile': 'Fetching profile...',
'platformAgent.create.noDevices': 'No devices connected',
- 'platformAgent.create.noDevicesHint': 'Run `lh connect` on the target machine first',
+ 'platformAgent.create.noDevicesDesktopHint':
+ 'Install the Desktop App — it connects automatically after login',
+ 'platformAgent.create.downloadDesktop': 'Download Desktop App',
+ 'platformAgent.create.noDevicesCliHint': 'Or connect any machine via CLI, then click Refresh:',
+ 'platformAgent.create.noDevicesCmd': 'lh connect',
'platformAgent.create.refresh': 'Refresh',
'platformAgent.create.selectDevice': 'Select a device',
'platformAgent.create.checking': 'Checking availability...',
'platformAgent.create.available': 'Available',
'platformAgent.create.notInstalled': '{{name}} not installed on this device',
'platformAgent.create.checkFailed': 'Check failed',
+ 'platformAgent.create.versionTooLow': 'lh version is too low',
+ 'platformAgent.create.versionTooLowHint': 'Update lh to the latest version:',
+ 'platformAgent.create.upgradeCmd': 'npm install -g @lobehub/cli',
'platformAgent.create.comingSoon': 'Coming Soon',
// Platform agent device guard banner