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): contain backend proxy network failures (#16206)

Innei422fa702ab12
diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
index 02200a7a8f2..e3b577156d7 100644
--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
@@ -3,6 +3,7 @@ import { BrowserWindow, type Session, session as electronSession } from 'electro
import { isDev } from '@/const/env';
import { isBackendPath } from '@/const/protocol';
+import { getDesktopEnv } from '@/env';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
@@ -33,8 +34,22 @@ export class BackendProxyProtocolManager {
private authRequiredDebounceTimer: NodeJS.Timeout | null = null;
private pendingAuthRequiredReason: string | null = null;
+ private surfacedUncaughtProxyError = false;
private static readonly AUTH_REQUIRED_DEBOUNCE_MS = 1000;
+ private shouldRethrowProxyErrors() {
+ return isDev && getDesktopEnv().DESKTOP_BACKEND_PROXY_RETHROW_ERRORS;
+ }
+
+ private surfaceUncaughtProxyError(error: unknown) {
+ if (!this.shouldRethrowProxyErrors() || this.surfacedUncaughtProxyError) return;
+
+ this.surfacedUncaughtProxyError = true;
+ setTimeout(() => {
+ throw error;
+ }, 0);
+ }
+
private notifyAuthorizationRequired(reason: string) {
// Trailing-edge debounce: coalesce rapid 401 bursts and fire AFTER the burst settles.
// This ensures the IPC event is sent after the renderer has had time to mount listeners.
@@ -132,16 +147,23 @@ export class BackendProxyProtocolManager {
const session = electronSession.defaultSession;
if (!session) return new Response('Backend Proxy Unavailable', { status: 502 });
- const proxied = await this.proxy(request, session);
- return proxied ?? new Response('Backend Proxy Unavailable', { status: 502 });
+ try {
+ const proxied = await this.proxy(request, session);
+ return proxied ?? new Response('Backend Proxy Unavailable', { status: 502 });
+ } catch (error) {
+ this.logger.error(`BackendProxy interceptor failed: ${request.url}`, error);
+ this.surfaceUncaughtProxyError(error);
+
+ return new Response('Backend Proxy Unavailable', { status: 502 });
+ }
};
}
/**
* Proxy a renderer-originated request through the remote LobeHub backend.
* Returns `null` if the session has no proxy context registered yet (caller
- * decides how to fall back). Throws on upstream fetch failure to mirror the
- * original `protocol.handle` semantics.
+ * decides how to fall back). Upstream network failures become a controlled
+ * 502 response so they do not escape Electron's `protocol.handle` callback.
*/
async proxy(request: Request, session: Session): Promise<Response | null> {
const context = this.contexts.get(session);
@@ -179,7 +201,24 @@ export class BackendProxyProtocolManager {
upstreamResponse = await netFetch(rewrittenUrl, requestInit);
} catch (error) {
this.logger.error(`${logPrefix} upstream fetch failed: ${rewrittenUrl}`, error);
- throw error;
+ this.surfaceUncaughtProxyError(error);
+
+ const responseHeaders = new Headers({
+ 'Access-Control-Allow-Headers': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ 'Content-Type': 'text/plain; charset=utf-8',
+ 'X-Src-Url': rewrittenUrl,
+ });
+ const allowOrigin = request.headers.get('Origin') || undefined;
+ if (allowOrigin) {
+ responseHeaders.set('Access-Control-Allow-Origin', allowOrigin);
+ responseHeaders.set('Access-Control-Allow-Credentials', 'true');
+ }
+ return new Response('Backend Proxy Upstream Unavailable', {
+ headers: responseHeaders,
+ status: 502,
+ statusText: 'Bad Gateway',
+ });
}
const responseHeaders = new Headers(upstreamResponse.headers);
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 36b8b97c646..cbc9452ddb1 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
@@ -197,7 +197,7 @@ describe('BackendProxyProtocolManager', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
- it('throws when upstream fetch throws', async () => {
+ it('returns 502 when upstream fetch throws', async () => {
const manager = new BackendProxyProtocolManager();
const session = {} as any;
@@ -211,16 +211,22 @@ describe('BackendProxyProtocolManager', () => {
getRemoteBaseUrl: async () => 'https://remote.example.com',
});
- await expect(
- manager.proxy(
- {
- headers: new Headers(),
- method: 'GET',
- url: 'app://renderer/trpc/hello',
- } as any,
- session,
- ),
- ).rejects.toThrow('network down');
+ const response = await manager.proxy(
+ {
+ headers: new Headers({ Origin: 'app://renderer' }),
+ method: 'GET',
+ url: 'app://renderer/trpc/hello',
+ } as any,
+ session,
+ );
+
+ expect(response).not.toBeNull();
+ expect(response!.status).toBe(502);
+ expect(response!.statusText).toBe('Bad Gateway');
+ expect(response!.headers.get('Access-Control-Allow-Origin')).toBe('app://renderer');
+ expect(response!.headers.get('Access-Control-Allow-Credentials')).toBe('true');
+ expect(response!.headers.get('X-Src-Url')).toBe('https://remote.example.com/trpc/hello');
+ expect(await response!.text()).toBe('Backend Proxy Upstream Unavailable');
});
it('broadcasts authorizationRequired when X-Auth-Required is set on HTTP 207 (batched tRPC)', async () => {
@@ -373,5 +379,26 @@ describe('BackendProxyProtocolManager', () => {
expect.objectContaining({ method: 'GET' }),
);
});
+
+ it('returns 502 for backend paths when the proxy path fails unexpectedly', async () => {
+ const manager = new BackendProxyProtocolManager();
+ manager.register(electronSession.defaultSession as any, {
+ getAccessToken: async () => {
+ throw new Error('token lookup failed');
+ },
+ rewriteUrl: async () => 'https://remote.example.com/trpc/hello',
+ });
+
+ const interceptor = manager.createAppRequestInterceptor();
+ const res = await interceptor({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/trpc/hello',
+ } as any);
+
+ expect(res).not.toBeNull();
+ expect(res!.status).toBe(502);
+ expect(await res!.text()).toBe('Backend Proxy Unavailable');
+ });
});
});
diff --git a/apps/desktop/src/main/env.ts b/apps/desktop/src/main/env.ts
index 6804ee8695e..0e3a58de7fb 100644
--- a/apps/desktop/src/main/env.ts
+++ b/apps/desktop/src/main/env.ts
@@ -52,6 +52,7 @@ const envNumber = (defaultValue: number) =>
const getRuntimeEnv = () => ({
...process.env,
+ DESKTOP_BACKEND_PROXY_RETHROW_ERRORS: process.env.DESKTOP_BACKEND_PROXY_RETHROW_ERRORS,
DESKTOP_EXTERNAL_NAVIGATION_HOSTS: process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS,
UPDATE_CHANNEL: process.env.UPDATE_CHANNEL,
UPDATE_SERVER_URL: process.env.UPDATE_SERVER_URL,
@@ -77,6 +78,10 @@ export const getDesktopEnv = memoize(() =>
// escape hatch: allow testing static renderer in dev via env
DESKTOP_RENDERER_STATIC: envBoolean(false),
+ // Dev-only failure injection: surface backend proxy errors as uncaught
+ // main-process exceptions so Electron's default dialog can be reproduced.
+ DESKTOP_BACKEND_PROXY_RETHROW_ERRORS: envBoolean(false),
+
DESKTOP_EXTERNAL_NAVIGATION_HOSTS: z.string().optional().default(''),
// device gateway url override (dev: point at a local `wrangler dev` instance,