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.

♻️ refactor(desktop): move backend URL rewrite into main process (#15304)

Inneie855fcc0b894
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts
index 62730ad4a11..ff5f19719c1 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -223,5 +223,19 @@ export default defineConfig({
dedupe: ['react', 'react-dom'],
tsconfigPaths: true,
},
+ // In dev the BrowserWindow loads `app://renderer/` and the Electron main process
+ // proxies non-backend requests to this Vite dev server via `net.fetch`. The HMR
+ // WebSocket still connects directly (browser β†’ ws://localhost:<port>) β€” so the
+ // port MUST be deterministic. `strictPort` fails fast on conflict instead of
+ // silently sliding, and `clientPort` baked into the HMR injection has to match.
+ server: {
+ hmr: {
+ clientPort: 5173,
+ host: 'localhost',
+ protocol: 'ws',
+ },
+ port: 5173,
+ strictPort: true,
+ },
},
});
diff --git a/apps/desktop/src/main/const/protocol.ts b/apps/desktop/src/main/const/protocol.ts
index 9203c2640a8..57c8741c900 100644
--- a/apps/desktop/src/main/const/protocol.ts
+++ b/apps/desktop/src/main/const/protocol.ts
@@ -1,4 +1,16 @@
-export const ELECTRON_BE_PROTOCOL_SCHEME = 'lobe-backend';
-
export const LOCAL_FILE_PROTOCOL_SCHEME = 'localfile';
export const LOCAL_FILE_PROTOCOL_HOST = 'file';
+
+/**
+ * Renderer pathnames that must be proxied to the remote LobeHub backend
+ * instead of being served as static assets. Covers tRPC, webapi, NextAuth,
+ * and the marketplace REST + OIDC token/userinfo/handoff endpoints.
+ *
+ * `/lobehub-oidc/*` is intentionally NOT here β€” those URLs are handed to
+ * `shell.openExternal` as fully-qualified web URLs and never reach renderer
+ * `fetch`.
+ */
+export const BACKEND_PATH_PREFIXES = ['/trpc', '/webapi', '/api/auth', '/market'];
+
+export const isBackendPath = (pathname: string) =>
+ BACKEND_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index dcb72c31549..919a1c8d998 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -10,7 +10,6 @@ import * as electronIs from 'electron-is';
import { name } from '@/../../package.json';
import { binDir, buildDir } from '@/const/dir';
import { isDev } from '@/const/env';
-import { ELECTRON_BE_PROTOCOL_SCHEME } from '@/const/protocol';
import type { IControlModule } from '@/controllers';
import AuthCtr from '@/controllers/AuthCtr';
import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';
@@ -29,6 +28,7 @@ import type { IServiceModule } from '@/services';
import { createLogger } from '@/utils/logger';
import { BrowserManager } from './browser/BrowserManager';
+import { backendProxyProtocolManager } from './infrastructure/BackendProxyProtocolManager';
import { I18nManager } from './infrastructure/I18nManager';
import { IoCContainer } from './infrastructure/IoCContainer';
import { LocalFileProtocolManager } from './infrastructure/LocalFileProtocolManager';
@@ -104,21 +104,17 @@ export class App {
this.storeManager = new StoreManager(this);
this.rendererUrlManager = new RendererUrlManager();
+ // Wire the backend reverse-proxy as an `app://` interceptor: keeps
+ // RendererUrlManager ignorant of "what counts as a backend path" while
+ // letting BackendProxyProtocolManager own that knowledge.
+ this.rendererUrlManager.addRequestInterceptor(
+ backendProxyProtocolManager.createAppRequestInterceptor(),
+ );
this.localFileProtocolManager = new LocalFileProtocolManager();
void this.localFileProtocolManager.approveWorkspaceRoots(
this.storeManager.get('localFileWorkspaceRoots', []),
);
protocol.registerSchemesAsPrivileged([
- {
- privileges: {
- allowServiceWorkers: true,
- corsEnabled: true,
- secure: true,
- standard: true,
- supportFetchAPI: true,
- },
- scheme: ELECTRON_BE_PROTOCOL_SCHEME,
- },
this.rendererUrlManager.protocolScheme,
this.localFileProtocolManager.protocolScheme,
]);
@@ -431,7 +427,6 @@ export class App {
if (!isDev) return;
logger.debug('Setting up dev branding');
- app.setName('lobehub-desktop-dev');
if (electronIs.macOS()) {
app.dock!.setIcon(path.join(buildDir, 'icon-dev.png'));
}
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index 6c0ef774c35..ac27f8a1e3c 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -8,7 +8,6 @@ import { app, BrowserWindow, ipcMain, screen, session as electronSession, shell
import { preloadDir, resourcesDir } from '@/const/dir';
import { isMac } from '@/const/env';
-import { ELECTRON_BE_PROTOCOL_SCHEME } from '@/const/protocol';
import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';
import { backendProxyProtocolManager } from '@/core/infrastructure/BackendProxyProtocolManager';
import { appendVercelCookie, setResponseHeader } from '@/utils/http-headers';
@@ -561,7 +560,10 @@ export default class Browser {
}
/**
- * Rewrite tRPC requests to remote server and inject OIDC token
+ * Bind this window's session to the backend proxy. The `app://` request
+ * interceptor (wired in `App.ts`) consumes this context to route
+ * `/trpc`, `/webapi`, `/api/auth`, and `/market` requests to the remote
+ * LobeHub server.
*/
private setupRemoteServerRequestHook(browserWindow: BrowserWindow): void {
const session = browserWindow.webContents.session;
@@ -577,7 +579,6 @@ export default class Browser {
const remoteServerUrl = await remoteServerConfigCtr.getRemoteServerUrl(config);
return remoteServerUrl || null;
},
- scheme: ELECTRON_BE_PROTOCOL_SCHEME,
source: this.identifier,
});
}
diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
index ff4416878bb..41038cf2a1c 100644
--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
@@ -1,44 +1,36 @@
import { AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
-import { BrowserWindow, type Session } from 'electron';
+import { BrowserWindow, type Session, session as electronSession } from 'electron';
import { isDev } from '@/const/env';
+import { isBackendPath } from '@/const/protocol';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
-interface BackendProxyProtocolManagerOptions {
+import type { RendererRequestInterceptor } from './RendererProtocolManager';
+
+interface BackendProxyContext {
getAccessToken: () => Promise<string | undefined | null>;
rewriteUrl: (rawUrl: string) => Promise<string | null>;
- scheme: string;
- /**
- * Used for log prefixes. e.g. window identifier
- */
source?: string;
}
-interface BackendProxyProtocolManagerRemoteBaseOptions {
+interface BackendProxyRemoteBaseOptions {
getAccessToken: () => Promise<string | undefined | null>;
getRemoteBaseUrl: () => Promise<string | undefined | null>;
- scheme: string;
- /**
- * Used for log prefixes. e.g. window identifier
- */
source?: string;
}
/**
- * Manage `lobe-backend://` (or any custom scheme) transparent proxy handler registration.
- * Keeps a WeakSet per session to avoid duplicate handler registration.
+ * Holds per-session proxy context for routing renderer-originated backend
+ * requests (`/trpc`, `/webapi`, `/api/auth`, `/market`) to the remote LobeHub
+ * server. The context is consumed by `createAppRequestInterceptor`, which the
+ * `app://` protocol manager invokes before its static / Vite fallback.
*/
export class BackendProxyProtocolManager {
- private readonly handledSessions = new WeakSet<Session>();
+ private readonly contexts = new WeakMap<Session, BackendProxyContext>();
private readonly logger = createLogger('core:BackendProxyProtocolManager');
- /**
- * Debounce timer for authorization required notifications.
- * Prevents multiple rapid 401 responses from triggering duplicate notifications.
- */
-
private authRequiredDebounceTimer: NodeJS.Timeout | null = null;
private static readonly AUTH_REQUIRED_DEBOUNCE_MS = 1000;
@@ -61,10 +53,12 @@ export class BackendProxyProtocolManager {
}, BackendProxyProtocolManager.AUTH_REQUIRED_DEBOUNCE_MS);
}
- registerWithRemoteBaseUrl(
- session: Session,
- options: BackendProxyProtocolManagerRemoteBaseOptions,
- ) {
+ /**
+ * Bind a session's proxy context using a remote-base-URL provider. Backend
+ * paths get rewritten onto the remote base; same-origin requests pass through
+ * (returns null so the `app://` handler falls back to its static / Vite path).
+ */
+ registerWithRemoteBaseUrl(session: Session, options: BackendProxyRemoteBaseOptions) {
let lastRemoteBaseUrl: string | undefined;
const rewriteUrl = async (rawUrl: string) => {
@@ -99,90 +93,117 @@ export class BackendProxyProtocolManager {
this.register(session, {
getAccessToken: options.getAccessToken,
rewriteUrl,
- scheme: options.scheme,
source: options.source,
});
}
- register(session: Session, options: BackendProxyProtocolManagerOptions) {
- if (!session || this.handledSessions.has(session)) return;
-
- const logPrefix = options.source ? `[${options.source}] BackendProxy` : '[BackendProxy]';
+ /**
+ * Bind a session's proxy context. Subsequent backend-path requests on this
+ * session will be rewritten via `rewriteUrl` and have `Oidc-Auth` injected.
+ */
+ register(session: Session, context: BackendProxyContext) {
+ if (!session) return;
+ this.contexts.set(session, context);
+ }
- session.protocol.handle(options.scheme, async (request: Request): Promise<Response | null> => {
- try {
- const rewrittenUrl = await options.rewriteUrl(request.url);
- if (!rewrittenUrl) return null;
+ /**
+ * Build an `app://` request interceptor that diverts backend-prefixed paths
+ * (trpc / webapi / api/auth / market) through `proxy()` against the default
+ * session. Plug into `RendererProtocolManager.addRequestInterceptor` so the
+ * protocol manager doesn't need to know what "backend" means.
+ *
+ * Returns `null` for non-backend paths (lets the fallback run). Returns a
+ * 502 if the backend context isn't wired up yet β€” for backend prefixes we
+ * must never fall through to the SPA HTML / Vite path.
+ */
+ createAppRequestInterceptor(): RendererRequestInterceptor {
+ return async (request) => {
+ const url = new URL(request.url);
+ if (!isBackendPath(url.pathname)) return null;
- const headers = new Headers(request.headers);
- const token = await options.getAccessToken();
- if (token) {
- headers.set('Oidc-Auth', token);
- }
- appendVercelCookie(headers);
-
- const requestInit: RequestInit & { duplex?: 'half' } = {
- headers,
- method: request.method,
- };
-
- // Only forward body for non-GET/HEAD requests
- if (request.method !== 'GET' && request.method !== 'HEAD') {
- const body = request.body ?? undefined;
- if (body) {
- requestInit.body = body;
- // Node.js (undici) requires `duplex` when sending a streaming body
- requestInit.duplex = 'half';
- }
- }
+ const session = electronSession.defaultSession;
+ if (!session) return new Response('Backend Proxy Unavailable', { status: 502 });
- let upstreamResponse: Response;
- try {
- upstreamResponse = await netFetch(rewrittenUrl, requestInit);
- } catch (error) {
- this.logger.error(`${logPrefix} upstream fetch failed: ${rewrittenUrl}`, error);
+ const proxied = await this.proxy(request, session);
+ return proxied ?? new Response('Backend Proxy Unavailable', { status: 502 });
+ };
+ }
- throw error;
- }
+ /**
+ * 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.
+ */
+ async proxy(request: Request, session: Session): Promise<Response | null> {
+ const context = this.contexts.get(session);
+ if (!context) return null;
- const responseHeaders = new Headers(upstreamResponse.headers);
- const allowOrigin = request.headers.get('Origin') || undefined;
+ const logPrefix = context.source ? `[${context.source}] BackendProxy` : '[BackendProxy]';
- if (allowOrigin) {
- responseHeaders.set('Access-Control-Allow-Origin', allowOrigin);
- responseHeaders.set('Access-Control-Allow-Credentials', 'true');
- }
+ const rewrittenUrl = await context.rewriteUrl(request.url);
+ if (!rewrittenUrl) return null;
- if (isDev) {
- responseHeaders.set('x-dev-oidc-auth', token);
- }
+ const headers = new Headers(request.headers);
+ const token = await context.getAccessToken();
+ if (token) {
+ headers.set('Oidc-Auth', token);
+ }
+ appendVercelCookie(headers);
- responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
- responseHeaders.set('Access-Control-Allow-Headers', '*');
- responseHeaders.set('X-Src-Url', rewrittenUrl);
-
- // Re-auth prompt: rely on X-Auth-Required (set by tRPC responseMeta for UNAUTHORIZED).
- // Batched tRPC responses can use HTTP 207 when calls mix success (200) and UNAUTHORIZED (401);
- // checking only status === 401 misses that case and the login modal never opens.
- // Other failures keep 401 without this header (e.g., invalid API keys) and must not notify here.
- const authRequired = upstreamResponse.headers.get(AUTH_REQUIRED_HEADER) === 'true';
- if (authRequired) {
- this.notifyAuthorizationRequired();
- }
+ const requestInit: RequestInit & { duplex?: 'half' } = {
+ headers,
+ method: request.method,
+ };
- return new Response(upstreamResponse.body, {
- headers: responseHeaders,
- status: upstreamResponse.status,
- statusText: upstreamResponse.statusText,
- });
- } catch (error) {
- this.logger.error(`${logPrefix} protocol.handle error:`, error);
- throw error;
+ // Only forward body for non-GET/HEAD requests
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
+ const body = request.body ?? undefined;
+ if (body) {
+ requestInit.body = body;
+ // Node.js (undici) requires `duplex` when sending a streaming body
+ requestInit.duplex = 'half';
}
- });
+ }
- this.logger.debug(`${logPrefix} protocol handler registered for ${options.scheme}`);
- this.handledSessions.add(session);
+ let upstreamResponse: Response;
+ try {
+ upstreamResponse = await netFetch(rewrittenUrl, requestInit);
+ } catch (error) {
+ this.logger.error(`${logPrefix} upstream fetch failed: ${rewrittenUrl}`, error);
+ throw error;
+ }
+
+ const responseHeaders = new Headers(upstreamResponse.headers);
+ const allowOrigin = request.headers.get('Origin') || undefined;
+
+ if (allowOrigin) {
+ responseHeaders.set('Access-Control-Allow-Origin', allowOrigin);
+ responseHeaders.set('Access-Control-Allow-Credentials', 'true');
+ }
+
+ if (isDev) {
+ responseHeaders.set('x-dev-oidc-auth', token);
+ }
+
+ responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
+ responseHeaders.set('Access-Control-Allow-Headers', '*');
+ responseHeaders.set('X-Src-Url', rewrittenUrl);
+
+ // Re-auth prompt: rely on X-Auth-Required (set by tRPC responseMeta for UNAUTHORIZED).
+ // Batched tRPC responses can use HTTP 207 when calls mix success (200) and UNAUTHORIZED (401);
+ // checking only status === 401 misses that case and the login modal never opens.
+ // Other failures keep 401 without this header (e.g., invalid API keys) and must not notify here.
+ const authRequired = upstreamResponse.headers.get(AUTH_REQUIRED_HEADER) === 'true';
+ if (authRequired) {
+ this.notifyAuthorizationRequired();
+ }
+
+ return new Response(upstreamResponse.body, {
+ headers: responseHeaders,
+ status: upstreamResponse.status,
+ statusText: upstreamResponse.statusText,
+ });
}
}
diff --git a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
index bc37b1b7e01..ee53be75ca8 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
@@ -1,7 +1,7 @@
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
-import { app, protocol } from 'electron';
+import { app, net, protocol } from 'electron';
import { pathExistsSync } from 'fs-extra';
import { createLogger } from '@/utils/logger';
@@ -10,41 +10,61 @@ import { getExportMimeType } from '../../utils/mime';
type ResolveRendererFilePath = (url: URL) => Promise<string | null>;
+/**
+ * Request interceptor: inspects an `app://` request and either produces a Response
+ * (short-circuits the pipeline) or returns `null` to let the next interceptor β€” and
+ * ultimately the fallback strategy β€” try.
+ */
+export type RendererRequestInterceptor = (request: Request) => Promise<Response | null>;
+
+/**
+ * Fallback strategy invoked when no interceptor handled the request. Static
+ * (production) and Vite-proxy (development) implementations live below; the
+ * protocol manager is agnostic to which one is plugged in.
+ */
+export interface RendererFallbackStrategy {
+ handle: (request: Request, url: URL) => Promise<Response>;
+}
+
const RENDERER_PROTOCOL_PRIVILEGES = {
allowServiceWorkers: true,
corsEnabled: true,
secure: true,
standard: true,
+ stream: true,
supportFetchAPI: true,
} as const;
interface RendererProtocolManagerOptions {
+ fallback: RendererFallbackStrategy;
host?: string;
- rendererDir: string;
- resolveRendererFilePath: ResolveRendererFilePath;
scheme?: string;
}
const RENDERER_DIR = 'renderer';
+
export class RendererProtocolManager {
private readonly scheme: string;
private readonly host: string;
- private readonly rendererDir: string;
- private readonly resolveRendererFilePath: ResolveRendererFilePath;
+ private readonly fallback: RendererFallbackStrategy;
+ private readonly interceptors: RendererRequestInterceptor[] = [];
private handlerRegistered = false;
constructor(options: RendererProtocolManagerOptions) {
- const { rendererDir, resolveRendererFilePath } = options;
-
- this.scheme = 'app';
- this.host = RENDERER_DIR;
- this.rendererDir = rendererDir;
- this.resolveRendererFilePath = resolveRendererFilePath;
+ this.scheme = options.scheme ?? 'app';
+ this.host = options.host ?? RENDERER_DIR;
+ this.fallback = options.fallback;
}
/**
- * Get the full renderer URL with scheme and host
+ * Register a request interceptor that runs before the fallback strategy.
+ * Interceptors are invoked in registration order; the first one to return a
+ * non-null Response short-circuits the pipeline.
*/
+ addRequestInterceptor(interceptor: RendererRequestInterceptor) {
+ this.interceptors.push(interceptor);
+ }
+
getRendererUrl(): string {
return `${this.scheme}://${this.host}`;
}
@@ -55,169 +75,30 @@ export class RendererProtocolManager {
scheme: this.scheme,
};
}
+
registerHandler() {
if (this.handlerRegistered) return;
- if (!pathExistsSync(this.rendererDir)) {
- createLogger('core:RendererProtocolManager').warn(
- `Renderer directory not found, skip static handler: ${this.rendererDir}`,
- );
- return;
- }
-
const logger = createLogger('core:RendererProtocolManager');
- logger.debug(
- `Registering renderer ${this.scheme}:// handler for production export at host ${this.host}`,
- );
+ logger.debug(`Registering ${this.scheme}:// handler for host ${this.host}`);
const register = () => {
if (this.handlerRegistered) return;
protocol.handle(this.scheme, async (request) => {
const url = new URL(request.url);
- const hostname = url.hostname;
- const pathname = url.pathname;
- const isAssetRequest = this.isAssetRequest(pathname);
- const isExplicit404HtmlRequest = pathname.endsWith('/404.html');
- if (hostname !== this.host) {
+ if (url.hostname !== this.host) {
return new Response('Not Found', { status: 404 });
}
- const buildFileResponse = async (targetPath: string) => {
- const fileStat = await stat(targetPath);
- const totalSize = fileStat.size;
-
- const buffer = await readFile(targetPath);
- const headers = new Headers();
- const mimeType = getExportMimeType(targetPath);
-
- if (mimeType) headers.set('Content-Type', mimeType);
-
- // Chromium media pipeline relies on byte ranges for video/audio.
- headers.set('Accept-Ranges', 'bytes');
-
- const method = request.method?.toUpperCase?.() || 'GET';
- const rangeHeader = request.headers.get('range') || request.headers.get('Range');
-
- // HEAD (no range): return only headers
- if (method === 'HEAD' && !rangeHeader) {
- headers.set('Content-Length', String(totalSize));
- return new Response(null, { headers, status: 200 });
- }
-
- // No Range: return entire file
- if (!rangeHeader) {
- headers.set('Content-Length', String(buffer.byteLength));
- return new Response(buffer, { headers, status: 200 });
- }
-
- // Range: bytes=start-end | bytes=-suffixLength
- const match = /^bytes=(\d*)-(\d*)$/i.exec(rangeHeader.trim());
- if (!match) {
- headers.set('Content-Range', `bytes */${totalSize}`);
- return new Response(null, {
- headers,
- status: 416,
- statusText: 'Range Not Satisfiable',
- });
- }
-
- const [, startRaw, endRaw] = match;
- let start = startRaw ? Number(startRaw) : NaN;
- let end = endRaw ? Number(endRaw) : NaN;
-
- // Suffix range: bytes=-N (last N bytes)
- if (!startRaw && endRaw) {
- const suffixLength = Number(endRaw);
- if (!Number.isFinite(suffixLength) || suffixLength <= 0) {
- headers.set('Content-Range', `bytes */${totalSize}`);
- return new Response(null, {
- headers,
- status: 416,
- statusText: 'Range Not Satisfiable',
- });
- }
- start = Math.max(totalSize - suffixLength, 0);
- end = totalSize - 1;
- } else {
- if (!Number.isFinite(start)) start = 0;
- if (!Number.isFinite(end)) end = totalSize - 1;
- }
-
- if (start < 0 || end < 0 || start > end || start >= totalSize) {
- headers.set('Content-Range', `bytes */${totalSize}`);
- return new Response(null, {
- headers,
- status: 416,
- statusText: 'Range Not Satisfiable',
- });
- }
-
- end = Math.min(end, totalSize - 1);
- const sliced = buffer.subarray(start, end + 1);
-
- headers.set('Content-Range', `bytes ${start}-${end}/${totalSize}`);
- headers.set('Content-Length', String(sliced.byteLength));
-
- if (method === 'HEAD') {
- return new Response(null, { headers, status: 206, statusText: 'Partial Content' });
- }
-
- return new Response(sliced, { headers, status: 206, statusText: 'Partial Content' });
- };
-
- const resolveEntryFilePath = () =>
- this.resolveRendererFilePath(new URL(`${this.scheme}://${this.host}/`));
-
- let filePath = await this.resolveRendererFilePath(url);
-
- // If the resolved file is the export 404 page, treat it as missing so we can
- // fall back to the entry HTML for SPA routing (unless explicitly requested).
- if (filePath && this.is404Html(filePath) && !isExplicit404HtmlRequest) {
- filePath = null;
- }
-
- if (!filePath) {
- if (isAssetRequest) {
- return new Response('File Not Found', { status: 404 });
- }
-
- // Fallback to entry HTML for unknown routes (SPA-like behavior)
- filePath = await resolveEntryFilePath();
- if (!filePath || this.is404Html(filePath)) {
- return new Response('Render file Not Found', { status: 404 });
- }
+ // Pipeline: first interceptor to return a Response wins; null = pass through.
+ for (const interceptor of this.interceptors) {
+ const response = await interceptor(request);
+ if (response) return response;
}
- try {
- return await buildFileResponse(filePath);
- } catch (error) {
- const code = (error as any).code;
-
- if (code === 'ENOENT') {
- logger.warn(`Export asset missing on disk ${filePath}, falling back`, error);
-
- if (isAssetRequest) {
- return new Response('File Not Found', { status: 404 });
- }
-
- const fallbackPath = await resolveEntryFilePath();
- if (!fallbackPath || this.is404Html(fallbackPath)) {
- return new Response('Render file Not Found', { status: 404 });
- }
-
- try {
- return await buildFileResponse(fallbackPath);
- } catch (fallbackError) {
- logger.error(`Failed to serve fallback entry ${fallbackPath}:`, fallbackError);
- return new Response('Internal Server Error', { status: 500 });
- }
- }
-
- logger.error(`Failed to serve export asset ${filePath}:`, error);
- return new Response('Internal Server Error', { status: 500 });
- }
+ return this.fallback.handle(request, url);
});
this.handlerRegistered = true;
@@ -227,10 +108,165 @@ export class RendererProtocolManager {
register();
} else {
// protocol.handle needs the default session, which is only available after ready
-
app.whenReady().then(register);
}
}
+}
+
+/**
+ * Production fallback: serve the renderer's static export from disk. Resolves
+ * the file via `resolveRendererFilePath`, falls back to the SPA entry HTML for
+ * unknown routes, and supports HTTP `Range` requests for media playback.
+ */
+export class StaticRendererFallback implements RendererFallbackStrategy {
+ private readonly rendererDir: string;
+ private readonly resolveRendererFilePath: ResolveRendererFilePath;
+ private readonly logger = createLogger('core:StaticRendererFallback');
+
+ constructor(rendererDir: string, resolveRendererFilePath: ResolveRendererFilePath) {
+ this.rendererDir = rendererDir;
+ this.resolveRendererFilePath = resolveRendererFilePath;
+
+ if (!pathExistsSync(this.rendererDir)) {
+ this.logger.warn(`Renderer directory not found: ${this.rendererDir}`);
+ }
+ }
+
+ async handle(request: Request, url: URL): Promise<Response> {
+ const pathname = url.pathname;
+ const isAssetRequest = this.isAssetRequest(pathname);
+ const isExplicit404HtmlRequest = pathname.endsWith('/404.html');
+
+ let filePath = await this.resolveRendererFilePath(url);
+
+ if (filePath && this.is404Html(filePath) && !isExplicit404HtmlRequest) {
+ filePath = null;
+ }
+
+ if (!filePath) {
+ if (isAssetRequest) {
+ return new Response('File Not Found', { status: 404 });
+ }
+
+ filePath = await this.resolveEntryFilePath(url);
+ if (!filePath || this.is404Html(filePath)) {
+ return new Response('Render file Not Found', { status: 404 });
+ }
+ }
+
+ try {
+ return await this.buildFileResponse(request, filePath);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+
+ if (code === 'ENOENT') {
+ this.logger.warn(`Export asset missing on disk ${filePath}, falling back`, error);
+
+ if (isAssetRequest) {
+ return new Response('File Not Found', { status: 404 });
+ }
+
+ const fallbackPath = await this.resolveEntryFilePath(url);
+ if (!fallbackPath || this.is404Html(fallbackPath)) {
+ return new Response('Render file Not Found', { status: 404 });
+ }
+
+ try {
+ return await this.buildFileResponse(request, fallbackPath);
+ } catch (fallbackError) {
+ this.logger.error(`Failed to serve fallback entry ${fallbackPath}:`, fallbackError);
+ return new Response('Internal Server Error', { status: 500 });
+ }
+ }
+
+ this.logger.error(`Failed to serve export asset ${filePath}:`, error);
+ return new Response('Internal Server Error', { status: 500 });
+ }
+ }
+
+ private resolveEntryFilePath(url: URL) {
+ return this.resolveRendererFilePath(new URL(`${url.protocol}//${url.host}/`));
+ }
+
+ private async buildFileResponse(request: Request, targetPath: string): Promise<Response> {
+ const fileStat = await stat(targetPath);
+ const totalSize = fileStat.size;
+
+ const buffer = await readFile(targetPath);
+ const headers = new Headers();
+ const mimeType = getExportMimeType(targetPath);
+
+ if (mimeType) headers.set('Content-Type', mimeType);
+
+ // Chromium media pipeline relies on byte ranges for video/audio.
+ headers.set('Accept-Ranges', 'bytes');
+
+ const method = request.method?.toUpperCase?.() || 'GET';
+ const rangeHeader = request.headers.get('range') || request.headers.get('Range');
+
+ if (method === 'HEAD' && !rangeHeader) {
+ headers.set('Content-Length', String(totalSize));
+ return new Response(null, { headers, status: 200 });
+ }
+
+ if (!rangeHeader) {
+ headers.set('Content-Length', String(buffer.byteLength));
+ return new Response(buffer, { headers, status: 200 });
+ }
+
+ const match = /^bytes=(\d*)-(\d*)$/i.exec(rangeHeader.trim());
+ if (!match) {
+ headers.set('Content-Range', `bytes */${totalSize}`);
+ return new Response(null, {
+ headers,
+ status: 416,
+ statusText: 'Range Not Satisfiable',
+ });
+ }
+
+ const [, startRaw, endRaw] = match;
+ let start = startRaw ? Number(startRaw) : Number.NaN;
+ let end = endRaw ? Number(endRaw) : Number.NaN;
+
+ // Suffix range: bytes=-N (last N bytes)
+ if (!startRaw && endRaw) {
+ const suffixLength = Number(endRaw);
+ if (!Number.isFinite(suffixLength) || suffixLength <= 0) {
+ headers.set('Content-Range', `bytes */${totalSize}`);
+ return new Response(null, {
+ headers,
+ status: 416,
+ statusText: 'Range Not Satisfiable',
+ });
+ }
+ start = Math.max(totalSize - suffixLength, 0);
+ end = totalSize - 1;
+ } else {
+ if (!Number.isFinite(start)) start = 0;
+ if (!Number.isFinite(end)) end = totalSize - 1;
+ }
+
+ if (start < 0 || end < 0 || start > end || start >= totalSize) {
+ headers.set('Content-Range', `bytes */${totalSize}`);
+ return new Response(null, {
+ headers,
+ status: 416,
+ statusText: 'Range Not Satisfiable',
+ });
+ }
+
+ end = Math.min(end, totalSize - 1);
+ const sliced = buffer.subarray(start, end + 1);
+
+ headers.set('Content-Range', `bytes ${start}-${end}/${totalSize}`);
+ headers.set('Content-Length', String(sliced.byteLength));
+
+ if (method === 'HEAD') {
+ return new Response(null, { headers, status: 206, statusText: 'Partial Content' });
+ }
+
+ return new Response(sliced, { headers, status: 206, statusText: 'Partial Content' });
+ }
private isAssetRequest(pathname: string) {
const normalizedPathname = pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;
@@ -249,3 +285,48 @@ export class RendererProtocolManager {
return path.basename(filePath) === '404.html';
}
}
+
+/**
+ * Development fallback: forward the request to the electron-vite dev server.
+ * Non-backend `app://renderer/<path>` requests get round-tripped through the
+ * Vite middleware (HTML rewrites, module transforms, optimized deps) and
+ * returned to the renderer as if served from `app://` directly.
+ *
+ * The HMR WebSocket bypasses this β€” the renderer opens
+ * `ws://localhost:<port>` straight against the dev server (see
+ * `electron.vite.config.ts` `server.hmr.clientPort`).
+ */
+export class ViteRendererFallback implements RendererFallbackStrategy {
+ private readonly viteOrigin: string;
+ private readonly logger = createLogger('core:ViteRendererFallback');
+
+ constructor(viteOrigin: string) {
+ this.viteOrigin = viteOrigin.replace(/\/+$/, '');
+ }
+
+ async handle(request: Request, url: URL): Promise<Response> {
+ const target = `${this.viteOrigin}${url.pathname}${url.search}`;
+
+ // Strip Host so net.fetch derives it from the target URL (otherwise Vite
+ // sees `Host: renderer` and middleware that keys off Host can misbehave).
+ const headers = new Headers(request.headers);
+ headers.delete('host');
+
+ const init: RequestInit & { duplex?: 'half' } = {
+ headers,
+ method: request.method,
+ };
+
+ if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {
+ init.body = request.body;
+ init.duplex = 'half';
+ }
+
+ try {
+ return await net.fetch(target, init);
+ } catch (error) {
+ this.logger.error(`Vite dev server fetch failed: ${target}`, error);
+ return new Response('Vite Dev Server Unavailable', { status: 502 });
+ }
+ }
+}
diff --git a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
index 7b5990afb2e..a4d930197ee 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
@@ -7,7 +7,12 @@ import { isDev } from '@/const/env';
import { getDesktopEnv } from '@/env';
import { createLogger } from '@/utils/logger';
-import { RendererProtocolManager } from './RendererProtocolManager';
+import {
+ RendererProtocolManager,
+ type RendererRequestInterceptor,
+ StaticRendererFallback,
+ ViteRendererFallback,
+} from './RendererProtocolManager';
const logger = createLogger('core:RendererUrlManager');
@@ -20,12 +25,11 @@ const POPUP_ENTRY_HTML = path.join(rendererDir, 'apps', 'desktop', 'popup.html')
export class RendererUrlManager {
private readonly rendererProtocolManager: RendererProtocolManager;
private readonly rendererStaticOverride = getDesktopEnv().DESKTOP_RENDERER_STATIC;
- private rendererLoadedUrl: string;
+ private readonly rendererLoadedUrl: string;
constructor() {
this.rendererProtocolManager = new RendererProtocolManager({
- rendererDir,
- resolveRendererFilePath: this.resolveRendererFilePath,
+ fallback: this.pickFallback(),
});
this.rendererLoadedUrl = this.rendererProtocolManager.getRendererUrl();
@@ -35,31 +39,22 @@ export class RendererUrlManager {
return this.rendererProtocolManager.protocolScheme;
}
+ addRequestInterceptor(interceptor: RendererRequestInterceptor) {
+ this.rendererProtocolManager.addRequestInterceptor(interceptor);
+ }
+
/**
- * Configure renderer loading strategy for dev/prod
+ * Register the `app://` protocol handler. Idempotent β€” safe to call after
+ * interceptors are wired.
*/
configureRendererLoader() {
- const electronRendererUrl = process.env['ELECTRON_RENDERER_URL'];
-
- if (isDev && !this.rendererStaticOverride && electronRendererUrl) {
- this.rendererLoadedUrl = electronRendererUrl;
- this.setupDevRenderer();
- return;
- }
-
- if (isDev && !this.rendererStaticOverride && !electronRendererUrl) {
- logger.warn('Dev mode: ELECTRON_RENDERER_URL not set, falling back to protocol handler');
- }
-
- if (isDev && this.rendererStaticOverride) {
- logger.warn('Dev mode: DESKTOP_RENDERER_STATIC enabled, using static renderer handler');
- }
-
- this.setupProdRenderer();
+ this.rendererProtocolManager.registerHandler();
}
/**
- * Build renderer URL for dev/prod.
+ * Build a renderer URL. Always uses `app://renderer` so dev and prod share
+ * the same origin (cookies, storage, service-workers). Dev requests are
+ * proxied to the Vite dev server inside the `app://` handler.
*/
buildRendererUrl(path: string): string {
const cleanPath = path.startsWith('/') ? path : `/${path}`;
@@ -69,7 +64,10 @@ export class RendererUrlManager {
}
/**
- * Resolve renderer file path in production.
+ * Resolve a renderer file path against the static export. Used by the
+ * production fallback; left on the manager so the desktop-specific entry
+ * HTML mappings stay in one place.
+ *
* Static assets map directly; /overlay routes fall back to overlay.html;
* popup routes go to popup.html; all other routes fall back to index.html (SPA).
*/
@@ -96,20 +94,26 @@ export class RendererUrlManager {
return SPA_ENTRY_HTML;
};
- /**
- * Development: use electron-vite renderer dev server
- */
- private setupDevRenderer() {
- logger.info(
- `Development mode: renderer served from electron-vite dev server at ${this.rendererLoadedUrl}`,
- );
- }
+ private pickFallback() {
+ const electronRendererUrl = process.env['ELECTRON_RENDERER_URL'];
- /**
- * Production: serve static renderer assets via protocol handler
- */
- private setupProdRenderer() {
- this.rendererLoadedUrl = this.rendererProtocolManager.getRendererUrl();
- this.rendererProtocolManager.registerHandler();
+ if (isDev && !this.rendererStaticOverride && electronRendererUrl) {
+ logger.info(
+ `Development mode: app:// requests proxied to Vite dev server at ${electronRendererUrl}`,
+ );
+ return new ViteRendererFallback(electronRendererUrl);
+ }
+
+ if (isDev && !this.rendererStaticOverride && !electronRendererUrl) {
+ logger.warn(
+ 'Dev mode: ELECTRON_RENDERER_URL not set, falling back to static renderer handler',
+ );
+ }
+
+ if (isDev && this.rendererStaticOverride) {
+ logger.warn('Dev mode: DESKTOP_RENDERER_STATIC enabled, using static renderer handler');
+ }
+
+ return new StaticRendererFallback(rendererDir, this.resolveRendererFilePath);
}
}
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 f51d3629fde..caebffd1a47 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
@@ -1,5 +1,5 @@
import { AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
-import { BrowserWindow } from 'electron';
+import { BrowserWindow, session as electronSession } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BackendProxyProtocolManager } from '../BackendProxyProtocolManager';
@@ -10,19 +10,6 @@ interface RequestInitWithDuplex extends RequestInit {
type FetchMock = (input: RequestInfo | URL, init?: RequestInitWithDuplex) => Promise<Response>;
-const { mockProtocol, protocolHandlerRef } = vi.hoisted(() => {
- const protocolHandlerRef = { current: null as any };
-
- return {
- mockProtocol: {
- handle: vi.fn((_scheme: string, handler: any) => {
- protocolHandlerRef.current = handler;
- }),
- },
- protocolHandlerRef,
- };
-});
-
vi.mock('electron-is', () => ({
dev: vi.fn(() => false),
macOS: vi.fn(() => false),
@@ -48,21 +35,23 @@ vi.mock('electron', () => ({
global.fetch(input as any, init as any),
),
},
+ session: {
+ defaultSession: {},
+ },
}));
describe('BackendProxyProtocolManager', () => {
beforeEach(() => {
vi.clearAllMocks();
- protocolHandlerRef.current = null;
});
afterEach(() => {
vi.useRealTimers();
});
- it('should rewrite url to remote base and inject Oidc-Auth token', async () => {
+ it('rewrites url to remote base and injects Oidc-Auth via proxy()', async () => {
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const fetchMock = vi.fn<FetchMock>(async () => {
return new Response('ok', {
@@ -76,19 +65,19 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => 'token-123',
getRemoteBaseUrl: async () => 'https://remote.example.com',
- scheme: 'lobe-backend',
source: 'main',
});
- const handler = protocolHandlerRef.current;
- expect(mockProtocol.handle).toHaveBeenCalledWith('lobe-backend', expect.any(Function));
-
- const response = await handler({
- headers: new Headers({ 'Origin': 'app://desktop', 'X-Test': '1' }),
- method: 'GET',
- url: 'lobe-backend://app/trpc/hello?batch=1',
- } as any);
+ const response = await manager.proxy(
+ {
+ headers: new Headers({ 'Origin': 'app://renderer', 'X-Test': '1' }),
+ method: 'GET',
+ url: 'app://renderer/trpc/hello?batch=1',
+ } as any,
+ session,
+ );
+ expect(response).not.toBeNull();
expect(fetchMock).toHaveBeenCalledTimes(1);
const [calledUrl, init] = fetchMock.mock.calls[0]!;
expect(calledUrl).toBe('https://remote.example.com/trpc/hello?batch=1');
@@ -100,16 +89,18 @@ describe('BackendProxyProtocolManager', () => {
expect(headers.get('Oidc-Auth')).toBe('token-123');
expect(headers.get('X-Test')).toBe('1');
- expect(response.status).toBe(200);
- expect(response.headers.get('X-Src-Url')).toBe('https://remote.example.com/trpc/hello?batch=1');
- expect(response.headers.get('Access-Control-Allow-Origin')).toBe('app://desktop');
- expect(response.headers.get('Access-Control-Allow-Credentials')).toBe('true');
- expect(await response.text()).toBe('ok');
+ expect(response!.status).toBe(200);
+ expect(response!.headers.get('X-Src-Url')).toBe(
+ 'https://remote.example.com/trpc/hello?batch=1',
+ );
+ expect(response!.headers.get('Access-Control-Allow-Origin')).toBe('app://renderer');
+ expect(response!.headers.get('Access-Control-Allow-Credentials')).toBe('true');
+ expect(await response!.text()).toBe('ok');
});
- it('should forward body and set duplex for non-GET requests', async () => {
+ it('forwards body and sets duplex for non-GET requests', async () => {
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const fetchMock = vi.fn<FetchMock>(async () => new Response('ok', { status: 200 }));
vi.stubGlobal('fetch', fetchMock as any);
@@ -117,18 +108,18 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => null,
getRemoteBaseUrl: async () => 'https://remote.example.com',
- scheme: 'lobe-backend',
});
- const handler = protocolHandlerRef.current;
-
- await handler({
- headers: new Headers(),
- method: 'POST',
- // body doesn't have to be a real stream for this unit test; manager only checks truthiness
- body: 'payload' as any,
- url: 'lobe-backend://app/api/upload',
- } as any);
+ await manager.proxy(
+ {
+ headers: new Headers(),
+ method: 'POST',
+ // body doesn't have to be a real stream for this unit test; manager only checks truthiness
+ body: 'payload' as any,
+ url: 'app://renderer/api/upload',
+ } as any,
+ session,
+ );
const [, init] = fetchMock.mock.calls[0]!;
expect(init).toBeDefined();
@@ -139,9 +130,9 @@ describe('BackendProxyProtocolManager', () => {
expect(init.duplex).toBe('half');
});
- it('should return null when remote base url is missing', async () => {
+ it('returns null when remote base url is missing', async () => {
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock as any);
@@ -149,19 +140,20 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => 'token',
getRemoteBaseUrl: async () => null,
- scheme: 'lobe-backend',
});
- const handler = protocolHandlerRef.current;
- const res = await handler({ method: 'GET', url: 'lobe-backend://app/trpc' } as any);
+ const res = await manager.proxy(
+ { method: 'GET', headers: new Headers(), url: 'app://renderer/trpc' } as any,
+ session,
+ );
expect(res).toBeNull();
expect(fetchMock).not.toHaveBeenCalled();
});
- it('should return null when request url is already the remote origin', async () => {
+ it('returns null when request url is already the remote origin', async () => {
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock as any);
@@ -169,22 +161,24 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => null,
getRemoteBaseUrl: async () => 'https://remote.example.com',
- scheme: 'lobe-backend',
});
- const handler = protocolHandlerRef.current;
- const res = await handler({
- method: 'GET',
- url: 'https://remote.example.com/trpc/hello?x=1',
- } as any);
+ const res = await manager.proxy(
+ {
+ method: 'GET',
+ headers: new Headers(),
+ url: 'https://remote.example.com/trpc/hello?x=1',
+ } as any,
+ session,
+ );
expect(res).toBeNull();
expect(fetchMock).not.toHaveBeenCalled();
});
- it('should return null when rewrite fails (invalid remote base url)', async () => {
+ it('returns null when rewrite fails (invalid remote base url)', async () => {
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock as any);
@@ -192,19 +186,20 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => null,
getRemoteBaseUrl: async () => 'not-a-url',
- scheme: 'lobe-backend',
});
- const handler = protocolHandlerRef.current;
- const res = await handler({ method: 'GET', url: 'lobe-backend://app/trpc' } as any);
+ const res = await manager.proxy(
+ { method: 'GET', headers: new Headers(), url: 'app://renderer/trpc' } as any,
+ session,
+ );
expect(res).toBeNull();
expect(fetchMock).not.toHaveBeenCalled();
});
- it('should throw when upstream fetch throws', async () => {
+ it('throws when upstream fetch throws', async () => {
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const fetchMock = vi.fn(async () => {
throw new Error('network down');
@@ -214,20 +209,21 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => null,
getRemoteBaseUrl: async () => 'https://remote.example.com',
- scheme: 'lobe-backend',
});
- const handler = protocolHandlerRef.current;
await expect(
- handler({
- headers: new Headers(),
- method: 'GET',
- url: 'lobe-backend://app/trpc/hello',
- } as any),
+ manager.proxy(
+ {
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/trpc/hello',
+ } as any,
+ session,
+ ),
).rejects.toThrow('network down');
});
- it('should broadcast authorizationRequired when X-Auth-Required is set on HTTP 207 (batched tRPC)', async () => {
+ it('broadcasts authorizationRequired when X-Auth-Required is set on HTTP 207 (batched tRPC)', async () => {
vi.useFakeTimers();
const send = vi.fn();
vi.mocked(BrowserWindow.getAllWindows).mockReturnValue([
@@ -235,7 +231,7 @@ describe('BackendProxyProtocolManager', () => {
] as any);
const manager = new BackendProxyProtocolManager();
- const session = { protocol: mockProtocol } as any;
+ const session = {} as any;
const headers = new Headers({
[AUTH_REQUIRED_HEADER]: 'true',
@@ -249,18 +245,77 @@ describe('BackendProxyProtocolManager', () => {
manager.registerWithRemoteBaseUrl(session, {
getAccessToken: async () => null,
getRemoteBaseUrl: async () => 'https://remote.example.com',
- scheme: 'lobe-backend',
});
- const handler = protocolHandlerRef.current;
- await handler({
- headers: new Headers(),
- method: 'GET',
- url: 'lobe-backend://app/trpc/lambda/batch?batch=1',
- } as any);
+ await manager.proxy(
+ {
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/trpc/lambda/batch?batch=1',
+ } as any,
+ session,
+ );
expect(send).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1000);
expect(send).toHaveBeenCalledWith('authorizationRequired');
});
+
+ describe('createAppRequestInterceptor', () => {
+ it('returns null for non-backend paths', async () => {
+ const manager = new BackendProxyProtocolManager();
+ const interceptor = manager.createAppRequestInterceptor();
+
+ const res = await interceptor({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/settings',
+ } as any);
+
+ expect(res).toBeNull();
+ });
+
+ it('returns 502 for backend paths when default session has no context', async () => {
+ // electronSession.defaultSession is the empty {} mock; no register() was called.
+ void electronSession.defaultSession;
+
+ const manager = new BackendProxyProtocolManager();
+ 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);
+ });
+
+ it('proxies backend paths through the registered default-session context', async () => {
+ const fetchMock = vi.fn<FetchMock>(async () => new Response('proxied', { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock as any);
+
+ const manager = new BackendProxyProtocolManager();
+ manager.registerWithRemoteBaseUrl(electronSession.defaultSession as any, {
+ getAccessToken: async () => null,
+ getRemoteBaseUrl: async () => 'https://remote.example.com',
+ });
+
+ const interceptor = manager.createAppRequestInterceptor();
+ const res = await interceptor({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/trpc/hello?batch=1',
+ } as any);
+
+ expect(res).not.toBeNull();
+ expect(res!.status).toBe(200);
+ expect(await res!.text()).toBe('proxied');
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://remote.example.com/trpc/hello?batch=1',
+ expect.objectContaining({ method: 'GET' }),
+ );
+ });
+ });
});
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts
index 4a04731a5f0..77f2e90df38 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts
@@ -1,30 +1,45 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { RendererProtocolManager } from '../RendererProtocolManager';
-
-const { mockApp, mockPathExistsSync, mockProtocol, mockReadFile, mockStat, protocolHandlerRef } =
- vi.hoisted(() => {
- const protocolHandlerRef = { current: null as any };
-
- return {
- mockApp: {
- isReady: vi.fn().mockReturnValue(true),
- whenReady: vi.fn().mockResolvedValue(undefined),
- },
- mockPathExistsSync: vi.fn().mockReturnValue(true),
- mockProtocol: {
- handle: vi.fn((_scheme: string, handler: any) => {
- protocolHandlerRef.current = handler;
- }),
- },
- mockReadFile: vi.fn(),
- mockStat: vi.fn(),
- protocolHandlerRef,
- };
- });
+import {
+ RendererProtocolManager,
+ StaticRendererFallback,
+ ViteRendererFallback,
+} from '../RendererProtocolManager';
+
+const {
+ mockApp,
+ mockNetFetch,
+ mockPathExistsSync,
+ mockProtocol,
+ mockReadFile,
+ mockStat,
+ protocolHandlerRef,
+} = vi.hoisted(() => {
+ const protocolHandlerRef = { current: null as any };
+
+ return {
+ mockApp: {
+ isReady: vi.fn().mockReturnValue(true),
+ whenReady: vi.fn().mockResolvedValue(undefined),
+ },
+ mockNetFetch: vi.fn(),
+ mockPathExistsSync: vi.fn().mockReturnValue(true),
+ mockProtocol: {
+ handle: vi.fn((_scheme: string, handler: any) => {
+ protocolHandlerRef.current = handler;
+ }),
+ },
+ mockReadFile: vi.fn(),
+ mockStat: vi.fn(),
+ protocolHandlerRef,
+ };
+});
vi.mock('electron', () => ({
app: mockApp,
+ net: {
+ fetch: mockNetFetch,
+ },
protocol: mockProtocol,
}));
@@ -46,7 +61,7 @@ vi.mock('@/utils/logger', () => ({
}),
}));
-describe('RendererProtocolManager', () => {
+describe('RendererProtocolManager + StaticRendererFallback', () => {
beforeEach(() => {
vi.clearAllMocks();
protocolHandlerRef.current = null;
@@ -59,7 +74,14 @@ describe('RendererProtocolManager', () => {
protocolHandlerRef.current = null;
});
- it('should fall back to entry HTML when resolve returns 404.html for non-asset routes', async () => {
+ const buildStaticManager = (resolve: (url: URL) => Promise<string | null>) => {
+ const fallback = new StaticRendererFallback('/export', resolve);
+ const manager = new RendererProtocolManager({ fallback });
+ manager.registerHandler();
+ return manager;
+ };
+
+ it('falls back to entry HTML when resolve returns 404.html for non-asset routes', async () => {
const resolveRendererFilePath = vi.fn(async (url: URL) => {
if (url.pathname === '/missing') return '/export/404.html';
if (url.pathname === '/') return '/export/index.html';
@@ -67,12 +89,7 @@ describe('RendererProtocolManager', () => {
});
mockReadFile.mockImplementation(async (path: string) => Buffer.from(`content:${path}`));
- const manager = new RendererProtocolManager({
- rendererDir: '/export',
- resolveRendererFilePath,
- });
-
- manager.registerHandler();
+ buildStaticManager(resolveRendererFilePath);
expect(mockProtocol.handle).toHaveBeenCalled();
const handler = protocolHandlerRef.current;
@@ -92,7 +109,7 @@ describe('RendererProtocolManager', () => {
expect(response.status).toBe(200);
});
- it('should serve 404.html when explicitly requested', async () => {
+ it('serves 404.html when explicitly requested', async () => {
const resolveRendererFilePath = vi.fn(async (url: URL) => {
if (url.pathname === '/404.html') return '/export/404.html';
if (url.pathname === '/') return '/export/index.html';
@@ -100,12 +117,7 @@ describe('RendererProtocolManager', () => {
});
mockReadFile.mockImplementation(async (path: string) => Buffer.from(`content:${path}`));
- const manager = new RendererProtocolManager({
- rendererDir: '/export',
- resolveRendererFilePath,
- });
-
- manager.registerHandler();
+ buildStaticManager(resolveRendererFilePath);
const handler = protocolHandlerRef.current;
const response = await handler({
@@ -119,36 +131,30 @@ describe('RendererProtocolManager', () => {
expect(response.status).toBe(200);
});
- it('should return 404 for missing asset requests without fallback', async () => {
+ it('returns 404 for missing asset requests without fallback', async () => {
const resolveRendererFilePath = vi.fn(async (_url: URL) => null);
- const manager = new RendererProtocolManager({
- rendererDir: '/export',
- resolveRendererFilePath,
- });
-
- manager.registerHandler();
+ buildStaticManager(resolveRendererFilePath);
const handler = protocolHandlerRef.current;
- const response = await handler({ url: 'app://renderer/logo.png' } as any);
+ const response = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/logo.png',
+ } as any);
expect(resolveRendererFilePath).toHaveBeenCalledTimes(1);
expect(response.status).toBe(404);
});
- it('should support Range requests for media assets', async () => {
+ it('supports Range requests for media assets', async () => {
const resolveRendererFilePath = vi.fn(async (_url: URL) => '/export/intro-video.mp4');
const payload = Buffer.from('0123456789');
mockStat.mockImplementation(async () => ({ size: payload.length }));
mockReadFile.mockImplementation(async () => payload);
- const manager = new RendererProtocolManager({
- rendererDir: '/export',
- resolveRendererFilePath,
- });
-
- manager.registerHandler();
+ buildStaticManager(resolveRendererFilePath);
const handler = protocolHandlerRef.current;
const response = await handler({
@@ -166,4 +172,126 @@ describe('RendererProtocolManager', () => {
const buf = Buffer.from(await response.arrayBuffer());
expect(buf.toString()).toBe('01');
});
+
+ it('runs interceptors before the fallback and short-circuits on first non-null Response', async () => {
+ const resolveRendererFilePath = vi.fn(async () => '/export/index.html');
+ mockReadFile.mockImplementation(async () => Buffer.from('static'));
+
+ const fallback = new StaticRendererFallback('/export', resolveRendererFilePath);
+ const manager = new RendererProtocolManager({ fallback });
+
+ manager.addRequestInterceptor(async () => null);
+ manager.addRequestInterceptor(async (request) =>
+ new URL(request.url).pathname === '/trpc/hello'
+ ? new Response('intercepted', { status: 200 })
+ : null,
+ );
+
+ manager.registerHandler();
+ const handler = protocolHandlerRef.current;
+
+ const intercepted = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/trpc/hello',
+ } as any);
+ expect(intercepted.status).toBe(200);
+ expect(await intercepted.text()).toBe('intercepted');
+ expect(resolveRendererFilePath).not.toHaveBeenCalled();
+
+ const fallthrough = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/anything',
+ } as any);
+ expect(fallthrough.status).toBe(200);
+ expect(await fallthrough.text()).toBe('static');
+ });
+
+ it('returns 404 for cross-host requests', async () => {
+ const resolveRendererFilePath = vi.fn(async () => '/export/index.html');
+ buildStaticManager(resolveRendererFilePath);
+ const handler = protocolHandlerRef.current;
+
+ const response = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://elsewhere/index.html',
+ } as any);
+
+ expect(response.status).toBe(404);
+ expect(resolveRendererFilePath).not.toHaveBeenCalled();
+ });
+});
+
+describe('ViteRendererFallback', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ protocolHandlerRef.current = null;
+ mockApp.isReady.mockReturnValue(true);
+ });
+
+ it('forwards GET requests to the Vite origin preserving pathname + search', async () => {
+ mockNetFetch.mockResolvedValue(new Response('vite-served', { status: 200 }));
+
+ const fallback = new ViteRendererFallback('http://localhost:5173');
+ const manager = new RendererProtocolManager({ fallback });
+ manager.registerHandler();
+ const handler = protocolHandlerRef.current;
+
+ const response = await handler({
+ headers: new Headers({ Accept: 'text/html' }),
+ method: 'GET',
+ url: 'app://renderer/src/main.tsx?t=12345',
+ } as any);
+
+ expect(mockNetFetch).toHaveBeenCalledTimes(1);
+ const [target, init] = mockNetFetch.mock.calls[0]!;
+ expect(target).toBe('http://localhost:5173/src/main.tsx?t=12345');
+ expect((init as RequestInit).method).toBe('GET');
+ const headers = (init as RequestInit).headers as Headers;
+ expect(headers.get('Accept')).toBe('text/html');
+ expect(headers.get('Host')).toBeNull();
+
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe('vite-served');
+ });
+
+ it('forwards body and sets duplex for non-GET requests', async () => {
+ mockNetFetch.mockResolvedValue(new Response('ok', { status: 200 }));
+
+ const fallback = new ViteRendererFallback('http://localhost:5173/');
+ const manager = new RendererProtocolManager({ fallback });
+ manager.registerHandler();
+ const handler = protocolHandlerRef.current;
+
+ await handler({
+ headers: new Headers(),
+ method: 'POST',
+ body: 'payload' as any,
+ url: 'app://renderer/__hmr',
+ } as any);
+
+ const [target, init] = mockNetFetch.mock.calls[0]!;
+ expect(target).toBe('http://localhost:5173/__hmr');
+ expect((init as RequestInit & { duplex?: string }).duplex).toBe('half');
+ expect((init as any).body).toBe('payload');
+ });
+
+ it('returns 502 when net.fetch throws', async () => {
+ mockNetFetch.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ const fallback = new ViteRendererFallback('http://localhost:5173');
+ const manager = new RendererProtocolManager({ fallback });
+ manager.registerHandler();
+ const handler = protocolHandlerRef.current;
+
+ const response = await handler({
+ headers: new Headers(),
+ method: 'GET',
+ url: 'app://renderer/@vite/client',
+ } as any);
+
+ expect(response.status).toBe(502);
+ });
});
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts
index 75fb86f49ad..440b279f3ef 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts
@@ -1,14 +1,18 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mockPathExistsSync = vi.fn();
+const mockProtocolHandle = vi.fn();
vi.mock('electron', () => ({
app: {
isReady: vi.fn(() => true),
whenReady: vi.fn(() => Promise.resolve()),
},
+ net: {
+ fetch: vi.fn(),
+ },
protocol: {
- handle: vi.fn(),
+ handle: mockProtocolHandle,
},
}));
@@ -45,6 +49,7 @@ describe('RendererUrlManager', () => {
beforeEach(() => {
vi.clearAllMocks();
mockPathExistsSync.mockReset();
+ mockProtocolHandle.mockReset();
mockIsDev = false;
delete process.env['ELECTRON_RENDERER_URL'];
});
@@ -79,43 +84,60 @@ describe('RendererUrlManager', () => {
});
});
- describe('configureRendererLoader (dev mode)', () => {
- it('should use ELECTRON_RENDERER_URL when available in dev mode', async () => {
+ describe('buildRendererUrl', () => {
+ it('always returns app://renderer regardless of dev/prod', async () => {
+ const { RendererUrlManager } = await import('../RendererUrlManager');
+ const prodManager = new RendererUrlManager();
+ expect(prodManager.buildRendererUrl('/')).toBe('app://renderer/');
+ expect(prodManager.buildRendererUrl('/settings')).toBe('app://renderer/settings');
+
mockIsDev = true;
process.env['ELECTRON_RENDERER_URL'] = 'http://localhost:5173';
+ const devManager = new RendererUrlManager();
+ expect(devManager.buildRendererUrl('/')).toBe('app://renderer/');
+ expect(devManager.buildRendererUrl('/settings')).toBe('app://renderer/settings');
+ });
+
+ it('prefixes a slash when the input lacks one', async () => {
+ const { RendererUrlManager } = await import('../RendererUrlManager');
+ const manager = new RendererUrlManager();
+ expect(manager.buildRendererUrl('settings')).toBe('app://renderer/settings');
+ });
+ });
+ describe('configureRendererLoader', () => {
+ it('registers the app:// protocol handler in prod', async () => {
+ mockIsDev = false;
const { RendererUrlManager } = await import('../RendererUrlManager');
const manager = new RendererUrlManager();
manager.configureRendererLoader();
- expect(manager.buildRendererUrl('/')).toBe('http://localhost:5173/');
- expect(manager.buildRendererUrl('/settings')).toBe('http://localhost:5173/settings');
+ expect(mockProtocolHandle).toHaveBeenCalledTimes(1);
+ expect(mockProtocolHandle.mock.calls[0][0]).toBe('app');
});
- it('should normalize trailing slashes from ELECTRON_RENDERER_URL', async () => {
+ it('registers the app:// protocol handler in dev (Vite fallback)', async () => {
mockIsDev = true;
- process.env['ELECTRON_RENDERER_URL'] = 'http://localhost:5173/';
+ process.env['ELECTRON_RENDERER_URL'] = 'http://localhost:5173';
const { RendererUrlManager } = await import('../RendererUrlManager');
const manager = new RendererUrlManager();
manager.configureRendererLoader();
- expect(manager.buildRendererUrl('/')).toBe('http://localhost:5173/');
- expect(manager.buildRendererUrl('/overlay')).toBe('http://localhost:5173/overlay');
+ expect(mockProtocolHandle).toHaveBeenCalledTimes(1);
+ expect(mockProtocolHandle.mock.calls[0][0]).toBe('app');
});
- it('should fall back to protocol handler when ELECTRON_RENDERER_URL is not set', async () => {
+ it('still registers in dev when ELECTRON_RENDERER_URL is missing (static fallback)', async () => {
mockIsDev = true;
-
const { RendererUrlManager } = await import('../RendererUrlManager');
const manager = new RendererUrlManager();
- mockPathExistsSync.mockReturnValue(true);
manager.configureRendererLoader();
- expect(manager.buildRendererUrl('/')).toBe('app://renderer/');
+ expect(mockProtocolHandle).toHaveBeenCalledTimes(1);
});
- it('should use protocol handler when DESKTOP_RENDERER_STATIC is enabled regardless of ELECTRON_RENDERER_URL', async () => {
+ it('uses static fallback when DESKTOP_RENDERER_STATIC overrides ELECTRON_RENDERER_URL', async () => {
mockIsDev = true;
process.env['ELECTRON_RENDERER_URL'] = 'http://localhost:5173';
@@ -124,10 +146,10 @@ describe('RendererUrlManager', () => {
const { RendererUrlManager } = await import('../RendererUrlManager');
const manager = new RendererUrlManager();
- mockPathExistsSync.mockReturnValue(true);
manager.configureRendererLoader();
expect(manager.buildRendererUrl('/')).toBe('app://renderer/');
+ expect(mockProtocolHandle).toHaveBeenCalledTimes(1);
});
});
});
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index fe0f948bd57..49a6ab3d6ff 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -1,3 +1,5 @@
+import './pre-app-init';
+
import fixPath from 'fix-path';
import { App } from './core/App';
diff --git a/apps/desktop/src/main/pre-app-init.ts b/apps/desktop/src/main/pre-app-init.ts
new file mode 100644
index 00000000000..7880afa2e8e
--- /dev/null
+++ b/apps/desktop/src/main/pre-app-init.ts
@@ -0,0 +1,15 @@
+import path from 'node:path';
+
+import { app } from 'electron';
+import * as electronIs from 'electron-is';
+
+// Must run BEFORE any module captures `app.getPath('userData')` (e.g. `@/const/dir`
+// reads it at top level). Once a path is read, `setName` / `setPath` no-op for it.
+//
+// Dev now uses the same `app://renderer/` origin as prod, so localStorage / cookies /
+// IndexedDB would collide if both shared the packaged-app's userData dir. Pin dev to
+// a sibling directory so prod sessions stay clean.
+if (electronIs.dev()) {
+ app.setName('lobehub-desktop-dev');
+ app.setPath('userData', path.join(app.getPath('appData'), 'lobehub-desktop-dev'));
+}
diff --git a/packages/const/src/protocol.ts b/packages/const/src/protocol.ts
index e3b1712b644..bb1f8d6a893 100644
--- a/packages/const/src/protocol.ts
+++ b/packages/const/src/protocol.ts
@@ -1,11 +1,3 @@
-import { isDesktop } from './version';
-
-export const ELECTRON_BE_PROTOCOL_SCHEME = 'lobe-backend';
-
-export const withElectronProtocolIfElectron = (url: string) => {
- return isDesktop ? `${ELECTRON_BE_PROTOCOL_SCHEME}://lobe${url}` : url;
-};
-
/**
* Custom protocol the desktop main process exposes for serving approved
* local workspace file previews to the renderer.
diff --git a/src/libs/trpc/client/async.ts b/src/libs/trpc/client/async.ts
index 642708f4de9..13942ceadf0 100644
--- a/src/libs/trpc/client/async.ts
+++ b/src/libs/trpc/client/async.ts
@@ -1,7 +1,6 @@
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import superjson from 'superjson';
-import { withElectronProtocolIfElectron } from '@/const/protocol';
import { type AsyncRouter } from '@/server/routers/async';
export const asyncClient = createTRPCClient<AsyncRouter>({
@@ -9,7 +8,7 @@ export const asyncClient = createTRPCClient<AsyncRouter>({
httpBatchLink({
maxURLLength: 2083,
transformer: superjson,
- url: withElectronProtocolIfElectron('/trpc/async'),
+ url: '/trpc/async',
}),
],
});
diff --git a/src/libs/trpc/client/lambda.ts b/src/libs/trpc/client/lambda.ts
index b3e9dc87729..d8555573f8d 100644
--- a/src/libs/trpc/client/lambda.ts
+++ b/src/libs/trpc/client/lambda.ts
@@ -6,7 +6,6 @@ import debug from 'debug';
import { type ModelProvider } from 'model-bank';
import superjson from 'superjson';
-import { withElectronProtocolIfElectron } from '@/const/protocol';
import { isDesktop } from '@/const/version';
import { type LambdaRouter } from '@/server/routers/lambda';
@@ -98,19 +97,7 @@ const errorHandlingLink: TRPCLink<LambdaRouter> = () => {
const linkOptions = {
fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
// Ensure credentials are included to send cookies (like mp_token)
-
- const fetchOptions: RequestInit = {
- ...init,
- credentials: 'include',
- };
-
- if (isDesktop) {
- const res = await fetch(input as string, fetchOptions);
-
- if (res) return res;
- }
-
- return await fetch(input, fetchOptions);
+ return fetch(input, { ...init, credentials: 'include' });
},
headers: async () => {
// dynamic import to avoid circular dependency
@@ -134,7 +121,7 @@ const linkOptions = {
return headers;
},
transformer: superjson,
- url: withElectronProtocolIfElectron('/trpc/lambda'),
+ url: '/trpc/lambda',
};
// Procedures that should skip batching for faster initial load
diff --git a/src/libs/trpc/client/tools.ts b/src/libs/trpc/client/tools.ts
index e73d1657982..31006a8fc83 100644
--- a/src/libs/trpc/client/tools.ts
+++ b/src/libs/trpc/client/tools.ts
@@ -2,7 +2,6 @@ import { createTRPCClient, httpBatchLink, type TRPCLink } from '@trpc/client';
import { observable } from '@trpc/server/observable';
import superjson from 'superjson';
-import { withElectronProtocolIfElectron } from '@/const/protocol';
import { type ToolsRouter } from '@/server/routers/tools';
// 401 error debouncing for market auth
@@ -62,7 +61,7 @@ export const toolsClient = createTRPCClient<ToolsRouter>({
},
maxURLLength: 2083,
transformer: superjson,
- url: withElectronProtocolIfElectron('/trpc/tools'),
+ url: '/trpc/tools',
}),
],
});
diff --git a/src/services/_url.ts b/src/services/_url.ts
index 5f17a4e12df..8a33d58aad4 100644
--- a/src/services/_url.ts
+++ b/src/services/_url.ts
@@ -1,26 +1,23 @@
-import { withElectronProtocolIfElectron } from '@/const/protocol';
-
export const API_ENDPOINTS = {
- oauth: withElectronProtocolIfElectron('/api/auth'),
+ oauth: '/api/auth',
// trace
- trace: withElectronProtocolIfElectron('/webapi/trace'),
+ trace: '/webapi/trace',
// chat
- chat: (provider: string) => withElectronProtocolIfElectron(`/webapi/chat/${provider}`),
+ chat: (provider: string) => `/webapi/chat/${provider}`,
// models
- models: (provider: string) => withElectronProtocolIfElectron(`/webapi/models/${provider}`),
- modelPull: (provider: string) =>
- withElectronProtocolIfElectron(`/webapi/models/${provider}/pull`),
+ models: (provider: string) => `/webapi/models/${provider}`,
+ modelPull: (provider: string) => `/webapi/models/${provider}/pull`,
// STT
- stt: withElectronProtocolIfElectron('/webapi/stt/openai'),
+ stt: '/webapi/stt/openai',
// TTS
- tts: (provider: string) => withElectronProtocolIfElectron(`/webapi/tts/${provider}`),
- edge: withElectronProtocolIfElectron('/webapi/tts/edge'),
- microsoft: withElectronProtocolIfElectron('/webapi/tts/microsoft'),
+ tts: (provider: string) => `/webapi/tts/${provider}`,
+ edge: '/webapi/tts/edge',
+ microsoft: '/webapi/tts/microsoft',
};
export const MARKET_OIDC_ENDPOINTS = {
@@ -28,70 +25,54 @@ export const MARKET_OIDC_ENDPOINTS = {
// so it must always be an HTTP(S) path joined with `NEXT_PUBLIC_MARKET_BASE_URL`.
// It MUST NOT be wrapped by the Electron backend protocol.
auth: '/lobehub-oidc/auth',
- token: withElectronProtocolIfElectron('/market/oidc/token'),
- userinfo: withElectronProtocolIfElectron('/market/oidc/userinfo'),
- handoff: withElectronProtocolIfElectron('/market/oidc/handoff'),
+ token: '/market/oidc/token',
+ userinfo: '/market/oidc/userinfo',
+ handoff: '/market/oidc/handoff',
// Same as `auth`: used as `redirect_uri` (must be a real web URL under market base).
desktopCallback: '/lobehub-oidc/callback/desktop',
};
export const MARKET_ENDPOINTS = {
- base: withElectronProtocolIfElectron('/market'),
+ base: '/market',
// Agent management
- createAgent: withElectronProtocolIfElectron('/market/agent/create'),
- getAgentDetail: (identifier: string) =>
- withElectronProtocolIfElectron(`/market/agent/${encodeURIComponent(identifier)}`),
- getOwnAgents: withElectronProtocolIfElectron('/market/agent/own'),
- createAgentVersion: withElectronProtocolIfElectron('/market/agent/versions/create'),
+ createAgent: '/market/agent/create',
+ getAgentDetail: (identifier: string) => `/market/agent/${encodeURIComponent(identifier)}`,
+ getOwnAgents: '/market/agent/own',
+ createAgentVersion: '/market/agent/versions/create',
// Agent status management
- publishAgent: (identifier: string) =>
- withElectronProtocolIfElectron(`/market/agent/${encodeURIComponent(identifier)}/publish`),
+ publishAgent: (identifier: string) => `/market/agent/${encodeURIComponent(identifier)}/publish`,
unpublishAgent: (identifier: string) =>
- withElectronProtocolIfElectron(`/market/agent/${encodeURIComponent(identifier)}/unpublish`),
+ `/market/agent/${encodeURIComponent(identifier)}/unpublish`,
deprecateAgent: (identifier: string) =>
- withElectronProtocolIfElectron(`/market/agent/${encodeURIComponent(identifier)}/deprecate`),
+ `/market/agent/${encodeURIComponent(identifier)}/deprecate`,
// User profile
- getUserProfile: (username: string) =>
- withElectronProtocolIfElectron(`/market/user/${encodeURIComponent(username)}`),
- updateUserProfile: withElectronProtocolIfElectron('/market/user/me'),
+ getUserProfile: (username: string) => `/market/user/${encodeURIComponent(username)}`,
+ updateUserProfile: '/market/user/me',
// Social - Follow
- follow: withElectronProtocolIfElectron('/market/social/follow'),
- unfollow: withElectronProtocolIfElectron('/market/social/unfollow'),
- followStatus: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/follow-status/${userId}`),
- following: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/following/${userId}`),
- followers: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/followers/${userId}`),
- followCounts: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/follow-counts/${userId}`),
+ follow: '/market/social/follow',
+ unfollow: '/market/social/unfollow',
+ followStatus: (userId: number) => `/market/social/follow-status/${userId}`,
+ following: (userId: number) => `/market/social/following/${userId}`,
+ followers: (userId: number) => `/market/social/followers/${userId}`,
+ followCounts: (userId: number) => `/market/social/follow-counts/${userId}`,
// Social - Favorite
- favorite: withElectronProtocolIfElectron('/market/social/favorite'),
- unfavorite: withElectronProtocolIfElectron('/market/social/unfavorite'),
+ favorite: '/market/social/favorite',
+ unfavorite: '/market/social/unfavorite',
favoriteStatus: (targetType: 'agent' | 'plugin', targetIdOrIdentifier: number | string) =>
- withElectronProtocolIfElectron(
- `/market/social/favorite-status/${targetType}/${encodeURIComponent(targetIdOrIdentifier)}`,
- ),
- myFavorites: withElectronProtocolIfElectron('/market/social/favorites'),
- userFavorites: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/user-favorites/${userId}`),
- favoriteAgents: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/favorite-agents/${userId}`),
- favoritePlugins: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/favorite-plugins/${userId}`),
+ `/market/social/favorite-status/${targetType}/${encodeURIComponent(targetIdOrIdentifier)}`,
+ myFavorites: '/market/social/favorites',
+ userFavorites: (userId: number) => `/market/social/user-favorites/${userId}`,
+ favoriteAgents: (userId: number) => `/market/social/favorite-agents/${userId}`,
+ favoritePlugins: (userId: number) => `/market/social/favorite-plugins/${userId}`,
// Social - Like
- like: withElectronProtocolIfElectron('/market/social/like'),
- unlike: withElectronProtocolIfElectron('/market/social/unlike'),
- toggleLike: withElectronProtocolIfElectron('/market/social/toggle-like'),
+ like: '/market/social/like',
+ unlike: '/market/social/unlike',
+ toggleLike: '/market/social/toggle-like',
likeStatus: (targetType: 'agent' | 'plugin', targetIdOrIdentifier: number | string) =>
- withElectronProtocolIfElectron(
- `/market/social/like-status/${targetType}/${encodeURIComponent(targetIdOrIdentifier)}`,
- ),
- likedAgents: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/liked-agents/${userId}`),
- likedPlugins: (userId: number) =>
- withElectronProtocolIfElectron(`/market/social/liked-plugins/${userId}`),
+ `/market/social/like-status/${targetType}/${encodeURIComponent(targetIdOrIdentifier)}`,
+ likedAgents: (userId: number) => `/market/social/liked-agents/${userId}`,
+ likedPlugins: (userId: number) => `/market/social/liked-plugins/${userId}`,
};