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: preserve gateway error event body (#16069)

YuTengjingc31627960688
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts
index e712655f4d5..039b831e97a 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts
@@ -1,3 +1,4 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import { formatErrorEventData } from '../formatErrorEventData';
@@ -62,6 +63,75 @@ describe('formatErrorEventData', () => {
});
describe('business-typed errors (must not be overridden)', () => {
+ it('preserves traceable runtime payload body for gateway error events', () => {
+ const out = formatErrorEventData(
+ {
+ error: { message: 'Upstream failed', traceId: 'trace-123' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: 'openai',
+ },
+ 'llm_execution',
+ );
+
+ expect(out).toMatchObject({
+ body: {
+ message: 'Upstream failed',
+ provider: 'openai',
+ traceId: 'trace-123',
+ },
+ error: 'Upstream failed',
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ phase: 'llm_execution',
+ });
+ });
+
+ it('uses the normalized runtime type for gateway error events', () => {
+ const out = formatErrorEventData(
+ {
+ error: { message: 'Payment required', status: 402, traceId: 'trace-402' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: 'lobehub',
+ },
+ 'llm_execution',
+ );
+
+ expect(out).toMatchObject({
+ body: {
+ message: 'Payment required',
+ provider: 'lobehub',
+ status: 402,
+ traceId: 'trace-402',
+ },
+ error: 'Payment required',
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ phase: 'llm_execution',
+ });
+ });
+
+ it('uses the normalized runtime message when the payload message is a placeholder', () => {
+ const out = formatErrorEventData(
+ {
+ error: { message: 'Payment required', status: 402, traceId: 'trace-402' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ message: 'error',
+ provider: 'lobehub',
+ },
+ 'llm_execution',
+ );
+
+ expect(out).toMatchObject({
+ body: {
+ message: 'Payment required',
+ provider: 'lobehub',
+ status: 402,
+ traceId: 'trace-402',
+ },
+ error: 'Payment required',
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ phase: 'llm_execution',
+ });
+ });
+
it('preserves ConversationParentMissing errorType and message even when .cause has PG info', () => {
// Mirrors createConversationParentMissingError from messagePersistErrors.ts:
// the user-facing errorType lives on the error object directly, and the
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts b/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts
index 2d1acaafece..c7017ec0aaa 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts
@@ -1,5 +1,11 @@
+import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';
+
+import { formatErrorForState } from './formatErrorForState';
import { formatPgError, pgErrorType, unwrapPgError } from './pgError';
+const isErrorType = (value: unknown): value is string | number =>
+ typeof value === 'string' || typeof value === 'number';
+
/**
* Normalize an arbitrary thrown value into the shape the runtime stream-event
* protocol expects. Extracts a human-readable `error` string and a best-effort
@@ -23,55 +29,38 @@ import { formatPgError, pgErrorType, unwrapPgError } from './pgError';
* DB failures by SQLSTATE.
*/
export const formatErrorEventData = (error: unknown, phase: string) => {
- let errorMessage = 'Unknown error';
- let errorType: string | undefined;
- // True when `errorType` came from a business-typed field on the error
- // payload (step 1 above). Driver class names assigned via `error.name`
- // do NOT set this flag, so raw `PostgresError` / `DatabaseError` instances
- // still fall through to the PG unwrap step.
- let hasBusinessErrorType = false;
-
- if (error && typeof error === 'object') {
- const payload = error as { error?: unknown; errorType?: unknown; message?: unknown };
-
- if (typeof payload.errorType === 'string') {
- errorType = payload.errorType;
- hasBusinessErrorType = true;
- }
-
- if (typeof payload.message === 'string' && payload.message.length > 0) {
- errorMessage = payload.message;
- } else if (typeof payload.error === 'string' && payload.error.length > 0) {
- errorMessage = payload.error;
- } else if (
- payload.error &&
- typeof payload.error === 'object' &&
- 'message' in payload.error &&
- typeof payload.error.message === 'string'
- ) {
- errorMessage = payload.error.message;
- } else if (error instanceof Error && error.message.length > 0) {
- errorMessage = error.message;
- } else if (errorType) {
- errorMessage = errorType;
- }
- } else if (error instanceof Error && error.message.length > 0) {
- errorMessage = error.message;
- errorType = error.name;
- } else if (typeof error === 'string' && error.length > 0) {
- errorMessage = error;
- }
+ const payload = toRecord(error);
+ const rawPayloadErrorType = payload?.errorType ?? payload?.type;
+ const payloadErrorType = isErrorType(rawPayloadErrorType) ? rawPayloadErrorType : undefined;
+ const structuredError =
+ error instanceof Error || payloadErrorType === undefined
+ ? undefined
+ : formatErrorForState(payload);
+ const body = structuredError?.body;
+ const hasPayloadErrorType = payloadErrorType !== undefined;
+ let errorType = hasPayloadErrorType
+ ? String(structuredError?.type ?? payloadErrorType)
+ : undefined;
+ const payloadError = payload?.error;
+ let errorMessage =
+ pickNonEmptyString(structuredError?.message) ??
+ pickNonEmptyString(payload?.message) ??
+ pickNonEmptyString(payloadError) ??
+ pickNonEmptyString(toRecord(payloadError)?.message) ??
+ (error instanceof Error ? pickNonEmptyString(error.message) : pickNonEmptyString(error)) ??
+ errorType ??
+ 'Unknown error';
if (!errorType && error instanceof Error && error.name) {
errorType = error.name;
}
- // Enrichment: run PG unwrap whenever no *business-typed* errorType was
+ // Enrichment: run PG unwrap whenever no payload errorType was
// declared. This covers both Drizzle-wrapped errors (PG info under .cause)
// AND raw top-level driver errors like `PostgresError` / `DatabaseError`
// which carry a specific `name` but are still real PG errors deserving
// `pg_<sqlstate>` classification on the dashboard.
- if (!hasBusinessErrorType) {
+ if (!hasPayloadErrorType) {
const pg = unwrapPgError(error);
if (pg) {
errorMessage = formatPgError(pg);
@@ -80,6 +69,7 @@ export const formatErrorEventData = (error: unknown, phase: string) => {
}
return {
+ ...(body === undefined ? {} : { body }),
error: errorMessage,
errorType,
phase,
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 c4e24209579..95786770a6d 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -1159,6 +1159,37 @@ describe('createGatewayEventHandler', () => {
);
});
+ it('error event preserves normalized body fields for trace-id error UI', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(
+ makeEvent('error', {
+ body: {
+ message: 'Upstream failed',
+ traceId: 'trace-123',
+ },
+ error: 'Upstream failed',
+ errorType: 'ProviderBizError',
+ phase: 'llm_execution',
+ }),
+ );
+ await flush();
+
+ expect(messageService.updateMessageError).toHaveBeenCalledWith(
+ 'msg-initial',
+ expect.objectContaining({
+ body: expect.objectContaining({
+ message: 'Upstream failed',
+ traceId: 'trace-123',
+ }),
+ message: 'Upstream failed',
+ type: 'ProviderBizError',
+ }),
+ expect.anything(),
+ );
+ });
+
// Contrast probe: agent_runtime_end on the SAME operation (which has a
// context.agentId) DOES mark unread completed — proving the negative
// assertion above is the error path's own behavior, not a missing agentId.
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index f7f4694371f..5592a9ec4ad 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -14,7 +14,7 @@ import type {
UIChatMessage,
} from '@lobechat/types';
import { AgentRuntimeErrorType } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils';
+import { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';
import { messageService } from '@/services/message';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
@@ -176,19 +176,20 @@ const isErrorType = (value: unknown): value is ChatMessageError['type'] =>
const getMessageFromErrorData = (data: unknown): string | undefined => {
if (!isRecord(data)) return undefined;
- const message = data.message;
- if (typeof message === 'string' && message) return message;
+ const message = pickNonEmptyString(data.message);
+ if (message) return message;
const error = data.error;
- if (typeof error === 'string' && error) return error;
+ const errorString = pickNonEmptyString(error);
+ if (errorString) return errorString;
if (isRecord(error)) {
- const errorMessage = error.message;
- if (typeof errorMessage === 'string' && errorMessage) return errorMessage;
+ const errorMessage = pickNonEmptyString(error.message);
+ if (errorMessage) return errorMessage;
const nestedError = error.error;
if (isRecord(nestedError)) {
- const nestedMessage = nestedError.message;
- if (typeof nestedMessage === 'string' && nestedMessage) return nestedMessage;
+ const nestedMessage = pickNonEmptyString(nestedError.message);
+ if (nestedMessage) return nestedMessage;
}
}
@@ -198,8 +199,8 @@ const getMessageFromErrorData = (data: unknown): string | undefined => {
const body = data.body;
if (isRecord(body)) {
- const bodyMessage = body.message;
- if (typeof bodyMessage === 'string' && bodyMessage) return bodyMessage;
+ const bodyMessage = pickNonEmptyString(body.message);
+ if (bodyMessage) return bodyMessage;
}
};
@@ -219,15 +220,14 @@ const buildGatewayRuntimeErrorBody = (
data: Record<string, unknown>,
message: string,
): Record<string, unknown> => {
- const sourceBody = isRecord(data._responseBody)
- ? data._responseBody
- : isRecord(data.error)
- ? data.error
- : {};
- const mergedBody =
- data._responseBody === undefined
- ? sourceBody
- : mergeGatewayPayloadError(sourceBody, data.error);
+ const body = toRecord(data.body);
+ const responseBody = toRecord(data._responseBody);
+ const errorBody = toRecord(data.error);
+ const sourceBody = body ?? responseBody ?? errorBody ?? {};
+ const shouldMergePayloadError = body === undefined && data._responseBody !== undefined;
+ const mergedBody = shouldMergePayloadError
+ ? mergeGatewayPayloadError(sourceBody, data.error)
+ : sourceBody;
return {
...mergedBody,