Skip to content

A full-featured download manager.

feat: add lightweight desktop mode (#1917)

Dr_rOote0aff26a061d
diff --git a/.claude/rules/electron-vite.md b/.claude/rules/electron-vite.md
index a89e7e76..b32254cd 100644
--- a/.claude/rules/electron-vite.md
+++ b/.claude/rules/electron-vite.md
@@ -1,6 +1,6 @@
---
description: Build outputs, Electron loading policy, pnpm scripts, and native ABI boundaries
-paths: ["electron-builder.json", "pnpm-workspace.yaml", "package.json", "Dockerfile", "vite.*.config.ts", "scripts/dev.mjs", "scripts/postinstall.mjs", "scripts/ensure-native-abi.mjs", "scripts/native-binary-target.mjs", "scripts/stage-*-app.mjs", "scripts/verify-*-package.mjs", "scripts/before-*-*.mjs", "src/main/index.ts", "src/main/window/renderer-url-policy*", "src/main/window/window-manager*", "src/preload/**"]
+paths: ["electron-builder.json", "pnpm-workspace.yaml", "package.json", "Dockerfile", "vite.*.config.ts", "scripts/dev.mjs", "scripts/postinstall.mjs", "scripts/ensure-electron-runtime.mjs", "scripts/ensure-native-abi.mjs", "scripts/native-binary-target.mjs", "scripts/stage-*-app.mjs", "scripts/verify-*-package.mjs", "scripts/before-*-*.mjs", "src/main/index.ts", "src/main/window/renderer-url-policy*", "src/main/window/window-manager*", "src/preload/**"]
---
# Electron + Vite
@@ -44,8 +44,10 @@ and packaged-file checks.
- Install-script permission is controlled by pnpm 11 `allowBuilds`. Keep
`electron` allowed for compatibility, but do not rely on `pnpm install` to
hydrate Electron 43: it exposes `install.js` as a package bin without a
- `postinstall` script. Packaging and legal-check workflows must explicitly
- run `node node_modules/electron/install.js` before consuming `dist/`.
+ `postinstall` script. Local workflows that consume Electron or its licenses
+ must run `pnpm run ensure:electron-runtime` first; that command validates the
+ entire payload and repairs partial installs safely. CI/container workflows
+ may invoke `install.js` directly when they immediately validate the result.
- Native modules such as `better-sqlite3` must match the active ABI. Tests use
the Node ABI; Electron and E2E use the Electron ABI. Preserve the
`ensure-native-abi.mjs` hooks when changing test or start scripts.
diff --git a/.gitignore b/.gitignore
index d8a35e15..dc83e536 100644
--- a/.gitignore
+++ b/.gitignore
@@ -78,6 +78,9 @@ typings/
# vuepress build output
.vuepress/dist
+# Local generated analysis and report artifacts
+/outputs/
+
# Serverless directories
.serverless/
diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts
index 914a17d6..cc4ba92c 100644
--- a/e2e/global-setup.ts
+++ b/e2e/global-setup.ts
@@ -15,6 +15,30 @@ const REQUIRED_ARTIFACTS = [
]
export default async function globalSetup() {
+ // Keep direct `pnpm exec playwright ...` invocations safe as well as the
+ // package scripts: existing build artifacts do not prove that pnpm left the
+ // Electron runtime (including its legal files) fully hydrated.
+ const electronRuntime = spawnSync(
+ 'pnpm',
+ ['run', 'ensure:electron-runtime'],
+ {
+ stdio: 'inherit',
+ cwd: ROOT,
+ shell: process.platform === 'win32',
+ }
+ )
+ if (electronRuntime.error) throw electronRuntime.error
+ if (electronRuntime.signal) {
+ throw new Error(
+ `Electron runtime check was killed by ${electronRuntime.signal}`
+ )
+ }
+ if (electronRuntime.status !== 0) {
+ throw new Error(
+ `Electron runtime check exited with status ${electronRuntime.status ?? 'unknown'}`
+ )
+ }
+
const missing = REQUIRED_ARTIFACTS.filter(
(rel) => !existsSync(path.join(ROOT, rel))
)
diff --git a/e2e/lightweight-mode.spec.ts b/e2e/lightweight-mode.spec.ts
new file mode 100644
index 00000000..7f819601
--- /dev/null
+++ b/e2e/lightweight-mode.spec.ts
@@ -0,0 +1,139 @@
+import { writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import type { ElectronApplication, Page } from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
+import { RunMode } from '../src/shared/constants'
+import {
+ expect,
+ findAddTaskWindow,
+ launchMotrix,
+ test,
+} from './fixtures/electron-app'
+
+async function waitForMainWindow(
+ electronApp: ElectronApplication
+): Promise<Page> {
+ const pagePromise = electronApp.waitForEvent('window')
+ await electronApp.evaluate(({ app }) => {
+ app.emit('activate')
+ })
+ const page = await pagePromise
+ await page.waitForLoadState('domcontentloaded')
+ await expect.poll(() => page.url()).toContain('w=main')
+ return page
+}
+
+async function closeMainWindow(
+ electronApp: ElectronApplication
+): Promise<void> {
+ await electronApp.evaluate(({ BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ main?.close()
+ })
+ await expect
+ .poll(() =>
+ electronApp.evaluate(
+ ({ BrowserWindow }) => BrowserWindow.getAllWindows().length
+ )
+ )
+ .toBe(0)
+}
+
+async function closeMainThroughRenderer(
+ electronApp: ElectronApplication,
+ mainWindow: Page
+): Promise<void> {
+ await mainWindow.evaluate(() => {
+ const api = (
+ window as unknown as {
+ motrix: { invoke: (channel: string) => Promise<unknown> }
+ }
+ ).motrix
+ // The window is expected to disappear before the invoke response can be
+ // observed, so attach a rejection handler and assert the host-side result.
+ void api.invoke('command:closeCurrentWindow').catch(() => {})
+ })
+ await expect
+ .poll(() =>
+ electronApp.evaluate(
+ ({ BrowserWindow }) => BrowserWindow.getAllWindows().length
+ )
+ )
+ .toBe(0)
+}
+
+test.describe('lightweight mode', () => {
+ test('stays renderer-free in the background and recreates windows on demand', async ({
+ userDataDir,
+ rpcPort,
+ }) => {
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ onboarding: { disclaimerAccepted: true },
+ app: {
+ lightweightMode: true,
+ runMode: RunMode.TrayOnly,
+ },
+ }),
+ 'utf8'
+ )
+
+ const electronApp = await launchMotrix({ userDataDir, rpcPort })
+ try {
+ // Waiting for the menu proves main-process initialization has passed the
+ // legal gate. Waiting beyond the historical add-task prewarm delay then
+ // proves lightweight startup did not allocate either renderer window.
+ await expect
+ .poll(() =>
+ electronApp.evaluate(({ Menu }) => Boolean(Menu.getApplicationMenu()))
+ )
+ .toBe(true)
+ await electronApp.evaluate(
+ () => new Promise((resolve) => setTimeout(resolve, 2_500))
+ )
+ expect(electronApp.windows()).toHaveLength(0)
+
+ const firstMain = await waitForMainWindow(electronApp)
+ const settings = await firstMain.evaluate(async () => {
+ const api = (
+ window as unknown as {
+ motrix: { invoke: (channel: string) => Promise<unknown> }
+ }
+ ).motrix
+ return api.invoke('query:getSettings') as Promise<{
+ app: { lightweightMode: boolean }
+ }>
+ })
+ expect(settings.app.lightweightMode).toBe(true)
+
+ await closeMainThroughRenderer(electronApp, firstMain)
+
+ const secondMain = await waitForMainWindow(electronApp)
+ await expect(
+ secondMain.getByRole('heading', { name: 'Dashboard' })
+ ).toBeVisible()
+ await closeMainWindow(electronApp)
+
+ const magnetUri =
+ 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
+ await electronApp.evaluate(({ app }, uri) => {
+ app.emit(
+ 'open-url',
+ { preventDefault: () => undefined } as Electron.Event,
+ uri
+ )
+ }, magnetUri)
+
+ const addTask = await findAddTaskWindow(electronApp)
+ await expect(addTask.getByRole('textbox', { name: 'URLs' })).toHaveValue(
+ magnetUri
+ )
+ } finally {
+ await electronApp.close().catch(() => {})
+ }
+ })
+})
diff --git a/package.json b/package.json
index dbd800d5..3402be13 100644
--- a/package.json
+++ b/package.json
@@ -15,13 +15,14 @@
"main": "dist/main/index.cjs",
"private": true,
"scripts": {
- "prestart": "node scripts/ensure-native-abi.mjs electron",
+ "ensure:electron-runtime": "node scripts/ensure-electron-runtime.mjs",
+ "prestart": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron",
"start": "node scripts/dev.mjs",
"build": "pnpm run build:builtin && pnpm run build:native-host && pnpm build:electron",
"build:electron": "pnpm run build:legal && node scripts/ensure-native-abi.mjs electron && vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.config.ts",
"stage:electron": "node scripts/stage-electron-app.mjs",
"verify:electron-package": "node scripts/verify-electron-package.mjs",
- "smoke:electron-package": "node scripts/smoke-electron-package.mjs",
+ "smoke:electron-package": "pnpm run ensure:electron-runtime && node scripts/smoke-electron-package.mjs",
"build:server": "pnpm run build:builtin && pnpm run build:legal && vite build --config vite.server.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.web.config.ts",
"stage:server": "node scripts/stage-server-app.mjs",
"verify:server-package": "node scripts/verify-server-package.mjs",
@@ -30,7 +31,7 @@
"measure:server-images": "node scripts/measure-server-images.mjs",
"build:builtin": "node scripts/fetch-builtins.mjs",
"build:native-host": "node packages/native-host/build.mjs",
- "build:legal": "node scripts/generate-third-party-notices.mjs",
+ "build:legal": "pnpm run ensure:electron-runtime && node scripts/generate-third-party-notices.mjs",
"package:flatpak-native-host": "node packages/native-host/package-flatpak-companion.mjs",
"build:snap:prepare": "node scripts/prepare-snap-project.mjs",
"build:mac-arm64": "pnpm run build:builtin && pnpm run build:native-host -- --platform darwin --arch arm64 && pnpm run build:electron",
@@ -40,9 +41,9 @@
"check:file-names": "node scripts/check-file-names.mjs",
"check:flatpak": "node scripts/verify-flatpak-packaging.mjs",
"check:i18n": "node --import tsx scripts/check-i18n.mjs",
- "check:registry-runtime": "node scripts/check-registry-electron-runtime.mjs",
+ "check:registry-runtime": "pnpm run ensure:electron-runtime && node scripts/check-registry-electron-runtime.mjs",
"check:schema-parity": "node scripts/check-schema-parity.mjs",
- "check:third-party-notices": "node scripts/generate-third-party-notices.mjs --check && vitest run tests/check-third-party-notices.test.ts tests/generate-third-party-notices.test.ts",
+ "check:third-party-notices": "pnpm run ensure:electron-runtime && node scripts/generate-third-party-notices.mjs --check && vitest run tests/check-third-party-notices.test.ts tests/generate-third-party-notices.test.ts",
"check:update-artifacts": "node scripts/verify-update-artifacts.mjs",
"check:snap": "node scripts/verify-snap-artifact.mjs",
"check:snap-store": "node scripts/verify-snap-store-channel.mjs",
@@ -62,11 +63,11 @@
"test": "vitest run",
"pretest:watch": "node scripts/ensure-native-abi.mjs node",
"test:watch": "vitest",
- "pretest:e2e": "node scripts/ensure-native-abi.mjs electron",
+ "pretest:e2e": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron",
"test:e2e": "playwright test",
- "pretest:e2e:ui": "node scripts/ensure-native-abi.mjs electron",
+ "pretest:e2e:ui": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron",
"test:e2e:ui": "playwright test --ui",
- "pretest:e2e:debug": "node scripts/ensure-native-abi.mjs electron",
+ "pretest:e2e:debug": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron",
"test:e2e:debug": "PWDEBUG=1 playwright test",
"postinstall": "node scripts/postinstall.mjs",
"fetch:engine": "node scripts/fetch-engine.mjs",
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 0420a868..feb9a4a0 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -12,7 +12,8 @@ nodeLinker: hoisted
# ignoredBuiltDependencies — packages not listed have their scripts skipped):
# - electron: retained for compatibility with releases that expose an
# install script. Electron 43 only exposes install.js as a package bin, so
-# packaging and legal-check workflows must hydrate dist/ explicitly.
+# local consumers must use ensure:electron-runtime to validate and hydrate
+# dist/ before reading runtime files.
# - better-sqlite3: native module rebuilt against the pinned ABI.
# - electron-winstaller / esbuild: harmless arch-selection scripts, allowed
# to keep installs warning-free (esbuild binaries ship via @esbuild/*
diff --git a/scripts/ensure-electron-runtime.mjs b/scripts/ensure-electron-runtime.mjs
new file mode 100644
index 00000000..da2c8d84
--- /dev/null
+++ b/scripts/ensure-electron-runtime.mjs
@@ -0,0 +1,263 @@
+#!/usr/bin/env node
+
+import { spawnSync } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { existsSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const require = createRequire(import.meta.url)
+
+export const REQUIRED_ELECTRON_RUNTIME_FILES = [
+ 'dist/LICENSE',
+ 'dist/LICENSES.chromium.html',
+ 'dist/version',
+ 'path.txt',
+]
+
+const defaultFs = {
+ existsSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+}
+
+function readTrimmed(filePath, fs = defaultFs) {
+ try {
+ return fs.readFileSync(filePath, 'utf8').trim()
+ } catch {
+ return null
+ }
+}
+
+function isNonEmptyFile(filePath, fs = defaultFs) {
+ try {
+ const stat = fs.statSync(filePath)
+ return stat.isFile() && stat.size > 0
+ } catch {
+ return false
+ }
+}
+
+export function inspectElectronRuntime(electronPackageDir, fs = defaultFs) {
+ const issues = []
+ const manifestPath = path.join(electronPackageDir, 'package.json')
+ let expectedVersion = null
+
+ try {
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
+ expectedVersion =
+ typeof manifest.version === 'string' ? manifest.version : null
+ } catch {
+ issues.push('package.json is missing or invalid')
+ }
+
+ for (const relativePath of REQUIRED_ELECTRON_RUNTIME_FILES) {
+ if (!isNonEmptyFile(path.join(electronPackageDir, relativePath), fs)) {
+ issues.push(`${relativePath} is missing or empty`)
+ }
+ }
+
+ const installedVersion = readTrimmed(
+ path.join(electronPackageDir, 'dist', 'version'),
+ fs
+ )?.replace(/^v/, '')
+ if (
+ expectedVersion &&
+ installedVersion &&
+ installedVersion !== expectedVersion
+ ) {
+ issues.push(
+ `dist/version is ${installedVersion}, expected ${expectedVersion}`
+ )
+ }
+
+ const executableRelativePath = readTrimmed(
+ path.join(electronPackageDir, 'path.txt'),
+ fs
+ )
+ if (executableRelativePath) {
+ const distDir = path.resolve(electronPackageDir, 'dist')
+ const executablePath = path.resolve(distDir, executableRelativePath)
+ const relativeToDist = path.relative(distDir, executablePath)
+ if (
+ relativeToDist.startsWith('..') ||
+ path.isAbsolute(relativeToDist) ||
+ !isNonEmptyFile(executablePath, fs)
+ ) {
+ issues.push(`Electron executable is missing: ${executableRelativePath}`)
+ }
+ }
+
+ return {
+ complete: issues.length === 0,
+ expectedVersion,
+ issues,
+ }
+}
+
+function moveAside(targetPath, fs = defaultFs) {
+ if (!fs.existsSync(targetPath)) return null
+ const backupPath = `${targetPath}.motrix-backup-${randomUUID()}`
+ fs.renameSync(targetPath, backupPath)
+ return backupPath
+}
+
+function removeIfPresent(targetPath, fs = defaultFs) {
+ if (!targetPath) return
+ if (fs.existsSync(targetPath)) {
+ fs.rmSync(targetPath, { force: true, recursive: true })
+ }
+}
+
+function restoreBackup(targetPath, backupPath, hadOriginal, fs = defaultFs) {
+ if (!hadOriginal) {
+ removeIfPresent(targetPath, fs)
+ return
+ }
+
+ // Do not delete an original payload when moving it aside failed before a
+ // backup path could be recorded, or when the backup unexpectedly vanished.
+ if (!backupPath) {
+ if (fs.existsSync(targetPath)) return
+ throw new Error(`backup is unavailable for ${targetPath}`)
+ }
+ if (!fs.existsSync(backupPath)) {
+ throw new Error(`backup is unavailable for ${targetPath}`)
+ }
+
+ removeIfPresent(targetPath, fs)
+ fs.renameSync(backupPath, targetPath)
+}
+
+function removeBackupBestEffort(backupPath, fs, logError) {
+ try {
+ removeIfPresent(backupPath, fs)
+ } catch (error) {
+ logError(
+ `[ensure-electron-runtime] repaired runtime is valid, but its temporary backup could not be removed: ${error?.message ?? error}`
+ )
+ }
+}
+
+export function resolveElectronPackageDir() {
+ return path.dirname(require.resolve('electron'))
+}
+
+export function ensureElectronRuntime(options = {}) {
+ const fs = options.fs ?? defaultFs
+ const spawn = options.spawn ?? spawnSync
+ const log = options.log ?? console.log
+ const logError = options.logError ?? console.error
+ let electronPackageDir
+
+ try {
+ electronPackageDir =
+ options.electronPackageDir ?? resolveElectronPackageDir()
+ } catch (error) {
+ logError(
+ `[ensure-electron-runtime] Electron package is unavailable; run pnpm install first: ${error?.message ?? error}`
+ )
+ return 1
+ }
+
+ const before = inspectElectronRuntime(electronPackageDir, fs)
+ if (before.complete) {
+ log(
+ `[ensure-electron-runtime] Electron ${before.expectedVersion ?? ''} runtime is complete`
+ )
+ return 0
+ }
+
+ const installerPath = path.join(electronPackageDir, 'install.js')
+ if (!isNonEmptyFile(installerPath, fs)) {
+ logError(
+ `[ensure-electron-runtime] Electron installer is missing: ${installerPath}`
+ )
+ return 1
+ }
+
+ log(
+ `[ensure-electron-runtime] repairing incomplete Electron runtime: ${before.issues.join('; ')}`
+ )
+
+ const distPath = path.join(electronPackageDir, 'dist')
+ const pathFile = path.join(electronPackageDir, 'path.txt')
+ const hadDist = fs.existsSync(distPath)
+ const hadPathFile = fs.existsSync(pathFile)
+ let distBackup = null
+ let pathBackup = null
+
+ try {
+ // Electron 43's installer returns early when dist/version + the binary
+ // look valid, even if runtime license files are missing. Move the entire
+ // generated payload aside so every incomplete state gets a clean repair.
+ distBackup = moveAside(distPath, fs)
+ pathBackup = moveAside(pathFile, fs)
+
+ const result = spawn(process.execPath, [installerPath], {
+ env: options.env ?? process.env,
+ stdio: 'inherit',
+ })
+ if (result.error) {
+ throw result.error
+ }
+ if (result.signal) {
+ throw new Error(`Electron installer was killed by ${result.signal}`)
+ }
+ if (result.status !== 0) {
+ const error = new Error(
+ `Electron installer exited with status ${result.status ?? 'unknown'}`
+ )
+ error.exitCode = result.status ?? 1
+ throw error
+ }
+
+ const after = inspectElectronRuntime(electronPackageDir, fs)
+ if (!after.complete) {
+ throw new Error(
+ `Electron installer completed without a valid runtime: ${after.issues.join('; ')}`
+ )
+ }
+
+ // Cleanup is deliberately best-effort. Once the repaired runtime has been
+ // validated, a backup cleanup error must not roll back working files.
+ removeBackupBestEffort(distBackup, fs, logError)
+ removeBackupBestEffort(pathBackup, fs, logError)
+ log(
+ `[ensure-electron-runtime] Electron ${after.expectedVersion ?? ''} runtime repaired`
+ )
+ return 0
+ } catch (error) {
+ const restoreErrors = []
+ for (const [targetPath, backupPath, hadOriginal] of [
+ [distPath, distBackup, hadDist],
+ [pathFile, pathBackup, hadPathFile],
+ ]) {
+ try {
+ restoreBackup(targetPath, backupPath, hadOriginal, fs)
+ } catch (restoreError) {
+ restoreErrors.push(restoreError?.message ?? String(restoreError))
+ }
+ }
+ if (restoreErrors.length > 0) {
+ logError(
+ `[ensure-electron-runtime] failed to fully restore the previous runtime after repair failure: ${restoreErrors.join('; ')}`
+ )
+ }
+ logError(
+ `[ensure-electron-runtime] repair failed: ${error?.message ?? error}`
+ )
+ return Number.isInteger(error?.exitCode) ? error.exitCode : 1
+ }
+}
+
+const invokedAsMain =
+ process.argv[1] != null &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+
+if (invokedAsMain) {
+ process.exit(ensureElectronRuntime())
+}
diff --git a/src/core/settings/migrations.ts b/src/core/settings/migrations.ts
index fe5bc19b..15592b5c 100644
--- a/src/core/settings/migrations.ts
+++ b/src/core/settings/migrations.ts
@@ -46,7 +46,7 @@ function migrateV2ToV3(data: Record<string, unknown>): Record<string, unknown> {
app: {
...app,
runMode: app.runMode ?? 1,
- traySpeedometer: app.traySpeedometer ?? false,
+ traySpeedometer: app.traySpeedometer ?? true,
},
}
}
diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.ts
index 26e54198..34df4e33 100644
--- a/src/core/settings/settings-manager.test.ts
+++ b/src/core/settings/settings-manager.test.ts
@@ -932,7 +932,7 @@ describe('SettingsManager', () => {
it('applies default values for new tray fields', async () => {
const app = manager.getApp()
expect(app.runMode).toBe(1) // RunMode.Standard
- expect(app.traySpeedometer).toBe(false)
+ expect(app.traySpeedometer).toBe(true)
})
})
diff --git a/src/main/index.ts b/src/main/index.ts
index 134b30b2..b4eab6f3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -97,7 +97,7 @@ import {
TrackerSyncer,
} from '@core/tracker'
import type { NatManager } from '@motrix/nat'
-import { APP_ID, RunMode } from '@shared/constants'
+import { APP_ID } from '@shared/constants'
import { DEFAULT_LOCALE, type SupportedLocale } from '@shared/constants/locales'
import { Events } from '@shared/protocol/events'
import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'
@@ -154,6 +154,7 @@ import { createOsNotificationBridge } from './notifications/os-bridge'
import { DisclaimerGate } from './onboarding/disclaimer-gate'
import { setupAppImageIntegration } from './platform/appimage-integration-host'
import { syncAutoLaunch } from './platform/auto-launch'
+import { resolveDesktopBackgroundPolicy } from './platform/desktop-background-policy'
import { removePathRecursive, renameAtomic } from './platform/fs-helpers'
import { setupNativeThemeSync } from './platform/native-theme-sync'
import { setupPowerManager } from './platform/power-manager'
@@ -176,6 +177,7 @@ import {
} from './window/liquid-glass'
import { initializeRendererUrlPolicy } from './window/renderer-url-policy'
import { WindowManager } from './window/window-manager'
+import { resolveMainWindowStartupPlan } from './window/window-startup-plan'
// ─── Platform Early Setup ───────────────────────────────
@@ -314,6 +316,15 @@ const settingsManager = new SettingsManager(settingsPath, {
) {
setTimeout(() => windowManager?.recreate('main'), 100)
}
+ if (
+ windowManager &&
+ (old.app.lightweightMode !== updated.app.lightweightMode ||
+ old.app.runMode !== updated.app.runMode)
+ ) {
+ // Let the settings IPC response reach its renderer before a newly
+ // enabled policy is allowed to release any hidden window.
+ setTimeout(() => windowManager?.reconcileWindowRetention(), 100)
+ }
if (
speedLimitController &&
JSON.stringify(old.speedLimit) !== JSON.stringify(updated.speedLimit)
@@ -1380,6 +1391,17 @@ async function initializeMainProcess(): Promise<void> {
? 'onboarding'
: requested,
onSessionEnd: prepareForSessionEnd,
+ retentionPolicy: {
+ releaseMainOnDismiss: () => {
+ const appSettings = settingsManager.getApp()
+ return resolveDesktopBackgroundPolicy({
+ lightweightMode: appSettings.lightweightMode,
+ platform: process.platform,
+ runMode: appSettings.runMode,
+ }).releaseMainWindowWhenHidden
+ },
+ prewarmAddTask: () => !settingsManager.getApp().lightweightMode,
+ },
})
// Apply the persisted theme before opening windows. Renderer-drawn Windows
// controls inherit the same theme through CSS without native overlay sync.
@@ -1416,9 +1438,19 @@ async function initializeMainProcess(): Promise<void> {
if (gate.isAccepted()) {
const runMode = settingsManager.getApp().runMode
- windowManager.open('main', {
- show: !launcher.wasOpenedAtLogin && runMode !== RunMode.TrayOnly,
+ const backgroundPolicy = resolveDesktopBackgroundPolicy({
+ lightweightMode: settingsManager.getApp().lightweightMode,
+ platform: process.platform,
+ runMode,
})
+ const mainWindowPlan = resolveMainWindowStartupPlan({
+ openedAtLogin: launcher.wasOpenedAtLogin,
+ runMode,
+ releaseWhenHidden: backgroundPolicy.releaseMainWindowWhenHidden,
+ })
+ if (mainWindowPlan.create) {
+ windowManager.open('main', { show: mainWindowPlan.show })
+ }
} else {
const disposeDisclaimerIpc = registerDisclaimerIpc({
gate,
@@ -2339,6 +2371,7 @@ async function initializeMainProcess(): Promise<void> {
setTimeout(() => {
if (!mainProcessWork.isAccepting()) return
+ if (settingsManager.getApp().lightweightMode) return
log.info('precreating add-task window')
windowManager.precreate('add-task')
}, 2000)
diff --git a/src/main/ipc/events.test.ts b/src/main/ipc/events.test.ts
index d0dd0358..e3cd201f 100644
--- a/src/main/ipc/events.test.ts
+++ b/src/main/ipc/events.test.ts
@@ -49,9 +49,10 @@ describe('setupEventForwarding', () => {
})
describe('NavigateTo', () => {
- it('forwards NavigateTo to main window webContents when main window exists', () => {
+ it('shows main and forwards NavigateTo when its renderer is loaded', () => {
+ vi.useFakeTimers()
const eventBus = new EventBus()
- const mainWin = createFakeWindow(false)
+ const mainWin = createFakeWindow(false, false)
const wm = createWindowManager(mainWin)
setupEventForwarding(eventBus, wm)
@@ -60,13 +61,16 @@ describe('setupEventForwarding', () => {
'/settings'
)
- expect(mainWin.webContents.send).toHaveBeenCalledWith(
+ expect(wm.show).toHaveBeenCalledWith('main')
+ vi.advanceTimersByTime(100)
+ expect(mainWin.webContents.send).toHaveBeenCalledExactlyOnceWith(
Events.NavigateTo,
'/settings'
)
+ vi.useRealTimers()
})
- it('does not send NavigateTo when main window is missing', () => {
+ it('shows main but tolerates a legal gate that leaves it unavailable', () => {
const eventBus = new EventBus()
const wm = createWindowManager(null)
@@ -78,6 +82,7 @@ describe('setupEventForwarding', () => {
'/settings'
)
}).not.toThrow()
+ expect(wm.show).toHaveBeenCalledWith('main')
})
it('does not send NavigateTo when main window is destroyed', () => {
@@ -91,7 +96,35 @@ describe('setupEventForwarding', () => {
'/settings'
)
+ expect(wm.show).toHaveBeenCalledWith('main')
+ expect(mainWin.webContents.send).not.toHaveBeenCalled()
+ })
+
+ it('waits for a newly-created main renderer before navigation', () => {
+ vi.useFakeTimers()
+ const eventBus = new EventBus()
+ const mainWin = createFakeWindow(false, true)
+ const wm = createWindowManager(mainWin)
+
+ setupEventForwarding(eventBus, wm)
+ eventBus.emit(
+ Events.NavigateTo as Parameters<typeof eventBus.emit>[0],
+ '/downloads'
+ )
+
expect(mainWin.webContents.send).not.toHaveBeenCalled()
+ const didFinishLoad = mainWin.webContents.once.mock.calls.find(
+ ([event]) => event === 'did-finish-load'
+ )?.[1] as (() => void) | undefined
+ expect(didFinishLoad).toBeInstanceOf(Function)
+
+ didFinishLoad?.()
+ vi.advanceTimersByTime(100)
+ expect(mainWin.webContents.send).toHaveBeenCalledExactlyOnceWith(
+ Events.NavigateTo,
+ '/downloads'
+ )
+ vi.useRealTimers()
})
})
diff --git a/src/main/ipc/events.ts b/src/main/ipc/events.ts
index ed994954..55d98580 100644
--- a/src/main/ipc/events.ts
+++ b/src/main/ipc/events.ts
@@ -1,15 +1,17 @@
import type { EventBus } from '@core/events/event-bus'
import { subscribeForwardableEvents } from '@core/events/forward-events'
-import { Events } from '@shared/protocol/events'
+import { type EventChannel, Events } from '@shared/protocol/events'
+import type { WindowId } from '@shared/types/window'
import type { WindowManager } from '../window/window-manager'
-function sendToAddTaskWhenReady(
+function sendToWindowWhenReady(
windowManager: WindowManager,
- channel: string,
+ id: WindowId,
+ channel: EventChannel,
args: unknown[]
): void {
- windowManager.show('add-task')
- const win = windowManager.get('add-task')
+ windowManager.show(id)
+ const win = windowManager.get(id)
if (!win || win.isDestroyed()) return
const send = () => {
@@ -41,10 +43,7 @@ export function setupEventForwarding(
eventBus.on(
Events.NavigateTo as Parameters<typeof eventBus.on>[0],
(...args) => {
- const win = windowManager.get('main')
- if (win && !win.isDestroyed()) {
- win.webContents.send(Events.NavigateTo, ...args)
- }
+ sendToWindowWhenReady(windowManager, 'main', Events.NavigateTo, args)
}
)
@@ -52,7 +51,12 @@ export function setupEventForwarding(
eventBus.on(
Events.MagnetFileSelection as Parameters<typeof eventBus.on>[0],
(...args) => {
- sendToAddTaskWhenReady(windowManager, Events.MagnetFileSelection, args)
+ sendToWindowWhenReady(
+ windowManager,
+ 'add-task',
+ Events.MagnetFileSelection,
+ args
+ )
}
)
}
diff --git a/src/main/platform/desktop-background-policy.test.ts b/src/main/platform/desktop-background-policy.test.ts
new file mode 100644
index 00000000..13c3cbc8
--- /dev/null
+++ b/src/main/platform/desktop-background-policy.test.ts
@@ -0,0 +1,63 @@
+import { RunMode } from '@shared/constants'
+import { describe, expect, it } from 'vitest'
+import { resolveDesktopBackgroundPolicy } from './desktop-background-policy'
+
+describe('resolveDesktopBackgroundPolicy', () => {
+ it.each<NodeJS.Platform>(['win32', 'linux'])(
+ 'forces a tray and releases the renderer for lightweight HideTray on %s',
+ (platform) => {
+ expect(
+ resolveDesktopBackgroundPolicy({
+ lightweightMode: true,
+ platform,
+ runMode: RunMode.HideTray,
+ })
+ ).toEqual({
+ keepTray: true,
+ releaseMainWindowWhenHidden: true,
+ })
+ }
+ )
+
+ it('uses the Dock instead of forcing a tray for lightweight HideTray on macOS', () => {
+ expect(
+ resolveDesktopBackgroundPolicy({
+ lightweightMode: true,
+ platform: 'darwin',
+ runMode: RunMode.HideTray,
+ })
+ ).toEqual({
+ keepTray: false,
+ releaseMainWindowWhenHidden: true,
+ })
+ })
+
+ it.each([RunMode.Standard, RunMode.TrayOnly])(
+ 'preserves the tray in run mode %s',
+ (runMode) => {
+ expect(
+ resolveDesktopBackgroundPolicy({
+ lightweightMode: false,
+ platform: 'linux',
+ runMode,
+ })
+ ).toEqual({
+ keepTray: true,
+ releaseMainWindowWhenHidden: false,
+ })
+ }
+ )
+
+ it('preserves legacy HideTray behavior when lightweight mode is disabled', () => {
+ expect(
+ resolveDesktopBackgroundPolicy({
+ lightweightMode: false,
+ platform: 'win32',
+ runMode: RunMode.HideTray,
+ })
+ ).toEqual({
+ keepTray: false,
+ releaseMainWindowWhenHidden: false,
+ })
+ })
+})
diff --git a/src/main/platform/desktop-background-policy.ts b/src/main/platform/desktop-background-policy.ts
new file mode 100644
index 00000000..2d01a285
--- /dev/null
+++ b/src/main/platform/desktop-background-policy.ts
@@ -0,0 +1,31 @@
+import { RunMode } from '@shared/constants'
+
+export interface DesktopBackgroundPolicyInput {
+ lightweightMode: boolean
+ platform: NodeJS.Platform
+ runMode: RunMode
+}
+
+export interface DesktopBackgroundPolicy {
+ keepTray: boolean
+ releaseMainWindowWhenHidden: boolean
+}
+
+/** Resolve the reopen surface and renderer-retention policy as one invariant. */
+export function resolveDesktopBackgroundPolicy({
+ lightweightMode,
+ platform,
+ runMode,
+}: DesktopBackgroundPolicyInput): DesktopBackgroundPolicy {
+ const keepTray =
+ runMode !== RunMode.HideTray || (lightweightMode && platform !== 'darwin')
+
+ return {
+ keepTray,
+ // macOS can reopen from the Dock. Windows/Linux lightweight mode forces
+ // the tray above, so releasing the final renderer never removes every
+ // discoverable reopen surface.
+ releaseMainWindowWhenHidden:
+ lightweightMode && (platform === 'darwin' || keepTray),
+ }
+}
diff --git a/src/main/platform/tray.test.ts b/src/main/platform/tray.test.ts
index 21161038..79ea96a2 100644
--- a/src/main/platform/tray.test.ts
+++ b/src/main/platform/tray.test.ts
@@ -68,24 +68,30 @@ vi.mock('./tray-speedometer', () => ({
}))
import { RunMode } from '@shared/constants'
+import { Events } from '@shared/protocol/events'
import { setupTray, type TrayDeps } from './tray'
const originalPlatform = process.platform
const trayMenu = { kind: 'tray-menu' }
const toggleMainWindow = vi.fn()
-function createDeps(): TrayDeps {
+function createDeps(
+ appSettings: {
+ lightweightMode: boolean
+ runMode: RunMode
+ traySpeedometer: boolean
+ } = {
+ lightweightMode: false,
+ runMode: RunMode.Standard,
+ traySpeedometer: false,
+ }
+): TrayDeps {
return {
eventBus: {
off: vi.fn(),
on: vi.fn(),
},
- settingsManager: {
- getApp: () => ({
- runMode: RunMode.Standard,
- traySpeedometer: false,
- }),
- },
+ settingsManager: { getApp: () => appSettings },
menuManager: {
getTrayMenu: () => trayMenu,
onTrayRebuilt: vi.fn(),
@@ -146,6 +152,68 @@ describe('setupTray', () => {
handle.destroy()
})
+ it.each(['win32', 'linux'] as const)(
+ 'forces a tray for lightweight HideTray on %s',
+ async (platform) => {
+ Object.defineProperty(process, 'platform', { value: platform })
+
+ const handle = setupTray(
+ createDeps({
+ lightweightMode: true,
+ runMode: RunMode.HideTray,
+ traySpeedometer: false,
+ })
+ )
+
+ await vi.waitFor(() => {
+ expect(trayConstructor).toHaveBeenCalled()
+ })
+
+ handle.destroy()
+ }
+ )
+
+ it('creates and removes the forced tray as lightweight mode changes', async () => {
+ Object.defineProperty(process, 'platform', { value: 'linux' })
+ const deps = createDeps({
+ lightweightMode: false,
+ runMode: RunMode.HideTray,
+ traySpeedometer: false,
+ })
+ const handle = setupTray(deps)
+ expect(trayConstructor).not.toHaveBeenCalled()
+
+ const settingsChanged = (
+ deps.eventBus.on as unknown as ReturnType<typeof vi.fn>
+ ).mock.calls.find(([event]) => event === Events.SettingsChanged)?.[1] as
+ | ((payload: unknown) => void)
+ | undefined
+ settingsChanged?.({
+ old: {
+ app: { lightweightMode: false, runMode: RunMode.HideTray },
+ },
+ updated: {
+ app: { lightweightMode: true, runMode: RunMode.HideTray },
+ },
+ })
+
+ await vi.waitFor(() => {
+ expect(trayConstructor).toHaveBeenCalled()
+ })
+
+ settingsChanged?.({
+ old: {
+ app: { lightweightMode: true, runMode: RunMode.HideTray },
+ },
+ updated: {
+ app: { lightweightMode: false, runMode: RunMode.HideTray },
+ },
+ })
+ expect(trayInstance.destroy).toHaveBeenCalledOnce()
+
+ handle.destroy()
+ })
+
it('toggles the main window without opening the menu on Windows left click', async () => {
Object.defineProperty(process, 'platform', { value: 'win32' })
diff --git a/src/main/platform/tray.ts b/src/main/platform/tray.ts
index 35727bfc..bbf68d87 100644
--- a/src/main/platform/tray.ts
+++ b/src/main/platform/tray.ts
@@ -8,6 +8,7 @@ import { Events } from '@shared/protocol/events'
import type { AppSettings } from '@shared/types/settings'
import { app, type Menu, Tray } from 'electron'
import type { MenuManager } from '../menu/menu-manager'
+import { resolveDesktopBackgroundPolicy } from './desktop-background-policy'
import type { createProtocolManager } from './protocol-manager'
import type { TrayIconProvider } from './tray-icon'
import { createIconProvider } from './tray-icon'
@@ -179,17 +180,35 @@ export function setupTray(deps: TrayDeps): TrayHandle {
updated: AppSettings
}
- // Run mode changed
- if (oldSettings.app.runMode !== updated.app.runMode) {
+ // Run mode and lightweight mode jointly decide whether a tray reopen
+ // surface is required.
+ if (
+ oldSettings.app.runMode !== updated.app.runMode ||
+ oldSettings.app.lightweightMode !== updated.app.lightweightMode
+ ) {
const newMode = updated.app.runMode
- log.info({ runMode: newMode }, 'run mode changed')
-
- if (newMode === RunMode.HideTray) {
- destroyTray()
- } else if (!tray) {
+ const policy = resolveDesktopBackgroundPolicy({
+ lightweightMode: updated.app.lightweightMode,
+ platform: process.platform,
+ runMode: newMode,
+ })
+ log.info(
+ {
+ keepTray: policy.keepTray,
+ lightweightMode: updated.app.lightweightMode,
+ runMode: newMode,
+ },
+ 'desktop background policy changed'
+ )
+
+ if (policy.keepTray && !tray) {
createTray().catch((err) => log.error({ err }, 'tray creation failed'))
+ } else if (!policy.keepTray) {
+ destroyTray()
+ }
+ if (oldSettings.app.runMode !== newMode) {
+ syncDockVisibility(newMode)
}
- syncDockVisibility(newMode)
}
// Speedometer toggled
@@ -219,9 +238,15 @@ export function setupTray(deps: TrayDeps): TrayHandle {
// ─── Init ───────────────────────────────────────────────
- const runMode = settingsManager.getApp().runMode
+ const appSettings = settingsManager.getApp()
+ const runMode = appSettings.runMode
+ const policy = resolveDesktopBackgroundPolicy({
+ lightweightMode: appSettings.lightweightMode,
+ platform: process.platform,
+ runMode,
+ })
- if (runMode !== RunMode.HideTray) {
+ if (policy.keepTray) {
createTray().catch((err) => log.error({ err }, 'tray creation failed'))
}
syncDockVisibility(runMode)
@@ -231,7 +256,7 @@ export function setupTray(deps: TrayDeps): TrayHandle {
eventBus.on(Events.EngineActiveChanged, onEngineActiveChanged)
eventBus.on(Events.StatsUpdated, onStatsUpdated)
- log.info({ runMode }, 'tray setup complete')
+ log.info({ keepTray: policy.keepTray, runMode }, 'tray setup complete')
// ─── Handle ─────────────────────────────────────────────
diff --git a/src/main/window/window-manager.test.ts b/src/main/window/window-manager.test.ts
index 2b0d348e..099f36d8 100644
--- a/src/main/window/window-manager.test.ts
+++ b/src/main/window/window-manager.test.ts
@@ -51,6 +51,7 @@ vi.mock('electron', () => {
})
isDestroyed = vi.fn(() => this._destroyed)
isVisible = vi.fn(() => this._visible)
+ isFocused = vi.fn(() => true)
getBounds = vi.fn(() => ({ ...this._bounds }))
setBounds = vi.fn(
(b: { x: number; y: number; width: number; height: number }) => {
@@ -436,6 +437,48 @@ describe('WindowManager', () => {
expect(win?.hide).toHaveBeenCalled()
})
+ it('close releases main window when the live retention policy requests it', () => {
+ const sm = createMockSettingsManager()
+ const wm = new WindowManager({
+ settingsManager: sm,
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ retentionPolicy: {
+ releaseMainOnDismiss: () => true,
+ prewarmAddTask: () => false,
+ },
+ })
+
+ const win = wm.open('main')
+ wm.close('main')
+
+ expect(win.hide).not.toHaveBeenCalled()
+ expect(win.destroy).toHaveBeenCalledOnce()
+ expect(wm.get('main')).toBeNull()
+ expect(sm.update).toHaveBeenCalledWith({
+ windowState: { main: expect.any(Object) },
+ })
+ })
+
+ it('toggle releases a focused main window in lightweight mode', () => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ retentionPolicy: {
+ releaseMainOnDismiss: () => true,
+ prewarmAddTask: () => false,
+ },
+ })
+
+ const win = wm.open('main')
+ win.show()
+ wm.toggle('main')
+
+ expect(win.destroy).toHaveBeenCalledOnce()
+ expect(wm.get('main')).toBeNull()
+ })
+
it('stops converting main-window close into hide after update quit starts', () => {
const wm = new WindowManager({
settingsManager: createMockSettingsManager(),
@@ -464,6 +507,38 @@ describe('WindowManager', () => {
expect(win.hide).not.toHaveBeenCalled()
})
+ it('allows a native main-window close to destroy the renderer in lightweight mode', () => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ retentionPolicy: {
+ releaseMainOnDismiss: () => true,
+ prewarmAddTask: () => false,
+ },
+ })
+ const win = wm.open('main')
+ const closeListener = (
+ win.on as unknown as ReturnType<typeof vi.fn>
+ ).mock.calls.find(([event]) => event === 'close')?.[1] as
+ | ((event: { preventDefault(): void }) => void)
+ | undefined
+ const closeEvent = { preventDefault: vi.fn() }
+
+ closeListener?.(closeEvent)
+
+ expect(closeEvent.preventDefault).not.toHaveBeenCalled()
+ expect(win.hide).not.toHaveBeenCalled()
+
+ const closedListener = (
+ win.once as unknown as ReturnType<typeof vi.fn>
+ ).mock.calls.find(([event]) => event === 'closed')?.[1] as
+ | (() => void)
+ | undefined
+ closedListener?.()
+ expect(wm.get('main')).toBeNull()
+ })
+
it('reports both early and terminal Windows session-end signals', () => {
const onSessionEnd = vi.fn()
const wm = new WindowManager({
@@ -500,6 +575,63 @@ describe('WindowManager', () => {
expect(wm.get('add-task')).toBeNull()
})
+ it('does not recycle add-task in lightweight mode', () => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ retentionPolicy: {
+ releaseMainOnDismiss: () => true,
+ prewarmAddTask: () => false,
+ },
+ })
+
+ wm.open('add-task')
+ wm.closeAndRecycle('add-task')
+
+ expect(wm.get('add-task')).toBeNull()
+ expect(
+ (BrowserWindow as unknown as { instances: unknown[] }).instances
+ ).toHaveLength(1)
+ })
+
+ it('preserves add-task recycling in the default retention mode', () => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ })
+
+ wm.open('add-task')
+ wm.closeAndRecycle('add-task')
+
+ expect(wm.get('add-task')).not.toBeNull()
+ expect(
+ (BrowserWindow as unknown as { instances: unknown[] }).instances
+ ).toHaveLength(2)
+ })
+
+ it('reconciles a hidden prewarmed add-task after lightweight mode is enabled', () => {
+ let lightweight = false
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ retentionPolicy: {
+ releaseMainOnDismiss: () => lightweight,
+ prewarmAddTask: () => !lightweight,
+ },
+ })
+
+ wm.precreate('add-task')
+ const prewarmed = wm.get('add-task')
+ lightweight = true
+ wm.reconcileWindowRetention()
+
+ expect(prewarmed?.destroy).toHaveBeenCalledOnce()
+ expect(wm.get('add-task')).toBeNull()
+ })
+
it('restores saved bounds if within screen', () => {
const savedBounds = { x: 100, y: 100, width: 1024, height: 768 }
const sm = createMockSettingsManager({ main: savedBounds })
diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.ts
index 97b27ce9..e663c120 100644
--- a/src/main/window/window-manager.ts
+++ b/src/main/window/window-manager.ts
@@ -33,6 +33,14 @@ export interface WindowManagerDeps {
onSessionEnd?: () => void
/** Frozen renderer trust policy shared with IPC sender validation. */
rendererUrlPolicy?: RendererUrlPolicy
+ /** Live policy so a settings change affects the next window dismissal
+ * without rebuilding the manager or restarting the application. */
+ retentionPolicy?: WindowRetentionPolicy
+}
+
+export interface WindowRetentionPolicy {
+ releaseMainOnDismiss(): boolean
+ prewarmAddTask(): boolean
}
export class WindowManager {
@@ -135,7 +143,7 @@ export class WindowManager {
}
if (win.isVisible() && win.isFocused()) {
- win.hide()
+ this.close(id)
} else {
win.show()
win.focus()
@@ -154,38 +162,59 @@ export class WindowManager {
const config = WINDOW_CONFIGS[id]
- if (config.closeBehavior === 'hide') {
+ if (config.closeBehavior === 'hide' && !this.shouldReleaseOnDismiss(id)) {
this.saveBounds(id)
win.hide()
} else {
- this.clearBoundsTimer(id)
- win.webContents.removeAllListeners()
- win.removeAllListeners()
- win.destroy()
- this.windows.set(id, null)
+ this.release(id)
}
}
+ release(id: WindowId): void {
+ const win = this.windows.get(id)
+ if (!win || win.isDestroyed()) return
+
+ this.saveBounds(id)
+ this.clearBoundsTimer(id)
+ win.webContents.removeAllListeners()
+ win.removeAllListeners()
+ win.destroy()
+ this.windows.set(id, null)
+ }
+
closeAndRecycle(id: WindowId): void {
this.close(id)
const config = WINDOW_CONFIGS[id]
- if (config.closeBehavior === 'destroy') {
+ if (
+ config.closeBehavior === 'destroy' &&
+ (id !== 'add-task' || this.shouldPrewarmAddTask())
+ ) {
this.precreate(id)
}
}
+ /** Reconcile already-created hidden windows after lightweight mode changes. */
+ reconcileWindowRetention(): void {
+ const main = this.get('main')
+ if (main && !main.isVisible() && this.shouldReleaseOnDismiss('main')) {
+ this.release('main')
+ }
+
+ const addTask = this.get('add-task')
+ if (this.shouldPrewarmAddTask()) {
+ if (!addTask) this.precreate('add-task')
+ } else if (addTask && !addTask.isVisible()) {
+ this.release('add-task')
+ }
+ }
+
recreate(id: WindowId): BrowserWindow {
id = this.resolveOpenTarget(id)
const existing = this.get(id)
const shouldShow = existing?.isVisible() ?? true
if (existing) {
- this.saveBounds(id)
- this.clearBoundsTimer(id)
- existing.webContents.removeAllListeners()
- existing.removeAllListeners()
- existing.destroy()
- this.windows.set(id, null)
+ this.release(id)
}
const win = this.registerWindow(id, shouldShow)
@@ -292,6 +321,12 @@ export class WindowManager {
}
this.deps.loadUrl(win, config.route)
this.setupCloseHandler(id, win)
+ win.once('closed', () => {
+ this.clearBoundsTimer(id)
+ if (this.windows.get(id) === win) {
+ this.windows.set(id, null)
+ }
+ })
return win
}
@@ -304,6 +339,17 @@ export class WindowManager {
}
}
+ private shouldReleaseOnDismiss(id: WindowId): boolean {
+ return (
+ id === 'main' &&
+ this.deps.retentionPolicy?.releaseMainOnDismiss() === true
+ )
+ }
+
+ private shouldPrewarmAddTask(): boolean {
+ return this.deps.retentionPolicy?.prewarmAddTask() ?? true
+ }
+
private createBrowserWindow(
config: (typeof WINDOW_CONFIGS)[WindowId],
show: boolean
@@ -438,8 +484,9 @@ export class WindowManager {
win.on('close', (event) => {
if (config.closeBehavior === 'hide' && !this.willQuit) {
- event.preventDefault()
this.saveBounds(id)
+ if (this.shouldReleaseOnDismiss(id)) return
+ event.preventDefault()
win.hide()
}
})
diff --git a/src/main/window/window-startup-plan.test.ts b/src/main/window/window-startup-plan.test.ts
new file mode 100644
index 00000000..681d790a
--- /dev/null
+++ b/src/main/window/window-startup-plan.test.ts
@@ -0,0 +1,51 @@
+import { RunMode } from '@shared/constants'
+import { describe, expect, it } from 'vitest'
+import { resolveMainWindowStartupPlan } from './window-startup-plan'
+
+describe('resolveMainWindowStartupPlan', () => {
+ it.each([RunMode.Standard, RunMode.HideTray])(
+ 'creates and shows an interactive %s launch',
+ (runMode) => {
+ expect(
+ resolveMainWindowStartupPlan({
+ openedAtLogin: false,
+ runMode,
+ releaseWhenHidden: true,
+ })
+ ).toEqual({ create: true, show: true })
+ }
+ )
+
+ it('keeps a background renderer in the default retention mode', () => {
+ expect(
+ resolveMainWindowStartupPlan({
+ openedAtLogin: true,
+ runMode: RunMode.Standard,
+ releaseWhenHidden: false,
+ })
+ ).toEqual({ create: true, show: false })
+ })
+
+ it.each([RunMode.Standard, RunMode.TrayOnly, RunMode.HideTray])(
+ 'skips a hidden %s renderer when release is enabled',
+ (runMode) => {
+ expect(
+ resolveMainWindowStartupPlan({
+ openedAtLogin: true,
+ runMode,
+ releaseWhenHidden: true,
+ })
+ ).toEqual({ create: false, show: false })
+ }
+ )
+
+ it('treats tray-only as a background launch without login metadata', () => {
+ expect(
+ resolveMainWindowStartupPlan({
+ openedAtLogin: false,
+ runMode: RunMode.TrayOnly,
+ releaseWhenHidden: true,
+ })
+ ).toEqual({ create: false, show: false })
+ })
+})
diff --git a/src/main/window/window-startup-plan.ts b/src/main/window/window-startup-plan.ts
new file mode 100644
index 00000000..1d6f550a
--- /dev/null
+++ b/src/main/window/window-startup-plan.ts
@@ -0,0 +1,26 @@
+import { RunMode } from '@shared/constants'
+
+export interface MainWindowStartupPlanInput {
+ openedAtLogin: boolean
+ runMode: RunMode
+ releaseWhenHidden: boolean
+}
+
+export interface MainWindowStartupPlan {
+ create: boolean
+ show: boolean
+}
+
+/** Decide whether startup needs a renderer at all. A visible launch always
+ * creates one; background launches may stay headless when release is safe. */
+export function resolveMainWindowStartupPlan({
+ openedAtLogin,
+ runMode,
+ releaseWhenHidden,
+}: MainWindowStartupPlanInput): MainWindowStartupPlan {
+ const show = !openedAtLogin && runMode !== RunMode.TrayOnly
+ return {
+ create: show || !releaseWhenHidden,
+ show,
+ }
+}
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
index 06e7058a..b0d938ef 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
@@ -30,6 +30,7 @@ const FIXTURE = {
language: 'en-US',
traySpeedometer: false,
runMode: 1, // RunMode.Standard — numeric enum
+ lightweightMode: false,
launchAtStartup: false,
defaultSaveDir: '/x',
notifyOnComplete: true,
@@ -114,6 +115,29 @@ describe('<AppearanceDialog>', () => {
expect(onClose).toHaveBeenCalled()
})
+ it('hydrates and submits lightweight mode independently', async () => {
+ render(
+ <AppearanceDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.appearance.title"
+ descKey="settings.cards.appearance.desc"
+ />
+ )
+ const lightweight = await screen.findByRole('switch', {
+ name: 'Lightweight mode',
+ })
+ const user = userEvent.setup()
+
+ expect(lightweight).not.toBeChecked()
+ await user.click(lightweight)
+ await user.click(screen.getByRole('button', { name: /save/i }))
+
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: { lightweightMode: true },
+ })
+ })
+
it('waits for the host locale event after persisting a language change', async () => {
render(
<AppearanceDialog
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.tsx b/src/renderer/routes/settings/cards/appearance-dialog.tsx
index c1e39d61..f2abfab7 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.tsx
@@ -40,7 +40,12 @@ import type { SettingsCardDialogProps } from './card-types'
type AppearanceFields = Pick<
MotrixAppSettings,
- 'theme' | 'language' | 'traySpeedometer' | 'runMode' | 'liquidGlassEffect'
+ | 'theme'
+ | 'language'
+ | 'traySpeedometer'
+ | 'runMode'
+ | 'liquidGlassEffect'
+ | 'lightweightMode'
>
// Source of truth: src/shared/schemas/app-settings.ts (DEFAULT_APP_SETTINGS).
@@ -52,6 +57,7 @@ const DEFAULTS: AppearanceFields = {
traySpeedometer: DEFAULT_APP_SETTINGS.traySpeedometer,
runMode: DEFAULT_APP_SETTINGS.runMode,
liquidGlassEffect: DEFAULT_APP_SETTINGS.liquidGlassEffect,
+ lightweightMode: DEFAULT_APP_SETTINGS.lightweightMode,
}
const LANGUAGE_OPTIONS = SUPPORTED_LOCALES.map(({ code, nativeName }) => ({
@@ -87,6 +93,7 @@ export function AppearanceDialog({
traySpeedometer: all.app.traySpeedometer,
runMode: all.app.runMode,
liquidGlassEffect: all.app.liquidGlassEffect,
+ lightweightMode: all.app.lightweightMode,
})
}
})
@@ -314,6 +321,31 @@ export function AppearanceDialog({
)}
/>
)}
+
+ {transport.platform !== 'web' && (
+ <FormField
+ control={form.control}
+ name="lightweightMode"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.appearance.lightweightMode')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.appearance.lightweightModeDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ )}
</form>
</Form>
</div>
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index de34fe27..182a7df0 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -959,7 +959,9 @@
"runMode": "Run as",
"runModeStandard": "Standard application",
"runModeTray": "Tray application",
- "runModeHideTray": "Hide tray application"
+ "runModeHideTray": "Hide tray application",
+ "lightweightMode": "Lightweight mode",
+ "lightweightModeDesc": "Release interface memory after the main window closes. Background downloads continue; Windows and Linux keep a tray entry for reopening. Reopening takes a little longer and unsaved interface state is discarded."
},
"advanced": {
"rpc": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 6a3e9055..291a77d4 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -946,7 +946,9 @@
"runMode": "运行方式",
"runModeStandard": "标准应用",
"runModeTray": "托盘应用",
- "runModeHideTray": "隐藏托盘"
+ "runModeHideTray": "隐藏托盘",
+ "lightweightMode": "轻量模式",
+ "lightweightModeDesc": "关闭主窗口后释放界面内存,后台下载继续运行。Windows 和 Linux 会保留托盘入口;重新打开会稍慢,未保存的界面状态将被丢弃。"
},
"about": {
"appIconAlt": "Motrix 应用图标",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 397119b7..8eb15238 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -946,7 +946,9 @@
"runMode": "執行方式",
"runModeStandard": "標準應用程式",
"runModeTray": "系統匣應用程式",
- "runModeHideTray": "隱藏系統匣應用程式"
+ "runModeHideTray": "隱藏系統匣應用程式",
+ "lightweightMode": "輕量模式",
+ "lightweightModeDesc": "關閉主視窗後釋放介面記憶體,背景下載會繼續運作。Windows 和 Linux 會保留系統匣入口;重新開啟會稍慢,未儲存的介面狀態將被捨棄。"
},
"advanced": {
"rpc": {
diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.ts
index b4a33bd3..da641982 100644
--- a/src/shared/schemas/app-settings.test.ts
+++ b/src/shared/schemas/app-settings.test.ts
@@ -2,6 +2,25 @@ import { describe, expect, it } from 'vitest'
import { appSettingsSchema, DEFAULT_APP_SETTINGS } from './app-settings'
describe('appSettingsSchema', () => {
+ it('defaults traySpeedometer to true while preserving an explicit opt-out', () => {
+ expect(DEFAULT_APP_SETTINGS.traySpeedometer).toBe(true)
+ expect(appSettingsSchema.parse({}).traySpeedometer).toBe(true)
+ expect(
+ appSettingsSchema.parse({ traySpeedometer: false }).traySpeedometer
+ ).toBe(false)
+ })
+
+ it('defaults lightweightMode to false', () => {
+ expect(DEFAULT_APP_SETTINGS.lightweightMode).toBe(false)
+ expect(appSettingsSchema.parse({}).lightweightMode).toBe(false)
+ })
+
+ it('recovers from an invalid lightweightMode value', () => {
+ expect(
+ appSettingsSchema.parse({ lightweightMode: 'yes' }).lightweightMode
+ ).toBe(false)
+ })
+
it('defaults autofillClipboardLinks to true', () => {
expect(DEFAULT_APP_SETTINGS.autofillClipboardLinks).toBe(true)
expect(appSettingsSchema.parse({}).autofillClipboardLinks).toBe(true)
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index a3d08cea..9d6ff22b 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -23,7 +23,8 @@ export const appSettingsSchema = z.object({
})
.catch({ magnet: true }),
runMode: z.enum(RunMode).catch(RunMode.Standard),
- traySpeedometer: z.boolean().catch(false),
+ lightweightMode: z.boolean().catch(false),
+ traySpeedometer: z.boolean().catch(true),
magnetFileSelection: z.boolean().catch(true),
browserBridgeEnabled: z.boolean().catch(true),
liquidGlassEffect: z.boolean().catch(false),
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index 819b2442..fb4e1380 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -220,6 +220,9 @@ export interface MotrixAppSettings {
magnet: boolean
}
runMode: RunMode
+ /** Release renderer windows while the desktop UI is closed. Background
+ * services such as downloads, notifications, and the tray keep running. */
+ lightweightMode: boolean
traySpeedometer: boolean
magnetFileSelection: boolean
/** Master switch for the WebSocket bridge that lets browser extensions
diff --git a/tests/scripts/electron-package-contract.test.ts b/tests/scripts/electron-package-contract.test.ts
index 9b8e1739..4731099d 100644
--- a/tests/scripts/electron-package-contract.test.ts
+++ b/tests/scripts/electron-package-contract.test.ts
@@ -29,6 +29,41 @@ async function readJson(relativePath: string): Promise<unknown> {
}
describe('Electron package contracts', () => {
+ it('hydrates Electron before local commands consume its runtime files', async () => {
+ const manifest = (await readJson('package.json')) as {
+ scripts?: Record<string, string>
+ }
+ const scripts = manifest.scripts ?? {}
+
+ expect(scripts['ensure:electron-runtime']).toBe(
+ 'node scripts/ensure-electron-runtime.mjs'
+ )
+ for (const scriptName of [
+ 'prestart',
+ 'build:legal',
+ 'check:registry-runtime',
+ 'check:third-party-notices',
+ 'pretest:e2e',
+ 'pretest:e2e:ui',
+ 'pretest:e2e:debug',
+ 'smoke:electron-package',
+ ]) {
+ expect(
+ scripts[scriptName],
+ `${scriptName} must hydrate Electron before consuming its runtime`
+ ).toMatch(/^pnpm run ensure:electron-runtime && /)
+ }
+ })
+
+ it('hydrates Electron when Playwright is invoked directly', async () => {
+ const globalSetup = await readFile(
+ path.join(REPOSITORY_ROOT, 'e2e/global-setup.ts'),
+ 'utf8'
+ )
+
+ expect(globalSetup).toContain("['run', 'ensure:electron-runtime']")
+ })
+
it('packages only the generated staged application', async () => {
const config = (await readJson('electron-builder.json')) as {
asarUnpack?: string[]
@@ -227,7 +262,7 @@ describe('Electron package contracts', () => {
}
expect(manifest.scripts?.['smoke:electron-package']).toBe(
- 'node scripts/smoke-electron-package.mjs'
+ 'pnpm run ensure:electron-runtime && node scripts/smoke-electron-package.mjs'
)
expect(
parseSmokeArguments([
diff --git a/tests/scripts/ensure-electron-runtime.test.ts b/tests/scripts/ensure-electron-runtime.test.ts
new file mode 100644
index 00000000..5992c085
--- /dev/null
+++ b/tests/scripts/ensure-electron-runtime.test.ts
@@ -0,0 +1,283 @@
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs'
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+// @ts-expect-error — .mjs without types
+import {
+ ensureElectronRuntime,
+ inspectElectronRuntime,
+} from '../../scripts/ensure-electron-runtime.mjs'
+
+const VERSION = '43.4.0'
+let packageDir: string
+
+async function writePackageShell(): Promise<void> {
+ await writeFile(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({ name: 'electron', version: VERSION })
+ )
+ await writeFile(path.join(packageDir, 'install.js'), '// test installer')
+}
+
+async function writeRuntime(): Promise<void> {
+ const executableRelativePath =
+ process.platform === 'win32'
+ ? 'electron.exe'
+ : process.platform === 'darwin'
+ ? 'Electron.app/Contents/MacOS/Electron'
+ : 'electron'
+ await mkdir(
+ path.dirname(path.join(packageDir, 'dist', executableRelativePath)),
+ { recursive: true }
+ )
+ await writeFile(path.join(packageDir, 'dist', 'version'), VERSION)
+ await writeFile(path.join(packageDir, 'dist', 'LICENSE'), 'Electron license')
+ await writeFile(
+ path.join(packageDir, 'dist', 'LICENSES.chromium.html'),
+ 'Chromium licenses'
+ )
+ await writeFile(
+ path.join(packageDir, 'dist', executableRelativePath),
+ 'binary'
+ )
+ await writeFile(path.join(packageDir, 'path.txt'), executableRelativePath)
+}
+
+function writeRuntimeSync(): void {
+ const executableRelativePath =
+ process.platform === 'win32'
+ ? 'electron.exe'
+ : process.platform === 'darwin'
+ ? 'Electron.app/Contents/MacOS/Electron'
+ : 'electron'
+ mkdirSync(
+ path.dirname(path.join(packageDir, 'dist', executableRelativePath)),
+ { recursive: true }
+ )
+ writeFileSync(path.join(packageDir, 'dist', 'version'), VERSION)
+ writeFileSync(path.join(packageDir, 'dist', 'LICENSE'), 'Electron license')
+ writeFileSync(
+ path.join(packageDir, 'dist', 'LICENSES.chromium.html'),
+ 'Chromium licenses'
+ )
+ writeFileSync(path.join(packageDir, 'dist', executableRelativePath), 'binary')
+ writeFileSync(path.join(packageDir, 'path.txt'), executableRelativePath)
+}
+
+beforeEach(async () => {
+ packageDir = await mkdtemp(path.join(tmpdir(), 'motrix-electron-runtime-'))
+ await writePackageShell()
+})
+
+afterEach(async () => {
+ await rm(packageDir, { force: true, recursive: true })
+})
+
+describe('inspectElectronRuntime', () => {
+ it('accepts a complete matching runtime', async () => {
+ await writeRuntime()
+
+ expect(inspectElectronRuntime(packageDir)).toEqual({
+ complete: true,
+ expectedVersion: VERSION,
+ issues: [],
+ })
+ })
+
+ it('reports missing runtime licenses and a missing executable', async () => {
+ await mkdir(path.join(packageDir, 'dist'), { recursive: true })
+ await writeFile(path.join(packageDir, 'dist', 'version'), VERSION)
+ await writeFile(path.join(packageDir, 'path.txt'), 'electron')
+
+ const result = inspectElectronRuntime(packageDir)
+ expect(result.complete).toBe(false)
+ expect(result.issues).toEqual(
+ expect.arrayContaining([
+ 'dist/LICENSE is missing or empty',
+ 'dist/LICENSES.chromium.html is missing or empty',
+ 'Electron executable is missing: electron',
+ ])
+ )
+ })
+
+ it('rejects a runtime hydrated for a different Electron version', async () => {
+ await writeRuntime()
+ await writeFile(path.join(packageDir, 'dist', 'version'), '42.0.0')
+
+ expect(inspectElectronRuntime(packageDir).issues).toContain(
+ `dist/version is 42.0.0, expected ${VERSION}`
+ )
+ })
+
+ it('rejects an executable path that escapes dist', async () => {
+ await writeRuntime()
+ await writeFile(path.join(packageDir, 'path.txt'), '../package.json')
+
+ expect(inspectElectronRuntime(packageDir).issues).toContain(
+ 'Electron executable is missing: ../package.json'
+ )
+ })
+})
+
+describe('ensureElectronRuntime', () => {
+ it('returns immediately without invoking the installer when complete', async () => {
+ await writeRuntime()
+ const spawn = vi.fn()
+
+ expect(
+ ensureElectronRuntime({
+ electronPackageDir: packageDir,
+ log: vi.fn(),
+ logError: vi.fn(),
+ spawn,
+ })
+ ).toBe(0)
+ expect(spawn).not.toHaveBeenCalled()
+ })
+
+ it('replaces a partially hydrated runtime instead of trusting version alone', async () => {
+ await mkdir(path.join(packageDir, 'dist'), { recursive: true })
+ await writeFile(path.join(packageDir, 'dist', 'version'), VERSION)
+ await writeFile(path.join(packageDir, 'dist', 'stale-file'), 'stale')
+ await writeFile(path.join(packageDir, 'path.txt'), 'electron')
+ const spawn = vi.fn(() => {
+ // The stale payload must already be out of the installer's way.
+ expect(existsSync(path.join(packageDir, 'dist', 'stale-file'))).toBe(
+ false
+ )
+ writeRuntimeSync()
+ return { status: 0, signal: null }
+ })
+
+ expect(
+ ensureElectronRuntime({
+ electronPackageDir: packageDir,
+ log: vi.fn(),
+ logError: vi.fn(),
+ spawn,
+ })
+ ).toBe(0)
+ expect(inspectElectronRuntime(packageDir).complete).toBe(true)
+ await expect(
+ readFile(path.join(packageDir, 'dist', 'stale-file'), 'utf8')
+ ).rejects.toMatchObject({ code: 'ENOENT' })
+ })
+
+ it('restores the previous payload when installation fails', async () => {
+ await mkdir(path.join(packageDir, 'dist'), { recursive: true })
+ await writeFile(path.join(packageDir, 'dist', 'version'), VERSION)
+ await writeFile(path.join(packageDir, 'dist', 'stale-file'), 'keep me')
+ await writeFile(path.join(packageDir, 'path.txt'), 'electron')
+
+ expect(
+ ensureElectronRuntime({
+ electronPackageDir: packageDir,
+ log: vi.fn(),
+ logError: vi.fn(),
+ spawn: vi.fn(() => ({ status: 7, signal: null })),
+ })
+ ).toBe(7)
+ await expect(
+ readFile(path.join(packageDir, 'dist', 'stale-file'), 'utf8')
+ ).resolves.toBe('keep me')
+ await expect(
+ readFile(path.join(packageDir, 'path.txt'), 'utf8')
+ ).resolves.toBe('electron')
+ })
+
+ it('preserves originals when moving one payload aside fails', async () => {
+ await mkdir(path.join(packageDir, 'dist'), { recursive: true })
+ await writeFile(path.join(packageDir, 'dist', 'version'), VERSION)
+ await writeFile(path.join(packageDir, 'dist', 'stale-file'), 'keep me')
+ const pathFile = path.join(packageDir, 'path.txt')
+ await writeFile(pathFile, 'electron')
+ const logError = vi.fn()
+
+ expect(
+ ensureElectronRuntime({
+ electronPackageDir: packageDir,
+ fs: {
+ existsSync,
+ readFileSync,
+ renameSync: vi.fn((source, destination) => {
+ if (source === pathFile) {
+ throw new Error('simulated rename failure')
+ }
+ renameSync(source, destination)
+ }),
+ rmSync,
+ statSync,
+ },
+ log: vi.fn(),
+ logError,
+ spawn: vi.fn(),
+ })
+ ).toBe(1)
+ await expect(
+ readFile(path.join(packageDir, 'dist', 'stale-file'), 'utf8')
+ ).resolves.toBe('keep me')
+ await expect(readFile(pathFile, 'utf8')).resolves.toBe('electron')
+ expect(logError).toHaveBeenCalledWith(
+ expect.stringContaining('simulated rename failure')
+ )
+ expect(logError).not.toHaveBeenCalledWith(
+ expect.stringContaining('failed to fully restore')
+ )
+ })
+
+ it('keeps a validated repair when temporary backup cleanup fails', async () => {
+ await mkdir(path.join(packageDir, 'dist'), { recursive: true })
+ await writeFile(path.join(packageDir, 'dist', 'version'), VERSION)
+ await writeFile(path.join(packageDir, 'path.txt'), 'electron')
+ const logError = vi.fn()
+
+ expect(
+ ensureElectronRuntime({
+ electronPackageDir: packageDir,
+ fs: {
+ existsSync,
+ readFileSync,
+ renameSync,
+ rmSync: vi.fn((target, options) => {
+ if (String(target).includes('.motrix-backup-')) {
+ throw new Error('simulated cleanup failure')
+ }
+ rmSync(target, options)
+ }),
+ statSync,
+ },
+ log: vi.fn(),
+ logError,
+ spawn: vi.fn(() => {
+ writeRuntimeSync()
+ return { status: 0, signal: null }
+ }),
+ })
+ ).toBe(0)
+ expect(inspectElectronRuntime(packageDir).complete).toBe(true)
+ expect(logError).toHaveBeenCalledWith(
+ expect.stringContaining('temporary backup could not be removed')
+ )
+ })
+
+ it('rejects an installer success that still leaves an incomplete runtime', () => {
+ expect(
+ ensureElectronRuntime({
+ electronPackageDir: packageDir,
+ log: vi.fn(),
+ logError: vi.fn(),
+ spawn: vi.fn(() => ({ status: 0, signal: null })),
+ })
+ ).toBe(1)
+ expect(inspectElectronRuntime(packageDir).complete).toBe(false)
+ })
+})