Skip to content

A full-featured download manager.

fix(navigation): unify task links and notification fallbacks (#2163)

Dr_rOot19c53e4dd1b7
diff --git a/e2e/task-inspector-activity.spec.ts b/e2e/task-inspector-activity.spec.ts
index 8ddb5501..3d672cf1 100644
--- a/e2e/task-inspector-activity.spec.ts
+++ b/e2e/task-inspector-activity.spec.ts
@@ -175,7 +175,7 @@ async function addLiveDownload(
async function launchSeededApp(
userDataDir: string,
- options: { failAfterFirstQuery?: boolean } = {}
+ options: { failAfterFirstQuery?: boolean; initialTaskId?: string } = {}
): Promise<{ app: ElectronApplication; page: Page }> {
const preparation = await launchMotrix({
userDataDir,
@@ -201,6 +201,14 @@ async function launchSeededApp(
: {}),
},
})
+ if (options.initialTaskId) {
+ await app.evaluate(
+ ({ app: electronApp }, url) => {
+ electronApp.emit('open-url', { preventDefault: () => undefined }, url)
+ },
+ `motrix://tasks/${encodeURIComponent(options.initialTaskId)}`
+ )
+ }
const page = await firstWindow(app)
const geometry = await configureTaskInspectorWindow(app, page, {
width: 914,
@@ -350,6 +358,128 @@ async function presentActiveReference(
test.describe('Task Inspector Activity', () => {
test.setTimeout(180_000)
+ test('opens the linked task details and restores them after recreating the main window', async ({
+ userDataDir,
+ }) => {
+ const { app, page } = await launchSeededApp(userDataDir, {
+ initialTaskId: TASK_INSPECTOR_ACTIVITY_IDS.rich,
+ })
+ const openTask = async (taskId: string) => {
+ await app.evaluate(
+ ({ app: electronApp }, url) => {
+ electronApp.emit('open-url', { preventDefault: () => undefined }, url)
+ },
+ `motrix://tasks/${encodeURIComponent(taskId)}`
+ )
+ }
+ const expectTaskDetails = async (
+ targetPage: Page,
+ taskId: string,
+ taskName: string
+ ) => {
+ await expect
+ .poll(() => targetPage.url())
+ .toContain(`#/downloads/all?task=${encodeURIComponent(taskId)}`)
+ const inspector = targetPage.getByRole('dialog', {
+ name: 'Task Inspector',
+ exact: true,
+ })
+ await expect(inspector).toBeVisible()
+ await expect(inspector.getByText(taskName, { exact: true })).toBeVisible()
+ await expect(
+ targetPage.getByRole('row', { name: new RegExp(taskName, 'i') })
+ ).toHaveAttribute('aria-selected', 'true')
+ }
+
+ try {
+ await expectTaskDetails(
+ page,
+ TASK_INSPECTOR_ACTIVITY_IDS.rich,
+ TASK_INSPECTOR_ACTIVITY_NAMES.rich
+ )
+ await openTask(TASK_INSPECTOR_ACTIVITY_IDS.error)
+ await expectTaskDetails(
+ page,
+ TASK_INSPECTOR_ACTIVITY_IDS.error,
+ TASK_INSPECTOR_ACTIVITY_NAMES.error
+ )
+
+ const inspector = page.getByRole('dialog', { name: 'Task Inspector' })
+ await inspector
+ .getByRole('button', { name: 'Close', exact: true })
+ .click()
+ await expect(inspector).toBeHidden()
+ await openTask(TASK_INSPECTOR_ACTIVITY_IDS.error)
+ await expectTaskDetails(
+ page,
+ TASK_INSPECTOR_ACTIVITY_IDS.error,
+ TASK_INSPECTOR_ACTIVITY_NAMES.error
+ )
+
+ const closed = page.waitForEvent('close')
+ await app.evaluate(({ BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ if (!main) throw new Error('Main window not found')
+ main.destroy()
+ })
+ await closed
+ const recreated = app.waitForEvent('window', {
+ predicate: async (candidate) => {
+ await candidate.waitForLoadState('domcontentloaded')
+ return candidate.url().includes('w=main')
+ },
+ })
+ await openTask(TASK_INSPECTOR_ACTIVITY_IDS.rich)
+ const restoredPage = await recreated
+ await restoredPage.waitForLoadState('domcontentloaded')
+ await expectTaskDetails(
+ restoredPage,
+ TASK_INSPECTOR_ACTIVITY_IDS.rich,
+ TASK_INSPECTOR_ACTIVITY_NAMES.rich
+ )
+
+ // A popup can retain a row after the App has already removed its task.
+ await restoredPage.evaluate(
+ async ({ command, taskId }) => {
+ const api = (
+ window as unknown as {
+ motrix: {
+ invoke: (channel: string, payload: unknown) => Promise<unknown>
+ }
+ }
+ ).motrix
+ await api.invoke(command, { taskId, deleteWithFiles: false })
+ },
+ {
+ command: Commands.RemoveTask,
+ taskId: TASK_INSPECTOR_ACTIVITY_IDS.rich,
+ }
+ )
+ for (const missingTaskId of [
+ TASK_INSPECTOR_ACTIVITY_IDS.rich,
+ 'already-deleted-task',
+ ]) {
+ await openTask(TASK_INSPECTOR_ACTIVITY_IDS.error)
+ await expectTaskDetails(
+ restoredPage,
+ TASK_INSPECTOR_ACTIVITY_IDS.error,
+ TASK_INSPECTOR_ACTIVITY_NAMES.error
+ )
+ await openTask(missingTaskId)
+ await expect
+ .poll(() => new URL(restoredPage.url()).hash)
+ .toBe('#/downloads/all')
+ await expect(
+ restoredPage.getByRole('dialog', { name: 'Task Inspector' })
+ ).toBeHidden()
+ }
+ } finally {
+ await app.close().catch(() => {})
+ }
+ })
+
test('keeps Activity scrollable in an overlay inside the minimum 914 by 672 window', async ({
userDataDir,
}) => {
diff --git a/src/main/index.ts b/src/main/index.ts
index ec9cb1fe..05037b0b 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -121,6 +121,10 @@ import {
import type { NatManager } from '@motrix/nat'
import { APP_ID } from '@shared/constants'
import { DEFAULT_LOCALE, type SupportedLocale } from '@shared/constants/locales'
+import {
+ ALL_DOWNLOADS_ROUTE,
+ resolveTaskRoute,
+} from '@shared/lib/task-navigation'
import { Events } from '@shared/protocol/events'
import {
DEFAULT_BYTE_UNIT_PREFERENCE,
@@ -637,14 +641,18 @@ function loadWindowUrl(win: BrowserWindow, route: string) {
function dispatchWhenReady(
win: BrowserWindow,
channel: string,
- payload: unknown
+ payload: unknown,
+ resolvePayload?: () => unknown
) {
const dispatchLog = getLogger('dispatch')
const send = (reason: string) => {
setTimeout(() => {
if (!win.isDestroyed()) {
dispatchLog.info({ channel, reason }, 'webContents.send firing')
- win.webContents.send(channel, payload)
+ win.webContents.send(
+ channel,
+ resolvePayload ? resolvePayload() : payload
+ )
} else {
dispatchLog.warn({ channel, reason }, 'window destroyed before send')
}
@@ -659,6 +667,21 @@ function dispatchWhenReady(
}
}
+// Notifications and protocol links share the same last-moment availability
+// check, including the wait for a released main window to finish loading.
+function navigateToTask(taskId: string) {
+ runShellAsyncWork('task navigation', async () => {
+ // A cold-start link can arrive before the persisted tasks are restored.
+ await mainProcessWork.waitForStartup()
+ if (!mainProcessWork.isAccepting()) return
+ const win = windowManager?.get('main')
+ if (!win || win.isDestroyed()) return
+ dispatchWhenReady(win, Events.NavigateTo, ALL_DOWNLOADS_ROUTE, () =>
+ resolveTaskRoute(taskId, taskManager.getById(taskId)?.status)
+ )
+ })
+}
+
// Each new add-task BrowserWindow gets a `closed` listener that resets
// protocolManager's dialog state. Without this, after the first .torrent
// open + close, dialogActive stays true and subsequent opens fall through
@@ -721,6 +744,11 @@ const protocolManager = createProtocolManager({
if (!win || win.isDestroyed()) return
dispatchWhenReady(win, Events.NavigateTo, `/plugins/${pluginId}`)
},
+ onOpenTaskDetail: (taskId) => {
+ if (!windowManager) return
+ windowManager.show('main')
+ navigateToTask(taskId)
+ },
})
setupExceptionHandler({
@@ -1642,14 +1670,12 @@ async function initializeMainProcess(): Promise<void> {
showMainWindow: () => windowManager?.show('main'),
getAppSettings: () => settingsManager.getApp(),
translate: i18n.t.bind(i18n),
- navigateToTask: (taskId) => {
+ getTaskStatus: (taskId) => taskManager.getById(taskId)?.status ?? null,
+ navigateToTask,
+ navigateToDownloads: () => {
const win = windowManager?.get('main')
if (!win || win.isDestroyed()) return
- dispatchWhenReady(
- win,
- Events.NavigateTo,
- `/downloads/all?task=${encodeURIComponent(taskId)}`
- )
+ dispatchWhenReady(win, Events.NavigateTo, ALL_DOWNLOADS_ROUTE)
},
revealTaskInFolder: (taskId) => revealNotificationTask({ taskId }),
log,
diff --git a/src/main/notifications/os-bridge.test.ts b/src/main/notifications/os-bridge.test.ts
index 2b4823fe..bb520e3f 100644
--- a/src/main/notifications/os-bridge.test.ts
+++ b/src/main/notifications/os-bridge.test.ts
@@ -12,6 +12,7 @@ import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
import type { AppNotification } from '@shared/types/notification'
import { NotificationKinds } from '@shared/types/notification'
import type { MotrixAppSettings } from '@shared/types/settings'
+import { TaskStatus } from '@shared/types/task'
import { afterEach, describe, expect, it, vi } from 'vitest'
// ---------------------------------------------------------------------------
@@ -145,12 +146,18 @@ function baseDeps(overrides: {
isSupported?: () => boolean
log?: ReturnType<typeof makeLog>
showMainWindow?: () => void
+ getTaskStatus?: (taskId: string) => TaskStatus | null
navigateToTask?: (taskId: string) => void
+ navigateToDownloads?: () => void
revealTaskInFolder?: (taskId: string) => Promise<void>
translate?: (key: string, params?: Record<string, string>) => string
}) {
const { subscribe, deliver } = makeCapturingSubscribe()
const navigateToTask = vi.fn(overrides.navigateToTask)
+ const navigateToDownloads = vi.fn(overrides.navigateToDownloads)
+ const getTaskStatus = vi.fn(
+ overrides.getTaskStatus ?? (() => TaskStatus.Completed)
+ )
const showMainWindow = vi.fn(overrides.showMainWindow)
const revealTaskInFolder = vi.fn(
overrides.revealTaskInFolder ?? (async () => {})
@@ -164,6 +171,8 @@ function baseDeps(overrides: {
deliver,
log,
navigateToTask,
+ navigateToDownloads,
+ getTaskStatus,
showMainWindow,
revealTaskInFolder,
deps: {
@@ -173,6 +182,8 @@ function baseDeps(overrides: {
getAppSettings: () => settings,
translate,
navigateToTask,
+ navigateToDownloads,
+ getTaskStatus,
revealTaskInFolder,
isSupported: overrides.isSupported ?? (() => true),
createNotification: overrides.createNotification,
@@ -309,6 +320,8 @@ describe('createOsNotificationBridge — subscription', () => {
getAppSettings: () => makeSettings(),
translate: (key) => key,
showMainWindow: vi.fn(),
+ getTaskStatus: () => null,
+ navigateToDownloads: vi.fn(),
revealTaskInFolder: vi.fn(async () => {}),
navigateToTask: vi.fn(),
isSupported: () => true,
@@ -444,6 +457,100 @@ describe('createOsNotificationBridge — body rendering', () => {
// ---------------------------------------------------------------------------
describe('createOsNotificationBridge — click behavior', () => {
+ it.each([
+ [NotificationKinds.TaskComplete, null],
+ [NotificationKinds.TaskComplete, TaskStatus.Removed],
+ [NotificationKinds.TaskError, null],
+ [NotificationKinds.TaskError, TaskStatus.Removed],
+ ])(
+ 'opens all downloads when a %s task becomes %s before the click',
+ async (kind, removedStatus) => {
+ const { createNotification, instances } = makeNotificationFactory()
+ let status: TaskStatus | null = TaskStatus.Completed
+ const {
+ deps,
+ deliver,
+ showMainWindow,
+ navigateToTask,
+ navigateToDownloads,
+ revealTaskInFolder,
+ getTaskStatus,
+ log,
+ } = baseDeps({
+ settings: makeSettings({ notifyOnComplete: true, notifyOnError: true }),
+ createNotification,
+ getTaskStatus: () => status,
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ kind, taskId: 't-1' }))
+ status = removedStatus
+
+ await instances[0].click()
+
+ expect(getTaskStatus).toHaveBeenCalledWith('t-1')
+ expect(showMainWindow).toHaveBeenCalledOnce()
+ expect(showMainWindow).toHaveBeenCalledBefore(navigateToDownloads)
+ expect(navigateToDownloads).toHaveBeenCalledOnce()
+ expect(navigateToTask).not.toHaveBeenCalled()
+ expect(revealTaskInFolder).not.toHaveBeenCalled()
+ expect(log.warn).not.toHaveBeenCalled()
+ }
+ )
+
+ it('rechecks task availability after an asynchronous reveal failure', async () => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const reveal = Promise.withResolvers<void>()
+ let status: TaskStatus | null = TaskStatus.Completed
+ const {
+ deps,
+ deliver,
+ navigateToTask,
+ navigateToDownloads,
+ showMainWindow,
+ log,
+ } = baseDeps({
+ settings: makeSettings({ notifyOnComplete: true }),
+ createNotification,
+ getTaskStatus: () => status,
+ revealTaskInFolder: () => reveal.promise,
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+ const click = instances[0].click()
+ status = null
+ reveal.reject(new Error('task removed while revealing'))
+ await click
+
+ expect(showMainWindow).toHaveBeenCalledOnce()
+ expect(navigateToDownloads).toHaveBeenCalledOnce()
+ expect(navigateToTask).not.toHaveBeenCalled()
+ expect(log.warn).not.toHaveBeenCalled()
+ })
+
+ it('rechecks task availability after recreating the main window', async () => {
+ const { createNotification, instances } = makeNotificationFactory()
+ let status: TaskStatus | null = TaskStatus.Error
+ const { deps, deliver, navigateToTask, navigateToDownloads } = baseDeps({
+ settings: makeSettings({ notifyOnError: true }),
+ createNotification,
+ getTaskStatus: () => status,
+ showMainWindow: () => {
+ status = null
+ },
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(
+ makeNotification({ kind: NotificationKinds.TaskError, taskId: 't-1' })
+ )
+ await instances[0].click()
+
+ expect(navigateToDownloads).toHaveBeenCalledOnce()
+ expect(navigateToTask).not.toHaveBeenCalled()
+ })
+
it.each(['hidden', 'released'])(
'reveals a completed task without showing the %s main window',
async (windowState) => {
@@ -631,7 +738,15 @@ describe('createOsNotificationBridge — click behavior', () => {
it('does not reopen the app if disposed while revealing', async () => {
const { createNotification, instances } = makeNotificationFactory()
const reveal = Promise.withResolvers<void>()
- const { deps, deliver, showMainWindow, navigateToTask } = baseDeps({
+ const {
+ deps,
+ deliver,
+ showMainWindow,
+ navigateToTask,
+ navigateToDownloads,
+ getTaskStatus,
+ log,
+ } = baseDeps({
settings: makeSettings({ notifyOnComplete: true }),
createNotification,
revealTaskInFolder: () => reveal.promise,
@@ -641,11 +756,14 @@ describe('createOsNotificationBridge — click behavior', () => {
deliver(makeNotification({ taskId: 't-1' }))
const click = instances[0].click()
bridge.dispose()
+ getTaskStatus.mockReturnValue(null)
reveal.reject(new Error('folder unavailable'))
await click
expect(showMainWindow).not.toHaveBeenCalled()
expect(navigateToTask).not.toHaveBeenCalled()
+ expect(navigateToDownloads).not.toHaveBeenCalled()
+ expect(log.warn).not.toHaveBeenCalled()
})
})
@@ -736,6 +854,8 @@ describe('createOsNotificationBridge — Electron defaults', () => {
getAppSettings: () => makeSettings({ notifyOnComplete: true }),
translate: (key) => key,
showMainWindow: vi.fn(),
+ getTaskStatus: () => null,
+ navigateToDownloads: vi.fn(),
revealTaskInFolder: vi.fn(async () => {}),
navigateToTask: vi.fn(),
log: { warn: vi.fn() },
@@ -760,6 +880,8 @@ describe('createOsNotificationBridge — Electron defaults', () => {
getAppSettings: () => makeSettings({ notifyOnComplete: true }),
translate: (key) => key,
showMainWindow: vi.fn(),
+ getTaskStatus: () => null,
+ navigateToDownloads: vi.fn(),
revealTaskInFolder: vi.fn(async () => {}),
navigateToTask: vi.fn(),
log: { warn: vi.fn() },
diff --git a/src/main/notifications/os-bridge.ts b/src/main/notifications/os-bridge.ts
index ba534ec5..1a35dc93 100644
--- a/src/main/notifications/os-bridge.ts
+++ b/src/main/notifications/os-bridge.ts
@@ -1,9 +1,11 @@
import type { Logger } from '@core/logger'
+import { isTaskAvailable } from '@shared/lib/task-navigation'
import type { EventChannel } from '@shared/protocol/events'
import { Events } from '@shared/protocol/events'
import type { AppNotification } from '@shared/types/notification'
import { NotificationKinds } from '@shared/types/notification'
import type { MotrixAppSettings } from '@shared/types/settings'
+import type { TaskStatus } from '@shared/types/task'
import { Notification } from 'electron'
/** Structural subset of Electron's `BrowserWindow` this bridge needs. */
@@ -30,8 +32,11 @@ export interface OsNotificationBridgeDeps {
getAppSettings: () => MotrixAppSettings
/** `i18n.t.bind(i18n)` — follows `LocaleCoordinator` language switches. */
translate: (key: string, params?: Record<string, string>) => string
+ /** Read current state: an OS notification may outlive its task. */
+ getTaskStatus: (taskId: string) => TaskStatus | null
/** Navigate once the main window's renderer is ready. */
navigateToTask: (taskId: string) => void
+ navigateToDownloads: () => void
/** Reveal the task's current output, or its containing directory if missing. */
revealTaskInFolder: (taskId: string) => Promise<void>
isSupported?: () => boolean
@@ -83,23 +88,31 @@ export function createOsNotificationBridge(deps: OsNotificationBridgeDeps): {
try {
if (
payload.kind === NotificationKinds.TaskComplete &&
- payload.taskId != null
+ payload.taskId != null &&
+ isTaskAvailable(deps.getTaskStatus(payload.taskId))
) {
try {
await deps.revealTaskInFolder(payload.taskId)
return
} catch (err) {
- deps.log.warn(
- { err, taskId: payload.taskId },
- 'os-notification-bridge: reveal failed; opening task'
- )
+ if (disposed) return
+ if (isTaskAvailable(deps.getTaskStatus(payload.taskId))) {
+ deps.log.warn(
+ { err, taskId: payload.taskId },
+ 'os-notification-bridge: reveal failed; opening task'
+ )
+ }
}
}
if (disposed) return
deps.showMainWindow()
if (payload.taskId != null) {
- deps.navigateToTask(payload.taskId)
+ if (isTaskAvailable(deps.getTaskStatus(payload.taskId))) {
+ deps.navigateToTask(payload.taskId)
+ } else {
+ deps.navigateToDownloads()
+ }
}
} catch (err) {
deps.log.warn({ err }, 'os-notification-bridge: click handler threw')
diff --git a/src/main/platform/protocol-manager.test.ts b/src/main/platform/protocol-manager.test.ts
index 33919c4d..6d9209c1 100644
--- a/src/main/platform/protocol-manager.test.ts
+++ b/src/main/platform/protocol-manager.test.ts
@@ -66,6 +66,7 @@ function makeDeps(magnetEnabled = true) {
const onOpenAddTask = vi.fn()
const deliverToAddTask = vi.fn()
const onOpenPluginDetail = vi.fn()
+ const onOpenTaskDetail = vi.fn()
mockParse.mockResolvedValue(defaultMeta)
return {
getWindow: () => mockWindow as never,
@@ -76,6 +77,7 @@ function makeDeps(magnetEnabled = true) {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
mockWindow,
}
}
@@ -101,6 +103,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps(true)
const pm = createProtocolManager({
getWindow,
@@ -109,6 +112,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
expect(pm.register()).toEqual({ magnetMatchesSetting: true })
@@ -124,6 +128,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps(false)
const pm = createProtocolManager({
getWindow,
@@ -132,6 +137,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
expect(pm.register()).toEqual({ magnetMatchesSetting: true })
@@ -148,6 +154,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps(true)
const pm = createProtocolManager({
getWindow,
@@ -156,6 +163,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
expect(pm.register()).toEqual({ magnetMatchesSetting: null })
@@ -170,6 +178,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps(true)
const pm = createProtocolManager({
getWindow,
@@ -178,6 +187,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
platform: 'win32',
})
expect(pm.register()).toEqual({ magnetMatchesSetting: null })
@@ -194,6 +204,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps(true)
const pm = createProtocolManager({
getWindow,
@@ -202,6 +213,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
isAppImage: true,
})
expect(pm.register()).toEqual({ magnetMatchesSetting: null })
@@ -218,6 +230,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps(true)
mockSetAsDefault.mockReturnValue(false)
mockIsDefault.mockReturnValue(false)
@@ -228,6 +241,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
expect(pm.register()).toEqual({ magnetMatchesSetting: false })
@@ -235,6 +249,34 @@ describe('createProtocolManager', () => {
})
describe('handle', () => {
+ it.each(['task-123', '任务/一?#&%'])(
+ 'opens task details for encoded id %s',
+ (id) => {
+ const deps = makeDeps()
+ createProtocolManager(deps).handle(
+ `motrix://tasks/${encodeURIComponent(id)}`
+ )
+ expect(deps.onOpenTaskDetail).toHaveBeenCalledExactlyOnceWith(id)
+ expect(deps.onOpenAddTask).not.toHaveBeenCalled()
+ expect(deps.onOpenPluginDetail).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ 'motrix://tasks/',
+ 'motrix://tasks/%20',
+ 'motrix://tasks/%E0%A4%A',
+ 'motrix://tasks/task-1?other=task-2',
+ 'motrix://tasks/task-1#other',
+ 'motrix://user@tasks/task-1',
+ `motrix://tasks/${'a'.repeat(1025)}`,
+ ])('does not navigate to a task for malformed deeplink %s', (url) => {
+ const deps = makeDeps()
+ createProtocolManager(deps).handle(url)
+ expect(deps.onOpenTaskDetail).not.toHaveBeenCalled()
+ expect(deps.onOpenAddTask).not.toHaveBeenCalled()
+ })
+
it('opens add-task window with magnet in links prefill', () => {
const {
getWindow,
@@ -243,6 +285,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -251,6 +294,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
pm.handle('magnet:?xt=urn:btih:abc123')
@@ -268,6 +312,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -276,6 +321,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
pm.handle('https://example.com/file.zip')
@@ -293,6 +339,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -301,6 +348,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
const encoded = encodeURIComponent('https://example.com/file.zip')
pm.handle(`motrix://new-task?uri=${encoded}`)
@@ -319,6 +367,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -327,6 +376,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
const encoded = encodeURIComponent('magnet:?xt=urn:btih:abc')
pm.handle(`motrix://new-task?uri=${encoded}`)
@@ -345,6 +395,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
mockWindow,
} = makeDeps()
const pm = createProtocolManager({
@@ -354,6 +405,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
pm.handle('motrix://')
@@ -369,6 +421,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
mockWindow,
} = makeDeps()
const pm = createProtocolManager({
@@ -378,6 +431,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
pm.handle('motrix://plugins/example.archive-unpacker')
@@ -396,6 +450,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
mockWindow,
} = makeDeps()
const pm = createProtocolManager({
@@ -405,6 +460,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
// No dot namespace / uppercase / traversal-looking ids are all refused.
pm.handle('motrix://plugins/no-namespace')
@@ -427,6 +483,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -435,6 +492,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
await pm.handleTorrentFile('/path/to/test.torrent')
@@ -460,6 +518,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -468,6 +527,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
await pm.handleTorrentFile('/path/to/file.txt')
@@ -488,6 +548,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -496,6 +557,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
await pm.handleTorrentFile('/path/to/a.torrent')
await pm.handleTorrentFile('/path/to/b.torrent')
@@ -523,6 +585,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -531,6 +594,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
await pm.handleTorrentFile('/path/to/a.torrent')
await pm.handleTorrentFile('/path/to/b.torrent')
@@ -583,6 +647,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
} = makeDeps()
const pm = createProtocolManager({
getWindow,
@@ -591,6 +656,7 @@ describe('createProtocolManager', () => {
onOpenAddTask,
deliverToAddTask,
onOpenPluginDetail,
+ onOpenTaskDetail,
})
await pm.handleTorrentFile('/path/to/a.torrent')
await pm.handleTorrentFile('/path/to/b.torrent')
diff --git a/src/main/platform/protocol-manager.ts b/src/main/platform/protocol-manager.ts
index 9e8c5f20..6c243d38 100644
--- a/src/main/platform/protocol-manager.ts
+++ b/src/main/platform/protocol-manager.ts
@@ -9,6 +9,7 @@ import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'
import type { TorrentMeta } from '@shared/types/torrent'
import type { BrowserWindow } from 'electron'
import { app } from 'electron'
+import { z } from 'zod'
export interface ProtocolManagerDeps {
getWindow: () => BrowserWindow | null
@@ -37,6 +38,8 @@ export interface ProtocolManagerDeps {
// marketplace detail route. Navigation-only by contract: the deeplink must
// never carry or trigger an install (.claude/rules/plugin-registry.md).
onOpenPluginDetail: (pluginId: string) => void
+ // motrix://tasks/<id> — open the existing task inspector, without changing it.
+ onOpenTaskDetail: (taskId: string) => void
}
export interface ProtocolRegistrationResult {
@@ -52,6 +55,7 @@ interface QueuedTorrent {
}
const RESOURCE_PREFIXES = ['magnet:', 'http:', 'https:', 'ftp:']
+const taskDeepLinkIdSchema = z.string().min(1).max(1024).regex(/^\S+$/u)
function uriToAddTaskParams(url: string): AddTaskUrlParams | null {
const lower = url.toLowerCase()
@@ -214,6 +218,24 @@ export function createProtocolManager(deps: ProtocolManagerDeps) {
if (lower.startsWith('motrix://')) {
try {
const parsed = new URL(url)
+ if (parsed.hostname === 'tasks') {
+ const taskId = taskDeepLinkIdSchema.safeParse(
+ decodeURIComponent(parsed.pathname.replace(/^\//, ''))
+ )
+ if (
+ taskId.success &&
+ !parsed.username &&
+ !parsed.password &&
+ !parsed.port &&
+ !parsed.search &&
+ !parsed.hash
+ ) {
+ deps.onOpenTaskDetail(taskId.data)
+ return
+ }
+ log.warn('rejecting malformed task deeplink')
+ return
+ }
if (
parsed.hostname === 'new-task' &&
parsed.searchParams.has('uri')
diff --git a/src/renderer/layouts/app-layout.test.tsx b/src/renderer/layouts/app-layout.test.tsx
index 24648109..02161730 100644
--- a/src/renderer/layouts/app-layout.test.tsx
+++ b/src/renderer/layouts/app-layout.test.tsx
@@ -1,5 +1,9 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
+import { useDownloadsSelection } from '@renderer/routes/downloads/store'
+import { useDownloadsView } from '@renderer/routes/downloads/view-preferences'
+import { Events } from '@shared/protocol/events'
+import { makeDownloadTask } from '@test-utils/task'
import { act, fireEvent, render, screen } from '@testing-library/react'
import { createMemoryRouter, RouterProvider } from 'react-router'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -22,15 +26,20 @@ function renderAppLayout(routeHandle?: Record<string, unknown>) {
element: <AppLayout />,
children: [
{ index: true, element: <div>INDEX_PAGE</div>, handle: routeHandle },
+ { path: 'downloads/all', element: <div>DOWNLOADS_PAGE</div> },
+ { path: 'plugins/:id', element: <div>PLUGIN_PAGE</div> },
],
},
],
{ initialEntries: ['/'] }
)
render(<RouterProvider router={router} />)
+ return router
}
beforeEach(() => {
+ useDownloadsSelection.getState().clearSelection()
+ useDownloadsView.setState({ inspectorVisible: false })
vi.stubGlobal(
'window',
Object.assign(window, {
@@ -80,6 +89,30 @@ beforeEach(() => {
})
describe('AppLayout', () => {
+ it.each([
+ ['/downloads/all', false],
+ ['/plugins/example', true],
+ ] as const)(
+ 'clears stale task details only for the downloads fallback: %s',
+ async (path, keepsSelection) => {
+ const task = makeDownloadTask({ id: 'previous-task' })
+ useDownloadsSelection.getState().setItems([task])
+ useDownloadsSelection.getState().select(task.id)
+ useDownloadsView.setState({ inspectorVisible: true })
+ const router = renderAppLayout()
+ const handler = vi
+ .mocked(window.motrix.on)
+ .mock.calls.find(([channel]) => channel === Events.NavigateTo)?.[1]
+ expect(handler).toBeTypeOf('function')
+ await act(async () => handler?.(path))
+ expect(router.state.location.pathname).toBe(path)
+ expect([
+ ...useDownloadsSelection.getState().committedSelectedIds,
+ ]).toEqual(keepsSelection ? [task.id] : [])
+ expect(useDownloadsView.getState().inspectorVisible).toBe(keepsSelection)
+ }
+ )
+
it('renders the renderer application menu in the Windows leading slot', async () => {
Object.defineProperty(window.motrix, 'platform', {
value: 'win32',
diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsx
index 57d4ae78..0eaa1917 100644
--- a/src/renderer/layouts/app-layout.tsx
+++ b/src/renderer/layouts/app-layout.tsx
@@ -21,7 +21,10 @@ import { PlatformServicesProvider } from '@renderer/platform/services'
import { webServices } from '@renderer/platform/web-services'
import type { RouteHandle } from '@renderer/router-types'
import { RemoveTasksDialogHost } from '@renderer/routes/downloads/inspector/remove-tasks-dialog-host'
+import { useDownloadsSelection } from '@renderer/routes/downloads/store'
+import { useDownloadsView } from '@renderer/routes/downloads/view-preferences'
import { usePairRequestPrompts } from '@renderer/routes/settings/cards/integration/use-pair-request-prompts'
+import { ALL_DOWNLOADS_ROUTE } from '@shared/lib/task-navigation'
import { Events } from '@shared/protocol/events'
import { Outlet, useMatches, useNavigate } from 'react-router'
@@ -46,7 +49,13 @@ export function AppLayout() {
)
useIpcEvent(Events.NavigateTo, (...args) => {
const path = args[0]
- if (typeof path === 'string' && path) navigate(path)
+ if (typeof path !== 'string' || !path) return
+ if (path === ALL_DOWNLOADS_ROUTE) {
+ // A deleted-task fallback must not leave another task's details open.
+ useDownloadsView.getState().setInspectorVisible(false)
+ useDownloadsSelection.getState().clearSelection()
+ }
+ navigate(path)
})
return (
diff --git a/src/renderer/routes/downloads/downloads-page.test.tsx b/src/renderer/routes/downloads/downloads-page.test.tsx
index 082f2ffd..5aeb45a0 100644
--- a/src/renderer/routes/downloads/downloads-page.test.tsx
+++ b/src/renderer/routes/downloads/downloads-page.test.tsx
@@ -393,12 +393,18 @@ describe('DownloadsPage', () => {
['unknown', []],
['removed', [task('b', TaskStatus.Removed)]],
] as const)(
- 'consumes a %s id after ready and does not reopen on a later snapshot',
+ 'replaces a %s task link with all downloads and does not reopen on a later snapshot',
async (_label, initialTasks) => {
setTaskList({ tasks: initialTasks })
- const view = renderAt('/downloads/active?task=b')
- await act(async () => Promise.resolve())
+ useDownloadsView.setState({ inspectorVisible: true })
+ const view = renderAt('/downloads/active?type=bt&q=old&task=b')
+ await waitFor(() =>
+ expect(screen.getByTestId('location').textContent).toBe(
+ '/downloads/all'
+ )
+ )
expect(selectedIds()).toEqual([])
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
setTaskList({ tasks: [task('b', TaskStatus.Downloading)] })
view.refresh()
@@ -408,6 +414,20 @@ describe('DownloadsPage', () => {
}
)
+ it('does not classify an unhydrated task as deleted until a ready snapshot arrives', async () => {
+ setTaskList({ tasks: [], status: 'loading', hasReadySnapshot: false })
+ const view = renderAt('/downloads/active?task=deleted')
+ expect(screen.getByTestId('location').textContent).toBe(
+ '/downloads/active?task=deleted'
+ )
+ setTaskList({ tasks: [], status: 'ready', hasReadySnapshot: true })
+ view.refresh()
+ await waitFor(() =>
+ expect(screen.getByTestId('location').textContent).toBe('/downloads/all')
+ )
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
it('closing the Inspector preserves selection and consumes the task deep link', async () => {
setTaskList({ tasks: [task('a', TaskStatus.Downloading)] })
renderAt('/downloads/active?task=a')
diff --git a/src/renderer/routes/downloads/downloads-page.tsx b/src/renderer/routes/downloads/downloads-page.tsx
index 16756e59..8d1f4516 100644
--- a/src/renderer/routes/downloads/downloads-page.tsx
+++ b/src/renderer/routes/downloads/downloads-page.tsx
@@ -2,8 +2,8 @@ import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'
import { Button } from '@renderer/components/ui/button'
import { Skeleton } from '@renderer/components/ui/skeleton'
import { useTaskList } from '@renderer/hooks/use-task-list'
+import { isTaskAvailable, resolveTaskRoute } from '@shared/lib/task-navigation'
import type { TaskType } from '@shared/types/task'
-import { TaskStatus } from '@shared/types/task'
import {
useCallback,
useEffect,
@@ -236,10 +236,12 @@ export function DownloadsPage() {
}
const target = tasks.find(
- (task) => task.id === taskParam && task.status !== TaskStatus.Removed
+ (task) => task.id === taskParam && isTaskAvailable(task.status)
)
if (!target) {
consumedDeepLinks.current.add(deepLinkSignature)
+ useDownloadsView.getState().setInspectorVisible(false)
+ navigate(resolveTaskRoute(taskParam, undefined), { replace: true })
return
}
diff --git a/src/renderer/routes/notifications/notifications-page.tsx b/src/renderer/routes/notifications/notifications-page.tsx
index 9ba77954..fdb9fc24 100644
--- a/src/renderer/routes/notifications/notifications-page.tsx
+++ b/src/renderer/routes/notifications/notifications-page.tsx
@@ -23,9 +23,10 @@ import { resolveNotificationText } from '@renderer/lib/notification-text'
import { formatRelativeTime } from '@renderer/lib/relative-time'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
+import { isTaskAvailable, resolveTaskRoute } from '@shared/lib/task-navigation'
import { Queries } from '@shared/protocol/queries'
import type { AppNotification } from '@shared/types/notification'
-import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import type { DownloadTask } from '@shared/types/task'
import { Bell, CheckCheck, Trash2 } from 'lucide-react'
import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -166,7 +167,7 @@ export function NotificationsPage() {
() =>
new Set(
tasks
- .filter((task) => task.status !== TaskStatus.Removed)
+ .filter((task) => isTaskAvailable(task.status))
.map((task) => task.id)
),
[tasks]
@@ -221,17 +222,13 @@ export function NotificationsPage() {
latest.status === 'ready' &&
!latest.tasks.some(
(candidate) =>
- candidate.id === taskId && candidate.status !== TaskStatus.Removed
+ candidate.id === taskId && isTaskAvailable(candidate.status)
)
- if (
- task == null ||
- task.status === TaskStatus.Removed ||
- removedDuringCheck
- ) {
+ if (task == null || !isTaskAvailable(task.status) || removedDuringCheck) {
setMissingTaskIds((ids) => new Set(ids).add(taskId))
return
}
- navigate(`/downloads/all?task=${encodeURIComponent(taskId)}`)
+ navigate(resolveTaskRoute(taskId, task.status))
}, 'notification.center.openTaskFailed')
return (
diff --git a/src/shared/lib/task-navigation.test.ts b/src/shared/lib/task-navigation.test.ts
new file mode 100644
index 00000000..f378c499
--- /dev/null
+++ b/src/shared/lib/task-navigation.test.ts
@@ -0,0 +1,22 @@
+import { TaskStatus } from '@shared/types/task'
+import { describe, expect, it } from 'vitest'
+import { isTaskAvailable, resolveTaskRoute } from './task-navigation'
+
+describe('task navigation', () => {
+ it.each([null, undefined, TaskStatus.Removed])(
+ 'falls back to all downloads when the current task status is %s',
+ (status) => {
+ expect(isTaskAvailable(status)).toBe(false)
+ expect(resolveTaskRoute('t-1', status)).toBe('/downloads/all')
+ }
+ )
+
+ it.each(
+ Object.values(TaskStatus).filter((status) => status !== TaskStatus.Removed)
+ )('preserves task navigation for an existing %s task', (status) => {
+ expect(isTaskAvailable(status)).toBe(true)
+ expect(resolveTaskRoute('task/?#1', status)).toBe(
+ '/downloads/all?task=task%2F%3F%231'
+ )
+ })
+})
diff --git a/src/shared/lib/task-navigation.ts b/src/shared/lib/task-navigation.ts
new file mode 100644
index 00000000..1e72fce0
--- /dev/null
+++ b/src/shared/lib/task-navigation.ts
@@ -0,0 +1,19 @@
+import { TaskStatus } from '@shared/types/task'
+
+export const ALL_DOWNLOADS_ROUTE = '/downloads/all'
+
+export function isTaskAvailable(
+ status: TaskStatus | null | undefined
+): status is Exclude<TaskStatus, TaskStatus.Removed> {
+ return status != null && status !== TaskStatus.Removed
+}
+
+/** Resolve against current state: links and notifications can outlive tasks. */
+export function resolveTaskRoute(
+ taskId: string,
+ status: TaskStatus | null | undefined
+): string {
+ return isTaskAvailable(status)
+ ? `${ALL_DOWNLOADS_ROUTE}?task=${encodeURIComponent(taskId)}`
+ : ALL_DOWNLOADS_ROUTE
+}