Skip to content

A full-featured download manager.

fix(window): preserve startup activation and restore minimized windows (#2325)

Dr_rOot031f841ef45d
diff --git a/e2e/window-reopen.spec.ts b/e2e/window-reopen.spec.ts
new file mode 100644
index 00000000..0efe6b08
--- /dev/null
+++ b/e2e/window-reopen.spec.ts
@@ -0,0 +1,127 @@
+import { writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import type { ElectronApplication } from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
+import { RunMode } from '../src/shared/constants'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForQueryHandlers,
+} from './fixtures/electron-app'
+
+async function secondLaunch(app: ElectronApplication): Promise<void> {
+ // Exercise the Windows/Linux desktop shortcut event, including on macOS CI.
+ await app.evaluate(({ app: electronApp }) => {
+ electronApp.emit('second-instance', {}, ['Motrix.exe'], '', {})
+ })
+}
+
+async function windowState(app: ElectronApplication, id = 'main') {
+ return app.evaluate(({ BrowserWindow }, windowId) => {
+ const win = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes(`w=${windowId}`)
+ )
+ return win
+ ? { visible: win.isVisible(), minimized: win.isMinimized() }
+ : null
+ }, id)
+}
+
+test('a second launch restores a minimized main window', async ({
+ electronApp,
+ mainWindow,
+}) => {
+ await waitForQueryHandlers(mainWindow)
+ await electronApp.evaluate(({ BrowserWindow }) => {
+ BrowserWindow.getAllWindows()
+ .find((window) => window.webContents.getURL().includes('w=main'))
+ ?.minimize()
+ })
+ await expect
+ .poll(async () => (await windowState(electronApp))?.minimized)
+ .toBe(true)
+
+ await secondLaunch(electronApp)
+ await expect
+ .poll(() => windowState(electronApp))
+ .toEqual({
+ visible: true,
+ minimized: false,
+ })
+})
+
+for (const lightweightMode of [false, true]) {
+ test(`a second launch reopens a closed main window with lightweight mode ${lightweightMode}`, async ({
+ userDataDir,
+ rpcPort,
+ }) => {
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ onboarding: { disclaimerAccepted: true },
+ tracker: { autoSync: false },
+ app: { runMode: RunMode.Standard, lightweightMode },
+ })
+ )
+ const app = await launchMotrix({ userDataDir, rpcPort })
+ try {
+ const main = await app.firstWindow()
+ await main.waitForLoadState('domcontentloaded')
+ await waitForQueryHandlers(main)
+ await app.evaluate(({ BrowserWindow }) => {
+ BrowserWindow.getAllWindows()
+ .find((window) => window.webContents.getURL().includes('w=main'))
+ ?.close()
+ })
+ await expect
+ .poll(() => windowState(app))
+ .toEqual(lightweightMode ? null : { visible: false, minimized: false })
+
+ await secondLaunch(app)
+ await expect
+ .poll(() => windowState(app))
+ .toEqual({
+ visible: true,
+ minimized: false,
+ })
+ } finally {
+ await app.close()
+ }
+ })
+}
+
+test('a second launch restores onboarding before consent is accepted', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ const app = await launchMotrix({
+ userDataDir,
+ rpcPort,
+ disclaimerAccepted: false,
+ })
+ try {
+ const onboarding = await app.firstWindow()
+ await expect(onboarding.getByTestId('disclaimer-agree')).toBeVisible()
+ await app.evaluate(({ BrowserWindow }) => {
+ BrowserWindow.getAllWindows()
+ .find((window) => window.webContents.getURL().includes('w=onboarding'))
+ ?.minimize()
+ })
+ await expect
+ .poll(async () => (await windowState(app, 'onboarding'))?.minimized)
+ .toBe(true)
+
+ await secondLaunch(app)
+ await expect
+ .poll(() => windowState(app, 'onboarding'))
+ .toEqual({
+ visible: true,
+ minimized: false,
+ })
+ expect(await windowState(app)).toBeNull()
+ } finally {
+ await app.close()
+ }
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index ebf94b11..42e45cef 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1761,6 +1761,7 @@ async function initializeMainProcess(): Promise<void> {
if (mainWindowPlan.create) {
windowManager.open('main', { show: mainWindowPlan.show })
}
+ launcher.markWindowReady()
} else {
const disposeDisclaimerIpc = registerDisclaimerIpc({
gate,
@@ -1780,6 +1781,9 @@ async function initializeMainProcess(): Promise<void> {
}
})
+ // A second launch must also be able to restore a minimized onboarding
+ // window while download ingress is still waiting for legal acceptance.
+ launcher.markWindowReady()
const decision = await gate.waitForDecision()
disposeDisclaimerIpc()
if (disposeIpcIngress === disposeDisclaimerIpc) {
diff --git a/src/main/launcher.test.ts b/src/main/launcher.test.ts
index 76ff360e..a7025fb8 100644
--- a/src/main/launcher.test.ts
+++ b/src/main/launcher.test.ts
@@ -48,6 +48,7 @@ describe('setupLauncher', () => {
mockOn.mockReset()
mockRequestLock.mockReturnValue(true)
mockHasSingleInstanceLock.mockReturnValue(true)
+ mockGetLoginItemSettings.mockReturnValue({ wasOpenedAtLogin: false })
callbacks.onProtocolUrl.mockClear()
callbacks.onTorrentFile.mockClear()
callbacks.onShowWindow.mockClear()
@@ -118,11 +119,13 @@ describe('setupLauncher', () => {
expect(mockExit).toHaveBeenCalledWith(0)
expect(handle.bridgeDataDirLockRecoveryAuthority).toBeNull()
expect(mockOn).not.toHaveBeenCalled()
+ expect(() => handle.markWindowReady()).not.toThrow()
})
- it('returns handle with wasOpenedAtLogin and flushDeferred', () => {
+ it('returns separate window and download ingress readiness handles', () => {
const handle = setupLauncher(callbacks)
expect(typeof handle.wasOpenedAtLogin).toBe('boolean')
+ expect(typeof handle.markWindowReady).toBe('function')
expect(typeof handle.flushDeferred).toBe('function')
expect(handle.bridgeDataDirLockRecoveryAuthority).toEqual({
ownershipEpoch: expect.stringMatching(/^[A-Za-z0-9_-]{43}$/u),
@@ -167,6 +170,76 @@ describe('setupLauncher', () => {
expect(registeredEvents).toContain('open-file')
})
+ describe.each(['win32', 'linux'])('%s window activation', (platform) => {
+ function emitSecondInstance(argv: string[] = ['Motrix.exe']) {
+ const handler = mockOn.mock.calls.find(
+ ([name]) => name === 'second-instance'
+ )?.[1]
+ expect(handler).toBeTypeOf('function')
+ handler({}, argv)
+ }
+
+ beforeEach(() => {
+ const originalPlatform = process.platform
+ const originalArgv = process.argv
+ Object.defineProperty(process, 'platform', { value: platform })
+ process.argv = ['Motrix.exe']
+ return () => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform })
+ process.argv = originalArgv
+ }
+ })
+
+ it('replays early shortcut launches once after windows are ready', () => {
+ const handle = setupLauncher(callbacks)
+ emitSecondInstance()
+ emitSecondInstance()
+ expect(callbacks.onShowWindow).not.toHaveBeenCalled()
+
+ handle.markWindowReady()
+ expect(callbacks.onShowWindow).toHaveBeenCalledOnce()
+ handle.markWindowReady()
+ handle.flushDeferred()
+ expect(callbacks.onShowWindow).toHaveBeenCalledOnce()
+
+ emitSecondInstance()
+ expect(callbacks.onShowWindow).toHaveBeenCalledTimes(2)
+ })
+
+ it('can reopen onboarding while download ingress remains deferred', () => {
+ const handle = setupLauncher(callbacks)
+ handle.markWindowReady()
+ emitSecondInstance(['Motrix.exe', 'magnet:?xt=urn:btih:pending'])
+ expect(callbacks.onShowWindow).toHaveBeenCalledOnce()
+ expect(callbacks.onProtocolUrl).not.toHaveBeenCalled()
+
+ handle.flushDeferred()
+ expect(callbacks.onProtocolUrl).toHaveBeenCalledExactlyOnceWith(
+ 'magnet:?xt=urn:btih:pending'
+ )
+ expect(callbacks.onShowWindow).toHaveBeenCalledOnce()
+ expect(callbacks.onShowWindow.mock.invocationCallOrder[0]).toBeLessThan(
+ callbacks.onProtocolUrl.mock.invocationCallOrder[0]
+ )
+ })
+
+ it('does not reveal a background launch without a second launch', () => {
+ const handle = setupLauncher(callbacks)
+ handle.markWindowReady()
+ handle.flushDeferred()
+ expect(callbacks.onShowWindow).not.toHaveBeenCalled()
+ })
+
+ it('does not discard a pending activation when download ingress flushes', () => {
+ const handle = setupLauncher(callbacks)
+ emitSecondInstance()
+ handle.flushDeferred()
+ expect(callbacks.onShowWindow).not.toHaveBeenCalled()
+ handle.markWindowReady()
+ expect(callbacks.onShowWindow).toHaveBeenCalledOnce()
+ })
+ })
+
it('flushDeferred drains pending URLs', () => {
mockOn.mockImplementation(((
event: string,
@@ -191,6 +264,7 @@ describe('setupLauncher', () => {
Object.defineProperty(process, 'platform', { value: 'linux' })
try {
const handle = setupLauncher(callbacks)
+ handle.markWindowReady()
const secondInstanceHandler = mockOn.mock.calls.find(
(call: unknown[]) => call[0] === 'second-instance'
)?.[1] as ((_event: unknown, argv: string[]) => void) | undefined
@@ -218,6 +292,7 @@ describe('setupLauncher', () => {
Object.defineProperty(process, 'platform', { value: 'linux' })
try {
const handle = setupLauncher(callbacks)
+ handle.markWindowReady()
const secondInstanceHandler = mockOn.mock.calls.find(
(call: unknown[]) => call[0] === 'second-instance'
)?.[1] as ((_event: unknown, argv: string[]) => void) | undefined
@@ -245,6 +320,7 @@ describe('setupLauncher', () => {
Object.defineProperty(process, 'platform', { value: 'linux' })
try {
const handle = setupLauncher(callbacks)
+ handle.markWindowReady()
handle.flushDeferred()
const secondInstanceHandler = mockOn.mock.calls.find(
(call: unknown[]) => call[0] === 'second-instance'
diff --git a/src/main/launcher.ts b/src/main/launcher.ts
index d27ec763..19fb2197 100644
--- a/src/main/launcher.ts
+++ b/src/main/launcher.ts
@@ -17,6 +17,8 @@ export interface LauncherHandle {
wasOpenedAtLogin: boolean
/** OS-level process ownership proof used only for bridge crash recovery. */
bridgeDataDirLockRecoveryAuthority: BridgeDataDirLockRecoveryAuthority | null
+ /** Enable window activation independently of deferred download ingress. */
+ markWindowReady: () => void
flushDeferred: () => void
}
@@ -60,6 +62,7 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
return {
wasOpenedAtLogin: false,
bridgeDataDirLockRecoveryAuthority: null,
+ markWindowReady: () => undefined,
flushDeferred: () => undefined,
}
}
@@ -87,6 +90,8 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
const pendingUrls: string[] = []
const pendingFiles: string[] = []
let flushed = false
+ let windowReady = false
+ let pendingShowWindow = false
function dispatchUrl(url: string) {
if (
@@ -124,7 +129,14 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
// second-instance (Windows/Linux: second launch passes argv)
app.on('second-instance', (_event, argv) => {
log.info('second instance detected')
- callbacks.onShowWindow()
+ if (windowReady) {
+ callbacks.onShowWindow()
+ } else {
+ // A desktop shortcut can be opened while settings and windows are still
+ // initializing. Retain that intent instead of losing it to an absent
+ // WindowManager; repeated launches need only one eventual activation.
+ pendingShowWindow = true
+ }
if (process.platform !== 'darwin' && argv.length > 1) {
const url = extractUrlFromArgv(argv)
@@ -156,6 +168,13 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
return {
wasOpenedAtLogin,
bridgeDataDirLockRecoveryAuthority,
+ markWindowReady() {
+ windowReady = true
+ if (pendingShowWindow) {
+ pendingShowWindow = false
+ callbacks.onShowWindow()
+ }
+ },
flushDeferred() {
flushed = true
for (const url of pendingUrls) {
diff --git a/src/main/window/window-manager-dock.test.ts b/src/main/window/window-manager-dock.test.ts
index 3a966190..d0547b63 100644
--- a/src/main/window/window-manager-dock.test.ts
+++ b/src/main/window/window-manager-dock.test.ts
@@ -34,6 +34,7 @@ vi.mock('electron', () => {
isVisible = vi.fn(() => this.visible)
isFocused = vi.fn(() => true)
isMaximized = vi.fn(() => false)
+ isMinimized = vi.fn(() => false)
isFullScreen = vi.fn(() => false)
getBounds = vi.fn(() => ({ x: 0, y: 0, width: 1024, height: 768 }))
getNormalBounds = vi.fn(() => ({
diff --git a/src/main/window/window-manager.test.ts b/src/main/window/window-manager.test.ts
index 53046544..30e0f182 100644
--- a/src/main/window/window-manager.test.ts
+++ b/src/main/window/window-manager.test.ts
@@ -13,6 +13,7 @@ vi.mock('electron', () => {
setWindowOpenHandler: ReturnType<typeof vi.fn>
}
private _destroyed = false
+ private _minimized = false
private _visible: boolean
private _bounds: { x: number; y: number; width: number; height: number }
@@ -55,6 +56,13 @@ vi.mock('electron', () => {
isVisible = vi.fn(() => this._visible)
isFocused = vi.fn(() => true)
isMaximized = vi.fn(() => false)
+ isMinimized = vi.fn(() => this._minimized)
+ minimize = vi.fn(() => {
+ this._minimized = true
+ })
+ restore = vi.fn(() => {
+ this._minimized = false
+ })
isFullScreen = vi.fn(() => false)
getBounds = vi.fn(() => ({ ...this._bounds }))
getNormalBounds = vi.fn(() => ({ ...this._bounds }))
@@ -144,6 +152,51 @@ describe('WindowManager', () => {
vi.clearAllMocks()
})
+ it.each(['show', 'open', 'toggle'] as const)(
+ '%s restores a minimized Windows window instead of dismissing it',
+ (action) => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ platform: 'win32',
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ })
+ const win = wm.open('main')
+ win.show()
+ win.minimize()
+ expect(win.isMinimized()).toBe(true)
+
+ wm[action]('main')
+
+ expect(wm.get('main')).toBe(win)
+ expect(win.isMinimized()).toBe(false)
+ expect(win.isVisible()).toBe(true)
+ expect(win.focus).toHaveBeenCalledOnce()
+ expect(win.hide).not.toHaveBeenCalled()
+ expect(win.destroy).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['show', 'open', 'toggle'] as const)(
+ '%s preserves an existing maximized window',
+ (action) => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ platform: 'win32',
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ })
+ const win = wm.open('main', { show: false })
+ vi.mocked(win.isMaximized).mockReturnValue(true)
+
+ wm[action]('main')
+
+ expect(win.restore).not.toHaveBeenCalled()
+ expect(win.isVisible()).toBe(true)
+ expect(win.focus).toHaveBeenCalledOnce()
+ }
+ )
+
it('opens a window with correct config', () => {
const sm = createMockSettingsManager()
const wm = new WindowManager({
diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.ts
index 5ca6e6be..e64ac4e8 100644
--- a/src/main/window/window-manager.ts
+++ b/src/main/window/window-manager.ts
@@ -70,8 +70,7 @@ export class WindowManager {
id = this.resolveOpenTarget(id)
const existing = this.windows.get(id)
if (existing && !existing.isDestroyed()) {
- existing.show()
- existing.focus()
+ this.focusWindow(id, existing)
return existing
}
@@ -127,8 +126,7 @@ export class WindowManager {
}
}
- win.show()
- win.focus()
+ this.focusWindow(id, win)
if (options && id === 'add-task') {
setTimeout(() => {
@@ -147,11 +145,10 @@ export class WindowManager {
return
}
- if (win.isVisible() && win.isFocused()) {
+ if (!win.isMinimized() && win.isVisible() && win.isFocused()) {
this.close(id)
} else {
- win.show()
- win.focus()
+ this.focusWindow(id, win)
}
}
@@ -306,6 +303,13 @@ export class WindowManager {
// ─── Private ──────────────────────────────────────────
+ private focusWindow(id: WindowId, win: BrowserWindow): void {
+ this.lastFocusRequested = id
+ if (win.isMinimized()) win.restore()
+ win.show()
+ win.focus()
+ }
+
private resolveOpenTarget(id: WindowId): WindowId {
return this.deps.resolveOpenTarget?.(id) ?? id
}