🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(gateway): gate the multiplexed socket on a server capability and a feature flag (#19816)
Arvin Xu670816b76e37
diff --git a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts b/apps/server/src/globalConfig/getServerGlobalConfig.test.tsindex d7db6fcf225..31ee738f489 100644--- a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts+++ b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({}));interface MockGlobalConfigOptions {+ agentGatewayProtocol?: number;agentGatewayUrl?: string;enableAgentGateway?: boolean;toolNameMaxLengthEnv?: string;@@ -39,6 +40,9 @@ const mockGlobalConfigDependencies = (vi.doMock('@/envs/app', () => ({appEnv: {+ ...(options.agentGatewayProtocol === undefined+ ? {}+ : { AGENT_GATEWAY_PROTOCOL: options.agentGatewayProtocol }),...(options.agentGatewayUrl ? { AGENT_GATEWAY_URL: options.agentGatewayUrl } : {}),...(options.enableAgentGateway === undefined? {}@@ -198,6 +202,33 @@ describe('getServerGlobalConfig', () => {});});+ it('should declare gateway protocol 2 only where the v2 socket exists', async () => {+ // The business gateway serves `/v2/ws`; `lobehub/lobehub-gateway`, which is+ // what a self-hosted deployment runs, serves only `/ws`.+ await expect(loadServerConfig(true)).resolves.toMatchObject({ agentGatewayProtocol: 2 });+ await expect(+ loadServerConfig(false, {+ agentGatewayUrl: 'https://gateway.test.com',+ enableAgentGateway: true,+ }),+ ).resolves.toMatchObject({ agentGatewayProtocol: 1 });+ });++ it('should let AGENT_GATEWAY_PROTOCOL correct either guess', async () => {+ await expect(+ loadServerConfig(false, {+ agentGatewayProtocol: 2,+ agentGatewayUrl: 'https://gateway.test.com',+ enableAgentGateway: true,+ }),+ ).resolves.toMatchObject({ agentGatewayProtocol: 2 });++ // An on-prem business deployment sitting in front of a v1 gateway.+ await expect(loadServerConfig(true, { agentGatewayProtocol: 1 })).resolves.toMatchObject({+ agentGatewayProtocol: 1,+ });+ });+// The client-driven chat path builds tool names in the browser, so `0`// (tool-name compression off) only takes effect if the server ships the value// with the global config.diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.tsindex b9ddf4ffd78..4fe7fc223e8 100644--- a/apps/server/src/globalConfig/index.ts+++ b/apps/server/src/globalConfig/index.ts@@ -32,6 +32,24 @@ const getBetterAuthSSOProviders = () => {return parseSSOProviders(authEnv.AUTH_SSO_PROVIDERS);};+/**+ * Which Agent Gateway wire protocol the client may dial.+ *+ * The multiplexed `/v2/ws` socket only exists on the gateway that ships with+ * business builds. A self-hosted deployment runs `lobehub/lobehub-gateway`,+ * which serves `GET /ws` and nothing else — a client that picks v2 there only+ * reaches a working socket after burning its dial budget on 404s, so the+ * default has to be the one that works everywhere. `AGENT_GATEWAY_PROTOCOL`+ * overrides both guesses, which is what an on-prem business deployment sitting+ * in front of a v1 gateway needs.+ */+const resolveAgentGatewayProtocol = (): 1 | 2 => {+ if (appEnv.AGENT_GATEWAY_PROTOCOL === 2) return 2;+ if (appEnv.AGENT_GATEWAY_PROTOCOL === 1) return 1;++ return ENABLE_BUSINESS_FEATURES ? 2 : 1;+};+export const getServerGlobalConfig = async () => {const { DEFAULT_AGENT_CONFIG } = getAppConfig();@@ -131,6 +149,7 @@ export const getServerGlobalConfig = async () => {// Expose Agent Gateway URL to client (used by hetero agents; also required for queue mode)...(appEnv.AGENT_GATEWAY_URL ? { agentGatewayUrl: appEnv.AGENT_GATEWAY_URL } : undefined),+ agentGatewayProtocol: resolveAgentGatewayProtocol(),image: cleanObject({defaultImageNum: imageEnv.AI_IMAGE_DEFAULT_IMAGE_NUM,diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdxindex 12f54711081..77b8a37dea3 100644--- a/docs/self-hosting/advanced/feature-flags.mdx+++ b/docs/self-hosting/advanced/feature-flags.mdx@@ -36,26 +36,27 @@ You can achieve various feature combinations using the above configuration syntatheir default values).</Callout>-| Configuration Item | Description | Default Value |-| ------------------------ | -------------------------------------------------------------------------------------------------------- | ------------- |-| `check_updates` | Allows checking for updates. | Enabled |-| `provider_settings` | Controls model provider settings display. | Enabled |-| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |-| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |-| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |-| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |-| `edit_agent` | Allows users to edit assistants. | Enabled |-| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |-| `speech_to_text` | Enables speech-to-text functionality. | Enabled |-| `token_counter` | Reserved for token counter display. | Enabled |-| `welcome_suggest` | Displays welcome suggestions. | Enabled |-| `changelog` | Controls changelog modal/page display. | Enabled |-| `market` | Enables the assistant market functionality. | Enabled |-| `knowledge_base` | Enables the knowledge base functionality. | Enabled |-| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |-| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |-| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |-| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |+| Configuration Item | Description | Default Value |+| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ------------- |+| `check_updates` | Allows checking for updates. | Enabled |+| `provider_settings` | Controls model provider settings display. | Enabled |+| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |+| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |+| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |+| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |+| `agent_gateway_mux` | Routes agent runs over one multiplexed gateway socket per user. Requires a gateway that serves `/v2/ws` (`AGENT_GATEWAY_PROTOCOL=2`). | Disabled |+| `edit_agent` | Allows users to edit assistants. | Enabled |+| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |+| `speech_to_text` | Enables speech-to-text functionality. | Enabled |+| `token_counter` | Reserved for token counter display. | Enabled |+| `welcome_suggest` | Displays welcome suggestions. | Enabled |+| `changelog` | Controls changelog modal/page display. | Enabled |+| `market` | Enables the assistant market functionality. | Enabled |+| `knowledge_base` | Enables the knowledge base functionality. | Enabled |+| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |+| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |+| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |+| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |## Interactive Agent Sharing: Deployment and Rollout Boundariesdiff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdxindex a538f5fa608..aa0acf46a99 100644--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx@@ -32,26 +32,27 @@ tags:关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。</Callout>-| 配置项 | 解释 | 默认值 |-| ------------------------ | ------------------------------------ | --- |-| `check_updates` | 允许检查更新。 | 开启 |-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |-| `edit_agent` | 允许用户编辑助手。 | 开启 |-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |-| `speech_to_text` | 启用语音转文本功能。 | 开启 |-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |-| `welcome_suggest` | 显示欢迎建议。 | 开启 |-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |-| `market` | 启用助手市场功能。 | 开启 |-| `knowledge_base` | 启用知识库功能。 | 开启 |-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |+| 配置项 | 解释 | 默认值 |+| ------------------------ | ---------------------------------------------------------------- | --- |+| `check_updates` | 允许检查更新。 | 开启 |+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |+| `agent_gateway_mux` | 让助理运行共用一条按用户复用的网关连接;需要网关提供 `/v2/ws`(`AGENT_GATEWAY_PROTOCOL=2`)。 | 关闭 |+| `edit_agent` | 允许用户编辑助手。 | 开启 |+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |+| `speech_to_text` | 启用语音转文本功能。 | 开启 |+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |+| `welcome_suggest` | 显示欢迎建议。 | 开启 |+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |+| `market` | 启用助手市场功能。 | 开启 |+| `knowledge_base` | 启用知识库功能。 | 开启 |+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |## 交互式助理分享:部署与灰度边界diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdxindex 3516a5dc268..eb5502d7ffa 100644--- a/docs/self-hosting/environment-variables/basic.mdx+++ b/docs/self-hosting/environment-variables/basic.mdx@@ -129,6 +129,13 @@ Business builds enable Gateway Mode automatically. Self-hosted deployments can s- Default: -- Example: `https://agent-gateway.example.com`+### `AGENT_GATEWAY_PROTOCOL`++- Type: Optional+- Description: Which Agent Gateway wire protocol clients may use. `1` is the per-operation WebSocket (`GET /ws`), which is what `lobehub/lobehub-gateway` serves; `2` adds the per-user multiplexed socket (`GET /v2/ws`). Self-hosted deployments default to `1` — a client that dials `/v2/ws` on a gateway without it cannot stream until it falls back. Set it only if you run a gateway that does serve `/v2/ws`.+- Default: `1`+- Example: `2`+### `AGENT_GATEWAY_INTERNAL_URL`- Type: Optionaldiff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdxindex 9dc0cf99299..be0e286e870 100644--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx@@ -125,6 +125,13 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变- 默认值:-- 示例:`https://agent-gateway.example.com`+### `AGENT_GATEWAY_PROTOCOL`++- 类型:可选+- 描述:客户端可以使用的 Agent Gateway 协议版本。`1` 是按运行建连的 WebSocket(`GET /ws`),也就是 `lobehub/lobehub-gateway` 提供的那个;`2` 额外提供按用户复用的连接(`GET /v2/ws`)。自托管部署默认为 `1`—— 网关没有 `/v2/ws` 时,客户端会一直拨不通,直到回退才能恢复流式输出。只有当你运行的网关确实提供 `/v2/ws` 时才需要设置。+- 默认值:`1`+- 示例:`2`+### `AGENT_GATEWAY_INTERNAL_URL`- 类型:可选diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex f244fd8cf24..605039e22b8 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -18,8 +18,6 @@"features.deviceTunnel.title": "Remote Port Links","features.evalCapture.desc": "Adds a message action that captures a conversation turn — its prior context, input and the answer it produced — as an evaluation test case.","features.evalCapture.title": "Save a turn as an eval case",- "features.gatewayMux.desc": "Route every agent run in this tab over one shared gateway WebSocket instead of opening a socket per run. Reconnects and event replay are handled per run on the shared connection.",- "features.gatewayMux.title": "Single-connection Gateway (experimental)","features.groupChat.desc": "Enable multi-agent group chat coordination.","features.groupChat.title": "Group Chat (Multi-Agent)","features.heteroSessionImport.desc": "Add an \"Import Local Agent Sessions\" entry to the topic list menu: scan local Claude Code / Codex CLI transcripts and import them as topics, with incremental sync on re-import.",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex b07fa548451..d52c0610a97 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -18,8 +18,6 @@"features.deviceTunnel.title": "远程端口链接","features.evalCapture.desc": "在消息动作里增加一项,把一轮对话(前置上下文、本轮输入与它产生的回答)捕获成评测用例。","features.evalCapture.title": "把对话保存为评测用例",- "features.gatewayMux.desc": "当前标签页里的所有智能体运行共用一条网关 WebSocket,而不是每次运行各开一条;断线重连与事件回放在这条共享连接上按运行分别处理。",- "features.gatewayMux.title": "单连接网关(实验)","features.groupChat.desc": "启用多代理协同群聊功能。","features.groupChat.title": "群聊(多代理)","features.heteroSessionImport.desc": "在话题列表菜单中新增「导入本地 Agent 会话」入口:扫描本地 Claude Code / Codex CLI 的会话记录并导入为话题,重复导入时增量同步新消息。",diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex fe7ed5bfcbd..f494c8bd689 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -39,6 +39,17 @@ export const FeatureFlagsSchema = z.object({rag_eval: FeatureFlagValue.optional(),+ /**+ * Rollout gate for the multiplexed Agent Gateway socket (protocol v2: one+ * `/v2/ws` connection per user instead of one per run). Array values are user+ * ids, so the rollout can go allowlist → everyone without a deploy.+ *+ * Deployment support is independent and enforced separately: the client also+ * requires `serverConfig.agentGatewayProtocol === 2`, because a gateway+ * without `/v2/ws` cannot serve this no matter what the flag says.+ */+ agent_gateway_mux: FeatureFlagValue.optional(),+// internal flagagent_self_iteration: FeatureFlagValue.optional(),agent_onboarding: FeatureFlagValue.optional(),@@ -102,6 +113,10 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {knowledge_base: true,rag_eval: false,+ // Off until an admin publishes a user allowlist or flips it to true; the+ // v1 socket stays the default everywhere until then.+ agent_gateway_mux: false,+agent_self_iteration: isDev,agent_onboarding: isDev,dev_dock: isDev,@@ -134,6 +149,7 @@ export const mapFeatureFlagsEnvToState = (isAgentEditable: evaluateFeatureFlag(config.edit_agent, userId),enableAgentShare: evaluateFeatureFlag(config.agent_share, userId),+ enableGatewayMux: evaluateFeatureFlag(config.agent_gateway_mux, userId),showProvider: evaluateFeatureFlag(config.provider_settings, userId),showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),diff --git a/packages/env/src/app.ts b/packages/env/src/app.tsindex 2d23b7671c5..1a1902beae2 100644--- a/packages/env/src/app.ts+++ b/packages/env/src/app.ts@@ -85,6 +85,18 @@ export const getAppConfig = () => {*/AGENT_GATEWAY_INTERNAL_URL: z.string().url().optional(),AGENT_GATEWAY_URL: z.string().url().optional(),+ /**+ * Which Agent Gateway wire protocol this deployment's gateway can serve.+ *+ * `2` means it exposes the per-user multiplexed socket (`GET /v2/ws`);+ * `1` means only the per-operation socket (`GET /ws`). Unset is resolved+ * from the build: business builds ship against the v2 gateway, every+ * other deployment gets 1, which is what `lobehub/lobehub-gateway`+ * serves. Set it explicitly when that guess is wrong — a client that+ * dials `/v2/ws` on a gateway without it has no stream until it has+ * burned its fallback budget on 404s.+ */+ AGENT_GATEWAY_PROTOCOL: z.coerce.number().int().min(1).max(2).optional(),/*** Enable Queue-based Agent Runtime* When true, use QStash for async agent execution (production)@@ -133,6 +145,7 @@ export const getAppConfig = () => {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,+ AGENT_GATEWAY_PROTOCOL: process.env.AGENT_GATEWAY_PROTOCOL || undefined,AGENT_GATEWAY_INTERNAL_URL: process.env.AGENT_GATEWAY_INTERNAL_URL || undefined,enableQueueAgentRuntime: process.env.AGENT_RUNTIME_MODE === 'queue',TELEMETRY_DISABLED: process.env.TELEMETRY_DISABLED === '1',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex 928d7341619..a7ddf3b6b3f 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -30,9 +30,6 @@ export default {'features.deviceTunnel.desc':'Give a port on the working device a link, so a dev server running there can be opened from here. The link only works for people who can reach that device.','features.deviceTunnel.title': 'Remote Port Links',- 'features.gatewayMux.desc':- 'Route every agent run in this tab over one shared gateway WebSocket instead of opening a socket per run. Reconnects and event replay are handled per run on the shared connection.',- 'features.gatewayMux.title': 'Single-connection Gateway (experimental)','features.heteroSessionImport.title': 'Local Agent Session Import','features.imessage.desc':'Connect agents to iMessage through the local LobeHub Desktop BlueBubbles bridge.',diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex f09cd58b712..97dcb2d8ac0 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -28,6 +28,12 @@ export type IFeatureFlagsState = {enableAuthCaptcha: boolean | undefined;enableCheckUpdates: boolean | undefined;enableDevDock: boolean | undefined;+ /**+ * Rollout gate for the multiplexed gateway socket. Necessary but not+ * sufficient: the transport also requires+ * `GlobalServerConfig.agentGatewayProtocol === 2`.+ */+ enableGatewayMux: boolean | undefined;enableKnowledgeBase: boolean | undefined;enableOnboardingV2: boolean | undefined;enableRAGEval: boolean | undefined;@@ -91,6 +97,17 @@ export interface ServerModelProviderConfig {export type ServerLanguageModel = Partial<Record<GlobalLLMProviderKey, ServerModelProviderConfig>>;export interface GlobalServerConfig {+ /**+ * Which Agent Gateway wire protocol this deployment's gateway can serve:+ * `2` when it exposes the per-user multiplexed socket (`/v2/ws`), `1` when+ * it only has the per-operation one (`/ws`). Absent ⇒ 1.+ *+ * A capability, not a rollout switch: the client may only pick the+ * multiplexed transport where the server says it exists, and there is no+ * negotiation on the socket itself — dialing `/v2/ws` on a gateway without+ * it is a 404 with nothing to fall back to until the client gives up.+ */+ agentGatewayProtocol?: 1 | 2;/*** Agent Gateway URL for WebSocket-based agent execution.* When set, the SPA can offload agent execution to the server and receivediff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 95af92c9868..21d2331ab6e 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -219,6 +219,11 @@ export const UserLabSchema = z.object({/*** route every agent run in this tab over one shared gateway WebSocket* (protocol v2 mux) instead of one socket per run+ *+ * @deprecated The Labs toggle is gone; the transport is gated by the+ * `agent_gateway_mux` feature flag. Still read on the server to pick+ * message-patch delivery and read-path projection until those decisions move+ * to the client's declared protocol, which removes this field.*/enableGatewayMux: z.boolean().optional(),/**diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.tsindex 7a8e9af6f4f..436457ea93a 100644--- a/src/features/Settings/labs/features.ts+++ b/src/features/Settings/labs/features.ts@@ -19,7 +19,6 @@ type LabFeatureI18nKey =| 'desktopSplitView'| 'deviceTunnel'| 'evalCapture'- | 'gatewayMux'| 'heteroSessionImport'| 'imessage'| 'inputMarkdown'@@ -79,12 +78,6 @@ export const LAB_FEATURES: LabFeatureItem[] = [searchKeywords: ['eval', 'test case', 'capture', 'regression', 'benchmark'],stage: 'alpha',},- {- flag: 'enableGatewayMux',- i18nKey: 'gatewayMux',- searchKeywords: ['gateway', 'websocket', 'multiplex'],- stage: 'alpha',- },{flag: 'enableTopicAcceptance',i18nKey: 'topicAcceptance',diff --git a/src/hooks/useGatewayMuxWarmup.ts b/src/hooks/useGatewayMuxWarmup.tsindex 85725010124..fb689358c2f 100644--- a/src/hooks/useGatewayMuxWarmup.ts+++ b/src/hooks/useGatewayMuxWarmup.ts@@ -1,17 +1,21 @@import { useEffect } from 'react';import { useChatStore } from '@/store/chat';+import { useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';/**- * Open the per-user gateway socket on app entry (lab `enableGatewayMux`),- * instead of on the first send. Waits for the signed-in user state so the- * mux can mint its token; re-runs when the lab toggle flips on.+ * Open the per-user gateway socket on app entry instead of on the first send,+ * so the session's first run never pays the WebSocket handshake on its critical+ * path. Waits for the signed-in user state so the mux can mint its token, and+ * re-runs when the rollout flag arrives with the server config.+ *+ * `warmupGatewayMux` re-checks the deployment capability and the flag itself —+ * this only decides when to ask.*/export const useGatewayMuxWarmup = (): void => {const isReady = useUserStore((s) => s.isUserStateInit && !!s.isSignedIn);- const enabled = useUserStore(labPreferSelectors.enableGatewayMux);+ const enabled = useServerConfigStore((s) => !!s.featureFlags.enableGatewayMux);const warmupGatewayMux = useChatStore((s) => s.warmupGatewayMux);useEffect(() => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.tsindex a87a97f787c..e937596e019 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts@@ -42,7 +42,8 @@ vi.mock('@/store/file/store', () => ({getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),}));-const mockLab = vi.hoisted(() => ({ enableGatewayMux: false }));+/** The two server-side halves the transport requires: capability + rollout. */+const mockServer = vi.hoisted(() => ({ agentGatewayProtocol: 2 as 1 | 2, enableGatewayMux: true }));const mockUserState = vi.hoisted(() => ({profile: { id: 'user-1' },workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },@@ -54,7 +55,6 @@ vi.mock('@/store/user', () => ({}));vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: { enableGatewayMux: () => mockLab.enableGatewayMux },settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },userGeneralSettingsSelectors: { telemetry: () => false },@@ -79,7 +79,10 @@ vi.mock('@/store/agent/selectors', () => ({getAgencyConfigById: () => () => undefined,getAgentById: () => () => undefined,},- agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },+ agentSelectors: {+ currentAgentWorkingDirectory: () => () => undefined,+ getAgentConfigById: () => () => undefined,+ },chatConfigByIdSelectors: {getChatConfigById: () => () => ({}),isChatModeById: () => () => false,@@ -178,9 +181,31 @@ function createTestAction(overrides: Record<string, any> = {}) {const flushMicrotasks = () => new Promise<void>((resolve) => setTimeout(resolve, 0));-describe('GatewayActionImpl (enableGatewayMux lab)', () => {+describe('GatewayActionImpl (multiplexed gateway transport)', () => {beforeEach(() => {- mockLab.enableGatewayMux = true;+ mockServer.agentGatewayProtocol = 2;+ mockServer.enableGatewayMux = true;+ (globalThis as any).window = {+ global_serverConfigStore: {+ getState: () => ({+ featureFlags: { enableGatewayMux: mockServer.enableGatewayMux },+ serverConfig: {+ agentGatewayProtocol: mockServer.agentGatewayProtocol,+ agentGatewayUrl: GATEWAY_URL,+ enableGatewayMode: true,+ },+ }),+ },+ };+ // The conversation read resolves Gateway mode from this store too.+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({+ featureFlags: { enableGatewayMux: mockServer.enableGatewayMux },+ serverConfig: {+ agentGatewayProtocol: mockServer.agentGatewayProtocol,+ agentGatewayUrl: GATEWAY_URL,+ enableGatewayMode: true,+ },+ } as unknown as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);vi.mocked(messageService.getMessages).mockClear();});@@ -218,8 +243,8 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {expect(state.gatewayConnections['op-1']).toEqual({ client: muxClient, status: 'connecting' });});- it('keeps the v1 per-operation socket byte-for-byte when the flag is off', () => {- mockLab.enableGatewayMux = false;+ it('keeps the v1 per-operation socket byte-for-byte outside the rollout', () => {+ mockServer.enableGatewayMux = false;const { action, state, v1Client } = createTestAction();action.connectToGateway({@@ -242,8 +267,8 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {expect(state.gatewayConnections['op-1'].client).toBe(v1Client);});- it('uses the share-scoped mux by default when the lab flag is off', () => {- mockLab.enableGatewayMux = false;+ it('uses the share-scoped mux even outside the rollout', () => {+ mockServer.enableGatewayMux = false;const { action, mux, muxClient, state, v1Client } = createTestAction();action.connectToGateway({@@ -483,7 +508,15 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {describe('warmupGatewayMux', () => {const withServerConfig = (serverConfig: Record<string, unknown>) => {(globalThis as any).window = {- global_serverConfigStore: { getState: () => ({ serverConfig }) },+ global_serverConfigStore: {+ getState: () => ({+ featureFlags: { enableGatewayMux: mockServer.enableGatewayMux },+ serverConfig: {+ agentGatewayProtocol: mockServer.agentGatewayProtocol,+ ...serverConfig,+ },+ }),+ },};};@@ -511,8 +544,13 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {const { action, mux } = createTestAction();Reflect.deleteProperty(globalThis, 'window');vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({- serverConfig: { agentGatewayUrl: GATEWAY_URL, enableGatewayMode: enabled },- } as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);+ featureFlags: { enableGatewayMux: true },+ serverConfig: {+ agentGatewayProtocol: 2,+ agentGatewayUrl: GATEWAY_URL,+ enableGatewayMode: enabled,+ },+ } as unknown as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);action.warmupGatewayMux();@@ -526,18 +564,26 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {},);- it('is a no-op when the lab flag is off or gateway mode is unavailable', () => {+ it('is a no-op outside the rollout, without gateway mode, or on a v1 deployment', () => {+ mockServer.enableGatewayMux = false;withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: true });- mockLab.enableGatewayMux = false;const off = createTestAction();off.action.warmupGatewayMux();expect(off.mux.connect).not.toHaveBeenCalled();- mockLab.enableGatewayMux = true;+ mockServer.enableGatewayMux = true;withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: false });const noGateway = createTestAction();noGateway.action.warmupGatewayMux();expect(noGateway.mux.connect).not.toHaveBeenCalled();++ // The deployment's gateway has no `/v2/ws` at all: dialing it would only+ // burn the client's fallback budget on 404s.+ mockServer.agentGatewayProtocol = 1;+ withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: true });+ const v1Deployment = createTestAction();+ v1Deployment.action.warmupGatewayMux();+ expect(v1Deployment.mux.connect).not.toHaveBeenCalled();});});@@ -560,7 +606,13 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {beforeEach(() => {(globalThis as any).window = {global_serverConfigStore: {- getState: () => ({ serverConfig: { agentGatewayUrl: GATEWAY_URL } }),+ getState: () => ({+ featureFlags: { enableGatewayMux: mockServer.enableGatewayMux },+ serverConfig: {+ agentGatewayProtocol: mockServer.agentGatewayProtocol,+ agentGatewayUrl: GATEWAY_URL,+ },+ }),},};});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 6fb30459eec..3628651c876 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -50,7 +50,6 @@ import { getServerConfigStoreState } from '@/store/serverConfig';import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import {- labPreferSelectors,settingsSelectors,toolInterventionSelectors,userProfileSelectors,@@ -77,6 +76,25 @@ const getGatewayServerConfig = () =>? window.global_serverConfigStore?.getState()?.serverConfig: undefined) ?? getServerConfigStoreState()?.serverConfig;+const getGatewayFeatureFlags = () =>+ (typeof window !== 'undefined'+ ? window.global_serverConfigStore?.getState()?.featureFlags+ : undefined) ?? getServerConfigStoreState()?.featureFlags;++/**+ * Whether this client may open the multiplexed (protocol v2) gateway socket.+ *+ * Both halves are required and mean different things: the deployment has to+ * actually expose `/v2/ws` (`agentGatewayProtocol` — a capability, since there+ * is no negotiation on the socket itself), and this user has to be inside the+ * rollout (`enableGatewayMux`, a server-published feature flag). Read+ * non-reactively like the other gateway prefs: a connection keeps the transport+ * it was opened with even if either side changes mid-run.+ */+const canUseGatewayMux = (): boolean =>+ getGatewayServerConfig()?.agentGatewayProtocol === 2 &&+ !!getGatewayFeatureFlags()?.enableGatewayMux;+/*** Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.*@@ -217,7 +235,7 @@ export interface ConnectGatewayParams {/*** This tab started the run, so it is the one that executes the run's local* `tool_execute` requests. `false` for a passive reconnect. Only the- * multiplexed transport (lab `enableGatewayMux`) carries it to the hub; the+ * multiplexed transport carries it to the hub; the* v1 per-operation socket is always the executor.*/executor?: boolean;@@ -308,7 +326,7 @@ export class GatewayActionImpl {new AgentStreamClient(options);/**- * Overridable seams for the multiplexed transport (lab `enableGatewayMux`):+ * Overridable seams for the multiplexed transport:* resolve the page-wide mux for an identity, then adapt one operation on it* to the v1 client surface.*/@@ -449,13 +467,12 @@ export class GatewayActionImpl {// Disconnect existing connection for this operation if anythis.disconnectFromGateway(operationId);- // Share visitors default to protocol v2 because the public surface does- // not inherit the creator's Labs preference. Owner runs keep the existing- // opt-in rollout: a connection keeps the transport it was opened with- // even if the toggle flips mid-run.+ // Share visitors take protocol v2 wherever the deployment has it: the+ // public surface has no user to carry a rollout flag. Owner runs wait for+ // the rollout to reach them.const muxIdentity: GatewayMuxIdentity = { agentShareId, gatewayUrl };const useGatewayMux =- (Boolean(agentShareId) || labPreferSelectors.enableGatewayMux(useUserStore.getState())) &&+ (agentShareId ? getGatewayServerConfig()?.agentGatewayProtocol === 2 : canUseGatewayMux()) &&!isGatewayMuxUnavailable(muxIdentity);let muxClient: OperationClient | undefined;if (useGatewayMux) {@@ -678,14 +695,15 @@ export class GatewayActionImpl {* has not disabled it. `disableGatewayMode: undefined` means enabled.*//**- * Dial the page-wide mux as soon as the user is in the app (lab- * `enableGatewayMux`), so the session's first run never pays the WebSocket- * handshake on its critical path — `connectToGateway` then only sends a- * `subscribe` frame on the already-open socket. No-op when gateway mode is- * off; safe to call repeatedly (`connect` is idempotent).+ * Dial the page-wide mux as soon as the user is in the app, so the session's+ * first run never pays the WebSocket handshake on its critical path —+ * `connectToGateway` then only sends a `subscribe` frame on the already-open+ * socket. No-op when gateway mode is off or this client may not use the+ * multiplexed transport (see `canUseGatewayMux`); safe to call repeatedly+ * (`connect` is idempotent).*/warmupGatewayMux = (): void => {- if (!labPreferSelectors.enableGatewayMux(useUserStore.getState())) return;+ if (!canUseGatewayMux()) return;const serverConfig = getGatewayServerConfig();if (!serverConfig?.agentGatewayUrl || !serverConfig.enableGatewayMode) return;diff --git a/src/store/chat/slices/agentRun/initialState.ts b/src/store/chat/slices/agentRun/initialState.tsindex 27fb8e54de8..447a7e71a12 100644--- a/src/store/chat/slices/agentRun/initialState.ts+++ b/src/store/chat/slices/agentRun/initialState.ts@@ -8,7 +8,7 @@ export type MainConversationScrollToIndex = (/*** Last `op_lifecycle` notice the shared gateway socket delivered for an- * operation. Written only when the `enableGatewayMux` lab flag routes runs+ * operation. Written only when the multiplexed transport routes runs* over the multiplexed socket; the hub emits one for every op the user owns,* whether or not this tab is subscribed to it.*/diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex 282bf07e281..e6cac9f6c60 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -15,7 +15,6 @@ export const labPreferSelectors = {enableDesktopSplitView: (s: UserState): boolean =>s.preference.lab?.enableDesktopSplitView ?? false,enableEvalCapture: (s: UserState): boolean => s.preference.lab?.enableEvalCapture ?? false,- enableGatewayMux: (s: UserState): boolean => s.preference.lab?.enableGatewayMux ?? false,enableHeteroSessionImport: (s: UserState): boolean =>s.preference.lab?.enableHeteroSessionImport ?? false,enableImessage: (s: UserState): boolean => s.preference.lab?.enableImessage ?? false,