Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(gateway): fall back to the v1 socket when the multiplexed one cannot connect (#19814)

Arvin Xu8e1bf7820d58
diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.ts
index 14c68c17ce9..e0b19b9fb09 100644
--- a/packages/agent-gateway-client/src/client.test.ts
+++ b/packages/agent-gateway-client/src/client.test.ts
@@ -162,6 +162,30 @@ describe('AgentStreamClient', () => {
expect(JSON.parse(ws.sent[1])).toEqual({ lastEventId: '', type: 'resume', wantStatus: true });
});
+ it('resumes from a cursor handed over by another transport', async () => {
+ // The v1 fallback picks up a run the multiplexed socket was streaming:
+ // the first resume must start after what that socket already delivered,
+ // and without the from-scratch buffering (nothing needs deduplicating).
+ const client = createClient({ lastEventId: '42', resumeOnConnect: true });
+ const ws = await connectAndAuth(client);
+
+ expect(JSON.parse(ws.sent[1])).toEqual({
+ lastEventId: '42',
+ type: 'resume',
+ wantStatus: true,
+ });
+
+ const onEvent = vi.fn();
+ client.on('agent_event', onEvent);
+ ws.simulateMessage({
+ event: { data: {}, stepIndex: 0, timestamp: 1, type: 'stream_chunk' },
+ id: '43',
+ type: 'agent_event',
+ } as any);
+ // Delivered live, not held in a resume buffer.
+ expect(onEvent).toHaveBeenCalledOnce();
+ });
+
it('should not connect if already connected', async () => {
const client = createClient();
await connectAndAuth(client);
diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.ts
index 5e3677a8022..83578781944 100644
--- a/packages/agent-gateway-client/src/client.ts
+++ b/packages/agent-gateway-client/src/client.ts
@@ -91,6 +91,7 @@ export class AgentStreamClient extends TypedEmitter {
this.token = options.token;
this.autoReconnect = options.autoReconnect ?? true;
this.resumeOnConnect = options.resumeOnConnect ?? false;
+ this.lastEventId = options.lastEventId ?? '';
}
// ─── Public API ───
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
index 9599fb2e263..4c73dbb93d7 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
@@ -722,6 +722,27 @@ describe('GatewayMuxClient', () => {
]);
});
+ it('hands queued tool results to an owner moving the operation elsewhere', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const a = mux.subscribe('op-a');
+ const b = mux.subscribe('op-b');
+ ws.simulateClose();
+
+ a.sendToolResult({ content: 'stale', success: true, toolCallId: 'call_old' });
+ await vi.advanceTimersByTimeAsync(121_000);
+ a.sendToolResult({ content: 'for a', success: true, toolCallId: 'call_a' });
+ b.sendToolResult({ content: 'for b', success: true, toolCallId: 'call_b' });
+
+ // Envelope stripped back to the v1 payload; expired entries are dropped.
+ expect(mux.takePendingToolResults('op-a')).toEqual([
+ { content: 'for a', success: true, toolCallId: 'call_a' },
+ ]);
+ // Taken means gone: nothing left for op-a, op-b untouched.
+ expect(mux.takePendingToolResults('op-a')).toEqual([]);
+ expect(mux.takePendingToolResults('op-b').map((r) => r.toolCallId)).toEqual(['call_b']);
+ });
+
it('drops queued tool_result older than 120s', async () => {
const { mux } = createMux();
const ws = await connectAndReady(mux);
@@ -952,4 +973,172 @@ describe('GatewayMuxClient', () => {
expect(sub.active).toBe(true);
});
});
+
+ describe('unavailable (fallback to v1)', () => {
+ it('gives up after maxDialFailures dials that never reach ready', async () => {
+ const { getToken, mux } = createMux();
+ const sub = mux.subscribe('op-1');
+ const onUnavailable = vi.fn();
+ mux.on('unavailable', onUnavailable);
+
+ let ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(500); // attempt 1: 0.5 * 1000 cap
+ ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(1000); // attempt 2: 0.5 * 2000 cap
+ ws = await settle();
+ expect(onUnavailable).not.toHaveBeenCalled();
+ ws.simulateClose(1006);
+
+ expect(onUnavailable).toHaveBeenCalledOnce();
+ expect(mux.isUnavailable).toBe(true);
+ // The owner re-establishes the run on v1, so the subscription must not be
+ // ended here β€” a terminal signal would complete the operation instead.
+ expect(sub.active).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mockWsInstances).toHaveLength(3);
+ expect(getToken).toHaveBeenCalledTimes(3);
+ });
+
+ it('gives up when the token cannot be minted at all', async () => {
+ const getToken = vi.fn().mockRejectedValue(new Error('404 issueGatewayUserToken'));
+ const { mux } = createMux({ getToken });
+ mux.on('error', () => {});
+ const onUnavailable = vi.fn();
+ mux.on('unavailable', onUnavailable);
+ mux.subscribe('op-1');
+
+ await vi.advanceTimersByTimeAsync(1);
+ await vi.advanceTimersByTimeAsync(500);
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onUnavailable).toHaveBeenCalledOnce();
+ expect(mockWsInstances).toHaveLength(0);
+ });
+
+ it('turns a terminal 4401 into unavailable instead of failing the runs', async () => {
+ const { mux } = createMux();
+ const sub = mux.subscribe('op-1');
+ const onAuthFailed = vi.fn();
+ const onUnavailable = vi.fn();
+ sub.on('auth_failed', onAuthFailed);
+ mux.on('unavailable', onUnavailable);
+
+ 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(onUnavailable).toHaveBeenCalledWith('auth_failed');
+ expect(onAuthFailed).not.toHaveBeenCalled();
+ expect(sub.active).toBe(true);
+ });
+
+ it('keeps retrying forever when nothing listens for unavailable', async () => {
+ const { mux } = createMux();
+ mux.subscribe('op-1');
+
+ let ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(500);
+ ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(1000);
+ ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(2000);
+ await settle();
+
+ expect(mux.isUnavailable).toBe(false);
+ expect(mockWsInstances).toHaveLength(4);
+ });
+
+ it('does not spend the budget on a healthy socket that drops', async () => {
+ const { mux } = createMux();
+ const onUnavailable = vi.fn();
+ mux.on('unavailable', onUnavailable);
+ mux.subscribe('op-1');
+
+ // A working connection that later drops is a network event, not evidence
+ // that this deployment cannot serve v2.
+ let ws = await connectAndReady(mux);
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(500);
+ ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(1000);
+ ws = await settle();
+ ws.simulateClose(1006);
+ expect(onUnavailable).not.toHaveBeenCalled();
+
+ // Three dials that never reached `ready` do spend it.
+ await vi.advanceTimersByTimeAsync(2000);
+ ws = await settle();
+ ws.simulateClose(1006);
+ expect(onUnavailable).toHaveBeenCalledOnce();
+ });
+
+ it('counts token failures that follow a healthy socket', async () => {
+ // The server can lose `issueGatewayUserToken` under the client (a bundle
+ // deployed ahead of its server). Minting is part of the dial, so those
+ // attempts have to spend the budget like any other failed dial.
+ const getToken = vi
+ .fn()
+ .mockResolvedValueOnce('tok')
+ .mockRejectedValue(new Error('404 issueGatewayUserToken'));
+ const { mux } = createMux({ getToken });
+ mux.on('error', () => {});
+ const onUnavailable = vi.fn();
+ mux.on('unavailable', onUnavailable);
+ mux.subscribe('op-1');
+
+ const ws = await connectAndReady(mux);
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(500);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onUnavailable).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(onUnavailable).toHaveBeenCalledOnce();
+ });
+
+ it('does not spend the budget on token refreshes', async () => {
+ const { mux } = createMux();
+ const onUnavailable = vi.fn();
+ mux.on('unavailable', onUnavailable);
+ mux.subscribe('op-1');
+
+ // Two 4401 refreshes (their own budget) then one ordinary failure must
+ // not add up to the dial budget.
+ let ws = await settle();
+ ws.simulateClose(4401);
+ ws = await settle();
+ ws.simulateClose(4401);
+ ws = await settle();
+ ws.simulateClose(1006);
+
+ expect(onUnavailable).not.toHaveBeenCalled();
+ });
+
+ it('rejects connect() once unavailable', async () => {
+ const { mux } = createMux();
+ mux.on('unavailable', () => {});
+ mux.subscribe('op-1');
+
+ let ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(500);
+ ws = await settle();
+ ws.simulateClose(1006);
+ await vi.advanceTimersByTimeAsync(1000);
+ ws = await settle();
+ ws.simulateClose(1006);
+
+ await expect(mux.connect()).rejects.toThrow('unavailable');
+ });
+ });
});
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
index 97570ad9c11..5eb57a0f9ba 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
@@ -26,6 +26,7 @@ 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 MAX_CONSECUTIVE_DIAL_FAILURES = 3;
const TOOL_RESULT_TTL = 120_000; // 120s
const AUTH_CLOSE_CODE = 4401;
/** Must match the hub's WebSocketRequestResponsePair byte-for-byte. */
@@ -62,6 +63,10 @@ class ListenerMap {
};
}
+ has(event: string): boolean {
+ return (this.listeners.get(event)?.size ?? 0) > 0;
+ }
+
emit(event: string, ...args: unknown[]): void {
const set = this.listeners.get(event);
if (!set) return;
@@ -334,6 +339,11 @@ export class GatewayMuxClient {
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempt = 0;
private consecutiveAuthFailures = 0;
+ /** Dials that never reached `ready`, since the last one that did. */
+ private consecutiveDialFailures = 0;
+ /** Whether the socket now being torn down ever reached `ready`. */
+ private currentDialReachedReady = false;
+ private declaredUnavailable = false;
private browserListenersInstalled = false;
private readonly subscriptions = new Map<string, Set<OperationSubscriptionImpl>>();
@@ -350,6 +360,7 @@ export class GatewayMuxClient {
private readonly autoReconnect: boolean;
private readonly heartbeatIntervalMs: number;
private readonly keepAlive: boolean;
+ private readonly maxDialFailures: number;
constructor(options: GatewayMuxClientOptions) {
this.gatewayUrl = options.gatewayUrl;
@@ -358,6 +369,7 @@ export class GatewayMuxClient {
this.autoReconnect = options.autoReconnect ?? true;
this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL;
this.keepAlive = options.keepAlive ?? false;
+ this.maxDialFailures = options.maxDialFailures ?? MAX_CONSECUTIVE_DIAL_FAILURES;
}
// ─── Public API ───
@@ -366,6 +378,11 @@ export class GatewayMuxClient {
return this._status;
}
+ /** True once this mux gave up on protocol v2 (see the `unavailable` event). */
+ get isUnavailable(): boolean {
+ return this.declaredUnavailable;
+ }
+
on<K extends keyof GatewayMuxClientEvents>(
event: K,
listener: GatewayMuxClientEvents[K],
@@ -379,6 +396,8 @@ export class GatewayMuxClient {
*/
connect(): Promise<void> {
this.clearIdleClose();
+ if (this.declaredUnavailable)
+ return Promise.reject(new Error('GatewayMuxClient is unavailable'));
if (this._status === 'connected') return Promise.resolve();
this.intentionalDisconnect = false;
this.installBrowserListeners();
@@ -472,6 +491,29 @@ export class GatewayMuxClient {
}
}
+ /**
+ * Remove and return the tool results still queued for an operation.
+ *
+ * `sendForSubscription` reports a queued result as sent, so the caller that
+ * produced it will not retry. An owner moving the operation to another
+ * transport (the v1 fallback after `unavailable`) must take these first and
+ * deliver them itself β€” unsubscribing drops them, and the server would then
+ * sit on the tool call until it times out. Expired entries are not returned.
+ */
+ takePendingToolResults(operationId: string): ToolResultPayload[] {
+ const now = Date.now();
+ const taken: ToolResultPayload[] = [];
+ this.toolResultQueue = this.toolResultQueue.filter((entry) => {
+ if (entry.message.operationId !== operationId) return true;
+ if (now - entry.at <= TOOL_RESULT_TTL) {
+ const { operationId: _operationId, type: _type, ...payload } = entry.message;
+ taken.push(payload);
+ }
+ return false;
+ });
+ return taken;
+ }
+
/** @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;
@@ -485,11 +527,17 @@ export class GatewayMuxClient {
// ─── Connection logic ───
private async doConnect(): Promise<void> {
+ if (this.declaredUnavailable) return;
if (this.intentionalDisconnect || this.ws || this.connectInFlight) return;
const generation = ++this.connectGeneration;
this.connectInFlight = true;
this.clearReconnectTimer();
this.setStatus('connecting');
+ // Before the token round trip, not after: minting is part of the dial, and
+ // a `getToken` that keeps rejecting is exactly the "this deployment cannot
+ // serve v2" case the budget exists for. Left set from the previous socket,
+ // those attempts would never count and the page would retry forever.
+ this.currentDialReachedReady = false;
let token: string;
try {
@@ -547,6 +595,8 @@ export class GatewayMuxClient {
case 'ready': {
this.reconnectAttempt = 0;
this.consecutiveAuthFailures = 0;
+ this.consecutiveDialFailures = 0;
+ this.currentDialReachedReady = true;
this.setStatus('connected');
this.startHeartbeat();
// Subscribe before flushing: the hub rejects op messages from a
@@ -619,6 +669,26 @@ export class GatewayMuxClient {
};
private handleConnectionLost(delayOverride?: number): void {
+ // Only a dial that never reached `ready` counts against the budget. A
+ // socket that worked and then dropped is a network event, not evidence
+ // that this deployment cannot serve v2; a refused token (`delayOverride`
+ // 0, immediate refresh) has its own budget in `consecutiveAuthFailures`.
+ // Counting either here would spend the fallback budget on a link that is
+ // fine and strand the page on v1 for the rest of the session.
+ const failedDial = delayOverride === undefined && !this.currentDialReachedReady;
+ if (failedDial) this.consecutiveDialFailures++;
+
+ // Retrying a deployment that cannot serve v2 at all only spins: give the
+ // owner the chance to fall back instead.
+ if (
+ failedDial &&
+ this.consecutiveDialFailures >= this.maxDialFailures &&
+ this.listeners.has('unavailable')
+ ) {
+ this.markUnavailable(`no usable connection after ${this.consecutiveDialFailures} attempts`);
+ return;
+ }
+
// An idle lazy mux that loses its socket just stays down (see isIdle).
if (this.autoReconnect && !this.intentionalDisconnect && !this.isIdle()) {
this.scheduleReconnect(delayOverride);
@@ -631,6 +701,14 @@ export class GatewayMuxClient {
}
private failAuth(reason: string): void {
+ // With a fallback listener attached, a refused token is a v2 problem, not
+ // the end of the run: the v1 socket mints its own per-operation token from
+ // a different endpoint, so hand the subscriptions back intact.
+ if (this.listeners.has('unavailable')) {
+ this.markUnavailable(reason);
+ return;
+ }
+
this.cleanup();
// Detach the subscriptions before failing them: `fail` unsubscribes, and an
// idle-close from `removeSubscription` must not race this teardown.
@@ -643,6 +721,27 @@ export class GatewayMuxClient {
this.listeners.emit('disconnected');
}
+ /**
+ * Terminal for this mux: stop dialing and tell the owner to fall back.
+ *
+ * Subscriptions are deliberately left alone β€” they are not failed and no
+ * terminal status is broadcast, because the owner re-establishes each
+ * operation on the v1 transport and a `session_complete` here would end the
+ * run instead.
+ */
+ private markUnavailable(reason: string): void {
+ if (this.declaredUnavailable) return;
+ this.declaredUnavailable = true;
+ this.intentionalDisconnect = true;
+ this.connectGeneration++;
+ this.connectInFlight = false;
+ this.cleanup();
+ this.setStatus('disconnected');
+ this.rejectWaiters(new Error(`Gateway mux unavailable: ${reason}`));
+ console.error('[GatewayMuxClient] protocol v2 unavailable: %s', reason);
+ this.listeners.emit('unavailable', reason);
+ }
+
// ─── Heartbeat ───
private startHeartbeat(): void {
diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.test.ts b/packages/agent-gateway-client/src/mux/createOperationClient.test.ts
index fd03eb1bfd1..ad18c19459f 100644
--- a/packages/agent-gateway-client/src/mux/createOperationClient.test.ts
+++ b/packages/agent-gateway-client/src/mux/createOperationClient.test.ts
@@ -282,6 +282,23 @@ describe('createOperationClient', () => {
expect(late).not.toHaveBeenCalled();
});
+ it('exposes the applied cursor so another transport can resume from it', async () => {
+ const mux = createMux();
+ const ws = await readyMux(mux);
+ const client = createOperationClient(mux, 'op-1');
+ expect(client.lastEventId).toBe('');
+
+ client.connect();
+ ws.simulateMessage(agentEvent('7'));
+ ws.simulateMessage(agentEvent('8'));
+ expect(client.lastEventId).toBe('8');
+
+ // Still readable after the subscription ends β€” the v1 handoff reads it
+ // right as it tears this client down.
+ client.disconnect();
+ expect(client.lastEventId).toBe('8');
+ });
+
it('reconnect() resubscribes from the last applied event id without emitting disconnected', async () => {
const mux = createMux();
const ws = await readyMux(mux);
diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.ts b/packages/agent-gateway-client/src/mux/createOperationClient.ts
index 68bd742c2fd..194cc1cde7d 100644
--- a/packages/agent-gateway-client/src/mux/createOperationClient.ts
+++ b/packages/agent-gateway-client/src/mux/createOperationClient.ts
@@ -28,6 +28,11 @@ export interface OperationClient {
readonly connectionStatus: ConnectionStatus;
/** Unsubscribe; emits `disconnected` like v1. */
disconnect: () => void;
+ /**
+ * Highest event id applied so far β€” the cursor another transport must resume
+ * from if this operation moves off the shared socket.
+ */
+ readonly lastEventId: string;
on: <K extends keyof OperationClientEvents>(
event: K,
listener: OperationClientEvents[K],
@@ -132,6 +137,9 @@ export const createOperationClient = (
get connectionStatus() {
return status;
},
+ get lastEventId() {
+ return subscription?.lastEventId || lastEventId;
+ },
connect,
disconnect: () => {
release();
diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.ts
index c25cc44c002..74270a65fa5 100644
--- a/packages/agent-gateway-client/src/mux/types.ts
+++ b/packages/agent-gateway-client/src/mux/types.ts
@@ -190,6 +190,14 @@ export interface GatewayMuxClientOptions {
* even with nothing subscribed.
*/
keepAlive?: boolean;
+ /**
+ * Consecutive dial failures after which the mux declares itself unavailable
+ * and emits `unavailable` instead of retrying forever (default: 3).
+ *
+ * Only honoured when someone listens for `unavailable`: a standalone client
+ * with no fallback keeps its original behaviour (retry with backoff).
+ */
+ maxDialFailures?: number;
}
export type GatewayMuxStatus = 'connected' | 'connecting' | 'disconnected';
@@ -201,6 +209,13 @@ export interface GatewayMuxClientEvents {
lifecycle: (lifecycle: MuxOpLifecycleMessage) => void;
reconnecting: (delay: number) => void;
status_changed: (status: GatewayMuxStatus) => void;
+ /**
+ * This deployment cannot serve protocol v2 to this client: the token could
+ * not be minted, `/v2/ws` is not there, or the hub refused the token past
+ * the auth-retry budget. Terminal β€” the mux stops dialing and the owner is
+ * expected to fall back to the v1 per-operation socket.
+ */
+ unavailable: (reason: string) => void;
}
// ─── Operation subscription ───
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index b9b5a7e1240..ed2cb200d1f 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -505,6 +505,15 @@ export interface AgentStreamClientOptions {
autoReconnect?: boolean;
/** Gateway WebSocket URL base (e.g. https://gateway.lobehub.com) */
gatewayUrl: string;
+ /**
+ * Last event id this operation has already applied, when the stream is being
+ * picked up from another transport (the v1 fallback after the multiplexed
+ * socket gave up). Both protocols read ids from the same per-operation
+ * sequence, so the first `resume` replays only what came after it β€” events
+ * the client already consumed, `tool_execute` included, are not delivered
+ * twice. Absent β‡’ replay from the beginning.
+ */
+ lastEventId?: string;
/** Operation ID to subscribe to */
operationId: string;
/**
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
index 11280cd728c..a87a97f787c 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
@@ -49,6 +49,7 @@ const mockUserState = vi.hoisted(() => ({
}));
vi.mock('@/store/user', () => ({
+ getUserStoreState: vi.fn(() => mockUserState),
useUserStore: { getState: vi.fn(() => mockUserState) },
}));
@@ -56,6 +57,7 @@ vi.mock('@/store/user/selectors', () => ({
labPreferSelectors: { enableGatewayMux: () => mockLab.enableGatewayMux },
settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },
toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },
+ userGeneralSettingsSelectors: { telemetry: () => false },
userProfileSelectors: { userId: (state: typeof mockUserState) => state.profile.id },
}));
@@ -132,6 +134,7 @@ function createMockOperationClient(): OperationClient & Emitter {
connectionStatus: 'disconnected',
disconnect: vi.fn(),
emit,
+ lastEventId: '',
on: on as OperationClient['on'],
reconnect: vi.fn(async () => {}),
sendToolResult: vi.fn(() => true),
@@ -148,6 +151,7 @@ function createFakeMux(): GatewayMuxClient & Emitter {
on,
status: 'disconnected',
subscribe: vi.fn(),
+ takePendingToolResults: vi.fn(() => []),
} as unknown as GatewayMuxClient & Emitter;
}
@@ -363,6 +367,119 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {
});
});
+ describe('fallback to v1 when the mux is unavailable', () => {
+ const connectParams = (operationId: string) => ({
+ executor: true,
+ gatewayUrl: GATEWAY_URL,
+ operationId,
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+
+ it('re-establishes every live operation on the v1 socket, resuming', () => {
+ const { action, mux, state, v1Client } = createTestAction();
+
+ action.connectToGateway(connectParams('op-1'));
+ action.connectToGateway(connectParams('op-2'));
+ expect(action.createClient).not.toHaveBeenCalled();
+
+ mux.emit('unavailable', 'no usable connection after 3 attempts');
+
+ expect(action.createClient).toHaveBeenCalledTimes(2);
+ expect(action.createClient).toHaveBeenNthCalledWith(1, {
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'op-1',
+ // The run kept executing on the server while the mux was failing, so a
+ // fresh subscribe would skip everything it missed.
+ resumeOnConnect: true,
+ token: 'tok',
+ });
+ expect(v1Client.connect).toHaveBeenCalledTimes(2);
+ expect(state.gatewayConnections['op-1'].client).toBe(v1Client);
+ expect(state.gatewayConnections['op-2'].client).toBe(v1Client);
+ });
+
+ it('resumes the v1 socket from the cursor the mux had already delivered', () => {
+ const { action, mux, muxClient } = createTestAction();
+
+ action.connectToGateway(connectParams('op-1'));
+ // Mid-run: the shared socket had streamed through event 42 before dying.
+ (muxClient as { lastEventId: string }).lastEventId = '42';
+ mux.emit('unavailable', 'no usable connection after 3 attempts');
+
+ // Replaying from the start would re-apply chunks and re-run
+ // `tool_execute` events this tab already executed.
+ expect(action.createClient).toHaveBeenCalledWith({
+ gatewayUrl: GATEWAY_URL,
+ lastEventId: '42',
+ operationId: 'op-1',
+ resumeOnConnect: true,
+ token: 'tok',
+ });
+ });
+
+ it('sends later connects straight to v1 without touching the mux again', () => {
+ const { action, mux } = createTestAction();
+
+ action.connectToGateway(connectParams('op-1'));
+ mux.emit('unavailable', 'auth_failed');
+ vi.mocked(action.createMuxClient).mockClear();
+
+ action.connectToGateway(connectParams('op-2'));
+
+ expect(action.createMuxClient).not.toHaveBeenCalled();
+ expect(action.createClient).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-2' }),
+ );
+ });
+
+ it('delivers tool results the mux had queued once the v1 socket connects', () => {
+ const { action, mux, state, v1Client } = createTestAction();
+ const pending = { content: 'tool output', success: true, toolCallId: 'call_1' };
+ vi.mocked(mux.takePendingToolResults).mockImplementation((operationId) =>
+ operationId === 'op-1' ? [pending] : [],
+ );
+
+ action.connectToGateway(connectParams('op-1'));
+ mux.emit('unavailable', 'no usable connection after 3 attempts');
+
+ // The executing tool was already told this result was sent; losing it
+ // would park the run until the server's tool timeout.
+ expect(mux.takePendingToolResults).toHaveBeenCalledWith('op-1');
+ expect(v1Client.sendToolResult).not.toHaveBeenCalled();
+
+ state.gatewayConnections['op-1'].status = 'connected';
+ v1Client.emit('connected');
+
+ expect(v1Client.sendToolResult).toHaveBeenCalledWith(pending);
+ });
+
+ it('keeps retrying a carried-over result on the next connect if the first send fails', () => {
+ const { action, mux, v1Client } = createTestAction();
+ const pending = { content: 'tool output', success: true, toolCallId: 'call_1' };
+ vi.mocked(mux.takePendingToolResults).mockReturnValue([pending]);
+ vi.mocked(v1Client.sendToolResult).mockReturnValueOnce(false).mockReturnValue(true);
+
+ action.connectToGateway(connectParams('op-1'));
+ mux.emit('unavailable', 'auth_failed');
+ v1Client.emit('connected');
+ v1Client.emit('connected');
+ v1Client.emit('connected');
+
+ expect(v1Client.sendToolResult).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves a completed operation alone', () => {
+ const { action, mux } = createTestAction();
+
+ action.connectToGateway(connectParams('op-1'));
+ action.disconnectFromGateway('op-1');
+ mux.emit('unavailable', 'auth_failed');
+
+ expect(action.createClient).not.toHaveBeenCalled();
+ });
+ });
+
describe('warmupGatewayMux', () => {
const withServerConfig = (serverConfig: Record<string, unknown>) => {
(globalThis as any).window = {
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 e238c5452a2..6fb30459eec 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -9,6 +9,7 @@ import {
type MuxOpLifecycleMessage,
type OperationClient,
type OperationClientOptions,
+ type ToolResultPayload,
} from '@lobechat/agent-gateway-client';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
@@ -27,6 +28,7 @@ import {
getRuntimeCanManageAgent,
} from '@/helpers/agentManagementAccess';
import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';
+import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';
import {
aiAgentService,
type ResumeApprovalParam,
@@ -62,7 +64,12 @@ import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
-import { type GatewayMuxIdentity, getGatewayMux } from './muxRegistry';
+import {
+ type GatewayMuxIdentity,
+ getGatewayMux,
+ isGatewayMuxUnavailable,
+ markGatewayMuxUnavailable,
+} from './muxRegistry';
import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMessagesFlag';
const getGatewayServerConfig = () =>
@@ -218,6 +225,12 @@ export interface ConnectGatewayParams {
* Gateway WebSocket URL (e.g. https://agent-gateway.lobehub.com)
*/
gatewayUrl: string;
+ /**
+ * Last event id this operation has already applied. Set when the stream is
+ * picked up from another transport, so the resume replays only what came
+ * after it instead of re-delivering events the run already handled.
+ */
+ lastEventId?: string;
/**
* Callback for each agent event received
*/
@@ -309,6 +322,18 @@ export class GatewayActionImpl {
/** Muxes whose `lifecycle` stream already feeds `gatewayFeed`. */
readonly #feedAttachedMuxes = new WeakSet<GatewayMuxClient>();
+ /** Muxes already wired to re-establish their operations on v1. */
+ readonly #fallbackAttachedMuxes = new WeakSet<GatewayMuxClient>();
+
+ /**
+ * How to re-establish each mux-backed operation on the v1 transport, kept
+ * per live connection so a mux that gives up mid-run can hand its runs over
+ * instead of leaving them without a stream. Tagged with the mux it rides on,
+ * because the owner and share-visitor identities have separate sockets and
+ * only the failing one's operations move.
+ */
+ readonly #muxFallbacks = new Map<string, { mux: GatewayMuxClient; redial: () => void }>();
+
constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
void _api;
this.#set = set;
@@ -340,6 +365,69 @@ export class GatewayActionImpl {
});
};
+ /**
+ * Hand every operation on this mux back to the v1 per-operation socket once
+ * the mux declares protocol v2 unusable.
+ *
+ * Attached once per mux. `connectToGateway` is re-entered with the original
+ * params, and `isGatewayMuxUnavailable` now routes it to `createClient`, so
+ * the run keeps the same handlers and resumes from the server's buffer
+ * instead of surfacing as a stalled stream.
+ */
+ #attachMuxFallback = (mux: GatewayMuxClient, identity: GatewayMuxIdentity): void => {
+ if (this.#fallbackAttachedMuxes.has(mux)) return;
+ this.#fallbackAttachedMuxes.add(mux);
+ mux.on('unavailable', (reason) => {
+ markGatewayMuxUnavailable(identity);
+ const affected = [...this.#muxFallbacks.entries()].filter(([, entry]) => entry.mux === mux);
+ for (const [operationId] of affected) this.#muxFallbacks.delete(operationId);
+ // Telemetry must never be what keeps a run from recovering.
+ void trackProductUsageEvent({
+ name: 'gateway_transport_fallback',
+ properties: { operation_count: affected.length, reason },
+ }).catch(() => {});
+ for (const [operationId, entry] of affected) {
+ // Taken before the redial: its disconnect unsubscribes the old
+ // operation, which drops whatever is still queued, and the tool that
+ // produced these was already told they were sent.
+ const pendingToolResults = mux.takePendingToolResults(operationId);
+ try {
+ entry.redial();
+ } catch (error) {
+ console.error('[Gateway] failed to fall back to the v1 transport:', error);
+ continue;
+ }
+ if (pendingToolResults.length > 0) {
+ this.#deliverOnConnect(operationId, pendingToolResults);
+ }
+ }
+ });
+ };
+
+ /**
+ * Send tool results over an operation's connection as soon as it is up.
+ *
+ * The v1 client has no outbound queue β€” `sendToolResult` on a socket that is
+ * still connecting just returns false β€” so results carried over from a mux
+ * wait for `connected` here. Anything that still cannot be sent then is left
+ * to the server's own tool timeout, the same as a v1 result sent into a dead
+ * socket today.
+ */
+ #deliverOnConnect = (operationId: string, results: ToolResultPayload[]): void => {
+ const client = this.#get().gatewayConnections[operationId]?.client;
+ if (!client) return;
+
+ // The v1 client's `on` hands back no unsubscribe, so the listener goes
+ // inert once everything has been delivered instead of detaching.
+ let remaining = results;
+ const flush = () => {
+ if (remaining.length === 0) return;
+ remaining = remaining.filter((result) => !client.sendToolResult(result));
+ };
+ client.on('connected', flush);
+ if (this.#get().gatewayConnections[operationId]?.status === 'connected') flush();
+ };
+
/**
* Connect to the Agent Gateway for a specific operation.
* Creates an AgentStreamClient, manages its lifecycle, and wires up event callbacks.
@@ -352,6 +440,7 @@ export class GatewayActionImpl {
gatewayUrl,
token,
topicId,
+ lastEventId,
onEvent,
onSessionComplete,
resumeOnConnect,
@@ -364,18 +453,49 @@ export class GatewayActionImpl {
// not inherit the creator's Labs preference. Owner runs keep the existing
// opt-in rollout: a connection keeps the transport it was opened with
// even if the toggle flips mid-run.
+ const muxIdentity: GatewayMuxIdentity = { agentShareId, gatewayUrl };
const useGatewayMux =
- Boolean(agentShareId) || labPreferSelectors.enableGatewayMux(useUserStore.getState());
+ (Boolean(agentShareId) || labPreferSelectors.enableGatewayMux(useUserStore.getState())) &&
+ !isGatewayMuxUnavailable(muxIdentity);
let muxClient: OperationClient | undefined;
if (useGatewayMux) {
- const mux = this.resolveGatewayMux({ agentShareId, gatewayUrl });
+ const mux = this.resolveGatewayMux(muxIdentity);
this.#attachGatewayFeed(mux);
+ this.#attachMuxFallback(mux, muxIdentity);
// 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 operationMuxClient = this.createMuxClient(mux, operationId, {
+ executor,
+ ...(lastEventId && { lastEventId }),
+ resumeOnConnect,
+ });
+ muxClient = operationMuxClient;
+ // Re-establishing on v1 always resumes: the run has been executing on the
+ // server the whole time the mux was failing to reach it, so a fresh
+ // subscribe would skip everything it missed. And it resumes from the
+ // mux's cursor, read at the moment of the handoff: both protocols number
+ // events from the same per-operation sequence, and replaying from the
+ // start would re-apply streamed chunks and re-run `tool_execute` events
+ // this tab already executed.
+ this.#muxFallbacks.set(operationId, {
+ mux,
+ redial: () =>
+ this.connectToGateway({
+ ...params,
+ lastEventId: operationMuxClient.lastEventId || lastEventId,
+ resumeOnConnect: true,
+ }),
+ });
}
const client: GatewayConnection['client'] =
- muxClient ?? this.createClient({ gatewayUrl, operationId, resumeOnConnect, token });
+ muxClient ??
+ this.createClient({
+ gatewayUrl,
+ ...(lastEventId && { lastEventId }),
+ operationId,
+ resumeOnConnect,
+ token,
+ });
// Track connection in store
this.#set(
@@ -569,8 +689,12 @@ export class GatewayActionImpl {
const serverConfig = getGatewayServerConfig();
if (!serverConfig?.agentGatewayUrl || !serverConfig.enableGatewayMode) return;
- const mux = this.resolveGatewayMux({ gatewayUrl: serverConfig.agentGatewayUrl });
+ const identity: GatewayMuxIdentity = { gatewayUrl: serverConfig.agentGatewayUrl };
+ if (isGatewayMuxUnavailable(identity)) return;
+
+ const mux = this.resolveGatewayMux(identity);
this.#attachGatewayFeed(mux);
+ this.#attachMuxFallback(mux, identity);
mux.connect().catch(() => {
// The mux keeps retrying with backoff; failures surface on its own
// `error` / `reconnecting` listeners.
@@ -1770,6 +1894,7 @@ export class GatewayActionImpl {
};
private internal_cleanupGatewayConnection = (operationId: string): void => {
+ this.#muxFallbacks.delete(operationId);
this.#set(
(state) => {
const { [operationId]: _, ...rest } = state.gatewayConnections;
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts
index 4eeb2139599..b62ab6da1f0 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry.ts
@@ -16,6 +16,15 @@ export interface GatewayMuxIdentity {
const registry = new Map<string, GatewayMuxClient>();
+/**
+ * Identities whose mux gave up on protocol v2 (`/v2/ws` missing, the token
+ * endpoint absent, the hub refusing the token). Page-scoped on purpose: a
+ * reload retries v2, so a transient outage does not pin the tab to v1 for the
+ * rest of the session, while a deployment that genuinely has no v2 only pays
+ * the dial budget once per page.
+ */
+const unavailableIdentities = new Set<string>();
+
const identityKey = ({ agentShareId, gatewayUrl }: GatewayMuxIdentity): string =>
`${gatewayUrl}|${agentShareId ?? 'owner'}`;
@@ -56,6 +65,24 @@ export const getGatewayMux = (identity: GatewayMuxIdentity): GatewayMuxClient =>
return mux;
};
+/**
+ * Whether protocol v2 has already failed for this identity on this page, in
+ * which case the caller must use the v1 per-operation socket instead.
+ */
+export const isGatewayMuxUnavailable = (identity: GatewayMuxIdentity): boolean =>
+ unavailableIdentities.has(identityKey(identity));
+
+/**
+ * Record that protocol v2 does not work for this identity, and forget the dead
+ * mux so a later `getGatewayMux` never hands out a client that will not dial
+ * again. Called by the transport when the mux reports itself `unavailable`.
+ */
+export const markGatewayMuxUnavailable = (identity: GatewayMuxIdentity): void => {
+ const key = identityKey(identity);
+ unavailableIdentities.add(key);
+ registry.delete(key);
+};
+
/**
* Tear down every mux (they hold window listeners and the lifecycle β†’ store
* feed) and forget them. Called when the user-data context resets
@@ -66,4 +93,7 @@ export const getGatewayMux = (identity: GatewayMuxIdentity): GatewayMuxClient =>
export const resetGatewayMuxRegistry = (): void => {
for (const mux of registry.values()) mux.disconnect();
registry.clear();
+ // A new user-data context is a new deployment as far as this page knows
+ // (the desktop app switching remote servers), so the v2 verdict starts over.
+ unavailableIdentities.clear();
};