🤯 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
✨ feat: unify local agent connection wizard (#17794)
Arvin Xuee800610eabc
diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.tsindex 79d72bd168b..2dfb68fcd53 100644--- a/apps/cli/src/tools/index.ts+++ b/apps/cli/src/tools/index.ts@@ -4,6 +4,7 @@ import { getAgentProfile } from './getAgentProfile';import { cancelHeteroTask, runHeteroTask } from './heteroTask';import { executeToolCallInWorker, shouldRunInWorker } from './isolatedWorker';import { runLocalSystemTool } from './localSystemRuntime';+import { scanHeterogeneousAgents } from './scanHeterogeneousAgents';/*** CLI-only tools (platform agents). File/shell tools are handled separately by@@ -15,6 +16,7 @@ const methodMap: Record<string, (args: any) => Promise<unknown>> = {checkPlatformCapability,getAgentProfile,runHeteroTask,+ scanHeterogeneousAgents,};export async function executeToolCall(diff --git a/apps/cli/src/tools/scanHeterogeneousAgents.ts b/apps/cli/src/tools/scanHeterogeneousAgents.tsnew file mode 100644index 00000000000..458dd6bfffa--- /dev/null+++ b/apps/cli/src/tools/scanHeterogeneousAgents.ts@@ -0,0 +1,14 @@+import type { HeterogeneousAgentScanMap } from '@lobechat/heterogeneous-agents';+import { scanHeterogeneousAgentsOnHost } from '@lobechat/heterogeneous-agents/scanHost';++export interface ScanHeterogeneousAgentsResult {+ agents: HeterogeneousAgentScanMap;+}++/**+ * Probe every known heterogeneous agent type on this device in one pass.+ * Dispatched by the server via the `device.scanAgents` tRPC procedure.+ */+export async function scanHeterogeneousAgents(): Promise<ScanHeterogeneousAgentsResult> {+ return { agents: await scanHeterogeneousAgentsOnHost() };+}diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 86b26650fcf..f745f78ce6f 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -21,6 +21,7 @@ import type {RunCommandParams,WriteLocalFileParams,} from '@lobechat/electron-client-ipc';+import { scanHeterogeneousAgentsOnHost } from '@lobechat/heterogeneous-agents/scanHost';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';import GatewayConnectionService from '@/services/gatewayConnectionSrv';@@ -570,6 +571,12 @@ export default class GatewayConnectionCtr extends ControllerModule {return { content: JSON.stringify(result), state: result, success: true };}+ case 'scanHeterogeneousAgents': {+ const agents = await scanHeterogeneousAgentsOnHost();+ const result = { agents };+ return { content: JSON.stringify(result), state: result, success: true };+ }+case 'runHeteroTask': {// runHeteroTask returns a pre-stringified JSON payload — pass it through// as `content` and surface the parsed shape as `state`.diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 4ab3a296085..b778594bc87 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -1,4 +1,7 @@-import { REMOTE_HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';+import {+ type HeterogeneousAgentScanMap,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+} from '@lobechat/heterogeneous-agents';import type {DeviceChannel,DeviceListItem,@@ -37,6 +40,9 @@ const remotePlatformEnum = z.enum(const CAPABILITY_TIMEOUT_MS = 5_000;const PROFILE_TIMEOUT_MS = 5_000;+// Batch scan probes every agent type (which + --version per binary, with+// login-shell PATH fallback), so it gets a longer budget than a single probe.+const SCAN_TIMEOUT_MS = 10_000;/*** A workspace device's user-editable fields (rename, working dirs, remove) may@@ -165,6 +171,41 @@ export const deviceRouter = router({}}),+ /**+ * Scan the given device for every known heterogeneous agent type in one+ * pass. Dispatches a `scanHeterogeneousAgents` tool call to the device via+ * the gateway; the device probes each binary and returns an availability+ * map. On gateway failure (offline device, older client without the tool)+ * returns an empty map plus the error so the client can distinguish+ * "nothing installed" from "scan failed".+ */+ scanAgents: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(+ async ({ ctx, input }): Promise<{ agents: HeterogeneousAgentScanMap; error?: string }> => {+ const result = await deviceGateway.executeToolCall(+ { deviceId: input.deviceId, userId: ctx.userId, workspaceId: ctx.workspaceId },+ {+ apiName: 'scanHeterogeneousAgents',+ arguments: JSON.stringify({}),+ identifier: 'local',+ },+ SCAN_TIMEOUT_MS,+ );++ if (!result.success) {+ return { agents: {}, error: result.error ?? 'Device tool call failed' };+ }++ try {+ const parsed = JSON.parse(result.content) as { agents?: HeterogeneousAgentScanMap };+ return { agents: parsed.agents ?? {} };+ } catch {+ return { agents: {}, error: 'Invalid response from device' };+ }+ },+ ),+/*** Granular git reads for a directory on a remote device, each via its own* device RPC so the web/remote git status bar mirrors the local desktop'sdiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 1074b952ab5..bfc13bc2050 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -163,6 +163,55 @@"confirmRemoveGroupSuccess": "Group deleted successfully","confirmRemoveSessionItemAlert": "You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.","confirmRemoveSessionSuccess": "Agent removed successfully",+ "connectAgent.create.back": "Back",+ "connectAgent.create.connect": "Connect",+ "connectAgent.create.connectCli": "Connect with CLI",+ "connectAgent.create.connectMany": "Connect {{total}} Agents",+ "connectAgent.create.connectOne": "Connect {{name}}",+ "connectAgent.create.connectedDevices": "Connected devices",+ "connectAgent.create.createFailed": "Connect failed",+ "connectAgent.create.customizeName": "Customize Name…",+ "connectAgent.create.descriptionPlaceholder": "Description (optional)",+ "connectAgent.create.detectedCount": "{{total}} detected — select the ones to connect",+ "connectAgent.create.detectedInScan": "detected in scan",+ "connectAgent.create.done": "Done",+ "connectAgent.create.doneHint": "All set — open one to give it its first task.",+ "connectAgent.create.doneTitle": "{{name}} connected",+ "connectAgent.create.doneTitleMany": "{{total}} agents connected",+ "connectAgent.create.download": "Download",+ "connectAgent.create.downloadDesktop": "Download Desktop App",+ "connectAgent.create.localDevice": "This computer",+ "connectAgent.create.localDeviceDesc": "Runs agents directly on this machine",+ "connectAgent.create.namePlaceholder": "Agent name",+ "connectAgent.create.noDevices": "No devices connected",+ "connectAgent.create.noDevicesCliHint": "Run this command on the computer you want to connect",+ "connectAgent.create.noDevicesCmd": "lh connect",+ "connectAgent.create.noDevicesDesc": "Connect a computer to discover and run the agents installed on it.",+ "connectAgent.create.noDevicesDesktopHint": "Install the Desktop App — it connects automatically after login",+ "connectAgent.create.noneDetected": "No agents detected on this device",+ "connectAgent.create.noneDetectedHint": "Install a supported agent on that machine, then rescan. For example:",+ "connectAgent.create.notInstalled": "Not installed",+ "connectAgent.create.offline": "Offline",+ "connectAgent.create.online": "Online",+ "connectAgent.create.openChat": "Open Chat",+ "connectAgent.create.refresh": "Refresh",+ "connectAgent.create.rescan": "Rescan",+ "connectAgent.create.rescanDevice": "Rescan Device",+ "connectAgent.create.runsOn": "Runs on {{device}}",+ "connectAgent.create.scanFailed": "Scan failed",+ "connectAgent.create.scanning": "Scanning agents on this device…",+ "connectAgent.create.selectFirst": "Select at least one detected agent",+ "connectAgent.create.stepAgents": "Step 2 of 3 · {{device}}",+ "connectAgent.create.stepConfirm": "Step 3 of 3 · Name it for your agent list",+ "connectAgent.create.stepDevice": "Step 1 of 3 · Pick the machine your agents run on — it will be scanned automatically.",+ "connectAgent.create.thisDevice": "This device",+ "connectAgent.create.title": "Connect Agent",+ "connectAgent.providerDesc.amp": "Sourcegraph coding agent CLI",+ "connectAgent.providerDesc.claude-code": "Anthropic coding agent CLI",+ "connectAgent.providerDesc.codex": "OpenAI coding agent CLI",+ "connectAgent.providerDesc.hermes": "Personal agent platform",+ "connectAgent.providerDesc.openclaw": "Personal agent platform",+ "connectAgent.providerDesc.opencode": "Open-source coding agent CLI","createModal.createBlank": "Start Blank","createModal.groupPlaceholder": "Describe what this Group should do...","createModal.groupTitle": "What should this Group do?",@@ -671,7 +720,8 @@"newGroupChat": "Create Group","newOpenCodeAgent": "Add OpenCode","newPage": "Create Page",- "newPlatformAgent": "Connect Agent",+ "newPlatformAgent": "Connect Local Agent",+ "newPlatformAgentDesc": "Connect to Claude Code, Codex, and other local agents","noAgentsYet": "This group has no members yet. Click the + button to invite agents.","noAvailableAgents": "No members available to invite","noMatchingAgents": "No matching members found",@@ -715,35 +765,6 @@"permission.configAccess.groupRoleRestricted": "Your workspace role cannot configure Agent Groups. You were returned to chat.","pin": "Pin","pinOff": "Unpin",- "platformAgent.create.available": "Available",- "platformAgent.create.back": "Back",- "platformAgent.create.checkFailed": "Check failed",- "platformAgent.create.checking": "Checking availability...",- "platformAgent.create.create": "Connect",- "platformAgent.create.creating": "Connecting...",- "platformAgent.create.desc.amp": "Connect to Amp running on one of your devices",- "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.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",- "platformAgent.create.step1": "Select Agent",- "platformAgent.create.step2": "Select Device",- "platformAgent.create.step3": "Configure Agent",- "platformAgent.create.title": "Connect 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.","platformAgent.deviceGuard.deviceOffline.title": "Device not connected",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 15b74f54c86..d0cb1846f61 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -163,6 +163,55 @@"confirmRemoveGroupSuccess": "群组已删除","confirmRemoveSessionItemAlert": "确认删除该助理吗?删除后无法恢复","confirmRemoveSessionSuccess": "助理已删除",+ "connectAgent.create.back": "上一步",+ "connectAgent.create.connect": "接入",+ "connectAgent.create.connectCli": "通过 CLI 连接",+ "connectAgent.create.connectMany": "接入 {{total}} 个助理",+ "connectAgent.create.connectOne": "接入 {{name}}",+ "connectAgent.create.connectedDevices": "已连接设备",+ "connectAgent.create.createFailed": "接入失败",+ "connectAgent.create.customizeName": "自定义名称…",+ "connectAgent.create.descriptionPlaceholder": "描述(可选)",+ "connectAgent.create.detectedCount": "检测到 {{total}} 个 — 勾选要接入的助理",+ "connectAgent.create.detectedInScan": "已通过扫描检测",+ "connectAgent.create.done": "完成",+ "connectAgent.create.doneHint": "一切就绪 — 打开对话,交给它第一个任务吧。",+ "connectAgent.create.doneTitle": "{{name}} 已接入",+ "connectAgent.create.doneTitleMany": "已接入 {{total}} 个助理",+ "connectAgent.create.download": "下载",+ "connectAgent.create.downloadDesktop": "下载桌面客户端",+ "connectAgent.create.localDevice": "这台电脑",+ "connectAgent.create.localDeviceDesc": "助理将直接在本机运行",+ "connectAgent.create.namePlaceholder": "助理名称",+ "connectAgent.create.noDevices": "暂无已连接设备",+ "connectAgent.create.noDevicesCliHint": "在需要连接的电脑上运行此命令",+ "connectAgent.create.noDevicesCmd": "lh connect",+ "connectAgent.create.noDevicesDesc": "连接一台电脑,以发现并运行其中安装的智能体。",+ "connectAgent.create.noDevicesDesktopHint": "安装桌面客户端,登录后将自动连接",+ "connectAgent.create.noneDetected": "未在该设备上检测到助理",+ "connectAgent.create.noneDetectedHint": "在该机器上安装受支持的助理后重新扫描。例如:",+ "connectAgent.create.notInstalled": "未安装",+ "connectAgent.create.offline": "离线",+ "connectAgent.create.online": "在线",+ "connectAgent.create.openChat": "打开对话",+ "connectAgent.create.refresh": "刷新",+ "connectAgent.create.rescan": "重新扫描",+ "connectAgent.create.rescanDevice": "重新扫描设备",+ "connectAgent.create.runsOn": "运行于 {{device}}",+ "connectAgent.create.scanFailed": "扫描失败",+ "connectAgent.create.scanning": "正在扫描设备上的助理…",+ "connectAgent.create.selectFirst": "请先勾选至少一个已检测到的助理",+ "connectAgent.create.stepAgents": "第 2 步,共 3 步 · {{device}}",+ "connectAgent.create.stepConfirm": "第 3 步,共 3 步 · 为助理命名",+ "connectAgent.create.stepDevice": "第 1 步,共 3 步 · 选择运行助理的设备,将自动扫描其上安装的助理。",+ "connectAgent.create.thisDevice": "本机",+ "connectAgent.create.title": "接入助理",+ "connectAgent.providerDesc.amp": "Sourcegraph 编码助理 CLI",+ "connectAgent.providerDesc.claude-code": "Anthropic 编码助理 CLI",+ "connectAgent.providerDesc.codex": "OpenAI 编码助理 CLI",+ "connectAgent.providerDesc.hermes": "个人智能体平台",+ "connectAgent.providerDesc.openclaw": "个人智能体平台",+ "connectAgent.providerDesc.opencode": "开源编码助理 CLI","createModal.createBlank": "从空白开始","createModal.groupPlaceholder": "描述这个群组要完成什么…","createModal.groupTitle": "这个群组要做什么?",@@ -671,7 +720,8 @@"newGroupChat": "创建群组","newOpenCodeAgent": "添加 OpenCode","newPage": "创建文稿",- "newPlatformAgent": "接入助理",+ "newPlatformAgent": "连接本地智能体",+ "newPlatformAgentDesc": "连接 Claude Code、Codex 等本地智能体","noAgentsYet": "这个群组还没有成员。点击「+」邀请助理加入","noAvailableAgents": "暂无可邀请的成员","noMatchingAgents": "未找到匹配的成员",@@ -715,35 +765,6 @@"permission.configAccess.groupRoleRestricted": "您的工作区角色无法配置代理组。您已返回到聊天界面。","pin": "置顶","pinOff": "取消置顶",- "platformAgent.create.available": "可用",- "platformAgent.create.back": "上一步",- "platformAgent.create.checkFailed": "检测失败",- "platformAgent.create.checking": "正在检测可用性...",- "platformAgent.create.create": "接入",- "platformAgent.create.creating": "接入中...",- "platformAgent.create.desc.amp": "接入你设备上运行的 Amp",- "platformAgent.create.desc.hermes": "接入你设备上运行的 Hermes",- "platformAgent.create.desc.openclaw": "接入你设备上运行的 OpenClaw",- "platformAgent.create.descriptionPlaceholder": "简短描述(可选)",- "platformAgent.create.downloadDesktop": "下载桌面端",- "platformAgent.create.fetchingProfile": "正在读取配置...",- "platformAgent.create.namePlaceholder": "例:我的 OpenClaw 助理",- "platformAgent.create.next": "下一步",- "platformAgent.create.noDevices": "没有已连接的设备",- "platformAgent.create.noDevicesCliHint": "或在任意机器上通过 CLI 连接,然后点击刷新:",- "platformAgent.create.noDevicesCmd": "lh connect",- "platformAgent.create.noDevicesDesktopHint": "安装桌面端,登录后自动完成连接",- "platformAgent.create.notInstalled": "此设备未安装 {{name}}",- "platformAgent.create.refresh": "刷新",- "platformAgent.create.selectDevice": "选择设备",- "platformAgent.create.step1": "选择助理",- "platformAgent.create.step2": "选择运行设备",- "platformAgent.create.step3": "配置助理",- "platformAgent.create.title": "接入助理",- "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` 后刷新。","platformAgent.deviceGuard.deviceOffline.title": "设备未连接",diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 62746d96e63..30055fbf4fb 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -12,6 +12,7 @@"./protocol": "./src/protocol/index.ts","./quota": "./src/quota/index.ts","./resolveCliCommand": "./src/spawn/resolveCliCommand.ts",+ "./scanHost": "./src/scan/scanHost.ts","./spawn": "./src/spawn/index.ts","./transcript": "./src/transcript/index.ts"},diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex e0f0c791be4..9810384b9ef 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -27,6 +27,7 @@ export type {} from './mainAgentCoordinator';export { createMainAgentRunState, reduceMainAgent } from './mainAgentCoordinator';export { createAdapter, listAgentTypes } from './registry';+export type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './scan/types';export { isHeteroStatusGuideErrorData } from './spawn/classifyProcessFailure';export type {CreateMessageIntent,diff --git a/packages/heterogeneous-agents/src/scan/scanHost.ts b/packages/heterogeneous-agents/src/scan/scanHost.tsnew file mode 100644index 00000000000..521c1442319--- /dev/null+++ b/packages/heterogeneous-agents/src/scan/scanHost.ts@@ -0,0 +1,69 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++import {+ HETEROGENEOUS_AGENT_CONFIGS,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+ type RemoteHeterogeneousAgentType,+} from '../config';+import { detectHeterogeneousCliCommand } from '../spawn/resolveCliCommand';+import type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './types';++/**+ * Host-side scanner behind the `scanHeterogeneousAgents` device tool: probes+ * every known heterogeneous agent type on the current machine in one pass.+ * Runs in Node contexts only (the `lh connect` CLI and Electron main) — like+ * `resolveCliCommand`, it must be imported via its dedicated subpath+ * (`@lobechat/heterogeneous-agents/scanHost`), never from a browser bundle.+ */++const execFileP = promisify(execFile);++const PROBE_TIMEOUT_MS = 5000;++// openclaw prints "openclaw x.y.z"; hermes prints "Hermes Agent vX.Y.Z (...)"+const parsePlatformVersion = (type: RemoteHeterogeneousAgentType, output: string) => {+ if (type === 'hermes') {+ const match = output.match(/v(\d+\.\d+\.\d+)/);+ if (match) return match[1];+ }+ return output.split(/\s+/).at(-1);+};++const probeRemotePlatform = async (+ type: RemoteHeterogeneousAgentType,+): Promise<HeterogeneousAgentScanStatus> => {+ try {+ const { stdout } = await execFileP(type, ['--version'], {+ timeout: PROBE_TIMEOUT_MS,+ windowsHide: true,+ });+ return { available: true, version: parsePlatformVersion(type, stdout.trim()) };+ } catch (error) {+ return {+ available: false,+ reason: error instanceof Error ? error.message : `${type} not found or failed to run`,+ };+ }+};++export const scanHeterogeneousAgentsOnHost = async (): Promise<HeterogeneousAgentScanMap> => {+ const entries = await Promise.all([+ ...HETEROGENEOUS_AGENT_CONFIGS.map(async (config) => {+ const status = await detectHeterogeneousCliCommand(config.type, config.command);+ return [+ config.type,+ {+ available: status.available,+ version: status.version,+ } satisfies HeterogeneousAgentScanStatus,+ ] as const;+ }),+ ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(async (config) => {+ const status = await probeRemotePlatform(config.type);+ return [config.type, status] as const;+ }),+ ]);++ return Object.fromEntries(entries);+};diff --git a/packages/heterogeneous-agents/src/scan/types.ts b/packages/heterogeneous-agents/src/scan/types.tsnew file mode 100644index 00000000000..afb2d25988a--- /dev/null+++ b/packages/heterogeneous-agents/src/scan/types.ts@@ -0,0 +1,19 @@+import type { HeterogeneousAgentType } from '../config';++/**+ * Availability of one heterogeneous agent on a scanned host.+ */+export interface HeterogeneousAgentScanStatus {+ available: boolean;+ reason?: string;+ version?: string;+}++/**+ * Result of scanning a host for every known heterogeneous agent type.+ * Keys absent from the map mean the type was not probed (e.g. older device+ * clients that predate the scan tool).+ */+export type HeterogeneousAgentScanMap = Partial<+ Record<HeterogeneousAgentType, HeterogeneousAgentScanStatus>+>;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 14d5a35bdee..bc7a63ee44c 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -812,7 +812,8 @@ export default {'newClaudeCodeAgent': 'Add Claude Code','newCodexAgent': 'Add Codex','newOpenCodeAgent': 'Add OpenCode',- 'newPlatformAgent': 'Connect Agent',+ 'newPlatformAgent': 'Connect Local Agent',+ 'newPlatformAgentDesc': 'Connect to Claude Code, Codex, and other local agents','newGroupChat': 'Create Group','agent.publishToWorkspace': 'Publish to Workspace','agent.publishToWorkspaceErrorFixedPrivateDevice':@@ -842,41 +843,61 @@ export default {'opStatusTray.steps': 'steps','opStatusTray.tokens': 'tokens',- // Connect agent: per-agent descriptions shown in step 0 of the connect modal- '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',- 'platformAgent.create.desc.amp': 'Connect to Amp running on one of your devices',-- // Connect agent: shared device status label (used in Select option labels)- 'platformAgent.device.online': 'Online',-- // Connect agent modal (openclaw / hermes)- 'platformAgent.create.title': 'Connect Agent',- 'platformAgent.create.step1': 'Select Agent',- 'platformAgent.create.step2': 'Select Device',- 'platformAgent.create.step3': 'Configure Agent',- 'platformAgent.create.next': 'Next',- 'platformAgent.create.back': 'Back',- 'platformAgent.create.create': 'Connect',- 'platformAgent.create.creating': 'Connecting...',- 'platformAgent.create.namePlaceholder': 'e.g. My OpenClaw Agent',- 'platformAgent.create.descriptionPlaceholder': 'Brief description (optional)',- 'platformAgent.create.fetchingProfile': 'Fetching profile...',- 'platformAgent.create.noDevices': 'No devices connected',- 'platformAgent.create.noDevicesDesktopHint':+ // Connect Agent wizard (device-first): pick a machine, auto-scan the agents+ // installed on it, connect the selected ones+ 'connectAgent.create.title': 'Connect Agent',+ 'connectAgent.create.stepDevice':+ 'Step 1 of 3 · Pick the machine your agents run on — it will be scanned automatically.',+ 'connectAgent.create.stepAgents': 'Step 2 of 3 · {{device}}',+ 'connectAgent.create.stepConfirm': 'Step 3 of 3 · Name it for your agent list',+ 'connectAgent.create.thisDevice': 'This device',+ 'connectAgent.create.connectedDevices': 'Connected devices',+ 'connectAgent.create.localDevice': 'This computer',+ 'connectAgent.create.localDeviceDesc': 'Runs agents directly on this machine',+ 'connectAgent.create.online': 'Online',+ 'connectAgent.create.offline': 'Offline',+ 'connectAgent.create.noDevices': 'No devices connected',+ 'connectAgent.create.noDevicesDesc':+ 'Connect a computer to discover and run the agents installed on it.',+ 'connectAgent.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',+ 'connectAgent.create.downloadDesktop': 'Download Desktop App',+ 'connectAgent.create.download': 'Download',+ 'connectAgent.create.connectCli': 'Connect with CLI',+ 'connectAgent.create.noDevicesCliHint': 'Run this command on the computer you want to connect',+ 'connectAgent.create.noDevicesCmd': 'lh connect',+ 'connectAgent.create.refresh': 'Refresh',+ 'connectAgent.create.scanning': 'Scanning agents on this device…',+ 'connectAgent.create.scanFailed': 'Scan failed',+ 'connectAgent.create.rescan': 'Rescan',+ 'connectAgent.create.rescanDevice': 'Rescan Device',+ 'connectAgent.create.noneDetected': 'No agents detected on this device',+ 'connectAgent.create.noneDetectedHint':+ 'Install a supported agent on that machine, then rescan. For example:',+ 'connectAgent.create.detectedCount': '{{total}} detected — select the ones to connect',+ 'connectAgent.create.notInstalled': 'Not installed',+ 'connectAgent.create.selectFirst': 'Select at least one detected agent',+ 'connectAgent.create.customizeName': 'Customize Name…',+ 'connectAgent.create.connect': 'Connect',+ 'connectAgent.create.connectOne': 'Connect {{name}}',+ 'connectAgent.create.connectMany': 'Connect {{total}} Agents',+ 'connectAgent.create.namePlaceholder': 'Agent name',+ 'connectAgent.create.descriptionPlaceholder': 'Description (optional)',+ 'connectAgent.create.runsOn': 'Runs on {{device}}',+ 'connectAgent.create.detectedInScan': 'detected in scan',+ 'connectAgent.create.back': 'Back',+ 'connectAgent.create.createFailed': 'Connect failed',+ 'connectAgent.create.doneTitle': '{{name}} connected',+ 'connectAgent.create.doneTitleMany': '{{total}} agents connected',+ 'connectAgent.create.doneHint': 'All set — open one to give it its first task.',+ 'connectAgent.create.openChat': 'Open Chat',+ 'connectAgent.create.done': 'Done',+ 'connectAgent.providerDesc.claude-code': 'Anthropic coding agent CLI',+ 'connectAgent.providerDesc.codex': 'OpenAI coding agent CLI',+ 'connectAgent.providerDesc.amp': 'Sourcegraph coding agent CLI',+ 'connectAgent.providerDesc.opencode': 'Open-source coding agent CLI',+ 'connectAgent.providerDesc.openclaw': 'Personal agent platform',+ 'connectAgent.providerDesc.hermes': 'Personal agent platform',// Connect agent device guard banner'platformAgent.deviceGuard.deviceOffline.title': 'Device not connected',diff --git a/src/features/AgentViewAll/AgentViewAllPage.tsx b/src/features/AgentViewAll/AgentViewAllPage.tsxindex 6b586b40865..5316c869559 100644--- a/src/features/AgentViewAll/AgentViewAllPage.tsx+++ b/src/features/AgentViewAll/AgentViewAllPage.tsx@@ -232,10 +232,9 @@ const AgentViewAllPage = memo(() => {const { allowed: canCreate, reason: createBlockedReason } = usePermission('create_content');const {createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,createMarketAgentMenuItem,- createPlatformAgentMenuItem,isMutatingAgent,} = useCreateMenuItems();@@ -252,22 +251,19 @@ const AgentViewAllPage = memo(() => {// sidebar's "add from Agent list" entry is omitted — it navigates to this// very page.const createMenuItems = useMemo(() => {- const heteroItems = createHeterogeneousAgentMenuItems(createOptions);- const platformItem = createPlatformAgentMenuItem(createOptions);+ const connectItem = createConnectAgentMenuItem(createOptions);return [createAgentMenuItem(createOptions),createGroupChatMenuItem(createOptions),- ...(heteroItems.length > 0 ? [{ type: 'divider' as const }, ...heteroItems] : []),- ...(platformItem ? [{ type: 'divider' as const }, platformItem] : []),+ ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),{ type: 'divider' as const },createMarketAgentMenuItem(),];}, [createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,createMarketAgentMenuItem,- createPlatformAgentMenuItem,createOptions,]);diff --git a/src/features/ConnectAgent/index.tsx b/src/features/ConnectAgent/index.tsxnew file mode 100644index 00000000000..b62adc3d0fd--- /dev/null+++ b/src/features/ConnectAgent/index.tsx@@ -0,0 +1,1010 @@+'use client';++import { isDesktop } from '@lobechat/const';+import type {+ HeterogeneousAgentScanStatus,+ HeterogeneousAgentType,+ RemoteHeterogeneousAgentType,+} from '@lobechat/heterogeneous-agents';+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';+import type { DeviceListItem } from '@lobechat/types';+import { Alert, CopyButton, Flexbox, Icon, Input, Text, TextArea, Tooltip } from '@lobehub/ui';+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';+import { Checkbox, Typography } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import { t as i18nT } from 'i18next';+import {+ ArrowLeft,+ CheckCircle2,+ Download,+ LaptopIcon,+ RefreshCw,+ ScanSearch,+ TerminalIcon,+} from 'lucide-react';+import { memo, type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { DOWNLOAD_URL } from '@/const/url';+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { deviceService } from '@/services/device';+import { useAgentStore } from '@/store/agent';+import { useHomeStore } from '@/store/home';++import { CONNECTABLE_PROVIDERS, type ConnectableProvider } from './providers';+import { type ScanTarget, useAgentScan } from './useAgentScan';++const styles = createStaticStyles(({ css }) => ({+ cmd: css`+ user-select: all;++ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadiusSM};++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;++ background: ${cssVar.colorFillTertiary};+ `,+ dot: css`+ flex: none;++ width: 8px;+ height: 8px;+ border-radius: 50%;++ background: ${cssVar.colorSuccess};+ `,+ dotOff: css`+ flex: none;++ width: 8px;+ height: 8px;+ border-radius: 50%;++ background: ${cssVar.colorTextQuaternary};+ `,+ emptyCard: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ emptyHero: css`+ padding-block: 24px;+ padding-inline: 24px;+ text-align: center;+ background: ${cssVar.colorFillQuaternary};+ `,+ emptyOption: css`+ display: flex;+ flex-direction: column;+ gap: 10px;+ align-items: flex-start;++ min-width: 0;+ min-height: 152px;+ padding: 18px;++ background: ${cssVar.colorBgContainer};+ `,+ emptyOptionAction: css`+ display: flex;+ align-items: center;++ width: 100%;+ min-height: 28px;+ margin-block-start: auto;++ > a {+ width: 100%;+ }+ `,+ emptyOptionCode: css`+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: space-between;++ box-sizing: border-box;+ width: 100%;+ height: 32px;+ padding-inline: 10px 4px;+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillTertiary};+ `,+ emptyOptions: css`+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 1px;++ border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBorderSecondary};+ `,+ emptyOptionIcon: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 40px;+ height: 40px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ heroIcon: css`+ display: flex;+ align-items: center;+ justify-content: center;++ width: 52px;+ height: 52px;+ border-radius: ${cssVar.borderRadiusLG};++ color: ${cssVar.colorText};++ background: ${cssVar.colorFillSecondary};+ `,+ groupList: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ iconBox: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 36px;+ height: 36px;+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillTertiary};+ `,+ mono: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ row: css`+ cursor: pointer;++ display: flex;+ gap: 12px;+ align-items: center;++ padding-block: 12px;+ padding-inline: 16px;++ transition: background 0.15s;++ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ rowDisabled: css`+ cursor: not-allowed;+ opacity: 0.5;++ &:hover {+ background: transparent;+ }+ `,+ rowStatic: css`+ cursor: default;++ &:hover {+ background: transparent;+ }+ `,+ skeletonBar: css`+ height: 10px;+ border-radius: 5px;+ background: ${cssVar.colorFillSecondary};+ animation: lobe-connect-agent-pulse 1.4s ease-in-out infinite;++ @keyframes lobe-connect-agent-pulse {+ 50% {+ opacity: 0.45;+ }+ }+ `,+ skeletonCircle: css`+ flex: none;++ width: 32px;+ height: 32px;+ border-radius: 50%;++ background: ${cssVar.colorFillSecondary};++ animation: lobe-connect-agent-pulse 1.4s ease-in-out infinite;+ `,+}));++interface AgentProfile {+ avatar?: string;+ description?: string;+ title?: string;+}++interface CreatedAgent {+ agentId: string;+ locationLabel: string;+ provider: ConnectableProvider;+ title: string;+ version?: string;+}++const SectionLabel = memo<{ children: ReactNode }>(({ children }) => (+ <Text fontSize={12} style={{ paddingInline: 4 }} type={'secondary'}>+ {children}+ </Text>+));++const SkeletonRow = memo<{ width: number }>(({ width }) => (+ <div className={`${styles.row} ${styles.rowStatic}`}>+ <div className={styles.skeletonCircle} />+ {/* Column height matches a real row's two-line text block so the+ scanning → done swap doesn't shift the modal */}+ <Flexbox flex={1} gap={10} justify={'center'} style={{ height: 42 }}>+ <div className={styles.skeletonBar} style={{ width }} />+ <div className={styles.skeletonBar} style={{ opacity: 0.6, width: width * 1.6 }} />+ </Flexbox>+ </div>+));++const DeviceRow = memo<{+ icon: ReactNode;+ offline?: boolean;+ onClick?: () => void;+ statusText: string;+ subtitle: string;+ title: string;+}>(({ icon, offline, onClick, statusText, subtitle, title }) => (+ <div+ className={offline ? `${styles.row} ${styles.rowDisabled}` : styles.row}+ role={'button'}+ tabIndex={offline ? -1 : 0}+ onClick={offline ? undefined : onClick}+ >+ <div className={styles.iconBox}>{icon}</div>+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis strong>+ {title}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {subtitle}+ </Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={6} style={{ flex: 'none' }}>+ <div className={offline ? styles.dotOff : styles.dot} />+ <Text fontSize={12} type={'secondary'}>+ {statusText}+ </Text>+ </Flexbox>+ </div>+));++const AgentScanRow = memo<{+ onToggle: () => void;+ provider: ConnectableProvider;+ selected: boolean;+ status?: HeterogeneousAgentScanStatus;+ subtitle: string;+ unavailableText: string;+}>(({ onToggle, provider, selected, status, subtitle, unavailableText }) => {+ const available = status?.available === true;+ const row = (+ <div+ className={available ? styles.row : `${styles.row} ${styles.rowDisabled}`}+ role={'button'}+ tabIndex={available ? 0 : -1}+ onClick={available ? onToggle : undefined}+ >+ <provider.brand.Avatar size={32} />+ <Flexbox flex={1} gap={1} style={{ minWidth: 0 }}>+ <Text strong>{provider.title}</Text>+ <Text ellipsis fontSize={12} type={'secondary'}>+ {subtitle}+ </Text>+ </Flexbox>+ {available ? (+ <>+ {status?.version && <span className={styles.mono}>{status.version}</span>}+ <Checkbox checked={selected} style={{ pointerEvents: 'none' }} />+ </>+ ) : (+ <Text fontSize={12} type={'secondary'}>+ {unavailableText}+ </Text>+ )}+ </div>+ );++ if (!available && status?.reason) return <Tooltip title={status.reason}>{row}</Tooltip>;+ return row;+});++interface ConnectAgentContentProps {+ groupId?: string;+ onTitleChange: (title: string) => void;+ visibility?: 'private' | 'public';+}++const ConnectAgentContent = memo<ConnectAgentContentProps>(+ ({ groupId, onTitleChange, visibility }) => {+ const { t } = useTranslation('chat');+ const { close, setCanDismissByClickOutside } = useModalContext();+ const navigate = useWorkspaceAwareNavigate();+ const storeCreateAgent = useAgentStore((s) => s.createAgent);+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);++ // Workspace agents must bind workspace devices: a workspace agent on a+ // personal device is unreachable to other members and rejected server-side.+ const activeWorkspaceId = useActiveWorkspaceId();+ const restrictToWorkspaceDevices = Boolean(activeWorkspaceId);++ const [step, setStep] = useState(0);+ const [target, setTarget] = useState<ScanTarget | null>(null);+ const [selectedTypes, setSelectedTypes] = useState<HeterogeneousAgentType[]>([]);+ const [profiles, setProfiles] = useState<+ Partial<Record<RemoteHeterogeneousAgentType, AgentProfile>>+ >({});+ const [name, setName] = useState('');+ const [description, setDescription] = useState('');+ const [creating, setCreating] = useState(false);+ const [createError, setCreateError] = useState<string | undefined>();+ const [done, setDone] = useState<CreatedAgent[] | null>(null);++ const { scan, state: scanState } = useAgentScan();++ useEffect(() => {+ setCanDismissByClickOutside(!creating);+ }, [creating, setCanDismissByClickOutside]);++ const {+ data: devices,+ isLoading: loadingDevices,+ isValidating: fetchingDevices,+ mutate: refetchDevices,+ } = useDeviceList();++ const listedDevices = useMemo(+ () => (devices ?? []).filter((d) => !restrictToWorkspaceDevices || d.scope === 'workspace'),+ [devices, restrictToWorkspaceDevices],+ );+ const onlineDevices = listedDevices.filter((d) => d.online);++ const deviceLabel = useCallback(+ (device: DeviceListItem) => device.friendlyName || device.hostname || device.deviceId,+ [],+ );++ const targetLabel =+ target?.kind === 'device' ? deviceLabel(target.device) : t('connectAgent.create.localDevice');++ // Providers listed for the current target: local targets only run CLI+ // subprocess agents. Device targets expose every remotely scannable agent.+ const visibleProviders = useMemo(+ () =>+ CONNECTABLE_PROVIDERS.filter((provider) => {+ if (target?.kind === 'local' && provider.kind === 'platform') return false;+ return true;+ }),+ [target?.kind],+ );++ const inventory = useMemo(() => {+ if (scanState.status !== 'success' || !scanState.agents) return [];+ const rank = (available?: boolean) => (available ? 0 : 1);+ return [...visibleProviders]+ .map((provider) => ({ provider, status: scanState.agents?.[provider.type] }))+ .sort((a, b) => rank(a.status?.available) - rank(b.status?.available));+ }, [scanState, visibleProviders]);++ const detectedCount = inventory.filter((entry) => entry.status?.available).length;++ const selectedProviders = useMemo(+ () => CONNECTABLE_PROVIDERS.filter((provider) => selectedTypes.includes(provider.type)),+ [selectedTypes],+ );+ // Customize (step 3) only applies to a single selection+ const single = selectedProviders.length === 1 ? selectedProviders[0] : null;+ const singleVersion = single ? scanState.agents?.[single.type]?.version : undefined;++ const pickTarget = useCallback(+ (next: ScanTarget) => {+ setTarget(next);+ setSelectedTypes([]);+ setProfiles({});+ setStep(1);+ void scan(next);+ },+ [scan],+ );++ const rescan = useCallback(() => {+ if (!target) return;+ setSelectedTypes([]);+ void scan(target);+ }, [scan, target]);++ const toggleType = useCallback(+ (provider: ConnectableProvider) => {+ setSelectedTypes((prev) =>+ prev.includes(provider.type)+ ? prev.filter((type) => type !== provider.type)+ : [...prev, provider.type],+ );+ // Prefetch the platform's profile so create/customize can prefill+ // title / description / avatar without an extra wait.+ if (+ provider.kind === 'platform' &&+ target?.kind === 'device' &&+ isRemoteHeterogeneousType(provider.type) &&+ !profiles[provider.type]+ ) {+ const platform = provider.type;+ void deviceService+ .getAgentProfile({ deviceId: target.device.deviceId, platform })+ .then((profile) => setProfiles((prev) => ({ ...prev, [platform]: profile })))+ .catch(() => {});+ }+ },+ [profiles, target],+ );++ const goConfirm = useCallback(() => {+ if (!single) return;+ const profile = isRemoteHeterogeneousType(single.type) ? profiles[single.type] : undefined;+ setName(profile?.title ?? single.title);+ setDescription(profile?.description ?? '');+ setStep(2);+ }, [profiles, single]);++ const buildCreateParams = useCallback(+ (provider: ConnectableProvider, overrides?: { description?: string; name?: string }) => {+ const title = overrides?.name?.trim() || provider.title;++ if (target?.kind === 'device' && provider.kind === 'platform') {+ const profile = isRemoteHeterogeneousType(provider.type)+ ? profiles[provider.type]+ : undefined;+ return {+ config: {+ agencyConfig: {+ boundDeviceId: target.device.deviceId,+ heterogeneousProvider: { type: provider.type },+ },+ avatar: profile?.avatar || undefined,+ description: (overrides?.description ?? profile?.description)?.trim() || undefined,+ title: overrides?.name?.trim() || profile?.title || provider.title,+ },+ groupId,+ visibility,+ };+ }++ const base = {+ avatar: provider.avatar,+ description: overrides?.description?.trim() || undefined,+ provider: provider.type,+ systemRole: '',+ title,+ };++ if (target?.kind === 'device') {+ return {+ config: {+ ...base,+ agencyConfig: {+ boundDeviceId: target.device.deviceId,+ executionTarget: 'device' as const,+ heterogeneousProvider: { command: provider.command, type: provider.type },+ },+ },+ groupId,+ visibility,+ };+ }++ return {+ config: {+ ...base,+ agencyConfig: {+ heterogeneousProvider: { command: provider.command, type: provider.type },+ },+ },+ groupId,+ visibility,+ };+ },+ [groupId, profiles, target, visibility],+ );++ const handleCreate = useCallback(+ async (overrides?: { description?: string; name?: string }) => {+ if (!target || selectedProviders.length === 0) return;+ setCreating(true);+ setCreateError(undefined);+ try {+ const created = await Promise.all(+ selectedProviders.map(async (provider) => {+ const params = buildCreateParams(+ provider,+ provider === single ? overrides : undefined,+ );+ const result = await storeCreateAgent(params);+ return {+ agentId: result.agentId,+ locationLabel: targetLabel,+ provider,+ title: params.config.title ?? provider.title,+ version: scanState.agents?.[provider.type]?.version,+ } satisfies CreatedAgent;+ }),+ );+ await refreshAgentList();+ setDone(created);+ onTitleChange(+ created.length === 1+ ? t('connectAgent.create.doneTitle', { name: created[0].title })+ : t('connectAgent.create.doneTitleMany', { total: created.length }),+ );+ } catch (error) {+ setCreateError(error instanceof Error ? error.message : String(error));+ } finally {+ setCreating(false);+ }+ },+ [+ buildCreateParams,+ onTitleChange,+ refreshAgentList,+ scanState,+ selectedProviders,+ single,+ storeCreateAgent,+ t,+ target,+ targetLabel,+ ],+ );++ const openChat = useCallback(+ (agentId: string) => {+ close();+ navigate(`/agent/${agentId}`);+ },+ [close, navigate],+ );++ // ── Done: connected summary stays inside the modal ──+ if (done) {+ return (+ <Flexbox gap={8} paddingBlock={'16px 8px'}>+ <SectionLabel>{t('connectAgent.create.doneHint')}</SectionLabel>+ <div className={styles.groupList}>+ {done.map((agent) => (+ <div className={`${styles.row} ${styles.rowStatic}`} key={agent.agentId}>+ <agent.provider.brand.Avatar size={32} />+ <Flexbox flex={1} gap={1} style={{ minWidth: 0 }}>+ <Text strong fontSize={13}>+ {agent.title}+ </Text>+ <Text ellipsis fontSize={12} type={'secondary'}>+ {agent.provider.title}+ {agent.version ? ` ${agent.version}` : ''} · {agent.locationLabel}+ </Text>+ </Flexbox>+ <div className={styles.dot} />+ <Button size={'small'} onClick={() => openChat(agent.agentId)}>+ {t('connectAgent.create.openChat')}+ </Button>+ </div>+ ))}+ </div>+ <Flexbox horizontal justify={'flex-end'} style={{ paddingBlockStart: 8 }}>+ <Button type={'primary'} onClick={close}>+ {t('connectAgent.create.done')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ }++ // ── Step 1: choose the machine ──+ if (step === 0) {+ const isRefreshing = loadingDevices || fetchingDevices;+ const showEmpty = !isDesktop && !isRefreshing && onlineDevices.length === 0;++ return (+ <Flexbox gap={16} paddingBlock={'16px 8px'}>+ <SectionLabel>{t('connectAgent.create.stepDevice')}</SectionLabel>+ {showEmpty ? (+ <div className={styles.emptyCard}>+ <Flexbox align={'center'} className={styles.emptyHero} gap={10}>+ <span className={styles.heroIcon}>+ <Icon icon={LaptopIcon} size={26} />+ </span>+ <Text fontSize={17} weight={600}>+ {t('connectAgent.create.noDevices')}+ </Text>+ <Text style={{ maxWidth: 400 }} type={'secondary'}>+ {t('connectAgent.create.noDevicesDesc')}+ </Text>+ </Flexbox>+ <div className={styles.emptyOptions}>+ <div className={styles.emptyOption}>+ <span className={styles.emptyOptionIcon}>+ <Icon icon={Download} size={20} />+ </span>+ <Flexbox gap={3}>+ <Text weight={500}>{t('connectAgent.create.downloadDesktop')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('connectAgent.create.noDevicesDesktopHint')}+ </Text>+ </Flexbox>+ <div className={styles.emptyOptionAction}>+ <a href={DOWNLOAD_URL.default} rel={'noreferrer'} target={'_blank'}>+ <Button+ icon={<Icon icon={Download} size={14} />}+ style={{ width: '100%' }}+ type={'primary'}+ >+ {t('connectAgent.create.download')}+ </Button>+ </a>+ </div>+ </div>+ <div className={styles.emptyOption}>+ <span className={styles.emptyOptionIcon}>+ <Icon icon={TerminalIcon} size={20} />+ </span>+ <Flexbox gap={3}>+ <Text weight={500}>{t('connectAgent.create.connectCli')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('connectAgent.create.noDevicesCliHint')}+ </Text>+ </Flexbox>+ <div className={styles.emptyOptionAction}>+ <div className={styles.emptyOptionCode}>+ <code>{t('connectAgent.create.noDevicesCmd')}</code>+ <CopyButton content={t('connectAgent.create.noDevicesCmd')} size={'small'} />+ </div>+ </div>+ </div>+ </div>+ <Flexbox horizontal justify={'flex-end'} padding={8}>+ <Button+ icon={<Icon icon={RefreshCw} size={13} />}+ loading={isRefreshing}+ size={'small'}+ type={'text'}+ onClick={() => void refetchDevices()}+ >+ {t('connectAgent.create.refresh')}+ </Button>+ </Flexbox>+ </div>+ ) : (+ <Flexbox gap={16}>+ {isDesktop && (+ <Flexbox gap={6}>+ <SectionLabel>{t('connectAgent.create.thisDevice')}</SectionLabel>+ <div className={styles.groupList}>+ <DeviceRow+ icon={<Icon icon={LaptopIcon} size={18} />}+ statusText={t('connectAgent.create.online')}+ subtitle={t('connectAgent.create.localDeviceDesc')}+ title={t('connectAgent.create.localDevice')}+ onClick={() => pickTarget({ kind: 'local' })}+ />+ </div>+ </Flexbox>+ )}+ {listedDevices.length > 0 && (+ <Flexbox gap={6}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <SectionLabel>{t('connectAgent.create.connectedDevices')}</SectionLabel>+ <Button+ icon={<Icon icon={RefreshCw} size={13} />}+ loading={isRefreshing}+ size={'small'}+ type={'text'}+ onClick={() => void refetchDevices()}+ >+ {t('connectAgent.create.refresh')}+ </Button>+ </Flexbox>+ <div className={styles.groupList}>+ {listedDevices.map((device) => (+ <DeviceRow+ icon={getDeviceIcon(device.platform, 18)}+ key={device.deviceId}+ offline={!device.online}+ subtitle={device.hostname || device.deviceId}+ title={deviceLabel(device)}+ statusText={+ device.online+ ? t('connectAgent.create.online')+ : t('connectAgent.create.offline')+ }+ onClick={() => pickTarget({ device, kind: 'device' })}+ />+ ))}+ </div>+ </Flexbox>+ )}+ {isDesktop && listedDevices.length === 0 && (+ <Flexbox gap={4}>+ <span>{t('connectAgent.create.noDevicesCliHint')}</span>+ <Typography.Text code copyable>+ {t('connectAgent.create.noDevicesCmd')}+ </Typography.Text>+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+ }++ // ── Step 2: auto-scanned agent inventory ──+ if (step === 1 && target) {+ const scanning = scanState.status === 'scanning';++ return (+ <Flexbox gap={8} paddingBlock={'0 8px'}>+ {/* Rescan stays mounted (disabled while scanning) and the row reserves+ its height — no jump when the scan settles */}+ <Flexbox horizontal align={'center'} justify={'space-between'} style={{ minHeight: 28 }}>+ <SectionLabel>+ {t('connectAgent.create.stepAgents', { device: targetLabel })}+ </SectionLabel>+ {!(scanState.status === 'success' && detectedCount === 0) &&+ scanState.status !== 'error' && (+ <Button+ disabled={scanning}+ icon={<Icon icon={RefreshCw} size={13} />}+ size={'small'}+ type={'text'}+ onClick={rescan}+ >+ {t('connectAgent.create.rescan')}+ </Button>+ )}+ </Flexbox>++ {scanning && (+ <Flexbox gap={6}>+ <SectionLabel>{t('connectAgent.create.scanning')}</SectionLabel>+ <div className={styles.groupList}>+ {[90, 70, 110, 80, 100, 75].slice(0, visibleProviders.length).map((width, i) => (+ <SkeletonRow key={i} width={width} />+ ))}+ </div>+ </Flexbox>+ )}++ {scanState.status === 'error' && (+ <Alert+ showIcon+ description={scanState.error}+ message={t('connectAgent.create.scanFailed')}+ type={'error'}+ action={+ <Button size={'small'} onClick={rescan}>+ {t('connectAgent.create.rescan')}+ </Button>+ }+ />+ )}++ {scanState.status === 'success' && detectedCount === 0 && (+ <Flexbox align={'center'} gap={12} paddingBlock={24}>+ <Icon icon={ScanSearch} size={28} />+ <Text strong>{t('connectAgent.create.noneDetected')}</Text>+ <Text style={{ textAlign: 'center' }} type={'secondary'}>+ {t('connectAgent.create.noneDetectedHint')}+ </Text>+ <span className={styles.cmd}>npm install -g @anthropic-ai/claude-code</span>+ <Button+ icon={<Icon icon={RefreshCw} size={13} />}+ size={'small'}+ type={'primary'}+ onClick={rescan}+ >+ {t('connectAgent.create.rescanDevice')}+ </Button>+ </Flexbox>+ )}++ {scanState.status === 'success' && detectedCount > 0 && (+ <Flexbox gap={6}>+ <SectionLabel>+ {t('connectAgent.create.detectedCount', { total: detectedCount })}+ </SectionLabel>+ <div className={styles.groupList}>+ {inventory.map(({ provider, status }) => (+ <AgentScanRow+ key={provider.type}+ provider={provider}+ selected={selectedTypes.includes(provider.type)}+ status={status}+ subtitle={t(`connectAgent.providerDesc.${provider.type}`)}+ unavailableText={t('connectAgent.create.notInstalled')}+ onToggle={() => toggleType(provider)}+ />+ ))}+ </div>+ </Flexbox>+ )}++ {createError && (+ <Alert+ showIcon+ description={createError}+ message={t('connectAgent.create.createFailed')}+ type={'error'}+ />+ )}++ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Button+ icon={<Icon icon={ArrowLeft} size={14} />}+ type={'text'}+ onClick={() => setStep(0)}+ >+ {t('connectAgent.create.back')}+ </Button>+ <Flexbox horizontal align={'center'} gap={8}>+ {single && (+ <Button type={'text'} onClick={goConfirm}>+ {t('connectAgent.create.customizeName')}+ </Button>+ )}+ <Tooltip+ title={selectedProviders.length > 0 ? '' : t('connectAgent.create.selectFirst')}+ >+ <Button+ disabled={selectedProviders.length === 0}+ loading={creating}+ type={'primary'}+ onClick={() => void handleCreate()}+ >+ {selectedProviders.length === 0+ ? t('connectAgent.create.connect')+ : selectedProviders.length === 1+ ? t('connectAgent.create.connectOne', { name: selectedProviders[0].title })+ : t('connectAgent.create.connectMany', { total: selectedProviders.length })}+ </Button>+ </Tooltip>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+ }++ // ── Step 3: confirm (optional customization, single-select only) ──+ if (step === 2 && single) {+ return (+ <Flexbox gap={16} paddingBlock={'16px 8px'}>+ <SectionLabel>{t('connectAgent.create.stepConfirm')}</SectionLabel>+ <Flexbox horizontal align={'center'} gap={12}>+ <single.brand.Avatar size={44} />+ <Flexbox flex={1}>+ <Input+ maxLength={60}+ placeholder={t('connectAgent.create.namePlaceholder')}+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </Flexbox>+ </Flexbox>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 2 }}+ maxLength={200}+ placeholder={t('connectAgent.create.descriptionPlaceholder')}+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ />+ <div className={styles.groupList}>+ <div className={`${styles.row} ${styles.rowStatic}`}>+ <div className={styles.iconBox}>+ {target?.kind === 'device' ? (+ getDeviceIcon(target.device.platform, 18)+ ) : (+ <Icon icon={LaptopIcon} size={18} />+ )}+ </div>+ <Flexbox flex={1} gap={1} style={{ minWidth: 0 }}>+ <Text fontSize={13}>+ {t('connectAgent.create.runsOn', { device: targetLabel })}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {single.title}+ {singleVersion ? ` ${singleVersion}` : ''} ·{' '}+ {t('connectAgent.create.detectedInScan')}+ </Text>+ </Flexbox>+ <Icon color={cssVar.colorSuccess} icon={CheckCircle2} size={16} />+ </div>+ </div>+ {createError && (+ <Alert+ showIcon+ description={createError}+ message={t('connectAgent.create.createFailed')}+ type={'error'}+ />+ )}+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Button+ icon={<Icon icon={ArrowLeft} size={14} />}+ type={'text'}+ onClick={() => setStep(1)}+ >+ {t('connectAgent.create.back')}+ </Button>+ <Button+ disabled={!name.trim()}+ loading={creating}+ type={'primary'}+ onClick={() => void handleCreate({ description, name })}+ >+ {t('connectAgent.create.connectOne', { name: single.title })}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ }++ return null;+ },+);++ConnectAgentContent.displayName = 'ConnectAgentContent';++export interface OpenConnectAgentModalOptions {+ groupId?: string;+ visibility?: 'private' | 'public';+}++export const openConnectAgentModal = (options?: OpenConnectAgentModalOptions): ModalInstance => {+ // The done view promotes the result into the modal title ("N agents+ // connected") — content updates it through the instance, which only exists+ // after createModal returns, hence the holder indirection.+ const holder: { instance?: ModalInstance } = {};+ holder.instance = createModal({+ content: (+ <ConnectAgentContent+ groupId={options?.groupId}+ visibility={options?.visibility}+ onTitleChange={(title) => holder.instance?.update({ title })}+ />+ ),+ footer: null,+ maskClosable: true,+ styles: { content: { paddingBlockStart: 0 } },+ title: i18nT('connectAgent.create.title', { ns: 'chat' }),+ width: 520,+ });+ return holder.instance;+};diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.tsnew file mode 100644index 00000000000..1c73a64d231--- /dev/null+++ b/src/features/ConnectAgent/providers.ts@@ -0,0 +1,63 @@+import {+ type HeterogeneousAgentType,+ type LocalHeterogeneousAgentType,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+ type RemoteHeterogeneousAgentType,+} from '@lobechat/heterogeneous-agents';+import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';+import { Amp, ClaudeCode, Codex, HermesAgent, OpenClaw, OpenCode } from '@lobehub/icons';++/**+ * One row in the connect wizard's agent inventory. `kind` mirrors the domain+ * split: `cli` agents spawn as processes (locally or on a bound device),+ * `platform` agents are always device-bound and reached over the gateway.+ */+export interface ConnectableProvider {+ /** CDN avatar to stamp on created cli agents (platform agents use the device profile's). */+ avatar?: string;+ /** Compound brand icon module — render via `icon.Avatar`. */+ brand:+ | typeof Amp+ | typeof ClaudeCode+ | typeof Codex+ | typeof HermesAgent+ | typeof OpenClaw+ | typeof OpenCode;+ /** Spawn command — cli providers only. */+ command?: string;+ kind: 'cli' | 'platform';+ title: string;+ type: HeterogeneousAgentType;+}++const CLI_BRANDS: Record<LocalHeterogeneousAgentType, ConnectableProvider['brand']> = {+ 'amp': Amp,+ 'claude-code': ClaudeCode,+ 'codex': Codex,+ 'opencode': OpenCode,+};++const PLATFORM_BRANDS: Record<RemoteHeterogeneousAgentType, ConnectableProvider['brand']> = {+ hermes: HermesAgent,+ openclaw: OpenClaw,+};++export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = [+ ...HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((config) => ({+ avatar: config.avatar,+ brand: CLI_BRANDS[config.type],+ command: config.command,+ kind: 'cli' as const,+ title: config.title,+ type: config.type,+ })),+ ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((config) => ({+ brand: PLATFORM_BRANDS[config.type],+ kind: 'platform' as const,+ title: config.title,+ type: config.type,+ })),+];++export const getConnectableProvider = (type: HeterogeneousAgentType) =>+ CONNECTABLE_PROVIDERS.find((provider) => provider.type === type);diff --git a/src/features/ConnectAgent/useAgentScan.ts b/src/features/ConnectAgent/useAgentScan.tsnew file mode 100644index 00000000000..99fb7cd153b--- /dev/null+++ b/src/features/ConnectAgent/useAgentScan.ts@@ -0,0 +1,84 @@+import type { HeterogeneousAgentScanMap } from '@lobechat/heterogeneous-agents';+import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';+import type { DeviceListItem } from '@lobechat/types';+import { useCallback, useRef, useState } from 'react';++import { deviceService } from '@/services/device';+import { binaryService } from '@/services/electron/binary';++/**+ * Where the wizard scans for installed agents: the local desktop machine+ * (agents run as desktop subprocesses) or a gateway-connected device.+ */+export type ScanTarget = { device: DeviceListItem; kind: 'device' } | { kind: 'local' };++export interface AgentScanState {+ agents: HeterogeneousAgentScanMap | null;+ error?: string;+ status: 'error' | 'idle' | 'scanning' | 'success';+}++const IDLE: AgentScanState = { agents: null, status: 'idle' };++/**+ * Local scans probe the four CLI agents through the desktop binary detector+ * (which + login-shell PATH + well-known install paths). Platform agents+ * (openclaw / hermes) are device-bound by design, so a local target never+ * reports them — the inventory simply omits those rows.+ */+const scanLocal = async (): Promise<HeterogeneousAgentScanMap> => {+ const entries = await Promise.all(+ HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map(async (config) => {+ try {+ const status = await binaryService.detectHeterogeneousAgentCommand({+ agentType: config.type,+ command: config.command,+ });+ return [config.type, { available: status.available, version: status.version }] as const;+ } catch {+ return [config.type, { available: false }] as const;+ }+ }),+ );+ return Object.fromEntries(entries);+};++export const useAgentScan = () => {+ const [state, setState] = useState<AgentScanState>(IDLE);+ const seqRef = useRef(0);++ const scan = useCallback(async (target: ScanTarget) => {+ const seq = ++seqRef.current;+ setState({ agents: null, status: 'scanning' });++ try {+ let agents: HeterogeneousAgentScanMap;+ if (target.kind === 'local') {+ agents = await scanLocal();+ } else {+ const result = await deviceService.scanAgents({ deviceId: target.device.deviceId });+ if (result.error) {+ if (seq === seqRef.current)+ setState({ agents: null, error: result.error, status: 'error' });+ return;+ }+ agents = result.agents;+ }+ if (seq === seqRef.current) setState({ agents, status: 'success' });+ } catch (error) {+ if (seq === seqRef.current)+ setState({+ agents: null,+ error: error instanceof Error ? error.message : String(error),+ status: 'error',+ });+ }+ }, []);++ const reset = useCallback(() => {+ seqRef.current += 1;+ setState(IDLE);+ }, []);++ return { reset, scan, state };+};diff --git a/src/features/CreatePlatformAgent/index.tsx b/src/features/CreatePlatformAgent/index.tsxdeleted file mode 100644index 5c83e89a68c..00000000000--- a/src/features/CreatePlatformAgent/index.tsx+++ /dev/null@@ -1,552 +0,0 @@-'use client';--import {- REMOTE_HETEROGENEOUS_AGENT_CONFIGS,- type RemoteHeterogeneousAgentType,-} from '@lobechat/heterogeneous-agents';-import { Flexbox, Icon } from '@lobehub/ui';-import {- Button as BaseButton,- Button,- createModal,- type ModalInstance,- Select,- useModalContext,-} from '@lobehub/ui/base-ui';-import { Alert, Input, Steps, Tag, Typography } from 'antd';-import { createStaticStyles, cssVar } from 'antd-style';-import { t as i18nT } from 'i18next';-import {- BotIcon,- CheckCircle2,- Download,- MonitorSmartphone,- RefreshCw,- XCircle,-} from 'lucide-react';-import { memo, useCallback, useEffect, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { DOWNLOAD_URL } from '@/const/url';-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { deviceService } from '@/services/device';-import { useAgentStore } from '@/store/agent';-import { useHomeStore } from '@/store/home';--const styles = createStaticStyles(({ css }) => ({- avatarPreview: css`- display: flex;- align-items: center;- justify-content: center;-- width: 48px;- height: 48px;- border-radius: ${cssVar.borderRadiusLG};-- font-size: 28px;- line-height: 1;-- background: ${cssVar.colorFillSecondary};- `,- deviceItem: css`- display: flex;- gap: 8px;- align-items: center;- `,- platformCard: css`- cursor: pointer;-- display: flex;- flex-direction: column;- gap: 4px;- align-items: flex-start;-- padding-block: 12px;- padding-inline: 16px;- border: 1.5px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgContainer};-- transition: border-color 0.2s;-- &:hover {- border-color: ${cssVar.colorPrimary};- }-- &[data-selected='true'] {- border-color: ${cssVar.colorPrimary};- background: ${cssVar.colorPrimaryBg};- }- `,- platformDesc: css`- font-size: 13px;- color: ${cssVar.colorTextSecondary};- `,- platformName: css`- font-size: 15px;- font-weight: 500;- color: ${cssVar.colorText};- `,-}));--interface AgentProfile {- avatar?: string;- description?: string;- title?: string;-}--interface CreatePlatformAgentContentProps {- groupId?: string;- visibility?: 'private' | 'public';-}--const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(- ({ groupId, visibility }) => {- const { t } = useTranslation('chat');- const { close, setCanDismissByClickOutside } = useModalContext();- const navigate = useWorkspaceAwareNavigate();- const storeCreateAgent = useAgentStore((s) => s.createAgent);- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);-- // Creating from a workspace context: the new agent inherits the active- // workspace's scope (server-side), so the device picker must restrict to- // workspace devices — a workspace agent bound to a personal device is- // unreachable to other members and the server rejects the write.- const activeWorkspaceId = useActiveWorkspaceId();- const restrictToWorkspaceDevices = Boolean(activeWorkspaceId);-- const [step, setStep] = useState(0);- const [platform, setPlatform] = useState<RemoteHeterogeneousAgentType>('openclaw');- const [deviceId, setDeviceId] = useState<string | undefined>(undefined);- const [agentName, setAgentName] = useState('');- const [agentDescription, setAgentDescription] = useState('');- const [agentProfile, setAgentProfile] = useState<AgentProfile | null>(null);- const [fetchingProfile, setFetchingProfile] = useState(false);- const [creating, setCreating] = useState(false);- useEffect(() => {- setCanDismissByClickOutside(!creating);- }, [creating, setCanDismissByClickOutside]);- const [capabilityResult, setCapabilityResult] = useState<- { available: boolean; reason?: string; version?: string } | undefined- >(undefined);- const [checkingCapability, setCheckingCapability] = useState(false);-- const platformDefs = REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => ({- desc: t(`platformAgent.create.desc.${c.type}`),- name: c.title,- type: c.type,- }));-- // Workspace-keyed SWR fetch (see useDeviceList) — the raw lambdaQuery key- // has no workspace dimension, so the wizard listed the previous- // workspace's pool after a switch.- const {- data: devices,- isLoading: loadingDevices,- isValidating: fetchingDevices,- mutate: refetchDevices,- } = useDeviceList();-- const selectedPlatformDef = platformDefs.find((p) => p.type === platform)!;-- useEffect(() => {- if (step !== 2) return;- if (agentProfile !== null) {- if (!agentName) setAgentName(agentProfile.title ?? selectedPlatformDef.name);- if (!agentDescription) setAgentDescription(agentProfile.description ?? '');- } else if (!fetchingProfile && !agentName) {- setAgentName(selectedPlatformDef.name);- }- }, [- agentDescription,- agentName,- agentProfile,- fetchingProfile,- selectedPlatformDef.name,- step,- ]);-- const handlePlatformChange = useCallback((type: RemoteHeterogeneousAgentType) => {- setPlatform(type);- // Reset device + capability state — capability is platform-specific;- // stale results from the previous platform must not carry over.- setDeviceId(undefined);- setCapabilityResult(undefined);- setAgentProfile(null);- }, []);-- const checkCapability = useCallback(- async (dId: string) => {- setCheckingCapability(true);- setCapabilityResult(undefined);- try {- const result = await deviceService.checkCapability({- deviceId: dId,- platform,- });- setCapabilityResult(result);- } catch {- setCapabilityResult({ available: false, reason: t('platformAgent.create.checkFailed') });- } finally {- setCheckingCapability(false);- }- },- [platform, t],- );-- const fetchProfile = useCallback(- async (dId: string) => {- setFetchingProfile(true);- setAgentProfile(null);- try {- const profile = await deviceService.getAgentProfile({- deviceId: dId,- platform,- });- setAgentProfile(profile);- } catch {- setAgentProfile({});- } finally {- setFetchingProfile(false);- }- },- [platform],- );-- const handleDeviceChange = useCallback(- (dId: string) => {- setDeviceId(dId);- void checkCapability(dId);- void fetchProfile(dId);- },- [checkCapability, fetchProfile],- );-- const handleNext = useCallback(() => {- setStep((s) => s + 1);- }, []);-- const handleBack = useCallback(() => {- setStep((s) => s - 1);- }, []);-- const handleCreate = useCallback(async () => {- if (!deviceId) return;- setCreating(true);- try {- const title = agentName.trim() || selectedPlatformDef.name;- const result = await storeCreateAgent({- config: {- agencyConfig: {- boundDeviceId: deviceId,- heterogeneousProvider: {- type: platform,- },- },- avatar: agentProfile?.avatar || undefined,- description: agentDescription.trim() || undefined,- title,- },- groupId,- visibility,- });- await refreshAgentList();- close();- navigate(`/agent/${result.agentId}`);- } finally {- setCreating(false);- }- }, [- deviceId,- agentName,- agentDescription,- agentProfile,- platform,- groupId,- visibility,- storeCreateAgent,- refreshAgentList,- close,- navigate,- selectedPlatformDef.name,- ]);-- const renderCapabilityStatus = () => {- if (!deviceId) return null;- if (checkingCapability)- return <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgent.create.checking')}</Tag>;- if (!capabilityResult) return null;- if (capabilityResult.available) {- return (- <Flexbox horizontal align="flex-start" gap={4} style={{ flexWrap: 'wrap' }}>- <Icon- color="var(--ant-color-success)"- icon={CheckCircle2}- size={14}- style={{ marginTop: 2, flexShrink: 0 }}- />- <Tag- color="success"- style={{ marginInlineEnd: 0, whiteSpace: 'normal', wordBreak: 'break-word' }}- >- {capabilityResult.version ?? t('platformAgent.create.available')}- </Tag>- </Flexbox>- );- }-- 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} />- <Tag color="error" style={{ marginInlineEnd: 0 }}>- {capabilityResult.reason ??- t('platformAgent.create.notInstalled', { name: selectedPlatformDef.name })}- </Tag>- </Flexbox>- );- };-- const step2NextDisabled =- !deviceId || checkingCapability || capabilityResult?.available === false;-- const renderStepContent = () => {- if (step === 0) {- return (- <Flexbox gap={12}>- {platformDefs.map((def) => (- <div- className={styles.platformCard}- data-selected={platform === def.type}- key={def.type}- role="button"- tabIndex={0}- onClick={() => handlePlatformChange(def.type)}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') handlePlatformChange(def.type);- }}- >- <Flexbox horizontal align="center" gap={8}>- <Icon icon={MonitorSmartphone} size={18} />- <span className={styles.platformName}>{def.name}</span>- </Flexbox>- <span className={styles.platformDesc}>{def.desc}</span>- </div>- ))}- </Flexbox>- );- }-- if (step === 1) {- const onlineDevices = (devices ?? []).filter(- (d) => d.online && (!restrictToWorkspaceDevices || d.scope === 'workspace'),- );- const isRefreshing = loadingDevices || fetchingDevices;-- const refreshButton = (- <Button- icon={<Icon icon={RefreshCw} size={13} />}- loading={isRefreshing}- size="small"- type="text"- onClick={() => void refetchDevices()}- >- {t('platformAgent.create.refresh')}- </Button>- );-- if (!isRefreshing && onlineDevices.length === 0) {- return (- <Flexbox gap={12}>- <Alert- showIcon- message={t('platformAgent.create.noDevices')}- type="info"- description={- <Flexbox gap={12}>- <Flexbox gap={6}>- <span>{t('platformAgent.create.noDevicesDesktopHint')}</span>- <a href={DOWNLOAD_URL.default} 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>- );- }-- return (- <Flexbox gap={12}>- <Flexbox horizontal align="center" gap={8}>- <Select- loading={isRefreshing}- placeholder={t('platformAgent.create.selectDevice')}- style={{ flex: 1 }}- value={deviceId}- options={onlineDevices.map((d) => ({- label: (- <div className={styles.deviceItem}>- <Icon icon={BotIcon} size={14} />- <span>{d.hostname}</span>- <Tag color="success" style={{ marginInlineEnd: 0 }}>- {t('platformAgent.device.online')}- </Tag>- </div>- ),- value: d.deviceId,- }))}- onChange={handleDeviceChange}- />- {refreshButton}- </Flexbox>- {renderCapabilityStatus()}- </Flexbox>- );- }-- if (step === 2) {- const avatar = agentProfile?.avatar;- return (- <Flexbox gap={12}>- {avatar && (- <Flexbox horizontal align="center" gap={12}>- <div className={styles.avatarPreview}>{avatar}</div>- </Flexbox>- )}- <Input- maxLength={60}- value={agentName}- placeholder={- fetchingProfile- ? t('platformAgent.create.fetchingProfile')- : t('platformAgent.create.namePlaceholder')- }- onChange={(e) => setAgentName(e.target.value)}- onPressEnter={() => void handleCreate()}- />- <Input.TextArea- autoSize={{ maxRows: 4, minRows: 2 }}- maxLength={200}- placeholder={t('platformAgent.create.descriptionPlaceholder')}- value={agentDescription}- onChange={(e) => setAgentDescription(e.target.value)}- />- </Flexbox>- );- }-- return null;- };-- const renderFooter = () => {- const buttons = [];-- if (step > 0) {- buttons.push(- <BaseButton key="back" onClick={handleBack}>- {t('platformAgent.create.back')}- </BaseButton>,- );- }-- if (step < 2) {- const nextDisabled = step === 1 && step2NextDisabled;- buttons.push(- <BaseButton disabled={nextDisabled} key="next" type="primary" onClick={handleNext}>- {t('platformAgent.create.next')}- </BaseButton>,- );- }-- if (step === 2) {- buttons.push(- <BaseButton- disabled={!agentName.trim() && !selectedPlatformDef.name}- key="create"- loading={creating}- type="primary"- onClick={() => void handleCreate()}- >- {creating ? t('platformAgent.create.creating') : t('platformAgent.create.create')}- </BaseButton>,- );- }-- return buttons;- };-- return (- <Flexbox gap={24} paddingBlock={'16px 8px'}>- <Steps- current={step}- size="small"- items={[- { title: t('platformAgent.create.step1') },- { title: t('platformAgent.create.step2') },- { title: t('platformAgent.create.step3') },- ]}- />- {renderStepContent()}- <Flexbox horizontal gap={8} justify={'flex-end'}>- {renderFooter()}- </Flexbox>- </Flexbox>- );- },-);--CreatePlatformAgentContent.displayName = 'CreatePlatformAgentContent';--interface OpenCreatePlatformAgentModalOptions {- groupId?: string;- visibility?: 'private' | 'public';-}--export const openCreatePlatformAgentModal = (- options?: OpenCreatePlatformAgentModalOptions,-): ModalInstance =>- createModal({- content: (- <CreatePlatformAgentContent groupId={options?.groupId} visibility={options?.visibility} />- ),- footer: null,- maskClosable: true,- title: i18nT('platformAgent.create.title', { ns: 'chat' }),- width: 480,- });diff --git a/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx b/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsxindex 9ef4e79e413..554da5daf2c 100644--- a/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/CreateAgentButton.tsx@@ -51,9 +51,8 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vicreateAgent,createAgentListMenuItem,createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,- createPlatformAgentMenuItem,createMarketAgentMenuItem,isMutatingAgent,openCreateModal,@@ -73,8 +72,7 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vi);const dropdownItems = useMemo(() => {- const heteroItems = createHeterogeneousAgentMenuItems(menuOptions);- const platformItem = createPlatformAgentMenuItem(menuOptions);+ const connectItem = createConnectAgentMenuItem(menuOptions);// Discovery entries stay available for the private bucket too — they only// navigate (list / market), so the bucket merely decides which tab the// agent-list page opens on.@@ -82,8 +80,7 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vireturn [createAgentMenuItem(menuOptions),createGroupChatMenuItem(menuOptions),- ...(heteroItems.length > 0 ? [{ type: 'divider' as const }, ...heteroItems] : []),- ...(platformItem ? [{ type: 'divider' as const }, platformItem] : []),+ ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),...(showDiscoveryItems? [{ type: 'divider' as const },@@ -95,10 +92,9 @@ const CreateAgentButton = memo<CreateAgentButtonProps>(({ groupId, className, vi}, [createAgentListMenuItem,createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,createMarketAgentMenuItem,- createPlatformAgentMenuItem,isCustomGroup,menuOptions,visibility,diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsxindex 2511abee0f4..b0b8b90c452 100644--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx@@ -13,7 +13,6 @@ import {useState,} from 'react';-import { openCreatePlatformAgentModal } from '@/features/CreatePlatformAgent';import EditingPopover from '@/features/EditingPopover';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useAgentStore } from '@/store/agent';@@ -63,7 +62,6 @@ interface AgentModalContextValue {openConfigGroupModal: (scope?: 'private' | 'public') => void;openCreateGroupModal: (sessionId?: string, visibility?: 'private' | 'public') => void;openCreateModal: (type: 'agent' | 'group', options?: OpenCreateModalOptions) => void;- openCreatePlatformAgentModal: (options?: OpenCreateModalOptions) => void;openGroupWizardModal: (callbacks: GroupWizardCallbacks) => void;openMemberSelectionModal: (callbacks: MemberSelectionCallbacks) => void;setGroupWizardLoading: (loading: boolean) => void;@@ -226,12 +224,6 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =setCreateModalVisibility(options?.visibility);setCreateModalOpen(true);},- openCreatePlatformAgentModal: (options?: OpenCreateModalOptions) => {- openCreatePlatformAgentModal({- groupId: options?.groupId,- visibility: options?.visibility,- });- },openGroupWizardModal: (callbacks: GroupWizardCallbacks) => {setGroupWizardCallbacks(callbacks);setGroupWizardOpen(true);diff --git a/src/routes/(main)/home/_layout/Body/Private/index.tsx b/src/routes/(main)/home/_layout/Body/Private/index.tsxindex 05bcfe9f340..2e3d191a453 100644--- a/src/routes/(main)/home/_layout/Body/Private/index.tsx+++ b/src/routes/(main)/home/_layout/Body/Private/index.tsx@@ -37,10 +37,9 @@ const Private = memo<PrivateProps>(({ itemKey }) => {const {createAgentListMenuItem,createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,createMarketAgentMenuItem,- createPlatformAgentMenuItem,isLoading,} = useCreateMenuItems();@@ -48,16 +47,12 @@ const Private = memo<PrivateProps>(({ itemKey }) => {// across both buckets — heterogeneous and platform agents are hard-pinned// to private here. Session-group creation lives in the "More" dropdown.const addMenuItems = useMemo(() => {- const heterogeneousItems = createHeterogeneousAgentMenuItems({ visibility: 'private' });- const platformItem = createPlatformAgentMenuItem({ visibility: 'private' });+ const connectItem = createConnectAgentMenuItem({ visibility: 'private' });return [createAgentMenuItem({ visibility: 'private' }),createGroupChatMenuItem({ visibility: 'private' }),- ...(heterogeneousItems.length > 0- ? [{ type: 'divider' as const }, ...heterogeneousItems]- : []),- ...(platformItem ? [{ type: 'divider' as const }, platformItem] : []),+ ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),// Same discovery entries as the workspace-public section — the agent// list opens on the Private tab so the surface matches this bucket.{ type: 'divider' as const },@@ -67,10 +62,9 @@ const Private = memo<PrivateProps>(({ itemKey }) => {}, [createAgentListMenuItem,createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,createMarketAgentMenuItem,- createPlatformAgentMenuItem,]);const handleOpenConfigGroupModal = useCallback(() => {diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsxindex b5cdbb8c713..18aef887506 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.test.tsx@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*/-import { act, renderHook } from '@testing-library/react';+import { act, render, renderHook, screen } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { useCreateMenuItems } from './useCreateMenuItems';@@ -15,6 +15,7 @@ const loadGroupsMock = vi.hoisted(() => vi.fn());const createNewPageMock = vi.hoisted(() => vi.fn());const messageErrorMock = vi.hoisted(() => vi.fn());const navigateMock = vi.hoisted(() => vi.fn());+const openConnectAgentModalMock = vi.hoisted(() => vi.fn());const openCreateGroupModalMock = vi.hoisted(() => vi.fn());const agentModalMock = vi.hoisted(() => ({current: undefined as { openCreateGroupModal: (id?: string, v?: string) => void } | undefined,@@ -24,53 +25,10 @@ vi.mock('@lobechat/const', () => ({isDesktop: true,}));-vi.mock('@lobechat/heterogeneous-agents/client', () => ({- HETEROGENEOUS_AGENT_CLIENT_CONFIGS: [- {- avatar: 'claude-avatar',- command: 'claude',- icon: () => null,- iconId: 'ClaudeCode',- menuKey: 'newClaudeCodeAgent',- menuLabelKey: 'newClaudeCodeAgent',- title: 'Claude Code',- type: 'claude-code',- },- {- avatar: 'avatar',- command: 'codex',- icon: () => null,- iconId: 'Codex',- menuKey: 'newCodexAgent',- menuLabelKey: 'newCodexAgent',- title: 'Codex',- type: 'codex',- },- {- avatar: 'amp-avatar',- command: 'amp',- icon: () => null,- iconId: 'Amp',- menuKey: 'newAmpAgent',- menuLabelKey: 'newAmpAgent',- title: 'Amp',- type: 'amp',- },- {- avatar: 'opencode-avatar',- command: 'opencode',- icon: () => null,- iconId: 'OpenCode',- menuKey: 'newOpenCodeAgent',- menuLabelKey: 'newOpenCodeAgent',- title: 'OpenCode',- type: 'opencode',- },- ],-}));-vi.mock('@lobehub/ui', () => ({+ Flexbox: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,Icon: () => null,+ Text: ({ children }: { children?: React.ReactNode }) => <span>{children}</span>,}));vi.mock('@lobehub/ui/icons', () => ({@@ -107,6 +65,10 @@ vi.mock('@/components/ChatGroupWizard/templates', () => ({useGroupTemplates: () => [],}));+vi.mock('@/features/ConnectAgent', () => ({+ openConnectAgentModal: openConnectAgentModalMock,+}));+vi.mock('@/routes/(main)/home/_layout/Body/Agent/ModalProvider', () => ({useOptionalAgentModal: () => agentModalMock.current,}));@@ -148,17 +110,6 @@ vi.mock('@/store/page', () => ({}),}));-vi.mock('@/store/user', () => ({- useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>- selector({ preference: { lab: {} } }),-}));--vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: {- enablePlatformAgent: () => false,- },-}));-const isActionItem = (item: unknown,): item is {@@ -189,10 +140,7 @@ describe('useCreateMenuItems', () => {'newAgent','newGroupChat','divider',- 'newClaudeCodeAgent',- 'newCodexAgent',- 'newAmpAgent',- 'newOpenCodeAgent',+ 'newPlatformAgent','divider','addAgentFromList','addAgentFromMarket',@@ -301,123 +249,37 @@ describe('useCreateMenuItems', () => {expect(configItem.label).toBe('sessionGroup.manageCategory');});- it('creates the Claude Code agent normally when the CLI is available', async () => {- const { result } = renderHook(() => useCreateMenuItems());-- const claudeItem = result.current- .createHeterogeneousAgentMenuItems()- .find((item) => isActionItem(item) && item.key === 'newClaudeCodeAgent');-- if (!isActionItem(claudeItem)) {- throw new Error('Expected Claude Code menu item');- }-- await act(async () => {- await claudeItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });- });-- expect(createAgentMock).toHaveBeenCalledWith({- config: {- agencyConfig: {- heterogeneousProvider: {- command: 'claude',- type: 'claude-code',- },- },- avatar: 'claude-avatar',- provider: 'claude-code',- systemRole: '',- title: 'Claude Code',- },- groupId: undefined,- });- expect(refreshAgentListMock).toHaveBeenCalled();- expect(navigateMock).toHaveBeenCalledWith('/agent/agent-codex');- });-- it('creates the Codex agent normally without preflight interception', async () => {+ it('opens the connect wizard and renders its explanatory label', async () => {const { result } = renderHook(() => useCreateMenuItems());+ const connectItem = result.current.createConnectAgentMenuItem();- const codexItem = result.current- .createHeterogeneousAgentMenuItems()- .find((item) => isActionItem(item) && item.key === 'newCodexAgent');+ if (!isActionItem(connectItem)) throw new Error('Expected Connect Agent menu item');- if (!isActionItem(codexItem)) {- throw new Error('Expected Codex menu item');- }+ render(<>{connectItem.label}</>);+ expect(screen.getByText('newPlatformAgent')).toBeTruthy();+ expect(screen.getByText('newPlatformAgentDesc')).toBeTruthy();await act(async () => {- await codexItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });+ await connectItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });});-- expect(createAgentMock).toHaveBeenCalledWith({- config: {- agencyConfig: {- heterogeneousProvider: {- command: 'codex',- type: 'codex',- },- },- avatar: 'avatar',- provider: 'codex',- systemRole: '',- title: 'Codex',- },- groupId: undefined,- });- expect(refreshAgentListMock).toHaveBeenCalled();- expect(navigateMock).toHaveBeenCalledWith('/agent/agent-codex');+ expect(openConnectAgentModalMock).toHaveBeenCalledWith(undefined);});- it('creates AMP as an independent local CLI agent', async () => {+ it('threads groupId and visibility into the connect wizard', async () => {const { result } = renderHook(() => useCreateMenuItems());-- const ampItem = result.current- .createHeterogeneousAgentMenuItems()- .find((item) => isActionItem(item) && item.key === 'newAmpAgent');-- if (!isActionItem(ampItem)) throw new Error('Expected AMP menu item');-- await act(async () => {- await ampItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });- });-- expect(createAgentMock).toHaveBeenCalledWith({- config: {- agencyConfig: { heterogeneousProvider: { command: 'amp', type: 'amp' } },- avatar: 'amp-avatar',- provider: 'amp',- systemRole: '',- title: 'Amp',- },- groupId: undefined,+ const connectItem = result.current.createConnectAgentMenuItem({+ groupId: 'group-1',+ visibility: 'private',});- });- it('creates OpenCode as an independent local CLI agent', async () => {- const { result } = renderHook(() => useCreateMenuItems());-- const openCodeItem = result.current- .createHeterogeneousAgentMenuItems()- .find((item) => isActionItem(item) && item.key === 'newOpenCodeAgent');-- if (!isActionItem(openCodeItem)) throw new Error('Expected OpenCode menu item');+ if (!isActionItem(connectItem)) throw new Error('Expected Connect Agent menu item');await act(async () => {- await openCodeItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });+ await connectItem.onClick?.({ domEvent: { stopPropagation: vi.fn() } });});-- expect(createAgentMock).toHaveBeenCalledWith({- config: {- agencyConfig: {- heterogeneousProvider: { command: 'opencode', type: 'opencode' },- },- avatar: 'opencode-avatar',- provider: 'opencode',- systemRole: '',- title: 'OpenCode',- },- groupId: undefined,+ expect(openConnectAgentModalMock).toHaveBeenCalledWith({+ groupId: 'group-1',+ visibility: 'private',});});});diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsxindex 9021686cb34..afde5ec6a06 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx@@ -1,7 +1,5 @@-import { isDesktop } from '@lobechat/const';import type { SFSymbol } from '@lobechat/electron-client-ipc';-import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';-import { Icon } from '@lobehub/ui';+import { Flexbox, Icon, Text } from '@lobehub/ui';import { GroupBotSquareIcon } from '@lobehub/ui/icons';import { App } from 'antd';import type { ItemType } from 'antd/es/menu/interface';@@ -21,8 +19,8 @@ import useSWRMutation from 'swr/mutation';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';+import { openConnectAgentModal } from '@/features/ConnectAgent';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useCreateHeteroAgent } from '@/hooks/useCreateHeteroAgent';import { usePermission } from '@/hooks/usePermission';import { useOptionalAgentModal } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';import type { CreateAgentParams } from '@/services/agent';@@ -32,8 +30,6 @@ import { useAgentStore } from '@/store/agent';import { useAgentGroupStore } from '@/store/agentGroup';import { useHomeStore } from '@/store/home';import { usePageStore } from '@/store/page';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';type MenuItem = NonNullable<ItemType> & { sfSymbol?: SFSymbol };@@ -70,7 +66,6 @@ export const useCreateMenuItems = () => {]);const [createGroup, loadGroups] = useAgentGroupStore((s) => [s.createGroup, s.loadGroups]);const createNewPage = usePageStore((s) => s.createNewPage);- const createHeterogeneousAgent = useCreateHeteroAgent();const [isCreatingGroup, setIsCreatingGroup] = useState(false);const [isCreatingSessionGroup, setIsCreatingSessionGroup] = useState(false);@@ -237,7 +232,6 @@ export const useCreateMenuItems = () => {const agentModal = useOptionalAgentModal();const openCreateModal = agentModal?.openCreateModal;const openCreateGroupModal = agentModal?.openCreateGroupModal;- const enablePlatformAgent = useUserStore(labPreferSelectors.enablePlatformAgent);/*** Create agent menu item@@ -308,47 +302,28 @@ export const useCreateMenuItems = () => {);/**- * Create heterogeneous agent menu items (Desktop only)+ * Connect Agent menu item — the unified device-first wizard for external+ * agents installed on a local or connected machine.*/- const createHeterogeneousAgentMenuItems = useCallback(- (options?: CreateAgentOptions): ItemType[] => {- if (!isDesktop) return [];-- return HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map((definition) => {- const AgentIcon = definition.icon;-- return {- icon: <AgentIcon size={'1em'} />,- disabled: !canCreate,- key: definition.menuKey,- label: t(definition.menuLabelKey),- onClick: async (info) => {- info.domEvent?.stopPropagation();- if (!canCreate) return;-- await createHeterogeneousAgent(definition, options);- },- };- });- },- [canCreate, t, createHeterogeneousAgent],- );-- /**- * Create platform agent menu item (openclaw / hermes — remote device agents)- * Opens the 3-step creation modal- */- const createPlatformAgentMenuItem = useCallback(+ const createConnectAgentMenuItem = useCallback((options?: CreateAgentOptions): MenuItem | null => {- if (!enablePlatformAgent) return null;return {icon: <Icon icon={MonitorSmartphone} />,+ disabled: !canCreate,key: 'newPlatformAgent',- label: t('newPlatformAgent'),+ label: (+ <Flexbox gap={1}>+ <Text>{t('newPlatformAgent')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('newPlatformAgentDesc')}+ </Text>+ </Flexbox>+ ),sfSymbol: 'laptopcomputer.and.iphone',onClick: (info) => {info.domEvent?.stopPropagation();- agentModal?.openCreatePlatformAgentModal(+ if (!canCreate) return;+ openConnectAgentModal(options?.groupId || options?.visibility? { groupId: options?.groupId, visibility: options?.visibility }: undefined,@@ -356,7 +331,7 @@ export const useCreateMenuItems = () => {},};},- [t, agentModal, enablePlatformAgent],+ [t, canCreate],);/**@@ -479,16 +454,12 @@ export const useCreateMenuItems = () => {* so users had no visible entry to `/community/agent`.*/const createTopLevelMenuItems = useCallback((): ItemType[] => {- const heterogeneousItems = createHeterogeneousAgentMenuItems();- const platformItem = createPlatformAgentMenuItem();+ const connectItem = createConnectAgentMenuItem();return [createAgentMenuItem(),createGroupChatMenuItem(),- ...(heterogeneousItems.length > 0- ? [{ type: 'divider' as const }, ...heterogeneousItems]- : []),- ...(platformItem ? [{ type: 'divider' as const }, platformItem] : []),+ ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),{ type: 'divider' as const },createAgentListMenuItem(),createMarketAgentMenuItem(),@@ -496,10 +467,9 @@ export const useCreateMenuItems = () => {}, [createAgentListMenuItem,createAgentMenuItem,+ createConnectAgentMenuItem,createGroupChatMenuItem,- createHeterogeneousAgentMenuItems,createMarketAgentMenuItem,- createPlatformAgentMenuItem,]);return {@@ -507,16 +477,14 @@ export const useCreateMenuItems = () => {createAgent,createAgentListMenuItem,createAgentMenuItem,+ createConnectAgentMenuItem,createEmptyGroup,createGroupChatMenuItem,createGroupFromTemplate,- createHeterogeneousAgent,- createHeterogeneousAgentMenuItems,createGroupWithMembers,createMarketAgentMenuItem,createPage,createPageMenuItem,- createPlatformAgentMenuItem,createSessionGroupMenuItem,createTopLevelMenuItems,openCreateModal,diff --git a/src/services/device.ts b/src/services/device.tsindex 7098def82d1..066b307a8f6 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -35,6 +35,11 @@ class DeviceService {getAgentProfile(input: Parameters<DeviceClient['getAgentProfile']['query']>[0]) {return lambdaClient.device.getAgentProfile.query(input);}++ /** Scan a device for every known heterogeneous agent type in one pass. */+ scanAgents(input: Parameters<DeviceClient['scanAgents']['query']>[0]) {+ return lambdaClient.device.scanAgents.query(input);+ }}export const deviceService = new DeviceService();