🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(device): distinguish local and gateway device targets (#15921)
Arvin Xud28e976ac23c
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.tsindex e58ca104fa4..dfffc6ce68e 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts@@ -180,10 +180,35 @@ describe('AiAgentService.execAgent - device auto-activation', () => {platform: 'darwin' as const,};+ // Override the agent's agencyConfig and rebuild the service. Auto-activation+ // is now exclusive to `executionTarget: 'auto'` — the default (`local`) never+ // grabs a device — so the auto-activation specs opt in explicitly.+ const useAgencyConfig = async (agencyConfig: Record<string, unknown>) => {+ const { AgentService } = await import('@/server/services/agent');+ vi.mocked(AgentService).mockImplementation(+ () =>+ ({+ getAgentConfig: vi.fn().mockResolvedValue({+ agencyConfig,+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ }) as any,+ );+ service = new AiAgentService(mockDb, userId);+ };+describe('IM/Bot scenario with botContext', () => {- it('should auto-activate when exactly one device is online', async () => {+ it('should auto-activate when exactly one device is online (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -202,9 +227,10 @@ describe('AiAgentService.execAgent - device auto-activation', () => {expect(createOpArgs.activeDeviceId).toBe('device-001');});- it('should NOT auto-activate when multiple devices are online', async () => {+ it('should NOT auto-activate when multiple devices are online (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -223,9 +249,10 @@ describe('AiAgentService.execAgent - device auto-activation', () => {expect(createOpArgs.activeDeviceId).toBeUndefined();});- it('should NOT auto-activate when no devices are online', async () => {+ it('should NOT auto-activate when no devices are online (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([]);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -243,12 +270,35 @@ describe('AiAgentService.execAgent - device auto-activation', () => {const createOpArgs = mockCreateOperation.mock.calls[0][0];expect(createOpArgs.activeDeviceId).toBeUndefined();});++ it('should NOT auto-activate the single online device by default (executionTarget unset → local)', async () => {+ // The default mode never grabs a device — only explicit `auto` does.+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await useAgencyConfig({}); // unset executionTarget → default `local`++ await service.execAgent({+ agentId: 'agent-1',+ botContext: {+ applicationId: 'app-1',+ isOwner: true,+ platform: 'discord',+ platformThreadId: 'discord:guild-1:channel-1',+ senderExternalUserId: 'owner-id',+ } as any,+ prompt: 'List my files',+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });});describe('IM/Bot scenario with discordContext', () => {- it('should auto-activate when exactly one device is online', async () => {+ it('should auto-activate when exactly one device is online (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -263,16 +313,15 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});describe('Web UI scenario (no botContext/discordContext)', () => {- // regular chat used to leave activeDeviceId undefined when no- // device was bound, which caused the local-system system prompt's- // {{workingDirectory}} / {{hostname}} placeholders to reach the LLM as- // literals. The model would then waste the first N steps groping for cwd.- // Now we auto-activate when exactly one device is online — multi-device- // users still need to bind explicitly, since picking one by recency- // would be a guess that could route tool calls to the wrong machine.- it('should auto-activate the only online device', async () => {+ // In `auto` mode a single online device is activated up-front, so the+ // local-system system prompt's {{workingDirectory}} / {{hostname}}+ // placeholders resolve instead of reaching the LLM as literals. Multi-device+ // users still pick explicitly (the model selects via the remote-device+ // tool). The default mode never auto-activates.+ it('should auto-activate the only online device (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -284,9 +333,10 @@ describe('AiAgentService.execAgent - device auto-activation', () => {expect(createOpArgs.activeDeviceId).toBe('device-001');});- it('should NOT auto-activate when multiple devices are online', async () => {+ it('should NOT auto-activate when multiple devices are online (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -297,9 +347,24 @@ describe('AiAgentService.execAgent - device auto-activation', () => {expect(createOpArgs.activeDeviceId).toBeUndefined();});- it('should NOT auto-activate when no devices are online', async () => {+ it('should NOT auto-activate when no devices are online (executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([]);+ await useAgencyConfig({ executionTarget: 'auto' });++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'List my files',+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });++ it('should NOT auto-activate the single online device by default (unset → local)', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await useAgencyConfig({}); // unset executionTarget → default `local`await service.execAgent({agentId: 'agent-1',@@ -482,33 +547,16 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});// Verifies topic-stored metadata.boundDeviceId is NOT silently reused as- // the runtime bound device. Setup: topic.metadata says device-002, but the- // only online device is device-001. If the topic metadata were reused as- // boundDeviceId, activeDeviceId would be undefined (device-002 is offline).- // After auto-activate, we instead pick the most-recent online+ // the runtime bound device. Setup: `auto` mode, topic.metadata says+ // device-002, but the only online device is device-001. If the topic+ // metadata were reused as boundDeviceId, activeDeviceId would be undefined+ // (device-002 is offline). Auto-activation instead picks the single online// device (device-001) — proving the topic's stale metadata wasn't honored.it('should not reuse topic boundDeviceId when no explicit deviceId is provided', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);topicMock.findById.mockResolvedValue({ metadata: { boundDeviceId: 'device-002' } });- const { AgentService } = await import('@/server/services/agent');- vi.mocked(AgentService).mockImplementation(- () =>- ({- getAgentConfig: vi.fn().mockResolvedValue({- chatConfig: {},- files: [],- id: 'agent-1',- knowledgeBases: [],- model: 'gpt-4',- plugins: [],- provider: 'openai',- systemRole: 'You are a helpful assistant',- }),- }) as any,- );-- service = new AiAgentService(mockDb, userId);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -585,11 +633,11 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});// Mirrors the "should not reuse topic boundDeviceId" test above with a- // different mock shape. Topic metadata stores device-002, but only- // device-001 is online; if topic metadata leaked into boundDeviceId,+ // different mock shape. `auto` mode, topic metadata stores device-002, but+ // only device-001 is online; if topic metadata leaked into boundDeviceId,// activeDeviceId would be undefined (since device-002 is offline). The- // post-auto-activate picks device-001 instead, confirming the- // stale topic.metadata.boundDeviceId path is dead.+ // auto-activation picks device-001 instead, confirming the stale+ // topic.metadata.boundDeviceId path is dead.it('should not reuse topic metadata bound device when no deviceId is supplied', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);@@ -597,6 +645,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {id: 'topic-1',metadata: { boundDeviceId: 'device-002' },});+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',@@ -635,27 +684,10 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});describe('Remote Device tool injection when device is auto-activated', () => {- it('should mark autoActivated when single device is auto-activated (IM/Bot)', async () => {+ it('should mark autoActivated when single device is auto-activated (IM/Bot, executionTarget: auto)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);-- const { AgentService } = await import('@/server/services/agent');- vi.mocked(AgentService).mockImplementation(- () =>- ({- getAgentConfig: vi.fn().mockResolvedValue({- chatConfig: {},- files: [],- id: 'agent-1',- knowledgeBases: [],- model: 'gpt-4',- plugins: [],- provider: 'openai',- systemRole: 'You are a helpful assistant',- }),- }) as any,- );- service = new AiAgentService(mockDb, userId);+ await useAgencyConfig({ executionTarget: 'auto' });await service.execAgent({agentId: 'agent-1',diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex add5933cbc7..cb3f13fa179 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -215,7 +215,9 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {{ deviceId: 'dev-1', deviceName: 'My PC', platform: 'win32' },]);- mockGetAgentConfig.mockResolvedValue(createBaseAgentConfig());+ mockGetAgentConfig.mockResolvedValue(+ createBaseAgentConfig({ agencyConfig: { executionTarget: 'auto' } }),+ );await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b88f61cba1b..bda52c337d9 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -233,9 +233,13 @@"heteroAgent.cloudRepo.noRepos": "No repositories configured. Add them in agent settings.","heteroAgent.cloudRepo.notSet": "No repo selected","heteroAgent.cloudRepo.sectionTitle": "Repositories",+ "heteroAgent.executionTarget.auto": "Auto",+ "heteroAgent.executionTarget.autoDesc": "Use an online device automatically, picking one when several are available","heteroAgent.executionTarget.downloadDesktop": "Get Desktop App","heteroAgent.executionTarget.downloadDesktopDesc": "Run agents with access to your computer","heteroAgent.executionTarget.downloadDesktopTitle": "Get the desktop app",+ "heteroAgent.executionTarget.gateway": "Gateway",+ "heteroAgent.executionTarget.gatewayDesc": "Run through the device gateway so other clients can follow progress","heteroAgent.executionTarget.infoTooltip": "Pick a device and the agent uses it as its runtime environment — reading and writing files and operating the computer. Cloud sandbox is provided by LobeHub Marketplace.","heteroAgent.executionTarget.loading": "Loading devices…","heteroAgent.executionTarget.local": "This device",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 65b06c2c0ae..22d0215afe8 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -233,9 +233,13 @@"heteroAgent.cloudRepo.noRepos": "未配置仓库,请在助理设置中添加。","heteroAgent.cloudRepo.notSet": "未选择仓库","heteroAgent.cloudRepo.sectionTitle": "代码仓库",+ "heteroAgent.executionTarget.auto": "自动",+ "heteroAgent.executionTarget.autoDesc": "自动使用在线设备,有多台时择一使用","heteroAgent.executionTarget.downloadDesktop": "下载桌面端","heteroAgent.executionTarget.downloadDesktopDesc": "让 Agent 直接连接你的电脑","heteroAgent.executionTarget.downloadDesktopTitle": "下载桌面端",+ "heteroAgent.executionTarget.gateway": "网关",+ "heteroAgent.executionTarget.gatewayDesc": "经由设备网关运行,其他客户端可跟踪进度","heteroAgent.executionTarget.infoTooltip": "选择某台设备后,Agent 将以该设备为运行环境,读写文件、操作电脑。云端沙箱由 LobeHub Marketplace 提供服务","heteroAgent.executionTarget.loading": "正在加载设备…","heteroAgent.executionTarget.local": "本机",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex b78121466b4..09990dff530 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -184,8 +184,14 @@ 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.auto': 'Auto',+ 'heteroAgent.executionTarget.autoDesc':+ 'Use an online device automatically, picking one when several are available','heteroAgent.executionTarget.infoTooltip':'Pick a device and the agent uses it as its runtime environment — reading and writing files and operating the computer. Cloud sandbox is provided by LobeHub Marketplace.',+ 'heteroAgent.executionTarget.gateway': 'Gateway',+ 'heteroAgent.executionTarget.gatewayDesc':+ 'Run through the device gateway so other clients can follow progress','heteroAgent.executionTarget.loading': 'Loading devices…','heteroAgent.executionTarget.local': 'This device','heteroAgent.executionTarget.localDesc': 'Run as a local process on this desktop app',diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex dbb2d956a66..724d71839a2 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -37,15 +37,19 @@ export interface HeterogeneousProviderConfig {}/**- * Where a hetero agent runs.+ * Where an agent runs.* - `none` : no execution environment — plain chat, no built-in run tools+ * - `auto` : auto-pick a device — when exactly one is online it is activated+ * automatically; with several online the model selects one via the+ * remote-device tool. The ONLY mode that touches a device the user+ * did not explicitly select. Opt-in: never a silent default.* - `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 DeviceExecutionTarget = 'device' | 'local' | 'none' | 'sandbox';+export type DeviceExecutionTarget = 'auto' | 'device' | 'local' | 'none' | 'sandbox';/*** Agent agency configuration.diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex a2be6b26798..416f7d672a9 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -17,6 +17,7 @@ import {MonitorDownIcon,MonitorIcon,MonitorOffIcon,+ SparklesIcon,} from 'lucide-react';import { memo, type ReactNode, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -311,9 +312,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {staleTime: 30_000,});- // The current machine's own gateway deviceId (desktop only), used only to- // badge the matching device row. The dedicated local "This device" option- // remains visible in desktop mode.+ // The current machine's own gateway deviceId (desktop only), used to badge the+ // matching device row with a "This device" tag and show the local-process+ // description instead of the generic online/offline status.useElectronStore((s) => s.useFetchGatewayDeviceInfo)();const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;@@ -358,7 +359,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {const boundDevice =executionTarget === 'device' ? devices?.find((d) => d.deviceId === boundDeviceId) : undefined;- const hasNoDevices = !devices || devices.length === 0;+ const currentDevice = devices?.find((d) => d.deviceId === currentDeviceId);+ const deviceRows = devices ?? [];+ const hasNoDevices = deviceRows.length === 0;// On web with no device, the prominent download card below replaces the small// header link — avoid showing the same CTA twice.const showWebDownloadCard = !isDesktop && hasNoDevices && !isLoading;@@ -369,8 +372,15 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {if (executionTarget === 'none') {chipIcon = <Icon icon={MonitorOffIcon} size={14} />;chipLabel = t('heteroAgent.executionTarget.none');+ } else if (executionTarget === 'auto') {+ chipIcon = <Icon icon={SparklesIcon} size={14} />;+ chipLabel = t('heteroAgent.executionTarget.auto');} else if (executionTarget === 'local') {- chipIcon = <Icon icon={LaptopIcon} size={14} />;+ chipIcon = currentDevice ? (+ getDeviceIcon(currentDevice.platform)+ ) : (+ <Icon icon={LaptopIcon} size={14} />+ );chipLabel = t('heteroAgent.executionTarget.local');} else if (executionTarget === 'device') {chipIcon = getDeviceIcon(boundDevice?.platform);@@ -385,6 +395,17 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {return executionTarget === target;};+ const renderDeviceStatus = (d: NonNullable<typeof devices>[number]) => (+ <>+ <span className={d.online ? styles.dotOnline : styles.dotOffline} />+ <span>+ {d.online+ ? t('heteroAgent.executionTarget.online')+ : t('heteroAgent.executionTarget.offline')}+ </span>+ </>+ );+const renderDeviceRow = (d: NonNullable<typeof devices>[number]) => (<OptionRowactive={isActive('device', d.deviceId)}@@ -392,16 +413,11 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {icon={getDeviceIcon(d.platform)}key={d.deviceId}label={d.friendlyName || d.hostname || d.deviceId}- tag={d.deviceId === currentDeviceId ? t('heteroAgent.executionTarget.local') : undefined}+ tag={d.deviceId === currentDeviceId ? t('heteroAgent.executionTarget.gateway') : undefined}desc={- <>- <span className={d.online ? styles.dotOnline : styles.dotOffline} />- <span>- {d.online- ? t('heteroAgent.executionTarget.online')- : t('heteroAgent.executionTarget.offline')}- </span>- </>+ d.deviceId === currentDeviceId+ ? t('heteroAgent.executionTarget.gatewayDesc')+ : renderDeviceStatus(d)}onClick={() => void handleSelect('device', d.deviceId)}/>@@ -439,12 +455,32 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {onClick={() => void handleSelect('none')}/>)}+ {isHetero ? null : (+ <OptionRow+ active={isActive('auto')}+ desc={t('heteroAgent.executionTarget.autoDesc')}+ icon={<Icon icon={SparklesIcon} size={14} />}+ label={t('heteroAgent.executionTarget.auto')}+ onClick={() => void handleSelect('auto')}+ />+ )}{isDesktop ? (<OptionRowactive={isActive('local')}desc={t('heteroAgent.executionTarget.localDesc')}- icon={<Icon icon={LaptopIcon} size={14} />}- label={t('heteroAgent.executionTarget.local')}+ tag={t('heteroAgent.executionTarget.local')}+ icon={+ currentDevice ? (+ getDeviceIcon(currentDevice.platform)+ ) : (+ <Icon icon={LaptopIcon} size={14} />+ )+ }+ label={+ currentDevice?.friendlyName ||+ currentDevice?.hostname ||+ t('heteroAgent.executionTarget.local')+ }onClick={() => void handleSelect('local')}/>) : null}@@ -455,7 +491,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {label={t('heteroAgent.executionTarget.sandbox')}onClick={() => void handleSelect('sandbox')}/>- {(devices ?? []).map((d) => renderDeviceRow(d))}+ {deviceRows.map((d) => renderDeviceRow(d))}{hasNoDevices && isLoading ? (<div className={styles.empty}>{t('heteroAgent.executionTarget.loading')}</div>) : null}diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex e79177e0597..1542e29df7a 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -184,27 +184,27 @@ describe('resolveExecutionPlan', () => {).toEqual({ kind: 'device-unrouted', reason: 'bound-device-offline', target: 'device' });});- it('auto-activates only when exactly one device is online and nothing is bound', () => {+ it('NEVER auto-activates a `local` target with nothing bound (no silent grab)', () => {const local = cfg({ executionTarget: 'local' });+ // a single online device used to be auto-activated for `local`; now only+ // `auto` does that — `local` stays unrouted until a device is bound.expect(resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: ONLINE_A }),- ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'local' });+ ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'local' });expect(resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: ONLINE_AB }),- ).toEqual({ kind: 'device-unrouted', reason: 'ambiguous-online-devices', target: 'local' });- expect(- resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: [] }),- ).toEqual({ kind: 'device-unrouted', reason: 'no-online-device', target: 'local' });+ ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'local' });});- it('treats the desktop default (unset target) as device-capable', () => {+ it('treats the desktop default (unset target) as `local` but never auto-grabs a device', () => {+ // unset → `local` on desktop; device-capable but unrouted until bound.expect(resolveExecutionPlan({agencyConfig: undefined,isDesktop: true,onlineDeviceIds: ONLINE_A,}),- ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'local' });+ ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'local' });});it('resolves the unset web target to none', () => {@@ -218,6 +218,58 @@ describe('resolveExecutionPlan', () => {});});+ describe('auto — the only mode that auto-activates an unbound device', () => {+ const auto = cfg({ executionTarget: 'auto' });++ it('activates the single online device', () => {+ expect(+ resolveExecutionPlan({ agencyConfig: auto, isDesktop: true, onlineDeviceIds: ONLINE_A }),+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'auto' });+ });++ it('stays unrouted (model picks) when several devices are online', () => {+ expect(+ resolveExecutionPlan({ agencyConfig: auto, isDesktop: true, onlineDeviceIds: ONLINE_AB }),+ ).toEqual({ kind: 'device-unrouted', reason: 'ambiguous-online-devices', target: 'auto' });+ });++ it('stays unrouted when no device is online', () => {+ expect(+ resolveExecutionPlan({ agencyConfig: auto, isDesktop: true, onlineDeviceIds: [] }),+ ).toEqual({ kind: 'device-unrouted', reason: 'no-online-device', target: 'auto' });+ });++ it('works on web too (auto can pick a remote device)', () => {+ expect(+ resolveExecutionPlan({ agencyConfig: auto, isDesktop: false, onlineDeviceIds: ONLINE_A }),+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'auto' });+ });++ it('ignores a stale stored boundDeviceId (auto is not an explicit selection)', () => {+ // a leftover binding from a previous `device` selection must not pin the+ // run — auto picks fresh from the online set.+ const staleBound = cfg({ boundDeviceId: 'device-a', executionTarget: 'auto' });+ expect(+ resolveExecutionPlan({+ agencyConfig: staleBound,+ isDesktop: true,+ onlineDeviceIds: ONLINE_AB,+ }),+ ).toEqual({ kind: 'device-unrouted', reason: 'ambiguous-online-devices', target: 'auto' });+ });++ it('still honours an explicit requestedDeviceId over auto-pick', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: auto,+ isDesktop: true,+ onlineDeviceIds: ONLINE_AB,+ requestedDeviceId: 'device-b',+ }),+ ).toEqual({ deviceId: 'device-b', kind: 'device', target: 'auto' });+ });+ });+describe('requestedDeviceId — explicit per-request override', () => {it('forces device routing regardless of the stored target', () => {expect(@@ -300,15 +352,17 @@ describe('resolveExecutionPlan', () => {it('does not degrade agent mode (toolMode wins over enableAgentMode)', () => {// explicit toolMode='agent' must keep device routing even if- // enableAgentMode is somehow false+ // enableAgentMode is somehow false. Uses `auto` so a single online device+ // is still activated — proving the device track survives agent mode (only+ // `auto` auto-activates; `local`'s no-grab behaviour is covered above).expect(resolveExecutionPlan({- agencyConfig: cfg({ executionTarget: 'local' }),+ agencyConfig: cfg({ executionTarget: 'auto' }),chatConfig: { enableAgentMode: false, toolMode: 'agent' },isDesktop: true,onlineDeviceIds: ONLINE_A,}),- ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'local' });+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'auto' });});it('ignores chat mode for hetero agents (they always need a runtime)', () => {diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 67f941fac79..865ad17d59c 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -38,6 +38,8 @@ export interface ResolveExecutionTargetOptions {* `agencyConfig.executionTarget` drives both desktop and web.** - `none` → no execution environment (plain chat)+ * - `auto` → auto-pick a device (opt-in; the only mode that activates a+ * device the user did not explicitly select)* - `local` → this machine (in-process; desktop only)* - `sandbox` → server cloud sandbox* - `device` → remote device (dispatched to `boundDeviceId`)@@ -71,10 +73,10 @@ export const resolveExecutionTarget = (/*** Derive the `runtimeMode` tool gate from the unified execution target:- * `local` → local-system tools, `sandbox` → cloud sandbox, `device` → gateway- * routing, `none` → no run tools (plain chat). `device`/`none` both gate to- * `'none'` — device tools are routed via `resolveExecutionPlan`, not via- * runtimeMode.+ * `local` → local-system tools, `sandbox` → cloud sandbox, `device`/`auto` →+ * gateway routing, `none` → no run tools (plain chat). `device`/`auto`/`none`+ * all gate to `'none'` — device tools are routed via `resolveExecutionPlan`,+ * not via runtimeMode.*/export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): RuntimeEnvMode => {switch (target) {@@ -101,13 +103,16 @@ export const resolveRuntimeMode = (executionTargetToRuntimeMode(resolveExecutionTarget(agencyConfig, { isDesktop }));export type ExecutionPlanUnroutedReason =- /** no bound device and more than one device online — the user must bind explicitly */+ /** `auto` mode with more than one device online — the model must pick one */| 'ambiguous-online-devices'/** an explicitly bound device exists but is offline — never silently fall back */| 'bound-device-offline'- /** target is `device` but nothing is bound */+ /**+ * device-capable target (`auto` / `local` / `device`) but no device selected —+ * nothing bound/requested, and not the `auto` single-online-device case+ */| 'no-bound-device'- /** no device online at all */+ /** `auto` mode but no device online at all */| 'no-online-device';/**@@ -179,15 +184,17 @@ export interface ResolveExecutionPlanParams {* rule about which device (if any) a run touches lives here:** 1. `requestedDeviceId` forces device routing; otherwise the resolved- * `executionTarget` decides (`local` routes to a device too — the local- * machine is just a device).+ * `executionTarget` decides (`auto` / `local` route to a device too — the+ * local machine is just a device).* 2. `none` / `sandbox` NEVER route to a device — no auto-activation, no* step-level re-injection, no exceptions.* 3. `canUseDevice === false` degrades any device-capable target to `none`* (sandbox stays available — it never touches the user's machines).* 4. With online info: a bound device is used only if online (an offline- * binding stays unrouted rather than guessing another machine); unbound- * runs auto-activate only when EXACTLY ONE device is online.+ * binding stays unrouted rather than guessing another machine). An UNBOUND+ * run auto-activates ONLY in the opt-in `auto` mode (single device → use it;+ * several → stay unrouted so the model picks one). `local` / `device` never+ * silently grab a device — they stay unrouted until one is bound/requested.*/export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): ExecutionPlan => {const {@@ -208,7 +215,8 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Executif (resolveToolMode(chatConfig) === 'chat' && !isHetero) return { kind: 'none', target: 'none' };const target = resolveExecutionTarget(agencyConfig, { isDesktop, isHetero });- const wantsDevice = !!requestedDeviceId || target === 'device' || target === 'local';+ const wantsDevice =+ !!requestedDeviceId || target === 'device' || target === 'local' || target === 'auto';if (!wantsDevice || !canUseDevice) {if (target === 'sandbox') return { kind: 'sandbox', target: 'sandbox' };@@ -221,9 +229,15 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Executreturn { kind: 'none', target: 'none' };}- const boundDeviceId = requestedDeviceId || agencyConfig?.boundDeviceId;- // requestedDeviceId may force device routing over a non-device stored target- const effectiveTarget = target === 'local' ? 'local' : 'device';+ // In `auto` mode a stored `boundDeviceId` is NOT an explicit selection (that+ // is what `device` mode is for) — ignore it so `auto` always picks fresh and+ // a stale binding left over from a previous `device` selection can't pin the+ // run. An explicit `requestedDeviceId` still wins everywhere.+ const boundDeviceId =+ requestedDeviceId || (target === 'auto' ? undefined : agencyConfig?.boundDeviceId);+ // requestedDeviceId may force device routing over a non-device stored target;+ // keep `auto` / `local` distinct, everything else collapses to `device`.+ const effectiveTarget = target === 'local' ? 'local' : target === 'auto' ? 'auto' : 'device';// No online info: trust the binding (the gateway errors on dispatch if the// device is offline). No auto-activation without visibility.@@ -238,13 +252,22 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut: { kind: 'device-unrouted', reason: 'bound-device-offline', target: effectiveTarget };}- if (onlineDeviceIds.length === 1) {- return { deviceId: onlineDeviceIds[0], kind: 'device', target: effectiveTarget };+ // Unbound. Auto-activation — picking a device the user never selected — is+ // exclusive to the opt-in `auto` mode: one online device is used directly;+ // with several, stay unrouted so the model selects one via the remote-device+ // tool.+ if (target === 'auto') {+ if (onlineDeviceIds.length === 1) {+ return { deviceId: onlineDeviceIds[0], kind: 'device', target: effectiveTarget };+ }+ return {+ kind: 'device-unrouted',+ reason: onlineDeviceIds.length === 0 ? 'no-online-device' : 'ambiguous-online-devices',+ target: effectiveTarget,+ };}- return {- kind: 'device-unrouted',- reason: onlineDeviceIds.length === 0 ? 'no-online-device' : 'ambiguous-online-devices',- target: effectiveTarget,- };+ // `local` / `device` with nothing bound: never auto-grab a device — stay+ // unrouted until the user binds/requests one (or switches to `auto`).+ return { kind: 'device-unrouted', reason: 'no-bound-device', target: effectiveTarget };};