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): web execution-target display + workingDirectory leak (#16869)

YuTengjing696cd4f727b5
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
index dddddcd6d54..905cf83a094 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
@@ -70,6 +70,35 @@ describe('serverMessagesEngine', () => {
expect(result[0].content).toBe(systemRole + '\n\n' + getCurrentDateContent());
});
+ it('renders {{workingDirectory}} to a fallback instead of leaking the literal (LOBE-11473)', async () => {
+ const messages = createBasicMessages();
+ const systemRole = '<working-directory>{{workingDirectory}}</working-directory>';
+
+ // No additionalVariables β€” e.g. a web-originated device run whose bound cwd
+ // could not be resolved. The literal must never survive into the prompt.
+ const fallback = await serverMessagesEngine({
+ messages,
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole,
+ });
+ expect(fallback[0].content).not.toContain('{{workingDirectory}}');
+ expect(fallback[0].content).toContain('(not specified, use user Home directory as default)');
+
+ // A resolved cwd (deviceSystemInfo.workingDirectory) overrides the fallback.
+ const resolved = await serverMessagesEngine({
+ additionalVariables: { workingDirectory: '/Users/tj/project' },
+ messages,
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole,
+ });
+ expect(resolved[0].content).toContain(
+ '<working-directory>/Users/tj/project</working-directory>',
+ );
+ expect(resolved[0].content).not.toContain('(not specified');
+ });
+
it('should inject model knowledge cutoff when provided', async () => {
const messages = createBasicMessages();
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
index 63fa103943d..3248421ce0e 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
@@ -24,6 +24,14 @@ const createServerVariableGenerators = (params: {
// Model-related variables
model: () => model ?? '',
provider: () => provider ?? '',
+ // Working directory fallback. Unlike the client generator, the server has no
+ // store to resolve cwd from β€” the real value arrives via `additionalVariables`
+ // (`deviceSystemInfo.workingDirectory`, only set when a device-run's bound cwd
+ // resolves) and overrides this through the spread order below. Without this
+ // fallback, a device-run whose cwd can't be resolved (e.g. a web-originated
+ // session with no bound directory) leaves `{{workingDirectory}}` unmatched and
+ // leaks the literal into the local-system system prompt (LOBE-11473).
+ workingDirectory: () => '(not specified, use user Home directory as default)',
};
};
diff --git a/src/features/AgentDocumentPage/RightPanel/index.tsx b/src/features/AgentDocumentPage/RightPanel/index.tsx
index 55733b71d30..8568b0563ed 100644
--- a/src/features/AgentDocumentPage/RightPanel/index.tsx
+++ b/src/features/AgentDocumentPage/RightPanel/index.tsx
@@ -12,6 +12,7 @@ import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { isDesktop } from '@/const/version';
import RightPanel from '@/features/RightPanel';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useClientDataSWR } from '@/libs/swr';
import AgentDocumentsGroup from '@/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup';
@@ -81,9 +82,11 @@ const AgentDocumentRightPanel = memo(() => {
const agencyConfig = useAgentStore((s) =>
activeAgentId ? agentByIdSelectors.getAgencyConfigById(activeAgentId)(s) : undefined,
);
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(activeAgentId);
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
- isHetero,
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
});
const remoteDeviceId =
effectiveTarget === 'device' && agencyConfig?.boundDeviceId
diff --git a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
index 1eb7d3b7871..ad0476793cf 100644
--- a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
+++ b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
@@ -71,6 +71,7 @@ vi.mock('antd-style', () => ({
vi.mock('lucide-react', () => ({
ChevronsUpDownIcon: () => <span data-testid="chevron" />,
+ Circle: () => <span data-testid="circle" />,
}));
vi.mock('react-i18next', () => ({
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 77b1109a588..b70172b9ee2 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -26,6 +26,7 @@ import { useTranslation } from 'react-i18next';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { lambdaQuery } from '@/libs/trpc/client';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -371,9 +372,11 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// 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 deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
const executionTarget = resolveExecutionTarget(agencyConfig, {
- isHetero,
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
});
const selectExecutionTarget = useSelectExecutionTarget(agentId);
diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
index 2c9f514d8b5..8d096cfb5e3 100644
--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
@@ -4,6 +4,7 @@ import { isDesktop } from '@lobechat/const';
import { memo } from 'react';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
@@ -36,9 +37,11 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(
const runtimeMode = useAgentStore(chatConfigByIdSelectors.getRuntimeModeById(agentId));
const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
- isHetero: isHeterogeneous,
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero: isHeterogeneous,
});
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
index dc9c50c84f2..c1a3d45738f 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
@@ -10,6 +10,7 @@ import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useFetchProjectSkills } from '@/hooks/useFetchProjectSkills';
import { useAgentStore } from '@/store/agent';
@@ -69,9 +70,11 @@ export const useSlashActionItems = (): SlashOptions['items'] => {
const isHetero = useAgentStore((s) =>
agentId ? agentByIdSelectors.isAgentHeterogeneousById(agentId)(s) : false,
);
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
- isHetero,
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
});
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
const remoteDeviceId = isDeviceMode ? agencyConfig.boundDeviceId : undefined;
diff --git a/src/features/SkillsList/useProjectSkillResolver.ts b/src/features/SkillsList/useProjectSkillResolver.ts
index e26c678ed50..147a194f1b9 100644
--- a/src/features/SkillsList/useProjectSkillResolver.ts
+++ b/src/features/SkillsList/useProjectSkillResolver.ts
@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';
import { useCallback } from 'react';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -48,8 +49,10 @@ export const useProjectSkillResolver = (
const isHetero = useAgentStore((s) =>
agentId ? agentByIdSelectors.isAgentHeterogeneousById(agentId)(s) : false,
);
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
isHetero,
});
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 178e415ef3b..5443cf86a95 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -46,7 +46,12 @@ describe('resolveExecutionTarget', () => {
).toBe('local');
});
- it('routes hetero desktop-local bindings to the bound device on web', () => {
+ it('routes a bound desktop-local selection to the bound device on web when device routing is available (plain and hetero)', () => {
+ // LOBE-11473: a `local` pick pins this desktop's own deviceId as
+ // `boundDeviceId`; on web that config still runs on the bound device
+ // server-side, so surface it honestly as `device` instead of masquerading
+ // as `sandbox`. Hetero agents always route here; plain agents need a
+ // device-gateway (`deviceRoutingAvailable`) to actually reach the machine.
expect(
resolveExecutionTarget(cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }), {
clientExecutionAvailable: false,
@@ -54,6 +59,20 @@ describe('resolveExecutionTarget', () => {
}),
).toBe('device');
+ expect(
+ resolveExecutionTarget(cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }), {
+ clientExecutionAvailable: false,
+ deviceRoutingAvailable: true,
+ }),
+ ).toBe('device');
+ });
+
+ it('keeps a bound `local` as `sandbox` when no device routing is available (LOBE-11473 regression)', () => {
+ // A plain agent with a bound `local` target but no device-gateway to route
+ // it (self-host without DEVICE_GATEWAY_URL, or any server call that leaves
+ // `deviceRoutingAvailable` unset) must fall back to the cloud sandbox β€” it
+ // cannot reach the bound device. Guards against resolving to
+ // `device`/`device-unrouted` and stripping sandbox tools server-side.
expect(
resolveExecutionTarget(cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }), {
clientExecutionAvailable: false,
@@ -192,6 +211,14 @@ describe('resolveRuntimeMode', () => {
// executionTarget=local synced from desktop, resolved on web β†’ sandbox β†’ cloud
expect(resolveRuntimeMode(cfg({ executionTarget: 'local' }), false)).toBe('cloud');
});
+
+ it('routes a bound web `local` to device (runtimeMode none) only when device routing is available', () => {
+ const boundLocal = cfg({ boundDeviceId: 'device-a', executionTarget: 'local' });
+ // with a device-gateway β†’ device β†’ runtimeMode none (routed via the plan)
+ expect(resolveRuntimeMode(boundLocal, false, true)).toBe('none');
+ // without one β†’ sandbox β†’ cloud (LOBE-11473 regression guard)
+ expect(resolveRuntimeMode(boundLocal, false)).toBe('cloud');
+ });
});
describe('resolveExecutionPlan', () => {
@@ -230,6 +257,20 @@ describe('resolveExecutionPlan', () => {
).toEqual({ kind: 'sandbox', target: 'sandbox' });
});
+ it('keeps a bound `local` as sandbox on a no-gateway backend (LOBE-11473 regression)', () => {
+ // No device-gateway: `clientExecutionAvailable` is false and the plan
+ // never passes `deviceRoutingAvailable`, so a bound `local` target must
+ // resolve to the sandbox β€” not `device`/`device-unrouted`, which would
+ // strip cloud-sandbox tools on a self-host without device routing.
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({ boundDeviceId: 'device-a', executionTarget: 'local' }),
+ clientExecutionAvailable: false,
+ onlineDeviceIds: [],
+ }),
+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });
+ });
+
it('survives canUseDevice=false β€” the sandbox never touches user machines', () => {
expect(
resolveExecutionPlan({
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 749d9fb2ecb..24066e31654 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -40,6 +40,26 @@ export interface ResolveExecutionTargetOptions {
* this is false.
*/
clientExecutionAvailable: boolean;
+ /**
+ * Whether a device-gateway can route the run to a registered device in this
+ * environment. Orthogonal to {@link clientExecutionAvailable} (in-process
+ * `local` capability): the two coincide on a server (both equal
+ * `gatewayConfigured`), but split on the web client β€” the browser can't run
+ * `local` in-process (`clientExecutionAvailable` false) yet its backend may
+ * still have a device-gateway that routes to a `lh connect`-ed machine
+ * (`deviceRoutingAvailable` true).
+ *
+ * Gates ONLY the web-display upgrade of a bound `local` target to `device`
+ * (see `resolveExecutionTarget`). Server execution never relies on it: with a
+ * gateway `clientExecutionAvailable` is already true (branch skipped, `local`
+ * routes to a device via `resolveExecutionPlan`); without one the target must
+ * stay `sandbox`. So server callers leave it `undefined` (false) and the
+ * branch is a no-op there β€” only web display sites pass
+ * `!!serverConfig.agentGatewayUrl` to keep the honest device display
+ * (LOBE-11473). `isHetero` also satisfies the gate: a hetero agent's bound
+ * `local` was always surfaced as `device` on web regardless of gateway state.
+ */
+ deviceRoutingAvailable?: boolean;
/**
* Heterogeneous agents (Claude Code / Codex) bring their own toolchain and
* must execute somewhere, so `'none'` is not a valid target for them: it
@@ -76,10 +96,22 @@ export interface ResolveExecutionTargetOptions {
* `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) 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`.
+ * (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
+ * to `device`, surfacing honestly that it runs on the user's machine (via
+ * `lh connect`) instead of masquerading as `sandbox`. This applies to plain
+ * agents too, not just heterogeneous CLI agents (LOBE-11473: plain agents used
+ * to leak here, showing "cloud sandbox" while the server ran on the device).
+ *
+ * This upgrade is gated on `deviceRoutingAvailable` (or `isHetero`): the run
+ * can only reach the bound device if a device-gateway exists to route it. Web
+ * display sites pass `!!serverConfig.agentGatewayUrl` (cloud always has one);
+ * a no-gateway self-host has no route, so its bound `local` stays `sandbox`.
+ * An UNBOUND `local` (no `boundDeviceId`) always falls back to `sandbox` on web.
+ * Server callers leave `deviceRoutingAvailable` unset β€” with a gateway they
+ * already pass `clientExecutionAvailable: true` and skip this branch, so it is
+ * inert server-side and never diverts a no-gateway run away from `sandbox`.
*
* Bot triggers (`trigger === bot`) upgrade a `local` target (a bot has no UI
* to pick a device and `local` in-process IPC is unreachable from the cloud
@@ -89,11 +121,21 @@ export interface ResolveExecutionTargetOptions {
*/
export const resolveExecutionTarget = (
agencyConfig: LobeAgentAgencyConfig | undefined,
- { clientExecutionAvailable, isHetero, trigger }: ResolveExecutionTargetOptions,
+ {
+ clientExecutionAvailable,
+ deviceRoutingAvailable,
+ isHetero,
+ trigger,
+ }: ResolveExecutionTargetOptions,
): DeviceExecutionTarget => {
const stored = agencyConfig?.executionTarget;
let effective = stored ?? (clientExecutionAvailable ? 'local' : 'none');
- if (isHetero && !clientExecutionAvailable && stored === 'local' && agencyConfig?.boundDeviceId) {
+ if (
+ !clientExecutionAvailable &&
+ (isHetero || deviceRoutingAvailable) &&
+ stored === 'local' &&
+ agencyConfig?.boundDeviceId
+ ) {
return 'device';
}
if (isHetero && effective === 'none') effective = clientExecutionAvailable ? 'local' : 'sandbox';
@@ -140,8 +182,11 @@ export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): Run
export const resolveRuntimeMode = (
agencyConfig: LobeAgentAgencyConfig | undefined,
clientExecutionAvailable: boolean,
+ deviceRoutingAvailable?: boolean,
): RuntimeEnvMode =>
- executionTargetToRuntimeMode(resolveExecutionTarget(agencyConfig, { clientExecutionAvailable }));
+ executionTargetToRuntimeMode(
+ resolveExecutionTarget(agencyConfig, { clientExecutionAvailable, deviceRoutingAvailable }),
+ );
export type ExecutionPlanUnroutedReason =
/** `auto` mode with more than one device online β€” the model must pick one */
diff --git a/src/helpers/gatewayMode.test.ts b/src/helpers/gatewayMode.test.ts
new file mode 100644
index 00000000000..3ecb4e1afb1
--- /dev/null
+++ b/src/helpers/gatewayMode.test.ts
@@ -0,0 +1,77 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentStore } from '@/store/agent';
+import { type AgentStoreState } from '@/store/agent/initialState';
+import * as serverConfigStore from '@/store/serverConfig';
+
+import { resolveGatewayModeEnabled, useIsGatewayModeEnabled } from './gatewayMode';
+
+const mockServerConfig = (serverConfig?: {
+ agentGatewayUrl?: string;
+ enableGatewayMode?: boolean;
+}) =>
+ vi
+ .spyOn(serverConfigStore, 'getServerConfigStoreState')
+ .mockReturnValue({ serverConfig } as ReturnType<
+ typeof serverConfigStore.getServerConfigStoreState
+ >);
+
+const stateWith = (disableGatewayMode?: boolean): AgentStoreState =>
+ ({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { chatConfig: { disableGatewayMode } } },
+ }) as unknown as AgentStoreState;
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('resolveGatewayModeEnabled', () => {
+ it('is enabled when the gateway URL + enableGatewayMode are set and the agent has not opted out', () => {
+ mockServerConfig({ agentGatewayUrl: 'wss://gw', enableGatewayMode: true });
+
+ expect(resolveGatewayModeEnabled(stateWith(false), 'agent-1')).toBe(true);
+ // `disableGatewayMode: undefined` counts as enabled.
+ expect(resolveGatewayModeEnabled(stateWith(undefined), 'agent-1')).toBe(true);
+ });
+
+ it('is disabled when the deployment has no gateway URL', () => {
+ mockServerConfig(undefined);
+
+ expect(resolveGatewayModeEnabled(stateWith(false), 'agent-1')).toBe(false);
+ });
+
+ it('is disabled when Gateway mode is off even with a gateway URL', () => {
+ mockServerConfig({ agentGatewayUrl: 'wss://gw', enableGatewayMode: false });
+
+ expect(resolveGatewayModeEnabled(stateWith(false), 'agent-1')).toBe(false);
+ });
+
+ it('is disabled when the agent opts out via disableGatewayMode', () => {
+ mockServerConfig({ agentGatewayUrl: 'wss://gw', enableGatewayMode: true });
+
+ expect(resolveGatewayModeEnabled(stateWith(true), 'agent-1')).toBe(false);
+ });
+});
+
+describe('useIsGatewayModeEnabled', () => {
+ it('re-computes when the agent toggles disableGatewayMode (reactivity, LOBE-11473)', () => {
+ mockServerConfig({ agentGatewayUrl: 'wss://gw', enableGatewayMode: true });
+ useAgentStore.setState(stateWith(false));
+
+ const { result } = renderHook(() => useIsGatewayModeEnabled('agent-1'));
+ expect(result.current).toBe(true);
+
+ // Toggling Gateway Mode from the chat ActionBar mutates chatConfig only; the
+ // hook must still re-render off its own subscription (the display sites
+ // subscribe to agencyConfig, a sibling slice, so they would otherwise stay
+ // stale after sends fall back to sandbox).
+ act(() => {
+ useAgentStore.setState({
+ agentMap: { 'agent-1': { chatConfig: { disableGatewayMode: true } } },
+ } as Partial<AgentStoreState>);
+ });
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/src/helpers/gatewayMode.ts b/src/helpers/gatewayMode.ts
new file mode 100644
index 00000000000..91558c77508
--- /dev/null
+++ b/src/helpers/gatewayMode.ts
@@ -0,0 +1,98 @@
+import { useAgentStore } from '@/store/agent';
+import { type AgentStoreState } from '@/store/agent/initialState';
+import { agentSelectors } from '@/store/agent/selectors';
+import { getServerConfigStoreState } from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+
+/**
+ * Whether Gateway mode is EFFECTIVELY enabled for a run β€” the predicate every
+ * execution-target DISPLAY site shares so the picker/sidebar never surface a
+ * `device` target the runtime can't actually reach.
+ *
+ * A configured `agentGatewayUrl` alone is NOT enough: the deployment must also
+ * turn Gateway mode on (`enableGatewayMode`) and the agent (or the user's
+ * default agent config) must not opt out via `disableGatewayMode`. When any of
+ * these is false, sends fall back to the non-gateway client path, so a bound
+ * `local` target cannot actually reach the device β€” the display must keep it as
+ * `sandbox` rather than surfacing `device` (LOBE-11473 follow-up).
+ *
+ * This intentionally mirrors dispatch's own gate,
+ * `GatewayActionImpl.isGatewayModeEnabled` in the gateway transport
+ * (`store/chat/.../gateway/gateway.ts`) β€” keep the two in sync.
+ *
+ * `serverConfig` is read non-reactively: `agentGatewayUrl` / `enableGatewayMode`
+ * are deployment-static app config, loaded once at hydration and never mutated
+ * at runtime, so no store subscribes to them (and the display sites'
+ * component tests deliberately run without the serverConfig context Provider).
+ * `disableGatewayMode`, by contrast, is user-toggleable at runtime (the chat
+ * ActionBar / advanced settings), so the reactive `useIsGatewayModeEnabled`
+ * hook subscribes to it β€” see that hook's note.
+ */
+const evaluateGatewayModeEnabled = (disableGatewayMode: boolean | undefined): boolean => {
+ const serverConfig = getServerConfigStoreState()?.serverConfig;
+
+ return (
+ !!serverConfig?.agentGatewayUrl &&
+ !!serverConfig.enableGatewayMode &&
+ disableGatewayMode !== true
+ );
+};
+
+/**
+ * Resolve the effective `disableGatewayMode` opt-out from an agent state: the
+ * agent's own `chatConfig.disableGatewayMode`, falling back to the user's
+ * default agent config. `disableGatewayMode: undefined` = enabled.
+ */
+const resolveDisableGatewayMode = (
+ agentState: AgentStoreState,
+ resolvedAgentId: string | undefined,
+): boolean | undefined => {
+ const agentDisableGatewayMode = resolvedAgentId
+ ? agentSelectors.getAgentConfigById(resolvedAgentId)(agentState)?.chatConfig?.disableGatewayMode
+ : undefined;
+ const defaultDisableGatewayMode = settingsSelectors.defaultAgentConfig(useUserStore.getState())
+ .chatConfig?.disableGatewayMode;
+
+ return agentDisableGatewayMode ?? defaultDisableGatewayMode;
+};
+
+/**
+ * Selector-friendly, non-reactive variant: derives the gate from an agent store
+ * state the caller already holds (e.g. a zustand selector's `s`). It re-runs
+ * whenever the enclosing `useAgentStore(selector)` re-evaluates on an agent
+ * store change, so it stays reactive to `disableGatewayMode` without a second
+ * global read.
+ */
+export const resolveGatewayModeEnabled = (
+ agentState: AgentStoreState,
+ agentId?: string,
+): boolean => {
+ const resolvedAgentId = agentId ?? agentState.activeAgentId;
+
+ return evaluateGatewayModeEnabled(resolveDisableGatewayMode(agentState, resolvedAgentId));
+};
+
+/**
+ * Reactive hook for render call sites (device switcher, workspace sidebar,
+ * resource/skill panels). Subscribes to the live-mutable `disableGatewayMode`
+ * (agent chatConfig + user default) so toggling Gateway Mode from the chat
+ * ActionBar re-renders the display and it stops surfacing a `device` target
+ * once sends have fallen back to sandbox (LOBE-11473 follow-up). `serverConfig`
+ * stays a non-reactive read β€” see `resolveGatewayModeEnabled`'s note.
+ */
+export const useIsGatewayModeEnabled = (agentId?: string): boolean => {
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const resolvedAgentId = agentId ?? activeAgentId;
+ const agentDisableGatewayMode = useAgentStore((s) =>
+ resolvedAgentId
+ ? agentSelectors.getAgentConfigById(resolvedAgentId)(s)?.chatConfig?.disableGatewayMode
+ : undefined,
+ );
+ const defaultDisableGatewayMode = useUserStore(
+ (s) => settingsSelectors.defaultAgentConfig(s).chatConfig?.disableGatewayMode,
+ );
+ const disableGatewayMode = agentDisableGatewayMode ?? defaultDisableGatewayMode;
+
+ return evaluateGatewayModeEnabled(disableGatewayMode);
+};
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index 0de9a661e78..90236a893f9 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -116,6 +116,7 @@ vi.mock('@/libs/router/navigation', () => ({
}));
vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => agentStoreStateMock,
useAgentStore: (selector: (state: { activeAgentId?: string }) => unknown) =>
selector(agentStoreStateMock),
}));
@@ -125,6 +126,9 @@ vi.mock('@/store/agent/selectors', () => ({
getAgencyConfigById: () => () => ({ boundDeviceId: 'device-1' }),
isAgentHeterogeneousById: () => () => true,
},
+ agentSelectors: {
+ getAgentConfigById: () => () => undefined,
+ },
}));
vi.mock('@/store/chat', () => {
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 cb685bb7730..bc821c7ad7e 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
@@ -18,6 +18,7 @@ import RingLoadingIcon from '@/components/RingLoading';
import { isDesktop } from '@/const/version';
import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
import { useAgentStore } from '@/store/agent';
@@ -255,9 +256,11 @@ const GroupItem = memo<GroupItemComponentProps>(
// 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 deviceRoutingAvailable = useIsGatewayModeEnabled(currentAgentId);
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
- isHetero: isHeterogeneous,
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero: isHeterogeneous,
});
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
const canAddTopic = (isDesktop || isDeviceMode) && !!workingDirectory;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index 80a5a9150bb..ffddd995c8c 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -33,10 +33,16 @@ vi.mock('../ProgressSection', () => ({ default: () => <div /> }));
vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));
vi.mock('../ParamsSection', () => ({ default: () => <div /> }));
-vi.mock('@/store/agent', () => ({ useAgentStore: () => undefined }));
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => ({ activeAgentId: undefined }),
+ useAgentStore: () => undefined,
+}));
vi.mock('@/store/agent/selectors', () => ({
agentByIdSelectors: {},
- agentSelectors: { isCurrentAgentHeterogeneous: () => false },
+ agentSelectors: {
+ getAgentConfigById: () => () => undefined,
+ isCurrentAgentHeterogeneous: () => false,
+ },
chatConfigByIdSelectors: {},
}));
vi.mock('@/store/global', () => ({ useGlobalStore: () => undefined }));
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index e82ec9a236b..d05f49bd735 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -10,6 +10,7 @@ import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';
import RightPanel from '@/features/RightPanel';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
import { useAgentStore } from '@/store/agent';
@@ -114,9 +115,11 @@ const AgentWorkingSidebar = memo(() => {
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const repoType = useRepoType(workingDirectory, targetDeviceId);
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(activeAgentId);
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
- isHetero,
clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
});
// Running against a bound device (remote, or this machine as a device): file
diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.ts b/src/store/agent/selectors/chatConfigByIdSelectors.ts
index e11069532f1..66583b2ff36 100644
--- a/src/store/agent/selectors/chatConfigByIdSelectors.ts
+++ b/src/store/agent/selectors/chatConfigByIdSelectors.ts
@@ -6,6 +6,7 @@ import {
import { type LobeAgentChatConfig, type RuntimeEnvMode } from '@lobechat/types';
import { resolveRuntimeMode, resolveToolMode } from '@/helpers/executionTarget';
+import { resolveGatewayModeEnabled } from '@/helpers/gatewayMode';
import { type AgentStoreState } from '@/store/agent/initialState';
import { agentSelectors } from './selectors';
@@ -73,7 +74,15 @@ const getRuntimeModeById =
(s: AgentStoreState): RuntimeEnvMode => {
const config = agentSelectors.getAgentConfigById(agentId)(s);
- return resolveRuntimeMode(config?.agencyConfig, isDesktop);
+ // On web a bound `local` target only surfaces as `device` (not `sandbox`)
+ // when Gateway mode is effectively enabled and can route to the device
+ // (LOBE-11473). Derive the gate from this selector's own state `s` so it
+ // re-evaluates on `disableGatewayMode` changes without a second global read.
+ return resolveRuntimeMode(
+ config?.agencyConfig,
+ isDesktop,
+ resolveGatewayModeEnabled(s, agentId),
+ );
};
const getSkillActivateModeById =