π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(desktop): reduce packaged app size (#17408)
Innei65753ef6a5df
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex 14ff8d06e87..f29e88c1015 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -11,7 +11,6 @@ import {getExternalRuntimeModulesFilesConfig,} from './external-runtime-deps.config.mjs';import {- copyNativeModules,copyNativeModulesToSource,getAsarUnpackPatterns,getNativeModulesFilesConfig,@@ -72,10 +71,6 @@ const getPublishConfig = () => {];};-// Keep only these Electron Framework localization folders (*.lproj)-// (aligned with previous Electron Forge build config)-const keepLanguages = new Set(['en', 'en_GB', 'en-US', 'en_US']);-// https://www.electron.build/code-signing-mac#how-to-disable-code-signing-during-the-build-process-on-macosif (!hasAppleCertificate) {// Disable auto discovery to keep electron-builder from searching unavailable signing identities@@ -138,72 +133,27 @@ const config = {console.info('β CLI bundle copied to resources/bin/lobe-cli.js');},/**- * AfterPack hook for post-processing:- * 1. Copy native modules to asar.unpacked (resolving pnpm symlinks)- * 2. Copy Liquid Glass Assets.car for macOS 26+- * 3. Remove unused Electron Framework localizations+ * AfterPack hook for copying Liquid Glass Assets.car on macOS 26+.** @see https://github.com/electron-userland/electron-builder/issues/9254* @see https://github.com/MultiboxLabs/flow-browser/pull/159- * @see https://github.com/electron/packager/pull/1806*/afterPack: async (context) => {const isMac = ['darwin', 'mas'].includes(context.electronPlatformName);- // Determine resources path based on platform- let resourcesPath;- if (isMac) {- resourcesPath = path.join(- context.appOutDir,- `${context.packager.appInfo.productFilename}.app`,- 'Contents',- 'Resources',- );- } else {- // Windows and Linux: resources is directly in appOutDir- resourcesPath = path.join(context.appOutDir, 'resources');- }-- // Copy native modules to asar.unpacked, resolving pnpm symlinks- const unpackedNodeModules = path.join(resourcesPath, 'app.asar.unpacked', 'node_modules');- await copyNativeModules(unpackedNodeModules);-- // macOS-specific post-processingif (!isMac) {return;}- const iconFileName = getIconFileName();- const assetsCarSource = path.join(__dirname, 'build', `${iconFileName}.Assets.car`);- const assetsCarDest = path.join(resourcesPath, 'Assets.car');-- // Remove unused Electron Framework localizations to reduce app size- const frameworkResourcePath = path.join(+ const resourcesPath = path.join(context.appOutDir,`${context.packager.appInfo.productFilename}.app`,'Contents',- 'Frameworks',- 'Electron Framework.framework',- 'Versions',- 'A','Resources',);-- try {- const entries = await fs.readdir(frameworkResourcePath);- await Promise.all(- entries.map(async (file) => {- if (!file.endsWith('.lproj')) return;-- const lang = file.split('.')[0];- if (keepLanguages.has(lang)) return;-- await fs.rm(path.join(frameworkResourcePath, file), { force: true, recursive: true });- }),- );- } catch {- // Non-critical: folder may not exist depending on packaging details- }+ const iconFileName = getIconFileName();+ const assetsCarSource = path.join(__dirname, 'build', `${iconFileName}.Assets.car`);+ const assetsCarDest = path.join(resourcesPath, 'Assets.car');try {await fs.access(assetsCarSource);@@ -220,6 +170,11 @@ const config = {artifactName: '${productName}-${version}.${ext}',},+ // Only explicitly selected native binaries should live outside app.asar.+ asar: {+ smartUnpack: false,+ },+// Native modules must be unpacked from asar to work correctlyasarUnpack: getAsarUnpackPatterns(),@@ -247,6 +202,9 @@ const config = {electronDownload: {mirror: 'https://npmmirror.com/mirrors/electron/',},+ // Electron uses underscores for macOS .lproj directories and hyphens for+ // Windows/Linux locale packs. Keep the English variants on every platform.+ electronLanguages: ['en', 'en_GB', 'en_US', 'en-GB', 'en-US'],files: ['dist',diff --git a/apps/desktop/module-deps.config.mjs b/apps/desktop/module-deps.config.mjsindex 1e2e9e00bf4..bbbb0074a6b 100644--- a/apps/desktop/module-deps.config.mjs+++ b/apps/desktop/module-deps.config.mjs@@ -10,9 +10,15 @@ const sourceNodeModules = path.join(__dirname, 'node_modules');* @param {string} moduleName - The module to resolve* @param {Set<string>} visited - Set of already visited modules* @param {string} nodeModulesPath - Path to node_modules directory+ * @param {{skipOptionalDependenciesFor?: Set<string>}} options - Dependency traversal options* @returns {Set<string>} Set of all dependencies*/-function resolveDependencies(moduleName, visited = new Set(), nodeModulesPath = sourceNodeModules) {+function resolveDependencies(+ moduleName,+ visited = new Set(),+ nodeModulesPath = sourceNodeModules,+ options = {},+) {if (visited.has(moduleName)) {return visited;}@@ -33,11 +39,13 @@ function resolveDependencies(moduleName, visited = new Set(), nodeModulesPath =const optionalDependencies = packageJson.optionalDependencies || {};for (const dep of Object.keys(dependencies)) {- resolveDependencies(dep, visited, nodeModulesPath);+ resolveDependencies(dep, visited, nodeModulesPath, options);}- for (const dep of Object.keys(optionalDependencies)) {- resolveDependencies(dep, visited, nodeModulesPath);+ if (!options.skipOptionalDependenciesFor?.has(moduleName)) {+ for (const dep of Object.keys(optionalDependencies)) {+ resolveDependencies(dep, visited, nodeModulesPath, options);+ }}} catch {// Ignore unreadable package.json files; electron-builder will surface any@@ -50,13 +58,14 @@ function resolveDependencies(moduleName, visited = new Set(), nodeModulesPath =/*** Get all transitive dependencies for a set of top-level modules.* @param {string[]} modules+ * @param {{skipOptionalDependenciesFor?: Set<string>}} options* @returns {string[]}*/-export function getDependenciesForModules(modules) {+export function getDependenciesForModules(modules, options = {}) {const allDeps = new Set();for (const moduleName of modules) {- const deps = resolveDependencies(moduleName);+ const deps = resolveDependencies(moduleName, new Set(), sourceNodeModules, options);for (const dep of deps) {allDeps.add(dep);}@@ -65,24 +74,16 @@ export function getDependenciesForModules(modules) {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+ * @param {{skipOptionalDependenciesFor?: Set<string>}} options* @returns {Array<{from: string, to: string, filter: string[]}>}*/-export function getModuleFilesConfig(modules) {- return getDependenciesForModules(modules).map((dep) => ({- filter: ['**/*'],+export function getModuleFilesConfig(modules, options = {}) {+ return getDependenciesForModules(modules, options).map((dep) => ({+ filter: ['**/*', '!**/*.map'],from: `node_modules/${dep}`,to: `node_modules/${dep}`,}));@@ -93,9 +94,10 @@ export function getModuleFilesConfig(modules) {* electron-builder can include them via file rules.* @param {string[]} modules* @param {string} label+ * @param {{skipOptionalDependenciesFor?: Set<string>}} options*/-export async function copyModulesToSource(modules, label) {- const deps = getDependenciesForModules(modules);+export async function copyModulesToSource(modules, label, options = {}) {+ const deps = getDependenciesForModules(modules, options);console.info(`π¦ Resolving ${deps.length} ${label} symlinks for packaging...`);@@ -121,43 +123,6 @@ export async function copyModulesToSource(modules, label) {console.info(`β ${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.info(`π¦ 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.info(` π ${dep} (symlink -> ${path.relative(sourceNodeModules, realPath)})`);-- await fs.promises.mkdir(path.dirname(destPath), { recursive: true });- await copyDir(realPath, destPath);- } else if (stat.isDirectory()) {- console.info(` π ${dep}`);- await fs.promises.mkdir(path.dirname(destPath), { recursive: true });- await copyDir(sourcePath, destPath);- }- } catch (err) {- console.info(` βοΈ ${dep} (skipped: ${err.code || err.message})`);- }- }-- console.info(`β ${label} copied successfully`);-}-/*** Recursively copy a directory.* @param {string} srcdiff --git a/apps/desktop/native-deps.config.mjs b/apps/desktop/native-deps.config.mjsindex 5ca0f6747a5..17c0db75036 100644--- a/apps/desktop/native-deps.config.mjs+++ b/apps/desktop/native-deps.config.mjs@@ -11,11 +11,9 @@import os from 'node:os';import {- copyModulesToDirectory,copyModulesToSource,getDependenciesForModules,getModuleFilesConfig,- getModuleFilesPatterns,} from './module-deps.config.mjs';/**@@ -28,6 +26,11 @@ function getTargetPlatform() {}const isDarwin = getTargetPlatform() === 'darwin';+// The packaged macOS runtime invokes get-windows' native helper directly.+// Its optional dependencies are build/install tooling and the Windows loader+// chain, neither of which is required in a macOS application artifact.+const dependencyOptions = isDarwin ? { skipOptionalDependenciesFor: new Set(['get-windows']) } : {};+/*** List of native modules that need special handling* Only add the top-level native modules here - dependencies are resolved automatically@@ -48,15 +51,7 @@ export const nativeModules = [* @returns {string[]} Array of all dependency names*/export function getAllNativeDependencies() {- return getDependenciesForModules(nativeModules);-}--/**- * Generate glob patterns for electron-builder files config- * @returns {string[]} Array of glob patterns- */-export function getNativeModuleFilesPatterns() {- return getModuleFilesPatterns(nativeModules);+ return getDependenciesForModules(nativeModules, dependencyOptions);}/**@@ -65,7 +60,7 @@ export function getNativeModuleFilesPatterns() {* @returns {Array<{from: string, to: string, filter: string[]}>}*/export function getNativeModulesFilesConfig() {- return getModuleFilesConfig(nativeModules);+ return getModuleFilesConfig(nativeModules, dependencyOptions);}/**@@ -73,7 +68,14 @@ export function getNativeModulesFilesConfig() {* @returns {string[]} Array of glob patterns*/export function getAsarUnpackPatterns() {- return getNativeModuleFilesPatterns();+ return [+ 'node_modules/@lydell/node-pty-*/prebuilds/**/*.node',+ 'node_modules/@lydell/node-pty-*/prebuilds/*/spawn-helper',+ 'node_modules/@napi-rs/canvas-*/*.node',+ 'node_modules/get-windows/main',+ 'node_modules/node-mac-permissions/build/Release/permissions.node',+ 'node_modules/node-screenshots-*/*.node',+ ];}/**@@ -90,14 +92,5 @@ export function getNativeExternalDependencies() {* included in the asar archive (electron-builder glob doesn't follow symlinks).*/export async function copyNativeModulesToSource() {- await copyModulesToSource(nativeModules, 'native module');-}--/**- * Copy native modules to destination, resolving symlinks- * This is used in afterPack hook to handle pnpm symlinks correctly- * @param {string} destNodeModules - Destination node_modules path- */-export async function copyNativeModules(destNodeModules) {- await copyModulesToDirectory(nativeModules, destNodeModules, 'native modules');+ await copyModulesToSource(nativeModules, 'native module', dependencyOptions);}diff --git a/apps/desktop/src/main/modules/screenCapture/WindowSourceService.test.ts b/apps/desktop/src/main/modules/screenCapture/WindowSourceService.test.tsindex 08f7f7c06f9..5c1a74bb528 100644--- a/apps/desktop/src/main/modules/screenCapture/WindowSourceService.test.ts+++ b/apps/desktop/src/main/modules/screenCapture/WindowSourceService.test.ts@@ -2,14 +2,25 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const mockWindows = vi.fn();const mockOpenWindowsSync = vi.fn();+const mockExecFileSync = vi.fn();+const mockElectronApp = vi.hoisted(() => ({ isPackaged: false }));const originalPlatform = process.platform;+const originalResourcesPath = process.resourcesPath;vi.mock('electron', () => ({app: {getName: vi.fn(() => 'LobeHub'),+ get isPackaged() {+ return mockElectronApp.isPackaged;+ },},}));+vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ execFileSync: mockExecFileSync,+}));+vi.mock('node-screenshots', () => ({Window: {all: mockWindows,@@ -23,7 +34,34 @@ vi.mock('get-windows', () => ({describe('WindowSourceService', () => {beforeEach(() => {vi.clearAllMocks();+ mockElectronApp.isPackaged = false;Object.defineProperty(process, 'platform', { value: originalPlatform });+ Object.defineProperty(process, 'resourcesPath', {+ configurable: true,+ value: originalResourcesPath,+ });+ });++ it('executes the unpacked get-windows helper in packaged macOS builds', async () => {+ Object.defineProperty(process, 'platform', { value: 'darwin' });+ Object.defineProperty(process, 'resourcesPath', {+ configurable: true,+ value: '/Applications/LobeHub.app/Contents/Resources',+ });+ mockElectronApp.isPackaged = true;+ mockExecFileSync.mockReturnValue(JSON.stringify([{ owner: { processId: 42 } }]));+ mockWindows.mockReturnValue([]);++ const { enumerateWindows } = await import('./WindowSourceService');++ await enumerateWindows({ height: 1080, width: 1920, x: 0, y: 0 });++ expect(mockExecFileSync).toHaveBeenCalledWith(+ '/Applications/LobeHub.app/Contents/Resources/app.asar.unpacked/node_modules/get-windows/main',+ ['--no-accessibility-permission', '--no-screen-recording-permission', '--open-windows-list'],+ { encoding: 'utf8' },+ );+ expect(mockOpenWindowsSync).not.toHaveBeenCalled();});it('normalizes window geometry to display DIPs on Windows high-DPI displays', async () => {diff --git a/apps/desktop/src/main/modules/screenCapture/WindowSourceService.ts b/apps/desktop/src/main/modules/screenCapture/WindowSourceService.tsindex e09c5245a61..94f5818fa98 100644--- a/apps/desktop/src/main/modules/screenCapture/WindowSourceService.ts+++ b/apps/desktop/src/main/modules/screenCapture/WindowSourceService.ts@@ -1,6 +1,8 @@+import { execFileSync } from 'node:child_process';+import path from 'node:path';+import type { ScreenCaptureWindowInfo } from '@lobechat/electron-client-ipc';import { app } from 'electron';-import { openWindowsSync } from 'get-windows';import { Window } from 'node-screenshots';import { createLogger } from '@/utils/logger';@@ -40,6 +42,37 @@ interface WindowWithOptionalScaleFactor {scaleFactor?: () => number;}+async function openWindowsForCapture(): Promise<Array<{ owner: { processId: number } }>> {+ if (process.platform !== 'darwin' || !app.isPackaged) {+ // Keep the cross-platform JavaScript loader available during development+ // and for Windows/Linux builds, but do not load its Windows installation+ // dependency chain at startup in a packaged macOS application.+ const { openWindowsSync } = await import('get-windows');+ return openWindowsSync({+ accessibilityPermission: false,+ screenRecordingPermission: false,+ });+ }++ // child_process does not redirect executable paths from app.asar to+ // app.asar.unpacked. Resolve the packaged macOS helper explicitly so only+ // that executable, rather than get-windows' optional install chain, ships.+ const binary = path.join(+ process.resourcesPath,+ 'app.asar.unpacked',+ 'node_modules',+ 'get-windows',+ 'main',+ );+ const stdout = execFileSync(+ binary,+ ['--no-accessibility-permission', '--no-screen-recording-permission', '--open-windows-list'],+ { encoding: 'utf8' },+ );++ return JSON.parse(stdout) as Array<{ owner: { processId: number } }>;+}+function intersects(a: DisplayBounds, b: DisplayBounds): boolean {return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;}@@ -73,10 +106,7 @@ export async function enumerateWindows(let visiblePids: Set<number> | undefined;try {- const visible = openWindowsSync({- accessibilityPermission: false,- screenRecordingPermission: false,- });+ const visible = await openWindowsForCapture();visiblePids = new Set(visible.map((w) => w.owner.processId));} catch (error) {logger.warn('get-windows unavailable, skipping whitelist filter:', error);diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.tsindex 231ed7bdc4b..3c4dc8f58a3 100644--- a/apps/desktop/vite.renderer.config.ts+++ b/apps/desktop/vite.renderer.config.ts@@ -1,4 +1,5 @@import { readFileSync } from 'node:fs';+import { rm } from 'node:fs/promises';import path from 'node:path';import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';@@ -23,6 +24,27 @@ import {ROOT_DIR,} from './vite.shared';+const RENDERER_OUT_DIR = path.resolve(__dirname, 'dist/renderer');+const WEB_SPA_BUILD_DIRECTORIES = ['_spa', '_spa-auth'];++/**+ * The repository public directory can contain ignored web build outputs after+ * local SPA builds. Vite copies the whole directory by default, so remove only+ * those generated web outputs from the generated desktop renderer directory.+ */+function excludeWebSpaBuildArtifactsPlugin(): PluginOption {+ return {+ async closeBundle() {+ await Promise.all(+ WEB_SPA_BUILD_DIRECTORIES.map((directory) =>+ rm(path.join(RENDERER_OUT_DIR, directory), { force: true, recursive: true }),+ ),+ );+ },+ name: 'exclude-web-spa-build-artifacts',+ };+}+/*** Rewrite SPA routes to their corresponding HTML entry so the Vite* dev server serves the right HTML when root is the monorepo root.@@ -197,9 +219,9 @@ export default defineConfig(async (env) => {// regardless of URL depth.base: '/',build: {- minify: false,+ minify: true,modulePreload: { polyfill: false },- outDir: path.resolve(__dirname, 'dist/renderer'),+ outDir: RENDERER_OUT_DIR,reportCompressedSize: false,rolldownOptions: {input: {@@ -209,6 +231,7 @@ export default defineConfig(async (env) => {},output: sharedRollupOutput,},+ sourcemap: false,target: RENDERER_CHROME_TARGET,},define: {@@ -222,6 +245,7 @@ export default defineConfig(async (env) => {isCloudDesktop && cloudTsconfigPathsPlugin(),isCloudDesktop && cloudDesktopBusinessConstPlugin(),electronDesktopHtmlPlugin(),+ excludeWebSpaBuildArtifactsPlugin(),vanillaExtractPlugin(),...(sharedRendererPlugins({ platform: 'desktop' }) as PluginOption[]),],