π€― 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(gateway): unstick input loading on auth_failed + recoverable auth_expired (#14419)
Arvin Xu41719dfd2973
diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex 6c11c033098..e65143b2032 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -187,6 +187,42 @@ describe('AgentStreamClient', () => {});});+ describe('auth_expired', () => {+ it('should emit auth_expired without disconnecting (recoverable)', async () => {+ const client = createClient();+ const onAuthExpired = vi.fn();+ const onDisconnected = vi.fn();+ client.on('auth_expired', onAuthExpired);+ client.on('disconnected', onDisconnected);++ const ws = await connectAndAuth(client);+ ws.simulateMessage({ type: 'auth_expired' });++ expect(onAuthExpired).toHaveBeenCalledOnce();+ // Critical: socket stays connected so the listener can refresh + re-auth.+ expect(onDisconnected).not.toHaveBeenCalled();+ expect(client.connectionStatus).toBe('connected');+ });++ it('reconnect() tears down current ws and dials a new one with the latest token', async () => {+ const client = createClient();+ await connectAndAuth(client);++ const wsCountBefore = mockWsInstances.length;++ // Simulate the "got auth_expired β refresh β reconnect" flow+ client.updateToken('new-token');+ await client.reconnect();+ // Let the new MockWebSocket auto-open+ await vi.advanceTimersByTimeAsync(1);++ expect(mockWsInstances.length).toBe(wsCountBefore + 1);+ const newWs = getLatestWs();+ // First message on the new socket is auth with the refreshed token+ expect(JSON.parse(newWs.sent[0])).toEqual({ token: 'new-token', type: 'auth' });+ });+ });+describe('agent events', () => {it('should emit agent_event for incoming events', async () => {const client = createClient();diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 6eb9db5b7f9..93f49f83952 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -158,12 +158,26 @@ export class AgentStreamClient extends TypedEmitter {}/**- * Update the auth token (e.g. after JWT refresh). Call connect() or wait for auto-reconnect.+ * Update the auth token used for (re)connections.+ * Call this after refreshing an expired JWT, then call `reconnect()`.*/updateToken(token: string): void {this.token = token;}+ /**+ * Force a reconnect cycle: tear down the current WebSocket and establish a+ * fresh connection (which will re-authenticate with the latest token).+ * Use this after `updateToken()` to recover from `auth_expired`.+ */+ async reconnect(): Promise<void> {+ this.cleanup();+ this.intentionalDisconnect = false;+ this.sessionEnded = false;+ this.reconnectDelay = INITIAL_RECONNECT_DELAY;+ this.doConnect();+ }+// βββ Connection Logic βββprivate doConnect(): void {@@ -249,6 +263,13 @@ export class AgentStreamClient extends TypedEmitter {break;}+ case 'auth_expired': {+ // Token expired but the server kept the socket open. Don't disconnect β+ // the listener will refresh the token and call `reconnect()`.+ this.emit('auth_expired');+ break;+ }+case 'heartbeat_ack': {this.missedHeartbeats = 0;break;diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex d2eb9ba849b..3d2cca68f4c 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -141,6 +141,17 @@ export interface AuthFailedMessage {type: 'auth_failed';}+/**+ * Server β Client: token expired (e.g. JWT past `exp`) but the operation is+ * still alive on the server. The server keeps the WebSocket open so the+ * client can refresh its token and re-send `auth` without rebuilding the+ * connection. Treat this as recoverable, NOT terminal β `auth_failed` remains+ * the terminal "this op no longer exists / token is bogus" signal.+ */+export interface AuthExpiredMessage {+ type: 'auth_expired';+}+export interface AgentEventMessage {event: AgentStreamEvent;id?: string;@@ -157,6 +168,7 @@ export interface SessionCompleteMessage {export type ServerMessage =| AgentEventMessage+ | AuthExpiredMessage| AuthFailedMessage| AuthSuccessMessage| HeartbeatAckMessage@@ -175,6 +187,12 @@ export type ConnectionStatus =export interface AgentStreamClientEvents {agent_event: (event: AgentStreamEvent) => void;+ /**+ * JWT expired but the server kept the socket open. Listener should refresh+ * the token, call `updateToken()`, then `reconnect()`. Until that happens+ * the socket is connected but unauthenticated β no events will arrive.+ */+ auth_expired: () => void;auth_failed: (reason: string) => void;connected: () => void;disconnected: () => void;diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.tsindex adad7193939..3f7c4cf9c47 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts@@ -10,6 +10,7 @@ vi.mock('@/services/aiAgent', () => ({aiAgentService: {execAgentTask: vi.fn(),interruptTask: vi.fn(),+ refreshGatewayToken: vi.fn(),},}));@@ -52,13 +53,17 @@ function createMockClient(): GatewayConnection['client'] & {}set.add(listener);}),+ reconnect: vi.fn(async () => {}),sendInterrupt: vi.fn(),sendToolResult: vi.fn(() => true),+ updateToken: vi.fn(),};}// βββ Test Helpers βββ+const TEST_TOPIC_ID = 'topic-test';+function createTestAction() {const state: Record<string, any> = { gatewayConnections: {} };const set = vi.fn((updater: any) => {@@ -92,6 +97,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});expect(state.gatewayConnections['op-1']).toBeDefined();@@ -106,6 +112,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});mockClient.emitEvent('status_changed', 'connected');@@ -121,6 +128,7 @@ describe('GatewayActionImpl', () => {onEvent: (e) => events.push(e),operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});const testEvent: AgentStreamEvent = {@@ -145,6 +153,7 @@ describe('GatewayActionImpl', () => {onSessionComplete: onComplete,operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});mockClient.emitEvent('session_complete');@@ -159,6 +168,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});mockClient.emitEvent('disconnected');@@ -172,12 +182,114 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});mockClient.emitEvent('auth_failed', 'invalid token');expect(state.gatewayConnections['op-1']).toBeUndefined();});+ // Regression: when the server rejects auth (e.g. the op was GC'd or the+ // refreshed JWT no longer matches), the local op stayed `running` forever+ // because `auth_failed` only cleaned the connection map and never fired+ // `onSessionComplete`. The `disconnected` listener that follows can't fix+ // this either β `receivedTerminalEvent` is false (no agent_event arrived),+ // so it short-circuits. Net result: input shows the stop button forever+ // and `topic.metadata.runningOperation` stays set, so every revisit+ // re-fires the same broken reconnect.+ it('should fire onSessionComplete on auth_failed so the local op gets completed', () => {+ const { action, mockClient } = createTestAction();+ const onSessionComplete = vi.fn();++ action.connectToGateway({+ gatewayUrl: 'https://gateway.test.com',+ onSessionComplete,+ operationId: 'op-1',+ token: 'test-token',+ topicId: TEST_TOPIC_ID,+ });++ mockClient.emitEvent('auth_failed', 'invalid token');+ expect(onSessionComplete).toHaveBeenCalledOnce();+ });++ // Same regression, but for the WS-close that follows `auth_failed`.+ // The previous behavior fired `disconnected` after `auth_failed`, but+ // since `receivedTerminalEvent` is false, the disconnected listener also+ // skipped onSessionComplete. The fix should still only call it once+ // (through the auth_failed path) β not twice.+ it('should not fire onSessionComplete twice when auth_failed is followed by disconnected', () => {+ const { action, mockClient } = createTestAction();+ const onSessionComplete = vi.fn();++ action.connectToGateway({+ gatewayUrl: 'https://gateway.test.com',+ onSessionComplete,+ operationId: 'op-1',+ token: 'test-token',+ topicId: TEST_TOPIC_ID,+ });++ mockClient.emitEvent('auth_failed', 'invalid token');+ mockClient.emitEvent('disconnected');+ expect(onSessionComplete).toHaveBeenCalledOnce();+ });++ describe('auth_expired (recoverable)', () => {+ it('should refresh token, reconnect, and NOT fire onSessionComplete', async () => {+ const { action, mockClient } = createTestAction();+ const onSessionComplete = vi.fn();+ vi.mocked(aiAgentService.refreshGatewayToken).mockResolvedValueOnce({+ token: 'fresh-token',+ });++ action.connectToGateway({+ gatewayUrl: 'https://gateway.test.com',+ onSessionComplete,+ operationId: 'op-1',+ token: 'old-token',+ topicId: TEST_TOPIC_ID,+ });++ mockClient.emitEvent('auth_expired');+ // The handler is async β let the promise chain settle.+ await Promise.resolve();+ await Promise.resolve();++ expect(aiAgentService.refreshGatewayToken).toHaveBeenCalledWith(TEST_TOPIC_ID);+ expect(mockClient.updateToken).toHaveBeenCalledWith('fresh-token');+ expect(mockClient.reconnect).toHaveBeenCalledOnce();+ // Critical: this is recoverable, so the local op MUST keep running.+ expect(onSessionComplete).not.toHaveBeenCalled();+ });++ it('should fire onSessionComplete when token refresh itself throws', async () => {+ const { action, mockClient } = createTestAction();+ const onSessionComplete = vi.fn();+ vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce(+ new Error('refresh API down'),+ );++ action.connectToGateway({+ gatewayUrl: 'https://gateway.test.com',+ onSessionComplete,+ operationId: 'op-1',+ token: 'old-token',+ topicId: TEST_TOPIC_ID,+ });++ mockClient.emitEvent('auth_expired');+ await Promise.resolve();+ await Promise.resolve();++ expect(aiAgentService.refreshGatewayToken).toHaveBeenCalledWith(TEST_TOPIC_ID);+ // No reconnect attempted β refresh failed, give up cleanly.+ expect(mockClient.reconnect).not.toHaveBeenCalled();+ expect(mockClient.disconnect).toHaveBeenCalled();+ expect(onSessionComplete).toHaveBeenCalledOnce();+ });+ });+it('should disconnect existing connection before creating new one', () => {const { action, state } = createTestAction();@@ -188,6 +300,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'token-1',+ topicId: TEST_TOPIC_ID,});// Second connection@@ -197,6 +310,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'token-2',+ topicId: TEST_TOPIC_ID,});expect(firstMock.disconnect).toHaveBeenCalled();@@ -212,6 +326,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});action.disconnectFromGateway('op-1');@@ -233,6 +348,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});action.interruptGatewayAgent('op-1');@@ -253,6 +369,7 @@ describe('GatewayActionImpl', () => {gatewayUrl: 'https://gateway.test.com',operationId: 'op-1',token: 'test-token',+ topicId: TEST_TOPIC_ID,});expect(action.getGatewayConnectionStatus('op-1')).toBe('connecting');diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex e5e4944894f..39a390aa632 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -23,7 +23,13 @@ type Setter = StoreSetter<ChatStore>;export interface GatewayConnection {client: Pick<AgentStreamClient,- 'connect' | 'disconnect' | 'on' | 'sendInterrupt' | 'sendToolResult'+ | 'connect'+ | 'disconnect'+ | 'on'+ | 'reconnect'+ | 'sendInterrupt'+ | 'sendToolResult'+ | 'updateToken'>;status: ConnectionStatus;}@@ -53,6 +59,12 @@ export interface ConnectGatewayParams {* Auth token for the Gateway*/token: string;+ /**+ * Topic this op runs against. Used to refresh the Gateway JWT via+ * `aiAgentService.refreshGatewayToken(topicId)` when the server signals+ * `auth_expired`. Every Gateway op has a topic, so this is required.+ */+ topicId: string;}// βββ Action Implementation βββ@@ -76,7 +88,8 @@ export class GatewayActionImpl {* Creates an AgentStreamClient, manages its lifecycle, and wires up event callbacks.*/connectToGateway = (params: ConnectGatewayParams): void => {- const { operationId, gatewayUrl, token, onEvent, onSessionComplete, resumeOnConnect } = params;+ const { operationId, gatewayUrl, token, topicId, onEvent, onSessionComplete, resumeOnConnect } =+ params;// Disconnect existing connection for this operation if anythis.disconnectFromGateway(operationId);@@ -136,8 +149,9 @@ export class GatewayActionImpl {});// Handle disconnection β only fire session complete if a terminal agent event- // was received (agent_runtime_end / error). Auth failures, explicit disconnect(),- // and other non-terminal disconnects should NOT trigger onSessionComplete.+ // was received (agent_runtime_end / error). Explicit disconnect() and other+ // non-terminal disconnects should NOT trigger onSessionComplete.+ // (auth_failed is handled separately below β it's also session-terminal.)client.on('disconnected', () => {this.internal_cleanupGatewayConnection(operationId);if (receivedTerminalEvent) {@@ -145,10 +159,37 @@ export class GatewayActionImpl {}});- // Handle auth failures+ // Handle auth failures β server-side terminal: the op no longer exists on+ // the server (GC'd, token rejected, etc.), so the local op must be marked+ // complete. Without this, the local op stays `running` forever and the+ // input stop button never clears; worse, `topic.metadata.runningOperation`+ // never gets cleared either, so each revisit re-triggers the same broken+ // reconnect.client.on('auth_failed', (reason) => {console.error(`[Gateway] Auth failed for operation ${operationId}: ${reason}`);this.internal_cleanupGatewayConnection(operationId);+ fireSessionComplete();+ });++ // Handle expired-but-recoverable auth: the JWT is past `exp` but the op+ // is still alive on the server. Refresh the token, hand it to the client,+ // and reconnect. If the refresh itself fails (refresh API down, server+ // refused refresh, etc.), fall back to terminal β leaving the op+ // `running` would freeze the input. The server keeps the ws open after+ // `auth_expired` to give the client a chance to recover, so we must+ // explicitly `disconnect()` before completing β otherwise heartbeat and+ // autoReconnect would keep running past the local op's lifetime.+ client.on('auth_expired', async () => {+ try {+ const { token: fresh } = await aiAgentService.refreshGatewayToken(topicId);+ client.updateToken(fresh);+ await client.reconnect();+ } catch (error) {+ console.error(`[Gateway] Token refresh failed for operation ${operationId}:`, error);+ client.disconnect();+ this.internal_cleanupGatewayConnection(operationId);+ fireSessionComplete();+ }});client.connect();@@ -328,6 +369,7 @@ export class GatewayActionImpl {},operationId: result.operationId,token: result.token || '',+ topicId: result.topicId,});return result;@@ -400,6 +442,7 @@ export class GatewayActionImpl {operationId,resumeOnConnect: true,token,+ topicId,});};