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.

✨ feat(device): default new agents' execution target to auto (#22949)

Arvin Xu2e436a784cbe
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index a319bac5f9b..fe9444aa2f0 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -308,11 +308,10 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(createOpArgs.activeDeviceId).toBeUndefined();
});
- it('should NOT auto-activate the single online device by default (executionTarget unset β†’ local)', async () => {
- // The default mode never grabs a device β€” only explicit `auto` does.
+ it('should auto-activate the single online device by default (executionTarget unset β†’ auto)', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
- await useAgencyConfig({}); // unset executionTarget β†’ default `local`
+ await useAgencyConfig({}); // unset executionTarget β†’ default `auto`
await service.execAgent({
agentId: 'agent-1',
@@ -321,7 +320,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
const createOpArgs = mockCreateOperation.mock.calls[0][0];
- expect(createOpArgs.activeDeviceId).toBeUndefined();
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
});
});
@@ -348,7 +347,8 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
// local-system system prompt's {{workingDirectory}} / {{hostname}}
// placeholders resolve instead of reaching the LLM as literals. Multi-device
// users still pick explicitly (the model selects via the remote-device
- // tool). The default mode never auto-activates.
+ // tool). An unset target defaults to `auto`; an explicit `local` never
+ // auto-activates.
it('should auto-activate the only online device (executionTarget: auto)', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
@@ -392,10 +392,24 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(createOpArgs.activeDeviceId).toBeUndefined();
});
- it('should NOT auto-activate the single online device by default (unset β†’ local)', async () => {
+ it('should auto-activate the single online device by default (unset β†’ auto)', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ await useAgencyConfig({}); // unset executionTarget β†’ default `auto`
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'List my files',
+ });
+
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
+ });
+
+ it('should NOT auto-activate the single online device for an explicit local target', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
- await useAgencyConfig({}); // unset executionTarget β†’ default `local`
+ await useAgencyConfig({ executionTarget: 'local' });
await service.execAgent({
agentId: 'agent-1',
@@ -643,6 +657,25 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(createOpArgs.activeDeviceId).toBe('device-001');
});
+ // An unset target is the same default as `auto`, so it must not resurrect a
+ // stale topic device either: the default agent re-picks the single online
+ // device instead of staying unrouted on the offline one.
+ it('should not reuse topic boundDeviceId for an unset target either', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ topicMock.findById.mockResolvedValue({ metadata: { boundDeviceId: 'device-002' } });
+ await useAgencyConfig({});
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-existing' },
+ prompt: 'Run a command',
+ });
+
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ expect(createOpArgs.activeDeviceId).toBe('device-001');
+ });
+
// An explicit device on the request is a promise to the caller, so the new
// topic records that the binding was pinned rather than auto-picked β€” a
// later turn on an `auto` agent then stays on it instead of choosing
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index cb17abf0349..41c3fcce7f2 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -27,6 +27,7 @@ import { AiModelModel } from '@/database/models/aiModel';
import type { MessageModel } from '@/database/models/message';
import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
import type { TopicModel } from '@/database/models/topic';
+import { defaultsToAuto } from '@/helpers/executionTarget';
import { resolveModelExtendParamsForUser } from '@/server/modules/AgentRuntime/adapters/serverCallLlmContextHints';
import type { AgentConfigWithId } from '@/server/services/agent';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
@@ -793,13 +794,19 @@ export const setupTurn = async (
// grab whichever machine is online now.
const topicDeviceBindingPinned =
canUseTopicPin && existingTopic?.metadata?.deviceBindingPinned === true;
+ // An unset target is the same default as `auto` (see `defaultsToAuto`), so
+ // both re-pick a device on every turn instead of resurrecting an earlier
+ // pick β€” only a binding the caller chose explicitly pins the conversation.
+ const autoTargetSelected =
+ agentConfig.agencyConfig?.executionTarget === 'auto' ||
+ defaultsToAuto(agentConfig.agencyConfig, isHeterogeneousAgentModelId(model));
// A project-directory topic already routed to its directory's device above.
if (
!requestedDeviceId &&
!existingTopic?.projectWorkingDirectoryId &&
topicPinnedDeviceId &&
!isFixedExecutionTargetSelection &&
- (agentConfig.agencyConfig?.executionTarget !== 'auto' || topicDeviceBindingPinned)
+ (!autoTargetSelected || topicDeviceBindingPinned)
) {
resolvedRequestedDeviceId = topicPinnedDeviceId;
effectiveRequestedDeviceId = topicPinnedDeviceId;
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 7e7e0396f79..b207697ccff 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -396,8 +396,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
selectExecutionTarget,
});
- // Auto-default to THIS desktop's local execution on first open, for both
- // personal and workspace agents (workspace behaviour used to be a hostname
+ // Auto-default to THIS desktop's local execution on first open when the
+ // unset target does not resolve to `auto` (hetero agents, or gateway mode
+ // off), for both personal and workspace agents (workspace behaviour used to be a hostname
// lookup against the workspace device pool β€” see β€” but with
// per-user overrides that lookup is unnecessary: `useSelectExecutionTarget`
// resolves `'local'` to this desktop's personal gateway `deviceId` and, for
@@ -413,6 +414,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
if (!isDesktop) return;
if (!canShowExecutionTargetSelector) return;
if (isWorkspacePreferenceLoading) return;
+ // the unset target already defaults to `auto` wherever the gateway routes,
+ // and canary's `getMachineDefaultTarget` below owns the stored-target
+ // decisions β€” this only keeps the auto default from being overwritten.
+ if (executionTarget === 'auto') return;
if (!currentDeviceId) return;
// Whether this machine has a workspace row is only known once the server
// confirms the list; deciding earlier would write `local` and then move it.
@@ -439,6 +444,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
agencyConfig?.executionTarget,
agencyConfig?.boundDeviceId,
currentDeviceId,
+ executionTarget,
canShowExecutionTargetSelector,
deviceListError,
isDeviceListConfirmed,
diff --git a/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts b/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts
index 8e6f33ae192..f60c8c3907c 100644
--- a/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts
@@ -38,6 +38,9 @@ vi.mock('@/store/agent/selectors', () => ({
getAgencyConfigById:
(id: string) => (s: { agentMap: Record<string, { agencyConfig?: unknown }> }) =>
s.agentMap[id]?.agencyConfig,
+ getAgentModelById:
+ (id: string) => (s: { agentMap: Record<string, { model?: string }> }) =>
+ s.agentMap[id]?.model ?? '',
getAgentById: (id: string) => (s: { agentMap: Record<string, unknown> }) => s.agentMap[id],
},
}));
diff --git a/src/features/Conversation/store/slices/generation/heteroRun.ts b/src/features/Conversation/store/slices/generation/heteroRun.ts
index a16a91cebe0..7a893e2ff7f 100644
--- a/src/features/Conversation/store/slices/generation/heteroRun.ts
+++ b/src/features/Conversation/store/slices/generation/heteroRun.ts
@@ -1,4 +1,4 @@
-import { LOADING_FLAT } from '@lobechat/const';
+import { isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';
import { type HeteroAttachedFileRef } from '@lobechat/heterogeneous-agents';
import type {
ChatImageItem,
@@ -88,7 +88,8 @@ export const ensureEffectiveAgencyAccess = async (agentId: string) => {
*/
export const getEffectiveAgencyConfig = (agentId: string, topic?: ChatTopic | null) => {
const agentState = getAgentStoreState();
- const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;
+ const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);
+ const sharedAgencyConfig = agentConfig?.agencyConfig;
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
const currentUserId = userProfileSelectors.userId(getUserStoreState());
// Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
@@ -120,6 +121,7 @@ export const getEffectiveAgencyConfig = (agentId: string, topic?: ChatTopic | nu
},
getTopicBoundDeviceId(topic, agentId),
getElectronStoreState().gatewayDeviceInfo?.deviceId,
+ { isHetero: isHeterogeneousAgentModelId(agentConfig?.model) },
);
return {
diff --git a/src/helpers/executionTarget.autoDefault.test.ts b/src/helpers/executionTarget.autoDefault.test.ts
new file mode 100644
index 00000000000..6e80dbbe860
--- /dev/null
+++ b/src/helpers/executionTarget.autoDefault.test.ts
@@ -0,0 +1,104 @@
+import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyTopicDeviceBinding,
+ resolveExecutionPlan,
+ resolveExecutionTarget,
+} from './executionTarget';
+
+const cfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({ ...over });
+
+describe('unset execution target defaults to auto', () => {
+ it('resolves to auto on web when a gateway can route to a device', () => {
+ const web = { clientExecutionAvailable: false, deviceRoutingAvailable: true };
+ expect(resolveExecutionTarget(undefined, web)).toBe('auto');
+ expect(resolveExecutionTarget(cfg(), web)).toBe('auto');
+ expect(resolveExecutionTarget(cfg(), { ...web, workspaceScoped: true })).toBe('auto');
+ // desktop takes the same default when the gateway routes …
+ expect(resolveExecutionTarget(cfg(), { ...web, clientExecutionAvailable: true })).toBe('auto');
+ // … and keeps its in-process default when it does not
+ expect(resolveExecutionTarget(cfg(), { clientExecutionAvailable: true })).toBe('local');
+ // no gateway β†’ nothing to route to
+ expect(resolveExecutionTarget(cfg(), { clientExecutionAvailable: false })).toBe('none');
+ // an explicit pick always wins
+ expect(resolveExecutionTarget(cfg({ executionTarget: 'none' }), web)).toBe('none');
+ // a leftover binding is not overridden by the auto default
+ expect(resolveExecutionTarget(cfg({ boundDeviceId: 'device-a' }), web)).toBe('none');
+ // hetero agents keep their own sandbox fallback
+ expect(resolveExecutionTarget(cfg(), { ...web, isHetero: true })).toBe('sandbox');
+ });
+
+ it('auto-picks a device in the server plan', () => {
+ const params = { clientExecutionAvailable: true, onlineDeviceIds: ['device-a'] };
+ expect(resolveExecutionPlan({ ...params, agencyConfig: cfg() })).toEqual({
+ deviceId: 'device-a',
+ kind: 'device',
+ target: 'auto',
+ });
+ expect(
+ resolveExecutionPlan({ ...params, agencyConfig: cfg(), onlineDeviceIds: ['a', 'b'] }),
+ ).toEqual({ kind: 'device-unrouted', reason: 'ambiguous-online-devices', target: 'auto' });
+ expect(resolveExecutionPlan({ ...params, agencyConfig: cfg(), onlineDeviceIds: [] })).toEqual({
+ kind: 'device-unrouted',
+ reason: 'no-online-device',
+ target: 'auto',
+ });
+ // a desktop request takes the same default
+ expect(
+ resolveExecutionPlan({ ...params, agencyConfig: cfg(), localDeviceId: 'device-a' }),
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'auto' });
+ // an explicit `local` still pins the sending desktop and never grabs another device
+ expect(
+ resolveExecutionPlan({
+ ...params,
+ agencyConfig: cfg({ executionTarget: 'local' }),
+ localDeviceId: 'this-desktop',
+ }),
+ ).toEqual({ kind: 'device-unrouted', reason: 'bound-device-offline', target: 'local' });
+ // no gateway β†’ nothing to route to
+ expect(
+ resolveExecutionPlan({ ...params, agencyConfig: cfg(), clientExecutionAvailable: false }),
+ ).toEqual({ kind: 'none', target: 'none' });
+ // an explicit `none` stays plain chat
+ expect(
+ resolveExecutionPlan({ ...params, agencyConfig: cfg({ executionTarget: 'none' }) }),
+ ).toEqual({ kind: 'none', target: 'none' });
+ });
+
+ describe('applyTopicDeviceBinding', () => {
+ it('leaves an agent with no stored target to the auto default', () => {
+ // An unset target already resolves to `auto`, so converting the topic's
+ // machine into a concrete pin here would make the default stricter than an
+ // explicit `auto` (which re-picks a device every run).
+ const unset = cfg();
+
+ expect(
+ applyTopicDeviceBinding({ agencyConfig: unset, workspaceScoped: false }, 'dev-a', undefined)
+ .agencyConfig,
+ ).toBe(unset);
+ });
+
+ it('keeps the topic machine for a model-only heterogeneous agent', () => {
+ // Legacy `model: 'claude-code'` agents carry no provider yet; they never
+ // take the auto default, so the topic must stay on its machine.
+ expect(
+ applyTopicDeviceBinding({ agencyConfig: cfg(), workspaceScoped: false }, 'dev-a', 'dev-b', {
+ isHetero: true,
+ }).agencyConfig,
+ ).toMatchObject({ boundDeviceId: 'dev-a', executionTarget: 'device' });
+ });
+
+ it('still honours a leftover binding on a config without a stored target', () => {
+ // A bound device is not an auto default β€” `defaultsToAuto` skips it, so the
+ // topic keeps routing to its own machine.
+ expect(
+ applyTopicDeviceBinding(
+ { agencyConfig: cfg({ boundDeviceId: 'dev-b' }), workspaceScoped: false },
+ 'dev-a',
+ undefined,
+ ).agencyConfig,
+ ).toMatchObject({ boundDeviceId: 'dev-a', executionTarget: 'device' });
+ });
+ });
+});
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index e050d19b640..cd11aab7e14 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -748,17 +748,6 @@ describe('resolveExecutionPlan', () => {
).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'local' });
});
- it('treats the desktop default (unset target) as `local` but never auto-grabs a device', () => {
- // unset β†’ `local` on desktop; device-capable but unrouted until bound.
- expect(
- resolveExecutionPlan({
- agencyConfig: undefined,
- clientExecutionAvailable: true,
- onlineDeviceIds: ONLINE_A,
- }),
- ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'local' });
- });
-
it('resolves the unset web target to none', () => {
expect(
resolveExecutionPlan({
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 793d9983f31..65769464d22 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -126,13 +126,29 @@ export const isHeterogeneousSandboxExecutionAvailable = (type: string | undefine
type !== 'qoder' &&
type !== 'trae';
+/**
+ * Whether an agent with no stored `executionTarget` takes the `auto` default
+ * (desktop and web alike, wherever a device-gateway can route). Heterogeneous
+ * agents keep their own local/sandbox runtime β€” `auto` is not offered for
+ * them β€” and a leftover `boundDeviceId` keeps routing to that device.
+ */
+export const defaultsToAuto = (
+ agencyConfig: LobeAgentAgencyConfig | undefined,
+ isHetero: boolean | undefined,
+): boolean =>
+ agencyConfig?.executionTarget === undefined &&
+ !agencyConfig?.boundDeviceId &&
+ !isHetero &&
+ !agencyConfig?.heterogeneousProvider;
+
/**
* Single source of truth for where an agent executes β€” one global
* `agencyConfig.executionTarget` drives both desktop and web.
*
* - `none` β†’ no execution environment (plain chat)
- * - `auto` β†’ auto-pick a device (opt-in; the only mode that activates a
- * device the user did not explicitly select)
+ * - `auto` β†’ auto-pick an online device (the only mode that activates a
+ * device the user did not explicitly select; also the default,
+ * see below)
* - `local` β†’ this machine (in-process; desktop only)
* - `sandbox` β†’ server cloud sandbox
* - `device` β†’ remote device (dispatched to `boundDeviceId`)
@@ -144,7 +160,11 @@ export const isHeterogeneousSandboxExecutionAvailable = (type: string | undefine
* 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
+ * Defaults: `auto` whenever a device-gateway can route
+ * (`deviceRoutingAvailable`); without one, desktop β†’ `local` and web β†’
+ * `none`. Heterogeneous agents and configs that already carry a
+ * `boundDeviceId` skip the `auto` default (see `defaultsToAuto`) and keep the
+ * gateway-less fallback. On web `local` isn't available
* (no local filesystem). A desktop `local` pick pins that desktop's own
* `deviceId` as `boundDeviceId` (see `useSelectExecutionTarget`), and the
* server routes such a config to that bound device β€” so on web we resolve it
@@ -198,7 +218,13 @@ export const resolveExecutionTarget = (
) {
return 'device';
}
- let effective = stored ?? (clientAvailable ? 'local' : 'none');
+ let effective =
+ stored ??
+ (deviceRoutingAvailable && defaultsToAuto(agencyConfig, isHetero)
+ ? 'auto'
+ : clientAvailable
+ ? 'local'
+ : 'none');
if (
!clientAvailable &&
(isHetero || deviceRoutingAvailable) &&
@@ -334,6 +360,10 @@ export interface TopicDeviceBindingResult {
* default in turnSetup.
*
* The binding is this member's own run history, so it lifts `workspaceScoped`.
+ *
+ * `isHetero` flags a legacy agent identified only by `model: '<cli-type>'`
+ * (no stored provider yet): it never takes the `auto` default, so its topic
+ * keeps its machine.
*/
export const applyTopicDeviceBinding = (
{
@@ -342,12 +372,17 @@ export const applyTopicDeviceBinding = (
}: { agencyConfig: LobeAgentAgencyConfig | undefined; workspaceScoped: boolean },
topicDeviceId: string | undefined,
currentDeviceId: string | undefined,
+ { isHetero }: { isHetero?: boolean } = {},
): TopicDeviceBindingResult => {
const unchanged = { agencyConfig, workspaceScoped };
const target = agencyConfig?.executionTarget;
if (
!topicDeviceId ||
+ // `auto` picks a fresh device every run, so its own earlier pick never pins
+ // the conversation. An unset target takes that same `auto` default (see
+ // `defaultsToAuto`), so it must not be converted into a concrete pin either.
target === 'auto' ||
+ defaultsToAuto(agencyConfig, isHetero) ||
agencyConfig?.executionTargetSelectionPolicy === 'fixed'
)
return unchanged;
@@ -536,7 +571,14 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
// agents always need a runtime, so they never take this path.
if (resolveToolMode(chatConfig) === 'chat' && !isHetero) return { kind: 'none', target: 'none' };
- const target = resolveExecutionTarget(agencyConfig, {
+ // Server callers signal a gateway through `clientExecutionAvailable`, which
+ // would resolve an unset target as `local`; give it the same `auto` default
+ // the picker shows on every client.
+ const planAgencyConfig: LobeAgentAgencyConfig | undefined =
+ clientExecutionAvailable && defaultsToAuto(agencyConfig, isHetero)
+ ? { ...agencyConfig, executionTarget: 'auto' }
+ : agencyConfig;
+ const target = resolveExecutionTarget(planAgencyConfig, {
isHetero,
clientExecutionAvailable,
sandboxExecutionAvailable,
diff --git a/src/hooks/useEffectiveAgencyConfig.test.ts b/src/hooks/useEffectiveAgencyConfig.test.ts
index c32cd797caa..49bbd53538f 100644
--- a/src/hooks/useEffectiveAgencyConfig.test.ts
+++ b/src/hooks/useEffectiveAgencyConfig.test.ts
@@ -47,6 +47,8 @@ vi.mock('@/store/agent/selectors', () => ({
agentMap: Record<string, { visibility?: 'private' | 'public'; workspaceId?: string }>;
}) =>
s.agentMap[id],
+ getAgentModelById: (id: string) => (s: { agentMap: Record<string, { model?: string }> }) =>
+ s.agentMap[id]?.model ?? 'gpt-4o',
},
}));
vi.mock('@/store/user', () => ({ useUserStore: vi.fn() }));
diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.ts
index 5955a0cee29..89c209be8e5 100644
--- a/src/hooks/useEffectiveAgencyConfig.ts
+++ b/src/hooks/useEffectiveAgencyConfig.ts
@@ -1,3 +1,4 @@
+import { isHeterogeneousAgentModelId } from '@lobechat/const';
import type { LobeAgentAgencyConfig } from '@lobechat/types';
import { resolveAgentAgencyConfig } from '@lobechat/types';
@@ -92,6 +93,10 @@ export const useEffectiveAgencyConfig = (
const agent = useAgentStore((s) =>
agentId ? agentByIdSelectors.getAgentById(agentId)(s) : undefined,
);
+ const isModelOnlyHetero = useAgentStore(
+ (s) =>
+ !!agentId && isHeterogeneousAgentModelId(agentByIdSelectors.getAgentModelById(agentId)(s)),
+ );
const { canManageAgent, isAccessLoading } = useAgentManagementAccess(agentId);
const usesWorkspaceMemberSelection =
!!agent?.workspaceId && agent.visibility !== 'private' && !canManageAgent;
@@ -153,6 +158,7 @@ export const useEffectiveAgencyConfig = (
},
topicDeviceId,
currentDeviceId,
+ { isHetero: isModelOnlyHetero },
);
// Managers and private-agent owners also keep their `local` pick in the
// per-user override, so any workspace agent must wait for the preference
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.localDevice.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.localDevice.test.ts
new file mode 100644
index 00000000000..59f2d281e40
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.localDevice.test.ts
@@ -0,0 +1,439 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { aiAgentService } from '@/services/aiAgent';
+
+import type { GatewayConnection } from '../transports/gateway/gateway';
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ execAgentTask: vi.fn(),
+ getTopics: vi.fn().mockResolvedValue([]),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ // Defaults to "no detail readable" so the silent-end reconcile stays
+ // fail-safe unless a test opts in by returning a row.
+ getTopicDetail: vi.fn().mockResolvedValue(null),
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+const moveChatComposerAttachments = vi.hoisted(() => vi.fn());
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatComposerAttachments }),
+}));
+
+const mockUserDefaultConfig = vi.hoisted(() => ({
+ disableGatewayMode: undefined as boolean | undefined,
+}));
+const mockToolInterventionConfig = vi.hoisted(() => ({
+ allowList: [] as string[],
+ approvalMode: 'manual' as 'allow-list' | 'auto-run' | 'manual',
+}));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: {
+ getState: vi.fn(() => mockUserState),
+ },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ settingsSelectors: {
+ defaultAgentConfig: () => ({
+ chatConfig: { disableGatewayMode: mockUserDefaultConfig.disableGatewayMode },
+ }),
+ },
+ toolInterventionSelectors: {
+ allowList: () => mockToolInterventionConfig.allowList,
+ approvalMode: () => mockToolInterventionConfig.approvalMode,
+ },
+ userProfileSelectors: {
+ userId: (state: typeof mockUserState) => state.profile.id,
+ },
+}));
+
+// ─── Local-device activation (本机) test seams ───
+// Controlled per-test; default off so the rest of the suite runs as web (no
+// device resolution, no electron IPC).
+const mockEnv = vi.hoisted(() => ({ isDesktop: false }));
+const mockGateway = vi.hoisted(() => ({ getDeviceInfo: vi.fn() }));
+// Effective runtime mode === 'local' (what isLocalSystemEnabledById returns)
+// and chat mode (what isChatModeById returns).
+const mockRuntime = vi.hoisted(() => ({ isChatMode: false, isLocal: false }));
+const mockAgentStore = vi.hoisted(() => ({
+ state: { activeAgentId: undefined, agentMap: {} } as any,
+}));
+
+vi.mock('@/const/version', async (importOriginal) => {
+ const actual = await importOriginal<typeof ConstVersion>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockEnv.isDesktop;
+ },
+ };
+});
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: mockGateway.getDeviceInfo },
+}));
+
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mockAgentStore.state }));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.agencyConfig,
+ getAgentModelById: (agentId: string) => (state: any) => state.agentMap?.[agentId]?.model ?? '',
+ getAgentById: (agentId: string) => (state: any) => state.agentMap?.[agentId],
+ },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
+ chatConfigByIdSelectors: {
+ getChatConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.chatConfig ?? {},
+ isChatModeById: () => () => mockRuntime.isChatMode,
+ isLocalSystemEnabledById: () => () => mockRuntime.isLocal,
+ },
+}));
+
+// ─── Mock Client Factory ───
+
+function createMockClient(): GatewayConnection['client'] & {
+ emitEvent: (event: string, ...args: any[]) => void;
+} {
+ const listeners = new Map<string, Set<(...args: any[]) => void>>();
+
+ return {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ emitEvent(event: string, ...args: any[]) {
+ listeners.get(event)?.forEach((listener) => listener(...args));
+ },
+ on: vi.fn((event: string, listener: (...args: any[]) => void) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener);
+ }),
+ reconnect: vi.fn(async () => {}),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+describe('GatewayActionImpl · local device activation (本机)', () => {
+ beforeEach(() => {
+ mockEnv.isDesktop = false;
+ mockRuntime.isLocal = false;
+ mockRuntime.isChatMode = false;
+ mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };
+ mockUserState.workspaceUserPreference.agentDeviceOverrides = {};
+ mockGateway.getDeviceInfo.mockReset();
+ });
+
+ afterEach(() => {
+ delete (globalThis as any).window;
+ });
+
+ function createExecuteTestAction() {
+ const mockClient = createMockClient();
+ const moveQueuedMessages = vi.fn();
+ const moveVoiceMessages = vi.fn();
+ const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };
+ const associateMessageWithOperation = vi.fn();
+ const connectToGateway = vi.fn();
+ const internalDispatchTopic = vi.fn();
+ const internalReplaceTopicId = vi.fn();
+ const onOperationCancel = vi.fn();
+ const replaceMessages = vi.fn();
+ const refreshTopic = vi.fn().mockResolvedValue(undefined);
+ const refreshTopicDetail = vi.fn().mockResolvedValue(undefined);
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));
+ const switchTopic = vi.fn();
+ const updateTopicStatus = vi.fn();
+ const set = vi.fn((updater: any) => {
+ if (typeof updater === 'function') {
+ Object.assign(state, updater(state));
+ } else {
+ Object.assign(state, updater);
+ }
+ });
+
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation,
+ connectToGateway,
+ internal_dispatchTopic: internalDispatchTopic,
+ internal_replaceTopicId: internalReplaceTopicId,
+ moveQueuedMessages,
+ moveVoiceMessages,
+ onOperationCancel,
+ replaceMessages,
+ refreshTopic,
+ refreshTopicDetail,
+ startOperation,
+ switchTopic,
+ updateTopicStatus,
+ })) as any;
+
+ // Set up window.global_serverConfigStore
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({
+ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' },
+ }),
+ },
+ };
+
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => mockClient);
+
+ return {
+ action,
+ associateMessageWithOperation,
+ connectToGateway,
+ get,
+ internalDispatchTopic,
+ internalReplaceTopicId,
+ mockClient,
+ moveQueuedMessages,
+ moveVoiceMessages,
+ onOperationCancel,
+ replaceMessages,
+ refreshTopic,
+ refreshTopicDetail,
+ set,
+ startOperation,
+ state,
+ switchTopic,
+ updateTopicStatus,
+ };
+ }
+
+ // When the desktop runs against 本机 (effective runtime mode 'local'), the
+ // client must forward this machine's own gateway deviceId so the server can
+ // preset activeDeviceId and inject lobe-local-system into the first LLM
+ // payload β€” skipping the activateDevice round-trip. It must NOT do so for a
+ // cloud/none run, otherwise that run would be wrongly routed to the device.
+ describe('local device activation (本机)', () => {
+ const successResult = {
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created' as const,
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ };
+
+ afterEach(() => {
+ mockEnv.isDesktop = false;
+ mockRuntime.isLocal = false;
+ mockRuntime.isChatMode = false;
+ mockGateway.getDeviceInfo.mockReset();
+ mockAgentStore.state.agentMap = {};
+ mockUserState.workspaceUserPreference.agentDeviceOverrides = {};
+ });
+
+ const send = async () => {
+ mockAgentStore.state.agentMap['agent-1'] ??= {
+ agencyConfig: { executionTarget: mockRuntime.isLocal ? 'local' : 'sandbox' },
+ userId: 'user-1',
+ };
+ const { action } = createExecuteTestAction();
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(successResult);
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },
+ message: 'list files in cwd',
+ });
+ };
+
+ it('forwards this desktop as both the route and local capability hint', async () => {
+ mockEnv.isDesktop = true;
+ mockRuntime.isLocal = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-1' });
+
+ await send();
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ deviceId: 'device-local-1',
+ localDeviceId: 'device-local-1',
+ }),
+ );
+ });
+
+ // 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;
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ // Regression guard (chat mode β†’ no execution environment): chat mode must
+ // not resolve this machine's deviceId even on a local target, otherwise
+ // the server presets activeDeviceId and re-injects lobe-local-system.
+ it('does not resolve a deviceId in chat mode, even when local mode is set', async () => {
+ mockEnv.isDesktop = true;
+ mockRuntime.isLocal = true;
+ mockRuntime.isChatMode = true;
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('never resolves a deviceId off desktop, even when local mode is set', async () => {
+ mockEnv.isDesktop = false;
+ mockRuntime.isLocal = true;
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('uses a workspace member local override instead of the shared remote device', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-member' });
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: { boundDeviceId: 'workspace-device', executionTarget: 'device' },
+ userId: 'workspace-owner',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ };
+ mockUserState.workspaceUserPreference.agentDeviceOverrides['agent-1'] = {
+ boundDeviceId: 'device-local-member',
+ executionTarget: 'local',
+ };
+
+ await send();
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device-local-member' }),
+ );
+ });
+
+ it('does not preset this desktop for a workspace member remote override', async () => {
+ mockEnv.isDesktop = true;
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: { executionTarget: 'local' },
+ userId: 'workspace-owner',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ };
+ mockUserState.workspaceUserPreference.agentDeviceOverrides['agent-1'] = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ };
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('sends a distinct local device hint for a local platform agent', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: {
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'openclaw' },
+ },
+ userId: 'user-1',
+ };
+
+ await send();
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({ localDeviceId: 'this-desktop' }),
+ );
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('sends a harmless desktop hint without overriding a remote platform target', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'hermes' },
+ },
+ userId: 'user-1',
+ };
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).toHaveBeenCalled();
+ const request = vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0];
+ expect(request).not.toHaveProperty('deviceId');
+ expect(request).toHaveProperty('localDeviceId', 'this-desktop');
+ });
+
+ // Regression guard: a legacy agent identified only by `model` (no stored
+ // provider yet) must keep this desktop's hints. The `auto` default is
+ // driven by `isHetero`, and a provider-only discriminator would let it
+ // swallow the hints β€” sending a Claude Code run to the cloud sandbox.
+ it('keeps both desktop hints for a model-only heterogeneous agent', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-1' });
+ mockAgentStore.state.agentMap['agent-1'] = { model: 'claude-code', userId: 'user-1' };
+
+ await send();
+
+ const request = vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0];
+ expect(request).toHaveProperty('deviceId', 'device-local-1');
+ expect(request).toHaveProperty('localDeviceId', 'device-local-1');
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 4392983d95e..15c5c99c329 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -124,6 +124,7 @@ vi.mock('@/store/agent/selectors', () => ({
agentByIdSelectors: {
getAgencyConfigById: (agentId: string) => (state: any) =>
state.agentMap?.[agentId]?.agencyConfig,
+ getAgentModelById: (agentId: string) => (state: any) => state.agentMap?.[agentId]?.model ?? '',
getAgentById: (agentId: string) => (state: any) => state.agentMap?.[agentId],
},
agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
@@ -3648,190 +3649,6 @@ describe('GatewayActionImpl', () => {
});
expect(internalPinTopicStatus).not.toHaveBeenCalled();
});
-
- // When the desktop runs against 本机 (effective runtime mode 'local'), the
- // client must forward this machine's own gateway deviceId so the server can
- // preset activeDeviceId and inject lobe-local-system into the first LLM
- // payload β€” skipping the activateDevice round-trip. It must NOT do so for a
- // cloud/none run, otherwise that run would be wrongly routed to the device.
- describe('local device activation (本机)', () => {
- const successResult = {
- agentId: 'agent-1',
- assistantMessageId: 'ast-1',
- autoStarted: true,
- createdAt: new Date().toISOString(),
- message: 'ok',
- operationId: 'server-op-1',
- status: 'created' as const,
- success: true,
- timestamp: new Date().toISOString(),
- token: 'test-token',
- topicId: 'topic-1',
- userMessageId: 'usr-1',
- };
-
- afterEach(() => {
- mockEnv.isDesktop = false;
- mockRuntime.isLocal = false;
- mockRuntime.isChatMode = false;
- mockGateway.getDeviceInfo.mockReset();
- mockAgentStore.state.agentMap = {};
- mockUserState.workspaceUserPreference.agentDeviceOverrides = {};
- });
-
- const send = async () => {
- mockAgentStore.state.agentMap['agent-1'] ??= {
- agencyConfig: { executionTarget: mockRuntime.isLocal ? 'local' : 'sandbox' },
- userId: 'user-1',
- };
- const { action } = createExecuteTestAction();
- vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(successResult);
- await action.executeGatewayAgent({
- context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },
- message: 'list files in cwd',
- });
- };
-
- it('forwards this desktop as both the route and local capability hint', async () => {
- mockEnv.isDesktop = true;
- mockRuntime.isLocal = true;
- mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-1' });
-
- await send();
-
- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({
- deviceId: 'device-local-1',
- localDeviceId: 'device-local-1',
- }),
- );
- });
-
- // 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;
-
- await send();
-
- expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
- expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
- 'deviceId',
- );
- });
-
- // Regression guard (chat mode β†’ no execution environment): chat mode must
- // not resolve this machine's deviceId even on a local target, otherwise
- // the server presets activeDeviceId and re-injects lobe-local-system.
- it('does not resolve a deviceId in chat mode, even when local mode is set', async () => {
- mockEnv.isDesktop = true;
- mockRuntime.isLocal = true;
- mockRuntime.isChatMode = true;
-
- await send();
-
- expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
- expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
- 'deviceId',
- );
- });
-
- it('never resolves a deviceId off desktop, even when local mode is set', async () => {
- mockEnv.isDesktop = false;
- mockRuntime.isLocal = true;
-
- await send();
-
- expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
- expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
- 'deviceId',
- );
- });
-
- it('uses a workspace member local override instead of the shared remote device', async () => {
- mockEnv.isDesktop = true;
- mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-member' });
- mockAgentStore.state.agentMap['agent-1'] = {
- agencyConfig: { boundDeviceId: 'workspace-device', executionTarget: 'device' },
- userId: 'workspace-owner',
- visibility: 'public',
- workspaceId: 'workspace-1',
- };
- mockUserState.workspaceUserPreference.agentDeviceOverrides['agent-1'] = {
- boundDeviceId: 'device-local-member',
- executionTarget: 'local',
- };
-
- await send();
-
- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ deviceId: 'device-local-member' }),
- );
- });
-
- it('does not preset this desktop for a workspace member remote override', async () => {
- mockEnv.isDesktop = true;
- mockAgentStore.state.agentMap['agent-1'] = {
- agencyConfig: { executionTarget: 'local' },
- userId: 'workspace-owner',
- visibility: 'public',
- workspaceId: 'workspace-1',
- };
- mockUserState.workspaceUserPreference.agentDeviceOverrides['agent-1'] = {
- boundDeviceId: 'remote-device',
- executionTarget: 'device',
- };
-
- await send();
-
- expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
- expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
- 'deviceId',
- );
- });
-
- it('sends a distinct local device hint for a local platform agent', async () => {
- mockEnv.isDesktop = true;
- mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });
- mockAgentStore.state.agentMap['agent-1'] = {
- agencyConfig: {
- executionTarget: 'local',
- heterogeneousProvider: { type: 'openclaw' },
- },
- userId: 'user-1',
- };
-
- await send();
-
- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ localDeviceId: 'this-desktop' }),
- );
- expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
- 'deviceId',
- );
- });
-
- it('sends a harmless desktop hint without overriding a remote platform target', async () => {
- mockEnv.isDesktop = true;
- mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });
- mockAgentStore.state.agentMap['agent-1'] = {
- agencyConfig: {
- boundDeviceId: 'remote-device',
- executionTarget: 'device',
- heterogeneousProvider: { type: 'hermes' },
- },
- userId: 'user-1',
- };
-
- await send();
-
- expect(mockGateway.getDeviceInfo).toHaveBeenCalled();
- const request = vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0];
- expect(request).not.toHaveProperty('deviceId');
- expect(request).toHaveProperty('localDeviceId', 'this-desktop');
- });
- });
});
describe('reconnectToGatewayOperation', () => {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index 7bdb377afe8..5340a8817fb 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -419,10 +419,9 @@ export class ConversationLifecycleActionImpl {
const deviceOverride = agent?.workspaceId
? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
: undefined;
- // Runtime selection must use the same per-user device override as the
- // switcher. A workspace-local pick is intentionally private to this member
- // and is therefore safe to execute in-process on their desktop. An existing
- // conversation then stays on the machine it already ran on.
+ // Runtime selection uses the switcher's per-user device override (a private
+ // workspace-local pick is safe to run in-process on this member's desktop);
+ // an existing conversation then stays on the machine it already ran on.
const topicBinding = applyTopicDeviceBinding(
{
agencyConfig: resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {
@@ -437,6 +436,7 @@ export class ConversationLifecycleActionImpl {
agentId,
),
getElectronStoreState().gatewayDeviceInfo?.deviceId,
+ { isHetero: isHeterogeneousAgentModelId(agentConfig?.model) },
);
const { workspaceScoped } = topicBinding;
let { agencyConfig } = topicBinding;
diff --git a/src/store/chat/slices/agentRun/actions/entries/gatewayResume.ts b/src/store/chat/slices/agentRun/actions/entries/gatewayResume.ts
index f02e8ca53e8..f7f470ad79b 100644
--- a/src/store/chat/slices/agentRun/actions/entries/gatewayResume.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/gatewayResume.ts
@@ -91,6 +91,7 @@ export const shouldUseConfiguredGatewayResume = async (
agentId,
),
getElectronStoreState().gatewayDeviceInfo?.deviceId,
+ { isHetero: isHeterogeneousAgentModelId(agentConfig?.model) },
);
const isGatewayMode = get().isGatewayModeEnabled(agentId);
const heterogeneousProvider =
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
index cdd54735422..f83c988d58c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
@@ -1,3 +1,4 @@
+import { isHeterogeneousAgentModelId } from '@lobechat/const';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
ChatTopic,
@@ -66,6 +67,16 @@ export const resolveDesktopDeviceHints = async (
if (chatConfigByIdSelectors.isChatModeById(agentId)(agentState)) return {};
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
+ // Legacy agents may be identified only by `model: '<cli-type>'` (no stored
+ // provider yet) and the server still routes those to the external-CLI path. A
+ // provider-only discriminator would let the `auto` default below swallow this
+ // desktop's device hints, sending the run to the cloud sandbox instead.
+ const isModelOnlyHetero = isHeterogeneousAgentModelId(
+ agentByIdSelectors.getAgentModelById(agentId)(agentState),
+ );
+ const isHetero =
+ isModelOnlyHetero ||
+ !!agentByIdSelectors.getAgencyConfigById(agentId)(agentState)?.heterogeneousProvider;
const userState = useUserStore.getState();
const currentUserId = userProfileSelectors.userId(userState);
// Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
@@ -111,11 +122,14 @@ export const resolveDesktopDeviceHints = async (
},
getTopicBoundDeviceId(topic, agentId),
getElectronStoreState().gatewayDeviceInfo?.deviceId,
+ { isHetero },
);
const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');
const executionTarget = resolveExecutionTarget(agencyConfig, {
clientExecutionAvailable: true,
- isHetero: !!agencyConfig?.heterogeneousProvider,
+ // this request goes through the device-gateway
+ deviceRoutingAvailable: true,
+ isHetero,
workspaceScoped,
});
// Platform hints are capability claims, not routing overrides. Always send