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(desktop): surface backend-proxy network failures as typed errors (#17390)

Inneic0836ad8b8fc
diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
index bde42354eaf..f2d131337d5 100644
--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
@@ -7,6 +7,7 @@ import { getDesktopEnv } from '@/env';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
+import { classifyProxyNetworkError } from '@/utils/proxy-network-error';
import { setDesktopUserAgentHeader } from '@/utils/user-agent';
import type { RendererRequestInterceptor } from './RendererProtocolManager';
@@ -34,6 +35,18 @@ const describeError = (error: unknown) => {
return String(error);
};
+/**
+ * Serialize a network-level proxy failure as the JSON `ErrorResponse` envelope
+ * (`{ body, errorType }`) the renderer's error chain already parses — a plain
+ * 502 is indistinguishable from a real server-side 502, and users read that as
+ * an app bug when it is almost always their own network/proxy/VPN.
+ */
+const proxyNetworkErrorBody = (reason: string, url?: string) =>
+ JSON.stringify({
+ body: { detail: reason, ...(url ? { url } : {}) },
+ errorType: classifyProxyNetworkError(reason),
+ });
+
export class BackendProxyProtocolManager {
private readonly contexts = new WeakMap<Session, BackendProxyContext>();
private readonly logger = createLogger('core:BackendProxyProtocolManager');
@@ -217,8 +230,11 @@ export class BackendProxyProtocolManager {
this.logger.error(`BackendProxy interceptor failed (${reason}): ${request.url}`, error);
this.surfaceUncaughtProxyError(error);
- return new Response(`Backend Proxy Unavailable: ${reason}`, {
- headers: new Headers({ 'X-Proxy-Error': reason }),
+ return new Response(proxyNetworkErrorBody(reason), {
+ headers: new Headers({
+ 'Content-Type': 'application/json',
+ 'X-Proxy-Error': reason,
+ }),
status: 502,
});
}
@@ -289,7 +305,7 @@ export class BackendProxyProtocolManager {
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Expose-Headers': '*',
- 'Content-Type': 'text/plain; charset=utf-8',
+ 'Content-Type': 'application/json',
'X-Proxy-Error': reason,
'X-Proxy-Open-Upstream-Bodies': String(this.openUpstreamBodies),
'X-Proxy-Pending-Upstream': String(this.pendingUpstream),
@@ -300,7 +316,7 @@ export class BackendProxyProtocolManager {
responseHeaders.set('Access-Control-Allow-Origin', allowOrigin);
responseHeaders.set('Access-Control-Allow-Credentials', 'true');
}
- return new Response(`Backend Proxy Upstream Unavailable: ${reason}\n${gauges}`, {
+ return new Response(proxyNetworkErrorBody(reason, rewrittenUrl), {
headers: responseHeaders,
status: 502,
statusText: 'Bad Gateway',
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
index 89d5adea087..81814f1b9f2 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
@@ -233,7 +233,13 @@ describe('BackendProxyProtocolManager', () => {
// The Chromium error (net::ERR_*) is the diagnosis — it must survive into the
// body and a header, or a packaged build gives us nothing to go on.
expect(response!.headers.get('X-Proxy-Error')).toBe('network down');
- expect(await response!.text()).toContain('Backend Proxy Upstream Unavailable: network down');
+ // The body must be the JSON ErrorResponse envelope the renderer error chain
+ // parses — a plain-text 502 is indistinguishable from a real server 502.
+ expect(response!.headers.get('Content-Type')).toBe('application/json');
+ expect(await response!.json()).toEqual({
+ body: { detail: 'network down', url: 'https://remote.example.com/trpc/hello' },
+ errorType: 'RemoteServerUnreachable',
+ });
// The failing request must not count itself: a lone failure with nothing else
// in flight reads 0, not 1 — otherwise every failure looks like a backlog.
expect(response!.headers.get('X-Proxy-Pending-Upstream')).toBe('0');
@@ -452,7 +458,36 @@ describe('BackendProxyProtocolManager', () => {
expect(res).not.toBeNull();
expect(res!.status).toBe(502);
- expect(await res!.text()).toContain('Backend Proxy Unavailable');
+ expect(await res!.json()).toEqual({
+ body: { detail: 'token lookup failed' },
+ errorType: 'RemoteServerUnreachable',
+ });
+ });
+
+ it('classifies upstream network failures into a typed errorType', async () => {
+ const manager = new BackendProxyProtocolManager();
+ const session = {} as any;
+
+ const fetchMock = vi.fn(async () => {
+ throw new Error('net::ERR_TIMED_OUT');
+ });
+ vi.stubGlobal('fetch', fetchMock as any);
+
+ manager.registerWithRemoteBaseUrl(session, {
+ getAccessToken: async () => null,
+ getRemoteBaseUrl: async () => 'https://remote.example.com',
+ });
+
+ const response = await manager.proxy(
+ { headers: new Headers(), method: 'GET', url: 'app://renderer/trpc/hello' } as any,
+ session,
+ );
+
+ expect(response!.status).toBe(502);
+ expect(await response!.json()).toEqual({
+ body: { detail: 'net::ERR_TIMED_OUT', url: 'https://remote.example.com/trpc/hello' },
+ errorType: 'RemoteServerTimeout',
+ });
});
});
});
diff --git a/apps/desktop/src/main/utils/__tests__/proxy-network-error.test.ts b/apps/desktop/src/main/utils/__tests__/proxy-network-error.test.ts
new file mode 100644
index 00000000000..db2e4823174
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/proxy-network-error.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyProxyNetworkError } from '../proxy-network-error';
+
+describe('classifyProxyNetworkError', () => {
+ it.each([
+ ['net::ERR_INTERNET_DISCONNECTED', 'RemoteServerOffline'],
+ ['net::ERR_TIMED_OUT', 'RemoteServerTimeout'],
+ ['net::ERR_CONNECTION_TIMED_OUT', 'RemoteServerTimeout'],
+ ['ETIMEDOUT', 'RemoteServerTimeout'],
+ ['net::ERR_NAME_NOT_RESOLVED', 'RemoteServerDNSFailed'],
+ ['net::ERR_NAME_RESOLUTION_FAILED', 'RemoteServerDNSFailed'],
+ ['getaddrinfo ENOTFOUND example.com', 'RemoteServerDNSFailed'],
+ ['net::ERR_CONNECTION_REFUSED', 'RemoteServerConnectionRefused'],
+ ['net::ERR_CONNECTION_RESET', 'RemoteServerConnectionRefused'],
+ ['net::ERR_CONNECTION_CLOSED', 'RemoteServerConnectionRefused'],
+ ['connect ECONNREFUSED 127.0.0.1:443', 'RemoteServerConnectionRefused'],
+ ['net::ERR_CERT_AUTHORITY_INVALID', 'RemoteServerCertInvalid'],
+ ['net::ERR_SSL_PROTOCOL_ERROR', 'RemoteServerCertInvalid'],
+ ['net::ERR_FAILED', 'RemoteServerUnreachable'],
+ ['something completely unexpected', 'RemoteServerUnreachable'],
+ ])('maps %s to %s', (reason, expected) => {
+ expect(classifyProxyNetworkError(reason)).toBe(expected);
+ });
+});
diff --git a/apps/desktop/src/main/utils/proxy-network-error.ts b/apps/desktop/src/main/utils/proxy-network-error.ts
new file mode 100644
index 00000000000..23ee8c769f7
--- /dev/null
+++ b/apps/desktop/src/main/utils/proxy-network-error.ts
@@ -0,0 +1,27 @@
+// Local mirror of `@lobechat/types`' ChatErrorType RemoteServer* members —
+// the desktop tsconfig doesn't expose `@lobechat/types` (runtime stub leak risk).
+export type ProxyNetworkErrorType =
+ | 'RemoteServerOffline'
+ | 'RemoteServerTimeout'
+ | 'RemoteServerDNSFailed'
+ | 'RemoteServerConnectionRefused'
+ | 'RemoteServerCertInvalid'
+ | 'RemoteServerUnreachable';
+
+const MATCHERS: [RegExp, ProxyNetworkErrorType][] = [
+ [/INTERNET_DISCONNECTED/i, 'RemoteServerOffline'],
+ [/TIMED_OUT|ETIMEDOUT|TIMEOUT/i, 'RemoteServerTimeout'],
+ [/NAME_NOT_RESOLVED|NAME_RESOLUTION_FAILED|ENOTFOUND|EAI_AGAIN|DNS/i, 'RemoteServerDNSFailed'],
+ [
+ /CONNECTION_REFUSED|CONNECTION_RESET|CONNECTION_CLOSED|CONNECTION_ABORTED|ECONNREFUSED|ECONNRESET/i,
+ 'RemoteServerConnectionRefused',
+ ],
+ [/CERT_|_CERT|SSL_|_SSL|CERTIFICATE/i, 'RemoteServerCertInvalid'],
+];
+
+export const classifyProxyNetworkError = (reason: string): ProxyNetworkErrorType => {
+ for (const [pattern, errorType] of MATCHERS) {
+ if (pattern.test(reason)) return errorType;
+ }
+ return 'RemoteServerUnreachable';
+};
diff --git a/locales/en-US/error.json b/locales/en-US/error.json
index 952065d0e6c..70cf0ff37c3 100644
--- a/locales/en-US/error.json
+++ b/locales/en-US/error.json
@@ -100,6 +100,12 @@
"response.ProviderContentModerationWarning": "Repeated content policy rejections detected. Please revise your prompt before retrying.",
"response.ProviderImageContentModerationWarning": "Repeated image safety rejections detected. Similar prompts may temporarily pause image generation.",
"response.QuotaLimitReachedCloud": "The model service is currently under heavy load. Please try again later or switch to another model.",
+ "response.RemoteServerCertInvalid": "A secure connection to the server could not be established due to a certificate problem. Please check your system clock, or whether a proxy/firewall is intercepting the connection.",
+ "response.RemoteServerConnectionRefused": "The connection to the server was refused or reset. This usually indicates a local network problem — please check your firewall, proxy, or VPN settings and try again.",
+ "response.RemoteServerDNSFailed": "The server address could not be resolved. This usually indicates a local network or DNS problem — please check your network, DNS, or VPN settings and try again.",
+ "response.RemoteServerOffline": "You appear to be offline. This is a problem with your local network, not the app — please check your internet connection and try again.",
+ "response.RemoteServerTimeout": "The connection to the server timed out. This usually indicates a local network problem — please check your network quality, proxy, or VPN settings and try again.",
+ "response.RemoteServerUnreachable": "The server could not be reached. This usually indicates a local network problem — please check your internet connection, proxy, or VPN settings and try again.",
"response.ServerAgentRuntimeError": "Sorry, the Agent service is currently unavailable. Please try again later or contact us via email for support.",
"response.SubscriptionKeyMismatch": "We apologize for the inconvenience. Due to a temporary system malfunction, your current subscription usage is inactive. Please click the button below to restore your subscription, or contact us via email for support.",
"response.SubscriptionPlanLimit": "Your subscription points have been exhausted, and you cannot use this feature. Please upgrade to a higher plan or configure a custom model API to continue using it.",
diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.json
index edc6a258c69..9feba51b67c 100644
--- a/locales/zh-CN/error.json
+++ b/locales/zh-CN/error.json
@@ -100,6 +100,12 @@
"response.ProviderContentModerationWarning": "检测到多次内容政策拦截。请修改提示词后重试。",
"response.ProviderImageContentModerationWarning": "检测到多次生图安全拦截。继续使用相似提示词可能会暂时暂停生图能力。",
"response.QuotaLimitReachedCloud": "当前模型服务负载较高,请稍后重试或切换其他模型。",
+ "response.RemoteServerCertInvalid": "由于证书问题,无法与服务器建立安全连接。请检查系统时间是否正确,或是否有代理/防火墙拦截了连接。",
+ "response.RemoteServerConnectionRefused": "与服务器的连接被拒绝或重置。这通常是本机网络问题——请检查防火墙、代理或 VPN 设置后重试。",
+ "response.RemoteServerDNSFailed": "无法解析服务器地址。这通常是本机网络或 DNS 问题——请检查网络、DNS 或 VPN 设置后重试。",
+ "response.RemoteServerOffline": "你似乎已离线。这是本机网络问题,而非应用故障——请检查网络连接后重试。",
+ "response.RemoteServerTimeout": "连接服务器超时。这通常是本机网络问题——请检查网络质量、代理或 VPN 设置后重试。",
+ "response.RemoteServerUnreachable": "无法连接到服务器。这通常是本机网络问题——请检查网络连接、代理或 VPN 设置后重试。",
"response.ServerAgentRuntimeError": "助理运行服务暂不可用。请稍后再试,或邮件联系我们",
"response.SubscriptionKeyMismatch": "订阅状态同步异常。你可以点击下方按钮恢复订阅,或邮件联系我们",
"response.SubscriptionPlanLimit": "订阅积分已用尽,暂时无法使用该功能。你可以升级计划,或配置自定义模型 API 后继续",
diff --git a/packages/fetch-sse/src/__tests__/parseError.test.ts b/packages/fetch-sse/src/__tests__/parseError.test.ts
index b0ae77c8675..b60b9cfcb58 100644
--- a/packages/fetch-sse/src/__tests__/parseError.test.ts
+++ b/packages/fetch-sse/src/__tests__/parseError.test.ts
@@ -79,6 +79,22 @@ describe('getMessageError', () => {
expect(mockResponse.json).toHaveBeenCalled();
});
+ it('should surface the desktop proxy network errorType instead of a generic 502', async () => {
+ const mockErrorResponse: ErrorResponse = {
+ body: { detail: 'net::ERR_TIMED_OUT', url: 'https://remote.example.com/trpc/hello' },
+ errorType: 'RemoteServerTimeout',
+ };
+ const mockResponse = createMockResponse(mockErrorResponse, false, 502);
+
+ const error = await getMessageError(mockResponse as any);
+
+ expect(error).toEqual({
+ body: mockErrorResponse.body,
+ message: 'translated_response.RemoteServerTimeout',
+ type: 'RemoteServerTimeout',
+ });
+ });
+
it('should handle timeout error correctly', async () => {
const mockResponse = createMockResponse(undefined, false, 504);
const error = await getMessageError(mockResponse as any);
diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.ts
index a629e87b84d..86325c98761 100644
--- a/packages/locales/src/default/error.ts
+++ b/packages/locales/src/default/error.ts
@@ -172,6 +172,18 @@ export default {
'Repeated image safety rejections detected. Similar prompts may temporarily pause image generation.',
'response.DeviceGatewayNotConfigured':
"Couldn't reach a run device for this agent. Connect a device, or configure the device gateway on the server, then try again.",
+ 'response.RemoteServerOffline':
+ 'You appear to be offline. This is a problem with your local network, not the app — please check your internet connection and try again.',
+ 'response.RemoteServerTimeout':
+ 'The connection to the server timed out. This usually indicates a local network problem — please check your network quality, proxy, or VPN settings and try again.',
+ 'response.RemoteServerDNSFailed':
+ 'The server address could not be resolved. This usually indicates a local network or DNS problem — please check your network, DNS, or VPN settings and try again.',
+ 'response.RemoteServerConnectionRefused':
+ 'The connection to the server was refused or reset. This usually indicates a local network problem — please check your firewall, proxy, or VPN settings and try again.',
+ 'response.RemoteServerCertInvalid':
+ 'A secure connection to the server could not be established due to a certificate problem. Please check your system clock, or whether a proxy/firewall is intercepting the connection.',
+ 'response.RemoteServerUnreachable':
+ 'The server could not be reached. This usually indicates a local network problem — please check your internet connection, proxy, or VPN settings and try again.',
'response.ServerAgentRuntimeError':
'Sorry, the Agent service is currently unavailable. Please try again later or contact us via email for support.',
'response.SubscriptionKeyMismatch':
diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.ts
index 426234e777f..6c8f84757e3 100644
--- a/packages/trpc/src/client/lambda.ts
+++ b/packages/trpc/src/client/lambda.ts
@@ -1,3 +1,4 @@
+import { isRemoteServerNetworkError } from '@lobechat/types';
import { type TRPCLink } from '@trpc/client';
import { createTRPCClient, httpBatchLink, httpLink, splitLink } from '@trpc/client';
import { createTRPCReact } from '@trpc/react-query';
@@ -100,11 +101,33 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
);
};
+// Desktop backend proxy serializes upstream network failures (offline, timeout,
+// DNS, refused) as a 502 JSON ErrorResponse — surface those as a network-problem
+// toast so users don't read their own connectivity issues as app bugs.
+// `X-Proxy-Error` is set only by the desktop proxy's failure paths, so a real
+// server-side 502 (no header) is never mistaken for a local network problem.
+const isProxyNetworkFailure = (response: Response) =>
+ response.status === 502 && response.headers.has('X-Proxy-Error');
+
+const notifyRemoteServerNetworkError = async (response: Response) => {
+ try {
+ const data = (await response.clone().json()) as { errorType?: unknown };
+ if (!isRemoteServerNetworkError(data.errorType)) return;
+
+ const { remoteServerErrorToast } = await import('@/components/Error/remoteServerErrorToast');
+ remoteServerErrorToast(data.errorType);
+ } catch {
+ /* body was not the proxy envelope */
+ }
+};
+
// 2. Shared link options
const linkOptions = {
fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
// Ensure credentials are included to send cookies (like mp_token)
- return fetch(input, { ...init, credentials: 'include' });
+ const response = await fetch(input, { ...init, credentials: 'include' });
+ if (isDesktop && isProxyNetworkFailure(response)) void notifyRemoteServerNetworkError(response);
+ return response;
},
headers: async () => {
// dynamic import to avoid circular dependency
diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.ts
index 50dcb77d674..35762eaa81a 100644
--- a/packages/types/src/fetch.ts
+++ b/packages/types/src/fetch.ts
@@ -28,6 +28,16 @@ export const ChatErrorType = {
ServerAgentRuntimeError: 'ServerAgentRuntimeError',
DeviceGatewayNotConfigured: 'DeviceGatewayNotConfigured', // Heterogeneous agent has no reachable run device / gateway
+ // ******* Desktop Backend-Proxy Network Errors ******* //
+ // Emitted by the Electron backend proxy when the upstream fetch fails at the
+ // network level — usually the user's own network/proxy/VPN, not a server bug.
+ RemoteServerOffline: 'RemoteServerOffline',
+ RemoteServerTimeout: 'RemoteServerTimeout',
+ RemoteServerDNSFailed: 'RemoteServerDNSFailed',
+ RemoteServerConnectionRefused: 'RemoteServerConnectionRefused',
+ RemoteServerCertInvalid: 'RemoteServerCertInvalid',
+ RemoteServerUnreachable: 'RemoteServerUnreachable',
+
// ******* Client Errors ******* //
BadRequest: 400,
Unauthorized: 401,
@@ -45,6 +55,24 @@ export const ChatErrorType = {
export type ErrorType = (typeof ChatErrorType)[keyof typeof ChatErrorType];
+const remoteServerNetworkErrorTypes = [
+ ChatErrorType.RemoteServerOffline,
+ ChatErrorType.RemoteServerTimeout,
+ ChatErrorType.RemoteServerDNSFailed,
+ ChatErrorType.RemoteServerConnectionRefused,
+ ChatErrorType.RemoteServerCertInvalid,
+ ChatErrorType.RemoteServerUnreachable,
+] as const;
+
+export type RemoteServerNetworkErrorType = (typeof remoteServerNetworkErrorTypes)[number];
+
+const remoteServerNetworkErrorTypeSet = new Set<string>(remoteServerNetworkErrorTypes);
+
+export const isRemoteServerNetworkError = (
+ errorType: unknown,
+): errorType is RemoteServerNetworkErrorType =>
+ typeof errorType === 'string' && remoteServerNetworkErrorTypeSet.has(errorType);
+
export interface ErrorResponse {
body: any;
errorType: ErrorType | ILobeAgentRuntimeErrorType;
diff --git a/src/components/Error/remoteServerErrorToast.test.ts b/src/components/Error/remoteServerErrorToast.test.ts
new file mode 100644
index 00000000000..e01266c33bc
--- /dev/null
+++ b/src/components/Error/remoteServerErrorToast.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { remoteServerErrorToast } from './remoteServerErrorToast';
+
+const toastError = vi.fn();
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ toast: { error: (...args: unknown[]) => toastError(...args) },
+}));
+
+vi.mock('i18next', () => ({
+ t: vi.fn((key) => `translated_${key}`),
+}));
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ toastError.mockClear();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('remoteServerErrorToast', () => {
+ it('shows the same errorType at most once per interval', () => {
+ remoteServerErrorToast('RemoteServerTimeout');
+ remoteServerErrorToast('RemoteServerTimeout');
+ remoteServerErrorToast('RemoteServerTimeout');
+
+ expect(toastError).toHaveBeenCalledTimes(1);
+ expect(toastError).toHaveBeenCalledWith({
+ title: 'translated_response.RemoteServerTimeout',
+ });
+
+ vi.advanceTimersByTime(10_000);
+ remoteServerErrorToast('RemoteServerTimeout');
+ expect(toastError).toHaveBeenCalledTimes(2);
+ });
+
+ it('debounces per errorType independently', () => {
+ remoteServerErrorToast('RemoteServerDNSFailed');
+ remoteServerErrorToast('RemoteServerOffline');
+
+ expect(toastError).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/components/Error/remoteServerErrorToast.ts b/src/components/Error/remoteServerErrorToast.ts
new file mode 100644
index 00000000000..4e9d3861661
--- /dev/null
+++ b/src/components/Error/remoteServerErrorToast.ts
@@ -0,0 +1,15 @@
+import type { RemoteServerNetworkErrorType } from '@lobechat/types';
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+const MIN_TOAST_INTERVAL = 10_000;
+const lastShownAt = new Map<string, number>();
+
+export const remoteServerErrorToast = (errorType: RemoteServerNetworkErrorType) => {
+ const now = Date.now();
+ const last = lastShownAt.get(errorType) ?? 0;
+ if (now - last < MIN_TOAST_INTERVAL) return;
+ lastShownAt.set(errorType, now);
+
+ toast.error({ title: t(`response.${errorType}`, { ns: 'error' }) });
+};