Skip to content

A full-featured download manager.

fix(window): preserve hidden main when cancelling new tasks (#2495)

Dr_rOote397d85e0173
diff --git a/e2e/add-task.spec.ts b/e2e/add-task.spec.ts
index 15080c92..2322d631 100644
--- a/e2e/add-task.spec.ts
+++ b/e2e/add-task.spec.ts
@@ -411,7 +411,7 @@ test.describe('add task', () => {
})
}
- test('http url submitted via the add-task window appears in Downloads', async ({
+ test('http url submitted via the add-task window reveals hidden main and appears in Downloads', async ({
electronApp,
mainWindow,
httpFixture,
@@ -437,11 +437,23 @@ test.describe('add task', () => {
.getByRole('textbox', { name: 'URLs' })
.fill(httpFixture.fileUrl)
- // FooterActions renders the submit as <Button> with text "Download"
- // (common.download). After submit the AddTaskWindow auto-closes
- // via electronServices.closeHost; we don't assert on that since
- // hide-vs-close is a window-manager detail.
+ // Successful creation still reveals main, even if it was hidden while
+ // the add-task window was open.
+ await electronApp.evaluate(({ BrowserWindow }) => {
+ BrowserWindow.getAllWindows()
+ .find((window) => window.webContents.getURL().includes('w=main'))
+ ?.hide()
+ })
await addTaskPage.getByRole('button', { name: 'Download' }).click()
+ await expect
+ .poll(() =>
+ electronApp.evaluate(({ BrowserWindow }) =>
+ BrowserWindow.getAllWindows()
+ .find((window) => window.webContents.getURL().includes('w=main'))
+ ?.isVisible()
+ )
+ )
+ .toBe(true)
// Switch the main window to the Downloads route. NavLink renders
// an <a>; getByRole('link') is the stable accessor across i18n.
diff --git a/e2e/window-reopen.spec.ts b/e2e/window-reopen.spec.ts
index 7ab52d3d..17b4f869 100644
--- a/e2e/window-reopen.spec.ts
+++ b/e2e/window-reopen.spec.ts
@@ -5,6 +5,7 @@ import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
import { RunMode } from '../src/shared/constants'
import {
expect,
+ findAddTaskWindow,
launchMotrix,
test,
waitForQueryHandlers,
@@ -31,6 +32,70 @@ async function windowState(app: ElectronApplication, id = 'main') {
}, id)
}
+for (const state of ['visible', 'hidden', 'released'] as const) {
+ test(`cancelling a new task preserves a ${state} main window`, async ({
+ userDataDir,
+ rpcPort,
+ }) => {
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ onboarding: { disclaimerAccepted: true },
+ tracker: { autoSync: false },
+ app: {
+ language: 'en-US',
+ autofillClipboardLinks: false,
+ runMode: RunMode.Standard,
+ lightweightMode: state === 'released',
+ },
+ })
+ )
+ const app = await launchMotrix({ userDataDir, rpcPort })
+ try {
+ const main = await app.firstWindow()
+ await main.waitForLoadState('domcontentloaded')
+ await waitForQueryHandlers(main)
+ await expect
+ .poll(() => windowState(app))
+ .toEqual({ visible: true, minimized: false })
+ if (state !== 'visible') {
+ await app.evaluate(({ BrowserWindow }) => {
+ BrowserWindow.getAllWindows()
+ .find((window) => window.webContents.getURL().includes('w=main'))
+ ?.close()
+ })
+ }
+ const expectedMain =
+ state === 'released'
+ ? null
+ : { visible: state === 'visible', minimized: false }
+ await expect.poll(() => windowState(app)).toEqual(expectedMain)
+
+ const magnetUri =
+ 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567'
+ await app.evaluate(({ app: electronApp }, uri) => {
+ electronApp.emit(
+ 'open-url',
+ { preventDefault: () => undefined } as Electron.Event,
+ uri
+ )
+ }, magnetUri)
+ const addTask = await findAddTaskWindow(app)
+ await expect(addTask.getByRole('textbox', { name: 'URLs' })).toHaveValue(
+ magnetUri
+ )
+ expect(await windowState(app)).toEqual(expectedMain)
+ await addTask.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect.poll(() => addTask.isClosed()).toBe(true)
+
+ expect(await windowState(app)).toEqual(expectedMain)
+ } finally {
+ await app.close()
+ }
+ })
+}
+
test('a second launch restores a minimized main window', async ({
electronApp,
mainWindow,
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 6250a3a5..5854516a 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -867,6 +867,39 @@ describe('buildCommandHandlers', () => {
expect(closeAndRecycle).toHaveBeenCalledWith('add-task')
})
+ it.each(['visible', 'hidden', 'released'] as const)(
+ 'CloseCurrentWindow preserves a %s main window on cancel',
+ async (state) => {
+ const ctx = fakeCtx()
+ const main =
+ state === 'released'
+ ? null
+ : { isVisible: vi.fn(() => state === 'visible') }
+ ctx.windowManager = {
+ ...ctx.windowManager,
+ getWindowIdBySender: vi.fn(() => 'add-task'),
+ get: vi.fn(() => main),
+ closeAndRecycle: vi.fn(),
+ show: vi.fn(),
+ } as any
+ // @ts-expect-error partial ctx
+ const handlers = buildCommandHandlers(ctx)
+
+ await handlers[Commands.CloseCurrentWindow]?.({} as never, {
+ showMain: 'if-visible',
+ })
+
+ expect(ctx.windowManager.closeAndRecycle).toHaveBeenCalledWith('add-task')
+ expect(ctx.protocolManager.resetDialogState).toHaveBeenCalled()
+ if (state === 'visible') {
+ expect(ctx.windowManager.show).toHaveBeenCalledWith('main')
+ } else {
+ expect(ctx.windowManager.show).not.toHaveBeenCalled()
+ }
+ expect(ctx.eventBus.emit).not.toHaveBeenCalled()
+ }
+ )
+
it('CloseCurrentWindow emits NavigateTo when navigateMainTo is set', async () => {
const ctx = fakeCtx()
const getWindowIdBySender = vi.fn(() => 'add-task')
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 4363b2d0..a141ac20 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -1447,7 +1447,11 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
protocolManager.resetDialogState()
}
windowManager.closeAndRecycle(id)
- if (options.showMain) {
+ if (
+ options.showMain === true ||
+ (options.showMain === 'if-visible' &&
+ windowManager.get('main')?.isVisible())
+ ) {
windowManager.show('main')
}
if (options.navigateMainTo) {
diff --git a/src/renderer/platform/services.tsx b/src/renderer/platform/services.tsx
index ac165f63..8858a86f 100644
--- a/src/renderer/platform/services.tsx
+++ b/src/renderer/platform/services.tsx
@@ -1,3 +1,4 @@
+import type { CloseCurrentWindowPayload } from '@shared/schemas/close-current-window'
import type { FilePickerOptions } from '@shared/schemas/file-picker'
import { createContext, type ReactNode, useContext } from 'react'
@@ -23,16 +24,11 @@ export interface PlatformServices {
allowFavoriteEditing?: boolean
}
): Promise<string | null>
- closeHost(options?: {
- showMain?: boolean
- /**
- * Electron only: after closing this child window and showing main,
- * ask the main window's React Router to navigate to this path.
- * Web ignores this — web hosts (e.g. dialogs) navigate via
- * `useNavigate()` directly because they share the main React tree.
- */
- navigateMainTo?: string
- }): Promise<void> | void
+ /**
+ * Electron uses the payload to focus or navigate the main window after closing.
+ * Web hosts ignore it and navigate via `useNavigate()` in the shared React tree.
+ */
+ closeHost(options?: CloseCurrentWindowPayload): Promise<void> | void
readClipboard(): Promise<string>
openExternal(url: string): Promise<void> | void
notify(
diff --git a/src/renderer/windows/add-task-window.test.tsx b/src/renderer/windows/add-task-window.test.tsx
index d1b8cd8a..e0a2d895 100644
--- a/src/renderer/windows/add-task-window.test.tsx
+++ b/src/renderer/windows/add-task-window.test.tsx
@@ -46,6 +46,21 @@ describe('AddTaskWindow', () => {
vi.restoreAllMocks()
})
+ it('cancels without requesting a hidden main window to be shown', async () => {
+ const user = userEvent.setup()
+ render(<AddTaskWindow />)
+
+ await user.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.CloseCurrentWindow, {
+ showMain: 'if-visible',
+ })
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.anything()
+ )
+ })
+
it('hosts and displays task creation errors in the standalone window', async () => {
const user = userEvent.setup()
const { baseElement } = render(<AddTaskWindow />)
diff --git a/src/renderer/windows/add-task-window.tsx b/src/renderer/windows/add-task-window.tsx
index 38f7cd7f..74659bee 100644
--- a/src/renderer/windows/add-task-window.tsx
+++ b/src/renderer/windows/add-task-window.tsx
@@ -52,7 +52,9 @@ export function AddTaskWindow() {
navigateMainTo: `/downloads/all?task=${encodeURIComponent(taskId)}`,
})
}
- onCancel={() => void electronServices.closeHost({ showMain: true })}
+ onCancel={() =>
+ void electronServices.closeHost({ showMain: 'if-visible' })
+ }
subscribeEvents
/>
</PlatformServicesProvider>
diff --git a/src/shared/schemas/close-current-window.ts b/src/shared/schemas/close-current-window.ts
index 80e82029..079570f2 100644
--- a/src/shared/schemas/close-current-window.ts
+++ b/src/shared/schemas/close-current-window.ts
@@ -5,6 +5,7 @@ import { z } from 'zod'
*
* - `showMain`: focus the main window after closing the current one
* (used when the closing window was a child like `add-task`).
+ * `true` always shows it; `'if-visible'` only focuses it if already visible.
* - `navigateMainTo`: when set, emit Events.NavigateTo with this path
* after showing main. Must be an absolute in-app route (`/...`) so
* a malformed value cannot push a non-route string into the main
@@ -18,7 +19,7 @@ import { z } from 'zod'
* one place and an explicit `?? {}` in another.
*/
export const closeCurrentWindowSchema = z.object({
- showMain: z.boolean().optional(),
+ showMain: z.union([z.boolean(), z.literal('if-visible')]).optional(),
navigateMainTo: z.string().min(1).startsWith('/').optional(),
})