Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(desktop): split runtime externals from native deps (#14776)

Innei36c4be46f07a
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjs
index 736a65a454a..f63d902a0e9 100644
--- a/apps/desktop/electron-builder.mjs
+++ b/apps/desktop/electron-builder.mjs
@@ -6,6 +6,10 @@ import { fileURLToPath } from 'node:url';
import dotenv from 'dotenv';
+import {
+ copyExternalRuntimeModulesToSource,
+ getExternalRuntimeModulesFilesConfig,
+} from './external-runtime-deps.config.mjs';
import {
copyNativeModules,
copyNativeModulesToSource,
@@ -106,6 +110,7 @@ const config = {
*/
beforePack: async () => {
await copyNativeModulesToSource();
+ await copyExternalRuntimeModulesToSource();
console.info('πŸ“¦ Downloading agent-browser binary...');
execSync('node scripts/download-agent-browser.mjs', { stdio: 'inherit', cwd: __dirname });
@@ -251,6 +256,8 @@ const config = {
'!node_modules',
// Then explicitly include native modules using object form (handles pnpm symlinks)
...getNativeModulesFilesConfig(),
+ // Include non-native runtime modules that are intentionally externalized from Vite.
+ ...getExternalRuntimeModulesFilesConfig(),
],
generateUpdatesFilesForAllChannels: true,
linux: {
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts
index 9b4a1c78675..406a9c595d7 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -13,7 +13,8 @@ import {
sharedRendererPlugins,
sharedRollupOutput,
} from '../../plugins/vite/sharedRendererConfig';
-import { getExternalDependencies } from './native-deps.config.mjs';
+import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
+import { getNativeExternalDependencies } from './native-deps.config.mjs';
/**
* Force `base: '/'` in renderer config. The `electron-vite` preset
@@ -99,7 +100,11 @@ const desktopPackageJson = JSON.parse(
readFileSync(path.resolve(__dirname, 'package.json'), 'utf8'),
) as { version: string };
const electronRuntimeExternals = ['electron'];
-const mainProcessRuntimeExternals = [...electronRuntimeExternals, 'node-mac-permissions'];
+const mainProcessRuntimeExternals = [
+ ...electronRuntimeExternals,
+ ...externalRuntimeModules,
+ 'node-mac-permissions',
+];
console.info(`[electron-vite.config.ts] Detected UPDATE_CHANNEL: ${updateChannel}`);
@@ -113,7 +118,7 @@ export default defineConfig({
// bufferutil and utf-8-validate are optional peer deps of ws that may not be installed.
external: [
...mainProcessRuntimeExternals,
- ...getExternalDependencies(),
+ ...getNativeExternalDependencies(),
'bufferutil',
'utf-8-validate',
],
diff --git a/apps/desktop/external-runtime-deps.config.mjs b/apps/desktop/external-runtime-deps.config.mjs
new file mode 100644
index 00000000000..850dc7e36c7
--- /dev/null
+++ b/apps/desktop/external-runtime-deps.config.mjs
@@ -0,0 +1,33 @@
+import {
+ copyModulesToSource,
+ getDependenciesForModules,
+ getModuleFilesConfig,
+} from './module-deps.config.mjs';
+
+/**
+ * Non-native modules intentionally externalized from the main-process bundle.
+ *
+ * These modules are not native dependencies. They stay external because their
+ * process-level side effects must be owned by one Node runtime module instance.
+ */
+export const externalRuntimeModules = ['electron-log'];
+
+/**
+ * Get all dependencies for runtime external modules.
+ * @returns {string[]}
+ */
+export function getAllExternalRuntimeDependencies() {
+ return getDependenciesForModules(externalRuntimeModules);
+}
+
+/**
+ * Generate files config objects for non-native runtime external modules.
+ * @returns {Array<{from: string, to: string, filter: string[]}>}
+ */
+export function getExternalRuntimeModulesFilesConfig() {
+ return getModuleFilesConfig(externalRuntimeModules);
+}
+
+export async function copyExternalRuntimeModulesToSource() {
+ await copyModulesToSource(externalRuntimeModules, 'runtime external module');
+}
diff --git a/apps/desktop/module-deps.config.mjs b/apps/desktop/module-deps.config.mjs
new file mode 100644
index 00000000000..62049db6ff2
--- /dev/null
+++ b/apps/desktop/module-deps.config.mjs
@@ -0,0 +1,189 @@
+/* eslint-disable no-console */
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const sourceNodeModules = path.join(__dirname, 'node_modules');
+
+/**
+ * Recursively resolve all dependencies of a module.
+ * @param {string} moduleName - The module to resolve
+ * @param {Set<string>} visited - Set of already visited modules
+ * @param {string} nodeModulesPath - Path to node_modules directory
+ * @returns {Set<string>} Set of all dependencies
+ */
+function resolveDependencies(moduleName, visited = new Set(), nodeModulesPath = sourceNodeModules) {
+ if (visited.has(moduleName)) {
+ return visited;
+ }
+
+ // Always add the module name first. Workspace and optional platform modules
+ // may not be materialized locally, but they still need stable package rules.
+ visited.add(moduleName);
+
+ const packageJsonPath = path.join(nodeModulesPath, moduleName, 'package.json');
+
+ if (!fs.existsSync(packageJsonPath)) {
+ return visited;
+ }
+
+ try {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
+ const dependencies = packageJson.dependencies || {};
+ const optionalDependencies = packageJson.optionalDependencies || {};
+
+ for (const dep of Object.keys(dependencies)) {
+ resolveDependencies(dep, visited, nodeModulesPath);
+ }
+
+ for (const dep of Object.keys(optionalDependencies)) {
+ resolveDependencies(dep, visited, nodeModulesPath);
+ }
+ } catch {
+ // Ignore unreadable package.json files; electron-builder will surface any
+ // actual missing runtime dependency during packaging or startup.
+ }
+
+ return visited;
+}
+
+/**
+ * Get all transitive dependencies for a set of top-level modules.
+ * @param {string[]} modules
+ * @returns {string[]}
+ */
+export function getDependenciesForModules(modules) {
+ const allDeps = new Set();
+
+ for (const moduleName of modules) {
+ const deps = resolveDependencies(moduleName);
+ for (const dep of deps) {
+ allDeps.add(dep);
+ }
+ }
+
+ return [...allDeps];
+}
+
+/**
+ * Generate glob patterns for electron-builder files config.
+ * @param {string[]} modules
+ * @returns {string[]}
+ */
+export function getModuleFilesPatterns(modules) {
+ return getDependenciesForModules(modules).map((dep) => `node_modules/${dep}/**/*`);
+}
+
+/**
+ * Generate object-form electron-builder files config.
+ * Object form is required because pnpm symlinks are resolved before packaging.
+ * @param {string[]} modules
+ * @returns {Array<{from: string, to: string, filter: string[]}>}
+ */
+export function getModuleFilesConfig(modules) {
+ return getDependenciesForModules(modules).map((dep) => ({
+ filter: ['**/*'],
+ from: `node_modules/${dep}`,
+ to: `node_modules/${dep}`,
+ }));
+}
+
+/**
+ * Copy module symlinks in source node_modules to real directories so
+ * electron-builder can include them via file rules.
+ * @param {string[]} modules
+ * @param {string} label
+ */
+export async function copyModulesToSource(modules, label) {
+ const deps = getDependenciesForModules(modules);
+
+ console.log(`πŸ“¦ Resolving ${deps.length} ${label} symlinks for packaging...`);
+
+ for (const dep of deps) {
+ const modulePath = path.join(sourceNodeModules, dep);
+
+ try {
+ const stat = await fs.promises.lstat(modulePath);
+
+ if (stat.isSymbolicLink()) {
+ const realPath = await fs.promises.realpath(modulePath);
+ console.log(` πŸ“Ž ${dep} (resolving symlink)`);
+
+ await fs.promises.rm(modulePath, { force: true, recursive: true });
+ await fs.promises.mkdir(path.dirname(modulePath), { recursive: true });
+ await copyDir(realPath, modulePath);
+ }
+ } catch (err) {
+ console.log(` ⏭️ ${dep} (skipped: ${err.code || err.message})`);
+ }
+ }
+
+ console.log(`βœ… ${label} symlinks resolved`);
+}
+
+/**
+ * Copy modules to a destination node_modules directory, resolving symlinks.
+ * @param {string[]} modules
+ * @param {string} destNodeModules
+ * @param {string} label
+ */
+export async function copyModulesToDirectory(modules, destNodeModules, label) {
+ const deps = getDependenciesForModules(modules);
+
+ console.log(`πŸ“¦ Copying ${deps.length} ${label} to unpacked directory...`);
+
+ for (const dep of deps) {
+ const sourcePath = path.join(sourceNodeModules, dep);
+ const destPath = path.join(destNodeModules, dep);
+
+ try {
+ const stat = await fs.promises.lstat(sourcePath);
+
+ if (stat.isSymbolicLink()) {
+ const realPath = await fs.promises.realpath(sourcePath);
+ console.log(` πŸ“Ž ${dep} (symlink -> ${path.relative(sourceNodeModules, realPath)})`);
+
+ await fs.promises.mkdir(path.dirname(destPath), { recursive: true });
+ await copyDir(realPath, destPath);
+ } else if (stat.isDirectory()) {
+ console.log(` πŸ“ ${dep}`);
+ await fs.promises.mkdir(path.dirname(destPath), { recursive: true });
+ await copyDir(sourcePath, destPath);
+ }
+ } catch (err) {
+ console.log(` ⏭️ ${dep} (skipped: ${err.code || err.message})`);
+ }
+ }
+
+ console.log(`βœ… ${label} copied successfully`);
+}
+
+/**
+ * Recursively copy a directory.
+ * @param {string} src
+ * @param {string} dest
+ */
+async function copyDir(src, dest) {
+ await fs.promises.mkdir(dest, { recursive: true });
+ const entries = await fs.promises.readdir(src, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const srcPath = path.join(src, entry.name);
+ const destPath = path.join(dest, entry.name);
+
+ if (entry.isDirectory()) {
+ await copyDir(srcPath, destPath);
+ } else if (entry.isSymbolicLink()) {
+ const realPath = await fs.promises.realpath(srcPath);
+ const realStat = await fs.promises.stat(realPath);
+ if (realStat.isDirectory()) {
+ await copyDir(realPath, destPath);
+ } else {
+ await fs.promises.copyFile(realPath, destPath);
+ }
+ } else {
+ await fs.promises.copyFile(srcPath, destPath);
+ }
+ }
+}
diff --git a/apps/desktop/native-deps.config.mjs b/apps/desktop/native-deps.config.mjs
index 8cf353d0cdd..69b45d5da3a 100644
--- a/apps/desktop/native-deps.config.mjs
+++ b/apps/desktop/native-deps.config.mjs
@@ -1,4 +1,3 @@
-/* eslint-disable no-console */
/**
* Native dependencies configuration for Electron build
*
@@ -9,12 +8,15 @@
*
* This module automatically resolves the full dependency tree.
*/
-import fs from 'node:fs';
import os from 'node:os';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
+import {
+ copyModulesToDirectory,
+ copyModulesToSource,
+ getDependenciesForModules,
+ getModuleFilesConfig,
+ getModuleFilesPatterns,
+} from './module-deps.config.mjs';
/**
* Get the current target platform
@@ -40,78 +42,20 @@ export const nativeModules = [
'node-screenshots',
];
-/**
- * Recursively resolve all dependencies of a module
- * @param {string} moduleName - The module to resolve
- * @param {Set<string>} visited - Set of already visited modules (to avoid cycles)
- * @param {string} nodeModulesPath - Path to node_modules directory
- * @returns {Set<string>} Set of all dependencies
- */
-function resolveDependencies(
- moduleName,
- visited = new Set(),
- nodeModulesPath = path.join(__dirname, 'node_modules'),
-) {
- if (visited.has(moduleName)) {
- return visited;
- }
-
- // Always add the module name first (important for workspace dependencies
- // that may not be in local node_modules but are declared in nativeModules)
- visited.add(moduleName);
-
- const packageJsonPath = path.join(nodeModulesPath, moduleName, 'package.json');
-
- // If module doesn't exist locally, still keep it in visited but skip dependency resolution
- if (!fs.existsSync(packageJsonPath)) {
- return visited;
- }
-
- try {
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
- const dependencies = packageJson.dependencies || {};
- const optionalDependencies = packageJson.optionalDependencies || {};
-
- // Resolve regular dependencies
- for (const dep of Object.keys(dependencies)) {
- resolveDependencies(dep, visited, nodeModulesPath);
- }
-
- // Also resolve optional dependencies (important for native modules like @napi-rs/canvas
- // which have platform-specific binaries in optional deps)
- for (const dep of Object.keys(optionalDependencies)) {
- resolveDependencies(dep, visited, nodeModulesPath);
- }
- } catch {
- // Ignore errors reading package.json
- }
-
- return visited;
-}
-
/**
* Get all dependencies for all native modules (including transitive dependencies)
* @returns {string[]} Array of all dependency names
*/
-export function getAllDependencies() {
- const allDeps = new Set();
-
- for (const nativeModule of nativeModules) {
- const deps = resolveDependencies(nativeModule);
- for (const dep of deps) {
- allDeps.add(dep);
- }
- }
-
- return [...allDeps];
+export function getAllNativeDependencies() {
+ return getDependenciesForModules(nativeModules);
}
/**
* Generate glob patterns for electron-builder files config
* @returns {string[]} Array of glob patterns
*/
-export function getFilesPatterns() {
- return getAllDependencies().map((dep) => `node_modules/${dep}/**/*`);
+export function getNativeModuleFilesPatterns() {
+ return getModuleFilesPatterns(nativeModules);
}
/**
@@ -120,11 +64,7 @@ export function getFilesPatterns() {
* @returns {Array<{from: string, to: string, filter: string[]}>}
*/
export function getNativeModulesFilesConfig() {
- return getAllDependencies().map((dep) => ({
- filter: ['**/*'],
- from: `node_modules/${dep}`,
- to: `node_modules/${dep}`,
- }));
+ return getModuleFilesConfig(nativeModules);
}
/**
@@ -132,15 +72,15 @@ export function getNativeModulesFilesConfig() {
* @returns {string[]} Array of glob patterns
*/
export function getAsarUnpackPatterns() {
- return getAllDependencies().map((dep) => `node_modules/${dep}/**/*`);
+ return getNativeModuleFilesPatterns();
}
/**
* Get the list of native dependencies for Vite external config
* @returns {string[]} Array of dependency names
*/
-export function getExternalDependencies() {
- return getAllDependencies();
+export function getNativeExternalDependencies() {
+ return getAllNativeDependencies();
}
/**
@@ -149,39 +89,7 @@ export function getExternalDependencies() {
* included in the asar archive (electron-builder glob doesn't follow symlinks).
*/
export async function copyNativeModulesToSource() {
- const fsPromises = await import('node:fs/promises');
- const deps = getAllDependencies();
- const sourceNodeModules = path.join(__dirname, 'node_modules');
-
- console.log(`πŸ“¦ Resolving ${deps.length} native module symlinks for packaging...`);
-
- for (const dep of deps) {
- const modulePath = path.join(sourceNodeModules, dep);
-
- try {
- const stat = await fsPromises.lstat(modulePath);
-
- if (stat.isSymbolicLink()) {
- // Resolve the symlink to get the real path
- const realPath = await fsPromises.realpath(modulePath);
- console.log(` πŸ“Ž ${dep} (resolving symlink)`);
-
- // Remove the symlink
- await fsPromises.rm(modulePath, { force: true, recursive: true });
-
- // Create parent directory if needed (for scoped packages like @napi-rs)
- await fsPromises.mkdir(path.dirname(modulePath), { recursive: true });
-
- // Copy the actual directory content in place of the symlink
- await copyDir(realPath, modulePath);
- }
- } catch (err) {
- // Module might not exist (optional dependency for different platform)
- console.log(` ⏭️ ${dep} (skipped: ${err.code || err.message})`);
- }
- }
-
- console.log(`βœ… Native module symlinks resolved`);
+ await copyModulesToSource(nativeModules, 'native module');
}
/**
@@ -190,72 +98,5 @@ export async function copyNativeModulesToSource() {
* @param {string} destNodeModules - Destination node_modules path
*/
export async function copyNativeModules(destNodeModules) {
- const fsPromises = await import('node:fs/promises');
- const deps = getAllDependencies();
- const sourceNodeModules = path.join(__dirname, 'node_modules');
-
- console.log(`πŸ“¦ Copying ${deps.length} native modules to unpacked directory...`);
-
- for (const dep of deps) {
- const sourcePath = path.join(sourceNodeModules, dep);
- const destPath = path.join(destNodeModules, dep);
-
- try {
- // Check if source exists (might be a symlink)
- const stat = await fsPromises.lstat(sourcePath);
-
- if (stat.isSymbolicLink()) {
- // Resolve the symlink to get the real path
- const realPath = await fsPromises.realpath(sourcePath);
- console.log(` πŸ“Ž ${dep} (symlink -> ${path.relative(sourceNodeModules, realPath)})`);
-
- // Create destination directory
- await fsPromises.mkdir(path.dirname(destPath), { recursive: true });
-
- // Copy the actual directory content (not the symlink)
- await copyDir(realPath, destPath);
- } else if (stat.isDirectory()) {
- console.log(` πŸ“ ${dep}`);
- await fsPromises.mkdir(path.dirname(destPath), { recursive: true });
- await copyDir(sourcePath, destPath);
- }
- } catch (err) {
- // Module might not exist (optional dependency for different platform)
- console.log(` ⏭️ ${dep} (skipped: ${err.code || err.message})`);
- }
- }
-
- console.log(`βœ… Native modules copied successfully`);
-}
-
-/**
- * Recursively copy a directory
- * @param {string} src - Source directory
- * @param {string} dest - Destination directory
- */
-async function copyDir(src, dest) {
- const fsPromises = await import('node:fs/promises');
-
- await fsPromises.mkdir(dest, { recursive: true });
- const entries = await fsPromises.readdir(src, { withFileTypes: true });
-
- for (const entry of entries) {
- const srcPath = path.join(src, entry.name);
- const destPath = path.join(dest, entry.name);
-
- if (entry.isDirectory()) {
- await copyDir(srcPath, destPath);
- } else if (entry.isSymbolicLink()) {
- // For symlinks within the module, resolve and copy the actual file
- const realPath = await fsPromises.realpath(srcPath);
- const realStat = await fsPromises.stat(realPath);
- if (realStat.isDirectory()) {
- await copyDir(realPath, destPath);
- } else {
- await fsPromises.copyFile(realPath, destPath);
- }
- } else {
- await fsPromises.copyFile(srcPath, destPath);
- }
- }
+ await copyModulesToDirectory(nativeModules, destNodeModules, 'native modules');
}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index e7bd0ef6330..30882021812 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -44,6 +44,7 @@
"dependencies": {
"@lobehub/fluent-emoji": "^4.1.0",
"@napi-rs/canvas": "^0.1.70",
+ "electron-log": "^5.4.3",
"get-windows": "^9.3.0",
"node-screenshots": "^0.2.8"
},
@@ -79,7 +80,6 @@
"electron-builder": "^26.8.1",
"electron-devtools-installer": "4.0.0",
"electron-is": "^3.0.0",
- "electron-log": "^5.4.3",
"electron-store": "^8.2.0",
"electron-updater": "^6.6.2",
"electron-vite": "6.0.0-beta.1",