🤯 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(hetero-agent): execution target switcher in composer (#15179)
Arvin Xu3c529981571b
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 5e974c1d087..bace4a7946e 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -28,8 +28,8 @@"agentSignal.receipts.memory.detail": "Saved this for future replies","agentSignal.receipts.memory.title": "Memory saved","agentSignal.receipts.recentActivity": "Recent activity",- "agentSignal.receipts.skill.detail": "Improved how this assistant handles similar requests",- "agentSignal.receipts.skill.title": "Skill updated",+ "agentSignal.receipts.skill.detail": "Self-refined how this agent handles similar requests",+ "agentSignal.receipts.skill.title": "Auto-learned a new skill","agents": "Agents","artifact.generating": "Generating","artifact.inThread": "Cannot view in subtopic, please switch to the main conversation area to open",@@ -208,6 +208,17 @@"heteroAgent.cloudRepo.noRepos": "No repositories configured. Add them in agent settings.","heteroAgent.cloudRepo.notSet": "No repo selected","heteroAgent.cloudRepo.sectionTitle": "Repositories",+ "heteroAgent.executionTarget.infoTooltip": "Pick a remote device to drive that machine from the web. \"This device\" runs the agent locally and is only available inside the desktop app.",+ "heteroAgent.executionTarget.loading": "Loading devices…",+ "heteroAgent.executionTarget.local": "This device",+ "heteroAgent.executionTarget.localDesc": "Run as a local process on this desktop app",+ "heteroAgent.executionTarget.noDevices": "No remote devices yet. Install the desktop app or run `lh connect` on another machine.",+ "heteroAgent.executionTarget.offline": "Offline",+ "heteroAgent.executionTarget.online": "Online",+ "heteroAgent.executionTarget.sandbox": "Cloud sandbox",+ "heteroAgent.executionTarget.sandboxDesc": "Run in an ephemeral cloud sandbox",+ "heteroAgent.executionTarget.title": "Execution Device",+ "heteroAgent.executionTarget.unknownDevice": "Unknown device","heteroAgent.fullAccess.label": "Full access","heteroAgent.fullAccess.tooltip": "Claude Code runs locally with full read/write access to the working directory. Switching permission modes is not available yet.","heteroAgent.resumeReset.cwdChanged": "Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex 4409b0e1a13..0edd70bd946 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -3,6 +3,8 @@"features.agentSelfIteration.title": "Agent Self-iteration","features.assistantMessageGroup.desc": "Group agent messages and their tool call results together for display","features.assistantMessageGroup.title": "Agent Message Grouping",+ "features.executionDeviceSwitcher.desc": "Surface the execution-device switcher in the heterogeneous agent toolbar so you can route runs to this device, a cloud sandbox, or a bound remote device.",+ "features.executionDeviceSwitcher.title": "Execution Device Switcher","features.gatewayMode.desc": "Execute agent tasks on the server via Gateway WebSocket instead of running locally. Enables faster execution and reduces client resource usage.","features.gatewayMode.title": "Server-Side Agent Execution (Gateway)","features.groupChat.desc": "Enable multi-agent group chat coordination.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 429d4884bd5..ea78c7a17d4 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -28,8 +28,8 @@"agentSignal.receipts.memory.detail": "已保存以供未来回复使用","agentSignal.receipts.memory.title": "记忆已保存","agentSignal.receipts.recentActivity": "最近活动",- "agentSignal.receipts.skill.detail": "改进了此助手处理类似请求的方式",- "agentSignal.receipts.skill.title": "技能已更新",+ "agentSignal.receipts.skill.detail": "已自主优化处理相似请求的方式",+ "agentSignal.receipts.skill.title": "已自动习得新技能","agents": "助理","artifact.generating": "生成中","artifact.inThread": "子话题中暂不支持查看。请回到主对话区打开",@@ -208,6 +208,17 @@"heteroAgent.cloudRepo.noRepos": "未配置仓库,请在助理设置中添加。","heteroAgent.cloudRepo.notSet": "未选择仓库","heteroAgent.cloudRepo.sectionTitle": "代码仓库",+ "heteroAgent.executionTarget.infoTooltip": "选择「远程设备」后可在网页中驱动该机器;「本机」仅在桌面端内运行 agent。",+ "heteroAgent.executionTarget.loading": "正在加载设备…",+ "heteroAgent.executionTarget.local": "本机",+ "heteroAgent.executionTarget.localDesc": "在当前桌面端以本地进程运行",+ "heteroAgent.executionTarget.noDevices": "暂无远程设备。在另一台机器上安装桌面端或执行 `lh connect` 接入。",+ "heteroAgent.executionTarget.offline": "离线",+ "heteroAgent.executionTarget.online": "在线",+ "heteroAgent.executionTarget.sandbox": "云端沙箱",+ "heteroAgent.executionTarget.sandboxDesc": "在临时云端沙箱中运行",+ "heteroAgent.executionTarget.title": "执行设备",+ "heteroAgent.executionTarget.unknownDevice": "未知设备","heteroAgent.fullAccess.label": "完全访问权限","heteroAgent.fullAccess.tooltip": "Claude Code 在本地运行,对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。","heteroAgent.resumeReset.cwdChanged": "工作目录已切换,之前的 Claude Code 会话只能在原目录下继续,已开始新对话。",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex e54b59b41f7..a4ab7bf8112 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -3,6 +3,8 @@"features.agentSelfIteration.title": "Agent 自我迭代","features.assistantMessageGroup.desc": "将代理消息及其工具调用结果组合在一起显示","features.assistantMessageGroup.title": "代理消息分组",+ "features.executionDeviceSwitcher.desc": "在异构 Agent 工具栏中展示「执行设备」切换器,可将运行任务路由到本机、云端沙箱或已绑定的远程设备。",+ "features.executionDeviceSwitcher.title": "执行设备切换器","features.gatewayMode.desc": "通过 Gateway 在服务端执行 Agent 任务。可实现关闭浏览器后仍然执行 agent。","features.gatewayMode.title": "服务端代理执行(Gateway)","features.groupChat.desc": "启用多代理协同群聊功能。",diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex b57687de3a2..60eacd0236a 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -36,18 +36,31 @@ export interface HeterogeneousProviderConfig {type: 'claude-code' | 'codex' | 'hermes' | 'openclaw';}+/**+ * Where a hetero agent runs.+ * - `local` : in-process spawn on the user's Electron desktop (desktop only)+ * - `device` : dispatched to an `lh connect` device identified by `boundDeviceId`+ * - `sandbox` : server-spawned cloud sandbox+ *+ * Remote hetero agents (`openclaw` | `hermes`) are always `device`.+ */+export type HeteroExecutionTarget = 'device' | 'local' | 'sandbox';+/*** Agent agency configuration.* Contains settings for agent execution modes and device binding.- *- * For remote hetero agents (`type: 'openclaw' | 'hermes'`), `boundDeviceId`- * identifies the target `lh connect` device and is required.*/export interface LobeAgentAgencyConfig {/*** Device ID of the machine connected via `lh connect`.- * Required when `heterogeneousProvider.type` is `'openclaw'` or `'hermes'`.+ * Required when `executionTarget === 'device'` (and always set for remote+ * hetero agents `openclaw` / `hermes`).*/boundDeviceId?: string;+ /**+ * Execution target for the hetero agent. When omitted, the server falls back+ * to `'sandbox'` (or `'device'` for remote hetero providers).+ */+ executionTarget?: HeteroExecutionTarget;heterogeneousProvider?: HeterogeneousProviderConfig;}diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 1c7bb5d314a..83271cf50e0 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -42,6 +42,11 @@ export const UserLabSchema = z.object({* enable agent self-iteration feedback capture and policy execution*/enableAgentSelfIteration: z.boolean().optional(),+ /**+ * surface the execution-device switcher for heterogeneous agents+ * (lets users pick local / cloud sandbox / a bound device)+ */+ enableExecutionDeviceSwitcher: z.boolean().optional(),/*** enable server-side agent execution via Gateway WebSocket*/diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsxindex 6fb60d464fa..f6b6dc3910a 100644--- a/src/features/ChatInput/ActionBar/Plus/index.tsx+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx@@ -15,6 +15,7 @@ import {LibraryBig,PlusIcon,SearchCheck,+ Settings2Icon,Store,TypeIcon,} from 'lucide-react';@@ -35,6 +36,8 @@ import {} from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';import { useFileStore } from '@/store/file';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import { useAgentId } from '../../hooks/useAgentId';@@ -57,7 +60,7 @@ const hotArea = css`const activeLabel = css`display: flex;- gap: 8px;+ gap: 16px;align-items: center;justify-content: space-between;@@ -256,6 +259,14 @@ const PlusAction = memo(() => {const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));const isAgentModeEnabled = useAgentStore(agentSelectors.isAgentModeEnabled);+ const [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel] =+ useGlobalStore((s) => [+ systemStatusSelectors.showRightPanel(s),+ s.status.workingSidebarTab,+ s.setWorkingSidebarTab,+ s.toggleRightPanel,+ ]);+ const isParamsPanelActive = Boolean(showRightPanel) && workingSidebarTab === 'params';const skillActivateMode = useAgentStore((s) =>chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),);@@ -324,6 +335,16 @@ const PlusAction = memo(() => {createSkillStoreModal();}, []);+ const handleToggleParams = useCallback(() => {+ setDropdownOpen(false);+ if (isParamsPanelActive) {+ toggleRightPanel(false);+ return;+ }+ setWorkingSidebarTab('params');+ toggleRightPanel(true);+ }, [isParamsPanelActive, setWorkingSidebarTab, toggleRightPanel]);+const items: ActionDropdownMenuItems = useMemo(() => {const renderActive = (label: string, active: boolean) =>active ? (@@ -443,12 +464,16 @@ const PlusAction = memo(() => {{icon: TypeIcon,key: 'typo',- label: renderActive(- tEditor(showTypoBar ? 'actions.typobar.off' : 'actions.typobar.on'),- Boolean(showTypoBar),- ),+ label: renderActive(tEditor('actions.typobar.on'), Boolean(showTypoBar)),onClick: () => setShowTypoBar(!showTypoBar),},+ // Advanced parameter settings — mirrors ParamsPanelToggle in the agent header.+ {+ icon: Settings2Icon,+ key: 'params',+ label: renderActive(tSetting('settingModel.params.title'), isParamsPanelActive),+ onClick: handleToggleParams,+ },{ type: 'divider' },// Memory toggle{@@ -545,8 +570,10 @@ const PlusAction = memo(() => {handleOpenTools,handleSelectSearch,handleToggleMemory,+ handleToggleParams,isAgentModeEnabled,isMemoryEnabled,+ isParamsPanelActive,knowledgeEnabledCount,setShowTypoBar,showProviderSearch,diff --git a/src/features/ChatInput/RuntimeConfig/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/RuntimeConfig/HeteroDeviceSwitcher.tsxnew file mode 100644index 00000000000..b9191e40f92--- /dev/null+++ b/src/features/ChatInput/RuntimeConfig/HeteroDeviceSwitcher.tsx@@ -0,0 +1,354 @@+'use client';++import { SiApple, SiLinux } from '@icons-pack/react-simple-icons';+import { isDesktop } from '@lobechat/const';+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';+import type { HeteroExecutionTarget } from '@lobechat/types';+import { Microsoft } from '@lobehub/icons';+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ CheckIcon,+ ChevronDownIcon,+ CloudIcon,+ InfoIcon,+ LaptopIcon,+ MonitorIcon,+} from 'lucide-react';+import { memo, type ReactNode, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { lambdaQuery } from '@/libs/trpc/client';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++const styles = createStaticStyles(({ css }) => ({+ button: css`+ cursor: pointer;++ display: flex;+ gap: 6px;+ align-items: center;++ height: 28px;+ padding-inline: 8px;+ border-radius: 6px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ transition: all 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ check: css`+ flex: none;+ margin-inline-start: auto;+ color: ${cssVar.colorPrimary};+ `,+ desc: css`+ display: flex;+ gap: 6px;+ align-items: center;++ font-size: 11px;+ color: ${cssVar.colorTextDescription};+ `,+ dotOffline: css`+ flex: none;++ width: 6px;+ height: 6px;+ border-radius: 50%;++ background: ${cssVar.colorTextQuaternary};+ `,+ dotOnline: css`+ flex: none;++ width: 6px;+ height: 6px;+ border-radius: 50%;++ background: ${cssVar.colorSuccess};+ box-shadow: 0 0 0 2px ${cssVar.colorSuccessBg};+ `,+ empty: css`+ padding-block: 8px;+ padding-inline: 8px;+ font-size: 12px;+ color: ${cssVar.colorTextQuaternary};+ `,+ option: css`+ cursor: pointer;++ display: flex;+ gap: 10px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};++ transition: background-color 0.2s;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ optionActive: css`+ background: ${cssVar.colorFillSecondary};+ `,+ optionDisabled: css`+ cursor: not-allowed;+ opacity: 0.55;++ &:hover {+ background: transparent;+ }+ `,+ optionIcon: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorText};++ background: ${cssVar.colorBgElevated};+ `,+ optionMeta: css`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 1px;++ min-width: 0;+ `,+ optionTitle: css`+ overflow: hidden;++ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ header: css`+ display: flex;+ gap: 6px;+ align-items: center;+ justify-content: space-between;++ padding-block: 6px 4px;+ padding-inline: 8px;+ `,+ headerInfo: css`+ cursor: help;+ color: ${cssVar.colorTextQuaternary};+ transition: color 0.2s;++ &:hover {+ color: ${cssVar.colorTextSecondary};+ }+ `,+ headerTitle: css`+ font-size: 12px;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};+ `,+}));++interface OptionRowProps {+ active: boolean;+ desc?: ReactNode;+ disabled?: boolean;+ icon: ReactNode;+ label: string;+ onClick: () => void;+}++const OptionRow = memo<OptionRowProps>(({ active, desc, disabled, icon, label, onClick }) => {+ return (+ <div+ className={cx(+ styles.option,+ active && styles.optionActive,+ disabled && styles.optionDisabled,+ )}+ onClick={() => {+ if (!disabled) onClick();+ }}+ >+ <div className={styles.optionIcon}>{icon}</div>+ <div className={styles.optionMeta}>+ <div className={styles.optionTitle}>{label}</div>+ {desc ? <div className={styles.desc}>{desc}</div> : null}+ </div>+ {active ? <Icon className={styles.check} icon={CheckIcon} size={14} /> : null}+ </div>+ );+});++OptionRow.displayName = 'HeteroDeviceSwitcher.OptionRow';++const getDeviceIcon = (platform: string | undefined, size = 14): ReactNode => {+ switch (platform) {+ case 'darwin': {+ return <SiApple color="currentColor" size={size} />;+ }+ case 'linux': {+ return <SiLinux color="currentColor" size={size} />;+ }+ case 'win32': {+ return <Microsoft color="currentColor" size={size} />;+ }+ default: {+ return <Icon icon={MonitorIcon} size={size} />;+ }+ }+};++interface HeteroDeviceSwitcherProps {+ agentId: string;+}++const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);++ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));+ const updateAgentConfig = useAgentStore((s) => s.updateAgentConfig);++ const heteroType = agencyConfig?.heterogeneousProvider?.type;+ const storedTarget = agencyConfig?.executionTarget;+ const boundDeviceId = agencyConfig?.boundDeviceId;++ // Effective target: falls back to local on desktop, sandbox on web+ const executionTarget: HeteroExecutionTarget = storedTarget ?? (isDesktop ? 'local' : 'sandbox');++ const { data: devices, isLoading } = lambdaQuery.device.listDevices.useQuery(undefined, {+ staleTime: 30_000,+ });++ const handleSelect = useCallback(+ async (target: HeteroExecutionTarget, deviceId?: string) => {+ setOpen(false);+ await updateAgentConfig({+ agencyConfig: {+ ...agencyConfig,+ executionTarget: target,+ ...(target === 'device' && deviceId ? { boundDeviceId: deviceId } : {}),+ },+ });+ },+ [agencyConfig, updateAgentConfig],+ );++ // Don't render for remote hetero agents — they use RemoteAgentConfigCard in profile.+ if (heteroType && isRemoteHeterogeneousType(heteroType)) return null;++ const boundDevice =+ executionTarget === 'device' ? devices?.find((d) => d.deviceId === boundDeviceId) : undefined;+ const hasNoDevices = !devices || devices.length === 0;++ // Compute chip+ let chipIcon: ReactNode = <Icon icon={CloudIcon} size={14} />;+ let chipLabel = t('heteroAgent.executionTarget.sandbox');+ if (executionTarget === 'local') {+ chipIcon = <Icon icon={LaptopIcon} size={14} />;+ chipLabel = t('heteroAgent.executionTarget.local');+ } else if (executionTarget === 'device') {+ chipIcon = getDeviceIcon(boundDevice?.platform);+ chipLabel = boundDevice?.hostname ?? t('heteroAgent.executionTarget.unknownDevice');+ }++ const isActive = (target: HeteroExecutionTarget, deviceId?: string) => {+ if (target === 'device') return executionTarget === 'device' && boundDeviceId === deviceId;+ return executionTarget === target;+ };++ const content = (+ <Flexbox gap={2} style={{ maxWidth: 320, minWidth: 280 }}>+ <div className={styles.header}>+ <span className={styles.headerTitle}>{t('heteroAgent.executionTarget.title')}</span>+ <Tooltip title={t('heteroAgent.executionTarget.infoTooltip')}>+ <span className={styles.headerInfo}>+ <Icon icon={InfoIcon} size={12} />+ </span>+ </Tooltip>+ </div>+ {isDesktop ? (+ <OptionRow+ active={isActive('local')}+ desc={t('heteroAgent.executionTarget.localDesc')}+ icon={<Icon icon={LaptopIcon} size={14} />}+ label={t('heteroAgent.executionTarget.local')}+ onClick={() => void handleSelect('local')}+ />+ ) : null}+ <OptionRow+ active={isActive('sandbox')}+ desc={t('heteroAgent.executionTarget.sandboxDesc')}+ icon={<Icon icon={CloudIcon} size={14} />}+ label={t('heteroAgent.executionTarget.sandbox')}+ onClick={() => void handleSelect('sandbox')}+ />+ {(devices ?? []).map((d) => (+ <OptionRow+ active={isActive('device', d.deviceId)}+ disabled={!d.online}+ icon={getDeviceIcon(d.platform)}+ key={d.deviceId}+ label={d.hostname}+ desc={+ <>+ <span className={d.online ? styles.dotOnline : styles.dotOffline} />+ <span>+ {d.online+ ? t('heteroAgent.executionTarget.online')+ : t('heteroAgent.executionTarget.offline')}+ </span>+ </>+ }+ onClick={() => void handleSelect('device', d.deviceId)}+ />+ ))}+ {hasNoDevices && isLoading ? (+ <div className={styles.empty}>{t('heteroAgent.executionTarget.loading')}</div>+ ) : null}+ {hasNoDevices && !isLoading ? (+ <div className={styles.empty}>{t('heteroAgent.executionTarget.noDevices')}</div>+ ) : null}+ </Flexbox>+ );++ return (+ <Popover+ content={content}+ open={open}+ placement="topLeft"+ styles={{ content: { padding: 4 } }}+ trigger="click"+ onOpenChange={setOpen}+ >+ <div className={styles.button}>+ {chipIcon}+ <span>{chipLabel}</span>+ <Icon icon={ChevronDownIcon} size={12} />+ </div>+ </Popover>+ );+});++HeteroDeviceSwitcher.displayName = 'HeteroDeviceSwitcher';++export default HeteroDeviceSwitcher;diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsxindex fc87752efca..0ea7b2482e4 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx@@ -73,7 +73,6 @@ describe('AgentSignalReceiptList', () => {expect(screen.getByText('GitHub PR review workflow')).toBeInTheDocument();expect(screen.getByText('Memory saved')).toBeInTheDocument();expect(screen.getByText('Skill updated')).toBeInTheDocument();- expect(screen.getAllByTitle('Agent Signal')).toHaveLength(2);});it('renders receipt cards without the recent activity label', () => {diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsxindex 9a2dc75f10f..61955732a5e 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx@@ -2,9 +2,10 @@import { LayersEnum } from '@lobechat/types';import { Icon } from '@lobehub/ui';+import { SkillsIcon } from '@lobehub/ui/icons';import { createStaticStyles } from 'antd-style';import type { LucideIcon } from 'lucide-react';-import { Brain, ClipboardCheck, FileText, RadioTower } from 'lucide-react';+import { Brain, ClipboardCheck } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -23,25 +24,7 @@ const MEMORY_ROUTE_BY_LAYER = {[LayersEnum.Preference]: { idParam: 'preferenceId', path: '/memory/preferences' },} satisfies Record<LayersEnum, { idParam: string; path: string }>;-const styles = createStaticStyles(({ css, cssVar }) => ({- agentSignalDescription: css`- display: inline-flex;- gap: 4px;- align-items: center;- max-width: 100%;- `,- agentSignalMarker: css`- display: inline-flex;- flex: none;- align-items: center;- color: ${cssVar.colorPrimary};- `,- descriptionText: css`- overflow: hidden;- min-width: 0;- text-overflow: ellipsis;- white-space: nowrap;- `,+const styles = createStaticStyles(({ css }) => ({list: css`display: flex;flex-direction: column;@@ -52,11 +35,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const RECEIPT_ICON_BY_KIND = {+const RECEIPT_LUCIDE_ICON_BY_KIND = {memory: Brain,review: ClipboardCheck,- skill: FileText,-} satisfies Record<AgentSignalReceiptView['kind'], LucideIcon>;+} as const satisfies Partial<Record<AgentSignalReceiptView['kind'], LucideIcon>>;++const renderReceiptIcon = (kind: AgentSignalReceiptView['kind']) => {+ if (kind === 'skill') return <SkillsIcon size={28} />;+ const LucideIconComponent = RECEIPT_LUCIDE_ICON_BY_KIND[kind];+ return LucideIconComponent ? <Icon icon={LucideIconComponent} size={28} /> : null;+};interface AgentSignalReceiptListProps {receipts: AgentSignalReceiptView[];@@ -81,26 +69,13 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =const { t } = useTranslation(['chat', 'common']);const navigate = useStableNavigate();const openDocument = useChatStore((s) => s.openDocument);- const ReceiptIcon = RECEIPT_ICON_BY_KIND[receipt.kind];+ const iconNode = renderReceiptIcon(receipt.kind);const fallbackTitle = t(`agentSignal.receipts.${receipt.kind}.title`, receipt.title);const detail = t(`agentSignal.receipts.${receipt.kind}.detail`, receipt.detail);const title = receipt.target?.title ?? fallbackTitle;const description = receipt.target ? fallbackTitle : detail;const summary = receipt.target?.summary ?? detail;const tooltip = `${fallbackTitle}: ${summary}`;- const agentSignalLabel = t('agentSignal.receipts.agentSignalLabel', 'Agent Signal');- const descriptionRender = (- <span className={styles.agentSignalDescription}>- <span- aria-label={agentSignalLabel}- className={styles.agentSignalMarker}- title={agentSignalLabel}- >- <Icon icon={RadioTower} size={12} />- </span>- <span className={styles.descriptionText}>{description}</span>- </span>- );const target = receipt.target;const documentId = target?.type === 'skill' ? (target.documentId ?? target.id) : undefined;const memoryRoute = getMemoryRoute(target);@@ -127,8 +102,8 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =return (<PortalResourceCard- description={descriptionRender}- icon={ReceiptIcon}+ description={description}+ icon={iconNode}openLabel={canOpen ? t('common:cmdk.toOpen', 'Open') : undefined}title={title}tooltip={tooltip}diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsxindex 5fcca8653b3..0e10626a23f 100644--- a/src/features/Conversation/Messages/Assistant/index.tsx+++ b/src/features/Conversation/Messages/Assistant/index.tsx@@ -130,7 +130,6 @@ const AssistantMessage = memo<AssistantMessageProps>(}messageExtra={<>- {footerRender}{interrupted && <InterruptedHint />}<AssistantMessageExtracontent={content}@@ -142,6 +141,7 @@ const AssistantMessage = memo<AssistantMessageProps>(tools={tools}usage={usage! || metadata}/>+ {footerRender}</>}onDoubleClick={onDoubleClick}diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex 1a300e9c3fd..9181e940ffc 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -216,10 +216,10 @@ const GroupMessage = memo<GroupMessageProps>(</div>)}{interrupted && <InterruptedHint />}- {footerRender}{isDevMode && model && (<Usage model={model} performance={performance} provider={provider!} usage={usage} />)}+ {footerRender}{reactions.length > 0 && (<ReactionDisplayisActive={isReactionActive}diff --git a/src/features/Conversation/components/PortalResourceCard/index.tsx b/src/features/Conversation/components/PortalResourceCard/index.tsxindex f27503f0894..389f9870f35 100644--- a/src/features/Conversation/components/PortalResourceCard/index.tsx+++ b/src/features/Conversation/components/PortalResourceCard/index.tsx@@ -2,7 +2,6 @@import { Center, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';import { createStaticStyles, cx } from 'antd-style';-import type { LucideIcon } from 'lucide-react';import { FileText } from 'lucide-react';import type { KeyboardEvent, ReactNode } from 'react';import { memo } from 'react';@@ -22,6 +21,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,avatar: css`flex: none;+ align-self: stretch;border-inline-end: 1px solid ${cssVar.colorBorderSecondary};background: ${cssVar.colorFillQuaternary};`,@@ -42,10 +42,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorBgContainer};`,container: css`+ overflow: hidden;+width: 100%;- min-height: 48px;+ height: 64px;border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 6px;+ border-radius: 12px;color: ${cssVar.colorText};@@ -69,7 +71,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({export interface PortalResourceCardProps {className?: string;description?: ReactNode;- icon?: LucideIcon;+ icon?: ReactNode;onOpen?: () => void;openLabel?: ReactNode;title: ReactNode;@@ -77,7 +79,7 @@ export interface PortalResourceCardProps {}const PortalResourceCard = memo<PortalResourceCardProps>(- ({ className, description, icon = FileText, openLabel, title, tooltip, onOpen }) => {+ ({ className, description, icon, openLabel, title, tooltip, onOpen }) => {const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {if (!onOpen) return;if (event.key !== 'Enter' && event.key !== ' ') return;@@ -97,10 +99,10 @@ const PortalResourceCard = memo<PortalResourceCardProps>(onClick={onOpen}onKeyDown={onOpen ? handleKeyDown : undefined}>- <Center horizontal className={styles.avatar} height={48} width={48}>- <Icon icon={icon} size={22} />+ <Center horizontal className={styles.avatar} width={64}>+ {icon ?? <Icon icon={FileText} size={28} />}</Center>- <Flexbox className={styles.content} flex={1} gap={2} paddingBlock={6} paddingInline={10}>+ <Flexbox className={styles.content} flex={1} gap={4} paddingInline={12}><Text ellipsis className={styles.title}>{title}</Text>diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 7eb7a6db17b..6fd67757e50 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -311,6 +311,7 @@ export const generationSlice: StateCreator<const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());const runtimeType = selectRuntimeType({+ executionTarget: agentConfig?.agencyConfig?.executionTarget,heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,isGatewayMode: chatStore.isGatewayModeEnabled(),});@@ -488,6 +489,7 @@ export const generationSlice: StateCreator<const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({+ executionTarget: agentConfig?.agencyConfig?.executionTarget,heterogeneousProvider,isGatewayMode: chatStore.isGatewayModeEnabled(),});diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 9b3ec72fe89..edb5a091d9e 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -36,8 +36,8 @@ export default {'agentSignal.receipts.memory.detail': 'Saved this for future replies','agentSignal.receipts.memory.title': 'Memory saved','agentSignal.receipts.recentActivity': 'Recent activity',- 'agentSignal.receipts.skill.detail': 'Improved how this assistant handles similar requests',- 'agentSignal.receipts.skill.title': 'Skill updated',+ 'agentSignal.receipts.skill.detail': 'Self-refined how this agent handles similar requests',+ 'agentSignal.receipts.skill.title': 'Auto-learned a new skill','agents': 'Agents','artifact.generating': 'Generating','artifact.inThread':@@ -175,6 +175,19 @@ export default {'heteroAgent.cloudRepo.notSet': 'No repo selected','heteroAgent.cloudRepo.noRepos': 'No repositories configured. Add them in agent settings.','heteroAgent.cloudRepo.multiSelected': '{{count}} repos selected',+ 'heteroAgent.executionTarget.infoTooltip':+ 'Pick a remote device to drive that machine from the web. "This device" runs the agent locally and is only available inside the desktop app.',+ 'heteroAgent.executionTarget.loading': 'Loading devices…',+ 'heteroAgent.executionTarget.local': 'This device',+ 'heteroAgent.executionTarget.localDesc': 'Run as a local process on this desktop app',+ 'heteroAgent.executionTarget.noDevices':+ 'No remote devices yet. Install the desktop app or run `lh connect` on another machine.',+ 'heteroAgent.executionTarget.offline': 'Offline',+ 'heteroAgent.executionTarget.online': 'Online',+ 'heteroAgent.executionTarget.sandbox': 'Cloud sandbox',+ 'heteroAgent.executionTarget.sandboxDesc': 'Run in an ephemeral cloud sandbox',+ 'heteroAgent.executionTarget.title': 'Execution Device',+ 'heteroAgent.executionTarget.unknownDevice': 'Unknown device','hideForYou':"Direct message content is hidden. Please enable 'Show Direct Message Content' in settings to view.",'history.title': 'The Agent will keep only the latest {{count}} messages.',diff --git a/src/locales/default/labs.ts b/src/locales/default/labs.tsindex cba506dc643..14dded5b0c8 100644--- a/src/locales/default/labs.ts+++ b/src/locales/default/labs.ts@@ -5,6 +5,9 @@ export default {'features.assistantMessageGroup.desc':'Group agent messages and their tool call results together for display','features.assistantMessageGroup.title': 'Agent Message Grouping',+ 'features.executionDeviceSwitcher.desc':+ 'Surface the execution-device switcher in the heterogeneous agent toolbar so you can route runs to this device, a cloud sandbox, or a bound remote device.',+ 'features.executionDeviceSwitcher.title': 'Execution Device Switcher','features.gatewayMode.desc':'Execute agent tasks on the server via Gateway WebSocket instead of running locally. Enables faster execution and reduces client resource usage.','features.gatewayMode.title': 'Server-Side Agent Execution (Gateway)',diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsxindex 62ef05e9550..39556b1a603 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/WorkingDirectoryBar.tsx@@ -17,12 +17,15 @@ import { useTranslation } from 'react-i18next';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import CloudRepoSwitcher from '@/features/ChatInput/RuntimeConfig/CloudRepoSwitcher';import GitStatus from '@/features/ChatInput/RuntimeConfig/GitStatus';+import HeteroDeviceSwitcher from '@/features/ChatInput/RuntimeConfig/HeteroDeviceSwitcher';import { useRepoType } from '@/features/ChatInput/RuntimeConfig/useRepoType';import WorkingDirectoryContent from '@/features/ChatInput/RuntimeConfig/WorkingDirectory';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';const styles = createStaticStyles(({ css }) => ({bar: css`@@ -78,6 +81,9 @@ const WorkingDirectoryBar = memo(() => {);const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);const effectiveWorkingDirectory = topicWorkingDirectory || agentWorkingDirectory;+ const enableExecutionDeviceSwitcher = useUserStore(+ labPreferSelectors.enableExecutionDeviceSwitcher,+ );const repoType = useRepoType(effectiveWorkingDirectory);@@ -93,7 +99,10 @@ const WorkingDirectoryBar = memo(() => {if (!agentId) return null;return (<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>- <CloudRepoSwitcher agentId={agentId} />+ <Flexbox horizontal align={'center'} gap={4}>+ {enableExecutionDeviceSwitcher && <HeteroDeviceSwitcher agentId={agentId} />}+ <CloudRepoSwitcher agentId={agentId} />+ </Flexbox></Flexbox>);}@@ -129,6 +138,7 @@ const WorkingDirectoryBar = memo(() => {return (<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}><Flexbox horizontal align={'center'} gap={4}>+ {enableExecutionDeviceSwitcher && <HeteroDeviceSwitcher agentId={agentId} />}<Popovercontent={<WorkingDirectoryContent agentId={agentId} onClose={() => setOpen(false)} />}open={open}diff --git a/src/routes/(main)/settings/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsxindex 6b7682c8737..5c5cf9b87dd 100644--- a/src/routes/(main)/settings/advanced/index.tsx+++ b/src/routes/(main)/settings/advanced/index.tsx@@ -35,14 +35,21 @@ const Page = memo(() => {const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);const [loading, setLoading] = useState(false);- const [isPreferenceInit, enableInputMarkdown, enableGatewayMode, enablePlatformAgent, updateLab] =- useUserStore((s) => [- preferenceSelectors.isPreferenceInit(s),- labPreferSelectors.enableInputMarkdown(s),- labPreferSelectors.enableGatewayMode(s),- labPreferSelectors.enablePlatformAgent(s),- s.updateLab,- ]);+ const [+ isPreferenceInit,+ enableInputMarkdown,+ enableGatewayMode,+ enablePlatformAgent,+ enableExecutionDeviceSwitcher,+ updateLab,+ ] = useUserStore((s) => [+ preferenceSelectors.isPreferenceInit(s),+ labPreferSelectors.enableInputMarkdown(s),+ labPreferSelectors.enableGatewayMode(s),+ labPreferSelectors.enablePlatformAgent(s),+ labPreferSelectors.enableExecutionDeviceSwitcher(s),+ s.updateLab,+ ]);const hasGatewayUrl = useServerConfigStore((s) => !!s.serverConfig.agentGatewayUrl);@@ -110,6 +117,19 @@ const Page = memo(() => {label: tLabs('features.inputMarkdown.title'),minWidth: undefined,},+ {+ children: (+ <Switch+ checked={enableExecutionDeviceSwitcher}+ loading={!isPreferenceInit}+ onChange={(checked) => updateLab({ enableExecutionDeviceSwitcher: checked })}+ />+ ),+ className: styles.labItem,+ desc: tLabs('features.executionDeviceSwitcher.desc'),+ label: tLabs('features.executionDeviceSwitcher.title'),+ minWidth: undefined,+ },...(hasGatewayUrl? [{diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 332a5733a58..b293a4b555a 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -904,49 +904,89 @@ export class AiAgentService {userMessageId: userMsg?.id ?? parentMessageId ?? '',};}- } else if (requestedDeviceId) {- // Local CLI (claude-code / codex) — dispatch to user's connected desktop.- const result = await deviceProxy.dispatchAgentRun({- ...heteroParams,- deviceId: requestedDeviceId,- });- if (!result.success) {- log('execAgent: hetero device dispatch failed: %s', result.error);- await this.messageModel.update(assistantMsg.id, {- content: '',- error: {- body: { detail: result.error },- message: result.error ?? 'Device dispatch failed',- type: 'ServerAgentRuntimeError',- },+ } else {+ // Local CLI hetero (claude-code / codex) — fork between device dispatch+ // and cloud sandbox based on:+ // 1. requestedDeviceId (topic-level override) — always wins+ // 2. agencyConfig.executionTarget (agent-level default)+ // - 'device' → dispatch to boundDeviceId (errors if unset/offline)+ // - 'sandbox' → cloud sandbox+ // - 'local' / undefined → cloud sandbox (server can't spawn locally)+ const executionTarget = agentConfig.agencyConfig?.executionTarget;+ const dispatchDeviceId = requestedDeviceId || agentConfig.agencyConfig?.boundDeviceId;+ const useDevice = !!requestedDeviceId || executionTarget === 'device';++ if (useDevice) {+ if (!dispatchDeviceId) {+ log('execAgent: hetero executionTarget=device but no boundDeviceId set');+ await this.messageModel.update(assistantMsg.id, {+ content: '',+ error: {+ body: {+ detail:+ 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',+ },+ message: 'No bound device for hetero agent',+ type: 'ServerAgentRuntimeError',+ },+ });+ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMsg.id,+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: 'No bound device',+ message: 'Hetero agent requires a bound device',+ operationId,+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMsg?.id ?? parentMessageId ?? '',+ };+ }+ const result = await deviceProxy.dispatchAgentRun({+ ...heteroParams,+ deviceId: dispatchDeviceId,+ });+ if (!result.success) {+ log('execAgent: hetero device dispatch failed: %s', result.error);+ await this.messageModel.update(assistantMsg.id, {+ content: '',+ error: {+ body: { detail: result.error },+ message: result.error ?? 'Device dispatch failed',+ type: 'ServerAgentRuntimeError',+ },+ });+ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMsg.id,+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: result.error,+ message: 'Hetero agent device dispatch failed',+ operationId,+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMsg?.id ?? parentMessageId ?? '',+ };+ }+ } else {+ // Cloud sandbox path — only for local CLI agents (claude-code / codex).+ // Remote agents (openclaw / hermes) always require a bound device.+ const { spawnHeteroSandbox } =+ await import('@/server/services/heterogeneousAgent/sandboxRunner');+ spawnHeteroSandbox({+ ...heteroParams,+ agentType: heteroType as 'claude-code' | 'codex',+ marketService: this.marketService,+ }).catch((err) => {+ log('execAgent: hetero sandbox spawn failed: %O', err);});- return {- agentId: resolvedAgentId,- assistantMessageId: assistantMsg.id,- autoStarted: false,- createdAt: new Date().toISOString(),- error: result.error,- message: 'Hetero agent device dispatch failed',- operationId,- status: 'error',- success: false,- timestamp: new Date().toISOString(),- topicId,- userMessageId: userMsg?.id ?? parentMessageId ?? '',- };}- } else {- // Cloud sandbox path — only for local CLI agents (claude-code / codex).- // Remote agents (openclaw / hermes) always require a bound device.- const { spawnHeteroSandbox } =- await import('@/server/services/heterogeneousAgent/sandboxRunner');- spawnHeteroSandbox({- ...heteroParams,- agentType: heteroType as 'claude-code' | 'codex',- marketService: this.marketService,- }).catch((err) => {- log('execAgent: hetero sandbox spawn failed: %O', err);- });}let gatewayToken: string | undefined;diff --git a/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.tsindex c68edb8f396..b9b0222ae24 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts@@ -77,6 +77,75 @@ describe('selectRuntimeType', () => {});});+ describe('executionTarget routing for local CLI hetero', () => {+ it('routes to gateway when executionTarget = device on desktop', () => {+ expect(+ selectRuntimeType(+ {+ executionTarget: 'device',+ heterogeneousProvider: heteroProvider,+ isGatewayMode: false,+ },+ { isDesktop: true },+ ),+ ).toBe('gateway');+ });++ it('routes to gateway when executionTarget = sandbox on desktop', () => {+ expect(+ selectRuntimeType(+ {+ executionTarget: 'sandbox',+ heterogeneousProvider: heteroProvider,+ isGatewayMode: false,+ },+ { isDesktop: true },+ ),+ ).toBe('gateway');+ });++ it('keeps hetero when executionTarget = local on desktop', () => {+ expect(+ selectRuntimeType(+ {+ executionTarget: 'local',+ heterogeneousProvider: heteroProvider,+ isGatewayMode: false,+ },+ { isDesktop: true },+ ),+ ).toBe('hetero');+ });++ it('falls back to gateway when executionTarget = local on web (no local path)', () => {+ expect(+ selectRuntimeType(+ {+ executionTarget: 'local',+ heterogeneousProvider: heteroProvider,+ isGatewayMode: false,+ },+ { isDesktop: false },+ ),+ ).toBe('gateway');+ });++ it('preserves legacy default when executionTarget is unset (desktop → hetero, web → gateway)', () => {+ expect(+ selectRuntimeType(+ { heterogeneousProvider: heteroProvider, isGatewayMode: false },+ { isDesktop: true },+ ),+ ).toBe('hetero');+ expect(+ selectRuntimeType(+ { heterogeneousProvider: heteroProvider, isGatewayMode: false },+ { isDesktop: false },+ ),+ ).toBe('gateway');+ });+ });+describe('parentRuntime override', () => {it('parentRuntime wins over every other signal', () => {expect(diff --git a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts b/src/store/chat/slices/aiChat/actions/agentDispatcher.tsindex 58f1b2d2cc8..43554cff124 100644--- a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts+++ b/src/store/chat/slices/aiChat/actions/agentDispatcher.ts@@ -1,6 +1,6 @@import { isDesktop as defaultIsDesktop } from '@lobechat/const';import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';-import { type HeterogeneousProviderConfig } from '@lobechat/types';+import { type HeteroExecutionTarget, type HeterogeneousProviderConfig } from '@lobechat/types';/*** Which agent runtime should handle an operation.@@ -47,6 +47,16 @@ export interface AgentInvocationIntent {}export interface RuntimeSelectionContext {+ /**+ * Per-agent execution device choice from the composer's Execution Device+ * switcher. Only meaningful when `heterogeneousProvider` is a local CLI+ * (claude-code / codex). Controls the desktop fork:+ * - `'device'` / `'sandbox'` → route through Gateway so the server can+ * dispatch to an `lh connect` device or spawn a sandbox.+ * - `'local'` / `undefined` → keep today's default (desktop → `hetero`+ * in-process spawn, web → `gateway` sandbox).+ */+ executionTarget?: HeteroExecutionTarget;/** Per-agent heterogeneous provider config (desktop only — takes priority over gateway). */heterogeneousProvider?: HeterogeneousProviderConfig;/** Result of `chatStore.isGatewayModeEnabled()`. */@@ -87,10 +97,15 @@ export const selectRuntimeType = (if (ctx.heterogeneousProvider && isRemoteHeterogeneousType(ctx.heterogeneousProvider.type)) {return 'gateway';}- // Local CLI agents (claude-code, codex) run as desktop subprocesses.- if (isDesktop && ctx.heterogeneousProvider) return 'hetero';- // On web, all remaining hetero agents run via the Gateway sandbox.- if (!isDesktop && ctx.heterogeneousProvider) return 'gateway';+ // Local CLI hetero (claude-code / codex) — route by executionTarget.+ // `device` / `sandbox` need server-side dispatch; `local` runs in-process+ // on the desktop. Default (unset) preserves legacy behavior: desktop → hetero,+ // web → gateway sandbox.+ if (ctx.heterogeneousProvider) {+ if (ctx.executionTarget === 'device' || ctx.executionTarget === 'sandbox') return 'gateway';+ if (ctx.executionTarget === 'local') return isDesktop ? 'hetero' : 'gateway';+ return isDesktop ? 'hetero' : 'gateway';+ }if (ctx.isGatewayMode) return 'gateway';return 'client';};diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.tsindex 6121410670c..94c5e1b574c 100644--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts@@ -61,6 +61,7 @@ export class ConversationControlActionImpl {: undefined;return (selectRuntimeType({+ executionTarget: agentConfig?.agencyConfig?.executionTarget,heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,isGatewayMode: this.#get().isGatewayModeEnabled(),}) === 'gateway'diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex d0bda848dc0..ae1f48a955a 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -225,6 +225,7 @@ export class ConversationLifecycleActionImpl {const agentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({+ executionTarget: agentConfig?.agencyConfig?.executionTarget,heterogeneousProvider,isGatewayMode: this.#get().isGatewayModeEnabled(),});diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex d6716579f26..b6bf2b279da 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -5,6 +5,8 @@ import { type UserState } from '@/store/user/initialState';export const labPreferSelectors = {enableAgentSelfIteration: (s: UserState): boolean =>s.preference.lab?.enableAgentSelfIteration ?? false,+ enableExecutionDeviceSwitcher: (s: UserState): boolean =>+ s.preference.lab?.enableExecutionDeviceSwitcher ?? false,enableGatewayMode: (s: UserState): boolean => s.preference.lab?.enableGatewayMode ?? false,enableInputMarkdown: (s: UserState): boolean =>s.preference.lab?.enableInputMarkdown ?? DEFAULT_PREFERENCE.lab!.enableInputMarkdown!,