๐คฏ 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
โป๏ธ refactor(agent): resolve device routing via a single execution plan (#15669)
Arvin Xu77e4d0492ba1
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.tsindex d89b1edc7f7..20b3908ba85 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts@@ -508,12 +508,34 @@ describe('createServerAgentToolsEngine', () => {expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);});- it('should disable LocalSystem when runtimeMode is explicitly set to cloud', () => {+ it('should disable LocalSystem when executionTarget is sandbox', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {agentConfig: {+ agencyConfig: { executionTarget: 'sandbox' },+ plugins: [LocalSystemManifest.identifier],+ },+ canUseDevice: true,+ deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [LocalSystemManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);+ });++ it('should disable LocalSystem when executionTarget is none', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ agencyConfig: { executionTarget: 'none' },plugins: [LocalSystemManifest.identifier],- chatConfig: { runtimeEnv: { runtimeMode: { desktop: 'cloud' } } },},canUseDevice: true,deviceContext: { gatewayConfigured: true, deviceOnline: true, autoActivated: true },@@ -574,6 +596,50 @@ describe('createServerAgentToolsEngine', () => {expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);});+ it('should disable RemoteDevice when executionTarget is none โ ๆ ่ฎพๅค means NO device', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ agencyConfig: { executionTarget: 'none' },+ plugins: [RemoteDeviceManifest.identifier],+ },+ canUseDevice: true,+ deviceContext: { gatewayConfigured: true },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [RemoteDeviceManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);+ });++ it('should disable RemoteDevice when executionTarget is sandbox โ sandbox and devices are mutually exclusive', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ agencyConfig: { executionTarget: 'sandbox' },+ plugins: [RemoteDeviceManifest.identifier],+ },+ canUseDevice: true,+ deviceContext: { gatewayConfigured: true },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [RemoteDeviceManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(RemoteDeviceManifest.identifier);+ });+it('should disable RemoteDevice when device is already auto-activated', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.tsindex cbb9908f0a0..d060f9315eb 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts@@ -28,7 +28,7 @@ import { ToolsEngine } from '@lobechat/context-engine';import { type RuntimeEnvMode, type RuntimePlatform } from '@lobechat/types';import debug from 'debug';-import { resolveRuntimeMode } from '@/helpers/executionTarget';+import { executionTargetToRuntimeMode, resolveExecutionTarget } from '@/helpers/executionTarget';import {buildAllowedBuiltinTools,DEVICE_TOOL_IDENTIFIERS,@@ -144,20 +144,22 @@ export const createServerAgentToolsEngine = (// back to the caller) is removed.const hasDeviceProxy = !!deviceContext?.gatewayConfigured;- // Platform key is used only to look up the user's per-platform- // `runtimeMode` preference. A server configured with a device-gateway is- // serving desktop-class users; otherwise the caller is treated as web.+ // A server configured with a device-gateway is serving desktop-class users+ // (the unset-target default resolves to `local`); otherwise the caller is+ // treated as web.const platform: RuntimePlatform = hasDeviceProxy ? 'desktop' : 'web';// Tool gate derived from the single `agencyConfig.executionTarget` param- // (sandbox โ cloud tools, local โ local-system tools, device โ gateway), with- // a no-regression fallback to the legacy per-platform `runtimeMode` for agents- // that predate `executionTarget`.- const runtimeMode: RuntimeEnvMode = resolveRuntimeMode(- agentConfig.agencyConfig,- agentConfig.chatConfig?.runtimeEnv?.runtimeMode?.[platform],- platform === 'desktop',- );+ // (sandbox โ cloud tools, local โ local-system tools, device โ gateway).+ const executionTarget = resolveExecutionTarget(agentConfig.agencyConfig, {+ isDesktop: platform === 'desktop',+ });+ const runtimeMode: RuntimeEnvMode = executionTargetToRuntimeMode(executionTarget);+ // Device tools (local-system, remote-device proxy) only exist for+ // device-capable targets. `none` means NO device โ the proxy that could+ // activate one mid-run must not be offered either; `sandbox` and devices+ // are mutually exclusive.+ const deviceCapable = executionTarget === 'local' || executionTarget === 'device';const searchMode = agentConfig.chatConfig?.searchMode ?? 'auto';const isSearchEnabled = searchMode !== 'off';@@ -231,7 +233,7 @@ export const createServerAgentToolsEngine = (// systemRole would otherwise leak the device list into the LLM// context โ see the gated injection in `aiAgent.execAgent`.[RemoteDeviceManifest.identifier]:- canUseDevice && hasDeviceProxy && !deviceContext?.autoActivated,+ canUseDevice && deviceCapable && hasDeviceProxy && !deviceContext?.autoActivated,[AgentDocumentsManifest.identifier]: hasAgentDocuments,[WebBrowsingManifest.identifier]: isSearchEnabled,};diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/types.tsindex 21936c1ed7f..060f7dbedf9 100644--- a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts@@ -1,10 +1,5 @@import { type LobeToolManifest, type PluginEnableChecker } from '@lobechat/context-engine';-import {- type LobeAgentAgencyConfig,- type LobeBuiltinTool,- type LobeTool,- type RuntimeEnvConfig,-} from '@lobechat/types';+import { type LobeAgentAgencyConfig, type LobeBuiltinTool, type LobeTool } from '@lobechat/types';/*** Installed plugin with manifest@@ -67,7 +62,6 @@ export interface ServerCreateAgentToolsEngineParams {* `plugins` and `alwaysOnToolIds`. Undefined / true โ agent mode.*/enableAgentMode?: boolean;- runtimeEnv?: RuntimeEnvConfig;searchMode?: 'off' | 'on' | 'auto';/*** Overrides the `enableAgentMode` derivation. `custom` = the toolset isdiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.tsindex a1ea6327795..373bb8df5ee 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts@@ -311,6 +311,63 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});});+ describe('executionTarget gating (none / sandbox never route to a device)', () => {+ const overrideAgencyConfig = 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);+ };++ it('should NOT auto-activate the single online device when executionTarget is none', async () => {+ // regression: ๆ ่ฎพๅค used to be bypassed by single-device auto-activation+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await overrideAgencyConfig({ executionTarget: 'none' });++ await service.execAgent({ agentId: 'agent-1', prompt: 'List my files' });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });++ it('should NOT activate a bound online device when executionTarget is none', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await overrideAgencyConfig({ boundDeviceId: 'device-001', executionTarget: 'none' });++ await service.execAgent({ agentId: 'agent-1', prompt: 'List my files' });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });++ it('should NOT activate any device when executionTarget is sandbox', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ await overrideAgencyConfig({ boundDeviceId: 'device-001', executionTarget: 'sandbox' });++ await service.execAgent({ agentId: 'agent-1', prompt: 'List my files' });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });+ });+describe('boundDeviceId scenario', () => {it('should use boundDeviceId when device is online', async () => {mockDeviceProxy.isConfigured = true;diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex fb8cbf53c19..462ea47da19 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -61,7 +61,7 @@ import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';import { UserPersonaModel } from '@/database/models/userMemory/persona';import { toolsEnv } from '@/envs/tools';-import { resolveRuntimeMode } from '@/helpers/executionTarget';+import { resolveExecutionPlan, resolveRuntimeMode } from '@/helpers/executionTarget';import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';@@ -1092,17 +1092,23 @@ export class AiAgentService {}} 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) {+ // and cloud sandbox via the shared execution plan:+ // - requestedDeviceId (topic-level override) always wins+ // - executionTarget 'device' โ dispatch to boundDeviceId (errors if unset)+ // - everything else ('sandbox' / 'local' / 'none' / unset) โ cloud+ // sandbox (the server can't spawn locally, and a hetero agent must+ // execute somewhere)+ // `onlineDeviceIds` is intentionally omitted: hetero dispatch trusts+ // the binding and fails loudly at the gateway if the device is offline.+ const heteroPlan = resolveExecutionPlan({+ agencyConfig: agentConfig.agencyConfig,+ isDesktop: false,+ isHetero: true,+ requestedDeviceId,+ });++ if (heteroPlan.kind !== 'sandbox') {+ const dispatchDeviceId = heteroPlan.kind === 'device' ? heteroPlan.deviceId : undefined;if (!dispatchDeviceId) {log('execAgent: hetero executionTarget=device but no boundDeviceId set');await this.messageModel.update(assistantMsg.id, {@@ -1556,40 +1562,37 @@ export class AiAgentService {...(shouldEnableVisualUnderstanding ? [LobeAgentManifest.identifier] : []),];- // Derive activeDeviceId from device context. Gated on `canUseDevice`- // first โ without this guard, an external bot sender's turn would still- // populate `state.metadata.activeDeviceId`, and `buildStepToolDelta`- // re-injects `LocalSystemManifest` whenever activeDeviceId is set,- // bypassing the engine's enabledToolIds exclusion. Skipping the- // assignment here closes that bypass at the source.+ // Resolve THE device decision for this run. All rules live in+ // `resolveExecutionPlan` (gated on `canUseDevice` first, `none`/`sandbox`+ // never route to a device, offline bindings stay unrouted, unbound runs+ // auto-activate only with exactly one device online). Without the+ // `canUseDevice` gate an external bot sender's turn would still populate+ // `state.metadata.activeDeviceId`, and `buildStepToolDelta` re-injects+ // `LocalSystemManifest` whenever activeDeviceId is set, bypassing the+ // engine's enabledToolIds exclusion โ resolving the plan here closes+ // that bypass at the source.//- // Resolution order:- // 0. executionTarget === 'sandbox': always skip โ sandbox and device are- // mutually exclusive. Without this gate a single online device would- // be auto-activated and local-system tool calls would silently route- // to that device instead of being suppressed for the sandbox session.- // 1. boundDeviceId (topic-bound > agent-bound): use if online; if offline,- // respect the explicit choice and stay unrouted โ don't silently fall- // back to a different device, that would surprise the user.- // 2. No bound device: auto-activate only when EXACTLY ONE device is- // online. Multi-device users must bind explicitly โ picking by- // recency / first-online would be a guess that could route tool calls- // to the wrong machine. This applies uniformly to regular chat and- // IM/Bot โ the previous "regular-chat does nothing" path was the bug- // behind (the local-system system prompt's- // `{{workingDirectory}}` reached the LLM as a literal, wasting the- // first N steps groping for cwd).- const regularAgentExecutionTarget = agentConfig.agencyConfig?.executionTarget;- activeDeviceId =- !canUseDevice || regularAgentExecutionTarget === 'sandbox'- ? undefined- : boundDeviceId- ? onlineDevices.some((device) => device.deviceId === boundDeviceId)- ? boundDeviceId- : undefined- : onlineDevices.length === 1- ? onlineDevices[0].deviceId- : undefined;+ // `isDesktop` uses `gatewayConfigured` as a proxy: a device-gateway+ // deployment serves desktop-class users, so the unset-target default+ // resolves to `local` there and `none` otherwise.+ const executionPlan = resolveExecutionPlan({+ agencyConfig: agentConfig.agencyConfig,+ canUseDevice,+ isDesktop: gatewayConfigured,+ onlineDeviceIds: onlineDevices.map((device) => device.deviceId),+ requestedDeviceId,+ });+ // Device tools (local-system / remote-device proxy) only exist in a+ // device-capable session โ `none` and `sandbox` sessions must never see+ // them, not even the proxy that could activate a device mid-run.+ const deviceCapable =+ executionPlan.kind === 'device' || executionPlan.kind === 'device-unrouted';+ activeDeviceId = executionPlan.kind === 'device' ? executionPlan.deviceId : undefined;+ log(+ 'execAgent: execution plan โ kind=%s deviceId=%s',+ executionPlan.kind,+ activeDeviceId ?? 'none',+ );const toolsEngine = createServerAgentToolsEngine(toolsContext, {additionalManifests: [...lobehubSkillManifests, ...klavisManifests, ...connectorManifests],@@ -1667,14 +1670,9 @@ export class AiAgentService {canUseDevice,disableLocalSystem,});- // Resolve effective runtimeMode once, mirroring AgentToolsEngine's derivation:- // executionTarget wins; falls back to per-platform chatConfig.runtimeEnv.runtimeMode- // for legacy agents that predate the unified executionTarget field.- const agentRuntimeMode = resolveRuntimeMode(- agentConfig.agencyConfig,- agentConfig.chatConfig?.runtimeEnv?.runtimeMode?.[gatewayConfigured ? 'desktop' : 'web'],- gatewayConfigured,- );+ // Resolve effective runtimeMode once, mirroring AgentToolsEngine's derivation+ // from the unified executionTarget field.+ const agentRuntimeMode = resolveRuntimeMode(agentConfig.agencyConfig, gatewayConfigured);// When sandbox is not the active runtime, remove lobe-cloud-sandbox from the// manifest map. The initial seed via getEnabledPluginManifests (which includes// defaultToolIds) may have already placed it there, and the allowedBuiltinTools@@ -1683,12 +1681,25 @@ export class AiAgentService {if (agentRuntimeMode !== 'cloud') {delete toolManifestMap[CloudSandboxManifest.identifier];}+ // Same single-point deletion for the device tools: a `none` / `sandbox`+ // session must not expose the remote-device proxy either โ leaving it+ // discoverable would let the model activate a device mid-run and bypass+ // the execution plan ("ๆ ่ฎพๅค" means NO device, not "no device yet").+ // Scoped to gateway deployments: in the standalone Electron deployment+ // (no DEVICE_GATEWAY) local-system routes in-process via the 'client'+ // executor marking below, and the desktop client owns the tool gate.+ const stripDeviceTools = gatewayConfigured && !deviceCapable;+ if (stripDeviceTools) {+ delete toolManifestMap[RemoteDeviceManifest.identifier];+ delete toolManifestMap[LocalSystemManifest.identifier];+ }for (const tool of allowedBuiltinTools) {// lobe-cloud-sandbox is only activator-discoverable when runtimeMode resolves- // to 'cloud'. Handles both executionTarget='sandbox' (new) and the legacy- // chatConfig.runtimeEnv.runtimeMode='cloud' path via resolveRuntimeMode.+ // to 'cloud' (i.e. executionTarget='sandbox').if (tool.identifier === CloudSandboxManifest.identifier && agentRuntimeMode !== 'cloud')continue;+ // device tools are only activator-discoverable in device-capable sessions+ if (stripDeviceTools && isDeviceToolIdentifier(tool.identifier)) continue;if (tool.discoverable !== false && !toolManifestMap[tool.identifier]) {toolManifestMap[tool.identifier] = tool.manifest as LobeToolManifest;}diff --git a/packages/builtin-agents/src/agents/web-onboarding/index.ts b/packages/builtin-agents/src/agents/web-onboarding/index.tsindex 354c90e1e45..4f0f09e0bbe 100644--- a/packages/builtin-agents/src/agents/web-onboarding/index.ts+++ b/packages/builtin-agents/src/agents/web-onboarding/index.ts@@ -19,12 +19,6 @@ export const WEB_ONBOARDING: BuiltinAgentDefinition = {memory: {enabled: false,},- runtimeEnv: {- runtimeMode: {- desktop: 'none',- web: 'none',- },- },searchMode: 'off',skillActivateMode: 'manual',},diff --git a/packages/types/src/agent/agentConfig.ts b/packages/types/src/agent/agentConfig.tsindex 05e167d7801..a8ca158bc61 100644--- a/packages/types/src/agent/agentConfig.ts+++ b/packages/types/src/agent/agentConfig.ts@@ -21,12 +21,9 @@ export type RuntimePlatform = 'desktop' | 'web';* Runtime environment configuration*/export interface RuntimeEnvConfig {- /**- * Runtime environment mode per platform- */- runtimeMode?: Partial<Record<RuntimePlatform, RuntimeEnvMode>>;/*** Working directory (desktop only)+ * @deprecated use `agencyConfig.workingDirByDevice` instead*/workingDirectory?: string;}diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex 0283490ecdc..d37c99d15a5 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -187,10 +187,7 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIte/*** Zod schema for RuntimeEnvConfig*/-const runtimeEnvModeEnum = z.enum(['local', 'cloud', 'none']);-export const RuntimeEnvConfigSchema = z.object({- runtimeMode: z.record(z.string(), runtimeEnvModeEnum).optional(),workingDirectory: z.string().optional(),});diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex e958b99886d..767bebd32fa 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -329,9 +329,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {async (target: DeviceExecutionTarget, deviceId?: string) => {setOpen(false);- // `executionTarget` is the single source of truth now โ the server tool- // gate + client `getRuntimeModeById` derive `runtimeMode` from it, so we no- // longer write the legacy per-platform `runtimeMode` record.+ // `executionTarget` is the single source of truth โ the server tool+ // gate + client `getRuntimeModeById` derive `runtimeMode` from it.await updateAgentConfigById(agentId, {agencyConfig: {...agencyConfig,diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex f84f4d90807..1dced1aa77c 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -2,7 +2,9 @@ import type { LobeAgentAgencyConfig } from '@lobechat/types';import { describe, expect, it } from 'vitest';import {+ type ExecutionPlan,executionTargetToRuntimeMode,+ resolveExecutionPlan,resolveExecutionTarget,resolveRuntimeMode,} from './executionTarget';@@ -11,30 +13,60 @@ const cfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig =describe('resolveExecutionTarget', () => {it('returns the stored target verbatim when set', () => {- expect(resolveExecutionTarget(cfg({ executionTarget: 'device' }), true)).toBe('device');- expect(resolveExecutionTarget(cfg({ executionTarget: 'sandbox' }), true)).toBe('sandbox');+ expect(resolveExecutionTarget(cfg({ executionTarget: 'device' }), { isDesktop: true })).toBe(+ 'device',+ );+ expect(resolveExecutionTarget(cfg({ executionTarget: 'sandbox' }), { isDesktop: true })).toBe(+ 'sandbox',+ );});it('defaults to local on desktop, none on web when unset', () => {- expect(resolveExecutionTarget(undefined, true)).toBe('local');- expect(resolveExecutionTarget(undefined, false)).toBe('none');- expect(resolveExecutionTarget(cfg(), true)).toBe('local');- expect(resolveExecutionTarget(cfg(), false)).toBe('none');+ expect(resolveExecutionTarget(undefined, { isDesktop: true })).toBe('local');+ expect(resolveExecutionTarget(undefined, { isDesktop: false })).toBe('none');+ expect(resolveExecutionTarget(cfg(), { isDesktop: true })).toBe('local');+ expect(resolveExecutionTarget(cfg(), { isDesktop: false })).toBe('none');});it('coerces a stored `local` to `sandbox` on web (no local filesystem)', () => {- expect(resolveExecutionTarget(cfg({ executionTarget: 'local' }), false)).toBe('sandbox');+ expect(resolveExecutionTarget(cfg({ executionTarget: 'local' }), { isDesktop: false })).toBe(+ 'sandbox',+ );// โฆbut keeps it on desktop- expect(resolveExecutionTarget(cfg({ executionTarget: 'local' }), true)).toBe('local');+ expect(resolveExecutionTarget(cfg({ executionTarget: 'local' }), { isDesktop: true })).toBe(+ 'local',+ );});it('keeps `device` on web (a bound device is reachable from anywhere)', () => {- expect(resolveExecutionTarget(cfg({ executionTarget: 'device' }), false)).toBe('device');+ expect(resolveExecutionTarget(cfg({ executionTarget: 'device' }), { isDesktop: false })).toBe(+ 'device',+ );});it('keeps an explicit `none` on both platforms', () => {- expect(resolveExecutionTarget(cfg({ executionTarget: 'none' }), true)).toBe('none');- expect(resolveExecutionTarget(cfg({ executionTarget: 'none' }), false)).toBe('none');+ expect(resolveExecutionTarget(cfg({ executionTarget: 'none' }), { isDesktop: true })).toBe(+ 'none',+ );+ expect(resolveExecutionTarget(cfg({ executionTarget: 'none' }), { isDesktop: false })).toBe(+ 'none',+ );+ });++ it('coerces `none` for hetero agents โ they must execute somewhere', () => {+ // stored none โ desktop local, web sandbox+ expect(+ resolveExecutionTarget(cfg({ executionTarget: 'none' }), { isDesktop: true, isHetero: true }),+ ).toBe('local');+ expect(+ resolveExecutionTarget(cfg({ executionTarget: 'none' }), {+ isDesktop: false,+ isHetero: true,+ }),+ ).toBe('sandbox');+ // unset โ platform default, then the same coercion on web+ expect(resolveExecutionTarget(undefined, { isDesktop: true, isHetero: true })).toBe('local');+ expect(resolveExecutionTarget(undefined, { isDesktop: false, isHetero: true })).toBe('sandbox');});});@@ -48,28 +80,198 @@ describe('executionTargetToRuntimeMode', () => {});describe('resolveRuntimeMode', () => {- it('honours the legacy runtimeMode when no executionTarget is set (no-regression)', () => {- expect(resolveRuntimeMode(undefined, 'cloud', false)).toBe('cloud');- expect(resolveRuntimeMode(cfg(), 'none', false)).toBe('none');- expect(resolveRuntimeMode(cfg(), 'local', true)).toBe('local');- });-- it('derives from the default target when neither executionTarget nor legacy is set', () => {+ it('derives from the default target when executionTarget is unset', () => {// desktop default โ local- expect(resolveRuntimeMode(undefined, undefined, true)).toBe('local');+ expect(resolveRuntimeMode(undefined, true)).toBe('local');// web default โ none (an unconfigured web agent is plain chat, no run tools)- expect(resolveRuntimeMode(undefined, undefined, false)).toBe('none');+ expect(resolveRuntimeMode(undefined, false)).toBe('none');});- it('lets an explicit executionTarget override the legacy runtimeMode', () => {- expect(resolveRuntimeMode(cfg({ executionTarget: 'sandbox' }), 'local', true)).toBe('cloud');- expect(resolveRuntimeMode(cfg({ executionTarget: 'device' }), 'cloud', true)).toBe('none');- expect(resolveRuntimeMode(cfg({ executionTarget: 'local' }), 'none', true)).toBe('local');- expect(resolveRuntimeMode(cfg({ executionTarget: 'none' }), 'local', true)).toBe('none');+ it('derives from an explicit executionTarget', () => {+ expect(resolveRuntimeMode(cfg({ executionTarget: 'sandbox' }), true)).toBe('cloud');+ expect(resolveRuntimeMode(cfg({ executionTarget: 'device' }), true)).toBe('none');+ expect(resolveRuntimeMode(cfg({ executionTarget: 'local' }), true)).toBe('local');+ expect(resolveRuntimeMode(cfg({ executionTarget: 'none' }), true)).toBe('none');});it('applies the web `local`โ`sandbox` coercion before mapping to runtime mode', () => {// executionTarget=local synced from desktop, resolved on web โ sandbox โ cloud- expect(resolveRuntimeMode(cfg({ executionTarget: 'local' }), undefined, false)).toBe('cloud');+ expect(resolveRuntimeMode(cfg({ executionTarget: 'local' }), false)).toBe('cloud');+ });+});++describe('resolveExecutionPlan', () => {+ const ONLINE_A = ['device-a'];+ const ONLINE_AB = ['device-a', 'device-b'];++ describe('none โ never routes to a device', () => {+ it('stays none even with a bound device and exactly one device online', () => {+ // the historical bug: single-online-device auto-activation used to+ // bypass an explicit `none`+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'none' }),+ isDesktop: true,+ onlineDeviceIds: ONLINE_A,+ }),+ ).toEqual({ kind: 'none' });+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'none' }),+ isDesktop: true,+ onlineDeviceIds: ONLINE_A,+ }),+ ).toEqual({ kind: 'none' });+ });+ });++ describe('sandbox โ mutually exclusive with devices', () => {+ it('resolves to sandbox regardless of bound / online devices', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'sandbox' }),+ isDesktop: true,+ onlineDeviceIds: ONLINE_A,+ }),+ ).toEqual({ kind: 'sandbox' });+ });++ it('survives canUseDevice=false โ the sandbox never touches user machines', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'sandbox' }),+ canUseDevice: false,+ isDesktop: true,+ onlineDeviceIds: ONLINE_A,+ }),+ ).toEqual({ kind: 'sandbox' });+ });+ });++ describe('device / local โ binding and auto-activation', () => {+ it('uses the bound device when online', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'device' }),+ isDesktop: false,+ onlineDeviceIds: ONLINE_AB,+ }),+ ).toEqual({ deviceId: 'device-a', kind: 'device' });+ });++ it('stays unrouted when the bound device is offline (no silent fallback)', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-x', executionTarget: 'device' }),+ isDesktop: false,+ onlineDeviceIds: ONLINE_AB,+ }),+ ).toEqual({ kind: 'device-unrouted', reason: 'bound-device-offline' });+ });++ it('auto-activates only when exactly one device is online and nothing is bound', () => {+ const local = cfg({ executionTarget: 'local' });+ expect(+ resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: ONLINE_A }),+ ).toEqual({ deviceId: 'device-a', kind: 'device' });+ expect(+ resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: ONLINE_AB }),+ ).toEqual({ kind: 'device-unrouted', reason: 'ambiguous-online-devices' });+ expect(+ resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: [] }),+ ).toEqual({ kind: 'device-unrouted', reason: 'no-online-device' });+ });++ it('treats the desktop default (unset target) as device-capable', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: undefined,+ isDesktop: true,+ onlineDeviceIds: ONLINE_A,+ }),+ ).toEqual({ deviceId: 'device-a', kind: 'device' });+ });++ it('resolves the unset web target to none', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: undefined,+ isDesktop: false,+ onlineDeviceIds: ONLINE_A,+ }),+ ).toEqual({ kind: 'none' });+ });+ });++ describe('requestedDeviceId โ explicit per-request override', () => {+ it('forces device routing regardless of the stored target', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'sandbox' }),+ isDesktop: false,+ onlineDeviceIds: ONLINE_AB,+ requestedDeviceId: 'device-b',+ }),+ ).toEqual({ deviceId: 'device-b', kind: 'device' });+ });++ it('wins over the agent-bound device', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'device' }),+ isDesktop: false,+ onlineDeviceIds: ONLINE_AB,+ requestedDeviceId: 'device-b',+ }),+ ).toEqual({ deviceId: 'device-b', kind: 'device' });+ });+ });++ describe('canUseDevice=false โ external bot senders', () => {+ it('degrades every device-capable target to none', () => {+ for (const executionTarget of ['local', 'device', 'none'] as const) {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget }),+ canUseDevice: false,+ isDesktop: true,+ onlineDeviceIds: ONLINE_A,+ requestedDeviceId: 'device-a',+ }),+ ).toEqual({ kind: 'none' });+ }+ });+ });++ describe('onlineDeviceIds=undefined โ hetero dispatch semantics', () => {+ it('trusts the binding without online checks and never auto-activates', () => {+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'device' }),+ isDesktop: false,+ isHetero: true,+ }),+ ).toEqual({ deviceId: 'device-a', kind: 'device' });+ expect(+ resolveExecutionPlan({+ agencyConfig: cfg({ executionTarget: 'device' }),+ isDesktop: false,+ isHetero: true,+ }),+ ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device' });+ });++ it('sends hetero non-device targets to the sandbox on the server', () => {+ // server resolves hetero with isDesktop=false: local โ sandbox,+ // none โ sandbox (hetero coercion), sandbox โ sandbox+ for (const executionTarget of ['local', 'none', 'sandbox', undefined] as const) {+ const plan: ExecutionPlan = resolveExecutionPlan({+ agencyConfig: executionTarget ? cfg({ executionTarget }) : undefined,+ isDesktop: false,+ isHetero: true,+ });+ expect(plan).toEqual({ kind: 'sandbox' });+ }+ });});});diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 20e6073b1d3..bea66e9a956 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -1,8 +1,22 @@import type { DeviceExecutionTarget, LobeAgentAgencyConfig, RuntimeEnvMode } from '@lobechat/types';+export interface ResolveExecutionTargetOptions {+ /**+ * Platform of the resolving side. On the server there is no real "desktop"+ * flag โ callers pass `gatewayConfigured` as a proxy (a device-gateway+ * deployment serves desktop-class users). See `resolveExecutionPlan`.+ */+ isDesktop: boolean;+ /**+ * Heterogeneous agents (Claude Code / Codex) bring their own toolchain and+ * must execute somewhere, so `'none'` is not a valid target for them: it+ * coerces to `'local'` on desktop and `'sandbox'` on web.+ */+ isHetero?: boolean;+}+/**- * Single source of truth for where an agent executes. Replaces the old- * per-platform `chatConfig.runtimeEnv.runtimeMode` record โ one global+ * Single source of truth for where an agent executes โ one global* `agencyConfig.executionTarget` drives both desktop and web.** - `none` โ ๆ ่ฎพๅค (no execution environment; plain chat)@@ -16,20 +30,21 @@ import type { DeviceExecutionTarget, LobeAgentAgencyConfig, RuntimeEnvMode } fro*/export const resolveExecutionTarget = (agencyConfig: LobeAgentAgencyConfig | undefined,- isDesktop: boolean,+ { isDesktop, isHetero }: ResolveExecutionTargetOptions,): DeviceExecutionTarget => {const stored = agencyConfig?.executionTarget;- const effective = stored ?? (isDesktop ? 'local' : 'none');+ let effective = stored ?? (isDesktop ? 'local' : 'none');+ if (isHetero && effective === 'none') effective = isDesktop ? 'local' : 'sandbox';if (!isDesktop && effective === 'local') return 'sandbox';return effective;};/**- * Derive the legacy `runtimeMode` (still used by the server tool gate) from the- * unified execution target: `local` โ local-system tools, `sandbox` โ cloud- * sandbox, `device` โ gateway-dispatched tools, `none` โ no run tools (plain- * chat). `device`/`none` both gate to `'none'` โ device tools are routed- * separately via `executionTarget === 'device'` + `boundDeviceId`.+ * 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.*/export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): RuntimeEnvMode => {switch (target) {@@ -47,15 +62,121 @@ export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): Run/*** The effective `runtimeMode` (server tool gate) from the unified execution- * target, with a no-regression fallback: agents that predate `executionTarget`- * still honour their legacy per-platform `runtimeMode` until migrated. New- * writes set `executionTarget`, so this fallback fades out over time.+ * target.*/export const resolveRuntimeMode = (agencyConfig: LobeAgentAgencyConfig | undefined,- legacyRuntimeMode: RuntimeEnvMode | undefined,isDesktop: boolean,-): RuntimeEnvMode => {- if (!agencyConfig?.executionTarget && legacyRuntimeMode) return legacyRuntimeMode;- return executionTargetToRuntimeMode(resolveExecutionTarget(agencyConfig, isDesktop));+): RuntimeEnvMode =>+ executionTargetToRuntimeMode(resolveExecutionTarget(agencyConfig, { isDesktop }));++export type ExecutionPlanUnroutedReason =+ /** no bound device and more than one device online โ the user must bind explicitly */+ | '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 */+ | 'no-bound-device'+ /** no device online at all */+ | 'no-online-device';++/**+ * Where (and whether) a run executes, resolved ONCE at the entry point.+ * Downstream layers consume the plan instead of re-deriving the answer from+ * `executionTarget` / `boundDeviceId` / online state themselves.+ */+export type ExecutionPlan =+ /** route execution / device tools to this device (includes ๆฌๆบ โ the local machine is a registered device) */+ | { deviceId: string; kind: 'device' }+ /**+ * Device-targeted but no routable device right now. The run proceeds without+ * an active device; the remote-device proxy may let the model activate one+ * mid-run (native agents), or the caller may treat this as a hard error+ * (hetero dispatch).+ */+ | { kind: 'device-unrouted'; reason: ExecutionPlanUnroutedReason }+ /** plain chat โ no execution environment, no run tools, no device ever */+ | { kind: 'none' }+ /** ephemeral cloud sandbox */+ | { kind: 'sandbox' };++export interface ResolveExecutionPlanParams {+ agencyConfig: LobeAgentAgencyConfig | undefined;+ /**+ * Verdict of `resolveDeviceAccessPolicy` โ `false` (e.g. an external bot+ * sender) kills device routing entirely but does NOT block the sandbox.+ * Defaults to `true` (first-party callers).+ */+ canUseDevice?: boolean;+ isDesktop: boolean;+ isHetero?: boolean;+ /**+ * Online device ids from the device gateway. Pass `undefined` to skip+ * online checks and single-device auto-activation entirely โ the binding is+ * trusted as-is and dispatch fails loudly if the device is offline (hetero+ * dispatch semantics).+ */+ onlineDeviceIds?: string[];+ /**+ * Explicit per-request device override (e.g. the desktop preset, or a+ * batch-task `deviceId`). Always wins: it forces device routing regardless+ * of the stored target.+ */+ requestedDeviceId?: string;+}++/**+ * Resolve the execution plan for a run. This is THE device decision โ every+ * 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).+ * 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.+ */+export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): ExecutionPlan => {+ const {+ agencyConfig,+ canUseDevice = true,+ isDesktop,+ isHetero,+ onlineDeviceIds,+ requestedDeviceId,+ } = params;++ const target = resolveExecutionTarget(agencyConfig, { isDesktop, isHetero });+ const wantsDevice = !!requestedDeviceId || target === 'device' || target === 'local';++ if (!wantsDevice || !canUseDevice) {+ if (target === 'sandbox') return { kind: 'sandbox' };+ return { kind: 'none' };+ }++ const boundDeviceId = requestedDeviceId || agencyConfig?.boundDeviceId;++ // No online info: trust the binding (the gateway errors on dispatch if the+ // device is offline). No auto-activation without visibility.+ if (!onlineDeviceIds) {+ if (boundDeviceId) return { deviceId: boundDeviceId, kind: 'device' };+ return { kind: 'device-unrouted', reason: 'no-bound-device' };+ }++ if (boundDeviceId) {+ return onlineDeviceIds.includes(boundDeviceId)+ ? { deviceId: boundDeviceId, kind: 'device' }+ : { kind: 'device-unrouted', reason: 'bound-device-offline' };+ }++ if (onlineDeviceIds.length === 1) return { deviceId: onlineDeviceIds[0], kind: 'device' };++ return {+ kind: 'device-unrouted',+ reason: onlineDeviceIds.length === 0 ? 'no-online-device' : 'ambiguous-online-devices',+ };};diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts b/src/store/agent/selectors/chatConfigByIdSelectors.test.tsindex 1bbb2b96184..d2933d896d2 100644--- a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts+++ b/src/store/agent/selectors/chatConfigByIdSelectors.test.ts@@ -453,14 +453,13 @@ describe('chatConfigByIdSelectors', () => {agentMap: {'agent-1': {chatConfig: {- runtimeEnv: { runtimeMode: { web: 'cloud' }, workingDirectory: '/home' },+ runtimeEnv: { workingDirectory: '/home' },},},},});expect(chatConfigByIdSelectors.getRuntimeEnvConfigById('agent-1')(state)).toEqual({- runtimeMode: { web: 'cloud' },workingDirectory: '/home',});});@@ -474,14 +473,13 @@ describe('chatConfigByIdSelectors', () => {});});- // In test environment, isDesktop is false (no __ELECTRON__), so CURRENT_PLATFORM = 'web'+ // In test environment, isDesktop is false (no __ELECTRON__), so the+ // unified executionTarget resolves with web semantics.describe('getRuntimeModeById (web platform)', () => {- it('should return web runtime mode when set', () => {+ it('should derive cloud from executionTarget=sandbox', () => {const state = createState({agentMap: {- 'agent-1': {- chatConfig: { runtimeEnv: { runtimeMode: { web: 'cloud' } } },- },+ 'agent-1': { agencyConfig: { executionTarget: 'sandbox' } },},});@@ -502,42 +500,31 @@ describe('chatConfigByIdSelectors', () => {expect(chatConfigByIdSelectors.getRuntimeModeById('non-existent')(state)).toBe('none');});- it('should ignore desktop runtime mode on web', () => {+ it('should coerce executionTarget=local to cloud on web (no local filesystem)', () => {const state = createState({agentMap: {- 'agent-1': {- chatConfig: { runtimeEnv: { runtimeMode: { desktop: 'local' } } },- },+ 'agent-1': { agencyConfig: { executionTarget: 'local' } },},});- // desktop is set but web is not, should fall back to web default- expect(chatConfigByIdSelectors.getRuntimeModeById('agent-1')(state)).toBe('none');+ expect(chatConfigByIdSelectors.getRuntimeModeById('agent-1')(state)).toBe('cloud');});- it('should read correct platform when both are set', () => {+ it('should gate device target to "none" (device tools are routed separately)', () => {const state = createState({agentMap: {- 'agent-1': {- chatConfig: {- runtimeEnv: { runtimeMode: { desktop: 'local', web: 'cloud' } },- },- },+ 'agent-1': { agencyConfig: { boundDeviceId: 'device-a', executionTarget: 'device' } },},});- expect(chatConfigByIdSelectors.getRuntimeModeById('agent-1')(state)).toBe('cloud');+ expect(chatConfigByIdSelectors.getRuntimeModeById('agent-1')(state)).toBe('none');});it('should work with different agents independently', () => {const state = createState({agentMap: {- 'agent-1': {- chatConfig: { runtimeEnv: { runtimeMode: { web: 'cloud' } } },- },- 'agent-2': {- chatConfig: { runtimeEnv: { runtimeMode: { web: 'none' } } },- },+ 'agent-1': { agencyConfig: { executionTarget: 'sandbox' } },+ 'agent-2': { agencyConfig: { executionTarget: 'none' } },'agent-3': { chatConfig: {} },},});@@ -549,12 +536,10 @@ describe('chatConfigByIdSelectors', () => {});describe('isLocalSystemEnabledById', () => {- it('should return false on web even with desktop set to local', () => {+ it('should return false on web even with executionTarget=local (coerced to sandbox)', () => {const state = createState({agentMap: {- 'agent-1': {- chatConfig: { runtimeEnv: { runtimeMode: { desktop: 'local' } } },- },+ 'agent-1': { agencyConfig: { executionTarget: 'local' } },},});diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.ts b/src/store/agent/selectors/chatConfigByIdSelectors.tsindex 7c735f931dc..b6f0db83db8 100644--- a/src/store/agent/selectors/chatConfigByIdSelectors.ts+++ b/src/store/agent/selectors/chatConfigByIdSelectors.ts@@ -66,20 +66,14 @@ const isLocalSystemEnabledById = (agentId: string) => (s: AgentStoreState) =>/*** Get the agent's runtime mode, derived from the unified* `agencyConfig.executionTarget` (sandbox โ cloud, local โ local, device โ- * none), falling back to the legacy per-platform `runtimeMode` for agents that- * predate `executionTarget`.+ * none).*/const getRuntimeModeById =(agentId: string) =>(s: AgentStoreState): RuntimeEnvMode => {const config = agentSelectors.getAgentConfigById(agentId)(s);- const platform = isDesktop ? 'desktop' : 'web';- return resolveRuntimeMode(- config?.agencyConfig,- config?.chatConfig?.runtimeEnv?.runtimeMode?.[platform],- isDesktop,- );+ return resolveRuntimeMode(config?.agencyConfig, isDesktop);};const getSkillActivateModeById =diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.tsindex 87a5da9ecfc..22811bd940e 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts@@ -829,9 +829,8 @@ describe('GatewayActionImpl', () => {);});- // Regression guard: the legacy ModeSelector writes only runtimeMode, so an- // explicit cloud/none run leaves executionTarget unset. Gating on the- // effective runtime mode (not the unset target) keeps it off the device.+ // Regression guard: an explicit sandbox/none/device target must not+ // preset this machine's deviceId โ only a `local` target does.it('does not resolve a deviceId when a non-local runtime mode is selected', async () => {mockEnv.isDesktop = true;mockRuntime.isLocal = false;diff --git a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts b/src/store/chat/slices/aiChat/actions/agentDispatcher.tsindex 77e785f1aed..781961b7c33 100644--- a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts+++ b/src/store/chat/slices/aiChat/actions/agentDispatcher.ts@@ -2,6 +2,8 @@ import { isDesktop as defaultIsDesktop } from '@lobechat/const';import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import { type DeviceExecutionTarget, type HeterogeneousProviderConfig } from '@lobechat/types';+import { resolveExecutionTarget } from '@/helpers/executionTarget';+/*** Which agent runtime should handle an operation.*@@ -97,14 +99,17 @@ export const selectRuntimeType = (if (ctx.heterogeneousProvider && isRemoteHeterogeneousType(ctx.heterogeneousProvider.type)) {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.+ // Local CLI hetero (claude-code / codex) โ route by the resolved execution+ // target (shared resolution with the server / the device switcher UI):+ // `device` / `sandbox` need server-side dispatch; `local` runs in-process on+ // the desktop. Unset and `none` resolve to `local` on desktop (in-process)+ // and `sandbox` on web (gateway).if (ctx.heterogeneousProvider) {- if (ctx.executionTarget === 'device' || ctx.executionTarget === 'sandbox') return 'gateway';- if (ctx.executionTarget === 'local') return isDesktop ? 'hetero' : 'gateway';- return isDesktop ? 'hetero' : 'gateway';+ const target = resolveExecutionTarget(+ { executionTarget: ctx.executionTarget },+ { isDesktop, isHetero: true },+ );+ return target === 'local' ? 'hetero' : 'gateway';}if (ctx.isGatewayMode) return 'gateway';return 'client';diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex eab87724db5..55dedaee1f7 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -29,13 +29,10 @@ import { createGatewayEventHandler } from './gatewayEventHandler';* is otherwise forced to make whenever more than one device is online (with a* single device the server's heuristic already covered it).*- * Gated on the effective runtime mode (`isLocalSystemEnabledById`), NOT on- * `agencyConfig.executionTarget`: the latter is only written by the newer- * HeteroDeviceSwitcher, whereas the legacy ModeSelector writes just- * `runtimeMode`. Resolving a device whenever the target is unset would override- * an explicit `cloud` / `none` choice and wrongly route a cloud run to the- * local machine. `runtimeMode` is the single source of truth both selectors- * agree on (and what the server gates CloudSandbox on).+ * Gated on the effective runtime mode (`isLocalSystemEnabledById`), which+ * derives from `agencyConfig.executionTarget` โ only a `local` target presets+ * the device. Resolving a device for `sandbox` / `none` / `device` targets+ * would wrongly route the run to this machine.** Desktop-only and best-effort: any failure falls back to the server-side* device-resolution heuristics. We don't pre-check online status here โ an