🤯 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(trpc): show readable copy and a request id when a gateway returns an HTML error page (#21568)
LiJianc87d7c2eb8a0
diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex f56b9c4bfdb..1cf7e365edb 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -128,6 +128,8 @@"response.WorkspaceAgentRequiresWorkspaceDevice": "This agent lives in a workspace, so it can only bind devices the whole team can reach. Personal devices stay with the user who registered them — pick a workspace device instead, or enroll this device to the workspace first.","response.WorkspaceFrozenByAdmin": "This workspace is frozen by an admin and cannot run requests. Please contact the workspace owner to resolve the issue.","response.WorkspaceFrozenByRiskControl": "This workspace was auto-frozen by risk control and cannot run requests. Please contact support to review the status.",+ "response.withRequestDetail": "{{message}} (HTTP {{status}} · Request ID: {{requestId}})",+ "response.withStatusDetail": "{{message}} (HTTP {{status}})","saveState.retry": "Retry","saveState.saveFailed": "Failed to save your changes. Please try again.","stt.responseError": "Service request failed, please check the configuration or try again",@@ -180,6 +182,7 @@"upload.fileOnlySupportInServerMode": "The current deployment mode does not support uploading non-image files. To upload files in {{ext}} format, please switch to server database deployment or use the {{cloud}} service.","upload.networkError": "Please check your network connection and ensure that the file storage service's cross-origin configuration is correct.","upload.permissionDenied": "You don't have permission to upload files in this workspace.",+ "upload.serviceUnavailable": "The upload service is temporarily unavailable. Please try again in a moment.","upload.storageBlock.billingUnavailable": "Your subscription billing status cannot be verified. Please try again later or update your billing details.","upload.storageBlock.cleanupFiles": "Free up space","upload.storageBlock.monthlyCapReached": "Your monthly storage spending cap has been reached.",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex 9365e6b5b65..1569e2ba95a 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -128,6 +128,8 @@"response.WorkspaceAgentRequiresWorkspaceDevice": "这是一个工作区助手,只能绑定全员都能访问的工作区设备。个人设备仅注册者本人可达 —— 请改选工作区设备,或先把这台设备加入工作区。","response.WorkspaceFrozenByAdmin": "工作区已被管理员冻结,暂时无法处理请求。请联系工作区所有者处理","response.WorkspaceFrozenByRiskControl": "工作区已被风控系统自动冻结,暂时无法处理请求。请联系客服处理",+ "response.withRequestDetail": "{{message}}(HTTP {{status}} · 请求 ID:{{requestId}})",+ "response.withStatusDetail": "{{message}}(HTTP {{status}})","saveState.retry": "重试","saveState.saveFailed": "保存失败,请重试。","stt.responseError": "请求失败。请检查配置后重试",@@ -180,6 +182,7 @@"upload.fileOnlySupportInServerMode": "当前部署模式不支持上传非图片文件。若需上传 {{ext}},请切换到服务端数据库部署或使用 {{cloud}}","upload.networkError": "网络异常或跨域配置不正确。请检查文件存储服务的 CORS 设置后重试","upload.permissionDenied": "您没有权限在此工作区上传文件。",+ "upload.serviceUnavailable": "上传服务暂时不可用,请稍后重试","upload.storageBlock.billingUnavailable": "无法验证您的订阅账单状态。请稍后重试或更新您的账单信息。","upload.storageBlock.cleanupFiles": "清理文件","upload.storageBlock.monthlyCapReached": "已达到月度存储消费上限。",diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex c88012d4cc4..785890cbd10 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -226,6 +226,8 @@ export default {'This workspace is frozen by an admin and cannot run requests. Please contact the workspace owner to resolve the issue.','response.WorkspaceFrozenByRiskControl':'This workspace was auto-frozen by risk control and cannot run requests. Please contact support to review the status.',+ 'response.withRequestDetail': '{{message}} (HTTP {{status}} · Request ID: {{requestId}})',+ 'response.withStatusDetail': '{{message}} (HTTP {{status}})','unknownError.troubleshoot': 'Troubleshoot','workspaceBillingInactive.bannerHint': 'Click for details','workspaceBillingInactive.bannerTitle': 'Workspace subscription inactive',@@ -310,6 +312,8 @@ export default {'The current deployment mode does not support uploading non-image files. To upload files in {{ext}} format, please switch to server database deployment or use the {{cloud}} service.','upload.networkError':"Please check your network connection and ensure that the file storage service's cross-origin configuration is correct.",+ 'upload.serviceUnavailable':+ 'The upload service is temporarily unavailable. Please try again in a moment.','upload.storageBlock.billingUnavailable':'Your subscription billing status cannot be verified. Please try again later or update your billing details.','upload.storageBlock.cleanupFiles': 'Free up space',diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex b87f994d931..ee6be0caf22 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -293,6 +293,31 @@ describe('lambdaClient unreadable response handling', () => {).rejects.toThrow('response.UnreadableServerResponse');});+ // Regression: a gateway HTML error page made @trpc/client fail `res.json()`+ // and drop the response, so the UI showed `Unexpected token '<', "<!doctype+ // "... is not valid JSON` with no status or id to trace the failure by.+ it('turns an HTML error page into readable copy that keeps the request id', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response('<!doctype html><html><body>504</body></html>', {+ headers: {+ 'cf-ray': 'a4f726100b0cd438-SJC',+ 'content-type': 'text/html',+ 'x-vercel-id': 'sfo1::abc-123',+ },+ status: 504,+ }),+ );++ const error = await lambdaClient.agent.getAgentConfigById+ .query({ agentId: 'agt_test' })+ .catch((e: unknown) => e);++ expect(error).toMatchObject({+ cause: { requestId: 'sfo1::abc-123', status: 504 },+ message: 'response.withRequestDetail',+ });+ });+it('keeps a well-formed tRPC error message untouched', async () => {fetchMock.mockResolvedValueOnce(new Response(diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 0e8deb05e7d..480b2096cd7 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -17,6 +17,11 @@ import superjson from 'superjson';import { isDesktop } from '@/const/version';import { type LambdaRouter } from '@/server/routers/lambda';+import {+ detectUnreadableServerResponse,+ findUnreadableServerResponseError,+} from './unreadableServerResponse';+const log = debug('lobe-image:lambda-client');// 401 error debouncing: prevent showing multiple login notifications in short time@@ -37,14 +42,19 @@ const isPublicShareRoute = () =>// says what actually happened.const TRANSFORM_RESULT_ERROR_MESSAGE = 'Unable to transform response from server';+//+// A body that is not JSON at all (a gateway HTML error page) is caught earlier,+// in `linkOptions.fetch`, which still holds the response and can keep its+// status and request id for the copy.const rewriteUnreadableResponseMessage = async (err: TRPCClientError<LambdaRouter>) => {- if (err.message !== TRANSFORM_RESULT_ERROR_MESSAGE) return;+ const unreadable = findUnreadableServerResponseError(err);+ if (!unreadable && err.message !== TRANSFORM_RESULT_ERROR_MESSAGE) return;// dynamic import to avoid circular dependencyconst { unreadableResponseMessage } =await import('@/components/Error/unreadableResponseMessage');- err.message = unreadableResponseMessage(err.meta?.responseJSON);+ err.message = unreadableResponseMessage(err.meta?.responseJSON, unreadable);};// handle error@@ -166,6 +176,13 @@ const linkOptions = {// Ensure credentials are included to send cookies (like mp_token)const response = await fetch(input, { ...init, credentials: 'include' });if (isDesktop && isProxyNetworkFailure(response)) void notifyRemoteServerNetworkError(response);++ // Throw while the response is still in hand: past this point @trpc/client+ // calls `res.json()` and, on an HTML error page, drops the response along+ // with its status and the request id we need to trace the failure.+ const unreadable = await detectUnreadableServerResponse(response);+ if (unreadable) throw unreadable;+return response;},headers: async () => {diff --git a/packages/trpc/src/client/unreadableServerResponse.test.ts b/packages/trpc/src/client/unreadableServerResponse.test.tsnew file mode 100644index 00000000000..7ef4597c23b--- /dev/null+++ b/packages/trpc/src/client/unreadableServerResponse.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';++import {+ detectUnreadableServerResponse,+ findUnreadableServerResponseError,+ UnreadableServerResponseError,+} from './unreadableServerResponse';++const htmlPage = '<!doctype html><html><body>504 Gateway Timeout</body></html>';++describe('detectUnreadableServerResponse', () => {+ it('keeps the status and the most specific edge request id of an HTML page', async () => {+ const error = await detectUnreadableServerResponse(+ new Response(htmlPage, {+ headers: {+ 'cf-ray': 'a4f726100b0cd438-SJC',+ 'content-type': 'text/html; charset=utf-8',+ 'x-vercel-id': 'sfo1::cle1::6gzdg-1792825689647-00c66abd3c56',+ },+ status: 504,+ }),+ );++ expect(error).toBeInstanceOf(UnreadableServerResponseError);+ expect(error).toMatchObject({+ requestId: 'sfo1::cle1::6gzdg-1792825689647-00c66abd3c56',+ status: 504,+ });+ });++ it('falls back to the Cloudflare Ray ID when the request never reached Vercel', async () => {+ const error = await detectUnreadableServerResponse(+ new Response(htmlPage, {+ headers: { 'cf-ray': 'a4f726100b0cd438-SJC', 'content-type': 'text/html' },+ status: 502,+ }),+ );++ expect(error).toMatchObject({ requestId: 'a4f726100b0cd438-SJC', status: 502 });+ });++ it('reports a proxy plain-text error without a request id', async () => {+ const error = await detectUnreadableServerResponse(+ new Response('upstream request timeout', {+ headers: { 'content-type': 'text/plain' },+ status: 504,+ }),+ );++ expect(error).toMatchObject({ requestId: undefined, status: 504 });+ expect(error?.message).toBe('Server returned a non-JSON response (HTTP 504)');+ });++ it('passes through a JSON response without reading its body', async () => {+ const response = new Response('{"result":{}}', {+ headers: { 'content-type': 'application/json' },+ });++ expect(await detectUnreadableServerResponse(response)).toBeUndefined();+ expect(response.bodyUsed).toBe(false);+ });++ it('passes through a JSON body served with a non-JSON content type', async () => {+ expect(+ await detectUnreadableServerResponse(+ new Response('{"result":{}}', { headers: { 'content-type': 'text/plain' } }),+ ),+ ).toBeUndefined();+ });+});++describe('findUnreadableServerResponseError', () => {+ const unreadable = new UnreadableServerResponseError({ status: 502 });++ it('finds the error directly or on a wrapping error cause', () => {+ expect(findUnreadableServerResponseError(unreadable)).toBe(unreadable);+ expect(findUnreadableServerResponseError(new Error('wrapped', { cause: unreadable }))).toBe(+ unreadable,+ );+ });++ it('ignores unrelated errors', () => {+ expect(findUnreadableServerResponseError(new Error('boom'))).toBeUndefined();+ expect(findUnreadableServerResponseError('boom')).toBeUndefined();+ expect(findUnreadableServerResponseError(undefined)).toBeUndefined();+ });+});diff --git a/packages/trpc/src/client/unreadableServerResponse.ts b/packages/trpc/src/client/unreadableServerResponse.tsnew file mode 100644index 00000000000..8924138de4f--- /dev/null+++ b/packages/trpc/src/client/unreadableServerResponse.ts@@ -0,0 +1,63 @@+// Edge ids set before the app runs, most specific first: Vercel's id names the+// region and function invocation, Cloudflare's Ray ID exists for every request+// that crossed the edge, and `x-request-id` covers self-hosted reverse proxies.+const REQUEST_ID_HEADERS = ['x-vercel-id', 'cf-ray', 'x-request-id'] as const;++/**+ * A lambda response whose body is not JSON — a gateway/CDN error page (502,+ * 504, function timeout, maintenance), an SPA HTML fallback, or a proxy's plain+ * text error. The tRPC client would otherwise fail `res.json()` and drop the+ * response, leaving only `Unexpected token '<', "<!doctype "...` with no status+ * and no id to look the failure up by.+ */+export class UnreadableServerResponseError extends Error {+ readonly requestId?: string;+ readonly status: number;++ constructor({ requestId, status }: { requestId?: string; status: number }) {+ super(+ `Server returned a non-JSON response (HTTP ${status}${requestId ? `, request id ${requestId}` : ''})`,+ );+ this.name = 'UnreadableServerResponseError';+ this.requestId = requestId;+ this.status = status;+ }+}++const getRequestId = (headers: Headers) => {+ for (const name of REQUEST_ID_HEADERS) {+ const value = headers.get(name);+ if (value) return value;+ }+};++/**+ * Return an `UnreadableServerResponseError` when the body cannot be parsed as+ * JSON. A tRPC server always answers JSON, so the body is only read here when+ * the content type already says otherwise — normal responses are untouched.+ */+export const detectUnreadableServerResponse = async (+ response: Response,+): Promise<UnreadableServerResponseError | undefined> => {+ if (response.headers.get('content-type')?.includes('json')) return;++ try {+ JSON.parse(await response.clone().text());+ return;+ } catch {+ return new UnreadableServerResponseError({+ requestId: getRequestId(response.headers),+ status: response.status,+ });+ }+};++/** Find the error on a thrown value or on its `cause` (tRPC wraps link errors). */+export const findUnreadableServerResponseError = (+ error: unknown,+): UnreadableServerResponseError | undefined => {+ if (error instanceof UnreadableServerResponseError) return error;++ const cause = (error as { cause?: unknown } | null | undefined)?.cause;+ if (cause instanceof UnreadableServerResponseError) return cause;+};diff --git a/src/components/Error/unreadableResponseMessage.ts b/src/components/Error/unreadableResponseMessage.tsindex ff44b0eeea5..c2fcc06e57f 100644--- a/src/components/Error/unreadableResponseMessage.ts+++ b/src/components/Error/unreadableResponseMessage.ts@@ -1,6 +1,24 @@import { isRemoteServerNetworkError } from '@lobechat/types';import { t } from 'i18next';+export interface UnreadableResponseDetail {+ requestId?: string;+ status: number;+}++/**+ * Append the HTTP status and the edge request id of a non-JSON response, so a+ * user report (often a screenshot of this text) can be traced in the+ * gateway/CDN logs.+ */+export const withResponseDetail = (+ message: string,+ { requestId, status }: UnreadableResponseDetail,+): string =>+ requestId+ ? t('response.withRequestDetail', { message, ns: 'error', requestId, status })+ : t('response.withStatusDetail', { message, ns: 'error', status });+/*** Build user-facing copy for a response body that parsed as JSON but was not a* `TRPCResponse`, so the tRPC client could not read it.@@ -9,12 +27,17 @@ import { t } from 'i18next';* envelope (`{ errorType, body }`) which already carries a precise diagnosis —* reuse the same copy `remoteServerErrorToast` shows for it. Any other foreign* JSON (a gateway or WAF error page, an unexpected redirect payload) only gets- * the generic "try again" message.+ * the generic "try again" message. A body that was not JSON at all (an HTML+ * gateway page) also gets the generic copy, plus its status and request id.*/-export const unreadableResponseMessage = (responseJSON: unknown): string => {+export const unreadableResponseMessage = (+ responseJSON: unknown,+ response?: UnreadableResponseDetail,+): string => {const errorType = (responseJSON as { errorType?: unknown } | null | undefined)?.errorType;- return isRemoteServerNetworkError(errorType)- ? t(`response.${errorType}`, { ns: 'error' })- : t('response.UnreadableServerResponse', { ns: 'error' });+ if (isRemoteServerNetworkError(errorType)) return t(`response.${errorType}`, { ns: 'error' });++ const message = t('response.UnreadableServerResponse', { ns: 'error' });+ return response ? withResponseDetail(message, response) : message;};diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsxindex 6dba7975cf3..dbb11da498e 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx@@ -61,6 +61,11 @@ const styles = createStaticStyles(({ css }) => ({line-height: 0;`,+ // Tooltips are unselectable by default; the error carries the request id a+ // user copies into a support report.+ errorText: css`+ user-select: text;+ `,name: css`overflow: hidden;flex: 1;@@ -100,7 +105,7 @@ const ContextItem = memo<FileItemProps>((props) => {<Flexbox align={'center'} justify={'center'} style={{ height: '1lh' }}><Icon icon={CircleAlertIcon} size={12} /></Flexbox>- <span>{error}</span>+ <span className={styles.errorText}>{error}</span></Flexbox>) : (<UploadDetail size={file.size} status={status} tasks={tasks} uploadState={uploadState} />diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex 3362bee8a76..5a8c15c4999 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -3,6 +3,7 @@ import { toast } from '@lobehub/ui';import { act, renderHook } from '@testing-library/react';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { UnreadableServerResponseError } from '@/libs/trpc/client/unreadableServerResponse';import { fileService } from '@/services/file';import { ragService } from '@/services/rag';import { shareChatService } from '@/services/shareChat';@@ -50,7 +51,10 @@ vi.mock('@/services/shareChat', () => ({}));vi.mock('i18next', () => ({- t: (key: string, options?: { reason?: string }) => {+ t: (+ key: string,+ options?: { message?: string; reason?: string; requestId?: string; status?: number },+ ) => {if (key === 'upload.permissionDenied') {return 'You do not have permission to upload files in this workspace.';}@@ -59,6 +63,12 @@ vi.mock('i18next', () => ({if (key === 'upload.unknownError') return `Error reason: ${options?.reason}`;+ if (key === 'upload.serviceUnavailable') return 'The upload service is unavailable.';++ if (key === 'response.withRequestDetail') {+ return `${options?.message} (HTTP ${options?.status} · Request ID: ${options?.requestId})`;+ }+return key;},}));@@ -341,6 +351,36 @@ describe('useFileStore:chat', () => {]);});+ // Regression: a gateway HTML error page answered the upload API and the card+ // showed `Error reason: Unexpected token '<', "<!doctype "... is not valid JSON`.+ it('shows the upload-unavailable copy with the request id of an HTML error page', async () => {+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });++ const { result } = renderHook(() => useStore());+ const file = new File(['docx'], 'report.docx', {+ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ });++ // tRPC wraps an error thrown by the link's fetch as the client error's cause.+ vi.spyOn(result.current, 'uploadWithProgress').mockRejectedValue(+ new Error('wrapped', {+ cause: new UnreadableServerResponseError({ requestId: 'a4f7-SJC', status: 502 }),+ }),+ );++ await act(async () => {+ await result.current.uploadChatFiles([file], AGENT_ID);+ });++ expect(result.current.chatUploadFileList).toEqual([+ expect.objectContaining({+ error: 'The upload service is unavailable. (HTTP 502 · Request ID: a4f7-SJC)',+ id: 'report.docx',+ status: 'error',+ }),+ ]);+ });+describe('uploadChatFiles as an agent-share visitor', () => {const SHARE_ID = 'share-1';diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 6c95c11b49f..05700f0fee6 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -5,7 +5,9 @@ import { toast } from '@lobehub/ui';import { Buffer } from 'buffer.js';import { t } from 'i18next';+import { withResponseDetail } from '@/components/Error/unreadableResponseMessage';import { FILE_UPLOAD_BLACKLIST } from '@/const/file';+import { findUnreadableServerResponseError } from '@/libs/trpc/client/unreadableServerResponse';import { fileService } from '@/services/file';import { ragService } from '@/services/rag';import { shareChatService } from '@/services/shareChat';@@ -78,6 +80,13 @@ const getUploadErrorDescription = (error: unknown): string => {return t('upload.permissionDenied', { ns: 'error' });}+ // A gateway error page answered instead of the upload API. Its parse error+ // means nothing to the user; the status and request id let support trace it.+ const unreadable = findUnreadableServerResponseError(error);+ if (unreadable) {+ return withResponseDetail(t('upload.serviceUnavailable', { ns: 'error' }), unreadable);+ }+return typeof error === 'string'? error: t('upload.unknownError', { ns: 'error', reason: getErrorMessage(error) });