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): drop electron-vite for plain Vite configs + dev orchestrator (#17179)

Innei98dc59893941
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 44d4495e1bf..1c88afc1a6b 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -12,9 +12,10 @@
"main": "./dist/main/index.js",
"scripts": {
"build:cli": "cd ../cli && cross-env MINIFY=1 bun run build",
- "build:main": "cross-env NODE_OPTIONS=--max-old-space-size=8192 electron-vite build",
+ "build:main": "cross-env NODE_OPTIONS=--max-old-space-size=8192 npm run build:main:raw",
+ "build:main:raw": "vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.renderer.config.ts",
"build:run-unpack": "electron .",
- "dev": "electron-vite dev",
+ "dev": "node scripts/dev.mjs",
"dev:static": "cross-env DESKTOP_RENDERER_STATIC=1 npm run dev",
"fix:electron": "node scripts/fix-electron-runtime.mjs",
"format": "prettier --write ",
@@ -34,7 +35,7 @@
"package:mac": "npm run build:main && electron-builder --mac --config electron-builder.mjs --publish never",
"package:mac:local": "npm run build:main && cross-env UPDATE_CHANNEL=nightly electron-builder --mac --config electron-builder.mjs --publish never --c.mac.notarize=false -c.mac.identity=null",
"package:win": "npm run build:main && electron-builder --win --config electron-builder.mjs --publish never",
- "start": "electron-vite preview",
+ "start": "electron .",
"stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",
"test": "vitest --run",
"type-check": "tsgo --noEmit -p tsconfig.json",
@@ -85,7 +86,6 @@
"electron-is": "^3.0.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.8.9",
- "electron-vite": "6.0.0-beta.1",
"electron-window-state": "^5.0.3",
"es-toolkit": "^1.49.0",
"eslint": "10.0.0",
diff --git a/apps/desktop/scripts/dev.mjs b/apps/desktop/scripts/dev.mjs
new file mode 100644
index 00000000000..31953316391
--- /dev/null
+++ b/apps/desktop/scripts/dev.mjs
@@ -0,0 +1,126 @@
+import { spawn } from 'node:child_process';
+import { existsSync, statSync, watch } from 'node:fs';
+import { createRequire } from 'node:module';
+import net from 'node:net';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const desktopRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const require = createRequire(path.join(desktopRoot, 'package.json'));
+const electronBin = require('electron');
+
+const VITE_PORT = Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173;
+const MAIN_BUNDLE = path.join(desktopRoot, 'dist/main/index.js');
+const PRELOAD_BUNDLE = path.join(desktopRoot, 'dist/preload/index.js');
+
+let electron = null;
+let restarting = false;
+let shuttingDown = false;
+
+const spawnVite = (args) =>
+ spawn('pnpm', ['exec', 'vite', ...args], { cwd: desktopRoot, stdio: 'inherit' });
+
+const children = [
+ spawnVite(['--config', 'vite.renderer.config.ts']),
+ spawnVite(['build', '--watch', '--mode', 'development', '--config', 'vite.main.config.ts']),
+ spawnVite(['build', '--watch', '--mode', 'development', '--config', 'vite.preload.config.ts']),
+];
+
+for (const child of children) {
+ child.on('exit', (code) => {
+ if (!shuttingDown) shutdown(code ?? 1);
+ });
+}
+
+function shutdown(code) {
+ if (shuttingDown) return;
+ shuttingDown = true;
+ electron?.kill();
+ for (const child of children) child.kill();
+ process.exit(code);
+}
+
+process.on('SIGINT', () => shutdown(0));
+process.on('SIGTERM', () => shutdown(0));
+
+function startElectron() {
+ electron = spawn(electronBin, ['.'], {
+ cwd: desktopRoot,
+ env: {
+ ...process.env,
+ ELECTRON_RENDERER_URL: `http://127.0.0.1:${VITE_PORT}`,
+ NODE_ENV: 'development',
+ },
+ stdio: 'inherit',
+ });
+ electron.on('exit', (code) => {
+ if (shuttingDown) return;
+ if (restarting) {
+ restarting = false;
+ startElectron();
+ return;
+ }
+ // The app was quit by hand β€” stop the watchers instead of idling forever.
+ console.log('[desktop-dev] electron exited, stopping dev watchers');
+ shutdown(code ?? 0);
+ });
+}
+
+let debounce = null;
+function scheduleRestart() {
+ clearTimeout(debounce);
+ debounce = setTimeout(() => {
+ if (shuttingDown || !electron) return;
+ console.log('[desktop-dev] main/preload bundle changed, restarting electron');
+ restarting = true;
+ electron.kill();
+ }, 400);
+}
+
+function watchBundles() {
+ for (const dir of [path.dirname(MAIN_BUNDLE), path.dirname(PRELOAD_BUNDLE)]) {
+ watch(dir, scheduleRestart);
+ }
+}
+
+const rendererServerReady = () =>
+ new Promise((resolve) => {
+ const socket = net.connect({ host: '127.0.0.1', port: VITE_PORT }, () => {
+ socket.destroy();
+ resolve(true);
+ });
+ socket.on('error', () => resolve(false));
+ });
+
+// The two build configs `emptyOutDir` on startup and finish at different times,
+// so wait until the renderer server accepts connections and both bundles exist
+// and have been quiet for a second before launching electron or attaching watchers.
+const started = Date.now();
+let lastChange = Date.now();
+let lastSignature = '';
+let checking = false;
+const poll = setInterval(async () => {
+ if (checking) return;
+ checking = true;
+ try {
+ if (Date.now() - started > 120_000) {
+ console.error('[desktop-dev] initial build did not produce bundles within 120s');
+ shutdown(1);
+ return;
+ }
+ if (!existsSync(MAIN_BUNDLE) || !existsSync(PRELOAD_BUNDLE)) return;
+ const signature = [MAIN_BUNDLE, PRELOAD_BUNDLE].map((f) => statSync(f).mtimeMs).join(':');
+ if (signature !== lastSignature) {
+ lastSignature = signature;
+ lastChange = Date.now();
+ return;
+ }
+ if (Date.now() - lastChange < 1000) return;
+ if (!(await rendererServerReady())) return;
+ clearInterval(poll);
+ watchBundles();
+ startElectron();
+ } finally {
+ checking = false;
+ }
+}, 200);
diff --git a/apps/desktop/src/main/utils/mime.ts b/apps/desktop/src/main/utils/mime.ts
index 95b94afdfb7..7c226262838 100644
--- a/apps/desktop/src/main/utils/mime.ts
+++ b/apps/desktop/src/main/utils/mime.ts
@@ -47,7 +47,7 @@ const EXPORT_MIME_MAP: Record<string, string> = {
/**
* Lookup table for renderer-bundled assets. The set of extensions is closed
- * (whatever `electron-vite` produces under the renderer dir), so a whitelist
+ * (whatever the renderer Vite build produces under the renderer dir), so a whitelist
* is appropriate here.
*/
export const getExportMimeType = (filePath: string): string | undefined => {
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
new file mode 100644
index 00000000000..37877a42dd5
--- /dev/null
+++ b/apps/desktop/vite.main.config.ts
@@ -0,0 +1,116 @@
+import path from 'node:path';
+
+import { defineConfig } from 'vite';
+
+import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
+import { getNativeExternalDependencies } from './native-deps.config.mjs';
+import {
+ loadDesktopEnv,
+ MAIN_NODE_TARGET,
+ mainProcessAlias,
+ nodeExternals,
+ processEnvDefine,
+} from './vite.shared';
+
+export default defineConfig(({ mode }) => {
+ loadDesktopEnv(mode);
+
+ const isDev = mode === 'development';
+ const updateChannel = process.env.UPDATE_CHANNEL;
+ const isCloudDesktopBuild = process.env.CLOUD_DESKTOP === '1';
+ const externalNavigationHosts =
+ process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS ?? (isCloudDesktopBuild ? 'stripe.com' : '');
+
+ console.info(`[vite.main.config.ts] Detected UPDATE_CHANNEL: ${updateChannel}`);
+ console.info(`[vite.main.config.ts] Cloud desktop build: ${isCloudDesktopBuild}`);
+
+ return {
+ build: {
+ assetsDir: 'chunks',
+ copyPublicDir: false,
+ emptyOutDir: true,
+ lib: {
+ entry: path.resolve(__dirname, 'src/main/index.ts'),
+ formats: ['cjs'],
+ },
+ minify: !isDev,
+ modulePreload: false,
+ outDir: 'dist/main',
+ reportCompressedSize: false,
+ rolldownOptions: {
+ // Native modules must be externalized to work correctly.
+ // bufferutil and utf-8-validate are optional peer deps of ws that may not be installed.
+ external: [
+ ...nodeExternals,
+ ...externalRuntimeModules,
+ 'node-mac-permissions',
+ ...getNativeExternalDependencies(),
+ 'bufferutil',
+ 'utf-8-validate',
+ ],
+ output: {
+ assetFileNames: 'chunks/[name]-[hash].[ext]',
+ // Prevent shared deps from being bundled into index.js to avoid side-effect pollution.
+ // Pattern: when a module is imported by both the main bundle (statically) and a
+ // dynamic-import chunk (lazy loader), rolldown places it in main and makes the
+ // chunk back-reference `require("./index.js")`. Electron's main entry isn't in
+ // Node's CJS cache, so that require recompiles `index.js` from scratch β€” which
+ // re-runs `new App()` at top-level and triggers `protocol.registerSchemesAsPrivileged`
+ // *after* the app is ready β†’ throw.
+ //
+ // Same root cause as the original `debug` regression fixed in #11827. Isolate
+ // each shared module into its own vendor chunk so both ends reference the vendor
+ // chunk instead of back-referencing main.
+ manualChunks(id: string) {
+ if (id.includes('node_modules/debug')) {
+ return 'vendor-debug';
+ }
+
+ // Small text/binary detection utilities in file-loaders/utils. Imported by
+ // main (via `sniffBinaryFile`) and potentially by lazy loader chunks.
+ // Explicitly enumerated to avoid catching `parser-utils.ts`, which pulls in
+ // xmldom / yauzl / concat-stream β€” those belong in docx/pptx loader chunks.
+ if (
+ /packages\/file-loaders\/src\/utils\/(?:detectUtf16|isBinaryContent|isTextReadableFile)\.ts$/.test(
+ id,
+ )
+ ) {
+ return 'vendor-file-loaders-utils';
+ }
+
+ // jszip β€” imported by main (via some static path) AND by the docx loader chunk.
+ // Without this, reading a .docx file throws the protocol re-init error.
+ if (id.includes('node_modules/jszip')) {
+ return 'vendor-jszip';
+ }
+
+ // Split i18n json resources by namespace (ns), not by locale.
+ // Example: ".../resources/locales/zh-CN/common.json?import" -> "locales-common"
+ const normalizedId = id.replaceAll('\\', '/').split('?')[0];
+ const match = normalizedId.match(/\/locales\/[^/]+\/([^/]+)\.json$/);
+
+ if (match?.[1]) return `locales-${match[1]}`;
+ },
+ },
+ },
+ sourcemap: isDev ? 'inline' : false,
+ ssr: true,
+ ssrEmitAssets: true,
+ target: MAIN_NODE_TARGET,
+ },
+ define: {
+ ...processEnvDefine,
+ 'process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS': JSON.stringify(externalNavigationHosts),
+ 'process.env.UPDATE_CHANNEL': JSON.stringify(process.env.UPDATE_CHANNEL),
+ 'process.env.UPDATE_SERVER_URL': JSON.stringify(process.env.UPDATE_SERVER_URL),
+ },
+ publicDir: false,
+ resolve: {
+ alias: mainProcessAlias,
+ conditions: ['node'],
+ mainFields: ['module', 'jsnext:main', 'jsnext'],
+ },
+ root: __dirname,
+ ssr: { noExternal: true },
+ };
+});
diff --git a/apps/desktop/vite.preload.config.ts b/apps/desktop/vite.preload.config.ts
new file mode 100644
index 00000000000..e85ac91cec8
--- /dev/null
+++ b/apps/desktop/vite.preload.config.ts
@@ -0,0 +1,53 @@
+import path from 'node:path';
+
+import { defineConfig } from 'vite';
+
+import {
+ loadDesktopEnv,
+ MAIN_NODE_TARGET,
+ mainProcessAlias,
+ nodeExternals,
+ processEnvDefine,
+} from './vite.shared';
+
+export default defineConfig(({ mode }) => {
+ loadDesktopEnv(mode);
+
+ const isDev = mode === 'development';
+
+ return {
+ build: {
+ assetsDir: 'chunks',
+ copyPublicDir: false,
+ emptyOutDir: true,
+ lib: {
+ entry: path.resolve(__dirname, 'src/preload/index.ts'),
+ formats: ['cjs'],
+ },
+ minify: !isDev,
+ modulePreload: false,
+ outDir: 'dist/preload',
+ reportCompressedSize: false,
+ rolldownOptions: {
+ external: nodeExternals,
+ },
+ sourcemap: isDev ? 'inline' : false,
+ ssr: true,
+ ssrEmitAssets: true,
+ target: MAIN_NODE_TARGET,
+ },
+ define: { ...processEnvDefine },
+ publicDir: false,
+ resolve: {
+ alias: mainProcessAlias,
+ },
+ root: __dirname,
+ ssr: {
+ noExternal: true,
+ resolve: {
+ conditions: ['module', 'browser', 'development|production'],
+ mainFields: ['browser', 'module', 'jsnext:main', 'jsnext'],
+ },
+ },
+ };
+});
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/vite.renderer.config.ts
similarity index 54%
rename from apps/desktop/electron.vite.config.ts
rename to apps/desktop/vite.renderer.config.ts
index fe7d77e6de0..c450de7069e 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -2,10 +2,8 @@ import { readFileSync } from 'node:fs';
import path from 'node:path';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
-import dotenv from 'dotenv';
-import { defineConfig } from 'electron-vite';
import type { PluginOption, ViteDevServer } from 'vite';
-import { loadEnv } from 'vite';
+import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import {
@@ -14,35 +12,18 @@ import {
sharedRendererPlugins,
sharedRollupOutput,
} from '../../plugins/vite/sharedRendererConfig';
-import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
-import { getNativeExternalDependencies } from './native-deps.config.mjs';
-
-// Renderer dev-server port. Overridable per instance (e.g. one git worktree per
-// concurrent dev instance) via LOBE_DESKTOP_VITE_PORT; `electron-vite dev` injects
-// the matching ELECTRON_RENDERER_URL into the main process automatically. Kept
-// deterministic (still `strictPort`) so the HMR `clientPort` stays in sync.
-const DEV_VITE_PORT = Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173;
-
-/**
- * Force `base: '/'` in renderer config. The `electron-vite` preset
- * unconditionally rewrites base to `'./'` in production (with `enforce: 'pre'`),
- * which produces relative asset URLs like `../../assets/...`. Those break in
- * the popup window because its SPA URL (`/popup/agent/:aid/:tid`) is deep
- * enough that relative resolution lands at `/popup/assets/...` instead of the
- * actual `/assets/...`. Our `app://` protocol handler resolves absolute
- * `/assets/...` correctly regardless of URL depth.
- */
-function forceAbsoluteBasePlugin(): PluginOption {
- return {
- name: 'electron-desktop-force-base',
- config(config) {
- config.base = '/';
- },
- };
-}
+import {
+ CLOUD_ROOT_DIR,
+ desktopPackageJson,
+ DEV_VITE_PORT,
+ isCloudDesktopBuild,
+ loadDesktopEnv,
+ RENDERER_CHROME_TARGET,
+ ROOT_DIR,
+} from './vite.shared';
/**
- * Rewrite SPA routes to their corresponding HTML entry so the electron-vite
+ * Rewrite SPA routes to their corresponding HTML entry so the Vite
* dev server serves the right HTML when root is the monorepo root.
*
* - `/popup/*` β†’ `/apps/desktop/popup.html` (topic popup SPA)
@@ -195,129 +176,27 @@ function cloudDesktopBusinessConstPlugin(): PluginOption {
};
}
-dotenv.config();
-
-const isDev = process.env.NODE_ENV === 'development';
-const ROOT_DIR = path.resolve(__dirname, '../..');
-const CLOUD_ROOT_DIR = path.resolve(__dirname, '../../..');
-const isCloudDesktopBuild = process.env.CLOUD_DESKTOP === '1';
-const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development';
-
-Object.assign(process.env, loadEnv(mode, ROOT_DIR, ''));
-const updateChannel = process.env.UPDATE_CHANNEL;
-const desktopPackageJson = JSON.parse(
- readFileSync(path.resolve(__dirname, 'package.json'), 'utf8'),
-) as { version: string };
-const electronRuntimeExternals = ['electron'];
-const mainProcessRuntimeExternals = [
- ...electronRuntimeExternals,
- ...externalRuntimeModules,
- 'node-mac-permissions',
-];
-const externalNavigationHosts =
- process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS ?? (isCloudDesktopBuild ? 'stripe.com' : '');
-
-console.info(`[electron-vite.config.ts] Detected UPDATE_CHANNEL: ${updateChannel}`);
-console.info(`[electron-vite.config.ts] Cloud desktop build: ${isCloudDesktopBuild}`);
-
const cloudTsconfigPathsPlugin = () =>
({
...tsconfigPaths({ projects: [path.resolve(CLOUD_ROOT_DIR, 'tsconfig.json')] }),
name: 'lobe-cloud-desktop-tsconfig-paths',
}) satisfies PluginOption;
-export default defineConfig({
- main: {
- build: {
- minify: !isDev,
- outDir: 'dist/main',
- rolldownOptions: {
- // Native modules must be externalized to work correctly.
- // bufferutil and utf-8-validate are optional peer deps of ws that may not be installed.
- external: [
- ...mainProcessRuntimeExternals,
- ...getNativeExternalDependencies(),
- 'bufferutil',
- 'utf-8-validate',
- ],
- output: {
- // Prevent shared deps from being bundled into index.js to avoid side-effect pollution.
- // Pattern: when a module is imported by both the main bundle (statically) and a
- // dynamic-import chunk (lazy loader), rolldown places it in main and makes the
- // chunk back-reference `require("./index.js")`. Electron's main entry isn't in
- // Node's CJS cache, so that require recompiles `index.js` from scratch β€” which
- // re-runs `new App()` at top-level and triggers `protocol.registerSchemesAsPrivileged`
- // *after* the app is ready β†’ throw.
- //
- // Same root cause as the original `debug` regression fixed in #11827. Isolate
- // each shared module into its own vendor chunk so both ends reference the vendor
- // chunk instead of back-referencing main.
- manualChunks(id) {
- if (id.includes('node_modules/debug')) {
- return 'vendor-debug';
- }
-
- // Small text/binary detection utilities in file-loaders/utils. Imported by
- // main (via `sniffBinaryFile`) and potentially by lazy loader chunks.
- // Explicitly enumerated to avoid catching `parser-utils.ts`, which pulls in
- // xmldom / yauzl / concat-stream β€” those belong in docx/pptx loader chunks.
- if (
- /packages\/file-loaders\/src\/utils\/(?:detectUtf16|isBinaryContent|isTextReadableFile)\.ts$/.test(
- id,
- )
- ) {
- return 'vendor-file-loaders-utils';
- }
-
- // jszip β€” imported by main (via some static path) AND by the docx loader chunk.
- // Without this, reading a .docx file throws the protocol re-init error.
- if (id.includes('node_modules/jszip')) {
- return 'vendor-jszip';
- }
-
- // Split i18n json resources by namespace (ns), not by locale.
- // Example: ".../resources/locales/zh-CN/common.json?import" -> "locales-common"
- const normalizedId = id.replaceAll('\\', '/').split('?')[0];
- const match = normalizedId.match(/\/locales\/[^/]+\/([^/]+)\.json$/);
+export default defineConfig(({ mode }) => {
+ loadDesktopEnv(mode);
- if (match?.[1]) return `locales-${match[1]}`;
- },
- },
- },
- sourcemap: isDev ? 'inline' : false,
- },
- define: {
- 'process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS': JSON.stringify(externalNavigationHosts),
- 'process.env.UPDATE_CHANNEL': JSON.stringify(process.env.UPDATE_CHANNEL),
- 'process.env.UPDATE_SERVER_URL': JSON.stringify(process.env.UPDATE_SERVER_URL),
- },
- resolve: {
- alias: {
- '@': path.resolve(__dirname, 'src/main'),
- '~common': path.resolve(__dirname, 'src/common'),
- },
- },
- },
- preload: {
- build: {
- minify: !isDev,
- outDir: 'dist/preload',
- rolldownOptions: {
- external: electronRuntimeExternals,
- },
- sourcemap: isDev ? 'inline' : false,
- },
- resolve: {
- alias: {
- '@': path.resolve(__dirname, 'src/main'),
- '~common': path.resolve(__dirname, 'src/common'),
- },
- },
- },
- renderer: {
- root: ROOT_DIR,
+ return {
+ // Absolute base: relative asset URLs break in the popup window because its
+ // SPA URL (`/popup/agent/:aid/:tid`) is deep enough that relative resolution
+ // lands at `/popup/assets/...` instead of the actual `/assets/...`. Our
+ // `app://` protocol handler resolves absolute `/assets/...` correctly
+ // regardless of URL depth.
+ base: '/',
build: {
+ minify: false,
+ modulePreload: { polyfill: false },
outDir: path.resolve(__dirname, 'dist/renderer'),
+ reportCompressedSize: false,
rolldownOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
@@ -326,16 +205,18 @@ export default defineConfig({
},
output: sharedRollupOutput,
},
+ target: RENDERER_CHROME_TARGET,
},
define: {
- ...sharedRendererDefine({ isMobile: false, isElectron: true }),
+ ...sharedRendererDefine({ isElectron: true, isMobile: false }),
__MAIN_VERSION__: JSON.stringify(desktopPackageJson.version),
},
+ envDir: __dirname,
+ envPrefix: ['RENDERER_VITE_', 'VITE_'],
optimizeDeps: sharedOptimizeDeps,
plugins: [
isCloudDesktopBuild && cloudTsconfigPathsPlugin(),
isCloudDesktopBuild && cloudDesktopBusinessConstPlugin(),
- forceAbsoluteBasePlugin(),
electronDesktopHtmlPlugin(),
vanillaExtractPlugin(),
...(sharedRendererPlugins({ platform: 'desktop' }) as PluginOption[]),
@@ -344,6 +225,7 @@ export default defineConfig({
dedupe: ['react', 'react-dom'],
tsconfigPaths: !isCloudDesktopBuild,
},
+ root: ROOT_DIR,
// 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
@@ -361,5 +243,5 @@ export default defineConfig({
port: DEV_VITE_PORT,
strictPort: true,
},
- },
+ };
});
diff --git a/apps/desktop/vite.shared.ts b/apps/desktop/vite.shared.ts
new file mode 100644
index 00000000000..05020d90553
--- /dev/null
+++ b/apps/desktop/vite.shared.ts
@@ -0,0 +1,50 @@
+import { readFileSync } from 'node:fs';
+import { builtinModules } from 'node:module';
+import path from 'node:path';
+
+import dotenv from 'dotenv';
+import { loadEnv } from 'vite';
+
+export const DESKTOP_DIR = __dirname;
+export const ROOT_DIR = path.resolve(__dirname, '../..');
+export const CLOUD_ROOT_DIR = path.resolve(__dirname, '../../..');
+
+export const isCloudDesktopBuild = process.env.CLOUD_DESKTOP === '1';
+
+// Renderer dev-server port. Overridable per instance (e.g. one git worktree per
+// concurrent dev instance) via LOBE_DESKTOP_VITE_PORT; `scripts/dev.mjs` injects
+// the matching ELECTRON_RENDERER_URL into the main process. Kept deterministic
+// (still `strictPort`) so the HMR `clientPort` stays in sync.
+export const DEV_VITE_PORT = Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173;
+
+// Electron 41 ships Node 24.14 / Chromium 146 β€” keep in sync when bumping electron.
+export const MAIN_NODE_TARGET = 'node24.14';
+export const RENDERER_CHROME_TARGET = 'chrome146';
+
+export const desktopPackageJson = JSON.parse(
+ readFileSync(path.resolve(__dirname, 'package.json'), 'utf8'),
+) as { version: string };
+
+export const loadDesktopEnv = (mode: string) => {
+ dotenv.config();
+ Object.assign(process.env, loadEnv(mode, ROOT_DIR, ''));
+};
+
+export const nodeExternals = [
+ 'electron',
+ /^electron\/.+/,
+ ...builtinModules.flatMap((m) => [m, `node:${m}`]),
+];
+
+// Keep `process.env` references live at runtime instead of statically replaced
+// (electron-vite preset parity); more specific `process.env.X` defines still win.
+export const processEnvDefine = {
+ 'global.process.env': 'global.process.env',
+ 'globalThis.process.env': 'globalThis.process.env',
+ 'process.env': 'process.env',
+};
+
+export const mainProcessAlias = {
+ '@': path.resolve(__dirname, 'src/main'),
+ '~common': path.resolve(__dirname, 'src/common'),
+};
diff --git a/src/types/global.d.ts b/src/types/global.d.ts
index 22864f28476..61975e62531 100644
--- a/src/types/global.d.ts
+++ b/src/types/global.d.ts
@@ -56,6 +56,6 @@ declare global {
/** Vite define: current bundle is Electron desktop variant */
const __ELECTRON__: boolean | undefined;
- /** Vite define: desktop app version injected by electron-vite renderer build */
+ /** Vite define: desktop app version injected by the desktop renderer Vite build */
const __MAIN_VERSION__: string;
}