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: complete operation and show error on gateway error event (#13714)

Arvin Xu390d82d73089
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index f0b4e3ccd2e..d8043e97083 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -1606,6 +1606,29 @@ export class AgentRuntimeService {
// Also dispatch onError hooks if reason is error
if (reason === 'error') {
await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);
+
+ // Persist error into the assistant message so the frontend can display it
+ // after fetching messages from DB. Without this, the message stays with
+ // placeholder content and no error indicator.
+ const assistantMessageId = metadata?.assistantMessageId;
+ if (assistantMessageId && state?.error) {
+ const errorMessage = this.extractErrorMessage(state.error) || String(state.error);
+ try {
+ await this.messageModel.update(assistantMessageId, {
+ error: {
+ body: { message: errorMessage },
+ message: errorMessage,
+ type: 'AgentRuntimeError',
+ },
+ });
+ } catch (updateError) {
+ log(
+ '[%s] Failed to update assistant message with error (non-fatal): %O',
+ operationId,
+ updateError,
+ );
+ }
+ }
}
// Cleanup hooks after completion
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
index be1598a7cef..c084c1358c0 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -245,13 +245,20 @@ describe('createGatewayEventHandler', () => {
});
describe('error', () => {
- it('should dispatch error to current message with operationId context', async () => {
+ it('should dispatch inline error, complete operation, and refresh messages', async () => {
const store = createMockStore();
const handler = createHandler(store);
handler(makeEvent('error', { message: 'Something went wrong' }));
await flush();
+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(
+ 'msg-initial',
+ undefined,
+ );
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+
+ // Should dispatch inline error immediately
expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
{
id: 'msg-initial',
@@ -262,9 +269,12 @@ describe('createGatewayEventHandler', () => {
},
{ operationId: 'op-1' },
);
+
+ // Should also fetch from DB
+ expect(store.replaceMessages).toHaveBeenCalled();
});
- it('should dispatch error to switched message ID', async () => {
+ it('should dispatch inline error with switched message ID', async () => {
const store = createMockStore();
const handler = createHandler(store);
@@ -272,10 +282,25 @@ describe('createGatewayEventHandler', () => {
handler(makeEvent('error', { error: 'Timeout' }));
await flush();
+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(
+ 'msg-step2',
+ undefined,
+ );
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+
+ // Should dispatch inline error with the switched message ID
expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: 'msg-step2' }),
+ expect.objectContaining({
+ id: 'msg-step2',
+ value: expect.objectContaining({
+ error: expect.objectContaining({
+ body: { message: 'Timeout' },
+ }),
+ }),
+ }),
{ operationId: 'op-1' },
);
+ expect(store.replaceMessages).toHaveBeenCalled();
});
});
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index a51a95d033f..6eb24a46342 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -106,20 +106,39 @@ export class GatewayActionImpl {
);
});
- // Forward agent events to caller
- if (onEvent) {
- client.on('agent_event', onEvent);
- }
+ // Track whether a terminal agent event was received (agent_runtime_end or error),
+ // so we can fire onSessionComplete from the subsequent disconnect.
+ // session_complete is handled separately as an explicit server signal.
+ let receivedTerminalEvent = false;
+ let sessionCompleted = false;
+ const fireSessionComplete = () => {
+ if (sessionCompleted) return;
+ sessionCompleted = true;
+ onSessionComplete?.();
+ };
+
+ // Forward agent events to caller, and track terminal events
+ client.on('agent_event', (event) => {
+ if (event.type === 'agent_runtime_end' || event.type === 'error') {
+ receivedTerminalEvent = true;
+ }
+ onEvent?.(event);
+ });
// Handle session completion
client.on('session_complete', () => {
this.internal_cleanupGatewayConnection(operationId);
- onSessionComplete?.();
+ fireSessionComplete();
});
- // Handle disconnection (terminal events auto-disconnect the client)
+ // 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.
client.on('disconnected', () => {
this.internal_cleanupGatewayConnection(operationId);
+ if (receivedTerminalEvent) {
+ fireSessionComplete();
+ }
});
// Handle auth failures
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index c7e23518d19..dd9560570fe 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -178,8 +178,19 @@ export const createGatewayEventHandler = (
}
case 'error': {
- enqueue(() => {
+ enqueue(async () => {
const errorMsg = event.data?.message || event.data?.error || 'Unknown error';
+
+ get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
+ get().completeOperation(operationId);
+
+ // Fetch from DB first β€” the server may have persisted a richer error
+ // detail into the message already.
+ await fetchAndReplaceMessages(get, context).catch(console.error);
+
+ // Then overlay the inline error. This ensures the UI always shows the
+ // error even if the server hasn't persisted it into the message yet
+ // (the DB fetch would have returned a message with no error field).
get().internal_dispatchMessage(
{
id: currentAssistantMessageId,