🤯 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): stop leaking the tRPC transform error into the agent-config notice (#19159)
Arvin Xu41451c047fbd
diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex c4bd1b15540..0ea21600828 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -111,6 +111,7 @@"response.SubscriptionPlanLimitUltimate": "Your subscription points have been exhausted, and you cannot use this feature. Please top up credits or configure a custom model API to continue using it.","response.SystemTimeNotMatchError": "Sorry, your system time does not match the server. Please check your system time and try again.","response.UnknownChatFetchError": "Sorry, an unknown request error occurred. Please check the information below or try again.",+ "response.UnreadableServerResponse": "The server returned a response the app could not read. This is usually a temporary network or gateway problem — please try again in a moment.","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.",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex af3b3e98f80..872fef728c8 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -111,6 +111,7 @@"response.SubscriptionPlanLimitUltimate": "您的订阅积分已用尽,无法使用此功能。请充值积分或配置自定义模型 API 以继续使用。","response.SystemTimeNotMatchError": "系统时间与服务器不一致。请校准系统时间后重试","response.UnknownChatFetchError": "请求失败(未知错误)。请根据以下信息排查或重试",+ "response.UnreadableServerResponse": "服务器返回了应用无法识别的响应。这通常是网络或网关的临时问题——请稍后重试。","response.WorkspaceAgentRequiresWorkspaceDevice": "这是一个工作区助手,只能绑定全员都能访问的工作区设备。个人设备仅注册者本人可达 —— 请改选工作区设备,或先把这台设备加入工作区。","response.WorkspaceFrozenByAdmin": "工作区已被管理员冻结,暂时无法处理请求。请联系工作区所有者处理","response.WorkspaceFrozenByRiskControl": "工作区已被风控系统自动冻结,暂时无法处理请求。请联系客服处理",diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex f53098c8dc0..df82cbb0675 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -196,6 +196,8 @@ export default {'The model "{{model}}" is no longer available. Please pick a current model from the model selector.','response.UnknownChatFetchError':'Sorry, an unknown request error occurred. Please check the information below or try again.',+ 'response.UnreadableServerResponse':+ 'The server returned a response the app could not read. This is usually a temporary network or gateway problem — please try again in a moment.','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':diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex d581581a7d6..046d52866c1 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -6,6 +6,9 @@ import { lambdaClient } from './lambda';vi.mock('@/const/version', () => ({ isDesktop: false }));vi.mock('@/services/_auth', () => ({ createHeaderWithAuth: async () => ({}) }));vi.mock('@/business/client/trpc-headers', () => ({ getBusinessTrpcHeaders: async () => ({}) }));+// i18next is never initialised in this suite, so `t` echoes the key — assertions+// below check which copy was selected, not its wording.+vi.mock('i18next', () => ({ t: (key: string) => key }));const okTrpcResponse = (data: unknown) =>new Response(JSON.stringify({ result: { data: superjson.serialize(data) } }), {@@ -69,3 +72,71 @@ describe('lambdaClient large-input query transport', () => {},);});++describe('lambdaClient unreadable response handling', () => {+ const fetchMock = vi.fn();++ beforeEach(() => {+ vi.stubGlobal('fetch', fetchMock);+ vi.stubGlobal('location', new URL('http://localhost/chat'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ fetchMock.mockReset();+ });++ // Regression: a JSON body that is not a `TRPCResponse` makes @trpc/client+ // throw `TransformResultError`, and its internal message used to reach the+ // UI — the agent-config alert above the chat input rendered "Unable to+ // transform response from server" while the desktop app was simply offline.+ it('replaces the transform error with the diagnosed network copy', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ body: { detail: 'net::ERR_CONNECTION_REFUSED' },+ errorType: 'RemoteServerConnectionRefused',+ }),+ { headers: { 'content-type': 'application/json' }, status: 502 },+ ),+ );++ await expect(+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ).rejects.toThrow('response.RemoteServerConnectionRefused');+ });++ it('falls back to generic copy for foreign JSON without a known error type', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ message: 'Forbidden' }), {+ headers: { 'content-type': 'application/json' },+ status: 403,+ }),+ );++ await expect(+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ).rejects.toThrow('response.UnreadableServerResponse');+ });++ it('keeps a well-formed tRPC error message untouched', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ error: superjson.serialize({+ code: -32_600,+ data: { code: 'BAD_REQUEST', httpStatus: 400 },+ message: 'agentId is required',+ }),+ }),+ { headers: { 'content-type': 'application/json' }, status: 400 },+ ),+ );++ await expect(+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ).rejects.toThrow('agentId is required');+ });+});diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 04b6c2e488a..0fb5617f132 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -1,5 +1,5 @@import { isRemoteServerNetworkError } from '@lobechat/types';-import { type TRPCLink } from '@trpc/client';+import { type TRPCClientError, type TRPCLink } from '@trpc/client';import {createTRPCClient,httpBatchLink,@@ -23,6 +23,26 @@ let last401Time = 0;let lastMarket401Time = 0;const MIN_401_INTERVAL = 5000; // 5 seconds+// `@trpc/client` throws `TransformResultError` when a response body parses as+// JSON but is not a `TRPCResponse` — the desktop proxy's 502 network envelope+// (`{ errorType, body }`), a gateway/WAF JSON error page, and so on. Its message+// is an internal transport detail, yet every surface that renders `err.message`+// prints it verbatim: that is how "Unable to transform response from server"+// ends up as the description of the "agent config failed to load" alert above+// the chat input while the app is simply offline. Rewrite it into copy that+// says what actually happened.+const TRANSFORM_RESULT_ERROR_MESSAGE = 'Unable to transform response from server';++const rewriteUnreadableResponseMessage = async (err: TRPCClientError<LambdaRouter>) => {+ if (err.message !== TRANSFORM_RESULT_ERROR_MESSAGE) return;++ // dynamic import to avoid circular dependency+ const { unreadableResponseMessage } =+ await import('@/components/Error/unreadableResponseMessage');++ err.message = unreadableResponseMessage(err.meta?.responseJSON);+};+// handle errorconst errorHandlingLink: TRPCLink<LambdaRouter> = () => {return ({ op, next }) =>@@ -37,6 +57,8 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {err.cause?.name === 'AbortError' ||err.message.includes('signal is aborted without reason');+ if (!isAbortError) await rewriteUnreadableResponseMessage(err);+const showError = (op.context?.showNotification as boolean) ?? true;const status = err.data?.httpStatus as number;diff --git a/src/components/Error/unreadableResponseMessage.ts b/src/components/Error/unreadableResponseMessage.tsnew file mode 100644index 00000000000..ff44b0eeea5--- /dev/null+++ b/src/components/Error/unreadableResponseMessage.ts@@ -0,0 +1,20 @@+import { isRemoteServerNetworkError } from '@lobechat/types';+import { t } from 'i18next';++/**+ * 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.+ *+ * The desktop backend proxy answers upstream network failures with its own+ * 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.+ */+export const unreadableResponseMessage = (responseJSON: unknown): string => {+ const errorType = (responseJSON as { errorType?: unknown } | null | undefined)?.errorType;++ return isRemoteServerNetworkError(errorType)+ ? t(`response.${errorType}`, { ns: 'error' })+ : t('response.UnreadableServerResponse', { ns: 'error' });+};diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsxindex 97ef3274cca..adbd4898569 100644--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx@@ -1,17 +1,42 @@'use client';+import { Flexbox } from '@lobehub/ui';import { Alert, Button } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { contextSelectors, useConversationStore } from '@/features/Conversation/store';+import WideScreenContainer from '@/features/WideScreenContainer';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';+const styles = createStaticStyles(({ css }) => ({+ // base-ui stacks title and description in a gapless column, and both use a+ // 20px line height — without this they read as one run-on paragraph.+ description: css`+ margin-block-start: 2px;+ `,+ // The action column is top-aligned by default, which strands the button in+ // the corner as soon as the diagnosis wraps. Centre it against the whole+ // block, and keep a gutter so wrapped text never runs up against it.+ retry: css`+ align-self: center;+ padding-inline-start: 12px;+ `,+}));+/*** Surfaces an agent-config fetch failure above the chat input with a retry* button. Only shown when the config is still missing (`isAgentConfigLoading`)* — a failed background revalidation over cached data stays silent.+ *+ * Wrapped in the composer's own `WideScreenContainer` so its edges land on the+ * input's edges — without it the alert is a plain sibling of `ChatInput` and+ * spills wider than the input on both sides. No extra inline padding: the+ * container's 16px is what the composer itself sits on. The bottom padding+ * absorbs the `skipScrollMarginWithList` -12px pull `MainChatInput` puts on the+ * composer, leaving the ~6px gap the other composer notices have.*/const AgentConfigError = memo(() => {const { t } = useTranslation('chat');@@ -23,18 +48,22 @@ const AgentConfigError = memo(() => {if (!errorMessage || !isConfigMissing) return null;return (- <Alert- showIcon- description={errorMessage}- message={t('agentConfigError.title')}- style={{ marginBlockEnd: 8 }}- type={'error'}- action={- <Button size={'small'} onClick={() => retryAgentConfigFetch(agentId)}>- {t('agentConfigError.retry')}- </Button>- }- />+ <WideScreenContainer>+ <Flexbox paddingBlock={'0 18px'}>+ <Alert+ showIcon+ classNames={{ action: styles.retry, description: styles.description }}+ description={errorMessage}+ title={t('agentConfigError.title')}+ type={'error'}+ action={+ <Button size={'small'} onClick={() => retryAgentConfigFetch(agentId)}>+ {t('agentConfigError.retry')}+ </Button>+ }+ />+ </Flexbox>+ </WideScreenContainer>);});