Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

โ™ป๏ธ refactor(agent): single-track device-tool injection via execution plan (#15683)

Arvin Xu575ef1e8eec4
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 49f851214f4..55c78ea64a0 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -73,6 +73,7 @@ import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { type LobeChatDatabase } from '@/database/type';
import { fileEnv } from '@/envs/file';
+import { type ExecutionPlan, isDeviceCapablePlan } from '@/helpers/executionTarget';
import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';
import { type EvalContext } from '@/server/modules/Mecha/ContextEngineering/types';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
@@ -577,17 +578,23 @@ export const createRuntimeExecutors = (
const provider = llmPayload.provider || state.modelRuntimeConfig?.provider;
// Resolve tools via ToolResolver (unified tool injection).
//
- // Belt-and-suspenders: even if `aiAgent.execAgent` ever forgets to clear
- // `state.metadata.activeDeviceId` for a non-trusted sender, swallowing
- // it here keeps `buildStepToolDelta` from re-injecting `local-system` โ€”
- // the engine's enabledToolIds exclusion alone is not enough, since the
- // delta builder treats activeDeviceId as an independent activation
- // signal and only dedupes against already-enabled tools.
+ // Single-track device gate: `buildStepToolDelta` treats activeDeviceId as
+ // an independent activation signal (it only dedupes against already-
+ // enabled tools), so any id that reaches it WILL inject local-system. The
+ // execution plan is the only authority on whether this session may touch
+ // a device โ€” swallow the id for non-device-capable plans (`none`,
+ // `sandbox`) and for denied senders, even if `state.metadata.activeDeviceId`
+ // was populated by a bug or a mid-run side effect. Plans absent on old /
+ // resumed operations fall back to the policy-only gate.
const devicePolicy = state.metadata?.deviceAccessPolicy as
| { canUseDevice: boolean; reason: DeviceAccessReason }
| undefined;
+ const executionPlan = state.metadata?.executionPlan as ExecutionPlan | undefined;
+ const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);
const activeDeviceId =
- devicePolicy?.canUseDevice === false ? undefined : state.metadata?.activeDeviceId;
+ devicePolicy?.canUseDevice === false || !planAllowsDevice
+ ? undefined
+ : state.metadata?.activeDeviceId;
const operationToolSet: OperationToolSet = state.operationToolSet ?? {
enabledToolIds: [],
executorMap: state.toolExecutorMap ?? {},
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index d060f9315eb..3ee3a440c1e 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -129,6 +129,7 @@ export const createServerAgentToolsEngine = (
canUseDevice = false,
deviceContext,
disableLocalSystem = false,
+ executionPlan,
globalMemoryEnabled = false,
hasAgentDocuments = false,
hasEnabledKnowledgeBases = false,
@@ -149,11 +150,15 @@ export const createServerAgentToolsEngine = (
// 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).
- const executionTarget = resolveExecutionTarget(agentConfig.agencyConfig, {
- isDesktop: platform === 'desktop',
- });
+ // Tool gate derived from the run's resolved execution plan (sandbox โ†’ cloud
+ // tools, local โ†’ local-system tools, device โ†’ gateway). Callers that don't
+ // resolve a plan (focused sub-agent engines) fall back to deriving the
+ // effective target from agencyConfig.
+ const executionTarget =
+ executionPlan?.target ??
+ 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
@@ -209,13 +214,14 @@ export const createServerAgentToolsEngine = (
// System-level rules (may override user selection for specific tools)
[CloudSandboxManifest.identifier]: runtimeMode === 'cloud',
[KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,
- // Local-system: gated by `canUseDevice` (resolveDeviceAccessPolicy)
- // first โ€” keeps external bot senders out before runtime checks even
- // run. Then user must have opted into local runtime on this platform
- // (`runtimeMode === 'local'`) AND have an online, auto-activated
- // device registered with the device-gateway.
+ // Local-system: the user must have opted into local runtime
+ // (`runtimeMode === 'local'`) AND have an online, auto-activated device
+ // registered with the device-gateway. Access policy (external bot
+ // senders) is enforced upstream: `resolveExecutionPlan` degrades denied
+ // targets to `none`, and `buildAllowedBuiltinTools` +
+ // `excludeIdentifiers` physically drop the manifest for
+ // `canUseDevice=false` turns.
[LocalSystemManifest.identifier]:
- canUseDevice &&
!disableLocalSystem &&
runtimeMode === 'local' &&
hasDeviceProxy &&
@@ -224,16 +230,13 @@ export const createServerAgentToolsEngine = (
[MemoryManifest.identifier]: globalMemoryEnabled,
// Only auto-enable in bot conversations; otherwise let user's plugin selection take effect
...(isBotConversation && { [MessageManifest.identifier]: true }),
- // Remote-device proxy: shown only when the server has a proxy but
- // no specific device is auto-activated yet (user must pick).
- //
- // `canUseDevice` is the first short-circuit: external bot senders
- // (and unconfigured bot owners) never reach the proxy, both because
- // it would let them poke at the owner's machine AND because its
- // systemRole would otherwise leak the device list into the LLM
- // context โ€” see the gated injection in `aiAgent.execAgent`.
+ // Remote-device proxy: shown only for device-capable targets when the
+ // server has a proxy but no specific device is auto-activated yet (user
+ // must pick). External bot senders never reach it: the plan degrades
+ // denied targets to `none` (โ†’ not deviceCapable) and the physical
+ // manifest walls drop it for `canUseDevice=false` turns.
[RemoteDeviceManifest.identifier]:
- canUseDevice && deviceCapable && hasDeviceProxy && !deviceContext?.autoActivated,
+ 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.ts
index 060f7dbedf9..df0be11ad24 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
@@ -1,6 +1,8 @@
import { type LobeToolManifest, type PluginEnableChecker } from '@lobechat/context-engine';
import { type LobeAgentAgencyConfig, type LobeBuiltinTool, type LobeTool } from '@lobechat/types';
+import type { ExecutionPlan } from '@/helpers/executionTarget';
+
/**
* Installed plugin with manifest
*/
@@ -91,6 +93,12 @@ export interface ServerCreateAgentToolsEngineParams {
};
/** Whether to suppress the local-system builtin while preserving other tools. */
disableLocalSystem?: boolean;
+ /**
+ * The run's resolved execution plan (see `resolveExecutionPlan`). When
+ * provided, its effective `target` drives the runtime tool gate; when
+ * omitted the engine derives the target from `agencyConfig` directly.
+ */
+ executionPlan?: ExecutionPlan;
/** Whether the user's global memory setting is enabled */
globalMemoryEnabled?: boolean;
/** Whether agent has agent documents */
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 4f190a7feac..038b593fa63 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -345,6 +345,7 @@ export class AgentRuntimeService {
deviceAccessPolicy,
discordContext,
evalContext,
+ executionPlan,
maxSteps,
userMemory,
deviceSystemInfo,
@@ -425,6 +426,7 @@ export class AgentRuntimeService {
deviceSystemInfo,
discordContext,
evalContext,
+ executionPlan,
// need be removed
modelRuntimeConfig,
queueRetries,
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 32295813a5c..f962ad32a4f 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -8,6 +8,7 @@ import type {
} from '@lobechat/context-engine';
import type { ChatTopicBotContext, UserInterventionConfig } from '@lobechat/types';
+import type { ExecutionPlan } from '@/helpers/executionTarget';
import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';
import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceAccessPolicy';
@@ -220,6 +221,13 @@ export interface OperationCreationParams {
deviceAccessPolicy?: { canUseDevice: boolean; reason: DeviceAccessReason };
/** Device system info for placeholder variable replacement in Local System systemRole */
deviceSystemInfo?: Record<string, string>;
+ /**
+ * Resolved execution plan for the run (see `resolveExecutionPlan`).
+ * Forwarded into `state.metadata.executionPlan` so step-level layers (the
+ * `call_llm` device-tool injection) consume the plan instead of re-deriving
+ * device capability from raw config.
+ */
+ executionPlan?: ExecutionPlan;
/** Discord context for injecting channel/guild info into agent system message */
discordContext?: any;
evalContext?: any;
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index b6648905d10..2127d24c480 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -300,6 +300,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
});
const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(callArgs.agentConfig.agencyConfig?.executionTarget).toBe('none');
expect(callArgs.agentConfig.systemRole).toContain('Preferred reply language: zh-CN');
expect(callArgs.agentConfig.systemRole).toContain(
'Every visible reply, question, and visible choice label must be entirely in zh-CN',
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 462ea47da19..7bfcf8559e4 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -61,7 +61,12 @@ 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 { resolveExecutionPlan, resolveRuntimeMode } from '@/helpers/executionTarget';
+import {
+ type ExecutionPlan,
+ executionTargetToRuntimeMode,
+ isDeviceCapablePlan,
+ resolveExecutionPlan,
+} from '@/helpers/executionTarget';
import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';
@@ -594,6 +599,13 @@ export class AiAgentService {
agentConfig.plugins = runtimeConfig.plugins;
log('execAgent: merged builtin agent runtime plugins for slug=%s', agentSlug);
}
+ if (runtimeConfig.agencyConfig) {
+ agentConfig.agencyConfig = {
+ ...agentConfig.agencyConfig,
+ ...runtimeConfig.agencyConfig,
+ };
+ log('execAgent: merged builtin agent runtime agencyConfig for slug=%s', agentSlug);
+ }
}
}
@@ -828,6 +840,23 @@ export class AiAgentService {
const model = agentConfig.model!;
const provider = agentConfig.provider!;
+ // Resolve device-tool access ONCE per turn, BEFORE the hetero early exit โ€”
+ // hetero dispatch routes the whole run to a user machine, so it must honour
+ // the same policy as native device tools. Discord-only flows (no
+ // botContext) keep the legacy first-party allow path; an external bot
+ // sender returns canUseDevice=false and reason='bot-external-sender',
+ // which degrades device-capable targets (hetero โ†’ sandbox, native โ†’ plain
+ // chat) and stops the device list from leaking into the LLM context.
+ const { canUseDevice, reason: deviceAccessReason } = resolveDeviceAccessPolicy({
+ botContext,
+ });
+ log(
+ 'execAgent: device access policy โ†’ canUseDevice=%s, reason=%s, hasBotContext=%s',
+ canUseDevice,
+ deviceAccessReason,
+ !!botContext,
+ );
+
// 3.5. Hetero-agent early exit โ€” Claude Code / Codex / OpenClaw / Hermes agents bypass the
// server-side LLM pipeline. After topic + message creation we hand off to
// the device gateway (desktop) or cloud sandbox, which will push events
@@ -997,6 +1026,37 @@ export class AiAgentService {
// frontend can subscribe before the first lh notify arrives.
if (isRemoteHetero) {
+ // Remote hetero agents are device-only โ€” there is no sandbox to
+ // degrade to, so a denied sender (external bot user) is refused
+ // outright instead of reaching the owner's machine.
+ if (!canUseDevice) {
+ log(
+ 'execAgent: device access denied for remote hetero dispatch (reason=%s)',
+ deviceAccessReason,
+ );
+ await this.messageModel.update(assistantMsg.id, {
+ content: '',
+ error: {
+ body: { detail: 'This sender is not allowed to run agents on a bound device.' },
+ message: 'Device access denied',
+ type: 'ServerAgentRuntimeError',
+ },
+ });
+ return {
+ agentId: resolvedAgentId,
+ assistantMessageId: assistantMsg.id,
+ autoStarted: false,
+ createdAt: new Date().toISOString(),
+ error: 'Device access denied',
+ message: 'Remote hetero agent requires device access',
+ operationId,
+ status: 'error',
+ success: false,
+ timestamp: new Date().toISOString(),
+ topicId,
+ userMessageId: userMsg?.id ?? parentMessageId ?? '',
+ };
+ }
if (!remoteDeviceId) {
log('execAgent: openclaw/hermes requires a bound device (boundDeviceId not set)');
await this.messageModel.update(assistantMsg.id, {
@@ -1095,13 +1155,19 @@ export class AiAgentService {
// 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
+ // - executionTarget 'local' + boundDeviceId (desktop sync opened on web)
+ // โ†’ dispatch to that device
+ // - everything else ('sandbox' / unbound '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.
+ // `canUseDevice` degrades device-capable targets to the sandbox for
+ // denied senders (e.g. external bot users) โ€” without it a synced
+ // local/device binding would let them run on the owner's machine.
const heteroPlan = resolveExecutionPlan({
agencyConfig: agentConfig.agencyConfig,
+ canUseDevice,
isDesktop: false,
isHetero: true,
requestedDeviceId,
@@ -1277,26 +1343,15 @@ export class AiAgentService {
const toolExecutorMap: Record<string, ToolExecutor> = {};
let onlineDevices: DeviceAttachment[] = [];
let activeDeviceId: string | undefined;
+ let executionPlan: ExecutionPlan | undefined;
let hasAgentDocuments = false;
let hasEnabledKnowledgeBases = false;
const isBotConversation = !!(botContext || discordContext);
- // Resolve device-tool access ONCE per turn. The decision flows into both
- // the engine's enable gates (LocalSystem / RemoteDevice) and the
- // RemoteDevice systemRole injection below. Discord-only flows (no
- // botContext) keep the legacy first-party allow path; an external bot
- // sender returns canUseDevice=false and reason='bot-external-sender',
- // which both denies the tools and stops the device list from leaking
- // into the LLM context.
- const { canUseDevice, reason: deviceAccessReason } = resolveDeviceAccessPolicy({
- botContext,
- });
- log(
- 'execAgent: device access policy โ†’ canUseDevice=%s, reason=%s, hasBotContext=%s',
- canUseDevice,
- deviceAccessReason,
- !!botContext,
- );
+ // Device-tool access (`canUseDevice` / `deviceAccessReason`) was resolved
+ // once before the hetero early exit above; the decision flows into the
+ // engine's enable gates (LocalSystem / RemoteDevice) and the RemoteDevice
+ // systemRole injection below.
// These are needed outside the tools block (for agent management context, skill engine, etc.)
let lobehubSkillManifests: LobeToolManifest[] = [];
@@ -1575,7 +1630,7 @@ export class AiAgentService {
// `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({
+ executionPlan = resolveExecutionPlan({
agencyConfig: agentConfig.agencyConfig,
canUseDevice,
isDesktop: gatewayConfigured,
@@ -1585,8 +1640,7 @@ export class AiAgentService {
// 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';
+ const deviceCapable = isDeviceCapablePlan(executionPlan);
activeDeviceId = executionPlan.kind === 'device' ? executionPlan.deviceId : undefined;
log(
'execAgent: execution plan โ†’ kind=%s deviceId=%s',
@@ -1610,6 +1664,7 @@ export class AiAgentService {
}
: undefined,
disableLocalSystem,
+ executionPlan,
globalMemoryEnabled,
hasAgentDocuments,
hasEnabledKnowledgeBases,
@@ -1670,9 +1725,9 @@ export class AiAgentService {
canUseDevice,
disableLocalSystem,
});
- // Resolve effective runtimeMode once, mirroring AgentToolsEngine's derivation
- // from the unified executionTarget field.
- const agentRuntimeMode = resolveRuntimeMode(agentConfig.agencyConfig, gatewayConfigured);
+ // Effective runtimeMode from the plan's resolved target โ€” same value the
+ // engine derives, single derivation point.
+ const agentRuntimeMode = executionTargetToRuntimeMode(executionPlan.target);
// 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
@@ -1708,10 +1763,11 @@ export class AiAgentService {
// lobe-local-system has `discoverable: isDesktop` in builtinTools, which
// evaluates to false on the Node.js server side, so it never enters the
// loop above. Explicitly inject it only when the device gateway is
- // configured AND the runtime mode is 'local' โ€” skip for sandbox/none
- // targets to avoid leaking local-system into non-local sessions.
+ // configured AND the plan's target is 'local' โ€” skip for sandbox/none
+ // targets to avoid leaking local-system into non-local sessions. (The
+ // plan already degrades to `none` when device access is denied, so no
+ // separate `canUseDevice` check is needed here.)
if (
- canUseDevice &&
!disableLocalSystem &&
gatewayConfigured &&
agentRuntimeMode === 'local' &&
@@ -2558,6 +2614,7 @@ export class AiAgentService {
activeDeviceId,
agentConfig,
deviceSystemInfo: Object.keys(deviceSystemInfo).length > 0 ? deviceSystemInfo : undefined,
+ executionPlan,
userTimezone,
appContext: {
// Background self-iteration runs execute under a builtin slug (so they
diff --git a/packages/builtin-agents/src/agents/web-onboarding/index.ts b/packages/builtin-agents/src/agents/web-onboarding/index.ts
index 4f0f09e0bbe..83ae42d8f22 100644
--- a/packages/builtin-agents/src/agents/web-onboarding/index.ts
+++ b/packages/builtin-agents/src/agents/web-onboarding/index.ts
@@ -15,6 +15,9 @@ export const WEB_ONBOARDING: BuiltinAgentDefinition = {
provider: DEFAULT_ONBOARDING_PROVIDER,
},
runtime: (ctx) => ({
+ agencyConfig: {
+ executionTarget: 'none',
+ },
chatConfig: {
memory: {
enabled: false,
diff --git a/packages/builtin-agents/src/types.ts b/packages/builtin-agents/src/types.ts
index f4774a80c09..5211de4c4c6 100644
--- a/packages/builtin-agents/src/types.ts
+++ b/packages/builtin-agents/src/types.ts
@@ -1,4 +1,8 @@
-import type { LobeAgentChatConfig, LobeAgentConfig } from '@lobechat/types';
+import type {
+ LobeAgentAgencyConfig,
+ LobeAgentChatConfig,
+ LobeAgentConfig,
+} from '@lobechat/types';
import type { GroupSupervisorContext } from './agents/group-supervisor/type';
@@ -38,6 +42,9 @@ export interface BuiltinAgentPersistConfig {
* Runtime Result - dynamically generated config, not persisted
*/
export interface BuiltinAgentRuntimeResult {
+ /** Runtime agency configuration overrides */
+ agencyConfig?: Partial<LobeAgentAgencyConfig>;
+
/** Runtime chat configuration overrides */
chatConfig?: Partial<LobeAgentChatConfig>;
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 767bebd32fa..a2be6b26798 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -21,7 +21,9 @@ import {
import { memo, type ReactNode, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { lambdaQuery } from '@/libs/trpc/client';
+import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useElectronStore } from '@/store/electron';
@@ -297,7 +299,6 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const heteroType = agencyConfig?.heterogeneousProvider?.type;
- const storedTarget = agencyConfig?.executionTarget;
const boundDeviceId = agencyConfig?.boundDeviceId;
// Heterogeneous agents (Claude Code / Codex โ€” remote types already early-return
@@ -317,13 +318,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);
const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;
- // Effective target: falls back to local on desktop, sandbox for heterogeneous
- // agents on web (they must execute somewhere), otherwise no device on web. A
- // hetero agent never resolves to `'none'`, even if one was previously stored.
- const fallbackTarget: DeviceExecutionTarget = isDesktop ? 'local' : isHetero ? 'sandbox' : 'none';
- const storedOrFallback = storedTarget ?? fallbackTarget;
- const executionTarget: DeviceExecutionTarget =
- isHetero && storedOrFallback === 'none' ? fallbackTarget : storedOrFallback;
+ // Effective target: shared with server dispatch. In particular, a hetero
+ // desktop "local" selection that carries this desktop's boundDeviceId becomes
+ // a device target when the same agent is opened from web.
+ const executionTarget = resolveExecutionTarget(agencyConfig, { isDesktop, isHetero });
const handleSelect = useCallback(
async (target: DeviceExecutionTarget, deviceId?: string) => {
@@ -331,15 +329,28 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// `executionTarget` is the single source of truth โ€” the server tool
// gate + client `getRuntimeModeById` derive `runtimeMode` from it.
+ let nextBoundDeviceId = target === 'device' ? deviceId : boundDeviceId;
+ if (target === 'local') {
+ nextBoundDeviceId = currentDeviceId;
+ if (!nextBoundDeviceId) {
+ try {
+ nextBoundDeviceId = (await gatewayConnectionService.getDeviceInfo())?.deviceId;
+ } catch {
+ nextBoundDeviceId = undefined;
+ }
+ }
+ if (isHetero && !nextBoundDeviceId) return;
+ }
+
await updateAgentConfigById(agentId, {
agencyConfig: {
...agencyConfig,
executionTarget: target,
- ...(target === 'device' && deviceId ? { boundDeviceId: deviceId } : {}),
+ ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),
},
});
},
- [agentId, agencyConfig, updateAgentConfigById],
+ [agentId, agencyConfig, boundDeviceId, currentDeviceId, isHetero, updateAgentConfigById],
);
// Don't render for remote hetero agents โ€” they use RemoteAgentConfigCard in profile.
diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
index a00be961b9f..0d1218b9bee 100644
--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
@@ -3,6 +3,7 @@
import { isDesktop } from '@lobechat/const';
import { memo } from 'react';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
@@ -35,8 +36,11 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(
const runtimeMode = useAgentStore(chatConfigByIdSelectors.getRuntimeModeById(agentId));
const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
- const isDeviceMode =
- agencyConfig?.executionTarget === 'device' && !!agencyConfig?.boundDeviceId;
+ const effectiveTarget = resolveExecutionTarget(agencyConfig, {
+ isDesktop,
+ isHetero: isHeterogeneous,
+ });
+ const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
const renderWorkspace = () => {
// Remote device runs get the device-scoped picker, regardless of runtimeMode
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index eb73ef26a37..c91d4be9a97 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -323,6 +323,7 @@ export const generationSlice: StateCreator<
const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());
const runtimeType = selectRuntimeType({
+ boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
isGatewayMode: chatStore.isGatewayModeEnabled(),
@@ -501,6 +502,7 @@ export const generationSlice: StateCreator<
const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());
const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;
const runtimeType = selectRuntimeType({
+ boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider,
isGatewayMode: chatStore.isGatewayModeEnabled(),
diff --git a/src/helpers/agentWorkingDirectory.test.ts b/src/helpers/agentWorkingDirectory.test.ts
index 4e628a89a03..d66b0ca9bc0 100644
--- a/src/helpers/agentWorkingDirectory.test.ts
+++ b/src/helpers/agentWorkingDirectory.test.ts
@@ -18,6 +18,21 @@ describe('resolveTargetDeviceId', () => {
expect(resolveTargetDeviceId(undefined, 'cur')).toBe('cur');
});
+ it('uses the synced local binding when no current machine id is available', () => {
+ expect(
+ resolveTargetDeviceId(cfg({ boundDeviceId: 'dev-1', executionTarget: 'local' }), undefined),
+ ).toBe('dev-1');
+ });
+
+ it('does not use stale bindings for sandbox targets', () => {
+ expect(
+ resolveTargetDeviceId(
+ cfg({ boundDeviceId: 'dev-1', executionTarget: 'sandbox' }),
+ undefined,
+ ),
+ ).toBeUndefined();
+ });
+
it('returns undefined when device target has no boundDeviceId', () => {
expect(resolveTargetDeviceId(cfg({ executionTarget: 'device' }), 'cur')).toBeUndefined();
});
diff --git a/src/helpers/agentWorkingDirectory.ts b/src/helpers/agentWorkingDirectory.ts
index 6c7ad544dff..5b0567c8b12 100644
--- a/src/helpers/agentWorkingDirectory.ts
+++ b/src/helpers/agentWorkingDirectory.ts
@@ -1,7 +1,8 @@
import type { LobeAgentAgencyConfig } from '@lobechat/types';
/**
- * The device a run targets: an explicitly bound device, else this machine.
+ * The device a run targets: an explicitly bound remote device, this machine,
+ * or (on web) a desktop-local binding synced from the desktop app.
* Local execution treats the current machine as its own device, so local and
* remote share one resolution model.
*/
@@ -9,7 +10,11 @@ export const resolveTargetDeviceId = (
agencyConfig: LobeAgentAgencyConfig | undefined,
currentDeviceId: string | undefined,
): string | undefined =>
- agencyConfig?.executionTarget === 'device' ? agencyConfig?.boundDeviceId : currentDeviceId;
+ agencyConfig?.executionTarget === 'device'
+ ? agencyConfig?.boundDeviceId
+ : agencyConfig?.executionTarget === 'local'
+ ? currentDeviceId || agencyConfig?.boundDeviceId
+ : currentDeviceId;
/**
* Unified working-directory precedence (mirrors the server's resolution):
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 1dced1aa77c..0c23304eb50 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -38,6 +38,21 @@ describe('resolveExecutionTarget', () => {
);
});
+ it('routes hetero desktop-local bindings to the bound device on web', () => {
+ expect(
+ resolveExecutionTarget(cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }), {
+ isDesktop: false,
+ isHetero: true,
+ }),
+ ).toBe('device');
+
+ expect(
+ resolveExecutionTarget(cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }), {
+ isDesktop: false,
+ }),
+ ).toBe('sandbox');
+ });
+
it('keeps `device` on web (a bound device is reachable from anywhere)', () => {
expect(resolveExecutionTarget(cfg({ executionTarget: 'device' }), { isDesktop: false })).toBe(
'device',
@@ -114,14 +129,14 @@ describe('resolveExecutionPlan', () => {
isDesktop: true,
onlineDeviceIds: ONLINE_A,
}),
- ).toEqual({ kind: 'none' });
+ ).toEqual({ kind: 'none', target: 'none' });
expect(
resolveExecutionPlan({
agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'none' }),
isDesktop: true,
onlineDeviceIds: ONLINE_A,
}),
- ).toEqual({ kind: 'none' });
+ ).toEqual({ kind: 'none', target: 'none' });
});
});
@@ -133,7 +148,7 @@ describe('resolveExecutionPlan', () => {
isDesktop: true,
onlineDeviceIds: ONLINE_A,
}),
- ).toEqual({ kind: 'sandbox' });
+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });
});
it('survives canUseDevice=false โ€” the sandbox never touches user machines', () => {
@@ -144,7 +159,7 @@ describe('resolveExecutionPlan', () => {
isDesktop: true,
onlineDeviceIds: ONLINE_A,
}),
- ).toEqual({ kind: 'sandbox' });
+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });
});
});
@@ -156,7 +171,7 @@ describe('resolveExecutionPlan', () => {
isDesktop: false,
onlineDeviceIds: ONLINE_AB,
}),
- ).toEqual({ deviceId: 'device-a', kind: 'device' });
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });
});
it('stays unrouted when the bound device is offline (no silent fallback)', () => {
@@ -166,20 +181,20 @@ describe('resolveExecutionPlan', () => {
isDesktop: false,
onlineDeviceIds: ONLINE_AB,
}),
- ).toEqual({ kind: 'device-unrouted', reason: 'bound-device-offline' });
+ ).toEqual({ kind: 'device-unrouted', reason: 'bound-device-offline', target: 'device' });
});
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' });
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'local' });
expect(
resolveExecutionPlan({ agencyConfig: local, isDesktop: true, onlineDeviceIds: ONLINE_AB }),
- ).toEqual({ kind: 'device-unrouted', reason: 'ambiguous-online-devices' });
+ ).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' });
+ ).toEqual({ kind: 'device-unrouted', reason: 'no-online-device', target: 'local' });
});
it('treats the desktop default (unset target) as device-capable', () => {
@@ -189,7 +204,7 @@ describe('resolveExecutionPlan', () => {
isDesktop: true,
onlineDeviceIds: ONLINE_A,
}),
- ).toEqual({ deviceId: 'device-a', kind: 'device' });
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'local' });
});
it('resolves the unset web target to none', () => {
@@ -199,7 +214,7 @@ describe('resolveExecutionPlan', () => {
isDesktop: false,
onlineDeviceIds: ONLINE_A,
}),
- ).toEqual({ kind: 'none' });
+ ).toEqual({ kind: 'none', target: 'none' });
});
});
@@ -212,7 +227,7 @@ describe('resolveExecutionPlan', () => {
onlineDeviceIds: ONLINE_AB,
requestedDeviceId: 'device-b',
}),
- ).toEqual({ deviceId: 'device-b', kind: 'device' });
+ ).toEqual({ deviceId: 'device-b', kind: 'device', target: 'device' });
});
it('wins over the agent-bound device', () => {
@@ -223,7 +238,7 @@ describe('resolveExecutionPlan', () => {
onlineDeviceIds: ONLINE_AB,
requestedDeviceId: 'device-b',
}),
- ).toEqual({ deviceId: 'device-b', kind: 'device' });
+ ).toEqual({ deviceId: 'device-b', kind: 'device', target: 'device' });
});
});
@@ -238,8 +253,36 @@ describe('resolveExecutionPlan', () => {
onlineDeviceIds: ONLINE_A,
requestedDeviceId: 'device-a',
}),
- ).toEqual({ kind: 'none' });
+ ).toEqual({ kind: 'none', target: 'none' });
+ }
+ });
+ });
+
+ describe('canUseDevice=false โ€” hetero degrades to sandbox, never a machine', () => {
+ it('sends denied hetero device-capable targets to the sandbox', () => {
+ // regression: the hetero early-dispatch used to omit the policy, so an
+ // external bot sender could run on the owner's bound machine via a
+ // synced local/device binding
+ for (const executionTarget of ['local', 'device'] as const) {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget }),
+ canUseDevice: false,
+ isDesktop: false,
+ isHetero: true,
+ }),
+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });
}
+ // requestedDeviceId must not bypass the policy either
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ executionTarget: 'sandbox' }),
+ canUseDevice: false,
+ isDesktop: false,
+ isHetero: true,
+ requestedDeviceId: 'device-a',
+ }),
+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });
});
});
@@ -251,18 +294,28 @@ describe('resolveExecutionPlan', () => {
isDesktop: false,
isHetero: true,
}),
- ).toEqual({ deviceId: 'device-a', kind: 'device' });
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });
expect(
resolveExecutionPlan({
agencyConfig: cfg({ executionTarget: 'device' }),
isDesktop: false,
isHetero: true,
}),
- ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device' });
+ ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'device' });
+ });
+
+ it('uses the bound desktop device for hetero local runs entered from web', () => {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }),
+ isDesktop: false,
+ isHetero: true,
+ }),
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });
});
it('sends hetero non-device targets to the sandbox on the server', () => {
- // server resolves hetero with isDesktop=false: local โ†’ sandbox,
+ // server resolves hetero with isDesktop=false: unbound local โ†’ sandbox,
// none โ†’ sandbox (hetero coercion), sandbox โ†’ sandbox
for (const executionTarget of ['local', 'none', 'sandbox', undefined] as const) {
const plan: ExecutionPlan = resolveExecutionPlan({
@@ -270,7 +323,7 @@ describe('resolveExecutionPlan', () => {
isDesktop: false,
isHetero: true,
});
- expect(plan).toEqual({ kind: 'sandbox' });
+ expect(plan).toEqual({ kind: 'sandbox', target: 'sandbox' });
}
});
});
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index bea66e9a956..0856659780d 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -24,9 +24,18 @@ export interface ResolveExecutionTargetOptions {
* - `sandbox` โ†’ ไบ‘็ซฏๆฒ™็ฎฑ (server cloud sandbox)
* - `device` โ†’ ่ฟœ็จ‹่ฎพๅค‡ (dispatched to `boundDeviceId`)
*
+ * `local` and `device` stay DISTINCT even when the bound device is this very
+ * machine: `device` dispatches through the server gateway, so progress streams
+ * to every client (mobile/web can follow the run); `local` is the faster
+ * in-process IPC path whose run lives only in this desktop session. Which one
+ * to use is the user's observability/latency trade-off โ€” never auto-collapse
+ * `device(currentDeviceId)` into the in-process path.
+ *
* Defaults: desktop โ†’ `local`, web โ†’ `none`. On web `local` isn't available
- * (no local filesystem), so a stored `local` (synced from desktop) resolves to
- * `sandbox`.
+ * (no local filesystem), so a stored `local` (synced from desktop) usually
+ * resolves to `sandbox`. For heterogeneous CLI agents, a desktop `local`
+ * selection that has already been bound to that desktop's `deviceId` resolves
+ * to `device` on web, so the same machine can execute through `lh connect`.
*/
export const resolveExecutionTarget = (
agencyConfig: LobeAgentAgencyConfig | undefined,
@@ -34,6 +43,9 @@ export const resolveExecutionTarget = (
): DeviceExecutionTarget => {
const stored = agencyConfig?.executionTarget;
let effective = stored ?? (isDesktop ? 'local' : 'none');
+ if (isHetero && !isDesktop && stored === 'local' && agencyConfig?.boundDeviceId) {
+ return 'device';
+ }
if (isHetero && effective === 'none') effective = isDesktop ? 'local' : 'sandbox';
if (!isDesktop && effective === 'local') return 'sandbox';
return effective;
@@ -84,21 +96,30 @@ export type ExecutionPlanUnroutedReason =
* 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.
+ *
+ * `target` is the EFFECTIVE execution target (platform defaults and coercions
+ * applied; degraded to `none` when device access is denied) โ€” consumers must
+ * read it instead of re-resolving `agencyConfig.executionTarget`.
*/
-export type ExecutionPlan =
+export type ExecutionPlan = { target: DeviceExecutionTarget } &
/** 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' };
+ (| { 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' }
+ );
+
+/** Device tools (local-system / remote-device proxy) only exist in device-capable sessions. */
+export const isDeviceCapablePlan = (plan: ExecutionPlan): boolean =>
+ plan.kind === 'device' || plan.kind === 'device-unrouted';
export interface ResolveExecutionPlanParams {
agencyConfig: LobeAgentAgencyConfig | undefined;
@@ -154,29 +175,40 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
const wantsDevice = !!requestedDeviceId || target === 'device' || target === 'local';
if (!wantsDevice || !canUseDevice) {
- if (target === 'sandbox') return { kind: 'sandbox' };
- return { kind: 'none' };
+ if (target === 'sandbox') return { kind: 'sandbox', target: 'sandbox' };
+ // Hetero agents must execute somewhere โ€” a device-capable target denied
+ // by the access policy falls back to the cloud sandbox (which never
+ // touches user machines) instead of the hetero-invalid `none`.
+ if (isHetero) return { kind: 'sandbox', target: 'sandbox' };
+ // a device-capable target denied by the access policy degrades to plain
+ // chat โ€” the effective target is `none`, not the stored one
+ return { 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';
// 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 { deviceId: boundDeviceId, kind: 'device', target: effectiveTarget };
+ return { kind: 'device-unrouted', reason: 'no-bound-device', target: effectiveTarget };
}
if (boundDeviceId) {
return onlineDeviceIds.includes(boundDeviceId)
- ? { deviceId: boundDeviceId, kind: 'device' }
- : { kind: 'device-unrouted', reason: 'bound-device-offline' };
+ ? { deviceId: boundDeviceId, kind: 'device', target: effectiveTarget }
+ : { kind: 'device-unrouted', reason: 'bound-device-offline', target: effectiveTarget };
}
- if (onlineDeviceIds.length === 1) return { deviceId: onlineDeviceIds[0], kind: 'device' };
+ 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,
};
};
diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.ts
index 8c28e0afd00..9e214fc5f0f 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.ts
@@ -21,8 +21,9 @@ interface UseRemoteAgentDeviceGuardResult {
}
/**
- * Checks whether the bound device is online and the agent platform is available.
- * Used in HeterogeneousChatInput to gate sending for openclaw / hermes agents.
+ * Checks whether the bound device is online and, for remote-only hetero
+ * platforms, whether that platform is available on the device. Used in
+ * HeterogeneousChatInput before device-dispatched hetero runs.
*/
export const useRemoteAgentDeviceGuard = ({
enabled = true,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index 462365b9306..dd79818f533 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { isDesktop } from '@/const/version';
import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -26,6 +27,9 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeT
const agentId = useAgentStore((s) => s.activeAgentId);
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId ?? ''));
+ const isHeterogeneous = useAgentStore((s) =>
+ agentId ? agentByIdSelectors.isAgentHeterogeneousById(agentId)(s) : false,
+ );
const { commitAgentDefault } = useCommitWorkingDirectory(agentId ?? '');
const handleAddTopic = useCallback(async () => {
@@ -39,7 +43,11 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeT
// Web can add a topic in a directory too when the agent targets a bound
// device โ€” the write goes to `workingDirByDevice`, no Electron dependency.
- const isDeviceMode = agencyConfig?.executionTarget === 'device' && !!agencyConfig?.boundDeviceId;
+ const effectiveTarget = resolveExecutionTarget(agencyConfig, {
+ isDesktop,
+ isHetero: isHeterogeneous,
+ });
+ const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
const canAddTopic = (isDesktop || isDeviceMode) && !!workingDirectory;
return (
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 037a9c6545a..3eab8a7c704 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -11,9 +11,11 @@ import { useNavigate, useParams } from 'react-router-dom';
import urlJoin from 'url-join';
import { useHeteroAgentCloudConfig } from '@/business/client/hooks/useHeteroAgentCloudConfig';
+import { isDesktop } from '@/const/version';
import { type ActionKeys } from '@/features/ChatInput';
import { ChatInput } from '@/features/Conversation';
import WideScreenContainer from '@/features/WideScreenContainer';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -43,15 +45,21 @@ const HeterogeneousChatInput = memo(() => {
const params = useParams<{ aid: string }>();
const navigate = useNavigate();
- const providerType = useAgentStore(agentSelectors.currentAgentHeterogeneousProviderType);
- const executionTarget = useAgentStore(agentSelectors.currentAgentExecutionTarget);
+ const agencyConfig = useAgentStore((s) => agentSelectors.currentAgentConfig(s)?.agencyConfig);
+ const providerType = agencyConfig?.heterogeneousProvider?.type;
+ const executionTarget = resolveExecutionTarget(agencyConfig, {
+ isDesktop,
+ isHetero: !!providerType,
+ });
const isRemoteAgent = !!providerType && isRemoteHeterogeneousType(providerType);
// A run goes to an `lh connect` device when the provider is a remote-only type
- // (openclaw / hermes) OR a local-CLI type (claude-code / codex) explicitly
- // targeted at a device. Either way the bound device must be online before we
- // let the user send โ€” guard it here instead of failing at dispatch time.
- const isDeviceExecution = isRemoteAgent || executionTarget === 'device';
+ // (openclaw / hermes) OR a local-CLI type (claude-code / codex) resolves to a
+ // bound device (including desktop "local" opened from web). Either way the
+ // bound device must be online before we let the user send โ€” guard it here
+ // instead of failing at dispatch time.
+ const isDeviceExecution =
+ isRemoteAgent || (executionTarget === 'device' && !!agencyConfig?.boundDeviceId);
const { status, refresh } = useRemoteAgentDeviceGuard({ enabled: isDeviceExecution });
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index a96a993c204..33194bc34e5 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -5,9 +5,11 @@ import { lazy, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { isDesktop } from '@/const/version';
import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';
import RightPanel from '@/features/RightPanel';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useAgentStore } from '@/store/agent';
import {
@@ -99,11 +101,15 @@ const AgentWorkingSidebar = memo(() => {
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const repoType = useRepoType(workingDirectory, targetDeviceId);
+ const effectiveTarget = resolveExecutionTarget(agencyConfig, {
+ isDesktop,
+ isHetero,
+ });
// Running against a bound device (remote, or this machine as a device): file
// tree + git reads go over RPC, so both Review and Files are reachable even
// when runtimeMode isn't `local`.
- const isDeviceMode = agencyConfig?.executionTarget === 'device' && !!agencyConfig?.boundDeviceId;
+ const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
// `targetDeviceId` also identifies the local desktop for per-device working
// directory state. Files/Review only need a deviceId when routing through a
// remote device RPC; local "This device" must keep Electron IPC + file-open
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index 641ba0a16b3..c25145431d8 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -419,6 +419,33 @@ describe('resolveAgentConfig', () => {
});
});
+ it('should merge runtime agencyConfig with base agencyConfig', () => {
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(
+ () =>
+ ({
+ ...mockAgentConfig,
+ agencyConfig: {
+ boundDeviceId: 'device-a',
+ executionTarget: 'device',
+ },
+ }) as any,
+ );
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ agencyConfig: {
+ executionTarget: 'none',
+ },
+ plugins: ['runtime-plugin'],
+ systemRole: 'Runtime system role',
+ });
+
+ const result = resolveAgentConfig({ agentId: 'builtin-agent' });
+
+ expect(result.agentConfig.agencyConfig).toEqual({
+ boundDeviceId: 'device-a',
+ executionTarget: 'none',
+ });
+ });
+
it('should override base chatConfig values with runtime chatConfig', () => {
vi.spyOn(agentSelectors.chatConfigByIdSelectors, 'getChatConfigById').mockReturnValue(
() =>
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index 2a95209c609..36566d57cdf 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -406,6 +406,12 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
...chatConfig,
...runtimeConfig?.chatConfig,
};
+ const resolvedAgencyConfig = runtimeConfig?.agencyConfig
+ ? {
+ ...agentConfig.agencyConfig,
+ ...runtimeConfig.agencyConfig,
+ }
+ : agentConfig.agencyConfig;
// === Page Editor Auto-Injection for Builtin Agents ===
// When a builtin agent (other than page-agent itself) is used in page editor,
@@ -452,6 +458,7 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
// Merge runtime systemRole into agent config
const resolvedAgentConfig: LobeAgentConfig = {
...agentConfig,
+ ...(resolvedAgencyConfig ? { agencyConfig: resolvedAgencyConfig } : {}),
systemRole: resolvedSystemRole,
};
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts
index b9b0222ae24..6887480e7e4 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts
@@ -18,7 +18,7 @@ describe('selectRuntimeType', () => {
expect(selectRuntimeType({ isGatewayMode: true }, opts)).toBe('gateway');
});
- it('routes local heterogeneousProvider to gateway on web โ€” cloud sandbox is the only execution env', () => {
+ it('routes local heterogeneousProvider to gateway on web', () => {
expect(
selectRuntimeType({ heterogeneousProvider: heteroProvider, isGatewayMode: true }, opts),
).toBe('gateway');
@@ -91,6 +91,25 @@ describe('selectRuntimeType', () => {
).toBe('gateway');
});
+ it('routes to gateway even when the bound device IS this desktop (observability choice)', () => {
+ // `device` vs `local` on the same machine is a user-facing semantic
+ // choice, not a transport detail: gateway dispatch streams progress
+ // through the server so other clients (mobile/web) can follow the run,
+ // while `local` IPC is faster but desktop-session-only. NEVER collapse
+ // `device(currentDeviceId)` into the in-process path.
+ expect(
+ selectRuntimeType(
+ {
+ boundDeviceId: 'this-desktop-device-id',
+ executionTarget: 'device',
+ heterogeneousProvider: heteroProvider,
+ isGatewayMode: false,
+ },
+ { isDesktop: true },
+ ),
+ ).toBe('gateway');
+ });
+
it('routes to gateway when executionTarget = sandbox on desktop', () => {
expect(
selectRuntimeType(
@@ -117,7 +136,7 @@ describe('selectRuntimeType', () => {
).toBe('hetero');
});
- it('falls back to gateway when executionTarget = local on web (no local path)', () => {
+ it('falls back to gateway when executionTarget = local on web (sandbox or bound device)', () => {
expect(
selectRuntimeType(
{
diff --git a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts b/src/store/chat/slices/aiChat/actions/agentDispatcher.ts
index 781961b7c33..ebbdf69b7b2 100644
--- a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts
+++ b/src/store/chat/slices/aiChat/actions/agentDispatcher.ts
@@ -49,6 +49,8 @@ export interface AgentInvocationIntent {
}
export interface RuntimeSelectionContext {
+ /** Device bound by the execution switcher. Used when desktop `local` syncs to web. */
+ boundDeviceId?: string;
/**
* Per-agent execution device choice from the composer's Execution Device
* switcher. Only meaningful when `heterogeneousProvider` is a local CLI
@@ -56,7 +58,8 @@ export interface RuntimeSelectionContext {
* - `'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).
+ * in-process spawn, web โ†’ `gateway` sandbox unless a desktop-local
+ * boundDeviceId is available, in which case the server dispatches to it.
*/
executionTarget?: DeviceExecutionTarget;
/** Per-agent heterogeneous provider config (desktop only โ€” takes priority over gateway). */
@@ -102,11 +105,11 @@ export const selectRuntimeType = (
// 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).
+ // the desktop. On web, unbound `local` resolves to sandbox, while a desktop
+ // `local` selection synced with boundDeviceId resolves to device dispatch.
if (ctx.heterogeneousProvider) {
const target = resolveExecutionTarget(
- { executionTarget: ctx.executionTarget },
+ { boundDeviceId: ctx.boundDeviceId, executionTarget: ctx.executionTarget },
{ isDesktop, isHetero: true },
);
return target === 'local' ? 'hetero' : 'gateway';
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index 94c5e1b574c..7dcf78880b3 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({
+ boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
isGatewayMode: this.#get().isGatewayModeEnabled(),
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 0fab4f9d1d7..cfde47b86fb 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -251,6 +251,7 @@ export class ConversationLifecycleActionImpl {
const agentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());
const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;
const runtimeType = selectRuntimeType({
+ boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider,
isGatewayMode: this.#get().isGatewayModeEnabled(),
@@ -1280,6 +1281,7 @@ export class ConversationLifecycleActionImpl {
{ kind: 'mention', targetAgentId, instruction, parentMessageId: toolMessage.id },
{
conversationContext: context,
+ boundDeviceId: parentAgentConfig?.agencyConfig?.boundDeviceId,
heterogeneousProvider: parentAgentConfig?.agencyConfig?.heterogeneousProvider,
inPortalThread,
isGatewayMode: this.#get().isGatewayModeEnabled(),
diff --git a/src/store/chat/slices/aiChat/actions/nonHeteroSubAgentDispatcher.ts b/src/store/chat/slices/aiChat/actions/nonHeteroSubAgentDispatcher.ts
index 024c51cdca1..281b7088fa1 100644
--- a/src/store/chat/slices/aiChat/actions/nonHeteroSubAgentDispatcher.ts
+++ b/src/store/chat/slices/aiChat/actions/nonHeteroSubAgentDispatcher.ts
@@ -18,6 +18,8 @@ import {
* dispatcher needs but that do not belong in the intent itself.
*/
export interface NonHeteroSubAgentDispatchContext {
+ /** Device bound by the parent agent execution switcher. */
+ boundDeviceId?: string;
/** Conversation context of the *parent* agent (agentId = parent agent). */
conversationContext: ConversationContext;
/** Per-agent heterogeneous provider config used for runtime resolution. */
@@ -73,6 +75,7 @@ export async function dispatchNonHeteroSubAgent(
store: Pick<ChatStore, 'executeClientAgent' | 'executeGatewayAgent'>,
): Promise<void> {
const runtimeType = selectRuntimeType({
+ boundDeviceId: ctx.boundDeviceId,
heterogeneousProvider: ctx.heterogeneousProvider,
isGatewayMode: ctx.isGatewayMode,
parentRuntime: ctx.parentRuntime,
diff --git a/src/store/tool/builtinToolRegistry.test.ts b/src/store/tool/builtinToolRegistry.test.ts
index abe4080c2c4..f525e0ae759 100644
--- a/src/store/tool/builtinToolRegistry.test.ts
+++ b/src/store/tool/builtinToolRegistry.test.ts
@@ -44,6 +44,7 @@ describe('builtin tool registry', () => {
expect(runtime.plugins).toContain(UserInteractionIdentifier);
expect(runtime.plugins).toContain(WebOnboardingIdentifier);
+ expect(runtime.agencyConfig?.executionTarget).toBe('none');
});
it('exposes the marketplace APIs under the web onboarding manifest', () => {