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.

πŸ› fix(agent): stop chat mode from auto-injecting local-system tools (#15981)

Arvin Xu5e2fdeb342ff
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index 46196452a3d..75a5cd51892 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -28,7 +28,11 @@ import { ToolsEngine } from '@lobechat/context-engine';
import { type RuntimeEnvMode, type RuntimePlatform } from '@lobechat/types';
import debug from 'debug';
-import { executionTargetToRuntimeMode, resolveExecutionTarget } from '@/helpers/executionTarget';
+import {
+ executionTargetToRuntimeMode,
+ resolveExecutionTarget,
+ resolveToolMode,
+} from '@/helpers/executionTarget';
import {
buildAllowedBuiltinTools,
DEVICE_TOOL_IDENTIFIERS,
@@ -170,9 +174,7 @@ export const createServerAgentToolsEngine = (
const isSearchEnabled = searchMode !== 'off';
// Tool mode: explicit `toolMode` wins; otherwise derive from `enableAgentMode`
// (undefined = agent). `custom` = toolset is exactly the agent's plugins.
- const toolMode: 'agent' | 'chat' | 'custom' =
- agentConfig.chatConfig?.toolMode ??
- (agentConfig.chatConfig?.enableAgentMode === false ? 'chat' : 'agent');
+ const toolMode = resolveToolMode(agentConfig.chatConfig ?? undefined);
const isChatMode = toolMode === 'chat';
const isCustomMode = toolMode === 'custom';
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 0d564b57cb1..44e6b9a56de 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1898,9 +1898,17 @@ 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.
+ //
+ // Chat mode is orthogonal to `executionTarget` (the UI toggle only writes
+ // `enableAgentMode`), so a default/stored `local` target would otherwise
+ // resolve a device and `buildStepToolDelta` would re-inject local-system.
+ // Pass `chatConfig` so the plan degrades to `none` in chat mode β€” the
+ // chat-mode derivation lives in `resolveExecutionPlan` (`resolveToolMode`),
+ // the same source of truth the tools engine uses.
executionPlan = resolveExecutionPlan({
agencyConfig: agentConfig.agencyConfig,
canUseDevice,
+ chatConfig: agentConfig.chatConfig ?? undefined,
isDesktop: gatewayConfigured,
onlineDeviceIds: onlineDevices.map((device) => device.deviceId),
requestedDeviceId,
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 0c23304eb50..e79177e0597 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -258,6 +258,72 @@ describe('resolveExecutionPlan', () => {
});
});
+ describe('chat mode β€” no execution environment, even on a local target', () => {
+ it('degrades every device-capable target to none despite an online device', () => {
+ // regression: chat mode only removes local-system from the rule-layer
+ // whitelist; the device track resolved an `activeDeviceId` from the
+ // default/stored `local` target and `buildStepToolDelta` re-injected
+ // local-system. The plan now honours chat mode at the source.
+ for (const executionTarget of ['local', 'device'] as const) {
+ // both ways of expressing chat mode degrade the plan
+ for (const chatConfig of [{ enableAgentMode: false }, { toolMode: 'chat' as const }]) {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget }),
+ chatConfig,
+ isDesktop: true,
+ onlineDeviceIds: ONLINE_A,
+ }),
+ ).toEqual({ kind: 'none', target: 'none' });
+ }
+ }
+ });
+
+ it('degrades the unset desktop default (local) and sandbox to none', () => {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: undefined,
+ chatConfig: { enableAgentMode: false },
+ isDesktop: true,
+ onlineDeviceIds: ONLINE_A,
+ }),
+ ).toEqual({ kind: 'none', target: 'none' });
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ executionTarget: 'sandbox' }),
+ chatConfig: { enableAgentMode: false },
+ isDesktop: true,
+ onlineDeviceIds: ONLINE_A,
+ }),
+ ).toEqual({ kind: 'none', target: 'none' });
+ });
+
+ it('does not degrade agent mode (toolMode wins over enableAgentMode)', () => {
+ // explicit toolMode='agent' must keep device routing even if
+ // enableAgentMode is somehow false
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ executionTarget: 'local' }),
+ chatConfig: { enableAgentMode: false, toolMode: 'agent' },
+ isDesktop: true,
+ onlineDeviceIds: ONLINE_A,
+ }),
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'local' });
+ });
+
+ it('ignores chat mode for hetero agents (they always need a runtime)', () => {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'device' }),
+ chatConfig: { enableAgentMode: false },
+ isDesktop: false,
+ isHetero: true,
+ onlineDeviceIds: ONLINE_A,
+ }),
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });
+ });
+ });
+
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
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index a117ccaa538..67f941fac79 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -1,4 +1,22 @@
-import type { DeviceExecutionTarget, LobeAgentAgencyConfig, RuntimeEnvMode } from '@lobechat/types';
+import type {
+ DeviceExecutionTarget,
+ LobeAgentAgencyConfig,
+ LobeAgentChatConfig,
+ RuntimeEnvMode,
+} from '@lobechat/types';
+
+/**
+ * The agent's tool mode β€” explicit `chatConfig.toolMode` wins; otherwise derive
+ * from `enableAgentMode` (undefined = agent). `chat` = no execution
+ * environment (plain chat); `custom` = toolset is exactly the agent's plugins.
+ *
+ * Single source of truth so client (selectors), server tools engine, and
+ * `resolveExecutionPlan` all agree on what counts as chat mode.
+ */
+export const resolveToolMode = (
+ chatConfig: LobeAgentChatConfig | undefined,
+): 'agent' | 'chat' | 'custom' =>
+ chatConfig?.toolMode ?? (chatConfig?.enableAgentMode === false ? 'chat' : 'agent');
export interface ResolveExecutionTargetOptions {
/**
@@ -129,6 +147,16 @@ export interface ResolveExecutionPlanParams {
* Defaults to `true` (first-party callers).
*/
canUseDevice?: boolean;
+ /**
+ * The agent's chat config. Chat mode (`resolveToolMode` β†’ `chat`) means "no
+ * execution environment" β€” plain chat. It is orthogonal to `executionTarget`:
+ * the UI toggle only writes `enableAgentMode` and never touches the target, so
+ * a stored/default `local` target would otherwise still resolve a device and
+ * `buildStepToolDelta` would re-inject local-system. The plan honours chat
+ * mode at the source (degraded to `none`) β€” except for hetero agents, which
+ * always need a runtime.
+ */
+ chatConfig?: LobeAgentChatConfig;
isDesktop: boolean;
isHetero?: boolean;
/**
@@ -165,12 +193,20 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
const {
agencyConfig,
canUseDevice = true,
+ chatConfig,
isDesktop,
isHetero,
onlineDeviceIds,
requestedDeviceId,
} = params;
+ // Chat mode = no execution environment (plain chat). It's orthogonal to the
+ // execution target, so collapse the whole plan to `none` here β€” this is the
+ // single point that stops a default/stored `local` target from resolving a
+ // device and letting `buildStepToolDelta` re-inject local-system. Hetero
+ // 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, { isDesktop, isHetero });
const wantsDevice = !!requestedDeviceId || target === 'device' || target === 'local';
diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.ts b/src/store/agent/selectors/chatConfigByIdSelectors.ts
index b6f0db83db8..e11069532f1 100644
--- a/src/store/agent/selectors/chatConfigByIdSelectors.ts
+++ b/src/store/agent/selectors/chatConfigByIdSelectors.ts
@@ -5,7 +5,7 @@ import {
} from '@lobechat/const';
import { type LobeAgentChatConfig, type RuntimeEnvMode } from '@lobechat/types';
-import { resolveRuntimeMode } from '@/helpers/executionTarget';
+import { resolveRuntimeMode, resolveToolMode } from '@/helpers/executionTarget';
import { type AgentStoreState } from '@/store/agent/initialState';
import { agentSelectors } from './selectors';
@@ -81,6 +81,18 @@ const getSkillActivateModeById =
(s: AgentStoreState): 'auto' | 'manual' =>
getChatConfigById(agentId)(s).skillActivateMode ?? 'auto';
+/**
+ * Resolve the agent's tool mode via the shared `resolveToolMode` helper, so
+ * client and server agree on what counts as chat mode.
+ */
+const getToolModeById =
+ (agentId: string) =>
+ (s: AgentStoreState): 'agent' | 'chat' | 'custom' =>
+ resolveToolMode(getChatConfigById(agentId)(s));
+
+const isChatModeById = (agentId: string) => (s: AgentStoreState) =>
+ getToolModeById(agentId)(s) === 'chat';
+
export const chatConfigByIdSelectors = {
getChatConfigById,
getEnableHistoryCountById,
@@ -92,7 +104,9 @@ export const chatConfigByIdSelectors = {
getSearchFCModelById,
getSearchModeById,
getSkillActivateModeById,
+ getToolModeById,
getUseModelBuiltinSearchById,
+ isChatModeById,
isEnableSearchById,
isLocalSystemEnabledById,
isMemoryToolEnabledById,
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
index 63ae360e244..675d4f7c883 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -51,8 +51,9 @@ vi.mock('@/store/user/selectors', () => ({
// 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).
-const mockRuntime = vi.hoisted(() => ({ isLocal: false }));
+// 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,
}));
@@ -78,6 +79,7 @@ vi.mock('@/store/agent/selectors', () => ({
chatConfigByIdSelectors: {
getChatConfigById: (agentId: string) => (state: any) =>
state.agentMap?.[agentId]?.chatConfig ?? {},
+ isChatModeById: () => () => mockRuntime.isChatMode,
isLocalSystemEnabledById: () => () => mockRuntime.isLocal,
},
}));
@@ -884,6 +886,7 @@ describe('GatewayActionImpl', () => {
afterEach(() => {
mockEnv.isDesktop = false;
mockRuntime.isLocal = false;
+ mockRuntime.isChatMode = false;
mockGateway.getDeviceInfo.mockReset();
});
@@ -924,6 +927,23 @@ describe('GatewayActionImpl', () => {
);
});
+ // 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(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: undefined }),
+ expect.anything(),
+ );
+ });
+
it('never resolves a deviceId off desktop, even when local mode is set', async () => {
mockEnv.isDesktop = false;
mockRuntime.isLocal = true;
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 15fbc8292a5..7d5d925c3ff 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -42,7 +42,14 @@ import { createGatewayEventHandler } from './gatewayEventHandler';
const resolveLocalDeviceId = async (agentId?: string): Promise<string | undefined> => {
if (!isDesktop || !agentId) return undefined;
- const isLocal = chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(getAgentStoreState());
+ const agentState = getAgentStoreState();
+ // Chat mode means "no execution environment" β€” never resolve a device, even
+ // when the target is `local`. The server enforces this too (it auto-activates
+ // a single online device), but skipping the deviceId round-trip here avoids
+ // sending an id the server would only discard.
+ if (chatConfigByIdSelectors.isChatModeById(agentId)(agentState)) return undefined;
+
+ const isLocal = chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(agentState);
if (!isLocal) return undefined;
try {