π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: retire superseded gateway operation owners (#20676)
AmAzing-40e2709801e7
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.tsindex 185c770e14b..2cad317a9be 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@@ -241,7 +241,10 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {expect(action.createClient).not.toHaveBeenCalled();expect(muxClient.connect).toHaveBeenCalled();expect(v1Client.connect).not.toHaveBeenCalled();- expect(state.gatewayConnections['op-1']).toEqual({ client: muxClient, status: 'connecting' });+ expect(state.gatewayConnections['op-1']).toMatchObject({+ client: muxClient,+ status: 'connecting',+ });});it('keeps the v1 per-operation socket byte-for-byte outside the rollout', () => {@@ -293,7 +296,10 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {expect(action.createClient).not.toHaveBeenCalled();expect(muxClient.connect).toHaveBeenCalled();expect(v1Client.connect).not.toHaveBeenCalled();- expect(state.gatewayConnections['op-1']).toEqual({ client: muxClient, status: 'connecting' });+ expect(state.gatewayConnections['op-1']).toMatchObject({+ client: muxClient,+ status: 'connecting',+ });});it('resolves the page-wide registry mux by default', () => {@@ -398,6 +404,7 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {const connectParams = (operationId: string) => ({executor: true,gatewayUrl: GATEWAY_URL,+ localOperationId: `local-${operationId}`,operationId,token: 'tok',topicId: 'topic-1',@@ -405,6 +412,18 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {it('re-establishes every live operation on the v1 socket, resuming', () => {const { action, mux, state, v1Client } = createTestAction();+ state.operations = Object.fromEntries(+ ['op-1', 'op-2'].map((id) => [+ `local-${id}`,+ {+ id: `local-${id}`,+ type: 'execServerAgentRuntime',+ status: 'running',+ metadata: { serverOperationId: id },+ },+ ]),+ );+ state.completeOperation = vi.fn();action.connectToGateway(connectParams('op-1'));action.connectToGateway(connectParams('op-2'));@@ -425,6 +444,7 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {expect(v1Client.connect).toHaveBeenCalledTimes(2);expect(state.gatewayConnections['op-1'].client).toBe(v1Client);expect(state.gatewayConnections['op-2'].client).toBe(v1Client);+ expect(state.completeOperation).not.toHaveBeenCalled();});it('resumes the v1 socket from the cursor the mux had already delivered', () => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 75f173c40a5..a0757db3abd 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -13,6 +13,7 @@ import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { getChatGroupStoreState, useAgentGroupStore } from '@/store/agentGroup';import { topicSelectors } from '@/store/chat/slices/topic/selectors';+import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import * as serverConfigStore from '@/store/serverConfig';@@ -289,6 +290,49 @@ describe('GatewayActionImpl', () => {expect(mockClient.connect).toHaveBeenCalledOnce();});+ it('preserves the local run across a transport handoff and ignores the old reconcile', async () => {+ const { action, mockClient, state } = createTestAction();+ state.operations = {+ 'local-1': {+ id: 'local-1',+ type: 'execServerAgentRuntime',+ status: 'running',+ metadata: { serverOperationId: 'op-1' },+ },+ };+ state.completeOperation = vi.fn();+ let resolveRunOver!: (value: boolean) => void;+ const onSilentEnd = vi.fn(+ () =>+ new Promise<boolean>((resolve) => {+ resolveRunOver = resolve;+ }),+ );+ const onSessionComplete = vi.fn();+ const params = {+ gatewayUrl: 'https://gateway.test.com',+ localOperationId: 'local-1',+ operationId: 'op-1',+ token: 'test-token',+ topicId: TEST_TOPIC_ID,+ onSilentEnd,+ onSessionComplete,+ };+ action.connectToGateway(params);+ mockClient.emitEvent('reconnecting', 1000);+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledOnce());+ const replacement = createMockClient();+ action.createClient = vi.fn(() => replacement);+ action.connectToGateway(params);+ resolveRunOver(true);+ for (let i = 0; i < 10; i++) await Promise.resolve();+ expect(state.completeOperation).not.toHaveBeenCalled();+ expect(onSessionComplete).not.toHaveBeenCalled();+ expect(state.gatewayConnections['op-1'].client).toBe(replacement);+ replacement.emitEvent('session_complete', { source: 'raw_session_complete' });+ expect(onSessionComplete).toHaveBeenCalledOnce();+ });+it('should wire up status_changed listener', () => {const { action, mockClient, state } = createTestAction();@@ -958,6 +1002,124 @@ describe('GatewayActionImpl', () => {userMessageId: 'user-1',};+ it.each(['reconnect-first', 'primary-first', 'primary-completed', 'token-rejected'] as const)(+ 'keeps one local owner when continuation races reconnect: %s',+ async (order) => {+ const reconnectFirst = order === 'reconnect-first';+ const { action, get, state } = createExecuteTestAction();+ const operations: ChatStore['operations'] = {};+ state.operations = operations;+ let startedOperations = 0;+ state.messagesMap = {};+ const originalGet = get.getMockImplementation()!;+ const completeOperation = vi.fn((id: string) => {+ operations[id].status = 'completed';+ });+ const clients: ReturnType<typeof createMockClient>[] = [];+ action.createClient = vi.fn(() => {+ const client = createMockClient();+ client.disconnect.mockImplementation(() => client.emitEvent('disconnected'));+ clients.push(client);+ return client;+ });+ get.mockImplementation(() => ({+ ...originalGet(),+ completeOperation,+ connectToGateway: action.connectToGateway,+ internal_pinTopicStatus: vi.fn(),+ startOperation: (params: Parameters<ChatStore['startOperation']>[0]) => {+ const id = `local-${++startedOperations}`;+ operations[id] = {+ ...params,+ abortController: new AbortController(),+ context: params.context ?? {},+ metadata: { startTime: Date.now(), ...params.metadata },+ id,+ status: 'running',+ };+ return { operationId: id };+ },+ }));+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({+ id: 'topic-1',+ metadata: { runningOperation: { operationId: 'server-op-resumed' } },+ } as never);+ let releaseToken!: (value: { token: string }) => void;+ let rejectToken!: (error: Error) => void;+ vi.mocked(aiAgentService.refreshGatewayToken).mockImplementationOnce(+ () =>+ new Promise((resolve, reject) => {+ releaseToken = resolve;+ rejectToken = reject;+ }),+ );+ const reconnect = action.reconnectToGatewayOperation({+ agentId: 'agent-1',+ assistantMessageId: 'ast-resumed',+ heteroType: null,+ operationId: 'server-op-resumed',+ topicId: 'topic-1',+ });+ operations.unrelated = {+ ...operations['local-1'],+ id: 'unrelated',+ metadata: { startTime: Date.now(), serverOperationId: 'other-server-run' },+ };+ if (reconnectFirst) {+ releaseToken({ token: 'fresh-token' });+ await reconnect;+ operations.reasoning = {+ ...operations['local-1'],+ id: 'reasoning',+ type: 'reasoning',+ parentOperationId: 'local-1',+ metadata: { startTime: Date.now() },+ };+ }+ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', topicId: 'topic-1' },+ message: '',+ parentMessageId: 'answered-tool',+ precreatedResult: precreatedInterventionResult,+ });+ if (order === 'primary-completed') {+ clients.at(-1)!.emitEvent('session_complete', { source: 'raw_session_complete' });+ }+ if (!reconnectFirst) {+ if (order === 'token-rejected') rejectToken(new Error('superseded token request failed'));+ else releaseToken({ token: 'fresh-token' });+ await reconnect;+ }+ // The primary must remain the executor; a passive token refresh cannot replace it.+ expect(clients).toHaveLength(reconnectFirst ? 2 : 1);+ const running = Object.values(operations).filter(+ (op) => op.id !== 'unrelated' && op.status === 'running',+ );+ expect(running.map((op) => op.id)).toEqual(+ order === 'primary-completed' ? [] : ['local-2'],+ );+ expect(aiAgentService.interruptTask).not.toHaveBeenCalled();+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ if (reconnectFirst) {+ // Late signals from the replaced subscription must not delete or settle its successor.+ clients[0].emitEvent('session_complete', { source: 'raw_session_complete' });+ clients[0].emitEvent('auth_failed', 'late auth failure');+ clients[0].emitEvent('status_changed', 'disconnected');+ expect(state.gatewayConnections['server-op-resumed']?.client).toBe(clients[1]);+ expect(operations['local-2'].status).toBe('running');+ }+ for (let i = 0; i < 10; i++) await Promise.resolve();+ clients.at(-1)!.emitEvent('session_complete', { source: 'raw_session_complete' });+ for (let i = 0; i < 10; i++) await Promise.resolve();+ expect(operations.unrelated.status).toBe('running');+ if (reconnectFirst) expect(operations.reasoning.status).toBe('completed');+ expect(['local-1', 'local-2'].map((id) => operations[id].status)).toEqual([+ 'completed',+ 'completed',+ ]);+ },+ );+it.each(['approved', 'rejected'] as const)('removes a %s question from pending interventions before connecting the precreated continuation',async (status) => {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 9dfcd9773be..d13c9f6aac2 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -230,6 +230,8 @@ export interface GatewayConnection {'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendToolResult' | 'updateToken'>;status: ConnectionStatus;+ /** Invalidate callbacks before another transport takes over this subscription. */+ supersede?: () => void;}export interface ConnectGatewayParams {@@ -256,6 +258,8 @@ export interface ConnectGatewayParams {* after it instead of re-delivering events the run already handled.*/lastEventId?: string;+ /** Local runtime operation that owns this subscription (preserved across protocol fallback). */+ localOperationId?: string;/*** Callback for each agent event received*/@@ -521,15 +525,44 @@ export class GatewayActionImpl {token,topicId,lastEventId,+ localOperationId,onEvent,onSessionComplete,onSilentEnd,resumeOnConnect,} = params;- // Disconnect existing connection for this operation if any+ // A handoff ends the old subscription, not the server run. Silence its+ // callbacks before disconnect() can trigger a terminal/silent-end reconcile.+ this.#get().gatewayConnections[operationId]?.supersede?.();this.disconnectFromGateway(operationId);+ if (localOperationId) {+ // Reconnect may already own a stream OR still be awaiting its token. Both+ // lose ownership here. Retire only local operations; never interrupt or+ // settle the server run that this replacement is about to consume.+ const operations = Object.values(this.#get().operations ?? {});+ const retired = new Set(+ operations+ .filter(+ (op) =>+ op.id !== localOperationId &&+ op.type === 'execServerAgentRuntime' &&+ op.metadata.serverOperationId === operationId,+ )+ .map((op) => op.id),+ );+ const retire = (id: string): void => {+ if (id === localOperationId) return;+ for (const child of operations.filter((op) => op.parentOperationId === id))+ retire(child.id);+ if (this.#get().operations[id]?.status === 'running') this.#get().completeOperation(id);+ };+ retired.forEach(retire);+ }++ let superseded = false;+// Share visitors take protocol v2 wherever the deployment has it: the// public surface has no user to carry a rollout flag. Owner runs wait for// the rollout to reach them.@@ -584,7 +617,14 @@ export class GatewayActionImpl {(state) => ({gatewayConnections: {...state.gatewayConnections,- [operationId]: { client, status: 'connecting' },+ [operationId]: {+ client,+ status: 'connecting',+ supersede: () => {+ eventBuffer.flush();+ superseded = true;+ },+ },},}),false,@@ -593,6 +633,7 @@ export class GatewayActionImpl {// Wire up status changesclient.on('status_changed', (status) => {+ if (superseded) return;this.#set((state) => {const conn = state.gatewayConnections[operationId];@@ -617,7 +658,7 @@ export class GatewayActionImpl {authFailed?: boolean;completion?: AgentStreamSessionCompletion;}) => {- if (sessionCompleted) return;+ if (superseded || sessionCompleted) return;sessionCompleted = true;eventBuffer.flush();onSessionComplete?.({@@ -636,6 +677,7 @@ export class GatewayActionImpl {// 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 (superseded) return;const isOwnOp = !event.operationId || event.operationId === operationId;// Same rule the transport ends the session by: a parked LLM call's error// is not the run's end.@@ -663,7 +705,7 @@ export class GatewayActionImpl {// 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;+ if (superseded || !gap) return;eventBuffer.push({data: { reason: 'resume_gap' },operationId,@@ -675,6 +717,7 @@ export class GatewayActionImpl {// Handle session completionclient.on('session_complete', (completion) => {+ if (superseded) return;this.internal_cleanupGatewayConnection(operationId);fireSessionComplete({ completion });});@@ -721,12 +764,13 @@ export class GatewayActionImpl {// other than `disconnected`. Completion is fired first so the `disconnected`// the teardown provokes is a no-op.const reconcileSilentEnd = (): void => {- if (receivedTerminalEvent || sessionCompleted) return;+ if (superseded || receivedTerminalEvent || sessionCompleted) return;if (!onSilentEnd || silentEndReconciling) return;silentEndReconciling = true;void Promise.resolve().then(() => onSilentEnd()).then((runOver) => {+ if (superseded) return;if (!runOver) {silentEndRetryArmed = true;return;@@ -763,6 +807,7 @@ export class GatewayActionImpl {// lifecycle to complete the op, so the close is pure cleanup.// (auth_failed is handled separately below β it's also session-terminal.)client.on('disconnected', () => {+ if (superseded) return;cleanupOwnConnection();if (receivedTerminalEvent) {fireSessionComplete();@@ -804,6 +849,7 @@ export class GatewayActionImpl {// never gets cleared either, so each revisit re-triggers the same broken// reconnect.client.on('auth_failed', (reason) => {+ if (superseded) return;console.error(`[Gateway] Auth failed for operation ${operationId}: ${reason}`);this.internal_cleanupGatewayConnection(operationId);fireSessionComplete({ authFailed: true });@@ -818,14 +864,17 @@ export class GatewayActionImpl {// explicitly `disconnect()` before completing β otherwise heartbeat and// autoReconnect would keep running past the local op's lifetime.client.on('auth_expired', async () => {+ if (superseded) return;try {const { token: fresh } = agentShareId? await shareChatService.refreshGatewayToken(agentShareId, topicId): await aiAgentService.refreshGatewayToken(topicId);+ if (superseded) return;client.updateToken(fresh);await client.reconnect();} catch (error) {console.error(`[Gateway] Token refresh failed for operation ${operationId}:`, error);+ if (superseded) return;client.disconnect();this.internal_cleanupGatewayConnection(operationId);// A rejected refresh means the gateway no longer accepts this op's token@@ -1609,6 +1658,7 @@ export class GatewayActionImpl {// This tab started the run: it owns the run's local tool execution.executor: true,gatewayUrl: agentGatewayUrl,+ localOperationId: gatewayOpId,onEvent: eventRouter,// A silent end (subscription gone, no terminal frame) means the run is// either still alive on the server or already over with its terminal lost.@@ -1904,6 +1954,11 @@ export class GatewayActionImpl {? await shareChatService.refreshGatewayToken(agentShareId, topicId): await aiAgentService.refreshGatewayToken(topicId));} catch (error) {+ // A replacement may have taken ownership while this request failed.+ // Its live marker must not be cleared by the discarded reconnect.+ const localOperation = this.#get().operations?.[gatewayOpId];+ if (localOperation && localOperation.status !== 'running') return;+// The operation above was created on the strength of the marker; a refusal// (or a transport failure SWR may retry) means no stream is coming, so// retire it instead of leaving a spinner nothing will ever settle.@@ -1916,10 +1971,22 @@ export class GatewayActionImpl {throw error;}+ // A primary connection may have retired this pending reconnect, including+ // when that primary already completed and removed its connection handle.+ const localOperation = this.#get().operations?.[gatewayOpId];+ if (localOperation && localOperation.status !== 'running') return;+// A task-detail refresh may have confirmed this run ended during token IO.// Do not attach a fresh stream after its local operation was reconciled.if (this.#get().operations?.[gatewayOpId]?.metadata.terminalReconciled) return;+ // Never let a passive reconnect replace the active executor for the same run.+ const connectionStatus = this.#get().gatewayConnections[operationId]?.status;+ if (connectionStatus && connectionStatus !== 'disconnected') {+ this.#get().completeOperation(gatewayOpId);+ return;+ }+// Re-check after the async token refresh: a newer executeGatewayAgent call may have// taken over for this topic while we were waiting. If so, bail to avoid a duplicate stream.// (disconnectFromGateway on the stale op is a no-op here because we haven't connected yet.)@@ -1961,6 +2028,7 @@ export class GatewayActionImpl {// its local tools; this one only renders.executor: false,gatewayUrl: agentGatewayUrl,+ localOperationId: gatewayOpId,onEvent: eventRouter,// Same silent-end reconcile as the primary path: a reconnect that never// receives a terminal frame must still retire its local op once the server