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): multiplex broadcast member streams onto the supervisor WS (#16388)

Arvin Xu0e92b07e5b4b
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index fbf7180a612..71a7afbc336 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -91,6 +91,7 @@ export class AgentRuntimeCoordinator {
operationId: string,
data: {
agentConfig?: any;
+ mirrorToOperationId?: string;
modelRuntimeConfig?: any;
userId?: string;
workspaceId?: string;
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 3fe4ae0a0ea..6f117d9634b 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -22,6 +22,14 @@ export interface AgentOperationMetadata {
agentConfig?: any;
createdAt: string;
lastActiveAt: string;
+ /**
+ * When set, the Gateway stream notifier mirrors this operation's stream events
+ * onto the named operation's Gateway channel as well (single-connection
+ * multiplexing, LOBE-10868). Used so a broadcast member's streaming events
+ * also flow down the supervisor's existing WebSocket β€” the supervisor's own
+ * operationId β€” instead of stranding on a member channel nobody subscribes to.
+ */
+ mirrorToOperationId?: string;
modelRuntimeConfig?: any;
status: AgentState['status'];
totalCost: number;
@@ -197,6 +205,7 @@ export class AgentStateManager {
modelRuntimeConfig: metadata.modelRuntimeConfig
? JSON.parse(metadata.modelRuntimeConfig)
: undefined,
+ mirrorToOperationId: metadata.mirrorToOperationId || undefined,
status: metadata.status as AgentState['status'],
totalCost: parseFloat(metadata.totalCost) || 0,
totalSteps: parseInt(metadata.totalSteps) || 0,
@@ -216,6 +225,7 @@ export class AgentStateManager {
operationId: string,
data: {
agentConfig?: any;
+ mirrorToOperationId?: string;
modelRuntimeConfig?: any;
userId?: string;
workspaceId?: string;
@@ -228,6 +238,7 @@ export class AgentStateManager {
agentConfig: data.agentConfig,
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
+ mirrorToOperationId: data.mirrorToOperationId,
modelRuntimeConfig: data.modelRuntimeConfig,
status: 'idle',
totalCost: 0,
@@ -247,6 +258,8 @@ export class AgentStateManager {
if (metadata.userId) redisData.userId = metadata.userId;
if (metadata.workspaceId) redisData.workspaceId = metadata.workspaceId;
+ if (metadata.mirrorToOperationId)
+ redisData.mirrorToOperationId = metadata.mirrorToOperationId;
if (metadata.modelRuntimeConfig)
redisData.modelRuntimeConfig = JSON.stringify(metadata.modelRuntimeConfig);
if (metadata.agentConfig) redisData.agentConfig = JSON.stringify(metadata.agentConfig);
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 1ed868b2d31..2786c371099 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -25,10 +25,40 @@ const MAX_INFLIGHT = 20; // bounded concurrency
export class GatewayStreamNotifier implements IStreamEventManager {
private inflight = 0;
+ /**
+ * `operationId β†’ mirrorOperationId`. When an operation declares a
+ * `mirrorToOperationId` (an in-group broadcast/speak member pointing at its
+ * supervisor op), every Gateway push for that operation is additionally
+ * delivered to the mirror op's channel β€” so member streaming events ride down
+ * the supervisor's single WebSocket instead of stranding on a per-member
+ * channel nobody subscribes to (single-connection multiplexing, LOBE-10868).
+ *
+ * Two population paths, so this works both in-process AND across queue workers:
+ * - fast path: set at `publishAgentRuntimeInit` from the initial state (the
+ * in-memory runtime, and the process that created the op).
+ * - queue path: in `AGENT_RUNTIME_MODE=queue` the member's chunks are emitted
+ * by a QStash worker that never ran init for that op, so its map starts
+ * empty. `pushEvent` then lazily resolves the target from PERSISTED op
+ * metadata via `resolveMirrorTarget` (Redis) on the op's first event and
+ * caches it β€” converging the worker onto the same mapping.
+ * Cleared at `publishAgentRuntimeEnd`.
+ */
+ private mirrorTargets = new Map<string, string>();
+ /** Ops whose mirror target has been resolved (target found OR confirmed none). */
+ private mirrorResolved = new Set<string>();
+ /** In-flight resolutions, deduped per op so concurrent events share one read. */
+ private mirrorResolving = new Map<string, Promise<string | undefined>>();
+
constructor(
private inner: IStreamEventManager,
private gatewayUrl: string,
private serviceToken: string,
+ /**
+ * Resolves an op's persisted `mirrorToOperationId` (from op metadata). Lets a
+ * queue worker β€” which never ran the op's init β€” still mirror its stream
+ * events onto the supervisor channel. Omitted β‡’ in-process map only.
+ */
+ private resolveMirrorTarget?: (operationId: string) => Promise<string | undefined>,
) {
log('Gateway notifier initialized: %s', gatewayUrl);
}
@@ -63,6 +93,15 @@ export class GatewayStreamNotifier implements IStreamEventManager {
async publishAgentRuntimeInit(operationId: string, initialState: any): Promise<string> {
const result = await this.inner.publishAgentRuntimeInit(operationId, initialState);
+ // Register the mirror target (if any) before the first event flows, so this
+ // op's whole stream β€” including the events below β€” fans out to the
+ // supervisor's channel too.
+ const mirrorTo = initialState?.mirrorToOperationId;
+ if (typeof mirrorTo === 'string' && mirrorTo && mirrorTo !== operationId) {
+ this.mirrorTargets.set(operationId, mirrorTo);
+ log('mirror registered: %s β†’ %s', operationId, mirrorTo);
+ }
+
this.httpPost('/api/operations/init', {
operationId,
userId: initialState?.userId || 'unknown',
@@ -104,6 +143,12 @@ export class GatewayStreamNotifier implements IStreamEventManager {
type: 'agent_runtime_end',
});
+ // Terminal event has been forwarded (including any mirror); drop the mapping
+ // so it can't leak across a reused operationId.
+ this.mirrorTargets.delete(operationId);
+ this.mirrorResolved.delete(operationId);
+ this.mirrorResolving.delete(operationId);
+
return result;
}
@@ -160,6 +205,60 @@ export class GatewayStreamNotifier implements IStreamEventManager {
event: sanitizedEvent,
operationId,
}).catch(() => {});
+
+ // Single-connection multiplexing: also deliver to the mirror op's channel so
+ // the event rides down that connection's WebSocket. The event payload keeps
+ // its own `operationId`, which the client's event router uses to demux it
+ // back to the right member column. Only the delivery channel changes.
+ const mirrorTo = this.mirrorTargets.get(operationId);
+ if (mirrorTo) {
+ this.mirrorPush(mirrorTo, sanitizedEvent);
+ return;
+ }
+ // Queue worker: target not in the in-process map. Resolve it from persisted
+ // metadata once, then mirror this (and future) events. Concurrent events for
+ // the same op share one resolution and fire their mirror pushes in order.
+ if (!this.mirrorResolved.has(operationId)) {
+ void this.resolveMirror(operationId).then((target) => {
+ if (target) this.mirrorPush(target, sanitizedEvent);
+ });
+ }
+ }
+
+ private mirrorPush(mirrorTo: string, event: Record<string, unknown>) {
+ this.httpPost('/api/operations/push-event', { event, operationId: mirrorTo }).catch(() => {});
+ }
+
+ /**
+ * Resolve and cache an op's mirror target from persisted metadata. Returns the
+ * target (cached in `mirrorTargets`) or undefined when the op has none. Deduped
+ * so many concurrent events trigger a single metadata read.
+ */
+ private resolveMirror(operationId: string): Promise<string | undefined> {
+ const cached = this.mirrorTargets.get(operationId);
+ if (cached) return Promise.resolve(cached);
+ if (this.mirrorResolved.has(operationId) || !this.resolveMirrorTarget) {
+ return Promise.resolve(undefined);
+ }
+ let pending = this.mirrorResolving.get(operationId);
+ if (!pending) {
+ pending = this.resolveMirrorTarget(operationId)
+ .then((target) => {
+ this.mirrorResolved.add(operationId);
+ this.mirrorResolving.delete(operationId);
+ if (target && target !== operationId) {
+ this.mirrorTargets.set(operationId, target);
+ return target;
+ }
+ return undefined;
+ })
+ .catch(() => {
+ this.mirrorResolving.delete(operationId);
+ return undefined;
+ });
+ this.mirrorResolving.set(operationId, pending);
+ }
+ return pending;
}
/**
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index 4ee8d4505eb..39021c4a142 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -120,6 +120,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
operationId: string,
data: {
agentConfig?: any;
+ mirrorToOperationId?: string;
modelRuntimeConfig?: any;
userId?: string;
workspaceId?: string;
@@ -129,6 +130,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
agentConfig: data.agentConfig,
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
+ mirrorToOperationId: data.mirrorToOperationId,
modelRuntimeConfig: data.modelRuntimeConfig,
status: 'idle',
totalCost: 0,
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index b54d1f74c26..025d7869445 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -493,4 +493,124 @@ describe('GatewayStreamNotifier', () => {
);
});
});
+
+ // ─── Single-connection multiplexing: mirror member events to supervisor op ───
+
+ describe('mirrorToOperationId (single-connection multiplexing)', () => {
+ const pushEventCalls = () =>
+ mockFetch.mock.calls
+ .filter(([url]) => String(url).endsWith('/api/operations/push-event'))
+ .map(([, init]) => JSON.parse((init as { body: string }).body));
+
+ it('mirrors a member op stream event to the supervisor channel, keeping the event operationId', async () => {
+ await notifier.publishAgentRuntimeInit('op-member', { mirrorToOperationId: 'op-supervisor' });
+
+ await notifier.publishStreamChunk('op-member', 0, {
+ chunkType: 'text',
+ content: 'hi',
+ } as StreamChunkData);
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const pushes = pushEventCalls().filter((b) => b.event?.type === 'stream_chunk');
+ // Delivered to BOTH the member channel and the supervisor channel.
+ expect(pushes.map((p) => p.operationId).sort()).toEqual(['op-member', 'op-supervisor']);
+ // Event payload keeps the member operationId so the client demuxes correctly.
+ for (const p of pushes) expect(p.event.operationId).toBe('op-member');
+ });
+
+ it('does not mirror when no mirrorToOperationId was registered', async () => {
+ await notifier.publishAgentRuntimeInit('op-solo', { userId: 'u1' });
+
+ await notifier.publishStreamChunk('op-solo', 0, {
+ chunkType: 'text',
+ content: 'hi',
+ } as StreamChunkData);
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const pushes = pushEventCalls().filter((b) => b.event?.type === 'stream_chunk');
+ expect(pushes.map((p) => p.operationId)).toEqual(['op-solo']);
+ });
+
+ it('ignores a self-referential mirror target', async () => {
+ await notifier.publishAgentRuntimeInit('op-x', { mirrorToOperationId: 'op-x' });
+
+ await notifier.publishStreamChunk('op-x', 0, {
+ chunkType: 'text',
+ content: 'hi',
+ } as StreamChunkData);
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const pushes = pushEventCalls().filter((b) => b.event?.type === 'stream_chunk');
+ expect(pushes.map((p) => p.operationId)).toEqual(['op-x']);
+ });
+
+ it('queue worker path: lazily resolves the mirror target from persisted metadata', async () => {
+ // Worker notifier never ran init for this op, so its in-process map is empty.
+ const resolve = vi.fn(async (op: string) =>
+ op === 'op-member-q' ? 'op-supervisor-q' : undefined,
+ );
+ const workerNotifier = new GatewayStreamNotifier(inner, gatewayUrl, serviceToken, resolve);
+
+ await workerNotifier.publishStreamChunk('op-member-q', 0, {
+ chunkType: 'text',
+ content: 'streamed-by-worker',
+ } as StreamChunkData);
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const pushes = pushEventCalls().filter(
+ (b) => b.event?.data?.content === 'streamed-by-worker',
+ );
+ expect(pushes.map((p) => p.operationId).sort()).toEqual(['op-member-q', 'op-supervisor-q']);
+
+ // Resolution is cached: a second event does not re-read metadata.
+ await workerNotifier.publishStreamChunk('op-member-q', 1, {
+ chunkType: 'text',
+ content: 'second',
+ } as StreamChunkData);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(resolve).toHaveBeenCalledTimes(1);
+ });
+
+ it('queue worker path: an op with no persisted mirror target is not mirrored', async () => {
+ const resolve = vi.fn(async () => undefined);
+ const workerNotifier = new GatewayStreamNotifier(inner, gatewayUrl, serviceToken, resolve);
+
+ await workerNotifier.publishStreamChunk('op-plain', 0, {
+ chunkType: 'text',
+ content: 'plain',
+ } as StreamChunkData);
+ await new Promise((r) => setTimeout(r, 50));
+
+ const pushes = pushEventCalls().filter((b) => b.event?.data?.content === 'plain');
+ expect(pushes.map((p) => p.operationId)).toEqual(['op-plain']);
+ });
+
+ it('stops mirroring after the member op reaches a terminal state', async () => {
+ await notifier.publishAgentRuntimeInit('op-member', { mirrorToOperationId: 'op-supervisor' });
+
+ await notifier.publishAgentRuntimeEnd({
+ finalState: {} as any,
+ operationId: 'op-member',
+ reason: 'completed',
+ stepIndex: 1,
+ });
+
+ // A late event after terminal must not mirror anymore.
+ await notifier.publishStreamChunk('op-member', 2, {
+ chunkType: 'text',
+ content: 'late',
+ } as StreamChunkData);
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ const lateChunk = pushEventCalls().filter(
+ (b) => b.event?.type === 'stream_chunk' && b.event?.data?.content === 'late',
+ );
+ expect(lateChunk.map((p) => p.operationId)).toEqual(['op-member']);
+ });
+ });
});
diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.ts
index 79666418cc5..6db1def9ef9 100644
--- a/apps/server/src/modules/AgentRuntime/factory.ts
+++ b/apps/server/src/modules/AgentRuntime/factory.ts
@@ -74,10 +74,19 @@ export const createStreamEventManager = (): IStreamEventManager => {
// Wrap with Gateway notifier when configured
if (appEnv.AGENT_GATEWAY_URL && appEnv.AGENT_GATEWAY_SERVICE_TOKEN) {
log('Wrapping with GatewayStreamNotifier (%s)', appEnv.AGENT_GATEWAY_URL);
+ // Resolver lets a queue worker (which never ran the member op's init) mirror
+ // its stream events onto the supervisor channel by reading the persisted
+ // `mirrorToOperationId` from op metadata. Shares the same state manager
+ // backing the runtime (in-memory singleton locally, Redis in queue mode).
+ const stateManager = createAgentStateManager();
return new GatewayStreamNotifier(
manager,
appEnv.AGENT_GATEWAY_URL,
appEnv.AGENT_GATEWAY_SERVICE_TOKEN,
+ async (operationId) => {
+ const meta = await stateManager.getOperationMetadata(operationId);
+ return meta?.mirrorToOperationId ?? undefined;
+ },
);
}
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 60117d3c667..71ab07ac848 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -36,6 +36,7 @@ export interface IAgentStateManager {
operationId: string,
data: {
agentConfig?: any;
+ mirrorToOperationId?: string;
modelRuntimeConfig?: any;
userId?: string;
workspaceId?: string;
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index f542bce9f45..e210a3cfa8a 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -524,9 +524,16 @@ export class AgentRuntimeService {
userInterventionConfig,
} as Partial<AgentState>;
- // Use coordinator to create operation, automatically sends initialization event
+ // Use coordinator to create operation, automatically sends initialization event.
+ // For an in-group broadcast/speak member, mirror its Gateway stream events
+ // onto the supervisor op's channel (parentOperationId) so they flow down the
+ // supervisor's existing WebSocket β€” the client subscribes to one connection,
+ // not one per member (single-connection multiplexing, LOBE-10868).
+ const mirrorToOperationId =
+ appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;
await this.coordinator.createAgentOperation(operationId, {
agentConfig,
+ mirrorToOperationId,
modelRuntimeConfig,
userId,
workspaceId: this.workspaceId,
diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.ts
index 818f32a3572..8b55eae72da 100644
--- a/packages/agent-gateway-client/src/client.test.ts
+++ b/packages/agent-gateway-client/src/client.test.ts
@@ -306,6 +306,45 @@ describe('AgentStreamClient', () => {
expect(client.connectionStatus).toBe('disconnected');
});
+ it('should NOT disconnect on a forwarded terminal for a different operationId', async () => {
+ // Multiplexed WS (LOBE-10868): a broadcast member's agent_runtime_end is
+ // mirrored onto the supervisor's channel. It must be emitted (so the member
+ // handler can finalize that member) but must NOT close the supervisor WS.
+ const client = createClient(); // operationId: 'op-123'
+ const events: any[] = [];
+ client.on('agent_event', (e) => events.push(e));
+
+ const ws = await connectAndAuth(client);
+ ws.simulateMessage({
+ event: {
+ data: { reason: 'done' },
+ operationId: 'op-member-456',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'agent_runtime_end',
+ },
+ type: 'agent_event',
+ });
+
+ expect(events).toHaveLength(1);
+ expect(events[0].operationId).toBe('op-member-456');
+ // Connection stays alive for the supervisor + sibling members.
+ expect(client.connectionStatus).toBe('connected');
+
+ // The owner op's own terminal still ends the session.
+ ws.simulateMessage({
+ event: {
+ data: {},
+ operationId: 'op-123',
+ stepIndex: 1,
+ timestamp: 2,
+ type: 'agent_runtime_end',
+ },
+ type: 'agent_event',
+ });
+ expect(client.connectionStatus).toBe('disconnected');
+ });
+
it('should emit session_complete and disconnect', async () => {
const client = createClient();
const onComplete = vi.fn();
diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.ts
index 514ad26032d..f2968fa92bf 100644
--- a/packages/agent-gateway-client/src/client.ts
+++ b/packages/agent-gateway-client/src/client.ts
@@ -283,13 +283,24 @@ export class AgentStreamClient extends TypedEmitter {
const agentEvent: AgentStreamEvent = message.event;
if (message.id) this.lastEventId = message.id;
+ // A single WS can be multiplexed: alongside this op's events it may
+ // carry forwarded events from other operations (e.g. broadcast council
+ // members mirrored onto the supervisor's channel, LOBE-10868). A
+ // terminal event ends the SESSION only when it belongs to THIS op β€”
+ // a member finishing must not disconnect the supervisor's socket and
+ // stop sibling/supervisor streaming. Events with no operationId
+ // (legacy gateway) are treated as this op's, preserving old behavior.
+ const isOwnTerminal =
+ (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') &&
+ (!agentEvent.operationId || agentEvent.operationId === this.operationId);
+
if (this.resumeMode) {
// Buffer events during resume β€” will be deduplicated and emitted after replay
this.resumeBuffer.push({ event: agentEvent, id: message.id });
this.scheduleResumeFlush();
- // Terminal events still end the session even in resume mode
- if (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') {
+ // Only this op's terminal ends the session (even in resume mode).
+ if (isOwnTerminal) {
this.sessionEnded = true;
this.flushResumeBuffer();
this.disconnect();
@@ -299,8 +310,10 @@ export class AgentStreamClient extends TypedEmitter {
this.emit('agent_event', agentEvent);
- // Terminal events β€” session is done, no need to reconnect
- if (agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') {
+ // This op's terminal β€” session is done, no need to reconnect. A
+ // forwarded member terminal is still emitted above (so its handler can
+ // finalize that member) but must NOT tear down this connection.
+ if (isOwnTerminal) {
this.sessionEnded = true;
this.disconnect();
}
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 7e64b273aeb..70167cdcbf7 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -23,6 +23,8 @@ import { settingsSelectors } from '@/store/user/selectors';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';
+import { createGatewayEventRouter } from './gatewayEventRouter';
+import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
/**
* When the agent runs against the local machine, resolve this desktop's
@@ -208,9 +210,16 @@ export class GatewayActionImpl {
});
};
- // Forward agent events to caller, and track terminal events
+ // Forward agent events to caller, and track terminal events.
+ //
+ // Only THIS op's terminal counts. On a multiplexed connection (LOBE-10868)
+ // the supervisor's WS also carries forwarded member terminals; a member
+ // finishing must not mark the supervisor run complete or stomp its unread
+ // status. Match on the event's operationId (absent β‡’ legacy single-op WS,
+ // treat as this op's to preserve prior behavior).
client.on('agent_event', (event) => {
- if (event.type === 'agent_runtime_end' || event.type === 'error') {
+ const isOwnOp = !event.operationId || event.operationId === operationId;
+ if (isOwnOp && (event.type === 'agent_runtime_end' || event.type === 'error')) {
receivedTerminalEvent = true;
}
// Only a clean completion counts as success β€” a cancel ('interrupted') or
@@ -218,6 +227,7 @@ export class GatewayActionImpl {
// branch so onSessionComplete clears the run back to 'active' instead of
// leaving the topic persisted as an unread completion.
if (
+ isOwnOp &&
event.type === 'agent_runtime_end' &&
isCompletedRuntimeEnd((event.data as { reason?: string } | undefined)?.reason)
) {
@@ -597,9 +607,21 @@ export class GatewayActionImpl {
}),
});
+ // Demux the supervisor's WebSocket: with single-connection multiplexing
+ // (LOBE-10868) this WS also carries each broadcast member's streaming events
+ // (forwarded server-side onto the supervisor op channel). Route owner events
+ // to the full handler and member events to render-only member handlers so a
+ // member's chunks stream into its own council column instead of corrupting
+ // the supervisor bubble.
+ const eventRouter = createGatewayEventRouter({
+ createMemberHandler: this.buildMemberHandlerFactory(execContext, gatewayOpId),
+ ownerHandler: eventHandler,
+ ownerOperationId: result.operationId,
+ });
+
this.#get().connectToGateway({
gatewayUrl: agentGatewayUrl,
- onEvent: eventHandler,
+ onEvent: eventRouter,
onSessionComplete: ({ succeeded, terminalReceived }) => {
// The gateway event handler already completed the op via the shared run
// lifecycle on `agent_runtime_end` / `error`. Only complete here as the
@@ -745,9 +767,18 @@ export class GatewayActionImpl {
}),
});
+ // Same demux as the initial-run path: a reconnected supervisor WS can also
+ // receive forwarded member events, so route them away from the supervisor
+ // handler (and stream them when the reconnect context carries the group).
+ const eventRouter = createGatewayEventRouter({
+ createMemberHandler: this.buildMemberHandlerFactory(context, gatewayOpId),
+ ownerHandler: eventHandler,
+ ownerOperationId: operationId,
+ });
+
this.#get().connectToGateway({
gatewayUrl: agentGatewayUrl,
- onEvent: eventHandler,
+ onEvent: eventRouter,
onSessionComplete: ({ succeeded, terminalReceived, authFailed }) => {
this.#get().internal_updateTopicLoading(topicId, false);
@@ -793,6 +824,41 @@ export class GatewayActionImpl {
});
};
+ /**
+ * Build the `createMemberHandler` factory for a run's event router, with a
+ * single memoized group-tree hydration shared across all of that run's member
+ * handlers. The first member to stream triggers one `getMessages` +
+ * `replaceMessages` so the canonical council structure (the `agentCouncil` tool
+ * message + every member row) lands β€” which is what makes the members render as
+ * parallel columns rather than a stack β€” and concurrent members reuse the same
+ * promise instead of each re-replacing the bucket and clobbering live content.
+ */
+ private buildMemberHandlerFactory = (
+ context: ConversationContext,
+ parentOperationId: string,
+ ): ((memberOperationId: string) => (event: AgentStreamEvent) => void) => {
+ let hydration: Promise<void> | undefined;
+ const ensureGroupHydrated = () => {
+ if (!hydration) {
+ hydration = messageService
+ .getMessages(context)
+ .then((messages) => {
+ this.#get().replaceMessages(messages, { context });
+ })
+ .catch(() => {});
+ }
+ return hydration;
+ };
+
+ return (memberOperationId: string) =>
+ createGatewayMemberStreamHandler(this.#get, {
+ context,
+ ensureGroupHydrated,
+ memberOperationId,
+ parentOperationId,
+ });
+ };
+
private internal_cleanupGatewayConnection = (operationId: string): void => {
this.#set(
(state) => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventRouter.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventRouter.test.ts
new file mode 100644
index 00000000000..b12b18a5a47
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventRouter.test.ts
@@ -0,0 +1,104 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createGatewayEventRouter } from './gatewayEventRouter';
+
+const evt = (operationId: string, type = 'stream_chunk'): AgentStreamEvent =>
+ ({ operationId, stepIndex: 0, timestamp: 0, type }) as unknown as AgentStreamEvent;
+
+describe('createGatewayEventRouter', () => {
+ it('routes owner-op events to the owner handler', () => {
+ const ownerHandler = vi.fn();
+ const createMemberHandler = vi.fn();
+
+ const route = createGatewayEventRouter({
+ createMemberHandler,
+ ownerHandler,
+ ownerOperationId: 'op_owner',
+ });
+
+ const e = evt('op_owner');
+ route(e);
+
+ expect(ownerHandler).toHaveBeenCalledWith(e);
+ expect(createMemberHandler).not.toHaveBeenCalled();
+ });
+
+ it('lazily creates one member handler per distinct operationId and reuses it', () => {
+ const ownerHandler = vi.fn();
+ const memberHandler = vi.fn();
+ const createMemberHandler = vi.fn(() => memberHandler);
+
+ const route = createGatewayEventRouter({
+ createMemberHandler,
+ ownerHandler,
+ ownerOperationId: 'op_owner',
+ });
+
+ route(evt('op_member_a'));
+ route(evt('op_member_a'));
+
+ expect(createMemberHandler).toHaveBeenCalledTimes(1);
+ expect(createMemberHandler).toHaveBeenCalledWith('op_member_a');
+ expect(memberHandler).toHaveBeenCalledTimes(2);
+ expect(ownerHandler).not.toHaveBeenCalled();
+ });
+
+ it('keeps separate handlers per member operation', () => {
+ const handlerA = vi.fn();
+ const handlerB = vi.fn();
+ const createMemberHandler = vi.fn((opId: string) => (opId === 'op_a' ? handlerA : handlerB));
+
+ const route = createGatewayEventRouter({
+ createMemberHandler,
+ ownerHandler: vi.fn(),
+ ownerOperationId: 'op_owner',
+ });
+
+ const a = evt('op_a');
+ const b = evt('op_b');
+ route(a);
+ route(b);
+
+ expect(createMemberHandler).toHaveBeenCalledTimes(2);
+ expect(handlerA).toHaveBeenCalledWith(a);
+ expect(handlerB).toHaveBeenCalledWith(b);
+ });
+
+ it('interleaves owner and member events without cross-talk', () => {
+ const ownerHandler = vi.fn();
+ const memberHandler = vi.fn();
+ const createMemberHandler = vi.fn(() => memberHandler);
+
+ const route = createGatewayEventRouter({
+ createMemberHandler,
+ ownerHandler,
+ ownerOperationId: 'op_owner',
+ });
+
+ route(evt('op_owner', 'stream_start'));
+ route(evt('op_member', 'stream_start'));
+ route(evt('op_owner', 'stream_chunk'));
+ route(evt('op_member', 'stream_chunk'));
+
+ expect(ownerHandler).toHaveBeenCalledTimes(2);
+ expect(memberHandler).toHaveBeenCalledTimes(2);
+ });
+
+ it('falls back to the owner handler when an event has no operationId', () => {
+ const ownerHandler = vi.fn();
+ const createMemberHandler = vi.fn();
+
+ const route = createGatewayEventRouter({
+ createMemberHandler,
+ ownerHandler,
+ ownerOperationId: 'op_owner',
+ });
+
+ const e = { stepIndex: 0, timestamp: 0, type: 'stream_chunk' } as unknown as AgentStreamEvent;
+ route(e);
+
+ expect(ownerHandler).toHaveBeenCalledWith(e);
+ expect(createMemberHandler).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventRouter.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventRouter.ts
new file mode 100644
index 00000000000..471cf1ccff9
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventRouter.ts
@@ -0,0 +1,73 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+/**
+ * A single agent stream event handler β€” the shape returned by
+ * `createGatewayEventHandler` / `createGatewayMemberStreamHandler`.
+ */
+export type GatewayEventListener = (event: AgentStreamEvent) => void;
+
+export interface GatewayEventRouterParams {
+ /**
+ * Lazily build a render-only handler for a non-owner operation whose events
+ * are multiplexed onto this same WebSocket (e.g. a broadcast council member
+ * forwarded via the server's `GatewayStreamNotifier` mirror). Called exactly
+ * once per distinct operationId, on that op's first event.
+ */
+ createMemberHandler: (operationId: string) => GatewayEventListener;
+ /**
+ * Handler for the operation this WebSocket was opened for (the supervisor /
+ * top-level op). Drives the full run lifecycle.
+ */
+ ownerHandler: GatewayEventListener;
+ /**
+ * The primary operationId the WebSocket subscribed to.
+ */
+ ownerOperationId: string;
+}
+
+/**
+ * Demultiplexes a single Gateway WebSocket that carries events for more than
+ * one `operationId`.
+ *
+ * The Gateway connection model is moving from per-operation (one WS per op) to
+ * single-connection multiplexing (LOBE-10868): a broadcast supervisor's WS now
+ * also receives the streaming events of each of its members, forwarded
+ * server-side onto the supervisor's op channel. Every `AgentStreamEvent` already
+ * carries its own `operationId`, so the routing key is intrinsic to the event β€”
+ * we just need to fan it out to the right handler.
+ *
+ * - Events for `ownerOperationId` β†’ `ownerHandler` (existing behavior, unchanged).
+ * - Events for any other operationId β†’ a render-only member handler, created
+ * lazily on first sighting and memoized for the connection's lifetime.
+ * - Events with no `operationId` (older gateway builds, or events without
+ * lineage) fall back to the owner so behavior degrades to the legacy
+ * single-op path rather than dropping the event.
+ *
+ * Without this demux, member events arriving on the supervisor WS would be
+ * processed by the supervisor handler and mis-dispatched into the supervisor
+ * bubble β€” so the router MUST front any handler on a connection that can receive
+ * forwarded member events.
+ */
+export const createGatewayEventRouter = (
+ params: GatewayEventRouterParams,
+): GatewayEventListener => {
+ const { ownerOperationId, ownerHandler, createMemberHandler } = params;
+
+ const memberHandlers = new Map<string, GatewayEventListener>();
+
+ return (event: AgentStreamEvent): void => {
+ const eventOperationId = event.operationId || ownerOperationId;
+
+ if (eventOperationId === ownerOperationId) {
+ ownerHandler(event);
+ return;
+ }
+
+ let handler = memberHandlers.get(eventOperationId);
+ if (!handler) {
+ handler = createMemberHandler(eventOperationId);
+ memberHandlers.set(eventOperationId, handler);
+ }
+ handler(event);
+ };
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts
new file mode 100644
index 00000000000..580bfd7e5ca
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts
@@ -0,0 +1,161 @@
+import type {
+ AgentStreamEvent,
+ StreamChunkData,
+ StreamStartData,
+} from '@lobechat/agent-gateway-client';
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+
+import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+export interface GatewayMemberStreamHandlerParams {
+ /**
+ * The shared group conversation context (groupId / topicId / scope='group').
+ * Members render in the same `messageMapKey` bucket as the supervisor β€” the
+ * key is derived from groupId, not agentId β€” so this resolves the member's
+ * assistant row to the supervisor's bucket for dispatch.
+ */
+ context: ConversationContext;
+ /**
+ * Pull the full canonical group tree into the store ONCE per run (memoized by
+ * the caller, shared across all member handlers). This is what makes the
+ * members render as a parallel AgentCouncil rather than a stack: the council
+ * only forms when the `agentCouncil` tool message AND the member rows are all
+ * present so `collectCouncilMembers` can group them. Inserting bare member
+ * rows is not enough. Shared + once so concurrent members don't repeatedly
+ * `replaceMessages` and clobber each other's in-flight streamed content.
+ */
+ ensureGroupHydrated: () => Promise<void>;
+ /**
+ * The member's server-side operationId (the op whose events are forwarded
+ * onto the supervisor's WebSocket).
+ */
+ memberOperationId: string;
+ /**
+ * The supervisor's LOCAL operation id, so the member's local loading op is
+ * recorded as its child for lineage.
+ */
+ parentOperationId?: string;
+}
+
+/**
+ * A render-only handler for a broadcast council member whose streaming events
+ * are multiplexed onto the supervisor's Gateway WebSocket (LOBE-10868, option
+ * B: server forwards member events onto the supervisor op channel).
+ *
+ * Scope is deliberately narrow β€” it owns ONLY the member's live text/reasoning/
+ * tool-call streaming into its council column. It does NOT drive any run
+ * lifecycle (the supervisor op owns the K=N barrier, unread, queue drain and
+ * notification).
+ *
+ * Structure availability: during the streaming window the supervisor is parked
+ * on the broadcast tool, so the client store has neither the `agentCouncil` tool
+ * message nor the member rows β€” and without the council tool message the members
+ * would render as a vertical stack instead of parallel columns. On the first
+ * member `stream_start` we therefore hydrate the full canonical group tree once
+ * (`ensureGroupHydrated`, shared across members) so the council forms, then
+ * stream content into the member row via targeted `updateMessage`. Because we
+ * dispatch the full accumulated content (not deltas), any chunk that lands
+ * before hydration completes is repainted once the row exists β€” self-healing.
+ */
+export const createGatewayMemberStreamHandler = (
+ get: () => ChatStore,
+ params: GatewayMemberStreamHandlerParams,
+): ((event: AgentStreamEvent) => void) => {
+ const { context, ensureGroupHydrated, memberOperationId, parentOperationId } = params;
+
+ const bucketKey = messageMapKey({
+ agentId: context.agentId ?? '',
+ groupId: context.groupId,
+ scope: context.scope,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ });
+
+ let localOperationId: string | undefined;
+ let currentAssistantMessageId: string | undefined;
+ let accumulatedContent = '';
+ let accumulatedReasoning = '';
+ let ended = false;
+
+ const isMessageInStore = (id: string): boolean =>
+ (get().dbMessagesMap[bucketKey] ?? []).some((m) => m.id === id);
+
+ const dispatch = (value: Partial<UIChatMessage>) => {
+ if (!currentAssistantMessageId || !localOperationId) return;
+ // Self-healing guard: skip until the member row lands in the store (via the
+ // shared group hydration). The next chunk repaints the full accumulated
+ // content once it's present.
+ if (!isMessageInStore(currentAssistantMessageId)) return;
+ get().internal_dispatchMessage(
+ { id: currentAssistantMessageId, type: 'updateMessage', value },
+ { operationId: localOperationId },
+ );
+ };
+
+ const ensureLocalOp = () => {
+ if (localOperationId) return;
+ const { operationId } = get().startOperation({
+ context,
+ metadata: { serverOperationId: memberOperationId },
+ parentOperationId,
+ type: 'execServerAgentRuntime',
+ });
+ localOperationId = operationId;
+ };
+
+ return (event: AgentStreamEvent) => {
+ if (ended) return;
+
+ switch (event.type) {
+ case 'stream_start': {
+ const data = event.data as StreamStartData | undefined;
+ const id = data?.assistantMessage?.id;
+ if (!id) break;
+
+ ensureLocalOp();
+ currentAssistantMessageId = id;
+ if (localOperationId) get().associateMessageWithOperation(id, localOperationId);
+ accumulatedContent = '';
+ accumulatedReasoning = '';
+ // Bring in the council structure (tool message + all member rows) so the
+ // members render as parallel columns, then repaint anything already
+ // accumulated.
+ void ensureGroupHydrated().then(() => {
+ if (ended) return;
+ if (accumulatedContent) dispatch({ content: accumulatedContent });
+ if (accumulatedReasoning) dispatch({ reasoning: { content: accumulatedReasoning } });
+ });
+ break;
+ }
+
+ case 'stream_chunk': {
+ const data = event.data as StreamChunkData | undefined;
+ if (!data) break;
+
+ if (data.chunkType === 'text' && data.content) {
+ accumulatedContent += data.content;
+ dispatch({ content: accumulatedContent });
+ }
+ if (data.chunkType === 'reasoning' && data.reasoning) {
+ accumulatedReasoning += data.reasoning;
+ dispatch({ reasoning: { content: accumulatedReasoning } });
+ }
+ if (data.chunkType === 'tools_calling' && data.toolsCalling) {
+ dispatch({ tools: data.toolsCalling });
+ }
+ break;
+ }
+
+ case 'agent_runtime_end':
+ case 'error': {
+ ended = true;
+ // The member row's final structure (tools, content, metadata) is
+ // reconciled by the supervisor op's terminal refetch / council barrier.
+ // This handler owns only the live text, so just retire the loading op.
+ if (localOperationId) get().completeOperation(localOperationId);
+ break;
+ }
+ }
+ };
+};