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): one WebSocket per user — GatewayMuxClient behind a Labs toggle (#19557)

Arvin Xu7fa8666563e0
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index 36f985c67e9..110738d1b55 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -16,6 +16,8 @@
"features.desktopSplitView.title": "Split Tab View",
"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.json
index 675c0b76add..38d37a56671 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -16,6 +16,8 @@
"features.desktopSplitView.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/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.md
new file mode 100644
index 00000000000..f08467ef3f0
--- /dev/null
+++ b/packages/agent-gateway-client/PROTOCOL_V2.md
@@ -0,0 +1,288 @@
+# Agent Gateway protocol v2 — one WebSocket per user (multiplexed)
+
+Status: design contract shared by three codebases. Every implementer works from this file;
+if you must deviate, document the deviation at the top of your report.
+
+Repos:
+- `agent-gateway` (Cloudflare Worker, Durable Objects) — worktree `/Users/arvinxx/CodeProjects/LobeHub/agent-gateway-wt-user-hub`
+- `lobehub` server (`apps/server`) and client (`packages/agent-gateway-client`, `src/store/chat/.../gateway`) — worktree `/Users/arvinxx/CodeProjects/LobeHub/lobehub-wt-gateway-mux`
+
+## 0. Why
+
+Today: one `AgentOperationDO` per operation AND one browser WebSocket per operation
+(`GET /ws?operationId=`). N running ops in a tab ⇒ N sockets, each with its own heartbeat,
+backoff, JWT. Member / sub-agent ops are never subscribed (server-side `mirrorToOperationId`
+hack copies member events onto the supervisor channel).
+
+Target: per browser tab, ONE WebSocket to a per-user `UserHubDO`; every operation is
+multiplexed over it with explicit `subscribe`/`unsubscribe`. `AgentOperationDO` stays the
+single writer of op state (seq, buffer, watchdog, confirmation long-polls) and forwards to
+the hub. v1 (`/ws?operationId=`) stays fully working and byte-for-byte unchanged for legacy
+clients (web without the Labs flag, CLI, desktop).
+
+Non-goals for this iteration: SharedWorker cross-tab sharing; removing `mirrorToOperationId`
+/ `subagent_progress`; migrating CLI; removing v1.
+
+## 1. Topology
+
+```
+LobeHub server ── POST /api/operations/{init,push-event,tool-execute,...} ──▶ AgentOperationDO (session:${operationId})
+ │ internal DO→DO fetch
+ ▼
+Browser tab ──── GET /v2/ws?token=… ────────────────────────────────────▶ UserHubDO (user:${userId})
+```
+
+Bindings (wrangler.toml): add `USER_HUB` → class `UserHubDO`; migration tag `v3`
+`new_classes = ["UserHubDO"]`. `Env.USER_HUB: DurableObjectNamespace`.
+
+Hub id: `env.USER_HUB.idFromName(\`user:${userId}\`)` where `userId` is the JWT `sub`
+(for share visitors this is the visitor user id — the same value LobeHub sends as
+`streamOwnerUserId`/`userId` in `init`, so ownership checks line up unchanged).
+
+## 2. Worker routes (src/index.ts)
+
+Existing routes unchanged. New:
+
+- `GET /v2/ws` — browser WS upgrade. Auth happens **at upgrade time** (no in-socket `auth`
+ message in v2):
+ - `token` query param (required). `tokenType` (`jwt` default | `apiKey`) and `serverUrl`
+ optional, resolved with the existing `resolveSocketAuth` from `src/auth.ts`.
+ - On auth failure: accept the socket pair in the worker and immediately
+ `server.close(4401, reason)` (`'auth_expired'` when only `exp` failed, else
+ `'auth_failed'`). Rationale: browsers can't read HTTP status on WS failure; a close code
+ is the only reliable signal.
+ - On success: forward the upgrade to the hub stub with headers
+ `x-lobe-user-id`, `x-lobe-client-id` (optional `clientId` query, default a random id).
+- Hub internal routes (only reachable via DO stubs; not exposed on the worker):
+ see §4.
+
+## 3. AgentOperationDO changes (src/AgentOperationDO.ts)
+
+### 3.1 P0 fixes (independent value, land as their own commit)
+1. **Persist the sequence.** Replace in-memory `eventCounter` with storage key `seq`
+ (number). `nextEventId()` must be monotonic across eviction/hibernation: load `seq` lazily
+ in `blockConcurrencyWhile` on construction, increment in memory, and write it in the same
+ `storage.put({...})` batch as `lastEventAt`/`lastEventType` (one multi-key put per event
+ instead of two). Ids stay strings of integers.
+2. **Resume gap instead of full replay.** `handleResume`: if `lastEventId` is not in the
+ buffer and is non-empty: replay only events with numeric id > lastEventId (buffer is
+ ordered). If the buffer's first id > lastEventId+1 (or buffer empty while `seq` >
+ lastEventId), the client missed events that are gone ⇒ `resume_complete` carries
+ `gap: true`. Empty `lastEventId` = "from the beginning" (replay everything buffered;
+ `gap` true iff buffer doesn't start at id 1).
+3. **Tool result URL.** `_forwardToolResult` must use
+ `${LOBE_API_BASE_URL ?? DEFAULT_LOBE_API_BASE_URL}/api/agent/tool-result`.
+4. **Auth before init.** A v1 socket authenticating before `init` landed must not be
+ accepted as owner of anything: keep the socket open but mark the attachment
+ `pendingOwner: true`; when `init` lands, re-check `userId` and close mismatches with
+ 1008 `'userId mismatch'`. (Do not change the timing of `auth_success` for matching users.)
+5. Watchdog: `tool-execute` and `update-status` also `touchActivity`.
+6. `session_complete` is only broadcast for `completed`; `error`/`interrupted` endings send
+ `status_change` (they already do via `update-status`; align the `agent_runtime_end` path).
+ Keep sending BOTH `status_change` and then `session_complete` when status is `completed`
+ is NOT required — just `session_complete`. Legacy web client treats `session_complete`
+ as terminal regardless, so make sure `status_change{error|interrupted}` is followed by a
+ `session_complete` **for v1 sockets only** to preserve today's terminal semantics
+ (i.e. v1 wire behavior unchanged: v1 still gets `session_complete` for every ending; the
+ hub gets the precise status via lifecycle, §3.3).
+ ⇒ Simplest implementation: keep the v1 broadcast exactly as today, and add the precise
+ status in the lifecycle notification only.
+
+Leave `interrupt` as-is (documented no-op; the web client interrupts via tRPC). Do not
+attempt to implement it.
+
+### 3.2 Init metadata
+`POST /api/operations/init` body becomes
+```ts
+{ operationId, userId,
+ meta?: { topicId?, threadId?, agentId?, groupId?, taskId?, scope?,
+ parentOperationId?, mirrorToOperationId?, rootOperationId? } }
+```
+Persist `meta` (storage key `meta`). Unknown fields ignored. Missing `meta` is fine (legacy).
+
+### 3.3 Forwarding to the hub
+After `init` the op DO knows `userId` ⇒ `hub = env.USER_HUB.get(idFromName(\`user:${userId}\`))`.
+
+Two classes of forward, both `POST` to the hub stub (fire-and-forget via `waitUntil`, 5s
+timeout, errors logged, never fail the backend request):
+
+- **Lifecycle** (always): `POST /internal/op-lifecycle`
+ `{ operationId, userId, status, meta, at, summary? }` sent on: `init` (status `running`),
+ every stored status change (`update-status`, `agent_runtime_end`, watchdog), and on
+ cleanup (`status: 'gone'`).
+- **Stream** (only while `hubSubscribed === true`, a persisted boolean):
+ `POST /internal/op-event` `{ operationId, message }` where `message` is exactly the
+ `ServerMessage & {id}` that `broadcastAndBuffer` sends to v1 sockets
+ (`agent_event` / `session_complete` / `status_change` / `tool_confirmation_request` /
+ `input_request`). Response `{ delivered: number }`; if `delivered === 0` set
+ `hubSubscribed=false` (self-healing after hub eviction).
+
+Ordering: the hub is called from inside `broadcastAndBuffer` in id order, but forwards are
+async — include `id` and let the hub order by numeric id (it drops ids ≤ per-socket lastSeq).
+
+### 3.4 Internal routes on the op DO (called by the hub)
+- `POST /api/operations/hub-subscribe` `{}` → sets `hubSubscribed=true`, returns
+ `{ userId, status, meta, seq }`. (`userId` undefined ⇒ not inited yet.)
+- `POST /api/operations/hub-unsubscribe` `{}` → `hubSubscribed=false`.
+- `POST /api/operations/replay` `{ since: string }` → `{ events: BufferedEvent['data'][],
+ status?: SessionStatus, gap: boolean, seq: number }` — same semantics as §3.1.2.
+- `POST /api/operations/client-message` `{ message: ClientMessage, connectionId }` → the
+ op DO handles `tool_result` / `tool_confirmation` / `user_input` / `interrupt` exactly as
+ if they had arrived on a v1 socket (refactor the v1 `webSocketMessage` switch into a
+ shared `handleClientMessage(message, sender)` used by both paths).
+
+All `/api/operations/*` routes keep the existing `SERVICE_TOKEN` check at the worker; DO→DO
+stub calls bypass the worker so they need no token.
+
+## 4. UserHubDO (new file src/UserHubDO.ts)
+
+State:
+- storage `conn:${connectionId}` → `{ userId, clientId, connectedAt,
+ subs: Record<operationId, { lastSeq: number; executor: boolean; state: 'pending'|'replaying'|'live' }> }`
+ (subscriptions live in storage, NOT in the 2 KB socket attachment; attachment holds only
+ `{ connectionId, userId }`).
+- in-memory: per-(connection, op) live-event queue used while `replaying`.
+
+WebSocket handling (Hibernation API):
+- `acceptWebSocket(server, [userId, connectionId])` (tags!) so `getWebSockets(tag)` works.
+- `setWebSocketAutoResponse(new WebSocketRequestResponsePair('{"type":"heartbeat"}','{"type":"heartbeat_ack"}'))`
+ — heartbeats never wake the DO. Idle check alarm every 120s: close sockets whose
+ `ctx.getWebSocketAutoResponseTimestamp(ws)` (or connectedAt) is older than 180s.
+- On open send `ready { type:'ready', userId, connectionId, protocol: 2 }`.
+- `webSocketClose`/`webSocketError`: delete `conn:*`, decrement op refcounts; when an op has
+ no subscriber left across all connections, call op DO `hub-unsubscribe`.
+
+Client → hub messages (JSON, all carry `operationId` where relevant):
+```ts
+| { type:'subscribe'; operationId; lastEventId?: string; executor?: boolean }
+| { type:'unsubscribe'; operationId }
+| { type:'heartbeat' } // auto-answered
+| { type:'tool_result'; operationId; toolCallId; content; success; error?; state?; workRegistration? }
+| { type:'tool_confirmation'; operationId; toolCallId; approved }
+| { type:'user_input'; operationId; requestId; content }
+| { type:'interrupt'; operationId }
+```
+Hub → client messages:
+```ts
+| { type:'ready'; userId; connectionId; protocol: 2 }
+| { type:'agent_event'; operationId; id; event } // event.operationId may differ (mirrored member)
+| { type:'session_complete'; operationId; id; summary? }
+| { type:'status_change'; operationId; id; status }
+| { type:'tool_confirmation_request'; operationId; id; toolCallId; tool }
+| { type:'input_request'; operationId; id; requestId; prompt }
+| { type:'resume_complete'; operationId; status?: SessionStatus; gap: boolean; pending?: boolean }
+| { type:'subscribe_failed'; operationId; reason: 'forbidden' | 'invalid' }
+| { type:'op_lifecycle'; operationId; status: SessionStatus | 'gone'; meta?; at; summary? }
+| { type:'heartbeat_ack' }
+| { type:'error'; code; message; operationId? }
+```
+
+Subscribe algorithm (per connection, per op):
+1. Record sub `{ lastSeq: Number(lastEventId ?? 0), executor, state:'replaying' }`.
+2. Call op DO `hub-subscribe`. If it returns a `userId` that ≠ hub's userId ⇒
+ `subscribe_failed{forbidden}` and drop the sub. If `userId` is undefined (op not inited
+ yet — the init/subscribe race, LOBE-10443): keep the sub with `state:'pending'`, send
+ `resume_complete{ pending:true, gap:false }` and return; when an `op-lifecycle` with
+ status `running` arrives for that op, run steps 3-5 for every pending sub.
+3. Call op DO `replay{ since: String(lastSeq) }`; send each returned message (with
+ `operationId` added) in order, updating `lastSeq`.
+4. Flush the in-memory live queue for this (connection, op): send those with id > lastSeq.
+5. Send `resume_complete{ operationId, status, gap }`; state ⇒ `live`.
+
+Live delivery (`/internal/op-event`): for every connection subscribed to the op:
+`replaying` ⇒ enqueue; `live` ⇒ send if `Number(id) > lastSeq`, then set lastSeq.
+`agent_event` whose `event.type === 'tool_execute'` is delivered **only to subs with
+`executor:true`**; if no executor sub exists for the op, deliver to all subs (v1 parity).
+Return `{ delivered }` = number of sockets it was sent or queued to.
+
+Lifecycle delivery (`/internal/op-lifecycle`): broadcast `op_lifecycle` to every socket on
+the hub (the user-level feed). On `gone`, remove the op from all subs.
+
+Client messages that target an op: verify the connection is subscribed to it (else
+`error{code:'not_subscribed'}`), then forward to op DO `client-message`.
+
+## 5. LobeHub server (apps/server)
+
+1. `GatewayStreamNotifier.publishAgentRuntimeInit`: send `meta` (§3.2) in the `init` body,
+ taken from the op metadata already passed in (`topicId`, `threadId`, `agentId`,
+ `groupId`, `taskId`, `scope`, `parentOperationId`, `mirrorToOperationId`,
+ `rootOperationId` — only those that exist on the metadata; do not invent lookups).
+2. New tRPC procedures returning `{ token }` = `signUserJWT(<subject>)` (5m TTL, as today):
+ - `aiAgent.issueGatewayUserToken` — no input, subject `ctx.userId`.
+ - `shareChat.issueGatewayUserToken({ agentShareId })` — subject the visitor user id
+ resolved the same way `shareChat.refreshGatewayToken` resolves it (reuse its helper),
+ without requiring a running operation.
+ Keep `refreshGatewayToken` untouched (v1 path).
+3. `src/services/aiAgent.ts` `issueGatewayUserToken()` and `src/services/shareChat.ts`
+ `issueGatewayUserToken(agentShareId)` wrappers.
+4. Tests for both procedures and the init body.
+
+## 6. Client package (`packages/agent-gateway-client`)
+
+New `src/mux/` exporting `GatewayMuxClient` and `createOperationClient`:
+
+```ts
+interface GatewayMuxClientOptions {
+ gatewayUrl: string; // same base as v1; client appends /v2/ws
+ getToken: () => Promise<string>; // called before EVERY connect attempt
+ clientId?: string;
+ autoReconnect?: boolean; // default true
+ heartbeatIntervalMs?: number; // default 30_000, sends exactly {"type":"heartbeat"}
+}
+class GatewayMuxClient {
+ connect(): Promise<void>; disconnect(): void; // idempotent; refcount-free (owner decides)
+ readonly status: 'disconnected'|'connecting'|'connected';
+ subscribe(operationId, opts?: { lastEventId?: string; executor?: boolean }): OperationSubscription;
+ on(event: 'lifecycle'|'status_changed'|'error'|'connected'|'disconnected'|'reconnecting', cb): () => void;
+}
+interface OperationSubscription {
+ operationId: string;
+ on<K extends keyof AgentStreamClientEvents>(event: K, cb: AgentStreamClientEvents[K]): () => void;
+ // plus 'resume_complete': (info: { status?: SessionStatus; gap: boolean; pending?: boolean }) => void
+ sendToolResult(result: ToolResultPayload): boolean; // queued while disconnected, TTL 120s
+ sendInterrupt(): boolean;
+ unsubscribe(): void;
+}
+```
+
+Behavior:
+- Single socket; `subscribe` while disconnected triggers `connect()`; on (re)connect the
+ client re-sends `subscribe` for every live subscription with its per-op `lastEventId`.
+- Reconnect: exponential 1s→30s **with full jitter**; immediate reconnect on `online` and on
+ `visibilitychange` to visible when the socket is not open; close code 4401 ⇒ refresh token
+ (via `getToken`) then reconnect (count toward backoff after 3 consecutive 4401s ⇒ emit
+ `auth_failed` on every subscription and stop).
+- Dedup: per-op numeric `lastSeq`; drop messages with id ≤ lastSeq.
+- Terminal semantics per subscription mirror v1 `AgentStreamClient`: own
+ `agent_runtime_end`/`error` (event.operationId === sub op or absent) ⇒ emit
+ `session_complete{source:'agent_event'...}` (reuse the existing
+ `AgentStreamSessionCompletion` shape) and auto-unsubscribe; `session_complete` message ⇒
+ same; `resume_complete` with terminal status ⇒ `session_complete{source:'resume_status'}`;
+ `resume_complete{pending:true}` ⇒ keep waiting (emit `resume_complete` only).
+- `createOperationClient(mux, operationId, { resumeOnConnect?, lastEventId?, executor? })`
+ returns an object structurally compatible with the store's
+ `GatewayConnection['client']` Pick (`connect`, `disconnect`, `on`, `reconnect`,
+ `sendInterrupt`, `sendToolResult`, `updateToken`): `connect` = subscribe, `disconnect` =
+ unsubscribe, `reconnect` = unsubscribe+subscribe with lastEventId, `updateToken` = no-op
+ (token comes from `getToken`). Emits the same `AgentStreamClientEvents`
+ (`connected` when `resume_complete`/first event arrives or immediately if the socket is
+ open, `disconnected` on unsubscribe/socket loss, etc.).
+- Export protocol message types for v2 from `src/mux/types.ts`, and re-export from index.
+
+## 7. Store integration (`src/store/chat/slices/agentRun/actions/transports/gateway`)
+
+- Labs flag `enableGatewayMux` (labPrefer selector + `LAB_FEATURES` entry `gatewayMux`,
+ stage `alpha`, i18n `labs` namespace en-US + zh-CN).
+- `GatewayActionImpl.createClient(options, ctx)` — when the flag is on, return
+ `createOperationClient(getMux(identity), operationId, {...})` where `identity` is
+ `'owner'` (getToken = `aiAgentService.issueGatewayUserToken`) or `share:${agentShareId}`
+ (getToken = `shareChatService.issueGatewayUserToken(agentShareId)`); one
+ `GatewayMuxClient` per identity per page (module-level registry). Flag off ⇒ v1
+ `AgentStreamClient` exactly as today.
+- `resume_complete{gap:true}` ⇒ run the same DB refetch as the `notify_update` handler
+ (`fetchAndReplaceMessages`) for the op's topic.
+- The rest of `connectToGateway` / `reconnectToGatewayOperation` / event handler stays.
+- `executor: true` for subscriptions created by `executeGatewayAgent` (this tab started the
+ run); `false` for `reconnectToGatewayOperation`.
+- Mux-level `lifecycle` events: store them in a small slice `gatewayFeed[operationId] =
+ { status, meta, at }` (no UI yet; selector only) so later work can drive spinners/reconnect.
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index beb741b895a..b523d7cc38d 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -1,5 +1,44 @@
export { AgentStreamClient } from './client';
export { sanitizeAgentInterventionRequestForReview } from './intervention';
+export {
+ createOperationClient,
+ type OperationClient,
+ type OperationClientEvents,
+ type OperationClientOptions,
+} from './mux/createOperationClient';
+export { GatewayMuxClient } from './mux/GatewayMuxClient';
+export type {
+ GatewayMuxClientEvents,
+ GatewayMuxClientOptions,
+ GatewayMuxStatus,
+ MuxAgentEventMessage,
+ MuxClientMessage,
+ MuxErrorMessage,
+ MuxHeartbeatAckMessage,
+ MuxHeartbeatMessage,
+ MuxInputRequestMessage,
+ MuxInterruptMessage,
+ MuxOperationMessage,
+ MuxOperationMeta,
+ MuxOpLifecycleMessage,
+ MuxReadyMessage,
+ MuxResumeCompleteMessage,
+ MuxServerMessage,
+ MuxSessionCompleteMessage,
+ MuxStatusChangeMessage,
+ MuxSubscribeFailedMessage,
+ MuxSubscribeMessage,
+ MuxToolConfirmationMessage,
+ MuxToolConfirmationRequestMessage,
+ MuxToolResultMessage,
+ MuxUnsubscribeMessage,
+ MuxUserInputMessage,
+ OperationSubscribeOptions,
+ OperationSubscription,
+ OperationSubscriptionEvents,
+ ResumeCompleteInfo,
+ ToolResultPayload,
+} from './mux/types';
export type {
AgentInterventionInteractionKind,
AgentInterventionProvider,
@@ -14,11 +53,13 @@ export type {
AgentStreamEventType,
AgentStreamSessionCompletion,
ConnectionStatus,
+ SessionStatus,
StepCompleteData,
StreamChunkData,
StreamChunkType,
StreamStartData,
SubAgentProgressData,
+ TerminalSessionStatus,
ToolEndData,
ToolExecuteData,
ToolResultMessage,
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
new file mode 100644
index 00000000000..4257faafdd7
--- /dev/null
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
@@ -0,0 +1,914 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GatewayMuxClient } from './GatewayMuxClient';
+import type { GatewayMuxClientOptions, MuxServerMessage } from './types';
+
+// ─── Mock WebSocket ───
+
+class MockWebSocket {
+ static CONNECTING = 0;
+ static OPEN = 1;
+ static CLOSING = 2;
+ static CLOSED = 3;
+
+ readyState = MockWebSocket.CONNECTING;
+ onopen: ((ev: any) => void) | null = null;
+ onmessage: ((ev: any) => void) | null = null;
+ onclose: ((ev: any) => void) | null = null;
+ onerror: ((ev: any) => void) | null = null;
+
+ sent: string[] = [];
+ closedWith: { code?: number; reason?: string } | null = null;
+
+ constructor(public url: string) {
+ // Auto-connect in next tick
+ setTimeout(() => {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.({});
+ }, 0);
+ }
+
+ send(data: string): void {
+ this.sent.push(data);
+ }
+
+ close(code?: number, reason?: string): void {
+ this.closedWith = { code, reason };
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({ code: 1000, reason: '' });
+ }
+
+ // Test helpers
+ simulateMessage(data: MuxServerMessage): void {
+ this.onmessage?.({ data: JSON.stringify(data) });
+ }
+
+ simulateClose(code = 1006, reason = ''): void {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({ code, reason });
+ }
+
+ simulateError(): void {
+ this.onerror?.({});
+ }
+
+ get messages(): any[] {
+ return this.sent.map((s) => JSON.parse(s));
+ }
+
+ ofType(type: string): any[] {
+ return this.messages.filter((m) => m.type === type);
+ }
+}
+
+let mockWsInstances: MockWebSocket[] = [];
+/** Muxes created by the current test; torn down so their window listeners don't leak. */
+let muxes: GatewayMuxClient[] = [];
+
+beforeEach(() => {
+ mockWsInstances = [];
+ muxes = [];
+ vi.stubGlobal(
+ 'WebSocket',
+ Object.assign(
+ class extends MockWebSocket {
+ constructor(url: string) {
+ super(url);
+ mockWsInstances.push(this);
+ }
+ },
+ {
+ CLOSED: MockWebSocket.CLOSED,
+ CLOSING: MockWebSocket.CLOSING,
+ CONNECTING: MockWebSocket.CONNECTING,
+ OPEN: MockWebSocket.OPEN,
+ },
+ ),
+ );
+ vi.useFakeTimers();
+ // Full jitter: delay = floor(random * cap). Pin it so backoff is deterministic.
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+});
+
+afterEach(() => {
+ for (const mux of muxes) mux.disconnect();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const READY: MuxServerMessage = {
+ connectionId: 'conn-1',
+ protocol: 2,
+ type: 'ready',
+ userId: 'user-1',
+};
+
+function createMux(overrides?: Partial<GatewayMuxClientOptions>) {
+ const getToken = vi.fn(async () => 'tok');
+ const mux = new GatewayMuxClient({
+ clientId: 'cid',
+ gatewayUrl: 'https://gateway.test.com',
+ getToken,
+ ...overrides,
+ });
+ muxes.push(mux);
+ return { getToken, mux };
+}
+
+function getLatestWs(): MockWebSocket {
+ return mockWsInstances.at(-1)!;
+}
+
+/** Let `getToken` resolve and the mock socket open. */
+async function settle(): Promise<MockWebSocket> {
+ await vi.advanceTimersByTimeAsync(1);
+ return getLatestWs();
+}
+
+async function connectAndReady(mux: GatewayMuxClient): Promise<MockWebSocket> {
+ const pending = mux.connect();
+ const ws = await settle();
+ ws.simulateMessage(READY);
+ await pending;
+ return ws;
+}
+
+const agentEvent = (
+ operationId: string,
+ id: string,
+ type = 'stream_chunk',
+ eventOperationId = operationId,
+): MuxServerMessage => ({
+ event: { data: { id }, operationId: eventOperationId, stepIndex: 0, timestamp: 1, type } as any,
+ id,
+ operationId,
+ type: 'agent_event',
+});
+
+describe('GatewayMuxClient', () => {
+ describe('connection', () => {
+ it('dials /v2/ws with token and clientId, deriving wss from https', async () => {
+ const { mux } = createMux();
+ mux.connect().catch(() => {});
+ const ws = await settle();
+ expect(ws.url).toBe('wss://gateway.test.com/v2/ws?token=tok&clientId=cid');
+ });
+
+ it('derives ws from http and strips trailing slashes', async () => {
+ const { mux } = createMux({ gatewayUrl: 'http://localhost:8787/' });
+ mux.connect().catch(() => {});
+ const ws = await settle();
+ expect(ws.url).toBe('ws://localhost:8787/v2/ws?token=tok&clientId=cid');
+ });
+
+ it('awaits getToken before every connect attempt', async () => {
+ const { getToken, mux } = createMux();
+ mux.subscribe('op-1'); // a live subscription keeps the lazy mux redialing
+ const ws = await connectAndReady(mux);
+ expect(getToken).toHaveBeenCalledTimes(1);
+
+ ws.simulateClose();
+ await vi.advanceTimersByTimeAsync(500); // 0.5 * 1000ms cap
+ await settle();
+ expect(getToken).toHaveBeenCalledTimes(2);
+ expect(mockWsInstances).toHaveLength(2);
+ });
+
+ it('sends nothing until ready, then the subscribe for every pending subscription', async () => {
+ const { mux } = createMux();
+ const sub = mux.subscribe('op-1', { executor: true });
+ const onConnected = vi.fn();
+ sub.on('connected', onConnected);
+
+ const ws = await settle();
+ expect(ws.sent).toHaveLength(0);
+ expect(mux.status).toBe('connecting');
+
+ ws.simulateMessage(READY);
+ expect(mux.status).toBe('connected');
+ expect(ws.messages).toEqual([{ executor: true, operationId: 'op-1', type: 'subscribe' }]);
+ expect(onConnected).toHaveBeenCalledOnce();
+ });
+
+ it('connect() resolves on ready and is idempotent', async () => {
+ const { mux } = createMux();
+ const first = mux.connect();
+ const second = mux.connect();
+ const ws = await settle();
+ expect(mockWsInstances).toHaveLength(1);
+ ws.simulateMessage(READY);
+ await expect(first).resolves.toBeUndefined();
+ await expect(second).resolves.toBeUndefined();
+ await expect(mux.connect()).resolves.toBeUndefined();
+ expect(mockWsInstances).toHaveLength(1);
+ });
+
+ it('emits status_changed / connected / disconnected at the mux level', async () => {
+ const { mux } = createMux();
+ const statuses: string[] = [];
+ const onConnected = vi.fn();
+ const onDisconnected = vi.fn();
+ mux.on('status_changed', (s) => statuses.push(s));
+ mux.on('connected', onConnected);
+ mux.on('disconnected', onDisconnected);
+
+ await connectAndReady(mux);
+ expect(statuses).toEqual(['connecting', 'connected']);
+ expect(onConnected).toHaveBeenCalledOnce();
+
+ mux.disconnect();
+ expect(statuses).toEqual(['connecting', 'connected', 'disconnected']);
+ expect(onDisconnected).toHaveBeenCalledOnce();
+ expect(getLatestWs().closedWith?.code).toBe(1000);
+ });
+
+ it('does not reconnect after an intentional disconnect', async () => {
+ const { mux } = createMux();
+ mux.subscribe('op-1');
+ await connectAndReady(mux);
+ mux.disconnect();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mockWsInstances).toHaveLength(1);
+ });
+
+ it('surfaces a getToken failure as error and retries with backoff', async () => {
+ const getToken = vi
+ .fn<() => Promise<string>>()
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValue('tok');
+ const { mux } = createMux({ getToken });
+ const onError = vi.fn();
+ const onReconnecting = vi.fn();
+ mux.on('error', onError);
+ mux.on('reconnecting', onReconnecting);
+
+ mux.connect().catch(() => {});
+ await vi.advanceTimersByTimeAsync(1);
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }));
+ expect(onReconnecting).toHaveBeenCalledWith(500);
+ expect(mockWsInstances).toHaveLength(0);
+
+ await vi.advanceTimersByTimeAsync(500);
+ await settle();
+ expect(mockWsInstances).toHaveLength(1);
+ });
+ });
+
+ describe('subscribe message shape', () => {
+ it('includes lastEventId and executor only when set', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+
+ mux.subscribe('op-a');
+ mux.subscribe('op-b', { executor: true, lastEventId: '42' });
+
+ expect(ws.messages).toEqual([
+ { operationId: 'op-a', type: 'subscribe' },
+ { executor: true, lastEventId: '42', operationId: 'op-b', type: 'subscribe' },
+ ]);
+ });
+
+ it('sends unsubscribe when the last subscription for an op leaves', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const a = mux.subscribe('op-1');
+ const b = mux.subscribe('op-1');
+
+ a.unsubscribe();
+ expect(ws.ofType('unsubscribe')).toHaveLength(0);
+ b.unsubscribe();
+ expect(ws.ofType('unsubscribe')).toEqual([{ operationId: 'op-1', type: 'unsubscribe' }]);
+ });
+
+ it('closes an idle lazy mux after the last subscription ends and redials on the next subscribe', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+
+ sub.unsubscribe();
+ expect(ws.ofType('unsubscribe')).toHaveLength(1);
+ // The close is deferred a tick so unsubscribe+subscribe reuses the socket.
+ expect(ws.closedWith).toBeNull();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ws.closedWith).not.toBeNull();
+ expect(mux.status).toBe('disconnected');
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mockWsInstances).toHaveLength(1);
+
+ mux.subscribe('op-2');
+ const ws2 = await settle();
+ expect(mockWsInstances).toHaveLength(2);
+ ws2.simulateMessage(READY);
+ expect(ws2.ofType('subscribe')).toEqual([{ operationId: 'op-2', type: 'subscribe' }]);
+ });
+
+ it('does not redial an idle lazy mux that loses its socket', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ ws.simulateClose();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mockWsInstances).toHaveLength(1);
+ expect(mux.status).toBe('disconnected');
+ });
+
+ it('keeps a keepAlive mux up after the last subscription ends', async () => {
+ const { mux } = createMux({ keepAlive: true });
+ const ws = await connectAndReady(mux);
+ mux.subscribe('op-1').unsubscribe();
+ expect(ws.ofType('unsubscribe')).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ws.closedWith).toBeNull();
+ expect(mux.status).toBe('connected');
+ });
+
+ it('reuses the socket when a subscribe follows the last unsubscribe in the same tick', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ mux.subscribe('op-1').unsubscribe();
+ mux.subscribe('op-2');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ws.closedWith).toBeNull();
+ expect(mockWsInstances).toHaveLength(1);
+ expect(ws.ofType('subscribe').map((m: any) => m.operationId)).toEqual(['op-1', 'op-2']);
+ });
+ });
+
+ describe('routing and dedup', () => {
+ it('emits replay then live events in arrival order and drops ids ≤ lastSeq', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const seen: string[] = [];
+ const onResume = vi.fn();
+ const onComplete = vi.fn();
+ sub.on('agent_event', (e) => seen.push(e.data.id));
+ sub.on('resume_complete', onResume);
+ sub.on('session_complete', onComplete);
+
+ // replay
+ ws.simulateMessage(agentEvent('op-1', '1'));
+ ws.simulateMessage(agentEvent('op-1', '2'));
+ ws.simulateMessage({
+ gap: false,
+ operationId: 'op-1',
+ status: 'running',
+ type: 'resume_complete',
+ });
+ // live, including a duplicate that raced the resubscribe
+ ws.simulateMessage(agentEvent('op-1', '3'));
+ ws.simulateMessage(agentEvent('op-1', '2'));
+ ws.simulateMessage(agentEvent('op-1', '4'));
+
+ expect(seen).toEqual(['1', '2', '3', '4']);
+ expect(sub.lastEventId).toBe('4');
+ expect(onResume).toHaveBeenCalledWith({ gap: false, pending: undefined, status: 'running' });
+ expect(onComplete).not.toHaveBeenCalled();
+ });
+
+ it('drops replayed ids at or below the initial lastEventId', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1', { lastEventId: '5' });
+ const seen: string[] = [];
+ sub.on('agent_event', (e) => seen.push(e.data.id));
+
+ ws.simulateMessage(agentEvent('op-1', '5'));
+ ws.simulateMessage(agentEvent('op-1', '6'));
+ expect(seen).toEqual(['6']);
+ });
+
+ it('routes two subscriptions on one socket by operationId', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const a = mux.subscribe('op-a');
+ const b = mux.subscribe('op-b');
+ const seenA: string[] = [];
+ const seenB: string[] = [];
+ a.on('agent_event', (e) => seenA.push(e.data.id));
+ b.on('agent_event', (e) => seenB.push(e.data.id));
+
+ ws.simulateMessage(agentEvent('op-a', '1'));
+ ws.simulateMessage(agentEvent('op-b', '1'));
+ ws.simulateMessage(agentEvent('op-a', '2'));
+ ws.simulateMessage(agentEvent('op-unknown', '9'));
+
+ expect(mockWsInstances).toHaveLength(1);
+ expect(seenA).toEqual(['1', '2']);
+ expect(seenB).toEqual(['1']);
+ });
+
+ it('delivers a tool_execute only to the subscription the hub addressed', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const executor = mux.subscribe('op-1', { executor: true });
+ const viewer = mux.subscribe('op-2');
+ const onExecutor = vi.fn();
+ const onViewer = vi.fn();
+ executor.on('agent_event', onExecutor);
+ viewer.on('agent_event', onViewer);
+
+ ws.simulateMessage(agentEvent('op-1', '1', 'tool_execute'));
+
+ expect(onExecutor).toHaveBeenCalledOnce();
+ expect(onExecutor.mock.calls[0][0].type).toBe('tool_execute');
+ expect(onViewer).not.toHaveBeenCalled();
+ });
+
+ it('routes a hub error carrying operationId to that subscription', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const onSubError = vi.fn();
+ const onMuxError = vi.fn();
+ sub.on('error', onSubError);
+ mux.on('error', onMuxError);
+
+ ws.simulateMessage({
+ code: 'not_subscribed',
+ message: 'nope',
+ operationId: 'op-1',
+ type: 'error',
+ });
+ ws.simulateMessage({ code: 'bad_request', message: 'huh', type: 'error' });
+
+ expect(onSubError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'not_subscribed: nope' }),
+ );
+ expect(onMuxError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'bad_request: huh' }),
+ );
+ });
+
+ it('surfaces op_lifecycle at the mux level', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const onLifecycle = vi.fn();
+ mux.on('lifecycle', onLifecycle);
+
+ const lifecycle: MuxServerMessage = {
+ at: 123,
+ meta: { topicId: 'tpc' },
+ operationId: 'op-9',
+ status: 'running',
+ type: 'op_lifecycle',
+ };
+ ws.simulateMessage(lifecycle);
+ expect(onLifecycle).toHaveBeenCalledWith(lifecycle);
+ });
+ });
+
+ describe('terminal handling', () => {
+ const terminalCases: Array<{
+ completion: unknown;
+ message: MuxServerMessage;
+ name: string;
+ }> = [
+ {
+ completion: { source: 'agent_event' },
+ message: agentEvent('op-1', '3', 'agent_runtime_end'),
+ name: 'own agent_runtime_end',
+ },
+ {
+ completion: { source: 'agent_event' },
+ message: agentEvent('op-1', '3', 'error'),
+ name: 'own error event',
+ },
+ {
+ completion: { source: 'raw_session_complete' },
+ message: { id: '3', operationId: 'op-1', type: 'session_complete' },
+ name: 'session_complete',
+ },
+ {
+ completion: { source: 'resume_status', status: 'completed' },
+ message: { gap: false, operationId: 'op-1', status: 'completed', type: 'resume_complete' },
+ name: 'terminal resume_complete',
+ },
+ {
+ completion: { source: 'status_change', status: 'error' },
+ message: { id: '3', operationId: 'op-1', status: 'error', type: 'status_change' },
+ name: 'terminal status_change',
+ },
+ ];
+
+ for (const { completion, message, name } of terminalCases) {
+ it(`${name} emits session_complete, then disconnected, and auto-unsubscribes`, async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const order: string[] = [];
+ sub.on('agent_event', () => order.push('event'));
+ sub.on('session_complete', (c) => {
+ order.push('complete');
+ expect(c).toEqual(completion);
+ });
+ sub.on('disconnected', () => order.push('disconnected'));
+
+ ws.simulateMessage(message);
+
+ expect(order.filter((o) => o !== 'event')).toEqual(['complete', 'disconnected']);
+ expect(sub.active).toBe(false);
+ expect(ws.ofType('unsubscribe')).toEqual([{ operationId: 'op-1', type: 'unsubscribe' }]);
+ // Nothing else is delivered to a finished subscription.
+ const late = vi.fn();
+ sub.on('agent_event', late);
+ ws.simulateMessage(agentEvent('op-1', '4'));
+ expect(late).not.toHaveBeenCalled();
+ });
+ }
+
+ it('keeps waiting on resume_complete{pending:true}', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const onResume = vi.fn();
+ const onComplete = vi.fn();
+ sub.on('resume_complete', onResume);
+ sub.on('session_complete', onComplete);
+
+ ws.simulateMessage({
+ gap: false,
+ operationId: 'op-1',
+ pending: true,
+ type: 'resume_complete',
+ });
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ expect(onResume).toHaveBeenCalledWith({ gap: false, pending: true, status: undefined });
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(sub.active).toBe(true);
+ });
+
+ it('does not end on a running resume_complete or a non-terminal status_change', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const onStatus = vi.fn();
+ sub.on('status_change', onStatus);
+
+ ws.simulateMessage({
+ gap: true,
+ operationId: 'op-1',
+ status: 'running',
+ type: 'resume_complete',
+ });
+ ws.simulateMessage({
+ id: '1',
+ operationId: 'op-1',
+ status: 'waiting_input',
+ type: 'status_change',
+ });
+
+ expect(onStatus).toHaveBeenCalledWith('waiting_input');
+ expect(sub.active).toBe(true);
+ });
+
+ it('does NOT end on a mirrored member terminal for a different operationId', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const events: any[] = [];
+ sub.on('agent_event', (e) => events.push(e));
+
+ ws.simulateMessage(agentEvent('op-1', '1', 'agent_runtime_end', 'op-member'));
+ expect(events).toHaveLength(1);
+ expect(events[0].operationId).toBe('op-member');
+ expect(sub.active).toBe(true);
+
+ ws.simulateMessage(agentEvent('op-1', '2', 'agent_runtime_end'));
+ expect(sub.active).toBe(false);
+ });
+
+ it('subscribe_failed emits auth_failed and ends the subscription', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const onAuthFailed = vi.fn();
+ sub.on('auth_failed', onAuthFailed);
+
+ ws.simulateMessage({ operationId: 'op-1', reason: 'forbidden', type: 'subscribe_failed' });
+ expect(onAuthFailed).toHaveBeenCalledWith('forbidden');
+ expect(sub.active).toBe(false);
+ });
+
+ it('emits input_request and tool_confirmation_request on the subscription', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const onInput = vi.fn();
+ const onConfirm = vi.fn();
+ sub.on('input_request', onInput);
+ sub.on('tool_confirmation_request', onConfirm);
+
+ ws.simulateMessage({
+ id: '1',
+ operationId: 'op-1',
+ prompt: 'p',
+ requestId: 'r',
+ type: 'input_request',
+ });
+ ws.simulateMessage({
+ id: '2',
+ operationId: 'op-1',
+ tool: { name: 'x' },
+ toolCallId: 'c',
+ type: 'tool_confirmation_request',
+ });
+ expect(onInput).toHaveBeenCalledWith(expect.objectContaining({ requestId: 'r' }));
+ expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({ toolCallId: 'c' }));
+
+ sub.sendUserInput('r', 'hello');
+ sub.sendToolConfirmation('c', true);
+ expect(ws.ofType('user_input')).toEqual([
+ { content: 'hello', operationId: 'op-1', requestId: 'r', type: 'user_input' },
+ ]);
+ expect(ws.ofType('tool_confirmation')).toEqual([
+ { approved: true, operationId: 'op-1', toolCallId: 'c', type: 'tool_confirmation' },
+ ]);
+ });
+ });
+
+ describe('outbound op messages', () => {
+ it('sends tool_result and interrupt with the operationId', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+
+ expect(
+ sub.sendToolResult({ content: '{"ok":true}', success: true, toolCallId: 'call_1' }),
+ ).toBe(true);
+ expect(sub.sendInterrupt()).toBe(true);
+
+ expect(ws.ofType('tool_result')).toEqual([
+ {
+ content: '{"ok":true}',
+ operationId: 'op-1',
+ success: true,
+ toolCallId: 'call_1',
+ type: 'tool_result',
+ },
+ ]);
+ expect(ws.ofType('interrupt')).toEqual([{ operationId: 'op-1', type: 'interrupt' }]);
+ });
+
+ it('queues tool_result while disconnected and flushes after resubscribe', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ ws.simulateMessage(agentEvent('op-1', '7'));
+
+ ws.simulateClose();
+ expect(sub.sendToolResult({ content: 'late', success: true, toolCallId: 'call_1' })).toBe(
+ true,
+ );
+ expect(sub.sendInterrupt()).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(500);
+ const ws2 = await settle();
+ expect(ws2.sent).toHaveLength(0);
+ ws2.simulateMessage(READY);
+
+ expect(ws2.messages).toEqual([
+ { lastEventId: '7', operationId: 'op-1', type: 'subscribe' },
+ {
+ content: 'late',
+ operationId: 'op-1',
+ success: true,
+ toolCallId: 'call_1',
+ type: 'tool_result',
+ },
+ ]);
+ });
+
+ it('drops queued tool_result older than 120s', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+
+ ws.simulateClose();
+ sub.sendToolResult({ content: 'stale', success: true, toolCallId: 'call_old' });
+ // Keep the socket down past the TTL, then let it come back.
+ await vi.advanceTimersByTimeAsync(500);
+ const ws2 = await settle();
+ ws2.simulateClose();
+ await vi.advanceTimersByTimeAsync(121_000);
+ sub.sendToolResult({ content: 'fresh', success: true, toolCallId: 'call_new' });
+ await vi.advanceTimersByTimeAsync(30_000);
+ const ws3 = await settle();
+ ws3.simulateMessage(READY);
+
+ expect(ws3.ofType('tool_result').map((m) => m.toolCallId)).toEqual(['call_new']);
+ });
+
+ it('returns false for outbound messages on an ended subscription', async () => {
+ const { mux } = createMux();
+ await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ sub.unsubscribe();
+ expect(sub.sendToolResult({ content: null, success: false, toolCallId: 'x' })).toBe(false);
+ expect(sub.sendInterrupt()).toBe(false);
+ });
+ });
+
+ describe('reconnection', () => {
+ it('resubscribes every live subscription with its own lastEventId after reconnect', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const a = mux.subscribe('op-a', { executor: true });
+ mux.subscribe('op-b');
+ const done = mux.subscribe('op-done');
+ const statuses: string[] = [];
+ const onReconnecting = vi.fn();
+ a.on('status_changed', (s) => statuses.push(s));
+ a.on('reconnecting', onReconnecting);
+
+ ws.simulateMessage(agentEvent('op-a', '12'));
+ ws.simulateMessage(agentEvent('op-b', '3'));
+ ws.simulateMessage({ id: '1', operationId: 'op-done', type: 'session_complete' });
+ expect(done.active).toBe(false);
+
+ ws.simulateClose();
+ expect(statuses).toEqual(['reconnecting']);
+ expect(onReconnecting).toHaveBeenCalledWith(500);
+ expect(mux.status).toBe('connecting');
+
+ await vi.advanceTimersByTimeAsync(500);
+ const ws2 = await settle();
+ ws2.simulateMessage(READY);
+
+ expect(ws2.messages).toEqual([
+ { executor: true, lastEventId: '12', operationId: 'op-a', type: 'subscribe' },
+ { lastEventId: '3', operationId: 'op-b', type: 'subscribe' },
+ ]);
+ expect(statuses).toEqual(['reconnecting', 'connected']);
+ });
+
+ it('backs off exponentially with full jitter, capped at 30s, and resets on ready', async () => {
+ const { mux } = createMux();
+ const delays: number[] = [];
+ mux.on('reconnecting', (d) => delays.push(d));
+ mux.subscribe('op-1');
+ const ws = await connectAndReady(mux);
+
+ ws.simulateClose();
+ for (let i = 0; i < 7; i++) {
+ await vi.advanceTimersByTimeAsync(delays.at(-1)!);
+ (await settle()).simulateClose();
+ }
+ // random = 0.5 → half of cap: 1s, 2s, 4s, 8s, 16s, 30s(cap), 30s, 30s
+ expect(delays).toEqual([500, 1000, 2000, 4000, 8000, 15_000, 15_000, 15_000]);
+
+ await vi.advanceTimersByTimeAsync(15_000);
+ const wsN = await settle();
+ wsN.simulateMessage(READY);
+ wsN.simulateClose();
+ expect(delays.at(-1)).toBe(500);
+ });
+
+ it('reconnects immediately on window online while backing off', async () => {
+ const { mux } = createMux();
+ mux.subscribe('op-1');
+ const ws = await connectAndReady(mux);
+
+ ws.simulateClose();
+ window.dispatchEvent(new Event('online'));
+ await settle();
+ expect(mockWsInstances).toHaveLength(2);
+ });
+
+ it('reconnects when the tab becomes visible while backing off', async () => {
+ const { mux } = createMux();
+ mux.subscribe('op-1');
+ const ws = await connectAndReady(mux);
+
+ ws.simulateClose();
+ document.dispatchEvent(new Event('visibilitychange'));
+ await settle();
+ expect(mockWsInstances).toHaveLength(2);
+ });
+
+ it('redials on window online with zero subscriptions only when keepAlive is set', async () => {
+ const { mux: lazy } = createMux();
+ const wsLazy = await connectAndReady(lazy);
+ wsLazy.simulateClose();
+ window.dispatchEvent(new Event('online'));
+ await settle();
+ // The backoff timer still owns the redial; the immediate path is gated.
+ expect(mockWsInstances).toHaveLength(1);
+ lazy.disconnect();
+
+ const { mux: eager } = createMux({ keepAlive: true });
+ const wsEager = await connectAndReady(eager);
+ wsEager.simulateClose();
+ window.dispatchEvent(new Event('online'));
+ await settle();
+ expect(mockWsInstances).toHaveLength(3);
+ });
+
+ it('treats 3 missed heartbeat acks as a dead socket and reconnects', async () => {
+ const { mux } = createMux();
+ mux.subscribe('op-1');
+ const ws = await connectAndReady(mux);
+ const onReconnecting = vi.fn();
+ mux.on('reconnecting', onReconnecting);
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(ws.sent.at(-1)).toBe('{"type":"heartbeat"}');
+ ws.simulateMessage({ type: 'heartbeat_ack' });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(ws.ofType('heartbeat')).toHaveLength(2);
+ // No acks from now on: 3 more heartbeats go unanswered, the 4th tick gives up.
+ await vi.advanceTimersByTimeAsync(30_000 * 2);
+ expect(ws.ofType('heartbeat')).toHaveLength(4);
+ expect(onReconnecting).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(onReconnecting).toHaveBeenCalledOnce();
+ expect(ws.closedWith?.code).toBe(1000);
+ });
+
+ it('does not reconnect when autoReconnect is false', async () => {
+ const { mux } = createMux({ autoReconnect: false });
+ const sub = mux.subscribe('op-1');
+ const onDisconnected = vi.fn();
+ mux.on('disconnected', onDisconnected);
+ const statuses: string[] = [];
+ sub.on('status_changed', (s) => statuses.push(s));
+ const ws = await connectAndReady(mux);
+
+ ws.simulateClose();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mockWsInstances).toHaveLength(1);
+ expect(mux.status).toBe('disconnected');
+ expect(onDisconnected).toHaveBeenCalledOnce();
+ expect(statuses.at(-1)).toBe('disconnected');
+ });
+ });
+
+ describe('auth (close code 4401)', () => {
+ it('refreshes the token and reconnects immediately', async () => {
+ const getToken = vi.fn().mockResolvedValueOnce('expired').mockResolvedValue('fresh');
+ const { mux } = createMux({ getToken });
+ const onReconnecting = vi.fn();
+ mux.on('reconnecting', onReconnecting);
+ mux.subscribe('op-1');
+ const ws = await connectAndReady(mux);
+ expect(ws.url).toContain('token=expired');
+
+ ws.simulateClose(4401, 'auth_expired');
+ expect(onReconnecting).toHaveBeenCalledWith(0);
+ const ws2 = await settle();
+ expect(getToken).toHaveBeenCalledTimes(2);
+ expect(ws2.url).toContain('token=fresh');
+ });
+
+ it('gives up after 3 consecutive 4401s: auth_failed on every subscription, no more dials', async () => {
+ const { getToken, mux } = createMux();
+ const a = mux.subscribe('op-a');
+ const b = mux.subscribe('op-b');
+ const onAuthA = vi.fn();
+ const onAuthB = vi.fn();
+ const onDisconnected = vi.fn();
+ a.on('auth_failed', onAuthA);
+ b.on('auth_failed', onAuthB);
+ mux.on('disconnected', onDisconnected);
+
+ let ws = await connectAndReady(mux);
+ ws.simulateClose(4401, 'auth_failed');
+ ws = await settle();
+ ws.simulateClose(4401, 'auth_failed');
+ ws = await settle();
+ ws.simulateClose(4401, 'auth_failed');
+
+ expect(onAuthA).toHaveBeenCalledWith('auth_failed');
+ expect(onAuthB).toHaveBeenCalledWith('auth_failed');
+ expect(a.active).toBe(false);
+ expect(b.active).toBe(false);
+ expect(mux.status).toBe('disconnected');
+ expect(onDisconnected).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(getToken).toHaveBeenCalledTimes(3);
+ expect(mockWsInstances).toHaveLength(3);
+ });
+
+ it('resets the 4401 counter once a connection reaches ready', async () => {
+ const { mux } = createMux();
+ const sub = mux.subscribe('op-1');
+ const onAuth = vi.fn();
+ sub.on('auth_failed', onAuth);
+
+ let ws = await connectAndReady(mux);
+ ws.simulateClose(4401);
+ ws = await settle();
+ ws.simulateClose(4401);
+ ws = await settle();
+ ws.simulateMessage(READY);
+ ws.simulateClose(4401);
+ ws = await settle();
+ ws.simulateClose(4401);
+
+ expect(onAuth).not.toHaveBeenCalled();
+ expect(sub.active).toBe(true);
+ });
+ });
+});
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
new file mode 100644
index 00000000000..26fa37b2ae6
--- /dev/null
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
@@ -0,0 +1,814 @@
+import type {
+ AgentStreamEvent,
+ AgentStreamSessionCompletion,
+ ConnectionStatus,
+ SessionStatus,
+ TerminalSessionStatus,
+} from '../types';
+import type {
+ GatewayMuxClientEvents,
+ GatewayMuxClientOptions,
+ GatewayMuxStatus,
+ MuxClientMessage,
+ MuxOperationMessage,
+ MuxServerMessage,
+ MuxToolResultMessage,
+ OperationSubscribeOptions,
+ OperationSubscription,
+ OperationSubscriptionEvents,
+ ToolResultPayload,
+} from './types';
+
+// ─── Constants ───
+
+const DEFAULT_HEARTBEAT_INTERVAL = 30_000; // 30s
+const INITIAL_RECONNECT_DELAY = 1000; // 1s
+const MAX_RECONNECT_DELAY = 30_000; // 30s
+const MAX_MISSED_HEARTBEATS = 3;
+const MAX_CONSECUTIVE_AUTH_FAILURES = 3;
+const TOOL_RESULT_TTL = 120_000; // 120s
+const AUTH_CLOSE_CODE = 4401;
+/** Must match the hub's WebSocketRequestResponsePair byte-for-byte. */
+const HEARTBEAT_WIRE = '{"type":"heartbeat"}';
+
+const TERMINAL_STATUSES = new Set<SessionStatus>(['completed', 'error', 'interrupted']);
+
+const isTerminalStatus = (status?: SessionStatus): status is TerminalSessionStatus =>
+ !!status && TERMINAL_STATUSES.has(status);
+
+const randomClientId = (): string =>
+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
+ ? crypto.randomUUID()
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+
+// ─── Listener map (browser-compatible, no node:events) ───
+
+type Listener = (...args: any[]) => void;
+
+class ListenerMap {
+ private listeners = new Map<string, Set<Listener>>();
+
+ constructor(private readonly tag: string) {}
+
+ on(event: string, listener: Listener): () => void {
+ let set = this.listeners.get(event);
+ if (!set) {
+ set = new Set();
+ this.listeners.set(event, set);
+ }
+ set.add(listener);
+ return () => {
+ set.delete(listener);
+ };
+ }
+
+ emit(event: string, ...args: unknown[]): void {
+ const set = this.listeners.get(event);
+ if (!set) return;
+ for (const listener of set) {
+ try {
+ listener(...args);
+ } catch (error) {
+ console.error(`[${this.tag}] Error in ${event} listener:`, error);
+ }
+ }
+ }
+
+ clear(): void {
+ this.listeners.clear();
+ }
+}
+
+// ─── Operation subscription ───
+
+/**
+ * One operation's view over the shared socket. Owns the per-op sequence
+ * cursor (dedup + resubscribe cursor) and the v1-compatible terminal
+ * semantics: a terminal signal emits `session_complete`, then the
+ * subscription ends itself and emits `disconnected`.
+ */
+class OperationSubscriptionImpl implements OperationSubscription {
+ readonly operationId: string;
+ readonly executor: boolean;
+ private _active = true;
+ private _status: ConnectionStatus = 'connecting';
+ private _lastEventId: string;
+ private lastSeq: number;
+ private readonly listeners: ListenerMap;
+
+ constructor(
+ private readonly mux: GatewayMuxClient,
+ operationId: string,
+ options: OperationSubscribeOptions,
+ ) {
+ this.operationId = operationId;
+ this.executor = options.executor ?? false;
+ this._lastEventId = options.lastEventId ?? '';
+ this.lastSeq = Number(this._lastEventId) || 0;
+ this.listeners = new ListenerMap(`GatewayMuxClient:${operationId}`);
+ }
+
+ get active(): boolean {
+ return this._active;
+ }
+
+ get lastEventId(): string {
+ return this._lastEventId;
+ }
+
+ get status(): ConnectionStatus {
+ return this._status;
+ }
+
+ on<K extends keyof OperationSubscriptionEvents>(
+ event: K,
+ listener: OperationSubscriptionEvents[K],
+ ): () => void {
+ return this.listeners.on(event, listener as Listener);
+ }
+
+ sendToolResult(result: ToolResultPayload): boolean {
+ if (!this._active) return false;
+ return this.mux.sendForSubscription(this, {
+ ...result,
+ operationId: this.operationId,
+ type: 'tool_result',
+ });
+ }
+
+ sendInterrupt(): boolean {
+ if (!this._active) return false;
+ return this.mux.sendForSubscription(this, { operationId: this.operationId, type: 'interrupt' });
+ }
+
+ sendToolConfirmation(toolCallId: string, approved: boolean): boolean {
+ if (!this._active) return false;
+ return this.mux.sendForSubscription(this, {
+ approved,
+ operationId: this.operationId,
+ toolCallId,
+ type: 'tool_confirmation',
+ });
+ }
+
+ sendUserInput(requestId: string, content: string): boolean {
+ if (!this._active) return false;
+ return this.mux.sendForSubscription(this, {
+ content,
+ operationId: this.operationId,
+ requestId,
+ type: 'user_input',
+ });
+ }
+
+ unsubscribe(): void {
+ this.end();
+ }
+
+ // ─── Called by the mux ───
+
+ /** @internal */
+ emit<K extends keyof OperationSubscriptionEvents>(
+ event: K,
+ ...args: Parameters<OperationSubscriptionEvents[K]>
+ ): void {
+ if (!this._active) return;
+ this.listeners.emit(event, ...args);
+ }
+
+ /** @internal The hub rejected the subscription or the token was refused. */
+ fail(reason: string): void {
+ if (!this._active) return;
+ this.listeners.emit('auth_failed', reason);
+ this.end();
+ }
+
+ /** @internal */
+ handleMessage(message: MuxOperationMessage): void {
+ if (!this._active) return;
+
+ // Per-op numeric dedup: the hub may deliver an event twice across a
+ // reconnect (replay + a live copy that raced the resubscribe).
+ if ('id' in message) {
+ const seq = Number(message.id);
+ if (Number.isFinite(seq)) {
+ if (seq <= this.lastSeq) return;
+ this.lastSeq = seq;
+ this._lastEventId = message.id;
+ }
+ }
+
+ switch (message.type) {
+ case 'agent_event': {
+ const agentEvent: AgentStreamEvent = message.event;
+ // A member's mirrored terminal must not end the supervisor's
+ // subscription — only THIS op's terminal (or one with no operationId,
+ // legacy gateway) is terminal here. Mirrors v1 exactly.
+ const isOwnTerminal =
+ (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') &&
+ (!agentEvent.operationId || agentEvent.operationId === this.operationId);
+ this.listeners.emit('agent_event', agentEvent);
+ if (isOwnTerminal) this.finish({ source: 'agent_event' });
+ break;
+ }
+
+ case 'session_complete': {
+ this.finish({ source: 'raw_session_complete' });
+ break;
+ }
+
+ case 'status_change': {
+ this.listeners.emit('status_change', message.status);
+ if (isTerminalStatus(message.status)) {
+ this.finish({ source: 'status_change', status: message.status });
+ }
+ break;
+ }
+
+ case 'resume_complete': {
+ this.listeners.emit('resume_complete', {
+ gap: message.gap,
+ pending: message.pending,
+ status: message.status,
+ });
+ // `pending` = the op DO has not seen `init` yet; the hub replays later.
+ // Non-terminal status = the run is alive, keep streaming. Never guess
+ // completion from silence (see v1 AgentStreamClient).
+ if (!message.pending && isTerminalStatus(message.status)) {
+ this.finish({ source: 'resume_status', status: message.status });
+ }
+ break;
+ }
+
+ case 'tool_confirmation_request': {
+ this.listeners.emit('tool_confirmation_request', message);
+ break;
+ }
+
+ case 'input_request': {
+ this.listeners.emit('input_request', message);
+ break;
+ }
+
+ case 'subscribe_failed': {
+ this.fail(message.reason);
+ break;
+ }
+
+ case 'error': {
+ this.listeners.emit('error', new Error(`${message.code}: ${message.message}`));
+ break;
+ }
+ }
+ }
+
+ /** @internal Connection-level status fan-out. */
+ notifyStatus(status: ConnectionStatus): void {
+ if (!this._active || this._status === status) return;
+ this._status = status;
+ this.listeners.emit('status_changed', status);
+ }
+
+ // ─── Internals ───
+
+ private finish(completion: AgentStreamSessionCompletion): void {
+ if (!this._active) return;
+ this.listeners.emit('session_complete', completion);
+ this.end();
+ }
+
+ private end(): void {
+ if (!this._active) return;
+ this._active = false;
+ this.mux.removeSubscription(this);
+ if (this._status !== 'disconnected') {
+ this._status = 'disconnected';
+ this.listeners.emit('status_changed', 'disconnected');
+ }
+ this.listeners.emit('disconnected');
+ this.listeners.clear();
+ }
+}
+
+// ─── GatewayMuxClient ───
+
+/**
+ * One WebSocket per user (protocol v2). Every operation is multiplexed over
+ * it via `subscribe` / `unsubscribe`; the hub replays each op's missed events
+ * (from the per-op `lastEventId`) before `resume_complete`, so subscriptions
+ * emit in arrival order with no client-side resume buffering.
+ *
+ * Protocol reference: packages/agent-gateway-client/PROTOCOL_V2.md §4, §6.
+ */
+/**
+ * Linear-time trailing-slash strip (a `/\/+$/` regex is flagged as polynomial
+ * ReDoS on untrusted input by CodeQL, and the gateway URL comes from server
+ * config).
+ */
+const trimTrailingSlashes = (value: string): string => {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 47 /* '/' */) end--;
+ return value.slice(0, end);
+};
+
+const stripHttpScheme = (value: string): string => {
+ if (value.startsWith('https://')) return value.slice('https://'.length);
+ if (value.startsWith('http://')) return value.slice('http://'.length);
+ return value;
+};
+
+export class GatewayMuxClient {
+ private ws: WebSocket | null = null;
+ private _status: GatewayMuxStatus = 'disconnected';
+ private intentionalDisconnect = false;
+ private idleCloseTimer: ReturnType<typeof setTimeout> | null = null;
+ private connectGeneration = 0;
+ private connectInFlight = false;
+ private connectWaiters: Array<{ reject: (error: Error) => void; resolve: () => void }> = [];
+
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
+ private missedHeartbeats = 0;
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private reconnectAttempt = 0;
+ private consecutiveAuthFailures = 0;
+ private browserListenersInstalled = false;
+
+ private readonly subscriptions = new Map<string, Set<OperationSubscriptionImpl>>();
+ private toolResultQueue: Array<{
+ at: number;
+ message: MuxToolResultMessage;
+ subscription: OperationSubscriptionImpl;
+ }> = [];
+ private readonly listeners = new ListenerMap('GatewayMuxClient');
+
+ private readonly gatewayUrl: string;
+ private readonly getToken: () => Promise<string>;
+ private readonly clientId: string;
+ private readonly autoReconnect: boolean;
+ private readonly heartbeatIntervalMs: number;
+ private readonly keepAlive: boolean;
+
+ constructor(options: GatewayMuxClientOptions) {
+ this.gatewayUrl = options.gatewayUrl;
+ this.getToken = options.getToken;
+ this.clientId = options.clientId ?? randomClientId();
+ this.autoReconnect = options.autoReconnect ?? true;
+ this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL;
+ this.keepAlive = options.keepAlive ?? false;
+ }
+
+ // ─── Public API ───
+
+ get status(): GatewayMuxStatus {
+ return this._status;
+ }
+
+ on<K extends keyof GatewayMuxClientEvents>(
+ event: K,
+ listener: GatewayMuxClientEvents[K],
+ ): () => void {
+ return this.listeners.on(event, listener as Listener);
+ }
+
+ /**
+ * Open the socket (idempotent). Resolves once the hub's `ready` arrives;
+ * rejects if `disconnect()` is called or auth gives up before that.
+ */
+ connect(): Promise<void> {
+ this.clearIdleClose();
+ if (this._status === 'connected') return Promise.resolve();
+ this.intentionalDisconnect = false;
+ this.installBrowserListeners();
+ const promise = new Promise<void>((resolve, reject) => {
+ this.connectWaiters.push({ reject, resolve });
+ });
+ // A pending backoff timer already owns the next attempt; don't bypass it.
+ if (!this.ws && !this.connectInFlight && !this.reconnectTimer) void this.doConnect();
+ return promise;
+ }
+
+ /**
+ * Close the socket and stop reconnecting. Subscriptions are kept and are
+ * resubscribed on the next `connect()`; the owner decides their lifetime.
+ */
+ disconnect(): void {
+ this.intentionalDisconnect = true;
+ this.connectGeneration++;
+ this.connectInFlight = false;
+ this.cleanup();
+ this.setStatus('disconnected');
+ this.broadcastStatus('disconnected');
+ this.rejectWaiters(new Error('GatewayMuxClient disconnected'));
+ this.listeners.emit('disconnected');
+ }
+
+ /**
+ * Subscribe to one operation's stream. Connects the socket if needed; the
+ * `subscribe` message is (re)sent whenever the socket becomes ready.
+ */
+ subscribe(operationId: string, options: OperationSubscribeOptions = {}): OperationSubscription {
+ this.clearIdleClose();
+ const subscription = new OperationSubscriptionImpl(this, operationId, options);
+ let set = this.subscriptions.get(operationId);
+ if (!set) {
+ set = new Set();
+ this.subscriptions.set(operationId, set);
+ }
+ set.add(subscription);
+
+ if (this.isReady()) {
+ this.sendSubscribe(subscription);
+ } else {
+ subscription.notifyStatus(this.reconnectTimer ? 'reconnecting' : 'connecting');
+ this.connect().catch(() => {
+ // Surfaced through `auth_failed` / `error` listeners; nothing to do here.
+ });
+ }
+ return subscription;
+ }
+
+ // ─── Subscription callbacks (internal) ───
+
+ /** @internal */
+ removeSubscription(subscription: OperationSubscriptionImpl): void {
+ const set = this.subscriptions.get(subscription.operationId);
+ if (!set?.delete(subscription)) return;
+ this.toolResultQueue = this.toolResultQueue.filter(
+ (entry) => entry.subscription !== subscription,
+ );
+ if (set.size === 0) {
+ this.subscriptions.delete(subscription.operationId);
+ this.sendMessage({ operationId: subscription.operationId, type: 'unsubscribe' });
+ }
+ // A lazily-dialed mux has no reason to stay up once nothing is subscribed;
+ // the next `subscribe` redials. `keepAlive` muxes are owned by the page.
+ if (this.isIdle()) this.scheduleIdleClose();
+ }
+
+ /** Nothing subscribed, nobody awaiting `connect()`, and not asked to stay up. */
+ private isIdle(): boolean {
+ return !this.keepAlive && this.subscriptions.size === 0 && this.connectWaiters.length === 0;
+ }
+
+ /**
+ * Close on the next tick, not synchronously: an unsubscribe immediately
+ * followed by a subscribe (the adapter's `reconnect()`) must reuse the socket.
+ */
+ private scheduleIdleClose(): void {
+ if (this.idleCloseTimer) return;
+ this.idleCloseTimer = setTimeout(() => {
+ this.idleCloseTimer = null;
+ if (this.isIdle()) this.disconnect();
+ }, 0);
+ }
+
+ private clearIdleClose(): void {
+ if (this.idleCloseTimer) {
+ clearTimeout(this.idleCloseTimer);
+ this.idleCloseTimer = null;
+ }
+ }
+
+ /** @internal Send now, or queue `tool_result` (TTL 120s) until the socket is ready. */
+ sendForSubscription(subscription: OperationSubscriptionImpl, message: MuxClientMessage): boolean {
+ if (this.sendMessage(message)) return true;
+ if (message.type === 'tool_result') {
+ this.toolResultQueue.push({ at: Date.now(), message, subscription });
+ return true;
+ }
+ return false;
+ }
+
+ // ─── Connection logic ───
+
+ private async doConnect(): Promise<void> {
+ if (this.intentionalDisconnect || this.ws || this.connectInFlight) return;
+ const generation = ++this.connectGeneration;
+ this.connectInFlight = true;
+ this.clearReconnectTimer();
+ this.setStatus('connecting');
+
+ let token: string;
+ try {
+ token = await this.getToken();
+ } catch (error) {
+ if (generation !== this.connectGeneration) return;
+ this.connectInFlight = false;
+ this.listeners.emit(
+ 'error',
+ error instanceof Error ? error : new Error('Failed to obtain gateway token'),
+ );
+ this.handleConnectionLost();
+ return;
+ }
+ // `disconnect()` or a newer attempt superseded this one while awaiting.
+ if (generation !== this.connectGeneration) return;
+ this.connectInFlight = false;
+
+ try {
+ const ws = new WebSocket(this.buildWsUrl(token));
+ ws.onmessage = this.handleMessage;
+ ws.onclose = this.handleClose;
+ ws.onerror = this.handleError;
+ this.ws = ws;
+ } catch (error) {
+ console.error('[GatewayMuxClient] Failed to create WebSocket:', error);
+ this.handleConnectionLost();
+ }
+ }
+
+ private buildWsUrl(token: string): string {
+ const query = `token=${encodeURIComponent(token)}&clientId=${encodeURIComponent(this.clientId)}`;
+ // If the URL already has a ws/wss protocol, use it directly
+ if (this.gatewayUrl.startsWith('ws://') || this.gatewayUrl.startsWith('wss://')) {
+ return `${trimTrailingSlashes(this.gatewayUrl)}/v2/ws?${query}`;
+ }
+ // Otherwise convert http(s) to ws(s)
+ const wsProtocol = this.gatewayUrl.startsWith('https') ? 'wss' : 'ws';
+ const host = trimTrailingSlashes(stripHttpScheme(this.gatewayUrl));
+ return `${wsProtocol}://${host}/v2/ws?${query}`;
+ }
+
+ // ─── WebSocket event handlers ───
+
+ private handleMessage = (event: MessageEvent): void => {
+ let message: MuxServerMessage;
+ try {
+ message = JSON.parse(event.data as string) as MuxServerMessage;
+ } catch (error) {
+ console.error('[GatewayMuxClient] Failed to parse message:', error);
+ return;
+ }
+
+ switch (message.type) {
+ case 'ready': {
+ this.reconnectAttempt = 0;
+ this.consecutiveAuthFailures = 0;
+ this.setStatus('connected');
+ this.startHeartbeat();
+ // Subscribe before flushing: the hub rejects op messages from a
+ // connection that is not subscribed to the op.
+ for (const set of this.subscriptions.values()) {
+ for (const subscription of set) this.sendSubscribe(subscription);
+ }
+ this.flushToolResults();
+ this.listeners.emit('connected');
+ this.resolveWaiters();
+ break;
+ }
+
+ case 'heartbeat_ack': {
+ this.missedHeartbeats = 0;
+ break;
+ }
+
+ case 'op_lifecycle': {
+ this.listeners.emit('lifecycle', message);
+ break;
+ }
+
+ case 'error': {
+ const { operationId } = message;
+ if (operationId && this.subscriptions.has(operationId)) {
+ this.route({ ...message, operationId });
+ } else {
+ this.listeners.emit('error', new Error(`${message.code}: ${message.message}`));
+ }
+ break;
+ }
+
+ default: {
+ this.route(message);
+ }
+ }
+ };
+
+ private route(message: MuxOperationMessage): void {
+ const set = this.subscriptions.get(message.operationId);
+ if (!set) return;
+ // Copy: a terminal message removes the subscription mid-iteration.
+ for (const subscription of set) subscription.handleMessage(message);
+ }
+
+ private handleClose = (event: CloseEvent | undefined): void => {
+ this.stopHeartbeat();
+ this.ws = null;
+
+ if (this.intentionalDisconnect) return;
+
+ if (event?.code === AUTH_CLOSE_CODE) {
+ this.consecutiveAuthFailures++;
+ if (this.consecutiveAuthFailures >= MAX_CONSECUTIVE_AUTH_FAILURES) {
+ this.failAuth(event.reason || 'auth_failed');
+ return;
+ }
+ // Token refused: refresh it (getToken runs on every attempt) and retry now.
+ this.handleConnectionLost(0);
+ return;
+ }
+
+ this.handleConnectionLost();
+ };
+
+ private handleError = (): void => {
+ // The close event will follow; just emit the error
+ this.listeners.emit('error', new Error('Gateway WebSocket error'));
+ };
+
+ private handleConnectionLost(delayOverride?: number): void {
+ // An idle lazy mux that loses its socket just stays down (see isIdle).
+ if (this.autoReconnect && !this.intentionalDisconnect && !this.isIdle()) {
+ this.scheduleReconnect(delayOverride);
+ return;
+ }
+ this.setStatus('disconnected');
+ this.broadcastStatus('disconnected');
+ this.rejectWaiters(new Error('Gateway connection lost'));
+ this.listeners.emit('disconnected');
+ }
+
+ private failAuth(reason: string): void {
+ this.cleanup();
+ // Detach the subscriptions before failing them: `fail` unsubscribes, and an
+ // idle-close from `removeSubscription` must not race this teardown.
+ const failed = [...this.subscriptions.values()].flatMap((set) => [...set]);
+ this.subscriptions.clear();
+ for (const subscription of failed) subscription.fail(reason);
+ this.toolResultQueue = [];
+ this.setStatus('disconnected');
+ this.rejectWaiters(new Error(`Gateway auth failed: ${reason}`));
+ this.listeners.emit('disconnected');
+ }
+
+ // ─── Heartbeat ───
+
+ private startHeartbeat(): void {
+ this.stopHeartbeat();
+ this.missedHeartbeats = 0;
+ this.heartbeatTimer = setInterval(() => {
+ this.missedHeartbeats++;
+ if (this.missedHeartbeats > MAX_MISSED_HEARTBEATS) {
+ console.error(
+ `[GatewayMuxClient] Missed ${this.missedHeartbeats} heartbeat acks, forcing reconnect`,
+ );
+ this.stopHeartbeat();
+ this.closeWebSocket();
+ this.handleConnectionLost();
+ return;
+ }
+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(HEARTBEAT_WIRE);
+ }, this.heartbeatIntervalMs);
+ }
+
+ private stopHeartbeat(): void {
+ if (this.heartbeatTimer) {
+ clearInterval(this.heartbeatTimer);
+ this.heartbeatTimer = null;
+ }
+ }
+
+ // ─── Reconnection (exponential backoff with full jitter) ───
+
+ private scheduleReconnect(delayOverride?: number): void {
+ this.clearReconnectTimer();
+
+ const cap = Math.min(MAX_RECONNECT_DELAY, INITIAL_RECONNECT_DELAY * 2 ** this.reconnectAttempt);
+ const delay = delayOverride ?? Math.floor(Math.random() * cap);
+ this.reconnectAttempt++;
+
+ this.setStatus('connecting');
+ this.broadcastStatus('reconnecting');
+ this.listeners.emit('reconnecting', delay);
+ for (const set of this.subscriptions.values()) {
+ for (const subscription of set) subscription.emit('reconnecting', delay);
+ }
+
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = null;
+ void this.doConnect();
+ }, delay);
+ }
+
+ private clearReconnectTimer(): void {
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ }
+
+ /** `online` / tab-visible: skip the remaining backoff and dial now. */
+ private reconnectNow = (): void => {
+ if (this.intentionalDisconnect || !this.autoReconnect) return;
+ if (this.ws || this.connectInFlight) return;
+ if (!this.keepAlive && this.subscriptions.size === 0 && this.connectWaiters.length === 0)
+ return;
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
+ this.clearReconnectTimer();
+ void this.doConnect();
+ };
+
+ private installBrowserListeners(): void {
+ if (this.browserListenersInstalled) return;
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
+ window.addEventListener('online', this.reconnectNow);
+ }
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
+ document.addEventListener('visibilitychange', this.reconnectNow);
+ }
+ this.browserListenersInstalled = true;
+ }
+
+ private removeBrowserListeners(): void {
+ if (!this.browserListenersInstalled) return;
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
+ window.removeEventListener('online', this.reconnectNow);
+ }
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
+ document.removeEventListener('visibilitychange', this.reconnectNow);
+ }
+ this.browserListenersInstalled = false;
+ }
+
+ // ─── Status ───
+
+ private setStatus(status: GatewayMuxStatus): void {
+ if (this._status === status) return;
+ this._status = status;
+ this.listeners.emit('status_changed', status);
+ }
+
+ private broadcastStatus(status: ConnectionStatus): void {
+ for (const set of this.subscriptions.values()) {
+ for (const subscription of set) subscription.notifyStatus(status);
+ }
+ }
+
+ private resolveWaiters(): void {
+ const waiters = this.connectWaiters;
+ this.connectWaiters = [];
+ for (const waiter of waiters) waiter.resolve();
+ }
+
+ private rejectWaiters(error: Error): void {
+ const waiters = this.connectWaiters;
+ this.connectWaiters = [];
+ for (const waiter of waiters) waiter.reject(error);
+ }
+
+ // ─── Helpers ───
+
+ private isReady(): boolean {
+ return this._status === 'connected' && this.ws?.readyState === WebSocket.OPEN;
+ }
+
+ private sendSubscribe(subscription: OperationSubscriptionImpl): void {
+ const sent = this.sendMessage({
+ ...(subscription.executor ? { executor: true } : {}),
+ ...(subscription.lastEventId ? { lastEventId: subscription.lastEventId } : {}),
+ operationId: subscription.operationId,
+ type: 'subscribe',
+ });
+ if (!sent) return;
+ subscription.notifyStatus('connected');
+ subscription.emit('connected');
+ }
+
+ private flushToolResults(): void {
+ const queue = this.toolResultQueue;
+ this.toolResultQueue = [];
+ const now = Date.now();
+ for (const entry of queue) {
+ if (now - entry.at > TOOL_RESULT_TTL || !entry.subscription.active) continue;
+ if (!this.sendMessage(entry.message)) this.toolResultQueue.push(entry);
+ }
+ }
+
+ private sendMessage(data: MuxClientMessage): boolean {
+ if (this.isReady()) {
+ this.ws!.send(JSON.stringify(data));
+ return true;
+ }
+ return false;
+ }
+
+ private closeWebSocket(): void {
+ if (!this.ws) return;
+ // Remove handlers to prevent handleClose from firing after manual close
+ this.ws.onopen = null;
+ this.ws.onmessage = null;
+ this.ws.onclose = null;
+ this.ws.onerror = null;
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
+ this.ws.close(1000, 'Client disconnect');
+ }
+ this.ws = null;
+ }
+
+ private cleanup(): void {
+ this.clearIdleClose();
+ this.stopHeartbeat();
+ this.clearReconnectTimer();
+ this.removeBrowserListeners();
+ this.closeWebSocket();
+ }
+}
diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.test.ts b/packages/agent-gateway-client/src/mux/createOperationClient.test.ts
new file mode 100644
index 00000000000..bc92ea0922a
--- /dev/null
+++ b/packages/agent-gateway-client/src/mux/createOperationClient.test.ts
@@ -0,0 +1,412 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentStreamClient } from '../client';
+import type { ConnectionStatus } from '../types';
+import { createOperationClient } from './createOperationClient';
+import { GatewayMuxClient } from './GatewayMuxClient';
+import type { MuxServerMessage } from './types';
+
+// ─── Mock WebSocket ───
+
+class MockWebSocket {
+ static CONNECTING = 0;
+ static OPEN = 1;
+ static CLOSING = 2;
+ static CLOSED = 3;
+
+ readyState = MockWebSocket.CONNECTING;
+ onopen: ((ev: any) => void) | null = null;
+ onmessage: ((ev: any) => void) | null = null;
+ onclose: ((ev: any) => void) | null = null;
+ onerror: ((ev: any) => void) | null = null;
+
+ sent: string[] = [];
+
+ constructor(public url: string) {
+ setTimeout(() => {
+ this.readyState = MockWebSocket.OPEN;
+ this.onopen?.({});
+ }, 0);
+ }
+
+ send(data: string): void {
+ this.sent.push(data);
+ }
+
+ close(): void {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({ code: 1000, reason: '' });
+ }
+
+ simulateMessage(data: MuxServerMessage): void {
+ this.onmessage?.({ data: JSON.stringify(data) });
+ }
+
+ simulateClose(code = 1006, reason = ''): void {
+ this.readyState = MockWebSocket.CLOSED;
+ this.onclose?.({ code, reason });
+ }
+
+ get messages(): any[] {
+ return this.sent.map((s) => JSON.parse(s));
+ }
+
+ ofType(type: string): any[] {
+ return this.messages.filter((m) => m.type === type);
+ }
+}
+
+let mockWsInstances: MockWebSocket[] = [];
+/** Muxes created by the current test; torn down so their window listeners don't leak. */
+let muxes: GatewayMuxClient[] = [];
+
+beforeEach(() => {
+ mockWsInstances = [];
+ muxes = [];
+ vi.stubGlobal(
+ 'WebSocket',
+ Object.assign(
+ class extends MockWebSocket {
+ constructor(url: string) {
+ super(url);
+ mockWsInstances.push(this);
+ }
+ },
+ {
+ CLOSED: MockWebSocket.CLOSED,
+ CLOSING: MockWebSocket.CLOSING,
+ CONNECTING: MockWebSocket.CONNECTING,
+ OPEN: MockWebSocket.OPEN,
+ },
+ ),
+ );
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+});
+
+afterEach(() => {
+ for (const mux of muxes) mux.disconnect();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const READY: MuxServerMessage = {
+ connectionId: 'conn-1',
+ protocol: 2,
+ type: 'ready',
+ userId: 'user-1',
+};
+
+function createMux() {
+ const mux = new GatewayMuxClient({
+ clientId: 'cid',
+ gatewayUrl: 'https://gateway.test.com',
+ getToken: async () => 'tok',
+ });
+ muxes.push(mux);
+ return mux;
+}
+
+function getLatestWs(): MockWebSocket {
+ return mockWsInstances.at(-1)!;
+}
+
+async function settle(): Promise<MockWebSocket> {
+ await vi.advanceTimersByTimeAsync(1);
+ return getLatestWs();
+}
+
+async function readyMux(mux: GatewayMuxClient): Promise<MockWebSocket> {
+ const pending = mux.connect();
+ const ws = await settle();
+ ws.simulateMessage(READY);
+ await pending;
+ return ws;
+}
+
+const agentEvent = (
+ id: string,
+ type = 'stream_chunk',
+ eventOperationId = 'op-1',
+): MuxServerMessage => ({
+ event: { data: { id }, operationId: eventOperationId, stepIndex: 0, timestamp: 1, type } as any,
+ id,
+ operationId: 'op-1',
+ type: 'agent_event',
+});
+
+/** The store's `GatewayConnection['client']` contract (kept in sync by hand). */
+type StoreClient = Pick<
+ AgentStreamClient,
+ 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendInterrupt' | 'sendToolResult' | 'updateToken'
+>;
+
+describe('createOperationClient', () => {
+ it('is assignable to the store client Pick of AgentStreamClient', () => {
+ const client = createOperationClient(createMux(), 'op-1');
+ const storeClient: StoreClient = client;
+ expect(storeClient).toBe(client);
+ expect(typeof storeClient.connect).toBe('function');
+ expect(typeof storeClient.reconnect).toBe('function');
+ expect(typeof storeClient.sendToolResult).toBe('function');
+ });
+
+ it('connect() subscribes on a shared open socket and emits connecting → connected', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1', { executor: true, lastEventId: '4' });
+ const statuses: ConnectionStatus[] = [];
+ const onConnected = vi.fn();
+ client.on('status_changed', (s) => statuses.push(s));
+ client.on('connected', onConnected);
+
+ client.connect();
+ client.connect(); // idempotent while the subscription is live
+
+ expect(ws.ofType('subscribe')).toEqual([
+ { executor: true, lastEventId: '4', operationId: 'op-1', type: 'subscribe' },
+ ]);
+ expect(statuses).toEqual(['connected']);
+ expect(onConnected).toHaveBeenCalledOnce();
+ expect(client.connectionStatus).toBe('connected');
+ });
+
+ it('connect() before the socket is up dials once and connects when ready arrives', async () => {
+ const mux = createMux();
+ const client = createOperationClient(mux, 'op-1');
+ const statuses: ConnectionStatus[] = [];
+ client.on('status_changed', (s) => statuses.push(s));
+
+ client.connect();
+ expect(statuses).toEqual(['connecting']);
+ const ws = await settle();
+ ws.simulateMessage(READY);
+
+ expect(statuses).toEqual(['connecting', 'connected']);
+ expect(ws.ofType('subscribe')).toEqual([{ operationId: 'op-1', type: 'subscribe' }]);
+ });
+
+ it('forwards agent_event and resume_complete', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ const events: any[] = [];
+ const onResume = vi.fn();
+ client.on('agent_event', (e) => events.push(e));
+ client.on('resume_complete', onResume);
+ client.connect();
+
+ ws.simulateMessage(agentEvent('1'));
+ ws.simulateMessage({
+ gap: true,
+ operationId: 'op-1',
+ status: 'running',
+ type: 'resume_complete',
+ });
+
+ expect(events.map((e) => e.data.id)).toEqual(['1']);
+ expect(onResume).toHaveBeenCalledWith({ gap: true, pending: undefined, status: 'running' });
+ });
+
+ it('own terminal event emits session_complete then disconnected (v1 order) and unsubscribes', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ const order: string[] = [];
+ client.on('agent_event', (e) => order.push(`event:${e.type}`));
+ client.on('session_complete', (c) => order.push(`complete:${c.source}`));
+ client.on('status_changed', (s) => order.push(`status:${s}`));
+ client.on('disconnected', () => order.push('disconnected'));
+ client.connect();
+
+ ws.simulateMessage(agentEvent('1', 'agent_runtime_end', 'op-member'));
+ ws.simulateMessage(agentEvent('2', 'agent_runtime_end'));
+
+ expect(order).toEqual([
+ 'status:connected',
+ 'event:agent_runtime_end',
+ 'event:agent_runtime_end',
+ 'complete:agent_event',
+ 'status:disconnected',
+ 'disconnected',
+ ]);
+ expect(ws.ofType('unsubscribe')).toEqual([{ operationId: 'op-1', type: 'unsubscribe' }]);
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
+ it('session_complete and terminal resume_complete keep the v1 completion shapes', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+
+ const raw = createOperationClient(mux, 'op-1');
+ const onRaw = vi.fn();
+ raw.on('session_complete', onRaw);
+ raw.connect();
+ ws.simulateMessage({ id: '1', operationId: 'op-1', type: 'session_complete' });
+ expect(onRaw).toHaveBeenCalledWith({ source: 'raw_session_complete' });
+
+ const resumed = createOperationClient(mux, 'op-2');
+ const onResumed = vi.fn();
+ resumed.on('session_complete', onResumed);
+ resumed.connect();
+ ws.simulateMessage({
+ gap: false,
+ operationId: 'op-2',
+ status: 'interrupted',
+ type: 'resume_complete',
+ });
+ expect(onResumed).toHaveBeenCalledWith({ source: 'resume_status', status: 'interrupted' });
+ });
+
+ it('disconnect() unsubscribes and emits disconnected like v1', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ const onDisconnected = vi.fn();
+ const onComplete = vi.fn();
+ client.on('disconnected', onDisconnected);
+ client.on('session_complete', onComplete);
+ client.connect();
+
+ client.disconnect();
+ expect(ws.ofType('unsubscribe')).toEqual([{ operationId: 'op-1', type: 'unsubscribe' }]);
+ expect(onDisconnected).toHaveBeenCalledOnce();
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(client.connectionStatus).toBe('disconnected');
+
+ // Late messages for the old subscription are ignored.
+ const late = vi.fn();
+ client.on('agent_event', late);
+ ws.simulateMessage(agentEvent('1'));
+ expect(late).not.toHaveBeenCalled();
+ });
+
+ it('reconnect() resubscribes from the last applied event id without emitting disconnected', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1', { executor: true });
+ const onDisconnected = vi.fn();
+ const events: string[] = [];
+ client.on('disconnected', onDisconnected);
+ client.on('agent_event', (e) => events.push(e.data.id));
+ client.connect();
+ ws.simulateMessage(agentEvent('9'));
+
+ client.updateToken('ignored'); // no-op in v2: the mux refreshes via getToken
+ await client.reconnect();
+
+ expect(ws.messages).toEqual([
+ { executor: true, operationId: 'op-1', type: 'subscribe' },
+ { operationId: 'op-1', type: 'unsubscribe' },
+ { executor: true, lastEventId: '9', operationId: 'op-1', type: 'subscribe' },
+ ]);
+ expect(onDisconnected).not.toHaveBeenCalled();
+
+ // The new subscription streams and dedups against the carried-over cursor.
+ ws.simulateMessage(agentEvent('9'));
+ ws.simulateMessage(agentEvent('10'));
+ expect(events).toEqual(['9', '10']);
+ });
+
+ it('connect() after a terminal completion resubscribes from the last event id', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ client.connect();
+ ws.simulateMessage(agentEvent('3', 'agent_runtime_end'));
+
+ client.connect();
+ expect(ws.ofType('subscribe')).toEqual([
+ { operationId: 'op-1', type: 'subscribe' },
+ { lastEventId: '3', operationId: 'op-1', type: 'subscribe' },
+ ]);
+ });
+
+ it('sendToolResult / sendInterrupt go out with the operationId; false before connect', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+
+ expect(client.sendToolResult({ content: null, success: false, toolCallId: 'x' })).toBe(false);
+
+ client.connect();
+ expect(client.sendToolResult({ content: '{"a":1}', success: true, toolCallId: 'call_1' })).toBe(
+ true,
+ );
+ client.sendInterrupt();
+
+ expect(ws.ofType('tool_result')).toEqual([
+ {
+ content: '{"a":1}',
+ operationId: 'op-1',
+ success: true,
+ toolCallId: 'call_1',
+ type: 'tool_result',
+ },
+ ]);
+ expect(ws.ofType('interrupt')).toEqual([{ operationId: 'op-1', type: 'interrupt' }]);
+ });
+
+ it('socket loss surfaces reconnecting, not disconnected; resubscribes after reconnect', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ const statuses: ConnectionStatus[] = [];
+ const onDisconnected = vi.fn();
+ const onReconnecting = vi.fn();
+ client.on('status_changed', (s) => statuses.push(s));
+ client.on('disconnected', onDisconnected);
+ client.on('reconnecting', onReconnecting);
+ client.connect();
+ ws.simulateMessage(agentEvent('5'));
+
+ ws.simulateClose();
+ expect(onReconnecting).toHaveBeenCalledWith(500);
+ expect(onDisconnected).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(500);
+ const ws2 = await settle();
+ ws2.simulateMessage(READY);
+
+ expect(statuses).toEqual(['connected', 'reconnecting', 'connected']);
+ expect(ws2.ofType('subscribe')).toEqual([
+ { lastEventId: '5', operationId: 'op-1', type: 'subscribe' },
+ ]);
+ });
+
+ it('forwards auth_failed after the mux gives up on 4401', async () => {
+ const mux = createMux();
+ const client = createOperationClient(mux, 'op-1');
+ const onAuthFailed = vi.fn();
+ const onDisconnected = vi.fn();
+ client.on('auth_failed', onAuthFailed);
+ client.on('disconnected', onDisconnected);
+ client.connect();
+
+ let ws = await settle();
+ ws.simulateClose(4401, 'auth_failed');
+ ws = await settle();
+ ws.simulateClose(4401, 'auth_failed');
+ ws = await settle();
+ ws.simulateClose(4401, 'auth_failed');
+
+ expect(onAuthFailed).toHaveBeenCalledWith('auth_failed');
+ expect(onDisconnected).toHaveBeenCalledOnce();
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
+ it('on() returns an unsubscribe function', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ const listener = vi.fn();
+ const off = client.on('agent_event', listener);
+ client.connect();
+
+ ws.simulateMessage(agentEvent('1'));
+ off();
+ ws.simulateMessage(agentEvent('2'));
+ expect(listener).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.ts b/packages/agent-gateway-client/src/mux/createOperationClient.ts
new file mode 100644
index 00000000000..3ee333b6624
--- /dev/null
+++ b/packages/agent-gateway-client/src/mux/createOperationClient.ts
@@ -0,0 +1,166 @@
+import type { AgentStreamClientEvents, ConnectionStatus } from '../types';
+import type { GatewayMuxClient } from './GatewayMuxClient';
+import type { OperationSubscription, ResumeCompleteInfo, ToolResultPayload } from './types';
+
+export interface OperationClientEvents extends AgentStreamClientEvents {
+ resume_complete: (info: ResumeCompleteInfo) => void;
+}
+
+export interface OperationClientOptions {
+ /** This tab started the run and executes its local `tool_execute` requests. */
+ executor?: boolean;
+ /** Last applied event id; the hub replays only newer events on subscribe. */
+ lastEventId?: string;
+ /**
+ * Accepted for v1 option parity only. The hub orders the replay before
+ * `resume_complete`, so no client-side buffering is needed.
+ */
+ resumeOnConnect?: boolean;
+}
+
+/**
+ * Structurally compatible with the store's
+ * `Pick<AgentStreamClient, 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendInterrupt' | 'sendToolResult' | 'updateToken'>`.
+ */
+export interface OperationClient {
+ /** Subscribe this operation on the shared socket (idempotent while active). */
+ connect: () => void;
+ readonly connectionStatus: ConnectionStatus;
+ /** Unsubscribe; emits `disconnected` like v1. */
+ disconnect: () => void;
+ on: <K extends keyof OperationClientEvents>(
+ event: K,
+ listener: OperationClientEvents[K],
+ ) => () => void;
+ /** Unsubscribe + resubscribe from the last applied event id. */
+ reconnect: () => Promise<void>;
+ sendInterrupt: () => void;
+ sendToolResult: (result: ToolResultPayload) => boolean;
+ /** No-op: the mux fetches a fresh token via `getToken` on every dial. */
+ updateToken: (token: string) => void;
+}
+
+const FORWARDED_EVENTS: Array<keyof OperationClientEvents> = [
+ 'agent_event',
+ 'auth_expired',
+ 'auth_failed',
+ 'connected',
+ 'disconnected',
+ 'error',
+ 'reconnecting',
+ 'resume_complete',
+ 'session_complete',
+ 'status_changed',
+];
+
+type Listener = (...args: any[]) => void;
+
+/**
+ * Adapt one operation on a `GatewayMuxClient` to the v1 `AgentStreamClient`
+ * surface so the store can swap transports without changing its handlers.
+ */
+export const createOperationClient = (
+ mux: GatewayMuxClient,
+ operationId: string,
+ options: OperationClientOptions = {},
+): OperationClient => {
+ const listeners = new Map<string, Set<Listener>>();
+ let subscription: OperationSubscription | null = null;
+ let detach: (() => void) | null = null;
+ let lastEventId = options.lastEventId ?? '';
+ let status: ConnectionStatus = 'disconnected';
+
+ const emit = (event: string, ...args: unknown[]): void => {
+ const set = listeners.get(event);
+ if (!set) return;
+ for (const listener of set) {
+ try {
+ listener(...args);
+ } catch (error) {
+ console.error(`[OperationClient:${operationId}] Error in ${event} listener:`, error);
+ }
+ }
+ };
+
+ const bind = (sub: OperationSubscription): void => {
+ const offs = FORWARDED_EVENTS.map((event) =>
+ sub.on(event, ((...args: unknown[]) => {
+ if (event === 'status_changed') status = args[0] as ConnectionStatus;
+ emit(event, ...args);
+ // A terminal signal ends the subscription; forget it so `connect()`
+ // can subscribe again from the last applied event id.
+ if (event === 'disconnected' && subscription === sub) {
+ lastEventId = sub.lastEventId || lastEventId;
+ subscription = null;
+ detach = null;
+ }
+ }) as Listener),
+ );
+ detach = () => {
+ for (const off of offs) off();
+ };
+ };
+
+ /** Drop the live subscription without surfacing `disconnected` (v1 `reconnect()` parity). */
+ const release = (): void => {
+ if (!subscription) return;
+ detach?.();
+ lastEventId = subscription.lastEventId || lastEventId;
+ const sub = subscription;
+ subscription = null;
+ detach = null;
+ sub.unsubscribe();
+ };
+
+ const connect = (): void => {
+ if (subscription?.active) return;
+ const sub = mux.subscribe(operationId, {
+ executor: options.executor,
+ ...(lastEventId ? { lastEventId } : {}),
+ });
+ subscription = sub;
+ bind(sub);
+ // `subscribe()` already emitted its initial state before we could listen;
+ // replay it so the store sees connecting → connected like v1.
+ if (sub.status !== status) {
+ status = sub.status;
+ emit('status_changed', status);
+ }
+ if (sub.status === 'connected') emit('connected');
+ };
+
+ return {
+ get connectionStatus() {
+ return status;
+ },
+ connect,
+ disconnect: () => {
+ release();
+ if (status !== 'disconnected') {
+ status = 'disconnected';
+ emit('status_changed', status);
+ }
+ emit('disconnected');
+ },
+ on: (event, listener) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener as Listener);
+ return () => {
+ set.delete(listener as Listener);
+ };
+ },
+ reconnect: async () => {
+ release();
+ connect();
+ },
+ sendInterrupt: () => {
+ subscription?.sendInterrupt();
+ },
+ sendToolResult: (result) => subscription?.sendToolResult(result) ?? false,
+ updateToken: () => {},
+ };
+};
diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.ts
new file mode 100644
index 00000000000..d62e013a4d2
--- /dev/null
+++ b/packages/agent-gateway-client/src/mux/types.ts
@@ -0,0 +1,253 @@
+import type {
+ AgentStreamClientEvents,
+ AgentStreamEvent,
+ ConnectionStatus,
+ SessionStatus,
+ ToolResultMessage,
+} from '../types';
+
+// ─── Protocol v2: Client → Hub ───
+
+export interface MuxSubscribeMessage {
+ executor?: boolean;
+ lastEventId?: string;
+ operationId: string;
+ type: 'subscribe';
+}
+
+export interface MuxUnsubscribeMessage {
+ operationId: string;
+ type: 'unsubscribe';
+}
+
+/** Auto-answered by the hub's WebSocket auto-response pair; never wakes the DO. */
+export interface MuxHeartbeatMessage {
+ type: 'heartbeat';
+}
+
+export interface MuxToolResultMessage extends Omit<ToolResultMessage, 'type'> {
+ operationId: string;
+ type: 'tool_result';
+}
+
+export interface MuxToolConfirmationMessage {
+ approved: boolean;
+ operationId: string;
+ toolCallId: string;
+ type: 'tool_confirmation';
+}
+
+export interface MuxUserInputMessage {
+ content: string;
+ operationId: string;
+ requestId: string;
+ type: 'user_input';
+}
+
+export interface MuxInterruptMessage {
+ operationId: string;
+ type: 'interrupt';
+}
+
+export type MuxClientMessage =
+ | MuxHeartbeatMessage
+ | MuxInterruptMessage
+ | MuxSubscribeMessage
+ | MuxToolConfirmationMessage
+ | MuxToolResultMessage
+ | MuxUnsubscribeMessage
+ | MuxUserInputMessage;
+
+// ─── Protocol v2: Hub → Client ───
+
+export interface MuxReadyMessage {
+ connectionId: string;
+ protocol: 2;
+ type: 'ready';
+ userId: string;
+}
+
+export interface MuxAgentEventMessage {
+ /** `event.operationId` may differ from `operationId` (mirrored member event). */
+ event: AgentStreamEvent;
+ id: string;
+ operationId: string;
+ type: 'agent_event';
+}
+
+export interface MuxSessionCompleteMessage {
+ id: string;
+ operationId: string;
+ summary?: unknown;
+ type: 'session_complete';
+}
+
+export interface MuxStatusChangeMessage {
+ id: string;
+ operationId: string;
+ status: SessionStatus;
+ type: 'status_change';
+}
+
+export interface MuxToolConfirmationRequestMessage {
+ id: string;
+ operationId: string;
+ tool: unknown;
+ toolCallId: string;
+ type: 'tool_confirmation_request';
+}
+
+export interface MuxInputRequestMessage {
+ id: string;
+ operationId: string;
+ prompt: unknown;
+ requestId: string;
+ type: 'input_request';
+}
+
+export interface MuxResumeCompleteMessage {
+ gap: boolean;
+ operationId: string;
+ /** The op DO has not received `init` yet; the hub will replay once it does. */
+ pending?: boolean;
+ status?: SessionStatus;
+ type: 'resume_complete';
+}
+
+export interface MuxSubscribeFailedMessage {
+ operationId: string;
+ reason: 'forbidden' | 'invalid';
+ type: 'subscribe_failed';
+}
+
+export interface MuxOperationMeta {
+ agentId?: string;
+ groupId?: string;
+ mirrorToOperationId?: string;
+ parentOperationId?: string;
+ rootOperationId?: string;
+ scope?: string;
+ taskId?: string;
+ threadId?: string;
+ topicId?: string;
+}
+
+export interface MuxOpLifecycleMessage {
+ at: number;
+ meta?: MuxOperationMeta;
+ operationId: string;
+ status: SessionStatus | 'gone';
+ summary?: unknown;
+ type: 'op_lifecycle';
+}
+
+export interface MuxHeartbeatAckMessage {
+ type: 'heartbeat_ack';
+}
+
+export interface MuxErrorMessage {
+ code: string;
+ message: string;
+ operationId?: string;
+ type: 'error';
+}
+
+export type MuxServerMessage =
+ | MuxAgentEventMessage
+ | MuxErrorMessage
+ | MuxHeartbeatAckMessage
+ | MuxInputRequestMessage
+ | MuxOpLifecycleMessage
+ | MuxReadyMessage
+ | MuxResumeCompleteMessage
+ | MuxSessionCompleteMessage
+ | MuxStatusChangeMessage
+ | MuxSubscribeFailedMessage
+ | MuxToolConfirmationRequestMessage;
+
+/** Hub → client messages that are addressed to one operation subscription. */
+export type MuxOperationMessage =
+ | Exclude<Extract<MuxServerMessage, { operationId: string }>, MuxOpLifecycleMessage>
+ | (MuxErrorMessage & { operationId: string });
+
+// ─── Client options ───
+
+export interface GatewayMuxClientOptions {
+ /** Auto-reconnect with per-op lastEventId resubscribe (default: true) */
+ autoReconnect?: boolean;
+ /** Stable id for this tab; the hub tags the connection with it. Random when omitted. */
+ clientId?: string;
+ /** Gateway URL base (e.g. https://gateway.lobehub.com); the client appends `/v2/ws`. */
+ gatewayUrl: string;
+ /** Called before EVERY connect attempt; must return a fresh user JWT. */
+ getToken: () => Promise<string>;
+ /** Heartbeat period in ms (default: 30_000). Sends exactly `{"type":"heartbeat"}`. */
+ heartbeatIntervalMs?: number;
+ /**
+ * Keep the socket up even while nothing is subscribed (default: false).
+ * Off: the socket is closed once the last subscription ends and a lost idle
+ * socket is not redialed (the next `subscribe` dials again). On: a page-wide
+ * mux dialed on app entry stays up and is redialed on `online` / tab-visible
+ * even with nothing subscribed.
+ */
+ keepAlive?: boolean;
+}
+
+export type GatewayMuxStatus = 'connected' | 'connecting' | 'disconnected';
+
+export interface GatewayMuxClientEvents {
+ connected: () => void;
+ disconnected: () => void;
+ error: (error: Error) => void;
+ lifecycle: (lifecycle: MuxOpLifecycleMessage) => void;
+ reconnecting: (delay: number) => void;
+ status_changed: (status: GatewayMuxStatus) => void;
+}
+
+// ─── Operation subscription ───
+
+export type ToolResultPayload = Omit<ToolResultMessage, 'type'>;
+
+export interface ResumeCompleteInfo {
+ gap: boolean;
+ pending?: boolean;
+ status?: SessionStatus;
+}
+
+export interface OperationSubscribeOptions {
+ /** Run local `tool_execute` requests on this tab (the tab that started the run). */
+ executor?: boolean;
+ /** Last event id already applied; the hub replays only newer events. */
+ lastEventId?: string;
+}
+
+/**
+ * Per-operation events. A superset of the v1 `AgentStreamClientEvents` so a
+ * subscription can stand in for an `AgentStreamClient` in the store.
+ */
+export interface OperationSubscriptionEvents extends AgentStreamClientEvents {
+ input_request: (request: MuxInputRequestMessage) => void;
+ resume_complete: (info: ResumeCompleteInfo) => void;
+ status_change: (status: SessionStatus) => void;
+ tool_confirmation_request: (request: MuxToolConfirmationRequestMessage) => void;
+}
+
+export interface OperationSubscription {
+ /** True until `unsubscribe()` or a terminal signal ends this subscription. */
+ readonly active: boolean;
+ /** Highest event id applied so far (empty string before any event). */
+ readonly lastEventId: string;
+ on: <K extends keyof OperationSubscriptionEvents>(
+ event: K,
+ listener: OperationSubscriptionEvents[K],
+ ) => () => void;
+ operationId: string;
+ sendInterrupt: () => boolean;
+ sendToolConfirmation: (toolCallId: string, approved: boolean) => boolean;
+ /** Queued while the socket is down (TTL 120s) and flushed after resubscribe. */
+ sendToolResult: (result: ToolResultPayload) => boolean;
+ sendUserInput: (requestId: string, content: string) => boolean;
+ /** Connection state as seen by this operation (v1 `connectionStatus` parity). */
+ readonly status: ConnectionStatus;
+ unsubscribe: () => void;
+}
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index ded4a9f2ca4..e54ff1d6d2f 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -402,14 +402,28 @@ export interface SessionCompleteMessage {
export type SessionStatus =
'running' | 'waiting_input' | 'waiting_confirmation' | 'completed' | 'error' | 'interrupted';
-/** Provenance for a terminal session signal emitted by AgentStreamClient. */
+export type TerminalSessionStatus = Extract<SessionStatus, 'completed' | 'error' | 'interrupted'>;
+
+/**
+ * Provenance for a terminal session signal emitted by AgentStreamClient (v1)
+ * or a mux `OperationSubscription` (v2). v1 only ever emits the first two.
+ */
export type AgentStreamSessionCompletion =
| {
source: 'raw_session_complete';
}
| {
source: 'resume_status';
- status: Extract<SessionStatus, 'completed' | 'error' | 'interrupted'>;
+ status: TerminalSessionStatus;
+ }
+ /** v2: this op's own `agent_runtime_end` / `error` agent event. */
+ | {
+ source: 'agent_event';
+ }
+ /** v2: hub `status_change` carrying a terminal status (e.g. watchdog). */
+ | {
+ source: 'status_change';
+ status: TerminalSessionStatus;
};
/**
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index 2f476f8cd54..f246b8d0c44 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -27,6 +27,9 @@ export default {
'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.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/user/preference.ts b/packages/types/src/user/preference.ts
index e1648133f96..d4016d31aeb 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -211,6 +211,11 @@ export const UserLabSchema = z.object({
enableTaskVerify: z.boolean().optional(),
/** Capture a conversation turn as an eval test case (developer-facing). */
enableEvalCapture: z.boolean().optional(),
+ /**
+ * route every agent run in this tab over one shared gateway WebSocket
+ * (protocol v2 mux) instead of one socket per run
+ */
+ enableGatewayMux: z.boolean().optional(),
/**
* enable the per-topic acceptance tray above the composer (author a topic's
* delivery checklist inline)
diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.ts
index c6eeaa7ae4c..dc86d44d095 100644
--- a/src/features/Settings/labs/features.ts
+++ b/src/features/Settings/labs/features.ts
@@ -18,6 +18,7 @@ type LabFeatureI18nKey =
| 'codexAppServer'
| 'desktopSplitView'
| 'evalCapture'
+ | 'gatewayMux'
| 'heteroSessionImport'
| 'imessage'
| 'inputMarkdown'
@@ -76,6 +77,12 @@ 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.ts
new file mode 100644
index 00000000000..85725010124
--- /dev/null
+++ b/src/hooks/useGatewayMuxWarmup.ts
@@ -0,0 +1,20 @@
+import { useEffect } from 'react';
+
+import { useChatStore } from '@/store/chat';
+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.
+ */
+export const useGatewayMuxWarmup = (): void => {
+ const isReady = useUserStore((s) => s.isUserStateInit && !!s.isSignedIn);
+ const enabled = useUserStore(labPreferSelectors.enableGatewayMux);
+ const warmupGatewayMux = useChatStore((s) => s.warmupGatewayMux);
+
+ useEffect(() => {
+ if (isReady && enabled) warmupGatewayMux();
+ }, [isReady, enabled, warmupGatewayMux]);
+};
diff --git a/src/routes/(main)/_layout/GatewayMuxWarmup.tsx b/src/routes/(main)/_layout/GatewayMuxWarmup.tsx
new file mode 100644
index 00000000000..34ba8b2430f
--- /dev/null
+++ b/src/routes/(main)/_layout/GatewayMuxWarmup.tsx
@@ -0,0 +1,13 @@
+import { memo } from 'react';
+
+import { useGatewayMuxWarmup } from '@/hooks/useGatewayMuxWarmup';
+
+/** Render-less: dials the per-user gateway socket once the user is in the app. */
+const GatewayMuxWarmup = memo(() => {
+ useGatewayMuxWarmup();
+ return null;
+});
+
+GatewayMuxWarmup.displayName = 'GatewayMuxWarmup';
+
+export default GatewayMuxWarmup;
diff --git a/src/routes/(main)/_layout/authMount.test.ts b/src/routes/(main)/_layout/authMount.test.ts
index bc4e8b23a08..fdb7a4247e8 100644
--- a/src/routes/(main)/_layout/authMount.test.ts
+++ b/src/routes/(main)/_layout/authMount.test.ts
@@ -43,6 +43,7 @@ vi.mock('@/features/Electron/titlebar/TitleBar', nullComponent);
vi.mock('@/features/HotkeyHelperPanel', nullComponent);
vi.mock('@/features/NavPanel/Shell', nullComponent);
vi.mock('@/layout/GlobalProvider/CmdkLazy', nullComponent);
+vi.mock('./GatewayMuxWarmup', nullComponent);
vi.mock('./RegisterHotkeys', nullComponent);
vi.mock('../home', nullComponent);
vi.mock('../home/_layout', passthrough);
diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsx
index 4743f488f58..e457c8591a0 100644
--- a/src/routes/(main)/_layout/index.desktop.tsx
+++ b/src/routes/(main)/_layout/index.desktop.tsx
@@ -36,6 +36,7 @@ import dynamic from '@/libs/next/dynamic';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';
+import GatewayMuxWarmup from './GatewayMuxWarmup';
import RegisterHotkeys from './RegisterHotkeys';
import { styles } from './style';
@@ -91,6 +92,7 @@ const Layout: FC = () => {
</DndContextWrapper>
<Suspense fallback={null}>
<HotkeyHelperPanel />
+ <GatewayMuxWarmup />
<RegisterHotkeys />
<CmdkLazy />
<GlobalApprovalNotification />
diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsx
index dd10b1bd7ee..81a409800b9 100644
--- a/src/routes/(main)/_layout/index.tsx
+++ b/src/routes/(main)/_layout/index.tsx
@@ -26,6 +26,7 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfi
import DesktopHome from '../home';
import DesktopHomeLayout from '../home/_layout';
import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';
+import GatewayMuxWarmup from './GatewayMuxWarmup';
import RegisterHotkeys from './RegisterHotkeys';
import { styles } from './style';
@@ -66,6 +67,7 @@ const Layout: FC = () => {
</DndContextWrapper>
<Suspense fallback={null}>
<HotkeyHelperPanel />
+ <GatewayMuxWarmup />
<RegisterHotkeys />
<CmdkLazy />
<GlobalApprovalNotification />
diff --git a/src/store/chat/selectors.ts b/src/store/chat/selectors.ts
index 85c9b6b56e4..df0b5b06dfa 100644
--- a/src/store/chat/selectors.ts
+++ b/src/store/chat/selectors.ts
@@ -1,4 +1,4 @@
-export { agentRunSelectors } from './slices/agentRun/selectors';
+export { agentRunSelectors, gatewayFeedSelectors } from './slices/agentRun/selectors';
export { chatToolSelectors } from './slices/builtinTool/selectors';
export * from './slices/message/selectors';
export * from './slices/operation/selectors';
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.ts
new file mode 100644
index 00000000000..e325c0f712a
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
@@ -0,0 +1,498 @@
+import type { GatewayMuxClient, OperationClient } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { aiAgentService } from '@/services/aiAgent';
+import { messageService } from '@/services/message';
+
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+import { getGatewayMux, resetGatewayMuxRegistry } from '../transports/gateway/muxRegistry';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ issueGatewayUserToken: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ issueGatewayUserToken: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: { getMessages: vi.fn().mockResolvedValue([]) },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),
+}));
+
+const mockLab = vi.hoisted(() => ({ enableGatewayMux: false }));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: { getState: vi.fn(() => mockUserState) },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableGatewayMux: () => mockLab.enableGatewayMux },
+ settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },
+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },
+ userProfileSelectors: { userId: (state: typeof mockUserState) => state.profile.id },
+}));
+
+vi.mock('@/const/version', async (importOriginal) => ({
+ ...(await importOriginal<typeof ConstVersion>()),
+ isDesktop: false,
+}));
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: vi.fn() },
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => ({ activeAgentId: undefined, agentMap: {} }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => undefined,
+ getAgentById: () => () => undefined,
+ },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
+ chatConfigByIdSelectors: {
+ getChatConfigById: () => () => ({}),
+ isChatModeById: () => () => false,
+ isLocalSystemEnabledById: () => () => false,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => ({ topicDataMap: {}, topicDetailMap: {} }) },
+}));
+
+// ─── Fakes ───
+
+type Emitter = { emit: (event: string, ...args: any[]) => void };
+
+function createListenerBag() {
+ const listeners = new Map<string, Set<(...args: any[]) => void>>();
+ const on = vi.fn((event: string, listener: (...args: any[]) => void) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener);
+ return () => set!.delete(listener);
+ });
+ const emit = (event: string, ...args: any[]) => {
+ listeners.get(event)?.forEach((listener) => listener(...args));
+ };
+ return { emit, on };
+}
+
+/** v1-shaped client the injected `createClient` seam returns (flag off). */
+function createMockV1Client() {
+ const { emit, on } = createListenerBag();
+ return {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ emit,
+ on,
+ reconnect: vi.fn(async () => {}),
+ sendInterrupt: vi.fn(),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+/** Adapter-shaped client the injected `createMuxClient` seam returns (flag on). */
+function createMockOperationClient(): OperationClient & Emitter {
+ const { emit, on } = createListenerBag();
+ return {
+ connect: vi.fn(),
+ connectionStatus: 'disconnected',
+ disconnect: vi.fn(),
+ emit,
+ on: on as OperationClient['on'],
+ reconnect: vi.fn(async () => {}),
+ sendInterrupt: vi.fn(),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+function createFakeMux(): GatewayMuxClient & Emitter {
+ const { emit, on } = createListenerBag();
+ return {
+ connect: vi.fn(async () => {}),
+ disconnect: vi.fn(),
+ emit,
+ on,
+ status: 'disconnected',
+ subscribe: vi.fn(),
+ } as unknown as GatewayMuxClient & Emitter;
+}
+
+const GATEWAY_URL = 'https://gateway.test.com';
+
+function createTestAction(overrides: Record<string, any> = {}) {
+ const state: Record<string, any> = { gatewayConnections: {}, gatewayFeed: {} };
+ const set = vi.fn((updater: any) => {
+ if (typeof updater === 'function') Object.assign(state, updater(state));
+ else Object.assign(state, updater);
+ });
+ const get = vi.fn(() => ({ ...state, ...overrides })) as any;
+ const action = new GatewayActionImpl(set as any, get, undefined);
+
+ const v1Client = createMockV1Client();
+ action.createClient = vi.fn(() => v1Client);
+ const muxClient = createMockOperationClient();
+ action.createMuxClient = vi.fn(() => muxClient);
+ const mux = createFakeMux();
+ action.resolveGatewayMux = vi.fn(() => mux);
+
+ return { action, get, mux, muxClient, set, state, v1Client };
+}
+
+const flushMicrotasks = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+describe('GatewayActionImpl (enableGatewayMux lab)', () => {
+ beforeEach(() => {
+ mockLab.enableGatewayMux = true;
+ vi.mocked(messageService.getMessages).mockClear();
+ });
+
+ afterEach(() => {
+ resetGatewayMuxRegistry();
+ delete (globalThis as any).window;
+ vi.restoreAllMocks();
+ });
+
+ describe('connectToGateway', () => {
+ it('adapts the operation on the identity mux instead of dialing a v1 socket', () => {
+ const { action, mux, muxClient, state, v1Client } = createTestAction();
+
+ action.connectToGateway({
+ agentShareId: 'share-1',
+ executor: true,
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ resumeOnConnect: true,
+ token: 'unused-in-mux',
+ topicId: 'topic-1',
+ });
+
+ expect(action.resolveGatewayMux).toHaveBeenCalledWith({
+ agentShareId: 'share-1',
+ gatewayUrl: GATEWAY_URL,
+ });
+ expect(action.createMuxClient).toHaveBeenCalledWith(mux, 'op-1', {
+ executor: true,
+ resumeOnConnect: true,
+ });
+ expect(action.createClient).not.toHaveBeenCalled();
+ expect(muxClient.connect).toHaveBeenCalled();
+ expect(v1Client.connect).not.toHaveBeenCalled();
+ 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;
+ const { action, state, v1Client } = createTestAction();
+
+ action.connectToGateway({
+ executor: true,
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+
+ expect(action.createClient).toHaveBeenCalledWith({
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ resumeOnConnect: undefined,
+ token: 'tok',
+ });
+ expect(action.resolveGatewayMux).not.toHaveBeenCalled();
+ expect(action.createMuxClient).not.toHaveBeenCalled();
+ expect(v1Client.connect).toHaveBeenCalled();
+ expect(state.gatewayConnections['op-1'].client).toBe(v1Client);
+ });
+
+ it('resolves the page-wide registry mux by default', () => {
+ const { action } = createTestAction();
+ action.resolveGatewayMux = getGatewayMux;
+
+ action.connectToGateway({
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+
+ expect(action.createMuxClient).toHaveBeenCalledWith(
+ getGatewayMux({ gatewayUrl: GATEWAY_URL }),
+ 'op-1',
+ expect.anything(),
+ );
+ });
+
+ it('forwards a resume gap as a notify_update so the handler refetches from DB', () => {
+ const onEvent = vi.fn();
+ const { action, muxClient } = createTestAction();
+
+ action.connectToGateway({
+ gatewayUrl: GATEWAY_URL,
+ onEvent,
+ operationId: 'op-1',
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+
+ muxClient.emit('resume_complete', { gap: false, status: 'running' });
+ expect(onEvent).not.toHaveBeenCalled();
+
+ muxClient.emit('resume_complete', { gap: true, status: 'running' });
+ expect(onEvent).toHaveBeenCalledTimes(1);
+ expect(onEvent).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-1', type: 'notify_update' }),
+ );
+ });
+
+ it('records mux lifecycle notices in gatewayFeed, attaching once per mux', () => {
+ const { action, mux, state } = createTestAction();
+
+ action.connectToGateway({
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+ action.connectToGateway({
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-2',
+ token: 'tok',
+ topicId: 'topic-2',
+ });
+
+ const lifecycleAttachments = vi
+ .mocked(mux.on)
+ .mock.calls.filter(([event]) => event === 'lifecycle');
+ expect(lifecycleAttachments).toHaveLength(1);
+
+ mux.emit('lifecycle', {
+ at: 1_700_000_000_000,
+ meta: { agentId: 'agent-1', topicId: 'topic-9' },
+ operationId: 'op-9',
+ status: 'running',
+ type: 'op_lifecycle',
+ });
+ mux.emit('lifecycle', {
+ at: 1_700_000_000_500,
+ operationId: 'op-9',
+ status: 'gone',
+ type: 'op_lifecycle',
+ });
+
+ expect(state.gatewayFeed).toEqual({
+ 'op-9': { at: 1_700_000_000_500, meta: undefined, status: 'gone' },
+ });
+ });
+
+ it('survives without an auth_expired round trip (token is minted per dial)', () => {
+ const { action, muxClient, state } = createTestAction();
+
+ action.connectToGateway({
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+
+ // The adapter never emits it; the handler is registered but inert.
+ expect(vi.mocked(muxClient.on).mock.calls.some(([e]) => e === 'auth_expired')).toBe(true);
+ expect(muxClient.updateToken).not.toHaveBeenCalled();
+ expect(aiAgentService.refreshGatewayToken).not.toHaveBeenCalled();
+ expect(state.gatewayConnections['op-1'].status).toBe('connecting');
+ });
+ });
+
+ describe('warmupGatewayMux', () => {
+ const withServerConfig = (serverConfig: Record<string, unknown>) => {
+ (globalThis as any).window = {
+ global_serverConfigStore: { getState: () => ({ serverConfig }) },
+ };
+ };
+
+ it('dials the identity mux on app entry and attaches the feed once', () => {
+ withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: true });
+ const { action, mux, state } = createTestAction();
+
+ action.warmupGatewayMux();
+ action.warmupGatewayMux();
+
+ expect(action.resolveGatewayMux).toHaveBeenCalledWith({ gatewayUrl: GATEWAY_URL });
+ expect(mux.connect).toHaveBeenCalledTimes(2);
+ mux.emit('lifecycle', {
+ at: 1,
+ operationId: 'op-feed',
+ status: 'running',
+ type: 'op_lifecycle',
+ });
+ expect(Object.keys(state.gatewayFeed)).toEqual(['op-feed']);
+ });
+
+ it('is a no-op when the lab flag is off or gateway mode is unavailable', () => {
+ withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: true });
+ mockLab.enableGatewayMux = false;
+ const off = createTestAction();
+ off.action.warmupGatewayMux();
+ expect(off.mux.connect).not.toHaveBeenCalled();
+
+ mockLab.enableGatewayMux = true;
+ withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: false });
+ const noGateway = createTestAction();
+ noGateway.action.warmupGatewayMux();
+ expect(noGateway.mux.connect).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('executor ownership', () => {
+ const execResult = {
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ };
+
+ beforeEach(() => {
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: GATEWAY_URL } }),
+ },
+ };
+ });
+
+ it('executeGatewayAgent subscribes as executor (this tab started the run)', async () => {
+ const connectToGateway = vi.fn();
+ const { action } = createTestAction({
+ associateMessageWithOperation: vi.fn(),
+ connectToGateway,
+ internal_dispatchTopic: vi.fn(),
+ internal_replaceTopicId: vi.fn(),
+ moveQueuedMessages: vi.fn(),
+ moveVoiceMessages: vi.fn(),
+ onOperationCancel: vi.fn(),
+ refreshTopic: vi.fn().mockResolvedValue(undefined),
+ replaceMessages: vi.fn(),
+ startOperation: vi.fn(() => ({ operationId: 'gw-op-1' })),
+ switchTopic: vi.fn(),
+ topicDataMap: {},
+ updateTopicStatus: vi.fn(),
+ });
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(execResult as any);
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },
+ message: 'Hello',
+ });
+
+ expect(connectToGateway).toHaveBeenCalledWith(
+ expect.objectContaining({ executor: true, operationId: 'server-op-1' }),
+ );
+ });
+
+ it('reconnectToGatewayOperation subscribes as a passive viewer', async () => {
+ const connectToGateway = vi.fn();
+ const { action } = createTestAction({
+ activeAgentId: 'agent-1',
+ associateMessageWithOperation: vi.fn(),
+ connectToGateway,
+ messagesMap: { 'agent-1_topic-1': [{ createdAt: Date.now(), id: 'ast-1' }] },
+ onOperationCancel: vi.fn(),
+ startOperation: vi.fn(() => ({ operationId: 'gw-op-reconnect' })),
+ topicDataMap: {},
+ });
+ vi.mocked(aiAgentService.refreshGatewayToken).mockResolvedValue({
+ token: 'fresh-token',
+ } as any);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(connectToGateway).toHaveBeenCalledWith(
+ expect.objectContaining({ executor: false, operationId: 'server-op-1' }),
+ );
+ });
+
+ it('a resume gap on a real run handler refetches the topic messages from DB', async () => {
+ // Capture the exact params executeGatewayAgent hands to connectToGateway
+ // (real event router + handler), then open the connection for real.
+ const captured = vi.fn();
+ const replaceMessages = vi.fn();
+ const { action, muxClient } = createTestAction({
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ connectToGateway: captured,
+ internal_dispatchTopic: vi.fn(),
+ internal_replaceTopicId: vi.fn(),
+ moveQueuedMessages: vi.fn(),
+ moveVoiceMessages: vi.fn(),
+ onOperationCancel: vi.fn(),
+ refreshTopic: vi.fn().mockResolvedValue(undefined),
+ replaceMessages,
+ startOperation: vi.fn(() => ({ operationId: 'gw-op-1' })),
+ switchTopic: vi.fn(),
+ topicDataMap: {},
+ updateTopicStatus: vi.fn(),
+ });
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(execResult as any);
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },
+ message: 'Hello',
+ });
+ action.connectToGateway(captured.mock.calls[0][0]);
+ vi.mocked(messageService.getMessages).mockClear();
+
+ muxClient.emit('resume_complete', { gap: true, status: 'running' });
+ await flushMicrotasks();
+
+ expect(messageService.getMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', topicId: 'topic-1' }),
+ );
+ expect(replaceMessages).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 98e8884fabe..806e9e09e2f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -66,6 +66,8 @@ vi.mock('@/store/user', () => ({
}));
vi.mock('@/store/user/selectors', () => ({
+ // Lab flag off: this suite pins the v1 per-operation socket path.
+ labPreferSelectors: { enableGatewayMux: () => false },
settingsSelectors: {
defaultAgentConfig: () => ({
chatConfig: { disableGatewayMode: mockUserDefaultConfig.disableGatewayMode },
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 6a8c577c768..3baa49c98be 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -4,6 +4,11 @@ import {
type AgentStreamEvent,
type AgentStreamSessionCompletion,
type ConnectionStatus,
+ createOperationClient,
+ type GatewayMuxClient,
+ type MuxOpLifecycleMessage,
+ type OperationClient,
+ type OperationClientOptions,
} from '@lobechat/agent-gateway-client';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
@@ -43,6 +48,7 @@ import { getFileStoreState } from '@/store/file/store';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import {
+ labPreferSelectors,
settingsSelectors,
toolInterventionSelectors,
userProfileSelectors,
@@ -56,6 +62,7 @@ import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
+import { type GatewayMuxIdentity, getGatewayMux } from './muxRegistry';
/**
* Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.
@@ -201,6 +208,13 @@ export interface ConnectGatewayParams {
* refresh cannot see the creator-owned share topic.
*/
agentShareId?: string;
+ /**
+ * 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
+ * v1 per-operation socket is always the executor.
+ */
+ executor?: boolean;
/**
* Gateway WebSocket URL (e.g. https://agent-gateway.lobehub.com)
*/
@@ -277,16 +291,56 @@ export class GatewayActionImpl {
readonly #get: () => ChatStore;
readonly #set: Setter;
- /** Overridable factory for testing */
+ /** Overridable factory for testing (v1: one socket per operation). */
createClient: (options: AgentStreamClientOptions) => GatewayConnection['client'] = (options) =>
new AgentStreamClient(options);
+ /**
+ * Overridable seams for the multiplexed transport (lab `enableGatewayMux`):
+ * resolve the page-wide mux for an identity, then adapt one operation on it
+ * to the v1 client surface.
+ */
+ resolveGatewayMux: (identity: GatewayMuxIdentity) => GatewayMuxClient = getGatewayMux;
+ createMuxClient: (
+ mux: GatewayMuxClient,
+ operationId: string,
+ options: OperationClientOptions,
+ ) => OperationClient = createOperationClient;
+
+ /** Muxes whose `lifecycle` stream already feeds `gatewayFeed`. */
+ readonly #feedAttachedMuxes = new WeakSet<GatewayMuxClient>();
+
constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
}
+ /**
+ * Mirror the hub's `op_lifecycle` notices into `gatewayFeed`. Attached once
+ * per mux: the feed is connection-level, not per subscription.
+ */
+ #attachGatewayFeed = (mux: GatewayMuxClient): void => {
+ if (this.#feedAttachedMuxes.has(mux)) return;
+ this.#feedAttachedMuxes.add(mux);
+ mux.on('lifecycle', (lifecycle: MuxOpLifecycleMessage) => {
+ this.#set(
+ (state) => ({
+ gatewayFeed: {
+ ...state.gatewayFeed,
+ [lifecycle.operationId]: {
+ at: lifecycle.at,
+ meta: lifecycle.meta ? { ...lifecycle.meta } : undefined,
+ status: lifecycle.status,
+ },
+ },
+ }),
+ false,
+ 'gateway/lifecycle',
+ );
+ });
+ };
+
/**
* Connect to the Agent Gateway for a specific operation.
* Creates an AgentStreamClient, manages its lifecycle, and wires up event callbacks.
@@ -294,6 +348,7 @@ export class GatewayActionImpl {
connectToGateway = (params: ConnectGatewayParams): void => {
const {
agentShareId,
+ executor,
operationId,
gatewayUrl,
token,
@@ -306,7 +361,19 @@ export class GatewayActionImpl {
// Disconnect existing connection for this operation if any
this.disconnectFromGateway(operationId);
- const client = this.createClient({ gatewayUrl, operationId, resumeOnConnect, token });
+ // Read the lab flag once per connect (non-reactive, like the other prefs
+ // `isGatewayModeEnabled` consults): a connection keeps the transport it
+ // was opened with even if the toggle flips mid-run.
+ let muxClient: OperationClient | undefined;
+ if (labPreferSelectors.enableGatewayMux(useUserStore.getState())) {
+ const mux = this.resolveGatewayMux({ agentShareId, gatewayUrl });
+ this.#attachGatewayFeed(mux);
+ // The mux mints its own token via `getToken` on every dial, so `token`
+ // is unused here and `auth_expired` never fires on this client.
+ muxClient = this.createMuxClient(mux, operationId, { executor, resumeOnConnect });
+ }
+ const client: GatewayConnection['client'] =
+ muxClient ?? this.createClient({ gatewayUrl, operationId, resumeOnConnect, token });
// Track connection in store
this.#set(
@@ -383,6 +450,23 @@ export class GatewayActionImpl {
eventBuffer.push(event);
});
+ // Mux resume with a gap: the hub could not replay every missed event
+ // (its per-op buffer was trimmed), so the DB is the only complete record.
+ // Ride the `notify_update` path instead of a second refetch routine: the
+ // synthetic event goes through the same buffer → router → handler chain,
+ // so it lands in the handler's sequential queue after the replayed events
+ // and under its snapshot-generation guard.
+ muxClient?.on('resume_complete', ({ gap }) => {
+ if (!gap) return;
+ eventBuffer.push({
+ data: { reason: 'resume_gap' },
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'notify_update',
+ });
+ });
+
// Handle session completion
client.on('session_complete', (completion) => {
this.internal_cleanupGatewayConnection(operationId);
@@ -473,6 +557,26 @@ export class GatewayActionImpl {
* Returns true when the server supports Gateway mode and the agent config
* 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).
+ */
+ warmupGatewayMux = (): void => {
+ if (!labPreferSelectors.enableGatewayMux(useUserStore.getState())) return;
+ const serverConfig = window.global_serverConfigStore?.getState()?.serverConfig;
+ if (!serverConfig?.agentGatewayUrl || !serverConfig.enableGatewayMode) return;
+
+ const mux = this.resolveGatewayMux({ gatewayUrl: serverConfig.agentGatewayUrl });
+ this.#attachGatewayFeed(mux);
+ mux.connect().catch(() => {
+ // The mux keeps retrying with backoff; failures surface on its own
+ // `error` / `reconnecting` listeners.
+ });
+ };
+
isGatewayModeEnabled = (agentId?: string): boolean => {
const serverConfig = window.global_serverConfigStore?.getState()?.serverConfig;
const agentState = getAgentStoreState();
@@ -1041,6 +1145,8 @@ export class GatewayActionImpl {
});
this.#get().connectToGateway({
+ // This tab started the run: it owns the run's local tool execution.
+ executor: true,
gatewayUrl: agentGatewayUrl,
onEvent: eventRouter,
onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {
@@ -1286,6 +1392,9 @@ export class GatewayActionImpl {
});
this.#get().connectToGateway({
+ // A reconnect is passive: the tab that started the run keeps executing
+ // its local tools; this one only renders.
+ executor: false,
gatewayUrl: agentGatewayUrl,
onEvent: eventRouter,
onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.test.ts
new file mode 100644
index 00000000000..e65d5b73edb
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.test.ts
@@ -0,0 +1,89 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentService } from '@/services/aiAgent';
+import { shareChatService } from '@/services/shareChat';
+
+import { getGatewayMux, resetGatewayMuxRegistry } from './muxRegistry';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: { issueGatewayUserToken: vi.fn() },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: { issueGatewayUserToken: vi.fn() },
+}));
+
+/** Never opens: enough for `connect()` to get past `getToken`. */
+class InertWebSocket {
+ static CONNECTING = 0;
+ static OPEN = 1;
+ static CLOSING = 2;
+ static CLOSED = 3;
+ readyState = InertWebSocket.CONNECTING;
+ onopen = null;
+ onmessage = null;
+ onclose = null;
+ onerror = null;
+ constructor(public url: string) {}
+ send() {}
+ close() {
+ this.readyState = InertWebSocket.CLOSED;
+ }
+}
+
+const GATEWAY_URL = 'https://gateway.test.com';
+const flushMicrotasks = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+describe('muxRegistry', () => {
+ beforeEach(() => {
+ vi.stubGlobal('WebSocket', InertWebSocket);
+ vi.mocked(aiAgentService.issueGatewayUserToken).mockResolvedValue({ token: 'owner-jwt' });
+ vi.mocked(shareChatService.issueGatewayUserToken).mockResolvedValue({ token: 'share-jwt' });
+ });
+
+ afterEach(() => {
+ resetGatewayMuxRegistry();
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ it('returns one mux per gatewayUrl + identity', () => {
+ const owner = getGatewayMux({ gatewayUrl: GATEWAY_URL });
+ expect(getGatewayMux({ gatewayUrl: GATEWAY_URL })).toBe(owner);
+ expect(getGatewayMux({ agentShareId: undefined, gatewayUrl: GATEWAY_URL })).toBe(owner);
+
+ const share = getGatewayMux({ agentShareId: 'share-1', gatewayUrl: GATEWAY_URL });
+ expect(share).not.toBe(owner);
+ expect(getGatewayMux({ agentShareId: 'share-1', gatewayUrl: GATEWAY_URL })).toBe(share);
+ expect(getGatewayMux({ agentShareId: 'share-2', gatewayUrl: GATEWAY_URL })).not.toBe(share);
+ expect(getGatewayMux({ gatewayUrl: 'https://other.test.com' })).not.toBe(owner);
+ });
+
+ it('mints an owner user token for the owner mux', async () => {
+ const owner = getGatewayMux({ gatewayUrl: GATEWAY_URL });
+ void owner.connect().catch(() => {});
+ await flushMicrotasks();
+
+ expect(aiAgentService.issueGatewayUserToken).toHaveBeenCalledTimes(1);
+ expect(shareChatService.issueGatewayUserToken).not.toHaveBeenCalled();
+ });
+
+ it('mints a share-scoped token for a share visitor mux', async () => {
+ const share = getGatewayMux({ agentShareId: 'share-1', gatewayUrl: GATEWAY_URL });
+ void share.connect().catch(() => {});
+ await flushMicrotasks();
+
+ expect(shareChatService.issueGatewayUserToken).toHaveBeenCalledWith('share-1');
+ expect(aiAgentService.issueGatewayUserToken).not.toHaveBeenCalled();
+ });
+
+ it('reset disconnects every mux and forgets it', () => {
+ const owner = getGatewayMux({ gatewayUrl: GATEWAY_URL });
+ const disconnect = vi.spyOn(owner, 'disconnect');
+
+ resetGatewayMuxRegistry();
+
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ expect(getGatewayMux({ gatewayUrl: GATEWAY_URL })).not.toBe(owner);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts
new file mode 100644
index 00000000000..4eeb2139599
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts
@@ -0,0 +1,69 @@
+import { GatewayMuxClient } from '@lobechat/agent-gateway-client';
+
+import { aiAgentService } from '@/services/aiAgent';
+import { shareChatService } from '@/services/shareChat';
+
+export interface GatewayMuxIdentity {
+ /**
+ * Present on the agent-share visitor surface. The visitor's socket is
+ * authenticated with a share-scoped user token, so it must not be shared
+ * with the owner-scoped socket of the same page.
+ */
+ agentShareId?: string;
+ /** Gateway URL base (e.g. https://agent-gateway.lobehub.com). */
+ gatewayUrl: string;
+}
+
+const registry = new Map<string, GatewayMuxClient>();
+
+const identityKey = ({ agentShareId, gatewayUrl }: GatewayMuxIdentity): string =>
+ `${gatewayUrl}|${agentShareId ?? 'owner'}`;
+
+/**
+ * `getToken` is invoked before EVERY dial (initial connect, backoff retry,
+ * 4401 refresh), so the mux never needs the v1 `auth_expired` → `updateToken`
+ * round trip. Owners mint a user-level token; share visitors mint one scoped
+ * to the share.
+ */
+const buildGetToken =
+ ({ agentShareId }: GatewayMuxIdentity): (() => Promise<string>) =>
+ async () => {
+ const { token } = agentShareId
+ ? await shareChatService.issueGatewayUserToken(agentShareId)
+ : await aiAgentService.issueGatewayUserToken();
+ return token;
+ };
+
+/**
+ * One `GatewayMuxClient` per `${gatewayUrl}|${agentShareId ?? 'owner'}` for
+ * the lifetime of the page. Every operation on the same identity multiplexes
+ * over that single socket (protocol v2). The socket is dialed on app entry by
+ * `warmupGatewayMux` (or lazily on the first `subscribe` if that never ran)
+ * and is kept up across runs — `keepAlive` so a drop is redialed even while
+ * nothing is subscribed.
+ */
+export const getGatewayMux = (identity: GatewayMuxIdentity): GatewayMuxClient => {
+ const key = identityKey(identity);
+ let mux = registry.get(key);
+ if (!mux) {
+ mux = new GatewayMuxClient({
+ gatewayUrl: identity.gatewayUrl,
+ getToken: buildGetToken(identity),
+ keepAlive: true,
+ });
+ registry.set(key, mux);
+ }
+ return mux;
+};
+
+/**
+ * Tear down every mux (they hold window listeners and the lifecycle → store
+ * feed) and forget them. Called when the user-data context resets
+ * (`stores.reset()`, e.g. the desktop app switching or disconnecting its
+ * remote server) so a socket authenticated for the previous identity never
+ * outlives it or keeps writing into the reset chat store; also a test seam.
+ */
+export const resetGatewayMuxRegistry = (): void => {
+ for (const mux of registry.values()) mux.disconnect();
+ registry.clear();
+};
diff --git a/src/store/chat/slices/agentRun/initialState.ts b/src/store/chat/slices/agentRun/initialState.ts
index 90df71c18df..92bf1e7700d 100644
--- a/src/store/chat/slices/agentRun/initialState.ts
+++ b/src/store/chat/slices/agentRun/initialState.ts
@@ -6,11 +6,31 @@ export type MainConversationScrollToIndex = (
options?: { align?: 'start' | 'center' | 'end'; smooth?: boolean },
) => void;
+/**
+ * Last `op_lifecycle` notice the shared gateway socket delivered for an
+ * operation. Written only when the `enableGatewayMux` lab flag 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.
+ */
+export interface GatewayFeedEntry {
+ /** Hub timestamp (epoch ms) of the lifecycle transition. */
+ at: number;
+ /** Op routing metadata (topicId, agentId, parent/root op...) as sent by the hub. */
+ meta?: Record<string, unknown>;
+ /** `SessionStatus` or `gone` once the hub has forgotten the op. */
+ status: string;
+}
+
export interface ChatAIChatState {
/**
* Active Agent Gateway WebSocket connections, keyed by operationId
*/
gatewayConnections: Record<string, GatewayConnection>;
+ /**
+ * Mux-level op lifecycle feed, keyed by operationId. No UI reads it yet;
+ * later work drives spinners / reconnect decisions from it.
+ */
+ gatewayFeed: Record<string, GatewayFeedEntry>;
inputFiles: File[];
inputMessage: string;
/**
@@ -35,6 +55,7 @@ export interface ChatAIChatState {
export const initialAiChatState: ChatAIChatState = {
gatewayConnections: {},
+ gatewayFeed: {},
inputFiles: [],
inputMessage: '',
mainConversationScrollToIndex: null,
diff --git a/src/store/chat/slices/agentRun/selectors.ts b/src/store/chat/slices/agentRun/selectors.ts
index 6f03d213c7b..3ccf058fe36 100644
--- a/src/store/chat/slices/agentRun/selectors.ts
+++ b/src/store/chat/slices/agentRun/selectors.ts
@@ -58,6 +58,15 @@ const isSendMessageLoadingForTopic = (topicKey: string) => (s: ChatStoreState) =
});
};
+const gatewayFeed = (s: ChatStoreState) => s.gatewayFeed;
+
+const gatewayFeedEntry = (operationId: string) => (s: ChatStoreState) => s.gatewayFeed[operationId];
+
+export const gatewayFeedSelectors = {
+ gatewayFeed,
+ gatewayFeedEntry,
+};
+
export const agentRunSelectors = {
isCurrentSendMessageError,
isCurrentSendMessageLoading,
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 9f326bacceb..24baa73f97e 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -14,6 +14,7 @@ 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,
diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.ts
new file mode 100644
index 00000000000..236ba6b26f1
--- /dev/null
+++ b/src/store/utils/userDataStores.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const resetGatewayMuxRegistry = vi.hoisted(() => vi.fn());
+const storeResets = vi.hoisted(() => [] as Array<() => void>);
+const fakeStore = vi.hoisted(() => () => ({
+ getState: () => {
+ const reset = vi.fn();
+ storeResets.push(reset);
+ return { reset };
+ },
+}));
+
+vi.mock('react-dom', () => ({ unstable_batchedUpdates: (fn: () => void) => fn() }));
+vi.mock('@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry', () => ({
+ resetGatewayMuxRegistry,
+}));
+vi.mock('@/store/agent', () => ({ useAgentStore: fakeStore() }));
+vi.mock('@/store/agentGroup', () => ({ useAgentGroupStore: fakeStore() }));
+vi.mock('@/store/chat', () => ({ useChatStore: fakeStore() }));
+vi.mock('@/store/discover', () => ({ useDiscoverStore: fakeStore() }));
+vi.mock('@/store/document', () => ({ useDocumentStore: fakeStore() }));
+vi.mock('@/store/eval', () => ({ useEvalStore: fakeStore() }));
+vi.mock('@/store/file', () => ({ useFileStore: fakeStore() }));
+vi.mock('@/store/home', () => ({ useHomeStore: fakeStore() }));
+vi.mock('@/store/image', () => ({ useImageStore: fakeStore() }));
+vi.mock('@/store/library', () => ({ useKnowledgeBaseStore: fakeStore() }));
+vi.mock('@/store/mention', () => ({ useMentionStore: fakeStore() }));
+vi.mock('@/store/notebook', () => ({ useNotebookStore: fakeStore() }));
+vi.mock('@/store/page', () => ({ usePageStore: fakeStore() }));
+vi.mock('@/store/session', () => ({ useSessionStore: fakeStore() }));
+vi.mock('@/store/task', () => ({ useTaskStore: fakeStore() }));
+vi.mock('@/store/tool', () => ({ useToolStore: fakeStore() }));
+vi.mock('@/store/user', () => ({ useUserStore: fakeStore() }));
+vi.mock('@/store/userMemory', () => ({ useUserMemoryStore: fakeStore() }));
+vi.mock('@/store/video', () => ({ useVideoStore: fakeStore() }));
+
+describe('stores.reset', () => {
+ beforeEach(() => {
+ resetGatewayMuxRegistry.mockClear();
+ storeResets.length = 0;
+ });
+
+ it('tears down the gateway mux registry before wiping the user-data stores', async () => {
+ const { stores } = await import('./userDataStores');
+ const order: string[] = [];
+ resetGatewayMuxRegistry.mockImplementation(() => order.push('mux'));
+
+ stores.reset();
+
+ expect(resetGatewayMuxRegistry).toHaveBeenCalledTimes(1);
+ expect(storeResets).toHaveLength(19);
+ for (const reset of storeResets) expect(reset).toHaveBeenCalledTimes(1);
+ expect(order[0]).toBe('mux');
+ });
+});
diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.ts
index 63c4049650b..65ea3f75487 100644
--- a/src/store/utils/userDataStores.ts
+++ b/src/store/utils/userDataStores.ts
@@ -3,6 +3,7 @@ import { unstable_batchedUpdates } from 'react-dom';
import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
+import { resetGatewayMuxRegistry } from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';
import { useDiscoverStore } from '@/store/discover';
import { useDocumentStore } from '@/store/document';
import { useEvalStore } from '@/store/eval';
@@ -51,6 +52,9 @@ export interface StoreActions extends ResetableStore {}
const createStoreActions = (stores: ResetableStoreApi[]): StoreActions => ({
reset: () => {
+ // Drop the per-user gateway socket(s) before the stores they feed are
+ // wiped — a new data context must not inherit the old identity's socket.
+ resetGatewayMuxRegistry();
unstable_batchedUpdates(() => {
for (const store of stores) {
store.getState().reset();