A full-featured download manager.
fix(bt): avoid long paths and retry magnet metadata (#1932)
Dr_rOotbabc297ed523
diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjsindex ef44e06e..2f70f0e4 100644--- a/scripts/smoke-server-image.mjs+++ b/scripts/smoke-server-image.mjs@@ -1026,9 +1026,16 @@ export async function smokeServerImage(options) {timeoutMs)await assertHostFile(- path.join(volumes.downloadsDir, 'sample-data', 'sample-data', 'test.bin'),+ path.join(volumes.downloadsDir, 'sample-data', 'test.bin'),await readFile(TORRENT_DATA_FILE))+ if (+ await pathExists(+ path.join(volumes.downloadsDir, 'sample-data', 'sample-data')+ )+ ) {+ throw new Error('BT output retained the duplicated torrent root')+ }await rpc(url, operatorToken, 'command', 'command:setTaskBtTracker', {engineGid: finalBtTask.engineTaskId,trackers: [trackerUrl],diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 58cda43e..3c3a228a 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -1086,6 +1086,42 @@ describe('Aria2Adapter', () => {expect(opts).not.toHaveProperty('select-file')})+ it('maps zero-based output paths to repeated aria2 index-out options', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addTorrent).mockResolvedValue('g')+ const adapter = new Aria2Adapter(rpc)++ await adapter.addTorrent({+ metadata: new Uint8Array([0]),+ saveDir: '/d/.motrix/abc',+ outputFilePaths: [+ { fileIndex: 0, relativePath: 'p/movie.mkv' },+ { fileIndex: 2, relativePath: 'p/sub/readme.txt' },+ ],+ })++ const [, , opts] = vi.mocked(rpc.addTorrent).mock.calls[0] as [+ string,+ string[],+ Record<string, string | string[]>,+ ]+ expect(opts['index-out']).toEqual(['1=p/movie.mkv', '3=p/sub/readme.txt'])+ })++ it('rejects traversal in an output file mapping before RPC dispatch', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)++ await expect(+ adapter.addTorrent({+ metadata: new Uint8Array([0]),+ saveDir: '/d',+ outputFilePaths: [{ fileIndex: 0, relativePath: '../escape' }],+ })+ ).rejects.toThrow('Invalid torrent output file mapping')+ expect(rpc.addTorrent).not.toHaveBeenCalled()+ })+it('forwards and returns a caller-reserved 16-hex gid', async () => {const rpc = createMockRpc()vi.mocked(rpc.addTorrent).mockResolvedValue('a1b2c3d4e5f60718')diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex c8fe18f0..1a1acc65 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -1,3 +1,4 @@+import path from 'node:path'import { getLogger } from '@core/logger'import { AppError, ErrorCode } from '@shared/errors'import type {@@ -460,7 +461,7 @@ export class Aria2Adapter implements EngineAdapter {}const requestedGid =params.gid ?? (typeof extraGid === 'string' ? extraGid : undefined)- const opts: Record<string, string> = {+ const opts: Record<string, string | string[]> = {dir: params.saveDir,pause: String(params.pause ?? false),}@@ -474,6 +475,33 @@ export class Aria2Adapter implements EngineAdapter {if (params.selectedFiles?.length) {opts['select-file'] = params.selectedFiles.join(',')}+ if (params.outputFilePaths?.length) {+ const seen = new Set<number>()+ opts['index-out'] = params.outputFilePaths.map(+ ({ fileIndex, relativePath }) => {+ const components = relativePath.replace(/\\/g, '/').split('/')+ if (+ !Number.isSafeInteger(fileIndex) ||+ fileIndex < 0 ||+ seen.has(fileIndex) ||+ relativePath.length === 0 ||+ relativePath.includes('\0') ||+ path.isAbsolute(relativePath) ||+ /^[A-Za-z]:[\\/]/.test(relativePath) ||+ components.some(+ (component) =>+ component.length === 0 ||+ component === '.' ||+ component === '..'+ )+ ) {+ throw new TypeError('Invalid torrent output file mapping')+ }+ seen.add(fileIndex)+ return `${fileIndex + 1}=${relativePath}`+ }+ )+ }if (params.seedTime !== undefined) {opts['seed-time'] = String(params.seedTime)}@@ -499,7 +527,7 @@ export class Aria2Adapter implements EngineAdapter {}if (params.extraEngineOptions) {for (const [k, v] of Object.entries(params.extraEngineOptions)) {- opts[k] = v as string+ opts[k] = v}}if (requestedGid !== undefined) {diff --git a/src/core/engine/aria2/aria2-rpc-client.ts b/src/core/engine/aria2/aria2-rpc-client.tsindex f0dc86f8..00b0c21e 100644--- a/src/core/engine/aria2/aria2-rpc-client.ts+++ b/src/core/engine/aria2/aria2-rpc-client.ts@@ -92,7 +92,7 @@ export class Aria2RpcClient {addTorrent(torrentBase64: string,uris?: string[],- options?: Record<string, string>+ options?: Record<string, string | string[]>): Promise<string> {const params: unknown[] = [torrentBase64]if (uris !== undefined) params.push(uris)diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex 862dcb7a..9fb11765 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -15,6 +15,13 @@ import type { GlobalStats } from '@shared/types/stats'import type { DownloadTask, TaskFile } from '@shared/types/task'import type { FileAllocation } from '@shared/types/tuning'+export interface OutputFilePath {+ /** Engine-neutral, zero-based file index. */+ fileIndex: number+ /** Output path relative to `saveDir`. */+ relativePath: string+}+export interface AddTorrentParams {metadata: Uint8ArraysaveDir: string@@ -26,6 +33,9 @@ export interface AddTorrentParams {* these are 1-based (matching aria2's `select-file`). The create path is* responsible for converting its 0-based request indices before calling. */selectedFiles?: number[]+ /** Optional per-file output mapping. The adapter translates indices and+ * option syntax to the target engine. */+ outputFilePaths?: OutputFilePath[]seedTime?: numberseedRatio?: numberbtSeedUnverified?: booleandiff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex 79704df3..c1602d53 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -100,6 +100,17 @@ function makePrimaryInstance(}}+function buildSingleFileTorrent(name: string): Uint8Array {+ const nameField = `4:name${Buffer.byteLength(name, 'utf8')}:${name}`+ const prefix = Buffer.from(+ `d4:infod6:lengthi1024e${nameField}12:piece lengthi16384e6:pieces20:`,+ 'utf8'+ )+ return new Uint8Array(+ Buffer.concat([prefix, Buffer.alloc(20), Buffer.from('ee')])+ )+}+describe('finalizeTask HTTP/FTP branch', () => {it('performs removeDownloadResult → rename → status=Completed', async () => {const deps = makeDeps()@@ -547,6 +558,74 @@ describe('finalizeTask BT branch', () => {} as Partial<DownloadTask>)}+ it('renames only the indexed payload and reseeds through the restored final name', async () => {+ const workspacePath = '/d/.motrix/0123456789abcdefabcd'+ const renameAtomic = vi.fn(async () => {})+ const removePathRecursive = vi.fn(async () => {})+ const rebaseTaskFilePaths = vi.fn()+ const deps = makeDeps({+ fs: { renameAtomic, removePathRecursive },+ rebaseTaskFilePaths,+ torrentMetaStore: {+ read: vi.fn(async () => buildSingleFileTorrent('original.iso')),+ },+ })+ ;(deps.adapter.getTaskFiles as ReturnType<typeof vi.fn>).mockResolvedValue([+ {+ index: 0,+ path: `${workspacePath}/p`,+ size: 1,+ completedBytes: 0,+ selected: false,+ },+ ])+ const task = makeBtTask({+ saveDir: '/d',+ diskPath: workspacePath,+ finalPath: '/d/User chosen.iso',+ finalName: 'User chosen.iso',+ instances: [+ makePrimaryInstance({+ phase: TaskInstancePhase.BtDownload,+ diskPath: workspacePath,+ payload: {+ btStorageLayout: {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath,+ payloadEntry: 'p',+ torrentRootName: 'original.iso',+ multiFile: false,+ },+ },+ }),+ ],+ })+ ;(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(+ task+ )++ await finalizeTask('t1', deps)++ expect(renameAtomic).toHaveBeenCalledWith(+ `${workspacePath}/p`,+ '/d/User chosen.iso'+ )+ expect(rebaseTaskFilePaths).toHaveBeenCalledWith(+ 't1',+ `${workspacePath}/p`,+ '/d/User chosen.iso'+ )+ expect(removePathRecursive).toHaveBeenCalledWith(workspacePath)+ expect(removePathRecursive).not.toHaveBeenCalledWith('/d/User chosen.iso')+ expect(deps.adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({+ saveDir: '/d',+ outputFilePaths: [{ fileIndex: 0, relativePath: 'User chosen.iso' }],+ })+ )+ })+it('transitions status→Finalizing before rename', async () => {const deps = makeDeps()const task = makeBtTask()diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex 38e7a5b4..60519530 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -15,6 +15,12 @@ import type { TaskOccurrence } from '@shared/types/task-occurrence'import type Database from 'better-sqlite3'import type { AddTorrentParams } from '../../engine/engine-adapter'import { applyTerminalTransition } from '../apply-terminal-transition'+import {+ buildFinalOutputFilePaths,+ getBtPayloadPath,+ getBtStorageLayout,+ parseBtFileLayout,+} from '../bt-storage-layout'import { fireAfterComplete, fireOnError } from '../hook-dispatch'import { normalizeTerminalRuntimeMetrics } from '../normalize-terminal-runtime-metrics'import type { OccurrenceDispatcher } from '../occurrences/occurrence-dispatcher'@@ -98,6 +104,12 @@ export interface FinalizeTaskDeps {torrentMetaStore: {read(metaPath: string): Promise<Uint8Array>}+ /** Rebase persisted task_files after the staging payload is renamed. */+ rebaseTaskFilePaths?: (+ taskId: string,+ sourceRoot: string,+ finalRoot: string+ ) => voidsettings: {get(): { bt: { seedTime: number; seedRatio: number } }}@@ -371,6 +383,9 @@ async function finalizeBt(}const desiredFinalPath = finalizeOutcome.finalFilePath ?? task.finalPathawait persistDesiredFinalPath(task, desiredFinalPath, deps)+ const storageLayout = getBtStorageLayout(task)+ const stagingPayloadPath = getBtPayloadPath(task)+ const renameSource = stagingPayloadPath ?? task.diskPath// Settle the retiring gid's contribution INTO the baseline before we// forceRemove it. Two reasons:@@ -397,9 +412,13 @@ async function finalizeBt(// `--bt-remove-unselected-file=true` cleanup may have raced past// (cleanup can run on a later event-loop tick than forceRemove// returns; if rename happens in between, aria2 looks at the old- // diskPath and silent-skips). All paths are absolute, rooted at- // task.diskPath; we relativize so we can re-apply under finalPath.- const unselectedRelPaths = await snapshotUnselectedRelPaths(task, deps)+ // staging location and silent-skips). All paths are absolute, rooted at the+ // actual payload path; we relativize so we can re-apply under finalPath.+ const unselectedRelPaths = await snapshotUnselectedRelPaths(+ task,+ deps,+ renameSource+ )// Stop the active seeding task BEFORE rename + re-add. `removeDownloadResult`// alone is insufficient: it only clears tasks already in stopped/error/@@ -417,7 +436,7 @@ async function finalizeBt(await deps.adapter.removeDownloadResult(task.engineTaskId)try {- await deps.fs.renameAtomic(task.diskPath, desiredFinalPath)+ await deps.fs.renameAtomic(renameSource, desiredFinalPath)} catch (e) {const cause = (e as Error).messageconst errorMessage = `Failed to rename directory: ${cause}`@@ -431,6 +450,27 @@ async function finalizeBt(}const completedAt = Date.now()+ if (storageLayout) {+ try {+ deps.rebaseTaskFilePaths?.(task.id, renameSource, desiredFinalPath)+ } catch (err) {+ deps.log.warn(+ { err, taskId: task.id },+ 'finalize_bt_task_file_path_rebase_failed'+ )+ }+ if (!isSameOrDescendant(desiredFinalPath, storageLayout.workspacePath)) {+ try {+ await deps.fs.removePathRecursive(storageLayout.workspacePath)+ } catch (err) {+ deps.log.warn(+ { err, taskId: task.id, workspacePath: storageLayout.workspacePath },+ 'finalize_bt_workspace_cleanup_failed'+ )+ }+ }+ }+// Commit staged metadata now that the rename succeeded. The commit is a// sync SQLite tx; the callback is empty because the rename above already// happened on disk (we are intentionally outside the tx body for IO).@@ -612,6 +652,8 @@ async function finalizeBtAfterRename(? task.bt.selectedFiles: undefinedtry {+ const storageLayout = getBtStorageLayout(task)+ const parsedLayout = storageLayout ? await parseBtFileLayout(bytes) : nullconst actualGid = await deps.adapter.addTorrent({metadata: bytes,// aria2 lays files out at `<dir>/<info.name>/...` (multi-file) or@@ -619,7 +661,15 @@ async function finalizeBtAfterRename(// `<saveDir>/<finalName>.motrix/...`; after rename those files live// under `<finalPath>/...`. Pointing aria2 at `task.finalPath` makes// its `<dir>/<info.name>` lookup hit the existing on-disk layout.- saveDir: task.finalPath,+ saveDir: storageLayout ? path.dirname(task.finalPath) : task.finalPath,+ outputFilePaths:+ storageLayout && parsedLayout+ ? buildFinalOutputFilePaths(+ parsedLayout,+ task.finalPath,+ storageLayout+ )+ : undefined,selectedFiles,seedTime: bt.seedTime,seedRatio: seedRatioForNewGid,@@ -822,8 +872,8 @@ async function persistTaskState(/*** Capture relative paths of unselected files while the gid is still alive.- * Returns paths relative to `task.diskPath` so the caller can re-rebase- * them under `task.finalPath` after rename. Empty result for tasks that+ * Returns paths relative to the supplied source root so the caller can+ * re-rebase them under `task.finalPath` after rename. Empty result for tasks that* downloaded all files (no select-file used) — `getTaskFiles` reports* every file as `selected: true` in that case.*@@ -833,7 +883,8 @@ async function persistTaskState(*/async function snapshotUnselectedRelPaths(task: DownloadTask,- deps: FinalizeTaskDeps+ deps: FinalizeTaskDeps,+ sourceRoot = task.diskPath): Promise<string[]> {try {const files = await deps.adapter.getTaskFiles(task.engineTaskId)@@ -842,13 +893,13 @@ async function snapshotUnselectedRelPaths(if (f.selected) continue// aria2 reports absolute paths under the task's `dir`. Relativize// so the caller can apply the same rel-path under finalPath.- const rel = path.relative(task.diskPath, f.path)+ const rel = path.relative(sourceRoot, f.path)// Defensive: if aria2 ever returns a path outside diskPath// (shouldn't, but escape '..' would let us walk into the user's// filesystem), skip it.- if (rel.startsWith('..') || path.isAbsolute(rel)) {+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {deps.log.warn(- { taskId: task.id, filePath: f.path, diskPath: task.diskPath },+ { taskId: task.id, filePath: f.path, diskPath: sourceRoot },'finalize_bt_unselected_path_outside_disk_path')continue@@ -865,6 +916,14 @@ async function snapshotUnselectedRelPaths(}}+function isSameOrDescendant(candidate: string, parent: string): boolean {+ const relative = path.relative(parent, candidate)+ return (+ relative === '' ||+ (!relative.startsWith('..') && !path.isAbsolute(relative))+ )+}+/*** Remove unselected files under finalPath. Idempotent — overlapping* with aria2's own cleanup is fine. Errors are logged but never@@ -878,6 +937,7 @@ async function cleanupUnselectedAfterRename(): Promise<void> {let removed = 0for (const rel of relPaths) {+ if (rel === '' || rel === '.') continueconst target = path.join(task.finalPath, rel)try {await deps.fs.removePathRecursive(target)diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex f15d65ff..88c42995 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -20,6 +20,17 @@ import { reAddTask } from './re-add-task'const RESERVED_GID = '0123456789abcdef'+function buildSingleFileTorrent(name: string): Uint8Array {+ const nameField = `4:name${Buffer.byteLength(name, 'utf8')}:${name}`+ const prefix = Buffer.from(+ `d4:infod6:lengthi1024e${nameField}12:piece lengthi16384e6:pieces20:`,+ 'utf8'+ )+ return new Uint8Array(+ Buffer.concat([prefix, Buffer.alloc(20), Buffer.from('ee')])+ )+}+function makeBtTask(overrides: Partial<DownloadTask> = {}): DownloadTask {return makeDownloadTask({id: 't1',@@ -110,6 +121,60 @@ describe('reAddTask (BT path)', () => {)})+ it.each([+ {+ label: 'completed reseed',+ status: TaskStatus.Completed,+ expectedSaveDir: '/tmp',+ expectedOutput: 'User chosen.iso',+ },+ {+ label: 'failed download retry',+ status: TaskStatus.Error,+ expectedSaveDir: '/tmp/.motrix/0123456789abcdefabcd',+ expectedOutput: 'p',+ },+ ])(+ 'restores indexed paths for $label',+ async ({ status, expectedSaveDir, expectedOutput }) => {+ const workspacePath = '/tmp/.motrix/0123456789abcdefabcd'+ const task = withPrimaryInstance(+ makeBtTask({+ status,+ diskPath:+ status === TaskStatus.Completed+ ? '/tmp/User chosen.iso'+ : workspacePath,+ finalPath: '/tmp/User chosen.iso',+ finalName: 'User chosen.iso',+ })+ )+ task.instances[0].payload = {+ btStorageLayout: {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath,+ payloadEntry: 'p',+ torrentRootName: 'original.iso',+ multiFile: false,+ },+ }+ const deps = makeDeps(task)+ ;(+ deps.torrentMetaStore.read as ReturnType<typeof vi.fn>+ ).mockResolvedValue(buildSingleFileTorrent('original.iso'))++ await reAddTask('t1', deps)++ expect(deps.adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({+ saveDir: expectedSaveDir,+ outputFilePaths: [{ fileIndex: 0, relativePath: expectedOutput }],+ })+ )+ }+ )+it('writes the new gid to the task and sets status Seeding', async () => {const task = makeBtTask()const deps = makeDeps(task)diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 0cb507a2..f1ef5b1d 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -1,3 +1,4 @@+import path from 'node:path'import { newEngineTaskId } from '@core/lib/ids'import { AppError, ErrorCode } from '@shared/errors'import type { EngineTaskOptions } from '@shared/types/engine-task-options'@@ -11,6 +12,12 @@ import {import type { EngineAdapter } from '../../engine/engine-adapter'import type { Logger } from '../../logger'import { applyTerminalTransition } from '../apply-terminal-transition'+import {+ buildFinalOutputFilePaths,+ buildStagingOutputFilePaths,+ getBtStorageLayout,+ parseBtFileLayout,+} from '../bt-storage-layout'import type { TorrentMetaStore } from '../torrent-meta-store'import { commitTaskUpdate, getTaskOrWarn, type TaskActionDeps } from './shared'@@ -83,13 +90,13 @@ async function readBtMetadata(/*** Where aria2 should write this re-add.*- * A Completed reseed points at `finalPath`: finalize already renamed the- * container away from `.motrix`, and that is where the seedable content- * lives (`diskPath` has been normalized to the same value anyway).+ * A legacy Completed reseed points at `finalPath`: finalize already renamed+ * the temporary output and that is where the seedable content lives+ * (`diskPath` has been normalized to the same value anyway).** A retry of a failed or removed download is the opposite case — finalize- * never ran, so the partial content is still in the in-flight `.motrix`- * container that `createTaskHandler` passed as `dir` at add time. Pointing+ * never ran, so the partial content is still in the in-flight location that+ * `createTaskHandler` passed as `dir` at add time. Pointing* `checkIntegrity` at `finalPath` there would scan an empty directory and* restart the download from zero.*/@@ -106,9 +113,26 @@ async function reAddBt(reservedGid: string,metadata: Uint8Array): Promise<string> {+ const storageLayout = getBtStorageLayout(task)+ const parsedLayout = storageLayout ? await parseBtFileLayout(metadata) : null+ const completed = task.status === TaskStatus.Completedreturn deps.adapter.addTorrent({metadata,- saveDir: reAddSaveDir(task),+ saveDir: storageLayout+ ? completed+ ? path.dirname(task.finalPath)+ : storageLayout.workspacePath+ : reAddSaveDir(task),+ outputFilePaths:+ storageLayout && parsedLayout+ ? completed+ ? buildFinalOutputFilePaths(+ parsedLayout,+ task.finalPath,+ storageLayout+ )+ : buildStagingOutputFilePaths(parsedLayout, storageLayout)+ : undefined,gid: reservedGid,selectedFiles: task.bt?.selectedFiles,checkIntegrity: true,diff --git a/src/core/task/bt-storage-layout.test.ts b/src/core/task/bt-storage-layout.test.tsnew file mode 100644index 00000000..19466596--- /dev/null+++ b/src/core/task/bt-storage-layout.test.ts@@ -0,0 +1,103 @@+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import {+ buildFinalOutputFilePaths,+ createBtStoragePlan,+ getBtStorageLayout,+ parseBtFileLayout,+} from './bt-storage-layout'++const FIXTURE_PATH = path.resolve(+ __dirname,+ '../torrent/__fixtures__/test.torrent'+)++function singleFileTorrent(name: string): Uint8Array {+ const nameField = `4:name${Buffer.byteLength(name, 'utf8')}:${name}`+ const prefix = Buffer.from(+ `d4:infod6:lengthi1024e${nameField}12:piece lengthi16384e6:pieces20:`,+ 'utf8'+ )+ return new Uint8Array(+ Buffer.concat([prefix, Buffer.alloc(20), Buffer.from('ee')])+ )+}++describe('BT indexed storage layout', () => {+ it('maps a multi-file torrent below one short payload entry', async () => {+ const parsed = await parseBtFileLayout(+ new Uint8Array(readFileSync(FIXTURE_PATH))+ )+ const plan = createBtStoragePlan('task-1', '/downloads', parsed)++ expect(plan.layout.workspacePath).toMatch(+ /^\/downloads\/\.motrix\/[a-f0-9]{20}$/+ )+ expect(plan.layout).toMatchObject({+ version: 1,+ strategy: 'indexed-staging',+ payloadEntry: 'p',+ torrentRootName: 'test-torrent',+ multiFile: true,+ })+ expect(plan.outputFilePaths).toEqual([+ {+ fileIndex: 0,+ relativePath: path.join('p', 'video', 'movie.mkv'),+ },+ {+ fileIndex: 1,+ relativePath: path.join('p', 'readme.txt'),+ },+ {+ fileIndex: 2,+ relativePath: path.join('p', 'cover.jpg'),+ },+ ])+ })++ it('maps a single-file torrent to the payload entry itself', async () => {+ const parsed = await parseBtFileLayout(singleFileTorrent('large.iso'))+ const plan = createBtStoragePlan('task-2', '/downloads', parsed)++ expect(plan.outputFilePaths).toEqual([{ fileIndex: 0, relativePath: 'p' }])+ expect(+ buildFinalOutputFilePaths(+ parsed,+ '/downloads/Linux image.iso',+ plan.layout+ )+ ).toEqual([{ fileIndex: 0, relativePath: 'Linux image.iso' }])+ })++ it('rejects a torrent root that could escape the workspace', async () => {+ await expect(parseBtFileLayout(singleFileTorrent('..'))).rejects.toThrow(+ 'Invalid torrent name'+ )+ })++ it('does not trust a persisted workspace outside the task save directory', () => {+ expect(+ getBtStorageLayout({+ saveDir: '/downloads',+ diskPath: '/etc',+ finalPath: '/downloads/file',+ instances: [+ {+ payload: {+ btStorageLayout: {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath: '/etc',+ payloadEntry: 'p',+ torrentRootName: 'file',+ multiFile: false,+ },+ },+ },+ ],+ } as unknown as Parameters<typeof getBtStorageLayout>[0])+ ).toBeNull()+ })+})diff --git a/src/core/task/bt-storage-layout.ts b/src/core/task/bt-storage-layout.tsnew file mode 100644index 00000000..723b81d9--- /dev/null+++ b/src/core/task/bt-storage-layout.ts@@ -0,0 +1,274 @@+import { createHash } from 'node:crypto'+import path from 'node:path'+import type { DownloadTask } from '@shared/types/task'+import parseTorrent from 'parse-torrent'++const STORAGE_ROOT = '.motrix'+const PAYLOAD_ENTRY = 'p'+const LAYOUT_KEY = 'btStorageLayout'++export interface BtStorageLayoutV1 {+ version: 1+ strategy: 'indexed-staging'+ workspacePath: string+ payloadEntry: typeof PAYLOAD_ENTRY+ torrentRootName: string+ multiFile: boolean+}++export interface BtOutputFilePath {+ /** Domain-native, zero-based torrent file index. */+ fileIndex: number+ /** Path relative to the engine add operation's saveDir. */+ relativePath: string+}++export interface ParsedBtFileLayout {+ torrentRootName: string+ multiFile: boolean+ isPrivate: boolean+ files: Array<{ fileIndex: number; pathInsideRoot: string | null }>+}++export interface BtStoragePlan {+ layout: BtStorageLayoutV1+ outputFilePaths: BtOutputFilePath[]+}++export class UnsafeTorrentPathError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'UnsafeTorrentPathError'+ }+}++/**+ * Parse and validate the paths declared by untrusted torrent metadata.+ * parse-torrent returns root-inclusive paths; Motrix strips that root before+ * mapping every file below its own short staging entry.+ */+export async function parseBtFileLayout(+ metadata: Uint8Array+): Promise<ParsedBtFileLayout> {+ const parsed = await parseTorrent(metadata)+ const torrentRootName = validatePathComponent(parsed.name, 'torrent name')+ const parsedFiles = parsed.files ?? []+ if (parsedFiles.length === 0) {+ throw new UnsafeTorrentPathError('Torrent contains no files')+ }++ const multiFile = Array.isArray(parsed.info?.files)+ const files = parsedFiles.map((file, fileIndex) => {+ const components = splitAndValidateTorrentPath(file.path)+ if (components[0] !== torrentRootName) {+ throw new UnsafeTorrentPathError(+ `Torrent file ${fileIndex} is outside its declared root directory`+ )+ }+ if (!multiFile) {+ if (components.length !== 1) {+ throw new UnsafeTorrentPathError(+ `Single-file torrent ${fileIndex} has a nested path`+ )+ }+ return { fileIndex, pathInsideRoot: null }+ }+ if (components.length < 2) {+ throw new UnsafeTorrentPathError(+ `Multi-file torrent ${fileIndex} has an empty path`+ )+ }+ return {+ fileIndex,+ pathInsideRoot: path.join(...components.slice(1)),+ }+ })++ return {+ torrentRootName,+ multiFile,+ isPrivate: parsed.private === true,+ files,+ }+}++export function createBtStoragePlan(+ taskId: string,+ saveDir: string,+ parsed: ParsedBtFileLayout+): BtStoragePlan {+ const layout: BtStorageLayoutV1 = {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath: btWorkspacePath(taskId, saveDir),+ payloadEntry: PAYLOAD_ENTRY,+ torrentRootName: parsed.torrentRootName,+ multiFile: parsed.multiFile,+ }+ return {+ layout,+ outputFilePaths: buildStagingOutputFilePaths(parsed, layout),+ }+}++export function btWorkspacePath(taskId: string, saveDir: string): string {+ const workspaceId = createHash('sha256')+ .update(taskId)+ .digest('hex')+ .slice(0, 20)+ return path.join(saveDir, STORAGE_ROOT, workspaceId)+}++export function buildStagingOutputFilePaths(+ parsed: ParsedBtFileLayout,+ layout: BtStorageLayoutV1+): BtOutputFilePath[] {+ assertLayoutMatchesMetadata(layout, parsed)+ return parsed.files.map((file) => ({+ fileIndex: file.fileIndex,+ relativePath:+ file.pathInsideRoot === null+ ? layout.payloadEntry+ : path.join(layout.payloadEntry, file.pathInsideRoot),+ }))+}++export function buildFinalOutputFilePaths(+ parsed: ParsedBtFileLayout,+ finalPath: string,+ expectedLayout?: BtStorageLayoutV1+): BtOutputFilePath[] {+ if (expectedLayout) assertLayoutMatchesMetadata(expectedLayout, parsed)+ const finalEntry = validatePathComponent(+ path.basename(finalPath),+ 'final name'+ )+ return parsed.files.map((file) => ({+ fileIndex: file.fileIndex,+ relativePath:+ file.pathInsideRoot === null+ ? finalEntry+ : path.join(finalEntry, file.pathInsideRoot),+ }))+}++export function btStoragePayload(+ layout: BtStorageLayoutV1+): Record<string, unknown> {+ return { [LAYOUT_KEY]: layout }+}++export function getBtStorageLayout(+ task: Pick<DownloadTask, 'instances' | 'saveDir' | 'diskPath' | 'finalPath'>+): BtStorageLayoutV1 | null {+ for (const instance of task.instances) {+ const candidate = instance.payload[LAYOUT_KEY]+ if (isBtStorageLayout(candidate) && isLayoutOwnedByTask(candidate, task)) {+ return candidate+ }+ }+ return null+}++export function getBtPayloadPath(+ task: Pick<DownloadTask, 'instances' | 'saveDir' | 'diskPath' | 'finalPath'>+): string | null {+ const layout = getBtStorageLayout(task)+ return layout ? path.join(layout.workspacePath, layout.payloadEntry) : null+}++function assertLayoutMatchesMetadata(+ layout: BtStorageLayoutV1,+ parsed: ParsedBtFileLayout+): void {+ if (+ layout.torrentRootName !== parsed.torrentRootName ||+ layout.multiFile !== parsed.multiFile+ ) {+ throw new Error(+ 'Persisted BT storage layout does not match torrent metadata'+ )+ }+}++function splitAndValidateTorrentPath(value: string): string[] {+ if (+ value.length === 0 ||+ value.startsWith('/') ||+ value.startsWith('\\') ||+ /^[A-Za-z]:[\\/]/.test(value)+ ) {+ throw new UnsafeTorrentPathError(+ 'Torrent contains an absolute or empty file path'+ )+ }+ const components = value.replace(/\\/g, '/').split('/')+ return components.map((component) =>+ validatePathComponent(component, 'torrent file path')+ )+}++function validatePathComponent(value: unknown, description: string): string {+ if (+ typeof value !== 'string' ||+ value.length === 0 ||+ value === '.' ||+ value === '..' ||+ value.includes('/') ||+ value.includes('\\') ||+ value.includes('\0')+ ) {+ throw new UnsafeTorrentPathError(`Invalid ${description}`)+ }+ return value+}++function isBtStorageLayout(value: unknown): value is BtStorageLayoutV1 {+ if (!value || typeof value !== 'object') return false+ const candidate = value as Partial<BtStorageLayoutV1>+ return (+ candidate.version === 1 &&+ candidate.strategy === 'indexed-staging' &&+ typeof candidate.workspacePath === 'string' &&+ path.isAbsolute(candidate.workspacePath) &&+ candidate.payloadEntry === PAYLOAD_ENTRY &&+ typeof candidate.torrentRootName === 'string' &&+ isSafePathComponent(candidate.torrentRootName) &&+ typeof candidate.multiFile === 'boolean'+ )+}++function isLayoutOwnedByTask(+ layout: BtStorageLayoutV1,+ task: Pick<DownloadTask, 'saveDir' | 'diskPath' | 'finalPath'>+): boolean {+ if (!task.saveDir) return false+ const workspacePath = path.resolve(layout.workspacePath)+ const storageRoot = path.resolve(task.saveDir, STORAGE_ROOT)+ if (+ path.dirname(workspacePath) !== storageRoot ||+ !/^[a-f0-9]{20}$/.test(path.basename(workspacePath))+ ) {+ return false+ }++ // While the task is in-flight, the canonical diskPath must identify the+ // same workspace. After rename diskPath equals finalPath, so the retained+ // layout remains available for reseed/retry mapping without authorizing+ // arbitrary filesystem operations from persisted JSON.+ return (+ task.diskPath === task.finalPath ||+ path.resolve(task.diskPath) === workspacePath+ )+}++function isSafePathComponent(value: string): boolean {+ return (+ value.length > 0 &&+ value !== '.' &&+ value !== '..' &&+ !value.includes('/') &&+ !value.includes('\\') &&+ !value.includes('\0')+ )+}diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 0d95c6aa..8c16018f 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -512,7 +512,20 @@ describe('handleCreateTask', () => {)const task = lastAddedTask(deps)expect(task.finalName).toBe('ubuntu-25.10-desktop-amd64.iso')- expect(task.diskPath).toBe('/d/ubuntu-25.10-desktop-amd64.iso.motrix')+ expect(task.diskPath).toMatch(/^\/d\/\.motrix\/[a-f0-9]{20}$/)+ expect(task.instances[0].payload.btStorageLayout).toMatchObject({+ version: 1,+ strategy: 'indexed-staging',+ workspacePath: task.diskPath,+ payloadEntry: 'p',+ torrentRootName: 'ubuntu-25.10-desktop-amd64.iso',+ multiFile: false,+ })+ const [, , options] = deps.addTorrent.mock.calls[0]+ expect(options).toMatchObject({+ dir: task.diskPath,+ 'index-out': ['1=p'],+ })})it('falls back to "torrent" literal when bytes are unparseable', async () => {@@ -531,6 +544,27 @@ describe('handleCreateTask', () => {expect(task.finalName).toBe('torrent')})+ it('rejects a parseable torrent with an unsafe root path', async () => {+ const deps = makeDeps({ addTorrentGid: 'gid-bt' })+ const bytes = buildMinimalTorrentBytes('..', false)++ await expect(+ handleCreateTask(+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: Buffer.from(bytes).toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/d',+ },+ deps+ )+ ).rejects.toMatchObject({ code: ErrorCode.TorrentParseFailed })+ expect(deps.addTorrent).not.toHaveBeenCalled()+ })+it('dispatches magnet via rpcClient.addUri', async () => {const deps = makeDeps({ addUriGid: 'gid-magnet' })const result = await handleCreateTask(@@ -1620,8 +1654,9 @@ describe('characterization: aria2 RPC args', () => {expect(options['select-file']).toBe('1,3')// Private torrent: bt-tracker forced to empty stringexpect(options['bt-tracker']).toBe('')- // BT dir = diskPath = saveDir/displayName.motrix- expect(options.dir).toBe('/dl/private-torrent.motrix')+ // Valid torrent metadata uses a short, task-stable staging workspace.+ expect(options.dir).toMatch(/^\/dl\/\.motrix\/[a-f0-9]{20}$/)+ expect(options['index-out']).toEqual(['1=p'])// No `out` for BT tasksexpect(options.out).toBeUndefined()})diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 12c45d18..e518c7ea 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -39,7 +39,14 @@ import {import { isTorrentLikeType } from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type Database from 'better-sqlite3'-import parseTorrent from 'parse-torrent'+import {+ type BtStoragePlan,+ btStoragePayload,+ createBtStoragePlan,+ type ParsedBtFileLayout,+ parseBtFileLayout,+ UnsafeTorrentPathError,+} from './bt-storage-layout'import type { FinalNamePicker } from './final-name-picker'import { toTempPath } from './paths'import type { TaskManager } from './task-manager'@@ -139,7 +146,7 @@ export interface CreateTaskOptions {* 1. Resolve `finalName` via FinalNamePicker (collision-safe).* 2. Persist torrent bytes (BT torrent-base64 only) via TorrentMetaStore.* 3. Build engine-agnostic create params with path overrides so on-disk- * artifacts land at `diskPath` (the `.motrix` in-flight location).+ * artifacts land in the task's in-flight location.* 4. Call the EngineAdapter to obtain the engine gid.* 5. Register the fully-populated DownloadTask with TaskManager so* subsequent polling updates merge onto an already-present record@@ -174,6 +181,7 @@ export async function handleCreateTask(const effectiveSaveDir = deps.prepareSaveDir? await deps.prepareSaveDir(requestedSaveDir): requestedSaveDir+ const taskId = newTaskId()log.info({@@ -191,19 +199,25 @@ export async function handleCreateTask(// 'torrent' when neither displayName nor magnet dn= is provided.let torrentBytes: Uint8Array | null = nulllet torrentInfoName: string | null = null+ let parsedBtLayout: ParsedBtFileLayout | null = nulllet isPrivateFromTorrent = falseif (req.type === 'bt' && req.payload.kind === 'torrent-base64') {torrentBytes = req.torrentBytes ?? decodeBase64ToBytes(req.payload.base64)try {- const meta = await parseTorrent(torrentBytes)- if (typeof meta.name === 'string' && meta.name.trim()) {- torrentInfoName = meta.name.trim()- }- isPrivateFromTorrent = meta.private === true+ parsedBtLayout = await parseBtFileLayout(torrentBytes)+ torrentInfoName = parsedBtLayout.torrentRootName+ isPrivateFromTorrent = parsedBtLayout.isPrivate} catch (err) {+ if (err instanceof UnsafeTorrentPathError) {+ throw new AppError(+ ErrorCode.TorrentParseFailed,+ 'Torrent contains an unsafe file path',+ err+ )+ }log.warn({ err },- 'failed to parse torrent for name extraction; falling back'+ 'failed to parse torrent for indexed staging; falling back to legacy layout')}}@@ -217,9 +231,10 @@ export async function handleCreateTask(const taskType = deriveTaskType(req)const finalPath = path.join(effectiveSaveDir, finalName)- const diskPath = toTempPath(finalPath)-- const taskId = newTaskId()+ const btStoragePlan: BtStoragePlan | null = parsedBtLayout+ ? createBtStoragePlan(taskId, effectiveSaveDir, parsedBtLayout)+ : null+ const diskPath = btStoragePlan?.layout.workspacePath ?? toTempPath(finalPath)// Anchor "now" early so the hook DTO's requestedAt and the persisted// task row share a clock — they are written in the same SQLite// transaction when plugin metadata is staged.@@ -243,10 +258,12 @@ export async function handleCreateTask(}// 2.5. Pre-create the on-disk slot before handing off to aria2.- // Both task families keep a `.motrix` suffix during download, but- // `diskPath` means different things:- // - BT/Magnet: `diskPath` IS a container directory aria2 populates- // (`dir = diskPath`, `out` dropped). Pre-creating it also+ // `diskPath` means different things by task family:+ // - Parsed .torrent: `diskPath` is a short task workspace and index-out+ // maps payload files below `<diskPath>/p`.+ // - Unresolved magnet / legacy BT: `diskPath` is the traditional+ // `<finalName>.motrix` container.+ // For both BT layouts, pre-creating the engine `dir` also// guarantees `aria2.addTorrent`'s metadata write// (`<diskPath>/<sha1>.torrent`) succeeds at add time. Without// this dir, the save fails silently; the resulting task gets a@@ -272,10 +289,10 @@ export async function handleCreateTask(}// 3. Build engine-agnostic create params per task family and dispatch- // through the EngineAdapter. Path options always point at `diskPath`- // (the `.motrix` in-flight location): for HTTP that means- // dir=saveDir + filename=<name>.motrix; for BT/magnet dir=diskPath- // with no `out`. The adapter is responsible for the aria2 wire shape.+ // through the EngineAdapter. For HTTP, dir=saveDir and out uses the+ // incomplete suffix. For BT/magnet, dir=diskPath and `out` is absent;+ // parsed torrents additionally carry per-file output mappings. The adapter+ // is responsible for the aria2 wire shape.let pluginStaged: { commit: (cb: () => void) => void } | undefinedlet dispatchEngine: (reservedGid: string) => Promise<string>// Shared by the HTTP and magnet branches — both dispatch through@@ -480,6 +497,7 @@ export async function handleCreateTask(// CREATE-PATH +1: req indices are 0-based; aria2 select-file is// 1-based, and addTorrent serializes selectedFiles with a raw join.selectedFiles: req.selectedFiles.map((i) => i + 1),+ outputFilePaths: btStoragePlan?.outputFilePaths,dlLimit: req.dlLimit,ulLimit: req.ulLimit,seedRatio: req.seedRatio,@@ -564,7 +582,7 @@ export async function handleCreateTask(transitionPhase: TransitionPhase.Idle,uris: deriveUris(req),uriHash: null,- payload: {},+ payload: btStoragePlan ? btStoragePayload(btStoragePlan.layout) : {},createdAt: now,updatedAt: now,}diff --git a/src/core/task/task-recovery-service.test.ts b/src/core/task/task-recovery-service.test.tsindex 20d62aff..03dfbce1 100644--- a/src/core/task/task-recovery-service.test.ts+++ b/src/core/task/task-recovery-service.test.ts@@ -1,6 +1,7 @@import { ErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'import {+ TaskInstancePhase,TaskKind,TaskStatus,TaskType,@@ -218,6 +219,62 @@ describe('TaskRecoveryServiceImpl.recoverOnStartup', () => {expect(report.errors).toHaveLength(0)})+ it('probes the indexed payload instead of the sidecar workspace on recovery', async () => {+ const workspacePath = '/d/.motrix/0123456789abcdefabcd'+ const task = makeTask({+ id: 'bt-indexed',+ saveDir: '/d',+ diskPath: workspacePath,+ finalPath: '/d/final-name',+ instances: [+ {+ instanceId: 'primary:bt-indexed',+ motrixId: 'bt-indexed',+ gid: 'gid-indexed',+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Finalizing,+ progress: 1,+ totalBytes: 10,+ downloadedBytes: 10,+ uploadedBytes: 0,+ diskPath: workspacePath,+ transitionPhase: TransitionPhase.Renaming,+ uris: [],+ uriHash: null,+ payload: {+ btStorageLayout: {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath,+ payloadEntry: 'p',+ torrentRootName: 'original-name',+ multiFile: true,+ },+ },+ createdAt: 1,+ updatedAt: 2,+ },+ ],+ })+ const fs = makeFs(new Set([`${workspacePath}/p`]))+ const finalizeTask = vi.fn(async () => {})+ const deps = makeDeps({+ taskManager: {+ getAll: vi.fn(() => [task]),+ persist: vi.fn(async () => {}),+ },+ fs,+ finalizeTask,+ })++ const report = await new TaskRecoveryServiceImpl(deps).recoverOnStartup()++ expect(fs.pathExists).toHaveBeenCalledWith(`${workspacePath}/p`)+ expect(fs.pathExists).not.toHaveBeenCalledWith(workspacePath)+ expect(finalizeTask).toHaveBeenCalledWith('bt-indexed')+ expect(report.recovered[0]?.action).toBe(RecoveryAction.ResumeFromRename)+ })+it('treats an existing same diskPath/finalPath as final_only and records recovered before reseed', async () => {const task = makeTask({id: 'same-path',diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.tsindex 5b0743e8..3ccd9f2f 100644--- a/src/core/task/task-recovery-service.ts+++ b/src/core/task/task-recovery-service.ts@@ -17,6 +17,7 @@ import {type TaskTransitionRecordInput,} from './actions/shared'import { applyTerminalTransition } from './apply-terminal-transition'+import { getBtPayloadPath } from './bt-storage-layout'import { applyDiagnosisUpgrade } from './diagnosis-upgrade'import { fireAfterComplete, fireOnError } from './hook-dispatch'import type { OccurrenceDispatcher } from './occurrences/occurrence-dispatcher'@@ -325,13 +326,14 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {}private async inspectFs(task: DownloadTask): Promise<FsState> {- if (task.diskPath === task.finalPath) {+ const temporaryPath = getBtPayloadPath(task) ?? task.diskPath+ if (temporaryPath === task.finalPath) {return (await this.deps.fs.pathExists(task.finalPath))? 'final_only': 'neither'}const [temp, final] = await Promise.all([- this.deps.fs.pathExists(task.diskPath),+ this.deps.fs.pathExists(temporaryPath),this.deps.fs.pathExists(task.finalPath),])if (temp && final) return 'both'diff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.tsindex fd23ac5e..ba03d4e3 100644--- a/src/core/torrent/magnet-tracker.test.ts+++ b/src/core/torrent/magnet-tracker.test.ts@@ -11,6 +11,7 @@ import type {TaskWithInstances,TaskWithInstancesAndFiles,} from '@core/session/motrix-database'+import { btWorkspacePath } from '@core/task/bt-storage-layout'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'import type { TaskManager } from '@core/task/task-manager'import { DownloadErrorCode, ErrorCode } from '@shared/errors'@@ -2101,6 +2102,132 @@ describe('MagnetTracker', () => {)})+ it('retries timed-out metadata under the same task with a fresh GID and double timeout', async () => {+ const dir = await makeTempDir()+ settings = createMockSettingsManager({+ magnetFileSelection: true,+ magnetResolveTimeout: 1,+ })+ const tracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser+ )++ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:retry-timeout',+ dir+ )+ const firstOptions = rpc.addUri.mock.calls[0][1]+ await vi.advanceTimersByTimeAsync(1_000)+ await vi.waitFor(() => {+ expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.Error)+ expect(+ tracker.observe({ gid: firstOptions?.gid, status: 'removed' } as never)+ ).toBe(false)+ })++ await tracker.retryMetadata(taskId)++ const secondOptions = rpc.addUri.mock.calls[1][1]+ expect(rpc.addUri).toHaveBeenCalledTimes(2)+ expect(secondOptions?.gid).not.toBe(firstOptions?.gid)+ expect(secondOptions?.dir).not.toBe(firstOptions?.dir)+ expect(db.getTask(taskId)).toMatchObject({+ task: {+ motrixId: taskId,+ aggStatus: TaskStatus.FetchingMetadata,+ errorCode: null,+ errorMessage: null,+ },+ instances: [+ {+ gid: secondOptions?.gid,+ payload: { metadataTimeoutMultiplier: 2 },+ },+ ],+ })++ await vi.advanceTimersByTimeAsync(1_000)+ expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.FetchingMetadata)++ await vi.advanceTimersByTimeAsync(1_000)+ expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.Error)+ })++ it('restores the doubled retry timeout from the persisted metadata payload', async () => {+ const dir = await makeTempDir()+ settings = createMockSettingsManager({+ magnetFileSelection: true,+ magnetResolveTimeout: 1,+ })+ const tracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser+ )+ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:retry-restart',+ dir+ )+ await vi.advanceTimersByTimeAsync(1_000)+ await vi.waitFor(() => {+ expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.Error)+ })+ await tracker.retryMetadata(taskId)+ await tracker.stopAndDrain()++ const restarted = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser+ )+ restarted.primeFromDatabase()++ await vi.advanceTimersByTimeAsync(1_000)+ expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.FetchingMetadata)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(db.getTask(taskId)?.task.aggStatus).toBe(TaskStatus.Error)+ })++ it('does not start a metadata retry until old GID cleanup is confirmed', async () => {+ const dir = await makeTempDir()+ settings = createMockSettingsManager({+ magnetFileSelection: true,+ magnetResolveTimeout: 1,+ })+ rpc.forceRemove.mockRejectedValue(new Error('ECONNREFUSED'))+ rpc.removeDownloadResult.mockRejectedValue(new Error('ECONNREFUSED'))+ const tracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser+ )++ const taskId = await tracker.submit(+ 'magnet:?xt=urn:btih:retry-cleanup-pending',+ dir+ )+ await vi.advanceTimersByTimeAsync(1_000)++ await expect(tracker.retryMetadata(taskId)).rejects.toMatchObject({+ code: ErrorCode.MagnetCleanupPending,+ })+ expect(rpc.addUri).toHaveBeenCalledTimes(1)+ })+it('error event path also forceRemoves by aria2 GID', async () => {const dir = await makeTempDir()rpc.addUri.mockResolvedValue('g-meta-err')@@ -2858,6 +2985,44 @@ describe('MagnetTracker', () => {await tracker.stopAndDrain()})+ it('cleans only the indexed workspace derived from the failed swap task id', async () => {+ const root = await makeTempDir()+ const saveDir = path.join(root, 'downloads')+ const taskId = 'm-indexed-cleanup'+ const workspacePath = btWorkspacePath(taskId, saveDir)+ await mkdir(workspacePath, { recursive: true })+ await writeFile(path.join(workspacePath, 'partial.bin'), 'partial')++ const tracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser+ )+ tracker.registerFailedSwapCleanup({+ taskId,+ instanceId: `meta:${taskId}`,+ gid: 'g-indexed-cleanup',+ magnetUri: 'magnet:?xt=urn:btih:indexed-cleanup',+ saveDir,+ metadataDir: workspacePath,+ torrentMetaPath: null,+ artifactPaths: [workspacePath],+ deleteParentOnSuccess: false,+ })++ await vi.advanceTimersByTimeAsync(5_000)+ vi.useRealTimers()+ await vi.waitFor(async () => {+ await expect(access(workspacePath)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ expect(tracker.hasPendingSwapCleanup(taskId)).toBe(false)+ })+ })+it('primeFromDatabase shields a normal metadata Error without a new timeout', () => {db.saveTaskWithInstances({task: {diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex 4d44e80c..57a0120f 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -25,6 +25,7 @@ import {applyTerminalTransition,terminalFieldsFromRow,} from '@core/task/apply-terminal-transition'+import { btWorkspacePath } from '@core/task/bt-storage-layout'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'import type { TaskManager } from '@core/task/task-manager'import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'@@ -56,6 +57,10 @@ const HEX_INFO_HASH_RE = /^[a-fA-F0-9]{40}$/const BASE32_INFO_HASH_RE = /^[A-Z2-7]{32}$/iconst BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'const UNKNOWN_INFO_HASH = '0'.repeat(40)+const METADATA_TIMEOUT_MULTIPLIER_PAYLOAD_KEY =+ 'metadataTimeoutMultiplier' as const+const INITIAL_METADATA_TIMEOUT_MULTIPLIER = 1+const RETRY_METADATA_TIMEOUT_MULTIPLIER = 2/** Outcome of magnet metadata cleanup attempt. `removed` means aria2* has confirmed the GID is no longer alive — safe for callers to@@ -144,6 +149,7 @@ interface MetadataInstanceCache {failedSwapCleanup: booleanhiddenTombstone: booleanrestoreGraph?: TaskWithInstancesAndFiles+ timeoutMultiplier: numbertimer: ReturnType<typeof setTimeout>cleanupAttempts: numbercleanupFirstFailureAt?: number@@ -276,6 +282,7 @@ export class MagnetTracker {failedSwapCleanup: isHiddenTombstone && cleanupArtifactPaths.length > 0,hiddenTombstone: isHiddenTombstone,restoreGraph: restoreGraph ?? undefined,+ timeoutMultiplier: metadataTimeoutMultiplier(metaInst.payload),timer: setTimeout(() => {}, 0),cleanupAttempts:isQuarantined && !isHiddenTombstone ? MAX_CLEANUP_ATTEMPTS : 0,@@ -293,7 +300,7 @@ export class MagnetTracker {RETRY_DELAY_MS)} else if (!isTerminalError) {- entry.timer = this.armTimeout(metaInst.gid)+ entry.timer = this.armTimeout(metaInst.gid, entry.timeoutMultiplier)}}}@@ -364,6 +371,7 @@ export class MagnetTracker {failedSwapCleanup: true,hiddenTombstone: scheduleCleanup,restoreGraph: input.restoreGraph,+ timeoutMultiplier: INITIAL_METADATA_TIMEOUT_MULTIPLIER,timer: setTimeout(() => {}, 0),cleanupAttempts: 0,quarantined: scheduleCleanup,@@ -551,6 +559,7 @@ export class MagnetTracker {cleanupArtifactPaths: [],failedSwapCleanup: false,hiddenTombstone: false,+ timeoutMultiplier: INITIAL_METADATA_TIMEOUT_MULTIPLIER,timer: this.armTimeout(reservedGid),cleanupAttempts: 0,quarantined: false,@@ -633,6 +642,216 @@ export class MagnetTracker {}}+ /**+ * Retry a failed pre-sidecar magnet metadata resolution in place. The+ * durable parent identity and magnet URI are retained, while the engine GID+ * and temporary directory are always replaced. Manual retries receive+ * twice the configured metadata timeout; later retries stay at 2x.+ */+ async retryMetadata(taskId: string): Promise<void> {+ if (this.stopped) {+ throw new Error('MagnetTracker is stopped')+ }+ await this.runTaskMutation(taskId, () =>+ this.retryMetadataUnderMutation(taskId)+ )+ }++ private async retryMetadataUnderMutation(taskId: string): Promise<void> {+ const pair = this.db.getTask(taskId)+ const metaInst = pair?.instances.find(+ (instance) =>+ instance.phase === TaskInstancePhase.MagnetMetadataResolution+ )+ const magnetUri = metaInst?.uris.find((uri) =>+ uri.toLowerCase().startsWith('magnet:?')+ )+ if (+ !pair ||+ pair.task.taskType !== TaskType.Magnet ||+ pair.task.aggStatus !== TaskStatus.Error ||+ pair.task.torrentMetaPath !== null ||+ pair.instances.length !== 1 ||+ !metaInst ||+ !magnetUri ||+ isMagnetCleanupTombstoneHidden(metaInst)+ ) {+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `task ${taskId} is not a retryable magnet metadata task`+ )+ }++ // A timeout publishes Error before it attempts engine cleanup, so a fast+ // click can arrive while the old GID is still shielded. Serialize behind+ // that cleanup and require authoritative absence before creating a new+ // sibling GID.+ const previousEntry = this.findCacheEntryByTaskId(taskId)+ if (previousEntry) {+ previousEntry.cleanupAttempts = 0+ previousEntry.cleanupFirstFailureAt = undefined+ previousEntry.quarantined = false+ await this.cleanupCacheEntryUnderMutation(previousEntry)+ if (this.cache.get(previousEntry.gid) === previousEntry) {+ throw new AppError(+ ErrorCode.MagnetCleanupPending,+ `previous magnet metadata attempt for task ${taskId} is still being cleaned up`+ )+ }+ }++ const metadataDir = await mkdtemp(join(tmpdir(), 'motrix-magnet-metadata-'))+ let reservedGid: string+ try {+ reservedGid = this.reserveNewEngineGid()+ } catch (err) {+ await this.cleanupMetadataDir(metadataDir)+ throw err+ }++ const now = Date.now()+ const terminal = applyTerminalTransition(+ terminalFieldsFromRow(pair.task),+ TaskStatus.FetchingMetadata,+ {},+ now+ )+ const updatedTask: TaskRow = {+ ...pair.task,+ aggStatus: terminal.status,+ finishedAt: terminal.finishedAt,+ errorMessage: terminal.errorMessage,+ errorCode: terminal.errorCode,+ errorDetailKey: terminal.errorDetailKey,+ errorDetailParams: terminal.errorDetailParams,+ diagnosisRevision: terminal.diagnosisRevision,+ updatedAt: now,+ }+ const updatedInstance: TaskInstanceRow = {+ ...metaInst,+ gid: reservedGid,+ status: TaskStatus.FetchingMetadata,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: metadataDir,+ transitionPhase: TransitionPhase.Idle,+ payload: metadataFetchPayload(+ metadataDir,+ RETRY_METADATA_TIMEOUT_MULTIPLIER+ ),+ updatedAt: now,+ }+ const previousDownloadTask = taskRowToDownloadTask(+ pair.task,+ pair.instances+ )+ let activeInstance = updatedInstance+ let retryTask = taskRowToDownloadTask(updatedTask, [activeInstance])+ let entry: MetadataInstanceCache | null = null+ let persisted = false+ let reservedOwnerInstalled = false+ let engineDispatchStarted = false++ try {+ await this.runExclusivePersistence(async () => {+ this.db.saveTaskWithInstances({+ task: updatedTask,+ instances: [activeInstance],+ })+ await this.recordExactTransition(previousDownloadTask, retryTask, now)+ })+ persisted = true++ this.taskManager.setReservedEngineTaskOwner(+ taskId,+ retryTask,+ reservedGid+ )+ reservedOwnerInstalled = true+ entry = {+ gid: reservedGid,+ taskId,+ instanceId: activeInstance.instanceId,+ magnetUri,+ saveDir: pair.task.finalPath,+ metadataDir,+ torrentMetaPath: null,+ torrentMetaDir: this.lifecycle.torrentMetaDir ?? null,+ cleanupArtifactPaths: [],+ failedSwapCleanup: false,+ hiddenTombstone: false,+ timeoutMultiplier: RETRY_METADATA_TIMEOUT_MULTIPLIER,+ timer: this.armTimeout(reservedGid, RETRY_METADATA_TIMEOUT_MULTIPLIER),+ cleanupAttempts: 0,+ quarantined: false,+ }+ this.cache.set(reservedGid, entry)++ engineDispatchStarted = true+ const returnedGid = await this.rpcClient.addUri([magnetUri], {+ 'bt-metadata-only': 'true',+ dir: metadataDir,+ 'follow-torrent': 'false',+ gid: reservedGid,+ })+ if (returnedGid !== entry.gid) {+ activeInstance = await this.rebindSubmittedMetadataGid(+ updatedTask,+ activeInstance,+ entry,+ returnedGid+ )+ retryTask = taskRowToDownloadTask(updatedTask, [activeInstance])+ }++ this.taskManager.set(taskId, retryTask)+ this.lifecycle.publishTaskUpdate()+ log.info(+ {+ gid: activeInstance.gid,+ taskId,+ timeoutMultiplier: RETRY_METADATA_TIMEOUT_MULTIPLIER,+ },+ 'magnet metadata retry started'+ )+ } catch (err) {+ if (engineDispatchStarted && entry) {+ const marked = await this.markMetadataFailure(+ entry,+ 'Magnet metadata retry submission failed',+ DownloadErrorCode.BtMetadataFailed+ )+ if (marked) await this.cleanupCacheEntryUnderMutation(entry)+ } else {+ const cached = this.cache.get(reservedGid)+ if (cached?.taskId === taskId) {+ clearTimeout(cached.timer)+ this.cache.delete(reservedGid)+ }+ const ownerRolledBack =+ reservedOwnerInstalled &&+ this.taskManager.rollbackReservedEngineTaskOwner(+ taskId,+ reservedGid,+ previousDownloadTask+ )+ if (!ownerRolledBack) {+ this.taskManager.releaseEngineTaskIdReservation(reservedGid)+ }+ if (persisted) {+ await this.runExclusivePersistence(() => {+ this.db.saveTaskWithInstances(pair)+ this.taskManager.set(taskId, previousDownloadTask)+ })+ }+ await this.cleanupMetadataDir(metadataDir)+ }+ throw err+ }+ }+observe(raw: Aria2RawStatus): boolean {// Source of truth for "this gid is metadata-only, polling should// skip it" is the cache Map. Returning true here makes the@@ -821,11 +1040,14 @@ export class MagnetTracker {return this.stopPromise}- private armTimeout(gid: string): ReturnType<typeof setTimeout> {+ private armTimeout(+ gid: string,+ timeoutMultiplier = INITIAL_METADATA_TIMEOUT_MULTIPLIER+ ): ReturnType<typeof setTimeout> {const timeoutSec = this.settingsManager.getEngine().magnetResolveTimeoutreturn setTimeout(() => void this.trackCallback(() => this.handleTimeout(gid)),- timeoutSec * 1000+ timeoutSec * timeoutMultiplier * 1000)}@@ -921,7 +1143,7 @@ export class MagnetTracker {clearTimeout(entry.timer)this.cache.delete(reservedGid)entry.gid = returnedGid- entry.timer = this.armTimeout(returnedGid)+ entry.timer = this.armTimeout(returnedGid, entry.timeoutMultiplier)this.cache.set(returnedGid, entry)const reboundInstance: TaskInstanceRow = {@@ -1808,6 +2030,29 @@ export class MagnetTracker {// ─── helpers ─────────────────────────────────────────────────+function metadataFetchPayload(+ metadataDir: string,+ timeoutMultiplier: number+): Record<string, unknown> {+ return withMagnetCleanupTombstoneHidden(+ withMagnetCleanupQuarantined(+ {+ metadataDir,+ [METADATA_TIMEOUT_MULTIPLIER_PAYLOAD_KEY]: timeoutMultiplier,+ },+ false+ ),+ false+ )+}++function metadataTimeoutMultiplier(payload: Record<string, unknown>): number {+ return payload[METADATA_TIMEOUT_MULTIPLIER_PAYLOAD_KEY] ===+ RETRY_METADATA_TIMEOUT_MULTIPLIER+ ? RETRY_METADATA_TIMEOUT_MULTIPLIER+ : INITIAL_METADATA_TIMEOUT_MULTIPLIER+}+function truncateName(uri: string): string {if (uri.length <= 64) return urireturn `${uri.slice(0, 60)}…`@@ -1856,6 +2101,17 @@ function isSafeSwapCleanupArtifactPath(return true}+ const indexedWorkspace = saveDir+ ? resolve(btWorkspacePath(entry.taskId, saveDir))+ : ''+ if (+ normalized === metadataDir &&+ normalized === indexedWorkspace &&+ dirname(normalized) === resolve(saveDir, '.motrix')+ ) {+ return true+ }+const torrentMetaPath = entry.torrentMetaPath? resolve(entry.torrentMetaPath): ''diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.tsindex 6e0b6ed9..456810ff 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts@@ -302,6 +302,17 @@ function createMockEventBus(): MockEventBus {return { emit: vi.fn<(event: string, payload: unknown) => void>() }}+function buildSingleFileTorrent(name: string): Uint8Array {+ const nameField = `4:name${Buffer.byteLength(name, 'utf8')}:${name}`+ const prefix = Buffer.from(+ `d4:infod6:lengthi1024e${nameField}12:piece lengthi16384e6:pieces20:`,+ 'utf8'+ )+ return new Uint8Array(+ Buffer.concat([prefix, Buffer.alloc(20), Buffer.from('ee')])+ )+}+// ─── Tests ──────────────────────────────────────────────────────describe('swapMagnetMetadataForBt', () => {@@ -1037,6 +1048,47 @@ describe('swapMagnetMetadataForBt', () => {expect(tmTask.type).toBe(TaskType.Bt)})+ it('uses indexed short staging after magnet metadata resolves', async () => {+ const torrent = buildSingleFileTorrent('very-long-original-name.iso')++ await swapMagnetMetadataForBt(+ {+ taskId: 'm-mag',+ base64: Buffer.from(torrent).toString('base64'),+ selectedFiles: [0],+ saveDir: '/Downloads',+ name: 'User friendly name.iso',+ },+ {+ db,+ taskManager,+ adapter: adapter as never,+ magnetTracker: magnetTracker as never as MagnetTracker,+ publishTaskUpdate: () =>+ eventBus.emit(Events.TaskUpdated, taskManager.getAll()),+ publishTaskUpdateNow: () =>+ eventBus.emit(Events.TaskUpdated, taskManager.getAll()),+ finalNamePicker: finalNamePicker as never,+ torrentMetaStore: torrentMetaStore as never,+ runTaskMutation: runImmediately,+ runExclusivePersistence: persistImmediately,+ }+ )++ const params = adapter.addTorrent.mock.calls[0][0]+ expect(params.saveDir).toMatch(/^\/Downloads\/\.motrix\/[a-f0-9]{20}$/)+ expect(params.outputFilePaths).toEqual([+ { fileIndex: 0, relativePath: 'p' },+ ])+ expect(+ db.getTask('m-mag')?.instances[0].payload.btStorageLayout+ ).toMatchObject({+ workspacePath: params.saveDir,+ payloadEntry: 'p',+ torrentRootName: 'very-long-original-name.iso',+ })+ })+it('passes 1-based file indices to adapter.addTorrent (aria2 --select-file)', async () => {// The dialog supplies 0-based indices from TorrentParser, but aria2's// --select-file uses 1-based indices. The first file is index 0 in thediff --git a/src/core/torrent/swap-magnet-metadata-for-bt.ts b/src/core/torrent/swap-magnet-metadata-for-bt.tsindex dc6912ec..1d7d6878 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.ts@@ -10,6 +10,14 @@ import type {TaskWithInstancesAndFiles,} from '@core/session/motrix-database'import type { TaskTransitionRecordInput } from '@core/task/actions/shared'+import {+ type BtStoragePlan,+ btStoragePayload,+ createBtStoragePlan,+ type ParsedBtFileLayout,+ parseBtFileLayout,+ UnsafeTorrentPathError,+} from '@core/task/bt-storage-layout'import type { FinalNamePicker } from '@core/task/final-name-picker'import { toTempPath } from '@core/task/paths'import type { TaskManager } from '@core/task/task-manager'@@ -54,9 +62,7 @@ export interface SwapMagnetMetadataDeps {taskManager: TaskManageradapter: EngineAdaptermagnetTracker: MagnetTracker- /** Collision-safe on-disk name picker — same instance createTaskHandler- * uses, so a resolved magnet lands in the identical `<name>.motrix`- * container scheme as every other task. */+ /** Collision-safe final on-disk name picker shared with createTaskHandler. */finalNamePicker: FinalNamePicker/** Persists the resolved .torrent bytes so finalize's reseed and* reAddTask can recover them (they read `torrentMetaPath`). */@@ -171,15 +177,33 @@ async function swapMagnetMetadataForBtUnderMutation(// cancelling the metadata fetch. If picker/mkdir/persist rejects, the// original cache + metadataDir remain usable and the selection can retry.//- // Mirror createTaskHandler's BT branch: collision-safe final name, an- // in-flight `<name>.motrix` container, and durable `.torrent` bytes.+ // Mirror createTaskHandler's BT branch: collision-safe final name, a short+ // indexed workspace when metadata is valid, and durable `.torrent` bytes.const desiredName = (name ?? existing.task.name).replace(METADATA_NAME_PREFIX,'')const finalName = await finalNamePicker.pick(saveDir, desiredName)const finalPath = path.join(saveDir, finalName)- const diskPath = toTempPath(finalPath)+ let btStoragePlan: BtStoragePlan | null = null+ let parsedBtLayout: ParsedBtFileLayout | null = null+ try {+ parsedBtLayout = await parseBtFileLayout(torrentBytes)+ btStoragePlan = createBtStoragePlan(taskId, saveDir, parsedBtLayout)+ } catch (err) {+ if (err instanceof UnsafeTorrentPathError) {+ throw new AppError(+ ErrorCode.TorrentParseFailed,+ 'Torrent contains an unsafe file path',+ err+ )+ }+ log.warn(+ { err, taskId },+ 'failed to parse resolved magnet metadata for indexed staging; using legacy layout'+ )+ }+ const diskPath = btStoragePlan?.layout.workspacePath ?? toTempPath(finalPath)let torrentMetaPath: stringtry {await mkdir(diskPath, { recursive: true })@@ -297,8 +321,8 @@ async function swapMagnetMetadataForBtUnderMutation(const now = Date.now()// The confirmation dialog lets the user change saveDir after metadata// resolution. Persist that validated root on the hidden reservation so a- // restarted cleanup can authorize the new `<name>.motrix` artifact without- // trusting a path embedded only in the instance payload. Cleanup restores+ // restarted cleanup can authorize the new task-derived artifact without+ // trusting an arbitrary path embedded only in instance payload. Cleanup restores// previousGraph (including the original finalPath) when it completes.const reservationTask: TaskRow = {...previousGraph.task,@@ -325,6 +349,7 @@ async function swapMagnetMetadataForBtUnderMutation(withMagnetCleanupQuarantined({...previousMetadataInstance.payload,+ ...(btStoragePlan ? btStoragePayload(btStoragePlan.layout) : {}),metadataDir: diskPath,},true@@ -429,7 +454,7 @@ async function swapMagnetMetadataForBtUnderMutation(transitionPhase: TransitionPhase.Idle,uris: [],uriHash: null,- payload: {},+ payload: btStoragePlan ? btStoragePayload(btStoragePlan.layout) : {},createdAt: now,updatedAt: now,}@@ -441,6 +466,7 @@ async function swapMagnetMetadataForBtUnderMutation(finalPath,finalName,torrentMetaPath,+ isPrivate: parsedBtLayout?.isPrivate ?? existing.task.isPrivate,aggStatus: TaskStatus.Downloading,finishedAt: null,errorMessage: null,@@ -469,7 +495,9 @@ async function swapMagnetMetadataForBtUnderMutation(// TorrentParser emits 0-based indices, but aria2's --select-file uses// 1-based indices; passing `0` makes aria2 reject the option.selectedFiles: selectedFiles.map((i) => i + 1),+ outputFilePaths: btStoragePlan?.outputFilePaths,pause: false,+ isPrivate: parsedBtLayout?.isPrivate ?? false,})if (addedGid !== newGid) {throw new Error(diff --git a/src/main/index.ts b/src/main/index.tsindex 582a86df..b407901d 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -873,7 +873,13 @@ async function syncTaskFilesIfMissing(engineTaskId: string): Promise<void> {try {- if (motrixDb.getTaskFiles(taskId).length > 0) return+ const persisted = motrixDb.getTaskFiles(taskId)+ // Magnet confirmation persists selected indices immediately, before the+ // replacement aria2 task has exposed real paths. Treat those placeholder+ // rows as missing so the first authoritative file list replaces them.+ if (persisted.length > 0 && persisted.every((file) => file.path !== '')) {+ return+ }// task_files has FK on task_metadata.motrix_id. The metadata row is// written by the periodic SessionManager.save() (15s default) — for// a freshly-created task, polling fires the file sync each tick from@@ -900,6 +906,28 @@ async function syncTaskFilesIfMissing(}}+function rebaseTaskFilePaths(+ taskId: string,+ sourceRoot: string,+ finalRoot: string+): void {+ const rows = motrixDb.getTaskFiles(taskId)+ let changed = false+ const rebased = rows.map((row) => {+ if (!row.path) return row+ const relative = path.relative(sourceRoot, row.path)+ if (relative.startsWith('..') || path.isAbsolute(relative)) return row+ changed = true+ return {+ ...row,+ path: relative === '' ? finalRoot : path.join(finalRoot, relative),+ }+ })+ if (!changed) return+ motrixDb.replaceTaskFiles(taskId, rebased)+ eventBus.emit(Events.TaskFilesUpdated, { taskId })+}+// ─── Task persistence / finalize wiring ─────────────────/**@@ -982,6 +1010,7 @@ function buildFinalizeDeps(adapter: Aria2Adapter) {adapter,fs: { renameAtomic, removePathRecursive },torrentMetaStore,+ rebaseTaskFilePaths,settings: { get: getFinalizeSettings },eventBus,activityRecorder,diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 2f7ea54f..6529377d 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -7,7 +7,7 @@ import { EXTERNAL_URLS } from '@shared/external-urls'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import { CliPackageManager } from '@shared/types/cli-tool'-import { TaskStatus, TaskType } from '@shared/types/task'+import { TaskInstancePhase, TaskStatus, TaskType } from '@shared/types/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { afterEach, describe, expect, it, vi } from 'vitest'import { MainProcessWorkCoordinator } from '../main-process-work-coordinator'@@ -213,6 +213,7 @@ function fakeCtx() {},magnetTracker: {submit: vi.fn().mockResolvedValue(undefined),+ retryMetadata: vi.fn().mockResolvedValue(undefined),},activityRecorder: NOOP_TASK_ACTIVITY_RECORDER,persistTask: vi.fn().mockResolvedValue(undefined),@@ -299,6 +300,31 @@ describe('buildCommandHandlers', () => {expect(handlers[Commands.AddMagnetTask]).toBeInstanceOf(Function)})+ it('routes RetryTasks for unresolved magnet metadata to MagnetTracker', async () => {+ const ctx = fakeCtx()+ vi.mocked(ctx.taskManager.getById).mockReturnValue({+ id: 'magnet-timeout',+ status: TaskStatus.Error,+ type: TaskType.Magnet,+ torrentMetaPath: null,+ instances: [+ {+ phase: TaskInstancePhase.MagnetMetadataResolution,+ uris: ['magnet:?xt=urn:btih:timeout'],+ },+ ],+ } as never)+ const handlers = buildCommandHandlers(ctx as unknown as CommandContext)++ await expect(+ handlers[Commands.RetryTasks]?.(['magnet-timeout'])+ ).resolves.toEqual({ succeeded: ['magnet-timeout'], failed: [] })++ expect(ctx.magnetTracker.retryMetadata).toHaveBeenCalledWith(+ 'magnet-timeout'+ )+ })+it('admits RemoveTask through the mutation lock and Session persistence queue', async () => {const ctx = fakeCtx()vi.mocked(ctx.taskManager.getById).mockReturnValue({diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex e404ac56..bddfb7fd 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -83,6 +83,7 @@ import {import { EngineRecoveryAction } from '@shared/types/engine'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'+import { canRetryMagnetMetadata } from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type { TaskOccurrence } from '@shared/types/task-occurrence'import { BrowserWindow, dialog, ipcMain, shell } from 'electron'@@ -753,6 +754,20 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {)},+ [Commands.RetryTasks]: async (rawPayload: unknown) => {+ const taskIds = taskIdsPayloadSchema.parse(rawPayload)+ return toBulkTaskCommandResult(+ await runBulkTaskAction(taskIds, reAddDeps, async (id) => {+ const task = taskManager.getById(id)+ if (task && canRetryMagnetMetadata(task)) {+ await magnetTracker.retryMetadata(id)+ return+ }+ await reAddTask(id, reAddDeps)+ })+ )+ },+[Commands.RemoveTasks]: async (rawPayload: unknown) => {const { taskIds, deleteWithFiles } =removeTasksPayloadSchema.parse(rawPayload)diff --git a/src/main/ipc/queries/get-task-files.test.ts b/src/main/ipc/queries/get-task-files.test.tsindex e594cbba..ef88fb04 100644--- a/src/main/ipc/queries/get-task-files.test.ts+++ b/src/main/ipc/queries/get-task-files.test.ts@@ -1,5 +1,11 @@import type { DownloadTask } from '@shared/types/task'-import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it, vi } from 'vitest'import { createGetTaskFilesHandler } from './get-task-files'@@ -255,4 +261,68 @@ describe('getTaskFiles handler', () => {const result = await handler('t1')expect(result[0]?.path).toBe('CD1/track01.flac')})++ it('hides the indexed payload entry from in-flight file paths', async () => {+ const workspacePath = '/Users/x/Downloads/.motrix/0123456789abcdefabcd'+ const absolutePath = `${workspacePath}/p/CD1/track01.flac`+ const db = { getTaskFiles: vi.fn(() => []) }+ const taskManager = {+ getById: vi.fn(() =>+ mkTask({+ status: TaskStatus.Downloading,+ diskPath: workspacePath,+ saveDir: '/Users/x/Downloads',+ instances: [+ {+ instanceId: 'primary:t1',+ motrixId: 't1',+ gid: 'gid1',+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Downloading,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: workspacePath,+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {+ btStorageLayout: {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath,+ payloadEntry: 'p',+ torrentRootName: 'Original album name',+ multiFile: true,+ },+ },+ createdAt: 1,+ updatedAt: 1,+ },+ ],+ })+ ),+ }+ const engine = {+ getTaskFiles: vi.fn(async () => [+ {+ index: 0,+ path: absolutePath,+ size: 50,+ completedBytes: 20,+ selected: true,+ },+ ]),+ }+ const handler = createGetTaskFilesHandler({+ db,+ taskManager,+ engine,+ } as unknown as Parameters<typeof createGetTaskFilesHandler>[0])++ const result = await handler('t1')++ expect(result[0]?.path).toBe('CD1/track01.flac')+ })})diff --git a/src/main/ipc/queries/get-task-files.ts b/src/main/ipc/queries/get-task-files.tsindex 4284fc8a..560577c0 100644--- a/src/main/ipc/queries/get-task-files.ts+++ b/src/main/ipc/queries/get-task-files.ts@@ -1,6 +1,7 @@import type { EngineAdapter } from '@core/engine/engine-adapter'import { getLogger } from '@core/logger'import type { MotrixDatabase } from '@core/session/motrix-database'+import { getBtPayloadPath } from '@core/task/bt-storage-layout'import type { TaskManager } from '@core/task/task-manager'import { relativizeTorrentPath } from '@shared/lib/path-ext'import type { DownloadTask, TaskFile } from '@shared/types/task'@@ -23,6 +24,7 @@ interface Deps {function relativize(absolutePath: string, task: DownloadTask): string {return relativizeTorrentPath(absolutePath,+ getBtPayloadPath(task),task.diskPath,task.finalPath,task.saveDirdiff --git a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx b/src/renderer/routes/downloads/inspector/overview-tab.test.tsxindex 3971b0a9..8fadb0b0 100644--- a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx@@ -20,6 +20,7 @@ import { DownloadErrorCode } from '@shared/errors'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import {+ TaskInstancePhase,TaskKind,TaskStatus,TaskType,@@ -98,6 +99,27 @@ const task: DownloadTask = {},}+function magnetMetadataInstance(taskId: string): DownloadTask['instances'][0] {+ return {+ instanceId: `meta:${taskId}`,+ motrixId: taskId,+ gid: 'metadata-gid',+ phase: TaskInstancePhase.MagnetMetadataResolution,+ status: TaskStatus.Error,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/tmp/metadata',+ transitionPhase: TransitionPhase.Idle,+ uris: ['magnet:?xt=urn:btih:timeout'],+ uriHash: null,+ payload: {},+ createdAt: 1,+ updatedAt: 2,+ }+}+describe('OverviewTab', () => {beforeEach(() => {Object.assign(navigator, {@@ -204,7 +226,7 @@ describe('OverviewTab', () => {).not.toBeInTheDocument()})- it('shows retry for a BT error task with its sidecar and dispatches ReAddTask', () => {+ it('shows retry for a BT error task with its sidecar and dispatches RetryTasks', () => {renderOverviewTab({...task,id: 'bt-error',@@ -216,9 +238,33 @@ describe('OverviewTab', () => {})const retryButton = screen.getByRole('button', { name: 'Retry' })fireEvent.click(retryButton)- expect(transport.invoke).toHaveBeenCalledWith(Commands.ReAddTasks, [+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RetryTasks, ['bt-error',])})++ it('adds Retry to the timeout Alert for unresolved magnet metadata', () => {+ renderOverviewTab({+ ...task,+ id: 'magnet-timeout',+ status: TaskStatus.Error,+ kind: TaskKind.Bt,+ type: TaskType.Magnet,+ torrentMetaPath: null,+ errorCode: DownloadErrorCode.Timeout,+ instances: [magnetMetadataInstance('magnet-timeout')],+ })++ expect(screen.getByText('Download timed out')).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Check your connection speed and stability, then retry'+ )+ ).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RetryTasks, [+ 'magnet-timeout',+ ])+ })})})diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.test.ts b/src/renderer/routes/downloads/inspector/use-task-actions.test.tsindex 7a2ee5d7..df6f0343 100644--- a/src/renderer/routes/downloads/inspector/use-task-actions.test.ts+++ b/src/renderer/routes/downloads/inspector/use-task-actions.test.ts@@ -1,5 +1,11 @@import type { DownloadTask } from '@shared/types/task'-import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -57,6 +63,36 @@ function makeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {})}+function makeRetryableMagnetMetadataTask(id: string): DownloadTask {+ return makeTask({+ id,+ status: TaskStatus.Error,+ kind: TaskKind.Bt,+ type: TaskType.Magnet,+ torrentMetaPath: null,+ instances: [+ {+ instanceId: `meta:${id}`,+ motrixId: id,+ gid: `gid-${id}`,+ phase: TaskInstancePhase.MagnetMetadataResolution,+ status: TaskStatus.Error,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/tmp/metadata',+ transitionPhase: TransitionPhase.Idle,+ uris: ['magnet:?xt=urn:btih:timeout'],+ uriHash: null,+ payload: {},+ createdAt: 1,+ updatedAt: 2,+ },+ ],+ })+}+describe('useTaskActions', () => {beforeEach(() => {vi.clearAllMocks()@@ -133,7 +169,7 @@ describe('useTaskActions', () => {expect(openAddTaskDialog).toHaveBeenCalled()})- it('onRetry({ alt: true }) on multi falls back to direct ReAddTask', async () => {+ it('onRetry({ alt: true }) on multi falls back to generic RetryTasks', async () => {const tasks = [makeRetryableErrorTask({ id: 'a' }),makeRetryableErrorTask({ id: 'b' }),@@ -141,12 +177,24 @@ describe('useTaskActions', () => {const { result } = renderHook(() => useTaskActions(tasks))await result.current.onRetry({ alt: true })expect(openAddTaskDialog).not.toHaveBeenCalled()- expect(transport.invoke).toHaveBeenCalledWith(Commands.ReAddTasks, [+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RetryTasks, ['a','b',])})+ it('routes magnet metadata Retry directly even when Alt is pressed', async () => {+ const tasks = [makeRetryableMagnetMetadataTask('magnet-timeout')]+ const { result } = renderHook(() => useTaskActions(tasks))++ await result.current.onRetry({ alt: true })++ expect(openAddTaskDialog).not.toHaveBeenCalled()+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RetryTasks, [+ 'magnet-timeout',+ ])+ })+it('retryCount counts only tasks whose engine inputs can be rebuilt', () => {const tasks = [// Never rebuildable: no single re-addable engine handle.@@ -155,9 +203,10 @@ describe('useTaskActions', () => {// persisted, so the uris alone are not the original request.makeTask({ id: 'h', status: TaskStatus.Error }),makeRetryableErrorTask({ id: 'e' }),+ makeRetryableMagnetMetadataTask('magnet'),]const { result } = renderHook(() => useTaskActions(tasks))- expect(result.current.retryCount).toBe(1) // only 'e'+ expect(result.current.retryCount).toBe(2) // sidecar BT + metadata magnet})it('onRetry() dispatches nothing for a Mux-kind Error task', async () => {diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.ts b/src/renderer/routes/downloads/inspector/use-task-actions.tsindex 3c168a8a..1ef5da42 100644--- a/src/renderer/routes/downloads/inspector/use-task-actions.ts+++ b/src/renderer/routes/downloads/inspector/use-task-actions.ts@@ -13,6 +13,7 @@ import {canReseed,canResume,canStopSeeding,+ getTaskRetryKind,} from '@shared/types/task-actions'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -276,14 +277,14 @@ export function useTaskActions(if (modifier?.alt &&selected.length === 1 &&- canAttemptRetry(selected[0])+ getTaskRetryKind(selected[0]) === 'torrent-readd') {await altReAddSingle(selected[0])return}- await directReAdd(canAttemptRetry)+ await dispatchSubset(Commands.RetryTasks, canAttemptRetry)},- [selected, altReAddSingle, directReAdd]+ [selected, altReAddSingle, dispatchSubset])const onRemove = useCallback((modifier?: { shift: boolean }) => {diff --git a/src/renderer/routes/downloads/task-row.test.tsx b/src/renderer/routes/downloads/task-row.test.tsxindex 53962254..5d0277d2 100644--- a/src/renderer/routes/downloads/task-row.test.tsx+++ b/src/renderer/routes/downloads/task-row.test.tsx@@ -14,13 +14,11 @@ vi.mock('@renderer/components/ui/toast', () => ({}))import '@renderer/lib/i18n'-import { transport } from '@renderer/lib/transport'import { DownloadErrorCode } from '@shared/errors'-import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'-import { fireEvent, render, screen } from '@testing-library/react'+import { render, screen } from '@testing-library/react'import { describe, expect, it } from 'vitest'import { TaskRow } from './task-row'@@ -189,7 +187,7 @@ describe('TaskRow', () => {).not.toBeInTheDocument()})- it('shows the retry button for a BT error task with its sidecar and dispatches ReAddTask', () => {+ it('does not add a retry button to a BT error row with a sidecar', () => {render(<TaskRowtask={fake({@@ -202,14 +200,12 @@ describe('TaskRow', () => {rowProps={rowProps}/>)- const retryButton = screen.getByRole('button', { name: 'Retry' })- fireEvent.click(retryButton)- expect(transport.invoke).toHaveBeenCalledWith(Commands.ReAddTasks, [- 'bt-error',- ])+ expect(+ screen.queryByRole('button', { name: 'Retry' })+ ).not.toBeInTheDocument()})- it('reveals the retry button once a memoized magnet task gains its torrentMetaPath sidecar', () => {+ it('keeps retry out of a memoized magnet row after a sidecar appears', () => {const errored = fake({id: 'magnet-error',status: TaskStatus.Error,@@ -225,15 +221,15 @@ describe('TaskRow', () => {screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()- // Same task id, same status/progress/speeds/error fields — only- // torrentMetaPath changes. The memoized row must still re-render.rerender(<TaskRowtask={{ ...errored, torrentMetaPath: '/sidecar/magnet.torrent' }}rowProps={rowProps}/>)- expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Retry' })+ ).not.toBeInTheDocument()})})})diff --git a/src/renderer/routes/downloads/task-row.tsx b/src/renderer/routes/downloads/task-row.tsxindex 70034567..4c9fefae 100644--- a/src/renderer/routes/downloads/task-row.tsx+++ b/src/renderer/routes/downloads/task-row.tsx@@ -1,4 +1,3 @@-import { Button } from '@renderer/components/ui/button'import { Checkbox } from '@renderer/components/ui/checkbox'import { resolveFailureReason } from '@renderer/lib/failure-reason'import { formatBytes, formatDurationHMS } from '@renderer/lib/format'@@ -6,14 +5,8 @@ import { getProgressBarTone } from '@renderer/lib/task-status-ui'import { cn } from '@renderer/lib/utils'import type { DownloadTask } from '@shared/types/task'import { TaskStatus, TaskType } from '@shared/types/task'-import {- canAttemptRetry,- canRebuildTaskInputs,-} from '@shared/types/task-actions'-import { RotateCcw } from 'lucide-react'import { memo } from 'react'import { useTranslation } from 'react-i18next'-import { useTaskActions } from './inspector/use-task-actions'import { StatusPill } from './status-pill'import { TASK_GRID_MIN_WIDTH, TASK_GRID_TEMPLATE } from './task-column-header'@@ -29,7 +22,6 @@ export interface TaskRowProps {function TaskRowBase({ task, rowProps }: TaskRowProps) {const { t, i18n } = useTranslation()- const { onRetry } = useTaskActions([task])const pct = Math.round(task.progress * 100)const showDash = (value: number) =>value <= 0 || task.status === TaskStatus.Completed@@ -52,8 +44,6 @@ function TaskRowBase({ task, rowProps }: TaskRowProps) {{ t, exists: (key) => i18n.exists(key) }): null- const showRetry = isError && canAttemptRetry(task)-return (<divrole="option"@@ -102,23 +92,7 @@ function TaskRowBase({ task, rowProps }: TaskRowProps) {</span></div></div>- <span className="flex items-center gap-1">- <StatusPill status={task.status} />- {showRetry && (- <Button- variant="ghost"- size="sm"- aria-label={t('panel.downloads.action.retry')}- title={t('panel.downloads.action.retry')}- onClick={(e) => {- e.stopPropagation()- void onRetry()- }}- >- <RotateCcw data-icon="inline-start" />- </Button>- )}- </span>+ <StatusPill status={task.status} /><span className="tabular-nums">{showDash(task.downloadSpeed)? '—'@@ -154,11 +128,6 @@ export const TaskRow = memo(TaskRowBase, (prev, next) => {a.errorMessage === b.errorMessage &&a.errorDetailKey === b.errorDetailKey &&a.errorDetailParams === b.errorDetailParams &&- a.diagnosisRevision === b.diagnosisRevision &&- // canRetry is fully determined by `status` (already compared above);- // canRebuildTaskInputs depends on kind/type/torrentMetaPath/uris, none- // of which are otherwise tracked here, so compare the derived gate- // directly rather than every raw field it happens to read today.- canRebuildTaskInputs(a) === canRebuildTaskInputs(b)+ a.diagnosisRevision === b.diagnosisRevision)})diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex b16d67b3..f8dc01d4 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -21,7 +21,12 @@ import type { MagnetTracker } from '@core/torrent/magnet-tracker'import type { TrackerManager } from '@core/tracker'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'-import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+} from '@shared/types/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ServerPluginInstallService } from '../plugin/install-service'import type { ServerCommandContext } from './commands'@@ -125,6 +130,7 @@ function makeFakeCtx() {} as unknown as ActivationDispatcher,magnetTracker: {submit: vi.fn().mockResolvedValue(undefined),+ retryMetadata: vi.fn().mockResolvedValue(undefined),cancel: vi.fn().mockResolvedValue('removed'),observe: vi.fn().mockReturnValue(false),dispose: vi.fn(),@@ -508,6 +514,33 @@ describe('server plural task commands', () => {await expect(handlers[Commands.PauseTasks]?.([])).rejects.toThrow()})++ it('RetryTasks routes unresolved magnet metadata to MagnetTracker', async () => {+ const ctx = makeFakeCtx()+ vi.mocked(ctx.taskManager.getById).mockReturnValue({+ id: 'magnet-timeout',+ status: TaskStatus.Error,+ type: TaskType.Magnet,+ torrentMetaPath: null,+ instances: [+ {+ phase: TaskInstancePhase.MagnetMetadataResolution,+ uris: ['magnet:?xt=urn:btih:timeout'],+ },+ ],+ } as never)+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )++ await expect(+ handlers[Commands.RetryTasks]?.(['magnet-timeout'])+ ).resolves.toEqual({ succeeded: ['magnet-timeout'], failed: [] })++ expect(ctx.magnetTracker.retryMetadata).toHaveBeenCalledWith(+ 'magnet-timeout'+ )+ })})describe('server Commands.StopSeedingTask', () => {diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 5f09257b..15441f15 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -57,6 +57,7 @@ import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'import { EngineRecoveryAction } from '@shared/types/engine'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'+import { canRetryMagnetMetadata } from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type { TaskOccurrence } from '@shared/types/task-occurrence'import { z } from 'zod'@@ -455,6 +456,20 @@ export function buildServerCommandHandlers()},+ [Commands.RetryTasks]: async (rawPayload: unknown) => {+ const taskIds = taskIdsPayloadSchema.parse(rawPayload)+ return toBulkTaskCommandResult(+ await runBulkTaskAction(taskIds, reAddDeps, async (id) => {+ const task = taskManager.getById(id)+ if (task && canRetryMagnetMetadata(task)) {+ await magnetTracker.retryMetadata(id)+ return+ }+ await reAddTask(id, reAddDeps)+ })+ )+ },+[Commands.RemoveTasks]: async (rawPayload: unknown) => {const { taskIds, deleteWithFiles } =removeTasksPayloadSchema.parse(rawPayload)diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex 8e0db035..646299d2 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -13,6 +13,9 @@ export const Commands = {ResumeTasks: 'command:resumeTasks',RemoveTasks: 'command:removeTasks',ReAddTasks: 'command:reAddTasks',+ // Generic user Retry. Shell handlers route sidecar-backed torrents to+ // re-add and unresolved magnets to a fresh metadata-resolution attempt.+ RetryTasks: 'command:retryTasks',StopSeedingTasks: 'command:stopSeedingTasks',SetSelectedFiles: 'command:setSelectedFiles',UpdateSettings: 'command:updateSettings',diff --git a/src/shared/schemas/bulk-task-command.ts b/src/shared/schemas/bulk-task-command.tsindex 836f1440..053827d0 100644--- a/src/shared/schemas/bulk-task-command.ts+++ b/src/shared/schemas/bulk-task-command.ts@@ -1,6 +1,6 @@import { z } from 'zod'-/** Payload of Commands.PauseTasks / ResumeTasks / ReAddTasks / StopSeedingTasks. */+/** Payload of plural task-id commands, including Commands.RetryTasks. */export const taskIdsPayloadSchema = z.array(z.string().min(1)).min(1)/** Payload of Commands.RemoveTasks. */diff --git a/src/shared/types/task-actions.test.ts b/src/shared/types/task-actions.test.tsindex dd5fa796..3118e136 100644--- a/src/shared/types/task-actions.test.ts+++ b/src/shared/types/task-actions.test.ts@@ -18,7 +18,9 @@ import {canReseed,canResume,canRetry,+ canRetryMagnetMetadata,canStopSeeding,+ getTaskRetryKind,isFinalizing,} from './task-actions'@@ -43,6 +45,16 @@ function muxInstance(status: TaskStatus): TaskInstance {}}+function magnetMetadataInstance(uri = 'magnet:?xt=urn:btih:abc'): TaskInstance {+ return {+ ...muxInstance(TaskStatus.Error),+ instanceId: 'meta:t1',+ gid: 'meta-gid',+ phase: TaskInstancePhase.MagnetMetadataResolution,+ uris: [uri],+ }+}+function makeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {return makeDownloadTask({id: 't1',@@ -424,4 +436,32 @@ describe('canAttemptRetry', () => {expect(canRetry(task) && canRebuildTaskInputs(task)).toBe(expected)expect(canAttemptRetry(task)).toBe(expected)})++ it('offers a distinct retry for failed magnet metadata without a sidecar', () => {+ const task = makeTask({+ kind: TaskKind.Bt,+ status: TaskStatus.Error,+ type: TaskType.Magnet,+ torrentMetaPath: null,+ instances: [magnetMetadataInstance()],+ })++ expect(canRebuildTaskInputs(task)).toBe(false)+ expect(canRetryMagnetMetadata(task)).toBe(true)+ expect(getTaskRetryKind(task)).toBe('magnet-metadata')+ expect(canAttemptRetry(task)).toBe(true)+ })++ it('does not offer metadata retry without a persisted magnet URI', () => {+ const task = makeTask({+ kind: TaskKind.Bt,+ status: TaskStatus.Error,+ type: TaskType.Magnet,+ torrentMetaPath: null,+ instances: [magnetMetadataInstance('https://example.com/not-magnet')],+ })++ expect(canRetryMagnetMetadata(task)).toBe(false)+ expect(getTaskRetryKind(task)).toBeNull()+ })})diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex e2c21529..daa5c667 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -133,8 +133,38 @@ export function canRebuildTaskInputs(t: DownloadTask): boolean {return false}+/**+ * A failed magnet metadata attempt can be replayed from the persisted magnet+ * URI even though no `.torrent` sidecar exists yet. This is deliberately+ * narrower than torrent re-add: only the metadata-resolution phase is+ * accepted, and removed/non-terminal tasks are excluded.+ */+export function canRetryMagnetMetadata(t: DownloadTask): boolean {+ return (+ t.status === TaskStatus.Error &&+ t.type === TaskType.Magnet &&+ t.torrentMetaPath == null &&+ t.instances.some(+ (instance) =>+ instance.phase === TaskInstancePhase.MagnetMetadataResolution &&+ instance.uris.some((uri) => uri.toLowerCase().startsWith('magnet:?'))+ )+ )+}++export type TaskRetryKind = 'torrent-readd' | 'magnet-metadata'++/** Resolve the concrete replay operation behind the generic Retry UI. */+export function getTaskRetryKind(t: DownloadTask): TaskRetryKind | null {+ if (!canRetry(t)) return null+ if (canRebuildTaskInputs(t)) return 'torrent-readd'+ if (canRetryMagnetMetadata(t)) return 'magnet-metadata'+ return null+}+/** A retry the UI should actually offer: the task is in a retryable status- * AND its engine dispatch can be rebuilt from the persisted record. */+ * AND its engine dispatch can be rebuilt from the persisted record. This+ * includes pre-sidecar magnet metadata retries as a distinct operation. */export function canAttemptRetry(t: DownloadTask): boolean {- return canRetry(t) && canRebuildTaskInputs(t)+ return getTaskRetryKind(t) !== null}diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.tsindex 61f842af..80fe69bb 100644--- a/tests/scripts/docker-server-runtime.test.ts+++ b/tests/scripts/docker-server-runtime.test.ts@@ -175,6 +175,10 @@ describe('Docker Server runtime staging contract', () => {imageSmoke.indexOf("new Set(['seeding', 'completed'])"))expect(imageSmoke).toContain('engineGid: finalBtTask.engineTaskId')+ expect(imageSmoke).toContain(+ "path.join(volumes.downloadsDir, 'sample-data', 'test.bin')"+ )+ expect(imageSmoke).not.toContain("'sample-data', 'sample-data', 'test.bin'")expect(imageSmoke).toContain("randomBytes(24).toString('hex')")expect(imageSmoke).toContain('downloadedBytes: lastTask.downloadedBytes')expect(imageSmoke).toContain('totalBytes: lastTask.totalBytes')