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(gateway): move gateway mode to chat config (#15714)

Arvin Xubc9a7cfab859
diff --git a/.env.example b/.env.example
index 39946ddc0e6..b2a69da1d72 100644
--- a/.env.example
+++ b/.env.example
@@ -445,6 +445,15 @@ OPENAI_API_KEY=sk-xxxxxxxxx
# MESSAGE_GATEWAY_URL=https://message-gateway.lobehub.com
# MESSAGE_GATEWAY_SERVICE_TOKEN=your_service_token_here
+# #######################################
+# ######### Agent Gateway Mode ##########
+# #######################################
+
+# Enable Gateway Mode for self-hosted deployments. Requires AGENT_GATEWAY_URL.
+# ENABLE_AGENT_GATEWAY=1
+# AGENT_GATEWAY_URL=https://agent-gateway.example.com
+# AGENT_GATEWAY_SERVICE_TOKEN=your_service_token_here
+
# #######################################
# ########### Messenger Bot #############
# #######################################
diff --git a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
index ab42cb99840..dcb28c8465e 100644
--- a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
+++ b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
@@ -15,7 +15,15 @@ const mocks = vi.hoisted(() => ({
),
}));
-const mockGlobalConfigDependencies = (enableBusinessFeatures: boolean) => {
+interface MockGlobalConfigOptions {
+ agentGatewayUrl?: string;
+ enableAgentGateway?: boolean;
+}
+
+const mockGlobalConfigDependencies = (
+ enableBusinessFeatures: boolean,
+ options: MockGlobalConfigOptions = {},
+) => {
vi.doMock('@lobechat/business-const', () => ({
ENABLE_BUSINESS_FEATURES: enableBusinessFeatures,
}));
@@ -29,7 +37,12 @@ const mockGlobalConfigDependencies = (enableBusinessFeatures: boolean) => {
}));
vi.doMock('@/envs/app', () => ({
- appEnv: {},
+ appEnv: {
+ ...(options.agentGatewayUrl ? { AGENT_GATEWAY_URL: options.agentGatewayUrl } : {}),
+ ...(options.enableAgentGateway === undefined
+ ? {}
+ : { ENABLE_AGENT_GATEWAY: options.enableAgentGateway }),
+ },
getAppConfig: vi.fn(() => ({
DEFAULT_AGENT_CONFIG: '',
})),
@@ -113,6 +126,18 @@ const loadCapturedProviderConfig = async (enableBusinessFeatures: boolean) => {
>;
};
+const loadServerConfig = async (
+ enableBusinessFeatures: boolean,
+ options?: MockGlobalConfigOptions,
+) => {
+ vi.resetModules();
+ mocks.genServerAiProvidersConfig.mockClear();
+ mockGlobalConfigDependencies(enableBusinessFeatures, options);
+
+ const { getServerGlobalConfig } = await import('./index');
+ return getServerGlobalConfig();
+};
+
describe('getServerGlobalConfig', () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -139,4 +164,36 @@ describe('getServerGlobalConfig', () => {
expect(providerConfig[ModelProvider.OpenAI]).toBeUndefined();
expect(providerConfig[ModelProvider.DeepSeek].enabled).toBe(true);
});
+
+ it('should enable gateway mode for business builds', async () => {
+ await expect(loadServerConfig(true)).resolves.toMatchObject({
+ enableGatewayMode: true,
+ });
+ });
+
+ it('should enable gateway mode for self-hosted builds only when explicitly enabled with a gateway url', async () => {
+ await expect(
+ loadServerConfig(false, {
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableAgentGateway: true,
+ }),
+ ).resolves.toMatchObject({
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableGatewayMode: true,
+ });
+
+ await expect(
+ loadServerConfig(false, {
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableAgentGateway: false,
+ }),
+ ).resolves.toMatchObject({
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableGatewayMode: false,
+ });
+
+ await expect(loadServerConfig(false, { enableAgentGateway: true })).resolves.toMatchObject({
+ enableGatewayMode: false,
+ });
+ });
});
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index 17df96cae26..34b71a83d18 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -104,6 +104,8 @@ export const getServerGlobalConfig = async () => {
disableEmailPassword: authEnv.AUTH_DISABLE_EMAIL_PASSWORD,
enableBusinessFeatures: ENABLE_BUSINESS_FEATURES,
enableEmailVerification: authEnv.AUTH_EMAIL_VERIFICATION,
+ enableGatewayMode:
+ ENABLE_BUSINESS_FEATURES || (!!appEnv.ENABLE_AGENT_GATEWAY && !!appEnv.AGENT_GATEWAY_URL),
enableKlavis: !!klavisEnv.KLAVIS_API_KEY,
enableLobehubSkill: !!(appEnv.MARKET_TRUSTED_CLIENT_SECRET && appEnv.MARKET_TRUSTED_CLIENT_ID),
enableMagicLink: authEnv.AUTH_ENABLE_MAGIC_LINK,
diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdx
index 264799414c9..0999d636bc8 100644
--- a/docs/self-hosting/environment-variables/basic.mdx
+++ b/docs/self-hosting/environment-variables/basic.mdx
@@ -1,9 +1,8 @@
---
title: Customize LobeHub Deployment with Environment Variables
description: >-
- Learn about the common environment variables used to customize LobeHub
- deployment, including access code, OAuth SSO, base path, and default agent
- configuration.
+ Learn about the common environment variables used to customize LobeHub deployment, including access code, OAuth SSO, base path, and default agent configuration.
+
tags:
- LobeHub
- environment variables
@@ -27,7 +26,8 @@ LobeHub provides some additional configuration options during deployment, which
- Example: `Kix2wcUONd4CX51E/ZPAd36BqM4wzJgKjPtz2sGztqQ=`
<Callout type={'warning'}>
- This key is used to encrypt sensitive data. Once set, do not change it, otherwise encrypted data cannot be decrypted.
+ This key is used to encrypt sensitive data. Once set, do not change it, otherwise encrypted data
+ cannot be decrypted.
</Callout>
<GenerateSecret envName="KEY_VAULTS_SECRET" />
@@ -108,6 +108,22 @@ Available system agents and their functions:
For specific content, please refer to the [Feature Flags](/docs/self-hosting/advanced/feature-flags) documentation.
+### `ENABLE_AGENT_GATEWAY`
+
+- Type: Optional
+- Description: Enables Gateway Mode for self-hosted deployments. It only takes effect when `AGENT_GATEWAY_URL` is also configured.
+- Default: `0`
+- Example: `1`
+
+Business builds enable Gateway Mode automatically. Self-hosted deployments can set `ENABLE_AGENT_GATEWAY=1` together with `AGENT_GATEWAY_URL` to expose Gateway Mode to clients.
+
+### `AGENT_GATEWAY_URL`
+
+- Type: Optional
+- Description: Agent Gateway endpoint used by Gateway Mode to run supported agent tasks through the backend.
+- Default: -
+- Example: `https://agent-gateway.example.com`
+
### `PROXY_URL`
- Type: Optional
@@ -137,9 +153,9 @@ For specific content, please refer to the [Feature Flags](/docs/self-hosting/adv
- Example: `1` or `0`
<Callout type="warning">
- **Security Notice**: Enabling this option will disable SSRF protection and allow connections to private
- IP addresses (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, etc.). Only enable this in
- trusted environments where you need to access internal network resources.
+ **Security Notice**: Enabling this option will disable SSRF protection and allow connections to
+ private IP addresses (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, etc.). Only enable
+ this in trusted environments where you need to access internal network resources.
</Callout>
**Use Cases**:
diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
index 8e7d7f1145f..d04ea3b3508 100644
--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
@@ -105,6 +105,22 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变
具体的内容可以参见 [特性标志](/zh/docs/self-hosting/advanced/feature-flags) 中的说明。
+### `ENABLE_AGENT_GATEWAY`
+
+- 类型:可选
+- 描述:为自托管部署启用 Gateway Mode。仅在同时配置 `AGENT_GATEWAY_URL` 时生效。
+- 默认值:`0`
+- 示例:`1`
+
+商业版本会自动启用 Gateway Mode。自托管部署可以同时设置 `ENABLE_AGENT_GATEWAY=1` 和 `AGENT_GATEWAY_URL`,让客户端显示 Gateway Mode。
+
+### `AGENT_GATEWAY_URL`
+
+- 类型:可选
+- 描述:Agent Gateway 端点,用于让 Gateway Mode 通过后端运行支持的助理任务。
+- 默认值:-
+- 示例:`https://agent-gateway.example.com`
+
### `PROXY_URL`
- 类型:可选
@@ -133,7 +149,8 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变
- 示例:`1` 或 `0`
<Callout type="warning">
- **安全提示**:启用此选项将关闭 SSRF 防护,允许连接私有 IP 地址段(127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16
+ **安全提示**:启用此选项将关闭 SSRF 防护,允许连接私有 IP
+ 地址段(127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16
等)。仅在需要访问内网资源的可信环境中启用。
</Callout>
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 25e0aff106f..28b61364f02 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -164,6 +164,7 @@
"extendParams.urlContext.title": "Extract Webpage Link Content",
"followUpPlaceholder": "Follow up.",
"followUpPlaceholderHeterogeneous": "Follow up.",
+ "gatewayMode.title": "Gateway Mode",
"group.desc": "Move a task forward with multiple Agents in one shared space.",
"group.memberTooltip": "There are {{count}} members in the group",
"group.orchestratorThinking": "Orchestrator is thinking...",
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 1815f03c1d1..c08ba832e9c 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -5,8 +5,6 @@
"features.agentSelfIteration.title": "Agent Self-iteration",
"features.assistantMessageGroup.desc": "Group agent messages and their tool call results together for display",
"features.assistantMessageGroup.title": "Agent Message Grouping",
- "features.gatewayMode.desc": "Execute agent tasks on the server via Gateway WebSocket instead of running locally. Enables faster execution and reduces client resource usage.",
- "features.gatewayMode.title": "Server-Side Agent Execution (Gateway)",
"features.groupChat.desc": "Enable multi-agent group chat coordination.",
"features.groupChat.title": "Group Chat (Multi-Agent)",
"features.imessage.desc": "Connect agents to iMessage through the local LobeHub Desktop BlueBubbles bridge.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 7d41e58b683..06d6ecdcb16 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1032,6 +1032,8 @@
"tab.addCustomSkill": "Add",
"tab.advanced": "Advanced",
"tab.advanced.appUpdates.title": "App updates",
+ "tab.advanced.gatewayMode.desc": "Run supported agent tasks through the cloud Gateway by default. Individual agents can override this from the chat menu.",
+ "tab.advanced.gatewayMode.title": "Gateway Mode",
"tab.advanced.toolsAndDiagnostics.title": "Tools and diagnostics",
"tab.advanced.updateChannel.canary": "Canary",
"tab.advanced.updateChannel.canaryDesc": "Triggered on every PR merge, multiple builds per day. Most unstable.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4925b484f64..eaec1cd7955 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -164,6 +164,7 @@
"extendParams.urlContext.title": "提取网页链接内容",
"followUpPlaceholder": "继续跟进。",
"followUpPlaceholderHeterogeneous": "继续跟进。",
+ "gatewayMode.title": "Gateway 模式",
"group.desc": "在同一对话空间,让多个助理一起推进任务",
"group.memberTooltip": "群组内有 {{count}} 名成员",
"group.orchestratorThinking": "主持人思考中…",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index f363f184c61..b65667ddbec 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -5,8 +5,6 @@
"features.agentSelfIteration.title": "Agent 自我迭代",
"features.assistantMessageGroup.desc": "将代理消息及其工具调用结果组合在一起显示",
"features.assistantMessageGroup.title": "代理消息分组",
- "features.gatewayMode.desc": "通过 Gateway 在服务端执行 Agent 任务。可实现关闭浏览器后仍然执行 agent。",
- "features.gatewayMode.title": "服务端代理执行(Gateway)",
"features.groupChat.desc": "启用多代理协同群聊功能。",
"features.groupChat.title": "群聊(多代理)",
"features.imessage.desc": "通过本地 LobeHub 桌面 BlueBubbles 桥接器将代理连接到 iMessage。",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index e34cd876acf..0875d1a3a53 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1032,6 +1032,8 @@
"tab.addCustomSkill": "添加",
"tab.advanced": "高级设置",
"tab.advanced.appUpdates.title": "应用更新",
+ "tab.advanced.gatewayMode.desc": "默认通过云端 Gateway 运行支持的助理任务。单个助理可以在聊天菜单中覆盖该设置。",
+ "tab.advanced.gatewayMode.title": "后端运行模式",
"tab.advanced.toolsAndDiagnostics.title": "工具与诊断",
"tab.advanced.updateChannel.canary": "Canary",
"tab.advanced.updateChannel.canaryDesc": "每次 PR 合并触发构建,一天可能多次。最不稳定。",
diff --git a/packages/env/src/app.ts b/packages/env/src/app.ts
index 3645593c78d..e8141ed3798 100644
--- a/packages/env/src/app.ts
+++ b/packages/env/src/app.ts
@@ -76,6 +76,7 @@ export const getAppConfig = () => {
MARKET_TRUSTED_CLIENT_ID: z.string().optional(),
AGENT_GATEWAY_SERVICE_TOKEN: z.string().optional(),
+ ENABLE_AGENT_GATEWAY: z.boolean().optional(),
AGENT_GATEWAY_URL: z.string().url().optional(),
/**
* Enable Queue-based Agent Runtime
@@ -121,6 +122,7 @@ export const getAppConfig = () => {
MARKET_TRUSTED_CLIENT_ID: process.env.MARKET_TRUSTED_CLIENT_ID,
AGENT_GATEWAY_SERVICE_TOKEN: process.env.AGENT_GATEWAY_SERVICE_TOKEN,
+ ENABLE_AGENT_GATEWAY: process.env.ENABLE_AGENT_GATEWAY === '1',
AGENT_GATEWAY_URL: process.env.AGENT_GATEWAY_URL,
enableQueueAgentRuntime: process.env.AGENT_RUNTIME_MODE === 'queue',
TELEMETRY_DISABLED: process.env.TELEMETRY_DISABLED === '1',
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index dc9b32e5c2e..ce34787fba3 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -484,6 +484,7 @@ export default {
'memory.on.desc': 'Allow AI to actively search and manage your memories during conversation.',
'memory.on.title': 'Enable Memory Tool',
'memory.title': 'Memory',
+ 'gatewayMode.title': 'Gateway Mode',
'search.grounding.imageSearchQueries': 'Image Search Keywords',
'search.grounding.imageTitle': 'Found {{count}} images',
'chatMode.agent': 'Agent',
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index 010d09912ba..ed1b85b7505 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -8,9 +8,6 @@ export default {
'features.assistantMessageGroup.desc':
'Group agent messages and their tool call results together for display',
'features.assistantMessageGroup.title': 'Agent Message Grouping',
- 'features.gatewayMode.desc':
- 'Execute agent tasks on the server via Gateway WebSocket instead of running locally. Enables faster execution and reduces client resource usage.',
- 'features.gatewayMode.title': 'Server-Side Agent Execution (Gateway)',
'features.imessage.desc':
'Connect agents to iMessage through the local LobeHub Desktop BlueBubbles bridge.',
'features.imessage.title': 'iMessage Channel',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index fd91faf2d83..99ac9a83193 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1201,6 +1201,9 @@ When I am ___, I need ___
'tab.about': 'About',
'tab.advanced': 'Advanced',
'tab.advanced.appUpdates.title': 'App updates',
+ 'tab.advanced.gatewayMode.desc':
+ 'Run supported agent tasks through the cloud Gateway by default. Individual agents can override this from the chat menu.',
+ 'tab.advanced.gatewayMode.title': 'Gateway Mode',
'tab.advanced.toolsAndDiagnostics.title': 'Tools and diagnostics',
'tab.addAgentSkill': 'Add Agent Skill',
'tab.advanced.updateChannel.canary': 'Canary',
diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.ts
index d37c99d15a5..09d052cb46c 100644
--- a/packages/types/src/agent/chatConfig.ts
+++ b/packages/types/src/agent/chatConfig.ts
@@ -36,6 +36,11 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIte
* Disable context caching
*/
disableContextCaching?: boolean;
+ /**
+ * Disable Gateway mode for this agent. Undefined means Gateway mode follows
+ * the app-level default and stays enabled when the server supports it.
+ */
+ disableGatewayMode?: boolean;
effort?: 'low' | 'medium' | 'high' | 'max';
/**
@@ -215,6 +220,7 @@ export const AgentChatConfigSchema = z
deepseekV4ReasoningEffort: z.enum(['none', 'high', 'max']).optional(),
compressionModelId: z.string().optional(),
disableContextCaching: z.boolean().optional(),
+ disableGatewayMode: z.boolean().optional(),
effort: z.enum(['low', 'medium', 'high', 'max']).optional(),
enableAdaptiveThinking: z.boolean().optional(),
enableAgentMode: z.boolean().optional(),
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 58714017489..696e0af1baa 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -67,6 +67,10 @@ export interface GlobalServerConfig {
*/
enabledOAuthSSO?: boolean;
enableEmailVerification?: boolean;
+ /**
+ * Whether Gateway mode is available for app-level agent execution.
+ */
+ enableGatewayMode?: boolean;
enableKlavis?: boolean;
enableLobehubSkill?: boolean;
enableMagicLink?: boolean;
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index fccfdb84f7b..d90106f6473 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -46,10 +46,6 @@ export const UserLabSchema = z.object({
* enable the floating chat panel in agent document preview
*/
enableAgentDocumentFloatingChatPanel: z.boolean().optional(),
- /**
- * enable server-side agent execution via Gateway WebSocket
- */
- enableGatewayMode: z.boolean().optional(),
/**
* enable multi-agent group chat mode
*/
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 93697e8570f..28c7016e6eb 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -10,6 +10,7 @@ import {
Brain,
CheckIcon,
ChevronRight,
+ Cloud,
CloudCog,
FileUp,
Globe,
@@ -37,7 +38,13 @@ import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/
import { useFileStore } from '@/store/file';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+import {
+ featureFlagsSelectors,
+ serverConfigSelectors,
+ useServerConfigStore,
+} from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
@@ -257,6 +264,10 @@ const PlusAction = memo(() => {
const upload = useFileStore((s) => s.uploadChatFiles);
const { enableKnowledgeBase } = useServerConfigStore(featureFlagsSelectors);
+ const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);
+ const defaultDisableGatewayMode = useUserStore(
+ (s) => settingsSelectors.defaultAgentConfig(s).chatConfig?.disableGatewayMode,
+ );
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
@@ -272,10 +283,12 @@ const PlusAction = memo(() => {
const skillActivateMode = useAgentStore((s) =>
chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),
);
- const [searchMode, useModelBuiltinSearch] = useAgentStore((s) => [
+ const [searchMode, useModelBuiltinSearch, disableGatewayMode] = useAgentStore((s) => [
chatConfigByIdSelectors.getSearchModeById(agentId)(s),
chatConfigByIdSelectors.getUseModelBuiltinSearchById(agentId)(s),
+ chatConfigByIdSelectors.getChatConfigById(agentId)(s).disableGatewayMode,
]);
+ const isGatewayModeEnabled = (disableGatewayMode ?? defaultDisableGatewayMode) !== true;
const isMemoryEnabled = useMemoryEnabled(agentId);
const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);
@@ -337,6 +350,13 @@ const PlusAction = memo(() => {
[updateAgentChatConfig],
);
+ const handleToggleGatewayMode = useCallback(
+ async (checked: boolean) => {
+ await updateAgentChatConfig({ disableGatewayMode: checked ? false : true });
+ },
+ [updateAgentChatConfig],
+ );
+
const handleToggleParams = useCallback(() => {
setDropdownOpen(false);
if (isParamsPanelActive) {
@@ -535,6 +555,18 @@ const PlusAction = memo(() => {
type: 'switch',
} as ActionDropdownMenuItems[number],
]),
+ ...(enableGatewayMode
+ ? [
+ {
+ checked: isGatewayModeEnabled,
+ icon: activeIcon(Cloud, isGatewayModeEnabled),
+ key: 'gateway-mode',
+ label: t('gatewayMode.title'),
+ onCheckedChange: handleToggleGatewayMode,
+ type: 'switch',
+ } as ActionDropdownMenuItems[number],
+ ]
+ : []),
{ type: 'divider' },
// Skills (with "Add Skills..." merged in) sits directly under the Web Search divider.
...toolsItems,
@@ -585,11 +617,15 @@ const PlusAction = memo(() => {
canUploadVideo,
editor,
enableFC,
+ enableGatewayMode,
enableKnowledgeBase,
+ defaultDisableGatewayMode,
handleSelectSearch,
+ handleToggleGatewayMode,
handleToggleMemory,
handleToggleParams,
isAgentModeEnabled,
+ isGatewayModeEnabled,
isMemoryEnabled,
isParamsPanelActive,
knowledgeEnabledCount,
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index c91d4be9a97..68329c6bdaf 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -326,7 +326,7 @@ export const generationSlice: StateCreator<
boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
- isGatewayMode: chatStore.isGatewayModeEnabled(),
+ isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),
});
// Hetero CLIs (CC / Codex) have no "continue a cut-off response" primitive
@@ -505,7 +505,7 @@ export const generationSlice: StateCreator<
boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider,
- isGatewayMode: chatStore.isGatewayModeEnabled(),
+ isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),
});
// ── Gateway mode: trigger server-side regeneration ──
diff --git a/src/routes/(main)/settings/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsx
index f072256ce38..fe063f99850 100644
--- a/src/routes/(main)/settings/advanced/index.tsx
+++ b/src/routes/(main)/settings/advanced/index.tsx
@@ -13,7 +13,7 @@ import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';
import { autoUpdateService } from '@/services/electron/autoUpdate';
-import { useServerConfigStore } from '@/store/serverConfig';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
@@ -32,14 +32,20 @@ const Page = memo(() => {
const { t: tLabs } = useTranslation('labs');
const general = useUserStore((s) => settingsSelectors.currentSettings(s).general, isEqual);
- const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
+ const defaultAgentGatewayModeEnabled = useUserStore(
+ (s) => settingsSelectors.defaultAgentConfig(s).chatConfig?.disableGatewayMode !== true,
+ );
+ const [setSettings, updateDefaultAgent, isUserStateInit] = useUserStore((s) => [
+ s.setSettings,
+ s.updateDefaultAgent,
+ s.isUserStateInit,
+ ]);
const [loading, setLoading] = useState(false);
const [
isPreferenceInit,
enableAgentDocumentFloatingChatPanel,
enableInputMarkdown,
- enableGatewayMode,
enablePlatformAgent,
enableImessage,
updateLab,
@@ -47,12 +53,12 @@ const Page = memo(() => {
preferenceSelectors.isPreferenceInit(s),
labPreferSelectors.enableAgentDocumentFloatingChatPanel(s),
labPreferSelectors.enableInputMarkdown(s),
- labPreferSelectors.enableGatewayMode(s),
labPreferSelectors.enablePlatformAgent(s),
labPreferSelectors.enableImessage(s),
s.updateLab,
]);
+ const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);
const hasGatewayUrl = useServerConfigStore((s) => !!s.serverConfig.agentGatewayUrl);
const [channel, setChannel] = useState<UpdateChannelValue>('stable');
@@ -70,6 +76,15 @@ const Page = memo(() => {
autoUpdateService.setUpdateChannel(value);
}, []);
+ const handleGatewayModeChange = useCallback(
+ (checked: boolean) => {
+ updateDefaultAgent({
+ config: { chatConfig: { disableGatewayMode: checked ? false : true } },
+ });
+ },
+ [updateDefaultAgent],
+ );
+
if (!isUserStateInit) return <Skeleton active paragraph={{ rows: 5 }} title={false} />;
const advancedGroup: FormGroupItemType = {
@@ -82,6 +97,22 @@ const Page = memo(() => {
name: 'isDevMode',
valuePropName: 'checked',
},
+ ...(enableGatewayMode
+ ? [
+ {
+ children: (
+ <Switch
+ checked={defaultAgentGatewayModeEnabled}
+ onChange={handleGatewayModeChange}
+ />
+ ),
+ className: styles.labItem,
+ desc: t('tab.advanced.gatewayMode.desc'),
+ label: t('tab.advanced.gatewayMode.title'),
+ minWidth: undefined,
+ } satisfies FormItemProps,
+ ]
+ : []),
],
extra: loading && <Icon spin icon={Loader2Icon} size={16} style={{ opacity: 0.5 }} />,
title: t('tab.advanced.toolsAndDiagnostics.title'),
@@ -151,19 +182,6 @@ const Page = memo(() => {
: []),
...(hasGatewayUrl
? [
- {
- children: (
- <Switch
- checked={enableGatewayMode}
- loading={!isPreferenceInit}
- onChange={(checked: boolean) => updateLab({ enableGatewayMode: checked })}
- />
- ),
- className: styles.labItem,
- desc: tLabs('features.gatewayMode.desc'),
- label: tLabs('features.gatewayMode.title'),
- minWidth: undefined,
- } satisfies FormItemProps,
{
children: (
<Switch
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 395005dac2d..63ae360e244 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -1,6 +1,6 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { RequestTrigger } from '@lobechat/types';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as ConstVersion from '@/const/version';
import { aiAgentService } from '@/services/aiAgent';
@@ -28,9 +28,21 @@ vi.mock('@/services/topic', () => ({
},
}));
+const mockUserDefaultConfig = vi.hoisted(() => ({
+ disableGatewayMode: undefined as boolean | undefined,
+}));
+
vi.mock('@/store/user', () => ({
useUserStore: {
- getState: vi.fn(() => ({ preference: { lab: {} } })),
+ getState: vi.fn(() => ({})),
+ },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ settingsSelectors: {
+ defaultAgentConfig: () => ({
+ chatConfig: { disableGatewayMode: mockUserDefaultConfig.disableGatewayMode },
+ }),
},
}));
@@ -41,6 +53,9 @@ 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 }));
+const mockAgentStore = vi.hoisted(() => ({
+ state: { activeAgentId: undefined, agentMap: {} } as any,
+}));
vi.mock('@/const/version', async (importOriginal) => {
const actual = await importOriginal<typeof ConstVersion>();
@@ -56,11 +71,15 @@ vi.mock('@/services/electron/gatewayConnection', () => ({
gatewayConnectionService: { getDeviceInfo: mockGateway.getDeviceInfo },
}));
-vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mockAgentStore.state }));
vi.mock('@/store/agent/selectors', () => ({
agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
- chatConfigByIdSelectors: { isLocalSystemEnabledById: () => () => mockRuntime.isLocal },
+ chatConfigByIdSelectors: {
+ getChatConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.chatConfig ?? {},
+ isLocalSystemEnabledById: () => () => mockRuntime.isLocal,
+ },
}));
// ─── Mock Client Factory ───
@@ -116,8 +135,69 @@ function createTestAction() {
}
describe('GatewayActionImpl', () => {
+ beforeEach(() => {
+ mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };
+ mockUserDefaultConfig.disableGatewayMode = undefined;
+ });
+
afterEach(() => {
vi.restoreAllMocks();
+ delete (globalThis as any).window;
+ });
+
+ describe('isGatewayModeEnabled', () => {
+ const setServerConfig = (serverConfig: Record<string, unknown>) => {
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig }),
+ },
+ };
+ };
+
+ it('returns true when backend enables Gateway mode and the agent does not disable it', () => {
+ const { action } = createTestAction();
+ setServerConfig({
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableGatewayMode: true,
+ });
+
+ expect(action.isGatewayModeEnabled('agent-1')).toBe(true);
+ });
+
+ it('returns false when the current agent disables Gateway mode', () => {
+ const { action } = createTestAction();
+ setServerConfig({
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableGatewayMode: true,
+ });
+ mockAgentStore.state = {
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { chatConfig: { disableGatewayMode: true } } },
+ };
+
+ expect(action.isGatewayModeEnabled('agent-1')).toBe(false);
+ });
+
+ it('falls back to the app-level default agent config', () => {
+ const { action } = createTestAction();
+ setServerConfig({
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableGatewayMode: true,
+ });
+ mockUserDefaultConfig.disableGatewayMode = true;
+
+ expect(action.isGatewayModeEnabled('agent-1')).toBe(false);
+ });
+
+ it('returns false when the backend does not enable Gateway mode', () => {
+ const { action } = createTestAction();
+ setServerConfig({
+ agentGatewayUrl: 'https://gateway.test.com',
+ enableGatewayMode: false,
+ });
+
+ expect(action.isGatewayModeEnabled('agent-1')).toBe(false);
+ });
});
describe('connectToGateway', () => {
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index 7dcf78880b3..3b76721cb5d 100644
--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts
@@ -64,7 +64,7 @@ export class ConversationControlActionImpl {
boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
- isGatewayMode: this.#get().isGatewayModeEnabled(),
+ isGatewayMode: this.#get().isGatewayModeEnabled(context.agentId),
}) === 'gateway'
);
};
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index cfde47b86fb..9e520969f5f 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -254,7 +254,7 @@ export class ConversationLifecycleActionImpl {
boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,
executionTarget: agentConfig?.agencyConfig?.executionTarget,
heterogeneousProvider,
- isGatewayMode: this.#get().isGatewayModeEnabled(),
+ isGatewayMode: this.#get().isGatewayModeEnabled(agentId),
// Callers that need to pin the runtime (e.g. task topics that were
// started server-side via runTask) pass `forceRuntime` to override
// the agent's local/cloud preference.
@@ -1284,7 +1284,7 @@ export class ConversationLifecycleActionImpl {
boundDeviceId: parentAgentConfig?.agencyConfig?.boundDeviceId,
heterogeneousProvider: parentAgentConfig?.agencyConfig?.heterogeneousProvider,
inPortalThread,
- isGatewayMode: this.#get().isGatewayModeEnabled(),
+ isGatewayMode: this.#get().isGatewayModeEnabled(context.agentId),
messages: messagesWithInstruction,
parentOperationId: operationId,
},
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index cd4f2b8afe1..592eedc5884 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -18,6 +18,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import type { ChatStore } from '@/store/chat/store';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
import { createGatewayEventHandler } from './gatewayEventHandler';
@@ -261,14 +262,25 @@ export class GatewayActionImpl {
/**
* Check if Gateway mode is available and enabled.
- * Returns true if both server config and user lab toggle are set.
+ * Returns true when the server supports Gateway mode and the agent config
+ * has not disabled it. `disableGatewayMode: undefined` means enabled.
*/
- isGatewayModeEnabled = (): boolean => {
- const agentGatewayUrl =
- window.global_serverConfigStore?.getState()?.serverConfig?.agentGatewayUrl;
- const enableGatewayMode = useUserStore.getState().preference.lab?.enableGatewayMode;
-
- return !!agentGatewayUrl && !!enableGatewayMode;
+ isGatewayModeEnabled = (agentId?: string): boolean => {
+ const serverConfig = window.global_serverConfigStore?.getState()?.serverConfig;
+ const agentState = getAgentStoreState();
+ const resolvedAgentId = agentId ?? agentState.activeAgentId;
+ const agentDisableGatewayMode = resolvedAgentId
+ ? chatConfigByIdSelectors.getChatConfigById(resolvedAgentId)(agentState).disableGatewayMode
+ : undefined;
+ const defaultDisableGatewayMode = settingsSelectors.defaultAgentConfig(useUserStore.getState())
+ .chatConfig?.disableGatewayMode;
+ const disableGatewayMode = agentDisableGatewayMode ?? defaultDisableGatewayMode;
+
+ return (
+ !!serverConfig?.agentGatewayUrl &&
+ !!serverConfig.enableGatewayMode &&
+ disableGatewayMode !== true
+ );
};
/**
diff --git a/src/store/serverConfig/selectors.test.ts b/src/store/serverConfig/selectors.test.ts
index ac23ba5938c..a450f3fb1eb 100644
--- a/src/store/serverConfig/selectors.test.ts
+++ b/src/store/serverConfig/selectors.test.ts
@@ -27,6 +27,35 @@ describe('featureFlagsSelectors', () => {
});
describe('serverConfigSelectors', () => {
+ describe('enableGatewayMode', () => {
+ it('should return true when gateway mode is enabled', () => {
+ const store = initServerConfigStore({
+ serverConfig: {
+ aiProvider: {},
+ enableGatewayMode: true,
+ telemetry: {},
+ },
+ });
+
+ const result = serverConfigSelectors.enableGatewayMode(store.getState());
+
+ expect(result).toBe(true);
+ });
+
+ it('should return false when gateway mode is not defined', () => {
+ const store = initServerConfigStore({
+ serverConfig: {
+ aiProvider: {},
+ telemetry: {},
+ },
+ });
+
+ const result = serverConfigSelectors.enableGatewayMode(store.getState());
+
+ expect(result).toBe(false);
+ });
+ });
+
describe('enabledTelemetryChat', () => {
it('should return langfuse value from store when defined', () => {
const store = initServerConfigStore({
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index 6d559727885..c302c60c2c0 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -7,6 +7,7 @@ export const serverConfigSelectors = {
enableBusinessFeatures: (s: ServerConfigStore) => s.serverConfig.enableBusinessFeatures || false,
enableEmailVerification: (s: ServerConfigStore) =>
s.serverConfig.enableEmailVerification || false,
+ enableGatewayMode: (s: ServerConfigStore) => s.serverConfig.enableGatewayMode || false,
enableKlavis: (s: ServerConfigStore) => s.serverConfig.enableKlavis || false,
enableLobehubSkill: (s: ServerConfigStore) => s.serverConfig.enableLobehubSkill || false,
enableMagicLink: (s: ServerConfigStore) => s.serverConfig.enableMagicLink || false,
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 468f2638cce..574de749ff6 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -9,7 +9,6 @@ export const labPreferSelectors = {
false,
enableAgentSelfIteration: (s: UserState): boolean =>
s.preference.lab?.enableAgentSelfIteration ?? false,
- enableGatewayMode: (s: UserState): boolean => s.preference.lab?.enableGatewayMode ?? false,
enableImessage: (s: UserState): boolean => s.preference.lab?.enableImessage ?? false,
enableInputMarkdown: (s: UserState): boolean =>
s.preference.lab?.enableInputMarkdown ?? DEFAULT_PREFERENCE.lab?.enableInputMarkdown ?? true,