Skip to content

A full-featured download manager.

fix(bt): recover magnet file selection and add timeout fallback (#2089)

Dr_rOot6f9d08585119
diff --git a/docs/screenshots/magnet-file-selection-header.png b/docs/screenshots/magnet-file-selection-header.png
new file mode 100644
index 00000000..22ce4922
Binary files /dev/null and b/docs/screenshots/magnet-file-selection-header.png differ
diff --git a/docs/screenshots/magnet-file-selection-timeout.png b/docs/screenshots/magnet-file-selection-timeout.png
new file mode 100644
index 00000000..d2f2941c
Binary files /dev/null and b/docs/screenshots/magnet-file-selection-timeout.png differ
diff --git a/e2e/settings-persistence.spec.ts b/e2e/settings-persistence.spec.ts
index 0435af4a..bf3c0ee5 100644
--- a/e2e/settings-persistence.spec.ts
+++ b/e2e/settings-persistence.spec.ts
@@ -1,5 +1,10 @@
import type { ElectronApplication, Page } from '@playwright/test'
-import { expect, launchMotrix, test } from './fixtures/electron-app'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
const SWITCH_LABEL = 'Notify when download completes'
@@ -20,6 +25,50 @@ async function openMain(app: ElectronApplication): Promise<Page> {
}
test.describe('settings persistence', () => {
+ test('magnet selection timeout is opt-in and persists its waiting time', async ({
+ userDataDir,
+ rpcPort,
+ }) => {
+ let app = await launchMotrix({ userDataDir, rpcPort })
+ const openBitTorrentSettings = async () => {
+ const main = await openMain(app)
+ await expect(() => waitForEngineReady(main)).toPass({ timeout: 15000 })
+ await main.getByRole('link', { name: 'Settings', exact: true }).click()
+ await main.getByText('BitTorrent', { exact: true }).first().click()
+ return main
+ }
+ try {
+ let main = await openBitTorrentSettings()
+ const toggle = main.getByRole('switch', {
+ name: 'Download all files when selection times out',
+ })
+ await expect(toggle).not.toBeChecked()
+ await toggle.click()
+ const timeout = main.getByRole('spinbutton', {
+ name: 'File selection timeout (seconds)',
+ })
+ await expect(timeout).toHaveValue('60')
+ await timeout.fill('120')
+ await main.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(toggle).toBeHidden()
+ await app.close()
+ app = await launchMotrix({ userDataDir, rpcPort })
+ main = await openBitTorrentSettings()
+ await expect(
+ main.getByRole('switch', {
+ name: 'Download all files when selection times out',
+ })
+ ).toBeChecked()
+ await expect(
+ main.getByRole('spinbutton', {
+ name: 'File selection timeout (seconds)',
+ })
+ ).toHaveValue('120')
+ } finally {
+ await app.close()
+ }
+ })
+
test('reduce motion applies immediately, survives restart, and can be disabled', async ({
userDataDir,
rpcPort,
diff --git a/package.json b/package.json
index bf1390cf..6c41add3 100644
--- a/package.json
+++ b/package.json
@@ -48,7 +48,7 @@
"check:remote-extension-compatibility": "node scripts/verify-remote-extension-compatibility.mjs",
"check:remote-extension-threats": "node scripts/verify-remote-extension-threat-evidence.mjs",
"check:schema-parity": "node scripts/check-schema-parity.mjs",
- "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: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 --config vitest.notices.config.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",
diff --git a/scripts/fetch-builtins.mjs b/scripts/fetch-builtins.mjs
index bf83c7df..101b132e 100644
--- a/scripts/fetch-builtins.mjs
+++ b/scripts/fetch-builtins.mjs
@@ -51,8 +51,9 @@ const CACHE_DIR = path.join(
)
const GITHUB = 'https://github.com'
const TIMEOUT_MS = 30_000
-const RETRIES = 3
-const BACKOFF_MS = 500
+const MAX_ATTEMPTS = 5
+const BACKOFF_MS = 2_000
+const MAX_BACKOFF_MS = 30_000
// Uncompressed-size caps, same shape as pack.mjs (Task 3): a plugin bundle is
// ≤ 1 MiB and the whole extracted tree ≤ 5 MiB — a decompression-bomb guard.
const ENTRY_MAX = 1 << 20
@@ -299,24 +300,41 @@ export async function installOne(id, entry, repo, deps, artifactDir, pubPem) {
}
}
-// Stream the response body with a running byte counter instead of buffering
-// the whole thing before checking its size: `Buffer.from(await
-// res.arrayBuffer())` would materialize an attacker/corruption-controlled
-// body in full (the size cap only kicked in *after* the OOM already
-// happened). Bail out — without reading further — the moment either the
-// declared Content-Length or the running total exceeds sizeCap.
+function retryAfterMs(value) {
+ if (!value) return 0
+ const delay = /^\d+$/.test(value)
+ ? Number(value) * 1_000
+ : Date.parse(value) - Date.now()
+ return Number.isFinite(delay)
+ ? Math.min(MAX_BACKOFF_MS, Math.max(0, delay))
+ : 0
+}
+
+// Stream with a running byte counter and reject oversized bodies immediately.
+// Retry transient HTTP/network failures with bounded backoff; digest, signature,
+// and size validation failures remain hard failures.
export async function downloadBytes(url, sizeCap) {
let lastErr
- for (let attempt = 1; attempt <= RETRIES; attempt++) {
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
const res = await fetch(url, {
redirect: 'follow',
signal: AbortSignal.timeout(TIMEOUT_MS),
})
- if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`)
+ if (!res.ok) {
+ await res.body?.cancel().catch(() => {})
+ throw Object.assign(new Error(`GET ${url} -> ${res.status}`), {
+ fatal:
+ res.status !== 408 &&
+ res.status !== 429 &&
+ (res.status < 500 || res.status > 599),
+ retryAfterMs: retryAfterMs(res.headers.get('retry-after')),
+ })
+ }
if (sizeCap) {
const declared = Number(res.headers.get('content-length'))
if (Number.isFinite(declared) && declared > sizeCap) {
+ await res.body?.cancel().catch(() => {})
throw Object.assign(
new Error(
`${url}: Content-Length ${declared}B exceeds lock size ${sizeCap}B`
@@ -367,8 +385,15 @@ export async function downloadBytes(url, sizeCap) {
} catch (err) {
if (err?.fatal) throw err
lastErr = err
- if (attempt < RETRIES) {
- await new Promise((r) => setTimeout(r, BACKOFF_MS * attempt))
+ if (attempt < MAX_ATTEMPTS) {
+ const delay = Math.min(
+ MAX_BACKOFF_MS,
+ Math.max(BACKOFF_MS * 2 ** (attempt - 1), err?.retryAfterMs ?? 0)
+ )
+ console.warn(
+ `[fetch-builtins] ${err?.message ?? err}; retry ${attempt + 1}/${MAX_ATTEMPTS} in ${delay}ms`
+ )
+ await new Promise((r) => setTimeout(r, delay))
}
}
}
diff --git a/src/core/torrent/magnet-selection-timeout.test.ts b/src/core/torrent/magnet-selection-timeout.test.ts
new file mode 100644
index 00000000..1b34850a
--- /dev/null
+++ b/src/core/torrent/magnet-selection-timeout.test.ts
@@ -0,0 +1,342 @@
+import { EventBus } from '@core/events/event-bus'
+import { Events } from '@shared/protocol/events'
+import type {
+ MagnetFileSelectionPayload,
+ TaskCreateCommandResult,
+ TaskCreateRequest,
+} from '@shared/schemas/add-task'
+import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
+import {
+ TaskInstancePhase,
+ TaskStatus,
+ TaskType,
+ TransitionPhase,
+} from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { MagnetSelectionTimeout } from './magnet-selection-timeout'
+
+function selection(taskId = 'magnet-1'): MagnetFileSelectionPayload {
+ return {
+ taskId,
+ magnetUri: `magnet:?xt=urn:btih:${'a'.repeat(40)}`,
+ torrentBase64: 'dG9ycmVudA==',
+ saveDir: '/downloads',
+ meta: {
+ name: 'demo',
+ infoHash: 'a'.repeat(40),
+ totalSize: 30,
+ files: [
+ { index: 0, path: 'demo/a', size: 10, extension: '' },
+ { index: 2, path: 'demo/b', size: 20, extension: '' },
+ ],
+ },
+ }
+}
+
+function fixture() {
+ const bus = new EventBus()
+ let settings = {
+ ...DEFAULT_APP_SETTINGS,
+ magnetFileSelectionAutoDownload: true,
+ }
+ let tasks = [
+ makeDownloadTask({
+ id: 'magnet-1',
+ name: 'demo',
+ type: TaskType.Magnet,
+ status: TaskStatus.MetadataReady,
+ updatedAt: Date.now(),
+ }),
+ ]
+ let engineReady = true
+ const getSelection = vi.fn(async (taskId: string) => selection(taskId))
+ const createTask = vi.fn(
+ async (_request: TaskCreateRequest): Promise<TaskCreateCommandResult> => {
+ tasks[0] = { ...tasks[0], status: TaskStatus.Downloading }
+ bus.emit(Events.TaskUpdated)
+ return { outcome: 'created', taskId: 'magnet-1', gid: 'bt-gid' }
+ }
+ )
+ const notify = vi.fn()
+ const settled = vi.fn()
+ bus.on(Events.MagnetFileSelectionSettled, settled)
+ const service = new MagnetSelectionTimeout({
+ eventBus: bus,
+ getSettings: () => settings,
+ getTasks: () => tasks,
+ isEngineReady: () => engineReady,
+ getSelection,
+ createTask,
+ notify,
+ log: { warn: vi.fn() },
+ })
+ services.push(service)
+ return {
+ bus,
+ service,
+ getSelection,
+ createTask,
+ notify,
+ settled,
+ get tasks() {
+ return tasks
+ },
+ set tasks(value) {
+ tasks = value
+ bus.emit(Events.TaskUpdated)
+ },
+ get settings() {
+ return settings
+ },
+ set settings(value) {
+ settings = value
+ bus.emit(Events.SettingsChanged)
+ },
+ set engineReady(value: boolean) {
+ engineReady = value
+ bus.emit(Events.EngineStateChanged)
+ },
+ }
+}
+
+const services: MagnetSelectionTimeout[] = []
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(1_000_000)
+})
+afterEach(async () => {
+ await Promise.all(services.splice(0).map((service) => service.stopAndDrain()))
+ vi.useRealTimers()
+})
+
+describe('MagnetSelectionTimeout', () => {
+ it('starts all files once at the deadline without a renderer', async () => {
+ const f = fixture()
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(59_999)
+ expect(f.createTask).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(f.createTask).toHaveBeenCalledExactlyOnceWith({
+ type: 'bt',
+ payload: { kind: 'torrent-base64', base64: selection().torrentBase64 },
+ selectedFiles: [0, 2],
+ saveDir: '/downloads',
+ displayName: 'demo',
+ existingTaskId: 'magnet-1',
+ })
+ expect(f.settled).toHaveBeenCalledWith({
+ taskId: 'magnet-1',
+ downloadTaskId: 'magnet-1',
+ })
+ expect(f.notify).toHaveBeenCalledWith(
+ expect.objectContaining({ severity: 'info' })
+ )
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(['magnetFileSelection', 'magnetFileSelectionAutoDownload'] as const)(
+ 'does nothing with %s disabled',
+ async (field) => {
+ const f = fixture()
+ f.settings = { ...f.settings, [field]: false }
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(f.getSelection).not.toHaveBeenCalled()
+ }
+ )
+
+ it('starts the countdown when metadata becomes ready, not when a magnet is added', async () => {
+ const f = fixture()
+ f.tasks = [{ ...f.tasks[0], status: TaskStatus.FetchingMetadata }]
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(f.createTask).not.toHaveBeenCalled()
+ f.tasks = [
+ {
+ ...f.tasks[0],
+ status: TaskStatus.MetadataReady,
+ updatedAt: Date.now(),
+ },
+ ]
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ })
+
+ it('preserves elapsed waiting time on restore even if the task timestamp changed', async () => {
+ const f = fixture()
+ f.tasks[0].instances = [
+ {
+ instanceId: 'metadata-1',
+ motrixId: 'magnet-1',
+ phase: TaskInstancePhase.MagnetMetadataResolution,
+ payload: { fileSelectionReadyAt: Date.now() - 50_000 },
+ gid: null,
+ status: TaskStatus.MetadataReady,
+ progress: 1,
+ totalBytes: 0,
+ downloadedBytes: 0,
+ uploadedBytes: 0,
+ diskPath: '',
+ transitionPhase: TransitionPhase.Idle,
+ uris: [],
+ uriHash: null,
+ createdAt: 0,
+ updatedAt: Date.now(),
+ },
+ ]
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ })
+
+ it('cancels the countdown when disabled and applies a changed deadline', async () => {
+ const f = fixture()
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(30_000)
+ f.settings = { ...f.settings, magnetFileSelectionAutoDownload: false }
+ await vi.advanceTimersByTimeAsync(40_000)
+ expect(f.createTask).not.toHaveBeenCalled()
+ f.settings = {
+ ...f.settings,
+ magnetFileSelectionAutoDownload: true,
+ magnetFileSelectionTimeoutSeconds: 90,
+ }
+ await vi.advanceTimersByTimeAsync(19_999)
+ expect(f.createTask).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([
+ 'confirmed',
+ 'removed',
+ 'disabled',
+ 'extended',
+ 'engine-down',
+ 'stopped',
+ ])('rechecks %s during metadata IO', async (change) => {
+ const f = fixture()
+ const pending = Promise.withResolvers<MagnetFileSelectionPayload>()
+ f.getSelection.mockReturnValueOnce(pending.promise)
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(60_000)
+ if (change === 'confirmed')
+ f.tasks = [{ ...f.tasks[0], status: TaskStatus.Downloading }]
+ if (change === 'removed') f.tasks = []
+ if (change === 'disabled')
+ f.settings = { ...f.settings, magnetFileSelectionAutoDownload: false }
+ if (change === 'extended')
+ f.settings = { ...f.settings, magnetFileSelectionTimeoutSeconds: 120 }
+ if (change === 'engine-down') f.engineReady = false
+ if (change === 'stopped') void f.service.stopAndDrain()
+ pending.resolve(selection())
+ await vi.advanceTimersByTimeAsync(0)
+ expect(f.createTask).not.toHaveBeenCalled()
+ expect(f.notify).not.toHaveBeenCalled()
+ })
+
+ it('waits for engine recovery when the deadline expires offline', async () => {
+ const f = fixture()
+ f.engineReady = false
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(f.getSelection).not.toHaveBeenCalled()
+ f.engineReady = true
+ await vi.advanceTimersByTimeAsync(1)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves a failed selection available for manual retry without a hot loop', async () => {
+ const f = fixture()
+ f.getSelection.mockRejectedValue(new Error('Torrent file missing'))
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(180_000)
+ f.bus.emit(Events.TaskUpdated)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(f.getSelection).toHaveBeenCalledTimes(1)
+ expect(f.createTask).not.toHaveBeenCalled()
+ expect(f.tasks[0].status).toBe(TaskStatus.MetadataReady)
+ expect(f.notify).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ severity: 'warning' })
+ )
+ expect(f.settled).not.toHaveBeenCalled()
+ })
+
+ it('keeps duplicate conflicts pending for an explicit user decision', async () => {
+ const f = fixture()
+ f.createTask.mockResolvedValue({
+ outcome: 'conflict',
+ conflict: {
+ reason: 'existing-files',
+ infoHash: 'a'.repeat(40),
+ targetDir: '/downloads/demo',
+ existingTaskId: null,
+ existingTaskName: null,
+ existingTaskStatus: null,
+ canCreateCopy: true,
+ },
+ })
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ expect(f.notify).toHaveBeenCalledWith(
+ expect.objectContaining({ severity: 'warning' })
+ )
+ expect(f.settled).not.toHaveBeenCalled()
+ })
+
+ it('ignores a stale rejection when a manual selection wins the task mutation lock', async () => {
+ const f = fixture()
+ f.createTask.mockImplementation(async () => {
+ f.tasks = [{ ...f.tasks[0], status: TaskStatus.Downloading }]
+ throw new Error('Task is no longer awaiting selection')
+ })
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(f.notify).not.toHaveBeenCalled()
+ })
+
+ it('advances multiple ready tasks once each, even when one metadata read is delayed', async () => {
+ const f = fixture()
+ f.tasks = [f.tasks[0], { ...f.tasks[0], id: 'magnet-2' }]
+ const pending = Promise.withResolvers<MagnetFileSelectionPayload>()
+ f.getSelection.mockReturnValueOnce(pending.promise)
+ f.createTask.mockImplementation(async (request) => {
+ const taskId = request.type === 'bt' ? request.existingTaskId : undefined
+ if (!taskId) throw new Error('Expected an existing magnet task')
+ f.tasks = f.tasks.map((task) =>
+ task.id === taskId ? { ...task, status: TaskStatus.Downloading } : task
+ )
+ return { outcome: 'created', taskId, gid: `bt-${taskId}` }
+ })
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(60_001)
+ expect(f.createTask).toHaveBeenCalledTimes(1)
+ expect(f.tasks[1].status).toBe(TaskStatus.Downloading)
+ pending.resolve(selection())
+ await vi.advanceTimersByTimeAsync(1)
+ expect(f.createTask).toHaveBeenCalledTimes(2)
+ expect(f.tasks[0].status).toBe(TaskStatus.Downloading)
+ })
+
+ it('drains an accepted download before shutdown completes', async () => {
+ const f = fixture()
+ const pending = Promise.withResolvers<TaskCreateCommandResult>()
+ f.createTask.mockReturnValueOnce(pending.promise)
+ f.service.start()
+ await vi.advanceTimersByTimeAsync(60_000)
+ let drained = false
+ const shutdown = f.service.stopAndDrain().then(() => {
+ drained = true
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(drained).toBe(false)
+ pending.resolve({ outcome: 'created', taskId: 'magnet-1', gid: 'bt-gid' })
+ await shutdown
+ expect(drained).toBe(true)
+ expect(f.notify).not.toHaveBeenCalled()
+ expect(f.settled).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/core/torrent/magnet-selection-timeout.ts b/src/core/torrent/magnet-selection-timeout.ts
new file mode 100644
index 00000000..8581a946
--- /dev/null
+++ b/src/core/torrent/magnet-selection-timeout.ts
@@ -0,0 +1,225 @@
+import type { EventBus } from '@core/events/event-bus'
+import { AsyncWorkTracker } from '@core/inspector-activity/async-work-tracker'
+import type { Logger } from '@core/logger'
+import type { NotifyInput } from '@core/notifications/notification-center'
+import { Events } from '@shared/protocol/events'
+import type {
+ MagnetFileSelectionPayload,
+ TaskCreateCommandResult,
+ TaskCreateRequest,
+} from '@shared/schemas/add-task'
+import type { MotrixAppSettings } from '@shared/types/settings'
+import {
+ type DownloadTask,
+ TaskInstancePhase,
+ TaskStatus,
+} from '@shared/types/task'
+
+interface MagnetSelectionTimeoutDeps {
+ eventBus: EventBus
+ getSettings: () => MotrixAppSettings
+ getTasks: () => DownloadTask[]
+ isEngineReady: () => boolean
+ getSelection: (
+ taskId: string
+ ) => Promise<MagnetFileSelectionPayload | undefined>
+ // Reuse the shell's CreateTask handler, including its path policy,
+ // duplicate admission and serialized metadata-to-download mutation.
+ createTask: (request: TaskCreateRequest) => Promise<TaskCreateCommandResult>
+ notify: (input: NotifyInput) => unknown
+ log: Pick<Logger, 'warn'>
+ runWork?: (operation: () => Promise<void>) => Promise<void>
+}
+
+const watchedEvents = [
+ Events.TaskUpdated,
+ Events.SettingsChanged,
+ Events.EngineStateChanged,
+ Events.EngineRecovered,
+] as const
+
+function readyAt(task: DownloadTask): number {
+ const timestamp = task.instances.find(
+ (instance) => instance.phase === TaskInstancePhase.MagnetMetadataResolution
+ )?.payload.fileSelectionReadyAt
+ // Older persisted tasks predate the explicit timestamp.
+ return typeof timestamp === 'number' && Number.isFinite(timestamp)
+ ? timestamp
+ : task.updatedAt
+}
+
+/** Host-owned countdowns keep working without an open renderer. */
+export class MagnetSelectionTimeout {
+ private readonly work = new AsyncWorkTracker()
+ private readonly attempted = new Map<string, number>()
+ private readonly running = new Set<string>()
+ private timer: ReturnType<typeof setTimeout> | undefined
+ private started = false
+ private stopped = false
+
+ constructor(private readonly deps: MagnetSelectionTimeoutDeps) {}
+
+ start(): void {
+ if (this.started || this.stopped) return
+ this.started = true
+ for (const event of watchedEvents)
+ this.deps.eventBus.on(event, this.refresh)
+ this.refresh()
+ }
+
+ stopAndDrain(): Promise<void> {
+ this.stopped = true
+ clearTimeout(this.timer)
+ for (const event of watchedEvents)
+ this.deps.eventBus.off(event, this.refresh)
+ return this.work.stopAndDrain()
+ }
+
+ private delay(task: DownloadTask): number | undefined {
+ const settings = this.deps.getSettings()
+ if (
+ this.stopped ||
+ !settings.magnetFileSelection ||
+ !settings.magnetFileSelectionAutoDownload ||
+ !this.deps.isEngineReady() ||
+ task.status !== TaskStatus.MetadataReady
+ )
+ return undefined
+ return (
+ readyAt(task) +
+ settings.magnetFileSelectionTimeoutSeconds * 1000 -
+ Date.now()
+ )
+ }
+
+ private refresh = (): void => {
+ clearTimeout(this.timer)
+ this.timer = undefined
+ if (this.stopped) return
+ const settings = this.deps.getSettings()
+ if (
+ !settings.magnetFileSelection ||
+ !settings.magnetFileSelectionAutoDownload ||
+ !this.deps.isEngineReady()
+ )
+ return
+ const tasks = this.deps.getTasks()
+ for (const [id, timestamp] of this.attempted) {
+ if (
+ !tasks.some(
+ (task) =>
+ task.id === id &&
+ task.status === TaskStatus.MetadataReady &&
+ readyAt(task) === timestamp
+ )
+ ) {
+ this.attempted.delete(id)
+ }
+ }
+ let next: DownloadTask | undefined
+ let nextDelay = Infinity
+ for (const task of tasks) {
+ if (
+ this.running.has(task.id) ||
+ this.attempted.get(task.id) === readyAt(task)
+ )
+ continue
+ const delay = this.delay(task)
+ if (delay !== undefined && delay < nextDelay) {
+ next = task
+ nextDelay = delay
+ }
+ }
+ if (!next) return
+ const taskId = next.id
+ const timestamp = readyAt(next)
+ this.timer = setTimeout(
+ () => {
+ this.running.add(taskId)
+ void this.work
+ .run(() =>
+ this.deps.runWork
+ ? this.deps.runWork(() => this.advance(taskId, timestamp))
+ : this.advance(taskId, timestamp)
+ )
+ .catch((error: unknown) =>
+ this.deps.log.warn(
+ { error, taskId },
+ 'Magnet selection timeout failed'
+ )
+ )
+ .finally(() => {
+ this.running.delete(taskId)
+ this.refresh()
+ })
+ this.refresh()
+ },
+ Math.max(0, nextDelay)
+ )
+ }
+
+ private eligibleTask(
+ taskId: string,
+ timestamp: number
+ ): DownloadTask | undefined {
+ const task = this.deps.getTasks().find((entry) => entry.id === taskId)
+ if (!task || readyAt(task) !== timestamp) return undefined
+ const delay = this.delay(task)
+ return delay !== undefined && delay <= 0 ? task : undefined
+ }
+
+ private async advance(taskId: string, timestamp: number): Promise<void> {
+ if (!this.eligibleTask(taskId, timestamp)) return
+ let outcome: 'started' | 'failed' = 'failed'
+ let downloadTaskId = taskId
+ try {
+ const selection = await this.deps.getSelection(taskId)
+ // The user may confirm, remove the task, disable the option, or extend
+ // the deadline while the torrent is being read from disk.
+ if (!this.eligibleTask(taskId, timestamp)) return
+ this.attempted.set(taskId, timestamp)
+ if (selection) {
+ const result = await this.deps.createTask({
+ type: 'bt',
+ payload: { kind: 'torrent-base64', base64: selection.torrentBase64 },
+ selectedFiles: selection.meta.files.map((file) => file.index),
+ saveDir: selection.saveDir,
+ displayName: selection.meta.name || undefined,
+ existingTaskId: taskId,
+ })
+ if (result.outcome !== 'conflict') {
+ outcome = 'started'
+ downloadTaskId = result.taskId
+ }
+ }
+ } catch (error) {
+ if (!this.eligibleTask(taskId, timestamp)) return
+ this.attempted.set(taskId, timestamp)
+ this.deps.log.warn(
+ { error, taskId },
+ 'Could not automatically select magnet files'
+ )
+ }
+ if (this.stopped) return
+ if (outcome === 'started') {
+ this.deps.eventBus.emit(Events.MagnetFileSelectionSettled, {
+ taskId,
+ downloadTaskId,
+ })
+ } else if (!this.eligibleTask(taskId, timestamp)) {
+ return
+ }
+ this.deps.notify({
+ sourceKey: `magnet-selection-timeout:${taskId}:${timestamp}:${outcome}`,
+ kind: 'magnet-selection-timeout',
+ severity: outcome === 'started' ? 'info' : 'warning',
+ titleKey: `task.add.selectionTimeout.${outcome}`,
+ titleParams: {
+ name:
+ this.deps.getTasks().find((task) => task.id === downloadTaskId)
+ ?.name ?? taskId,
+ },
+ taskId: downloadTaskId,
+ })
+ }
+}
diff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.ts
index ccadd3b3..3a341e61 100644
--- a/src/core/torrent/magnet-tracker.test.ts
+++ b/src/core/torrent/magnet-tracker.test.ts
@@ -1285,6 +1285,13 @@ describe('MagnetTracker', () => {
// User dismissed the dialog — clear emits so we assert the RE-open emits.
;(eventBus.emit as ReturnType<typeof vi.fn>).mockClear()
+ const selection = await tracker.getFileSelection(taskId)
+ expect(magnetFileSelectionPayloadSchema.safeParse(selection).success).toBe(
+ true
+ )
+ expect(selection).toMatchObject({ taskId, torrentBase64: torrent.base64 })
+ expect(eventBus.emit).not.toHaveBeenCalled()
+
await tracker.reopenFileSelection(taskId)
const emitCall = (
@@ -1443,6 +1450,9 @@ describe('MagnetTracker', () => {
const after = db.getTask(taskId)
expect(after?.task.aggStatus).toBe(TaskStatus.MetadataReady)
expect(after?.instances[0].status).toBe(TaskStatus.MetadataReady)
+ expect(after?.instances[0].payload.fileSelectionReadyAt).toBe(
+ after?.task.updatedAt
+ )
// The placeholder name is upgraded to the resolved torrent name
// so the row stops showing the raw magnet URI.
expect(after?.task.name).toBe('resolved-name.torrent')
diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.ts
index 7c2be3e6..60918229 100644
--- a/src/core/torrent/magnet-tracker.ts
+++ b/src/core/torrent/magnet-tracker.ts
@@ -39,6 +39,7 @@ import type { TaskManager } from '@core/task/task-manager'
import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'
import { AppError, DownloadErrorCode, ErrorCode } from '@shared/errors'
import { Events } from '@shared/protocol/events'
+import type { MagnetFileSelectionPayload } from '@shared/schemas/add-task'
import type { DownloadTask, SourceMeta, TaskSource } from '@shared/types/task'
import {
TaskInstancePhase,
@@ -1025,6 +1026,17 @@ export class MagnetTracker {
* Routing/window handling is identical to the first emit: the bootstrap
* forwards MagnetFileSelection to the add-task window. */
async reopenFileSelection(taskId: string): Promise<void> {
+ const selection = await this.getFileSelection(taskId)
+ if (!selection) return
+ this.eventBus.emit(Events.MagnetFileSelection, selection)
+ log.info({ taskId }, 'magnet file selection reopened')
+ }
+
+ /** Read the selection for one caller without broadcasting a dialog to
+ * every connected WebUI. HTTP callers can recover missed WS events. */
+ async getFileSelection(
+ taskId: string
+ ): Promise<MagnetFileSelectionPayload | undefined> {
const pair = this.db.getTask(taskId)
if (!pair) {
throw new AppError(ErrorCode.TaskNotFound, `task ${taskId} not found`)
@@ -1078,14 +1090,17 @@ export class MagnetTracker {
const meta = await this.torrentParser.parse(torrentBase64)
if (this.stopped) return
- this.eventBus.emit(Events.MagnetFileSelection, {
+ // A different client may have confirmed or removed the task during IO.
+ if (this.db.getTask(taskId)?.task.aggStatus !== TaskStatus.MetadataReady) {
+ return
+ }
+ return {
taskId,
meta,
magnetUri,
torrentBase64,
saveDir,
- })
- log.info({ taskId }, 'magnet file selection reopened')
+ }
}
/** Cancel all in-flight cleanup retry timers. Called on app shutdown
@@ -1491,6 +1506,7 @@ export class MagnetTracker {
? {
...i,
status: TaskStatus.MetadataReady,
+ payload: { ...i.payload, fileSelectionReadyAt: now },
updatedAt: now,
}
: i
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index eb8c8d9f..477073cb 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -70,6 +70,7 @@ import type { FinalNamePicker } from '@core/task/final-name-picker'
import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'
import type { TaskManager } from '@core/task/task-manager'
import type { TorrentMetaStore } from '@core/task/torrent-meta-store'
+import { MagnetSelectionTimeout } from '@core/torrent/magnet-selection-timeout'
import type { MagnetTracker } from '@core/torrent/magnet-tracker'
import { swapMagnetMetadataForBt } from '@core/torrent/swap-magnet-metadata-for-bt'
import type { TorrentParser } from '@core/torrent/torrent-parser'
@@ -98,7 +99,7 @@ import {
CLI_INSTALL_PACKAGE_MANAGERS,
type CliInstallRequest,
} from '@shared/types/cli-tool'
-import { EngineRecoveryAction } from '@shared/types/engine'
+import { EngineRecoveryAction, EngineState } from '@shared/types/engine'
import type { ProxySettings } from '@shared/types/settings'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
@@ -1634,6 +1635,33 @@ export function registerCommandHandlers(ctx: CommandContext): () => void {
? ctx.trackAsyncWork(async () => operation())
: Promise.resolve().then(operation)
+ const createTask = handlers[Commands.CreateTask]
+ if (!createTask) throw new Error('CreateTask handler is not registered')
+ const selectionTimeout = new MagnetSelectionTimeout({
+ eventBus: ctx.eventBus,
+ getSettings: () => ctx.settingsManager.getApp(),
+ getTasks: () => ctx.taskManager.getAll(),
+ isEngineReady: () => ctx.supervisor.getState() === EngineState.Ready,
+ getSelection: (taskId) => ctx.magnetTracker.getFileSelection(taskId),
+ createTask: async (request) =>
+ (await createTask(request)) as TaskCreateCommandResult,
+ notify: (input) => ctx.notificationCenter.notify(input),
+ log: getLogger('magnet-selection-timeout'),
+ runWork: ctx.trackAsyncWork,
+ })
+ if (ctx.waitForTasksReady) {
+ void ctx.waitForTasksReady().then(
+ () => selectionTimeout.start(),
+ (error: unknown) =>
+ getLogger('magnet-selection-timeout').warn(
+ { error },
+ 'Task restore failed'
+ )
+ )
+ } else {
+ selectionTimeout.start()
+ }
+
for (const [channel, handler] of Object.entries(handlers)) {
// Window-bound commands need event.sender — pass it as the first arg.
if (
@@ -1657,6 +1685,7 @@ export function registerCommandHandlers(ctx: CommandContext): () => void {
}
}
return () => {
+ void selectionTimeout.stopAndDrain()
for (const channel of channels) {
ipcMain.removeHandler(channel)
}
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
index 64d8a71f..90b7cf5d 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
@@ -4,6 +4,8 @@ import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import { transport } from '@renderer/lib/transport'
import { Events } from '@shared/protocol/events'
+import type { AddTaskFormValues } from '@shared/schemas/add-task'
+import { useState } from 'react'
import { MemoryRouter, Route, Routes } from 'react-router'
import { AddTaskDialogHost } from './add-task-dialog-host'
import { useAddTaskDialogStore } from './use-add-task-dialog-store'
@@ -12,6 +14,10 @@ vi.mock('@renderer/lib/transport', () => ({
transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn() },
}))
+vi.mock('@renderer/hooks/use-task-list', () => ({
+ useTaskList: () => ({ tasks: [] }),
+}))
+
// Stub AddTaskForm so tests can drive onSubmitSuccess / onCancel directly
// without filling the actual form. The host's contract with the form is
// just those two callbacks plus defaultValues — keeping the stub narrow
@@ -30,15 +36,22 @@ vi.mock('@renderer/components/add-task/add-task-form', () => ({
onCancel,
onAdvancedOpenChange: _onAdvancedOpenChange,
presentation,
+ defaultValues,
}: {
onSubmitSuccess?: (gid: string) => void
onCancel: () => void
onAdvancedOpenChange?: (expanded: boolean) => void
presentation?: 'dialog' | 'window'
+ defaultValues?: Partial<AddTaskFormValues>
}) => {
+ // Like react-hook-form, defaults are read on mount, not on every render.
+ const [initialValues] = useState(defaultValues)
submitSuccessRef.current = onSubmitSuccess
return (
<div data-testid="add-task-form-stub" data-presentation={presentation}>
+ <span data-testid="initial-values">
+ {JSON.stringify(initialValues)}
+ </span>
<button type="button" onClick={() => onSubmitSuccess?.('gid-1')}>
stub-submit
</button>
@@ -70,6 +83,56 @@ function renderWithRouter() {
}
describe('AddTaskDialogHost', () => {
+ it('closes only the matching picker when the background service accepts it', () => {
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'torrent', existingTaskId: 'ready-1' })
+ renderWithRouter()
+ const listener = vi
+ .mocked(transport.on)
+ .mock.calls.find(
+ ([channel]) => channel === Events.MagnetFileSelectionSettled
+ )?.[1]
+ expect(listener).toBeDefined()
+ act(() => listener?.({ taskId: 'ready-2', downloadTaskId: 'ready-2' }))
+ expect(useAddTaskDialogStore.getState().open).toBe(true)
+ act(() => listener?.({ taskId: 'ready-1', downloadTaskId: 'ready-1' }))
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+
+ it('hydrates a replacement form while the dialog is already open', () => {
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'links', urls: 'https://example.com/a' })
+ renderWithRouter()
+ act(() => {
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'torrent', existingTaskId: 'ready-2' })
+ })
+ expect(screen.getByTestId('initial-values')).toHaveTextContent('ready-2')
+ expect(screen.getByTestId('initial-values')).not.toHaveTextContent(
+ 'https://example.com/a'
+ )
+ })
+
+ it('does not let an old submission close a replacement file selection', () => {
+ useAddTaskDialogStore.getState().openWith({ tab: 'links' })
+ renderWithRouter()
+ const oldSubmission = submitSuccessRef.current
+ act(() => {
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'torrent', existingTaskId: 'ready-2' })
+ })
+ act(() => oldSubmission?.('old-task'))
+ expect(useAddTaskDialogStore.getState()).toMatchObject({
+ open: true,
+ prefill: { existingTaskId: 'ready-2' },
+ })
+ expect(screen.queryByTestId('downloads-route')).toBeNull()
+ })
+
beforeEach(() => {
useAddTaskDialogStore.setState({ open: false, prefill: undefined })
vi.mocked(transport.on).mockClear()
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
index e20a04a2..a083f91c 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
@@ -9,6 +9,7 @@ import {
} from '@renderer/components/ui/dialog'
import { Input } from '@renderer/components/ui/input'
import { WindowChromeCaptionIcon } from '@renderer/components/window-chrome/window-chrome'
+import { showMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
import { transport } from '@renderer/lib/transport'
import { PlatformServicesProvider } from '@renderer/platform/services'
import {
@@ -24,6 +25,7 @@ import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import {
magnetFileSelectionPayloadSchema,
+ magnetFileSelectionSettledPayloadSchema,
protocolTorrentFilePayloadSchema,
setAddTaskModeEventPayloadSchema,
urlParamsToFormDefaults,
@@ -33,10 +35,12 @@ import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router'
import { useAdaptiveDialogHeight } from './use-adaptive-dialog-height'
import { useAddTaskDialogStore } from './use-add-task-dialog-store'
+import { usePendingMagnetSelection } from './use-pending-magnet-selection'
export function AddTaskDialogHost() {
const { t } = useTranslation()
const open = useAddTaskDialogStore((s) => s.open)
+ const revision = useAddTaskDialogStore((s) => s.revision)
const prefill = useAddTaskDialogStore((s) => s.prefill)
const openWith = useAddTaskDialogStore((s) => s.openWith)
const close = useAddTaskDialogStore((s) => s.close)
@@ -69,13 +73,16 @@ export function AddTaskDialogHost() {
// navigating would yank them off whatever route they switched to.
const onSubmitSuccess = useCallback(
(taskId: string) => {
- if (!useAddTaskDialogStore.getState().open) return
+ const current = useAddTaskDialogStore.getState()
+ if (!current.open || current.revision !== revision) return
close()
navigate(`/downloads/all?task=${encodeURIComponent(taskId)}`)
},
- [close, navigate]
+ [close, navigate, revision]
)
+ usePendingMagnetSelection(onSubmitSuccess)
+
// Register the web close handler so webServices.closeHost() works.
useEffect(() => {
__setWebCloseHandler(() => useAddTaskDialogStore.getState().close())
@@ -87,19 +94,22 @@ export function AddTaskDialogHost() {
const onMagnet = (...args: unknown[]) => {
const p = magnetFileSelectionPayloadSchema.safeParse(args[0])
if (!p.success) return
- openWith({
- tab: 'torrent',
- source: 'magnet',
- magnetUri: p.data.magnetUri,
- base64: p.data.torrentBase64,
- torrentMeta: p.data.meta,
- selectedFiles: p.data.meta.files.map((f) => f.index),
- saveDir: p.data.saveDir,
- // Plan B: forward the metadata pending task's motrixId so the
- // CreateTask handler can swap the instance in place rather
- // than creating a duplicate row in Downloads.
- existingTaskId: p.data.taskId,
- })
+ // The snapshot recovery hook offers this task after the current form
+ // closes. Never overwrite user input or an in-flight submission.
+ if (useAddTaskDialogStore.getState().open) return
+ showMagnetFileSelection(p.data)
+ }
+ const onSelectionSettled = (...args: unknown[]) => {
+ const parsed = magnetFileSelectionSettledPayloadSchema.safeParse(args[0])
+ const current = useAddTaskDialogStore.getState()
+ if (
+ !parsed.success ||
+ !current.open ||
+ current.prefill?.tab !== 'torrent' ||
+ current.prefill.existingTaskId !== parsed.data.taskId
+ )
+ return
+ current.close()
}
const onProtocol = (...args: unknown[]) => {
const p = protocolTorrentFilePayloadSchema.safeParse(args[0])
@@ -119,10 +129,12 @@ export function AddTaskDialogHost() {
}
transport.on(Events.MagnetFileSelection, onMagnet)
+ transport.on(Events.MagnetFileSelectionSettled, onSelectionSettled)
transport.on(Events.ProtocolTorrentFile, onProtocol)
transport.on(Events.SetAddTaskMode, onSetMode)
return () => {
transport.off(Events.MagnetFileSelection, onMagnet)
+ transport.off(Events.MagnetFileSelectionSettled, onSelectionSettled)
transport.off(Events.ProtocolTorrentFile, onProtocol)
transport.off(Events.SetAddTaskMode, onSetMode)
}
@@ -148,7 +160,7 @@ export function AddTaskDialogHost() {
</DialogHeader>
<PlatformServicesProvider services={webServices}>
<AddTaskForm
- key={open ? 'open' : 'closed'}
+ key={revision}
defaultValues={prefill}
onSubmitSuccess={onSubmitSuccess}
onCancel={close}
diff --git a/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts b/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts
index 86dd372c..f5500109 100644
--- a/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts
+++ b/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts
@@ -7,6 +7,7 @@ type DeepPartial<T> = {
interface AddTaskDialogState {
open: boolean
+ revision: number
prefill: DeepPartial<AddTaskFormValues> | undefined
openWith: (prefill?: DeepPartial<AddTaskFormValues>) => void
close: () => void
@@ -14,7 +15,14 @@ interface AddTaskDialogState {
export const useAddTaskDialogStore = create<AddTaskDialogState>((set) => ({
open: false,
+ revision: 0,
prefill: undefined,
- openWith: (prefill) => set({ open: true, prefill }),
- close: () => set({ open: false, prefill: undefined }),
+ openWith: (prefill) =>
+ set((state) => ({ open: true, prefill, revision: state.revision + 1 })),
+ close: () =>
+ set((state) => ({
+ open: false,
+ prefill: undefined,
+ revision: state.revision + 1,
+ })),
}))
diff --git a/src/renderer/components/add-task-dialog/use-pending-magnet-selection.test.tsx b/src/renderer/components/add-task-dialog/use-pending-magnet-selection.test.tsx
new file mode 100644
index 00000000..7efd16e2
--- /dev/null
+++ b/src/renderer/components/add-task-dialog/use-pending-magnet-selection.test.tsx
@@ -0,0 +1,186 @@
+import '@renderer/lib/i18n'
+import { toast } from '@renderer/components/ui/toast'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import type { DownloadTask } from '@shared/types/task'
+import { TaskStatus, TaskType } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { StrictMode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useAddTaskDialogStore } from './use-add-task-dialog-store'
+import { usePendingMagnetSelection } from './use-pending-magnet-selection'
+
+const taskList = vi.hoisted(() => ({
+ tasks: [] as DownloadTask[],
+ hasReadySnapshot: true,
+}))
+vi.mock('@renderer/hooks/use-task-list', () => ({
+ useTaskList: () => taskList,
+}))
+vi.mock('@renderer/lib/transport', () => ({ transport: { invoke: vi.fn() } }))
+vi.mock('@renderer/components/ui/toast', () => ({ toast: { add: vi.fn() } }))
+
+function displayedTaskId() {
+ const prefill = useAddTaskDialogStore.getState().prefill
+ return prefill?.tab === 'torrent' ? prefill.existingTaskId : undefined
+}
+
+function ready(id: string) {
+ return makeDownloadTask({
+ id,
+ type: TaskType.Magnet,
+ status: TaskStatus.MetadataReady,
+ })
+}
+
+function result(taskId: string) {
+ return {
+ ok: true,
+ selection: {
+ taskId,
+ magnetUri: `magnet:?xt=urn:btih:${'a'.repeat(40)}`,
+ torrentBase64: 'dG9ycmVudA==',
+ saveDir: '/downloads',
+ meta: {
+ name: taskId,
+ infoHash: 'a'.repeat(40),
+ totalSize: 10,
+ comment: null,
+ isPrivate: false,
+ files: [{ index: 0, path: 'demo/a.txt', size: 10, extension: '.txt' }],
+ },
+ },
+ }
+}
+
+beforeEach(() => {
+ vi.stubGlobal('__MOTRIX_TARGET__', 'web')
+ vi.clearAllMocks()
+ taskList.tasks = []
+ useAddTaskDialogStore.setState({
+ open: false,
+ prefill: undefined,
+ revision: 0,
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (_channel, taskId) =>
+ result(String(taskId))
+ )
+})
+afterEach(() => vi.unstubAllGlobals())
+
+describe('pending magnet selection recovery', () => {
+ it('closes a stale picker when a reconnect snapshot shows it already downloading', () => {
+ taskList.tasks = [ready('restored')]
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'torrent', existingTaskId: 'restored' })
+ const { rerender } = renderHook(() => usePendingMagnetSelection())
+ taskList.tasks = [{ ...ready('restored'), status: TaskStatus.Downloading }]
+ rerender()
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+
+ it('opens a restored task without receiving a selection event', async () => {
+ taskList.tasks = [ready('restored')]
+ renderHook(() => usePendingMagnetSelection())
+ await waitFor(() =>
+ expect(useAddTaskDialogStore.getState().open).toBe(true)
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.ReopenMagnetFileSelection,
+ 'restored'
+ )
+ expect(useAddTaskDialogStore.getState().prefill).toMatchObject({
+ existingTaskId: 'restored',
+ tab: 'torrent',
+ selectedFiles: [0],
+ saveDir: '/downloads',
+ })
+ })
+
+ it('recovers a ready task from a reconnect snapshot', async () => {
+ taskList.tasks = [
+ { ...ready('reconnected'), status: TaskStatus.FetchingMetadata },
+ ]
+ const { rerender } = renderHook(() => usePendingMagnetSelection())
+ expect(transport.invoke).not.toHaveBeenCalled()
+ taskList.tasks = [ready('reconnected')]
+ rerender()
+ await waitFor(() => expect(displayedTaskId()).toBe('reconnected'))
+ })
+
+ it('waits for the current form, then offers multiple tasks once each', async () => {
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'links', urls: 'https://example.com/a' })
+ taskList.tasks = [ready('one'), ready('two')]
+ const { rerender } = renderHook(() => usePendingMagnetSelection())
+ expect(transport.invoke).not.toHaveBeenCalled()
+ act(() => useAddTaskDialogStore.getState().close())
+ await waitFor(() => expect(displayedTaskId()).toBe('one'))
+ act(() => useAddTaskDialogStore.getState().close())
+ await waitFor(() => expect(displayedTaskId()).toBe('two'))
+ act(() => useAddTaskDialogStore.getState().close())
+ taskList.tasks = [...taskList.tasks]
+ rerender()
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ expect(transport.invoke).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not let a delayed automatic response overwrite a newly opened form', async () => {
+ let resolve!: (value: unknown) => void
+ vi.mocked(transport.invoke).mockReturnValueOnce(
+ new Promise((done) => {
+ resolve = done
+ })
+ )
+ taskList.tasks = [ready('slow')]
+ renderHook(() => usePendingMagnetSelection())
+ act(() =>
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ tab: 'links', urls: 'https://example.com/keep' })
+ )
+ await act(async () => resolve(result('slow')))
+ expect(useAddTaskDialogStore.getState().prefill).toMatchObject({
+ urls: 'https://example.com/keep',
+ })
+ act(() => useAddTaskDialogStore.getState().close())
+ await waitFor(() => expect(displayedTaskId()).toBe('slow'))
+ })
+
+ it('ignores a response after the task leaves MetadataReady', async () => {
+ let resolve!: (value: unknown) => void
+ vi.mocked(transport.invoke).mockReturnValueOnce(
+ new Promise((done) => {
+ resolve = done
+ })
+ )
+ taskList.tasks = [ready('removed')]
+ const { rerender } = renderHook(() => usePendingMagnetSelection())
+ taskList.tasks = []
+ rerender()
+ await act(async () => resolve(result('removed')))
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+
+ it('reports a failed automatic open once and leaves manual recovery available', async () => {
+ vi.mocked(transport.invoke).mockRejectedValue(
+ new Error('Metadata unavailable')
+ )
+ taskList.tasks = [ready('missing')]
+ const { rerender } = renderHook(() => usePendingMagnetSelection())
+ await waitFor(() => expect(toast.add).toHaveBeenCalledTimes(1))
+ taskList.tasks = [...taskList.tasks]
+ rerender()
+ expect(transport.invoke).toHaveBeenCalledTimes(1)
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+
+ it('does not get stuck during StrictMode effect replay', async () => {
+ taskList.tasks = [ready('strict')]
+ renderHook(() => usePendingMagnetSelection(), { wrapper: StrictMode })
+ await waitFor(() => expect(displayedTaskId()).toBe('strict'))
+ })
+})
diff --git a/src/renderer/components/add-task-dialog/use-pending-magnet-selection.ts b/src/renderer/components/add-task-dialog/use-pending-magnet-selection.ts
new file mode 100644
index 00000000..55ee49ca
--- /dev/null
+++ b/src/renderer/components/add-task-dialog/use-pending-magnet-selection.ts
@@ -0,0 +1,94 @@
+import { toast } from '@renderer/components/ui/toast'
+import { useTaskList } from '@renderer/hooks/use-task-list'
+import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
+import { TaskStatus } from '@shared/types/task'
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useAddTaskDialogStore } from './use-add-task-dialog-store'
+
+/** Recover one-shot selection events from the task snapshot, including after
+ * refresh/reconnect. Wait for the current form to close and offer each task
+ * once per page session; dismissed selections remain available in the inspector header. */
+export function usePendingMagnetSelection(
+ onSelectionSettled?: (taskId: string) => void
+) {
+ const { tasks, hasReadySnapshot } = useTaskList()
+ const { t } = useTranslation()
+ const open = useAddTaskDialogStore((state) => state.open)
+ const revision = useAddTaskDialogStore((state) => state.revision)
+ const prefill = useAddTaskDialogStore((state) => state.prefill)
+ const [handled, setHandled] = useState(() => new Set<string>())
+ const latestTasks = useRef(tasks)
+ const taskId = tasks.find(
+ (task) => task.status === TaskStatus.MetadataReady && !handled.has(task.id)
+ )?.id
+
+ useEffect(() => {
+ latestTasks.current = tasks
+ }, [tasks])
+
+ useEffect(() => {
+ const displayedTaskId =
+ open && prefill?.tab === 'torrent' ? prefill.existingTaskId : undefined
+ if (!displayedTaskId) return
+ setHandled((previous) =>
+ previous.has(displayedTaskId)
+ ? previous
+ : new Set(previous).add(displayedTaskId)
+ )
+ }, [open, prefill])
+
+ useEffect(() => {
+ if (
+ !hasReadySnapshot ||
+ !open ||
+ prefill?.tab !== 'torrent' ||
+ !prefill.existingTaskId
+ )
+ return
+ const task = tasks.find((entry) => entry.id === prefill.existingTaskId)
+ if (task && task.status !== TaskStatus.MetadataReady) {
+ if (onSelectionSettled) onSelectionSettled(task.id)
+ else useAddTaskDialogStore.getState().close()
+ }
+ }, [hasReadySnapshot, open, prefill, tasks, onSelectionSettled])
+
+ useEffect(() => {
+ if (open || !taskId) return
+ let active = true
+ const taskName = latestTasks.current.find(
+ (task) => task.id === taskId
+ )?.name
+ const remember = () =>
+ setHandled((previous) => new Set(previous).add(taskId))
+ void openMagnetFileSelection(taskId, () => {
+ const dialog = useAddTaskDialogStore.getState()
+ return (
+ active &&
+ !dialog.open &&
+ dialog.revision === revision &&
+ latestTasks.current.some(
+ (task) =>
+ task.id === taskId && task.status === TaskStatus.MetadataReady
+ )
+ )
+ })
+ .then(() => {
+ if (active) remember()
+ })
+ .catch((error: unknown) => {
+ if (!active) return
+ remember()
+ toast.add({
+ title: t('panel.downloads.action.singleTaskFailed', {
+ name: taskName ?? taskId,
+ reason: error instanceof Error ? error.message : String(error),
+ }),
+ type: 'error',
+ })
+ })
+ return () => {
+ active = false
+ }
+ }, [open, revision, taskId, t])
+}
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 2c49ff8c..23caa2d3 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -221,7 +221,8 @@ export function AddTaskForm({
form,
subscribeEvents,
hydrateOpenState,
- handleTorrentQueueChanged
+ handleTorrentQueueChanged,
+ onSubmitSuccess
)
// Backfill the default save directory for the initially mounted form.
diff --git a/src/renderer/components/add-task/use-external-hydration.test.ts b/src/renderer/components/add-task/use-external-hydration.test.ts
index 59cd9a7f..8a66e805 100644
--- a/src/renderer/components/add-task/use-external-hydration.test.ts
+++ b/src/renderer/components/add-task/use-external-hydration.test.ts
@@ -29,7 +29,37 @@ describe('useExternalHydration', () => {
for (const k of Object.keys(listeners)) delete listeners[k]
})
- it('subscribes to the three IPC events when enabled', () => {
+ it('settles only the current magnet selection after automatic acceptance', () => {
+ const settled = vi.fn()
+ const { result } = renderHook(() =>
+ useForm<AddTaskFormValues>({
+ defaultValues: {
+ tab: 'torrent',
+ existingTaskId: 'ready-1',
+ saveDir: '/downloads',
+ },
+ })
+ )
+ renderHook(() =>
+ useExternalHydration(result.current, true, undefined, undefined, settled)
+ )
+ act(() =>
+ fire(Events.MagnetFileSelectionSettled, {
+ taskId: 'ready-2',
+ downloadTaskId: 'ready-2',
+ })
+ )
+ expect(settled).not.toHaveBeenCalled()
+ act(() =>
+ fire(Events.MagnetFileSelectionSettled, {
+ taskId: 'ready-1',
+ downloadTaskId: 'ready-1',
+ })
+ )
+ expect(settled).toHaveBeenCalledWith('ready-1')
+ })
+
+ it('subscribes to selection and hydration events when enabled', () => {
const { result } = renderHook(() =>
useForm({ defaultValues: { tab: 'links', urls: '', saveDir: '/d' } })
)
diff --git a/src/renderer/components/add-task/use-external-hydration.ts b/src/renderer/components/add-task/use-external-hydration.ts
index 1715967d..8504a873 100644
--- a/src/renderer/components/add-task/use-external-hydration.ts
+++ b/src/renderer/components/add-task/use-external-hydration.ts
@@ -3,6 +3,7 @@ import { Events } from '@shared/protocol/events'
import {
type AddTaskFormValues,
magnetFileSelectionPayloadSchema,
+ magnetFileSelectionSettledPayloadSchema,
protocolTorrentFilePayloadSchema,
setAddTaskModeEventPayloadSchema,
torrentQueueSizeChangedPayloadSchema,
@@ -29,7 +30,8 @@ export function useExternalHydration(
form: UseFormReturn<AddTaskFormValues>,
enabled: boolean,
onModeHydrated?: (context: AddTaskModeHydrationContext) => void,
- onTorrentQueueChanged?: (update: TorrentQueueUpdate) => void
+ onTorrentQueueChanged?: (update: TorrentQueueUpdate) => void,
+ onSelectionSettled?: (taskId: string) => void
) {
useEffect(() => {
if (!enabled) return
@@ -56,6 +58,18 @@ export function useExternalHydration(
)
}
+ const onSettled = (...args: unknown[]) => {
+ const parsed = magnetFileSelectionSettledPayloadSchema.safeParse(args[0])
+ const values = form.getValues()
+ if (
+ parsed.success &&
+ values.tab === 'torrent' &&
+ values.existingTaskId === parsed.data.taskId
+ ) {
+ onSelectionSettled?.(parsed.data.downloadTaskId)
+ }
+ }
+
const onProtocol = (...args: unknown[]) => {
const parsed = protocolTorrentFilePayloadSchema.safeParse(args[0])
if (!parsed.success) return
@@ -102,15 +116,17 @@ export function useExternalHydration(
}
transport.on(Events.MagnetFileSelection, onMagnet)
+ transport.on(Events.MagnetFileSelectionSettled, onSettled)
transport.on(Events.ProtocolTorrentFile, onProtocol)
transport.on(Events.SetAddTaskMode, onSetMode)
transport.on(Events.TorrentQueueSizeChanged, onTorrentQueueSizeChanged)
return () => {
transport.off(Events.MagnetFileSelection, onMagnet)
+ transport.off(Events.MagnetFileSelectionSettled, onSettled)
transport.off(Events.ProtocolTorrentFile, onProtocol)
transport.off(Events.SetAddTaskMode, onSetMode)
transport.off(Events.TorrentQueueSizeChanged, onTorrentQueueSizeChanged)
}
- }, [form, enabled, onModeHydrated, onTorrentQueueChanged])
+ }, [form, enabled, onModeHydrated, onTorrentQueueChanged, onSelectionSettled])
}
diff --git a/src/renderer/components/task/magnet-file-selection-button.tsx b/src/renderer/components/task/magnet-file-selection-button.tsx
new file mode 100644
index 00000000..f14dd7da
--- /dev/null
+++ b/src/renderer/components/task/magnet-file-selection-button.tsx
@@ -0,0 +1,51 @@
+import { Button } from '@renderer/components/ui/button'
+import { toast } from '@renderer/components/ui/toast'
+import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
+import type { DownloadTask } from '@shared/types/task'
+import { ListChecks } from 'lucide-react'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export function MagnetFileSelectionButton({ task }: { task: DownloadTask }) {
+ const { t } = useTranslation()
+ const pendingRef = useRef(false)
+ const [pending, setPending] = useState(false)
+
+ const openSelection = async () => {
+ if (pendingRef.current) return
+ pendingRef.current = true
+ setPending(true)
+ try {
+ await openMagnetFileSelection(task.id)
+ } catch (error) {
+ toast.add({
+ title: t('panel.downloads.action.singleTaskFailed', {
+ name: task.name,
+ reason: error instanceof Error ? error.message : String(error),
+ }),
+ type: 'error',
+ })
+ } finally {
+ pendingRef.current = false
+ setPending(false)
+ }
+ }
+
+ return (
+ <Button
+ size="xs"
+ variant="outline"
+ className="w-fit max-w-full"
+ disabled={pending}
+ onClick={(event) => {
+ event.stopPropagation()
+ void openSelection()
+ }}
+ >
+ <ListChecks />
+ <span className="truncate">
+ {t('panel.downloads.action.selectFiles')}
+ </span>
+ </Button>
+ )
+}
diff --git a/src/renderer/lib/open-magnet-file-selection.test.ts b/src/renderer/lib/open-magnet-file-selection.test.ts
new file mode 100644
index 00000000..6483dabc
--- /dev/null
+++ b/src/renderer/lib/open-magnet-file-selection.test.ts
@@ -0,0 +1,89 @@
+import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ openMagnetFileSelection,
+ showMagnetFileSelection,
+} from './open-magnet-file-selection'
+
+vi.mock('@renderer/lib/transport', () => ({ transport: { invoke: vi.fn() } }))
+const selection = {
+ taskId: 'ready',
+ magnetUri: 'magnet:?xt=urn:btih:abc',
+ torrentBase64: 'dG9ycmVudA==',
+ saveDir: '/downloads',
+ meta: {
+ name: 'demo',
+ infoHash: 'a'.repeat(40),
+ totalSize: 30,
+ comment: null,
+ isPrivate: false,
+ files: [
+ { index: 0, path: 'a.txt', size: 10, extension: '.txt' },
+ { index: 1, path: 'b.txt', size: 20, extension: '.txt' },
+ ],
+ },
+}
+
+beforeEach(() => {
+ vi.stubGlobal('__MOTRIX_TARGET__', 'web')
+ vi.clearAllMocks()
+ useAddTaskDialogStore.setState({
+ open: false,
+ prefill: undefined,
+ revision: 0,
+ })
+ vi.mocked(transport.invoke).mockResolvedValue({ ok: true, selection })
+})
+afterEach(() => vi.unstubAllGlobals())
+
+describe('openMagnetFileSelection', () => {
+ it('opens from the HTTP response without any WebSocket event', async () => {
+ await expect(openMagnetFileSelection('ready')).resolves.toBe(true)
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.ReopenMagnetFileSelection,
+ 'ready'
+ )
+ expect(useAddTaskDialogStore.getState().prefill).toMatchObject({
+ existingTaskId: 'ready',
+ selectedFiles: [0, 1],
+ base64: selection.torrentBase64,
+ })
+ })
+
+ it('does not reset edits if the matching selection is already displayed', async () => {
+ showMagnetFileSelection(selection)
+ useAddTaskDialogStore
+ .getState()
+ .openWith({ existingTaskId: 'ready', tab: 'torrent', selectedFiles: [1] })
+ const revision = useAddTaskDialogStore.getState().revision
+ await openMagnetFileSelection('ready')
+ expect(useAddTaskDialogStore.getState().revision).toBe(revision)
+ expect(useAddTaskDialogStore.getState().prefill).toMatchObject({
+ selectedFiles: [1],
+ })
+ })
+
+ it('ignores a stale task selection', async () => {
+ vi.mocked(transport.invoke).mockResolvedValue({ ok: true, selection: null })
+ await expect(openMagnetFileSelection('ready')).resolves.toBe(false)
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+
+ it('reports malformed responses instead of silently claiming success', async () => {
+ vi.mocked(transport.invoke).mockResolvedValue({ ok: true })
+ await expect(openMagnetFileSelection('ready')).rejects.toThrow()
+ })
+
+ it('retains the desktop window command flow', async () => {
+ vi.stubGlobal('__MOTRIX_TARGET__', 'electron')
+ vi.mocked(transport.invoke).mockResolvedValue(undefined)
+ await openMagnetFileSelection('ready')
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.ReopenMagnetFileSelection,
+ 'ready'
+ )
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/open-magnet-file-selection.ts b/src/renderer/lib/open-magnet-file-selection.ts
new file mode 100644
index 00000000..aca5afcb
--- /dev/null
+++ b/src/renderer/lib/open-magnet-file-selection.ts
@@ -0,0 +1,48 @@
+import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import {
+ type MagnetFileSelectionPayload,
+ reopenMagnetFileSelectionResultSchema,
+} from '@shared/schemas/add-task'
+
+export function showMagnetFileSelection(selection: MagnetFileSelectionPayload) {
+ useAddTaskDialogStore.getState().openWith({
+ tab: 'torrent',
+ source: 'magnet',
+ magnetUri: selection.magnetUri,
+ base64: selection.torrentBase64,
+ torrentMeta: selection.meta,
+ selectedFiles: selection.meta.files.map((file) => file.index),
+ saveDir: selection.saveDir,
+ existingTaskId: selection.taskId,
+ })
+}
+
+/** Web selection uses the HTTP response, so a disconnected event socket
+ * cannot leave a successful button click without a dialog. */
+export async function openMagnetFileSelection(
+ taskId: string,
+ shouldOpen: () => boolean = () => true
+): Promise<boolean> {
+ const revision = useAddTaskDialogStore.getState().revision
+ const result = await transport.invoke(
+ Commands.ReopenMagnetFileSelection,
+ taskId
+ )
+ if (__MOTRIX_TARGET__ === 'electron') return true
+ if (!shouldOpen()) return false
+ const { selection } = reopenMagnetFileSelectionResultSchema.parse(result)
+ if (!selection || selection.taskId !== taskId) return false
+ // The event can beat the command response. Keep the user's current edits.
+ const current = useAddTaskDialogStore.getState()
+ if (
+ current.open &&
+ current.prefill?.tab === 'torrent' &&
+ current.prefill.existingTaskId === taskId
+ )
+ return true
+ if (current.revision !== revision) return false
+ showMagnetFileSelection(selection)
+ return true
+}
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
index e88bfca0..0ee8352c 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
@@ -219,6 +219,28 @@ describe('TaskInspectorActionBar', () => {
)
})
+ it('shows failure feedback and allows retry from the inspector header', async () => {
+ vi.mocked(transport.invoke).mockRejectedValueOnce(
+ new Error('Metadata unavailable')
+ )
+ render(
+ <TaskInspectorActionBar
+ selected={[
+ makeTask({ type: TaskType.Magnet, status: TaskStatus.MetadataReady }),
+ ]}
+ onClose={vi.fn()}
+ />
+ )
+ const button = screen.getByRole('button', { name: 'Select files' })
+ fireEvent.click(button)
+ await waitFor(() =>
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'error' })
+ )
+ )
+ expect(button.hasAttribute('disabled')).toBe(false)
+ })
+
it('non-MetadataReady single: hides Select files', () => {
render(
<TaskInspectorActionBar
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
index 306e46bb..3471ae51 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
@@ -1,4 +1,5 @@
import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
+import { MagnetFileSelectionButton } from '@renderer/components/task/magnet-file-selection-button'
import { Button } from '@renderer/components/ui/button'
import { toast } from '@renderer/components/ui/toast'
import { useModifierKeys } from '@renderer/hooks/use-modifier-keys'
@@ -14,7 +15,6 @@ import { isTorrentLike } from '@shared/types/task-actions'
import {
ChevronDown,
FolderOpen,
- ListChecks,
Pause,
Play,
RadioTower,
@@ -271,19 +271,7 @@ export function TaskInspectorActionBar({
)}
{single && single.status === TaskStatus.MetadataReady && (
- <Button
- size="xs"
- variant="outline"
- onClick={() =>
- void transport.invoke(
- Commands.ReopenMagnetFileSelection,
- single.id
- )
- }
- >
- <ListChecks />
- {t('panel.downloads.action.selectFiles')}
- </Button>
+ <MagnetFileSelectionButton task={single} />
)}
{single &&
diff --git a/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx b/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
index 3fd0959b..e327f5ae 100644
--- a/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
@@ -35,7 +35,11 @@ const FIXTURE = {
seedRatio: 1,
seedTime: 60,
},
- app: { magnetFileSelection: true },
+ app: {
+ magnetFileSelection: true,
+ magnetFileSelectionAutoDownload: false,
+ magnetFileSelectionTimeoutSeconds: 60,
+ },
tracker: {
autoSync: true,
syncIntervalHours: 24,
@@ -67,6 +71,96 @@ describe('<BitTorrentDialog>', () => {
})
})
+ it('saves the opt-in and waiting time together using only dirty fields', async () => {
+ render(
+ <BitTorrentDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.bittorrent.title"
+ descKey="settings.cards.bittorrent.desc"
+ />
+ )
+ await waitFor(() => screen.getByDisplayValue('128'))
+ expect(
+ screen.queryByRole('spinbutton', {
+ name: 'File selection timeout (seconds)',
+ })
+ ).toBeNull()
+ const user = userEvent.setup()
+ const toggle = screen.getByRole('switch', {
+ name: 'Download all files when selection times out',
+ })
+ expect(toggle).not.toBeChecked()
+ await user.click(toggle)
+ const timeout = screen.getByRole('spinbutton', {
+ name: 'File selection timeout (seconds)',
+ })
+ expect(timeout).toHaveValue(60)
+ fireEvent.change(timeout, { target: { value: '120' } })
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: {
+ magnetFileSelectionAutoDownload: true,
+ magnetFileSelectionTimeoutSeconds: 120,
+ },
+ })
+ })
+
+ it('rejects out-of-range waiting times before saving', async () => {
+ render(
+ <BitTorrentDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.bittorrent.title"
+ descKey="settings.cards.bittorrent.desc"
+ />
+ )
+ await waitFor(() => screen.getByDisplayValue('128'))
+ const user = userEvent.setup()
+ await user.click(
+ screen.getByRole('switch', {
+ name: 'Download all files when selection times out',
+ })
+ )
+ fireEvent.change(
+ screen.getByRole('spinbutton', {
+ name: 'File selection timeout (seconds)',
+ }),
+ { target: { value: '0' } }
+ )
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(
+ screen.getByText('Enter a whole number from 10 to 3600 seconds.')
+ ).toBeInTheDocument()
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.UpdateSettings,
+ expect.anything()
+ )
+ })
+
+ it('disables automatic selection when magnet file selection is off', async () => {
+ render(
+ <BitTorrentDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.bittorrent.title"
+ descKey="settings.cards.bittorrent.desc"
+ />
+ )
+ await waitFor(() => screen.getByDisplayValue('128'))
+ const user = userEvent.setup()
+ await user.click(
+ screen.getByRole('switch', {
+ name: 'Open file selection after magnet metadata loads',
+ })
+ )
+ expect(
+ screen.getByRole('switch', {
+ name: 'Download all files when selection times out',
+ })
+ ).toHaveAttribute('aria-disabled', 'true')
+ })
+
it('hydrates engine + app + tracker fields', async () => {
render(
<BitTorrentDialog
diff --git a/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx b/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
index ad64eb39..eccf5f1e 100644
--- a/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
+++ b/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
@@ -17,6 +17,7 @@ import {
FormField,
FormItem,
FormLabel,
+ FormMessage,
} from '@renderer/components/ui/form'
import { Input } from '@renderer/components/ui/input'
import { Separator } from '@renderer/components/ui/separator'
@@ -26,6 +27,11 @@ import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
import { DEFAULT_APP_SETTINGS, DEFAULT_ENGINE_SETTINGS } from '@shared/schemas'
+import {
+ MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS,
+ MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS,
+ magnetFileSelectionTimeoutSecondsSchema,
+} from '@shared/schemas/app-settings'
import { DEFAULT_TRACKER_SETTINGS } from '@shared/schemas/tracker-settings'
import type {
AppSettings,
@@ -50,7 +56,12 @@ interface BtFields {
| 'seedRatio'
| 'seedTime'
>
- app: Pick<MotrixAppSettings, 'magnetFileSelection'>
+ app: Pick<
+ MotrixAppSettings,
+ | 'magnetFileSelection'
+ | 'magnetFileSelectionAutoDownload'
+ | 'magnetFileSelectionTimeoutSeconds'
+ >
tracker: Omit<
TrackerSettings,
'sources' | 'sourcesEnabled' | 'blacklistEnabled' | 'blacklistSources'
@@ -69,6 +80,10 @@ const DEFAULTS: BtFields = {
},
app: {
magnetFileSelection: DEFAULT_APP_SETTINGS.magnetFileSelection,
+ magnetFileSelectionAutoDownload:
+ DEFAULT_APP_SETTINGS.magnetFileSelectionAutoDownload,
+ magnetFileSelectionTimeoutSeconds:
+ DEFAULT_APP_SETTINGS.magnetFileSelectionTimeoutSeconds,
},
tracker: {
autoSync: DEFAULT_TRACKER_SETTINGS.autoSync,
@@ -89,6 +104,8 @@ export function BitTorrentDialog({
}: SettingsCardDialogProps) {
const { t } = useTranslation()
const form = useForm<BtFields>({ defaultValues: DEFAULTS })
+ const fileSelectionEnabled = form.watch('app.magnetFileSelection')
+ const autoDownloadEnabled = form.watch('app.magnetFileSelectionAutoDownload')
// biome-ignore lint/correctness/useExhaustiveDependencies: form is stable
useEffect(() => {
@@ -109,7 +126,13 @@ export function BitTorrentDialog({
seedRatio: all.engine.seedRatio,
seedTime: all.engine.seedTime,
},
- app: { magnetFileSelection: all.app.magnetFileSelection },
+ app: {
+ magnetFileSelection: all.app.magnetFileSelection,
+ magnetFileSelectionAutoDownload:
+ all.app.magnetFileSelectionAutoDownload,
+ magnetFileSelectionTimeoutSeconds:
+ all.app.magnetFileSelectionTimeoutSeconds,
+ },
tracker: {
autoSync: all.tracker.autoSync,
syncIntervalHours: all.tracker.syncIntervalHours,
@@ -318,6 +341,83 @@ export function BitTorrentDialog({
)}
/>
+ <FormField
+ control={form.control}
+ name="app.magnetFileSelectionAutoDownload"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t(
+ 'settings.bittorrent.peers.magnetFileSelectionAutoDownload'
+ )}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t(
+ 'settings.bittorrent.peers.magnetFileSelectionAutoDownloadDesc'
+ )}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ disabled={!fileSelectionEnabled}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ {autoDownloadEnabled && (
+ <FormField
+ control={form.control}
+ name="app.magnetFileSelectionTimeoutSeconds"
+ rules={{
+ validate: (value) =>
+ magnetFileSelectionTimeoutSecondsSchema.safeParse(value)
+ .success ||
+ t(
+ 'settings.bittorrent.peers.magnetFileSelectionTimeoutInvalid',
+ {
+ min: MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS,
+ max: MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS,
+ }
+ ),
+ }}
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t(
+ 'settings.bittorrent.peers.magnetFileSelectionTimeoutSeconds'
+ )}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t(
+ 'settings.bittorrent.peers.magnetFileSelectionTimeoutSecondsDesc'
+ )}
+ </FormDescription>
+ <FormMessage />
+ </div>
+ <FormControl>
+ <Input
+ {...field}
+ type="number"
+ min={MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS}
+ max={MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS}
+ step={1}
+ className="w-30 h-8"
+ disabled={!fileSelectionEnabled}
+ onChange={(event) =>
+ field.onChange(Number(event.target.value))
+ }
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ )}
+
<Separator className="my-4" />
{/* Seeding */}
diff --git a/src/server/index.ts b/src/server/index.ts
index 4a076b25..a6545a44 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -110,6 +110,7 @@ import {
} from '@core/task/task-recovery-service'
import { TaskUpdatePublisher } from '@core/task/task-update-publisher'
import { TorrentMetaStoreImpl } from '@core/task/torrent-meta-store'
+import { MagnetSelectionTimeout } from '@core/torrent/magnet-selection-timeout'
import { MagnetTracker } from '@core/torrent/magnet-tracker'
import { shouldSkipForPendingMagnetMetadata } from '@core/torrent/metadata-task-filter'
import { TorrentParser } from '@core/torrent/torrent-parser'
@@ -120,7 +121,9 @@ import {
TrackerSyncer,
} from '@core/tracker'
import { resolveSupportedLocale } from '@shared/constants/locales'
+import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
+import type { TaskCreateCommandResult } from '@shared/schemas/add-task'
import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'
import { EngineState } from '@shared/types/engine'
import type { AppSettings } from '@shared/types/settings'
@@ -1127,6 +1130,25 @@ async function main() {
publishTaskUpdateNow,
downloadPathPolicy,
})
+ const createTask = commandHandlers[Commands.CreateTask]
+ if (!createTask) throw new Error('CreateTask handler is not registered')
+ const selectionTimeout = new MagnetSelectionTimeout({
+ eventBus,
+ getSettings: () => settingsManager.getApp(),
+ getTasks: () => taskManager.getAll(),
+ isEngineReady: () => supervisor.getState() === EngineState.Ready,
+ getSelection: (taskId) => magnetTracker.getFileSelection(taskId),
+ createTask: async (request) =>
+ (await createTask(request)) as TaskCreateCommandResult,
+ notify: (input) => notificationCenter.notify(input),
+ log: getLogger('magnet-selection-timeout'),
+ })
+ shutdownActions.drainMagnet = async () => {
+ await Promise.all([
+ selectionTimeout.stopAndDrain(),
+ magnetTracker.stopAndDrain(),
+ ])
+ }
const queryHandlers = buildServerQueryHandlers({
taskManager,
statsAggregator,
@@ -1552,6 +1574,7 @@ async function main() {
})
pluginStartup.openProducers(() => {
+ selectionTimeout.start()
adapter.onBtDownloadComplete((engineTaskId) => {
runShellAsyncWork('BT finalize', async () => {
const task = taskManager.getByEngineTaskId(engineTaskId)
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index ec64975b..0e67a738 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -156,6 +156,7 @@ function makeFakeCtx() {
dispatch: vi.fn().mockResolvedValue(undefined),
} as unknown as ActivationDispatcher,
magnetTracker: {
+ getFileSelection: vi.fn().mockResolvedValue(undefined),
submit: vi.fn().mockResolvedValue(undefined),
retryMetadata: vi.fn().mockResolvedValue(undefined),
cancel: vi.fn().mockResolvedValue('removed'),
@@ -734,6 +735,36 @@ describe('server Commands.UpdateGeoIPDatabase', () => {
})
describe('server Commands.CreateTask magnet metadata selection', () => {
+ it('returns file selection to the requesting WebUI without broadcasting', async () => {
+ const ctx = makeFakeCtx()
+ const selection = { taskId: 'ready-1', torrentBase64: 'dG9ycmVudA==' }
+ vi.mocked(ctx.magnetTracker.getFileSelection).mockResolvedValue(
+ selection as never
+ )
+ const handlers = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )
+ await expect(
+ handlers[Commands.ReopenMagnetFileSelection]?.('ready-1')
+ ).resolves.toEqual({
+ ok: true,
+ selection,
+ })
+ expect(ctx.magnetTracker.getFileSelection).toHaveBeenCalledWith('ready-1')
+ expect(ctx.eventBus.emit).not.toHaveBeenCalled()
+ })
+
+ it('returns a stale selection as null', async () => {
+ const handlers = buildServerCommandHandlers(
+ makeFakeCtx() as unknown as ServerCommandContext
+ )
+ await expect(
+ handlers[Commands.ReopenMagnetFileSelection]?.('finished-1')
+ ).resolves.toEqual({
+ ok: true,
+ selection: null,
+ })
+ })
it('submits bare magnet to metadata selection when enabled', async () => {
const ctx = makeFakeCtx()
const handlers = buildServerCommandHandlers(
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 276a40d2..f7891a82 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -400,8 +400,8 @@ export function buildServerCommandHandlers(
},
[Commands.ReopenMagnetFileSelection]: async (taskId: string) => {
- await magnetTracker.reopenFileSelection(taskId)
- return { ok: true }
+ const selection = await magnetTracker.getFileSelection(taskId)
+ return { ok: true, selection: selection ?? null }
},
[Commands.CreateTask]: async (request: unknown) => {
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 3a83caa7..43ab28f2 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -843,6 +843,10 @@
"saveDirRequired": "Save directory is required",
"noFilesSelected": "Select at least one file",
"missingSource": "Torrent file or magnet link is required"
+ },
+ "selectionTimeout": {
+ "started": "File selection timed out: downloading all files in {{name}}",
+ "failed": "Could not start {{name}} automatically. Open task details to select files and retry."
}
},
"detail": {
@@ -1141,7 +1145,12 @@
"btEnableLpd": "Local peer discovery",
"btEnableLpdDesc": "Find peers on the local network.",
"magnetFileSelection": "Open file selection after magnet metadata loads",
- "magnetFileSelectionDesc": "Show a file picker once magnet metadata arrives."
+ "magnetFileSelectionDesc": "Show a file picker once magnet metadata arrives.",
+ "magnetFileSelectionAutoDownload": "Download all files when selection times out",
+ "magnetFileSelectionAutoDownloadDesc": "If file selection is not confirmed in time, download all files to the task’s save folder, even when the window or WebUI is closed.",
+ "magnetFileSelectionTimeoutSeconds": "File selection timeout (seconds)",
+ "magnetFileSelectionTimeoutSecondsDesc": "Count from when metadata is ready. Changing the timeout also applies to tasks already waiting for file selection.",
+ "magnetFileSelectionTimeoutInvalid": "Enter a whole number from {{min}} to {{max}} seconds."
},
"seeding": {
"title": "Seeding",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index e39bc737..b7d9c692 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -831,6 +831,10 @@
"saveDirRequired": "必须指定保存目录",
"noFilesSelected": "请至少选择一个文件",
"missingSource": "需要种子文件或 magnet 链接"
+ },
+ "selectionTimeout": {
+ "started": "选择文件已超时,开始下载 {{name}} 的全部文件",
+ "failed": "无法自动开始下载 {{name}},请打开任务详情,选择文件后重试。"
}
},
"detail": {
@@ -1128,7 +1132,12 @@
"btEnableLpd": "本地节点发现",
"btEnableLpdDesc": "在本地网络发现节点。",
"magnetFileSelection": "磁链元数据加载后弹出文件选择",
- "magnetFileSelectionDesc": "磁链元数据到达后显示文件选择器。"
+ "magnetFileSelectionDesc": "磁链元数据到达后显示文件选择器。",
+ "magnetFileSelectionAutoDownload": "选择文件超时后自动下载全部文件",
+ "magnetFileSelectionAutoDownloadDesc": "未在限定时间内确认文件选择,将下载全部文件到任务保存目录;关闭窗口或 WebUI 后仍会生效。",
+ "magnetFileSelectionTimeoutSeconds": "选择文件等待时间(秒)",
+ "magnetFileSelectionTimeoutSecondsDesc": "从元数据解析完成、进入待选文件状态开始计时。修改时长也会应用到已经等待选择的任务。",
+ "magnetFileSelectionTimeoutInvalid": "请输入 {{min}} 至 {{max}} 秒之间的整数。"
},
"seeding": {
"title": "做种",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 69ef1709..fab6c177 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -831,6 +831,10 @@
"saveDirRequired": "必須指定儲存目錄",
"noFilesSelected": "至少選擇一個檔案",
"missingSource": "必須提供 Torrent 檔案或 Magnet 連結"
+ },
+ "selectionTimeout": {
+ "started": "選擇檔案已逾時,開始下載 {{name}} 的全部檔案",
+ "failed": "無法自動開始下載 {{name}},請開啟任務詳細資料,選擇檔案後重試。"
}
},
"detail": {
@@ -1128,7 +1132,12 @@
"btEnableLpd": "區域網路對等節點探索",
"btEnableLpdDesc": "在區域網路尋找對等節點。",
"magnetFileSelection": "Magnet 中繼資料載入後開啟檔案選擇",
- "magnetFileSelectionDesc": "收到 Magnet 中繼資料後顯示檔案選擇器。"
+ "magnetFileSelectionDesc": "收到 Magnet 中繼資料後顯示檔案選擇器。",
+ "magnetFileSelectionAutoDownload": "選擇檔案逾時後自動下載全部檔案",
+ "magnetFileSelectionAutoDownloadDesc": "未在限定時間內確認檔案選擇,將下載全部檔案到任務儲存目錄;關閉視窗或 WebUI 後仍會生效。",
+ "magnetFileSelectionTimeoutSeconds": "選擇檔案等待時間(秒)",
+ "magnetFileSelectionTimeoutSecondsDesc": "從中繼資料解析完成、進入待選檔案狀態開始計時。修改時長也會套用到已經等待選擇的任務。",
+ "magnetFileSelectionTimeoutInvalid": "請輸入 {{min}} 至 {{max}} 秒之間的整數。"
},
"seeding": {
"title": "做種",
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index ddf4cd68..fe5b5597 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -41,6 +41,7 @@ export const Events = {
SpeedLimitChanged: 'event:speedLimitChanged',
// Torrent
MagnetFileSelection: 'event:magnetFileSelection',
+ MagnetFileSelectionSettled: 'event:magnetFileSelectionSettled',
// SetAddTaskMode payload is now `AddTaskUrlParams` — see
// @shared/schemas/add-task.ts setAddTaskModeEventPayloadSchema.
// The legacy `{ mode: 'links' | 'torrent' }` shape is a valid subset.
diff --git a/src/shared/protocol/forwardable-events.test.ts b/src/shared/protocol/forwardable-events.test.ts
index 84cf4e3e..85d79e50 100644
--- a/src/shared/protocol/forwardable-events.test.ts
+++ b/src/shared/protocol/forwardable-events.test.ts
@@ -21,7 +21,7 @@ describe('ForwardableEvents', () => {
})
it('has the expected number of forwardable events', () => {
- expect(ForwardableEvents).toHaveLength(51)
+ expect(ForwardableEvents).toHaveLength(52)
})
it('includes the bridge approval events (web-shell pairing)', () => {
@@ -43,6 +43,7 @@ describe('ForwardableEvents', () => {
expect(ForwardableEvents).toContain(Events.TaskInspectorActivityUpdated)
expect(ForwardableEvents).toContain(Events.StatsUpdated)
expect(ForwardableEvents).toContain(Events.MagnetFileSelection)
+ expect(ForwardableEvents).toContain(Events.MagnetFileSelectionSettled)
})
it('includes all engine events', () => {
diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.ts
index a92e02ba..a3f97c7b 100644
--- a/src/shared/protocol/forwardable-events.ts
+++ b/src/shared/protocol/forwardable-events.ts
@@ -7,6 +7,7 @@ export const ForwardableEvents = [
Events.TaskActivityUpdated,
Events.TaskInspectorActivityUpdated,
Events.MagnetFileSelection,
+ Events.MagnetFileSelectionSettled,
Events.StatsUpdated,
Events.EngineDisconnected,
Events.EngineRecovered,
diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.ts
index 582444c1..5ca41851 100644
--- a/src/shared/schemas/add-task.ts
+++ b/src/shared/schemas/add-task.ts
@@ -213,6 +213,15 @@ export const magnetFileSelectionPayloadSchema = z.object({
saveDir: z.string(),
})
+export type MagnetFileSelectionPayload = z.infer<
+ typeof magnetFileSelectionPayloadSchema
+>
+
+export const reopenMagnetFileSelectionResultSchema = z.object({
+ ok: z.literal(true),
+ selection: magnetFileSelectionPayloadSchema.nullable(),
+})
+
export const protocolTorrentFilePayloadSchema = z.object({
payload: z.object({ name: z.string(), dataBase64: z.string() }),
meta: torrentMetaSchema,
@@ -349,3 +358,9 @@ export function encodeUrlParams(p: AddTaskUrlParams): Record<string, string> {
}
return out
}
+
+/** The pending selection was accepted by the background timeout service. */
+export const magnetFileSelectionSettledPayloadSchema = z.object({
+ taskId: z.string().min(1),
+ downloadTaskId: z.string().min(1),
+})
diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.ts
index 05c709d4..bcab8a44 100644
--- a/src/shared/schemas/app-settings.test.ts
+++ b/src/shared/schemas/app-settings.test.ts
@@ -2,6 +2,32 @@ import { describe, expect, it } from 'vitest'
import { appSettingsSchema, DEFAULT_APP_SETTINGS } from './app-settings'
describe('appSettingsSchema', () => {
+ it('keeps selection timeout downloads opt-in with a 60 second default', () => {
+ expect(DEFAULT_APP_SETTINGS.magnetFileSelectionAutoDownload).toBe(false)
+ expect(DEFAULT_APP_SETTINGS.magnetFileSelectionTimeoutSeconds).toBe(60)
+ expect(
+ appSettingsSchema.parse({ magnetFileSelectionAutoDownload: true })
+ .magnetFileSelectionAutoDownload
+ ).toBe(true)
+ })
+
+ it.each([0, -1, 9, 3601, 60.5, '60', null])(
+ 'recovers invalid selection timeout %s',
+ (value) => {
+ expect(
+ appSettingsSchema.parse({ magnetFileSelectionTimeoutSeconds: value })
+ .magnetFileSelectionTimeoutSeconds
+ ).toBe(60)
+ }
+ )
+
+ it.each([10, 120, 3600])('preserves valid selection timeout %s', (value) => {
+ expect(
+ appSettingsSchema.parse({ magnetFileSelectionTimeoutSeconds: value })
+ .magnetFileSelectionTimeoutSeconds
+ ).toBe(value)
+ })
+
it('defaults reduceMotion to false and preserves an explicit opt-in', () => {
expect(DEFAULT_APP_SETTINGS.reduceMotion).toBe(false)
expect(appSettingsSchema.parse({}).reduceMotion).toBe(false)
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index cd4bc45f..a201f1e2 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -6,6 +6,14 @@ import { supportedLocaleSchema } from './locale'
export const appUpdateChannelSchema = z.enum(['stable', 'beta'])
+export const MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS = 10
+export const MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS = 3600
+export const magnetFileSelectionTimeoutSecondsSchema = z
+ .number()
+ .int()
+ .min(MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS)
+ .max(MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS)
+
export const appSettingsSchema = z.object({
launchAtStartup: z.boolean().catch(false),
theme: z.enum(['system', 'light', 'dark']).catch('system'),
@@ -27,6 +35,9 @@ export const appSettingsSchema = z.object({
lightweightMode: z.boolean().catch(false),
traySpeedometer: z.boolean().catch(true),
magnetFileSelection: z.boolean().catch(true),
+ magnetFileSelectionAutoDownload: z.boolean().catch(false),
+ magnetFileSelectionTimeoutSeconds:
+ magnetFileSelectionTimeoutSecondsSchema.catch(60),
browserBridgeEnabled: z.boolean().catch(true),
liquidGlassEffect: z.boolean().catch(false),
warnBeforeQuit: z.boolean().catch(true),
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index 5fdc2e54..c2252da2 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -233,6 +233,8 @@ export interface MotrixAppSettings {
lightweightMode: boolean
traySpeedometer: boolean
magnetFileSelection: boolean
+ magnetFileSelectionAutoDownload: boolean
+ magnetFileSelectionTimeoutSeconds: number
/** Master switch for the WebSocket bridge that lets browser extensions
* hand downloads to Motrix. Default true. Changing requires app restart. */
browserBridgeEnabled: boolean
diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.ts
index cf3c264b..27bfa06b 100644
--- a/tests/check-third-party-notices.test.ts
+++ b/tests/check-third-party-notices.test.ts
@@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
+import noticeTestConfig from '../vitest.notices.config'
const ROOT = process.cwd()
const NATIVE_HOST_CARGO_LOCK = path.join(
@@ -662,6 +663,12 @@ describe('third-party graph dependency notices', () => {
expect(scripts['check:third-party-notices']).toContain(
'vitest run tests/check-third-party-notices.test.ts tests/generate-third-party-notices.test.ts'
)
+ expect(scripts['check:third-party-notices']).toContain(
+ '--config vitest.notices.config.ts'
+ )
+ expect(noticeTestConfig.test?.environment).toBe('node')
+ expect(noticeTestConfig.test?.globalSetup).toEqual([])
+ expect(noticeTestConfig.test?.setupFiles).toEqual([])
expect(scripts['check:third-party-notices']).not.toContain(
NOTICE_GATE_COMMAND
)
diff --git a/tests/scripts/fetch-builtins.test.ts b/tests/scripts/fetch-builtins.test.ts
index 4c7e64c3..6d2a8e9f 100644
--- a/tests/scripts/fetch-builtins.test.ts
+++ b/tests/scripts/fetch-builtins.test.ts
@@ -1,5 +1,5 @@
import { createHash, generateKeyPairSync, sign as signBytes } from 'node:crypto'
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// @ts-expect-error — .mjs without types
import {
downloadBytes,
@@ -277,7 +277,7 @@ function fakeStreamResponse(
? String(contentLength)
: null,
},
- body: { getReader: () => ({ read, cancel }) },
+ body: { getReader: () => ({ read, cancel }), cancel },
},
read,
cancel,
@@ -285,8 +285,117 @@ function fakeStreamResponse(
}
describe('downloadBytes', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ })
+
afterEach(() => {
vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ })
+
+ function httpFailure(status: number, retryAfter?: string) {
+ return {
+ ok: false,
+ status,
+ headers: { get: () => retryAfter ?? null },
+ body: { cancel: vi.fn(async () => {}) },
+ }
+ }
+
+ it('recovers after repeated gateway failures with increasing delays and retry diagnostics', async () => {
+ const failure = httpFailure(504)
+ const { response } = fakeStreamResponse([new Uint8Array([1, 2])])
+ const fetchMock = vi.fn().mockResolvedValue(response)
+ for (let i = 0; i < 3; i++) fetchMock.mockResolvedValueOnce(failure)
+ vi.stubGlobal('fetch', fetchMock)
+
+ const pending = downloadBytes('https://example.test/f.moext.sig', 10)
+ await vi.advanceTimersByTimeAsync(1_999)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(4_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(8_000)
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(await pending).toEqual(Buffer.from([1, 2]))
+ expect(fetchMock).toHaveBeenCalledTimes(4)
+ expect(failure.body.cancel).toHaveBeenCalledTimes(3)
+ expect(console.warn).toHaveBeenCalledWith(
+ expect.stringContaining('-> 504; retry 4/5 in 8000ms')
+ )
+ })
+
+ it('fails after the bounded retry budget when the service stays unavailable', async () => {
+ const failure = httpFailure(503)
+ const fetchMock = vi.fn().mockResolvedValue(failure)
+ vi.stubGlobal('fetch', fetchMock)
+ const result = expect(
+ downloadBytes('https://example.test/f.moext', 10)
+ ).rejects.toThrow(/-> 503/)
+
+ await vi.runAllTimersAsync()
+ await result
+ expect(fetchMock).toHaveBeenCalledTimes(5)
+ expect(failure.body.cancel).toHaveBeenCalledTimes(5)
+ })
+
+ it.each([401, 403, 404])(
+ 'does not retry a permanent HTTP %i failure',
+ async (status) => {
+ const failure = httpFailure(status)
+ const fetchMock = vi.fn().mockResolvedValue(failure)
+ vi.stubGlobal('fetch', fetchMock)
+
+ await expect(
+ downloadBytes('https://example.test/f.moext', 10)
+ ).rejects.toThrow(`-> ${status}`)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(failure.body.cancel).toHaveBeenCalledOnce()
+ expect(console.warn).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ ['seconds', '7', 7_000],
+ ['date', 'Mon, 07 Sep 2026 00:00:07 GMT', 7_000],
+ ['bounded delay', '3600', 30_000],
+ ['invalid header', 'invalid', 2_000],
+ ])(
+ 'honors Retry-After with a %s value',
+ async (_label, retryAfter, delay) => {
+ vi.setSystemTime(new Date('2026-09-07T00:00:00Z'))
+ const { response } = fakeStreamResponse([new Uint8Array([1])])
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(httpFailure(429, retryAfter))
+ .mockResolvedValue(response)
+ vi.stubGlobal('fetch', fetchMock)
+ const pending = downloadBytes('https://example.test/f.moext', 10)
+
+ await vi.advanceTimersByTimeAsync(delay - 1)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(await pending).toEqual(Buffer.from([1]))
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ }
+ )
+
+ it('retries a request timeout', async () => {
+ const { response } = fakeStreamResponse([new Uint8Array([1])])
+ const fetchMock = vi
+ .fn()
+ .mockRejectedValueOnce(new DOMException('Timed out', 'TimeoutError'))
+ .mockResolvedValueOnce(response)
+ vi.stubGlobal('fetch', fetchMock)
+ const pending = downloadBytes('https://example.test/f.moext', 10)
+
+ await vi.runAllTimersAsync()
+ expect(await pending).toEqual(Buffer.from([1]))
+ expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('streams a body within sizeCap and returns the concatenated bytes', async () => {
@@ -317,10 +426,11 @@ describe('downloadBytes', () => {
).rejects.toThrow(/exceeds lock size/)
expect(read).toHaveBeenCalledTimes(2)
expect(cancel).toHaveBeenCalled()
+ expect(fetch).toHaveBeenCalledTimes(1)
})
it('rejects on an over-cap Content-Length before reading any body chunk', async () => {
- const { response, read } = fakeStreamResponse([new Uint8Array(3)], {
+ const { response, read, cancel } = fakeStreamResponse([new Uint8Array(3)], {
contentLength: 999,
})
vi.stubGlobal(
@@ -331,5 +441,7 @@ describe('downloadBytes', () => {
downloadBytes('https://example.test/big.moext', 5)
).rejects.toThrow(/Content-Length/)
expect(read).not.toHaveBeenCalled()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(fetch).toHaveBeenCalledTimes(1)
})
})
diff --git a/vitest.notices.config.ts b/vitest.notices.config.ts
new file mode 100644
index 00000000..068f4dca
--- /dev/null
+++ b/vitest.notices.config.ts
@@ -0,0 +1,15 @@
+import { defineConfig } from 'vitest/config'
+
+// License checks read local manifests and artifacts. Keep them independent of
+// the application's worker build and signed builtin-plugin downloads.
+export default defineConfig({
+ test: {
+ environment: 'node',
+ setupFiles: [],
+ globalSetup: [],
+ include: [
+ 'tests/check-third-party-notices.test.ts',
+ 'tests/generate-third-party-notices.test.ts',
+ ],
+ },
+})