A full-featured download manager.
refactor(bt): retire suffixes and hidden payload staging (#2139)
Dr_rOot82861a0c0464
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 99f9fa47..cef47e57 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -1284,6 +1284,23 @@ describe('Aria2Adapter', () => {})describe('getTaskStatus — status translation', () => {+ it('returns null only when the engine identity is absent', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)+ vi.mocked(rpc.tellStatus).mockRejectedValueOnce(+ new Error('GID#0123456789abcdef is not found')+ )+ await expect(+ adapter.getTaskStatus('0123456789abcdef')+ ).resolves.toBeNull()+ vi.mocked(rpc.tellStatus).mockRejectedValueOnce(+ new Error('connection lost')+ )+ await expect(adapter.getTaskStatus('0123456789abcdef')).rejects.toThrow(+ 'connection lost'+ )+ })+it('translates active HTTP download', async () => {const rpc = createMockRpc()vi.mocked(rpc.tellStatus).mockResolvedValue(RAW_HTTP_ACTIVE)diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex e8ae39dd..424a4e0d 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -1,4 +1,4 @@-import { access } from 'node:fs/promises'+import { access, mkdir } from 'node:fs/promises'import path from 'node:path'import { setTimeout as delay } from 'node:timers/promises'import { getLogger } from '@core/logger'@@ -600,8 +600,13 @@ export class Aria2Adapter implements EngineAdapter {}async getTaskStatus(engineTaskId: string): Promise<DownloadTask | null> {- const raw = await this.rpc.tellStatus(engineTaskId)- return translateRawToTask(raw)+ try {+ const raw = await this.rpc.tellStatus(engineTaskId)+ return translateRawToTask(raw)+ } catch (error) {+ if (isNotFoundError(error)) return null+ throw error+ }}async getTaskFiles(engineTaskId: string): Promise<TaskFile[]> {@@ -700,6 +705,8 @@ export class Aria2Adapter implements EngineAdapter {if (params.selectedFiles?.length) {opts['select-file'] = params.selectedFiles.join(',')}+ if (params.outputRoot !== undefined && !path.isAbsolute(params.outputRoot))+ throw new TypeError('Torrent output root must be absolute')if (params.outputFilePaths?.length) {const seen = new Set<number>()opts['index-out'] = params.outputFilePaths.map(@@ -723,7 +730,10 @@ export class Aria2Adapter implements EngineAdapter {throw new TypeError('Invalid torrent output file mapping')}seen.add(fileIndex)- return `${fileIndex + 1}=${relativePath}`+ const outputPath = params.outputRoot+ ? path.join(params.outputRoot, relativePath)+ : relativePath+ return `${fileIndex + 1}=${outputPath}`})}@@ -768,6 +778,7 @@ export class Aria2Adapter implements EngineAdapter {// Override both user configuration and stale task options so a failed// Web Seed cannot abort peers or other Web Seeds before their first byte.opts['max-file-not-found'] = '0'+ if (params.outputRoot) await mkdir(params.saveDir, { recursive: true })const b64 = Buffer.from(params.metadata).toString('base64')const actualGid = await this.rpc.addTorrent(b64, [], opts)if (diff --git a/src/core/engine/aria2/bt-webseed-policy.integration.test.ts b/src/core/engine/aria2/bt-webseed-policy.integration.test.tsindex 067c19d8..f376050f 100644--- a/src/core/engine/aria2/bt-webseed-policy.integration.test.ts+++ b/src/core/engine/aria2/bt-webseed-policy.integration.test.ts@@ -5,10 +5,7 @@ import { mkdir, mkdtemp, open, rm, stat } from 'node:fs/promises'import http from 'node:http'import { tmpdir } from 'node:os'import path from 'node:path'-import {- createBtStoragePlan,- parseBtFileLayout,-} from '@core/task/bt-storage-layout'+import { parseBtFileLayout } from '@core/task/bt-storage-layout'import {type Aria2Handle,bundledAria2Exists,@@ -16,6 +13,7 @@ import {connectAdapter,spawnAria2ForTest,} from '@test-utils/aria2'+import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'import { afterEach, describe, expect, it } from 'vitest'import type { Aria2RawStatus } from './types'diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex 5dbc08f8..7c75e2ce 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -53,9 +53,11 @@ 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. */+ /** Optional per-file mapping relative to outputRoot, or saveDir when absent.+ * The adapter translates indices and option syntax to the target engine. */outputFilePaths?: OutputFilePath[]+ /** Trusted absolute payload root, independent of the engine metadata directory. */+ outputRoot?: stringseedTime?: numberseedRatio?: numberbtSeedUnverified?: booleandiff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 044ec490..7bf16b3c 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -13,6 +13,7 @@ import {TransitionPhase,} from '@shared/types/task'import type { TaskTerminalOccurrence } from '@shared/types/task-occurrence'+import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'@@ -24,7 +25,7 @@ import { clearStoppedTasks } from '../task/actions/clear-stopped-tasks'import { stopSeedingTask } from '../task/actions/stop-seeding-task'import {btStoragePayload,- createBtStoragePlan,+ createBtDirectStoragePlan,getBtPayloadPath,parseBtFileLayout,} from '../task/bt-storage-layout'@@ -4339,3 +4340,43 @@ it('re-adds an interrupted indexed BT download with its original payload mappingfs.rmSync(root, { recursive: true, force: true })}})++it('restores a paused direct BT download at its exact final filename', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-readd-layout-'))+ try {+ const bytes = buildSingleFileTorrent('movie.mkv')+ const metadata = path.join(root, 'source.torrent')+ fs.writeFileSync(metadata, bytes)+ const parsed = await parseBtFileLayout(bytes)+ const plan = createBtDirectStoragePlan(+ path.join(root, 'chosen.mkv'),+ parsed+ )+ const tm = new TaskManager()+ const db = createMockDb()+ const adapter = createMockAdapter()+ seedAsPair(db, {+ motrixId: 'readd-layout',+ gid: 'old-gid',+ type: TaskType.Bt,+ status: TaskStatus.Paused,+ infoHash: parsed.infoHash,+ torrentMetaPath: metadata,+ diskPath: path.join(root, 'chosen.mkv'),+ finalPath: path.join(root, 'chosen.mkv'),+ payload: btStoragePayload(plan.layout),+ })+ await new SessionManager(tm, createMockRpc(), db, adapter).restore()+ expect(adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({+ saveDir: root,+ outputFilePaths: [{ fileIndex: 0, relativePath: 'chosen.mkv' }],+ pause: true,+ checkIntegrity: true,+ })+ )+ expect(tm.getById('readd-layout')?.saveDir).toBe(root)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 96cf517d..cc9c48fa 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -48,8 +48,10 @@ import {terminalFieldsFromRow,} from '../task/apply-terminal-transition'import {+ buildBtDirectOutputPaths,buildFinalOutputFilePaths,buildStagingOutputFilePaths,+ getBtDirectStorageLayout,getBtStorageLayout,parseBtFileLayout,shouldPrioritizeBtPreviewPiecesFromMetadata,@@ -1465,28 +1467,53 @@ export class SessionManager {await shouldPrioritizeBtPreviewPiecesFromMetadata(bytes)const restored = taskRowToDownloadTask(taskPart, pair.instances)const layout = getBtStorageLayout(restored)- const parsed = layout ? await parseBtFileLayout(bytes) : null+ const directLayout = getBtDirectStorageLayout(restored)+ const parsed =+ layout || directLayout?.torrentRootName+ ? await parseBtFileLayout(bytes)+ : nullconst alreadyRenamed = restored.diskPath === restored.finalPathreturn this.dispatchRecoveryCandidate(pair, (gid) =>this.adapter.addTorrent({metadata: bytes,gid,- saveDir: layout- ? alreadyRenamed- ? path.dirname(restored.finalPath)- : layout.workspacePath- : primary?.diskPath || restored.saveDir || '/',- ...(layout && parsed+ saveDir: directLayout+ ? buildBtDirectOutputPaths(+ restored.diskPath,+ parsed,+ restored.torrentMetaPath+ ).saveDir+ : layout+ ? alreadyRenamed+ ? path.dirname(restored.finalPath)+ : layout.workspacePath+ : primary?.diskPath || restored.saveDir || '/',+ ...(directLayout && parsed? {- outputFilePaths: alreadyRenamed- ? buildFinalOutputFilePaths(- parsed,- restored.finalPath,- layout- )- : buildStagingOutputFilePaths(parsed, layout),+ outputFilePaths: buildBtDirectOutputPaths(+ restored.diskPath,+ parsed,+ restored.torrentMetaPath+ ).outputFilePaths,}- : {}),+ : layout && parsed+ ? {+ outputFilePaths: alreadyRenamed+ ? buildFinalOutputFilePaths(+ parsed,+ restored.finalPath,+ layout+ )+ : buildStagingOutputFilePaths(parsed, layout),+ }+ : {}),+ outputRoot: directLayout+ ? buildBtDirectOutputPaths(+ restored.diskPath,+ parsed,+ restored.torrentMetaPath+ ).outputRoot+ : undefined,pause: taskPart.aggStatus === TaskStatus.Paused,checkIntegrity: true,...(prioritizePreviewPiecesdiff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex f8293060..d9d24ab9 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -683,6 +683,96 @@ describe('finalizeTask BT branch', () => {} as Partial<DownloadTask>)}+ it('recovers a missing engine identity without abandoning seeding', async () => {+ const task = makeBtTask({+ status: TaskStatus.Finalizing,+ transitionPhase: TransitionPhase.Renaming,+ diskPath: '/d/movie.iso',+ finalPath: '/d/movie.iso',+ instances: [+ makePrimaryInstance({+ phase: TaskInstancePhase.BtDownload,+ diskPath: '/d/movie.iso',+ transitionPhase: TransitionPhase.Renaming,+ payload: {+ btStorageLayout: {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'original.iso',+ multiFile: false,+ finalized: false,+ },+ },+ }),+ ],+ })+ const deps = makeDeps()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue(null)+ vi.mocked(deps.torrentMetaStore.read).mockResolvedValue(+ buildSingleFileTorrent('original.iso')+ )+ await expect(finalizeTask('t1', deps)).resolves.toBeUndefined()+ expect(deps.adapter.addTorrent).toHaveBeenCalled()+ expect(task.status).toBe(TaskStatus.Seeding)+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()+ expect(task.transitionPhase).toBe(TransitionPhase.Idle)+ })++ it.each([TaskStatus.Seeding, TaskStatus.Completed])(+ 'finalizes direct BT in place with engine status %s and retains its GID',+ async (engineStatus) => {+ const task = makeBtTask({+ diskPath: '/d/movie.iso',+ finalPath: '/d/movie.iso',+ uploadedBytesBaseline: 20,+ instances: [+ makePrimaryInstance({+ phase: TaskInstancePhase.BtDownload,+ diskPath: '/d/movie.iso',+ payload: {+ btStorageLayout: {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'original.iso',+ multiFile: false,+ finalized: false,+ },+ },+ }),+ ],+ })+ const deps = makeDeps()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue(+ makeBtTask({+ status: engineStatus,+ totalBytes: 1024,+ downloadedBytes: 1024,+ uploadedBytes: 10,+ })+ )+ const gid = task.engineTaskId+ await finalizeTask('t1', deps)+ expect(task.status).toBe(engineStatus)+ expect(task.engineTaskId).toBe(gid)+ expect(task.uploadedBytesBaseline).toBe(20)+ expect(task.uploadedBytes).toBe(30)+ expect(task.progress).toBe(1)+ expect(task.instances[0].payload.btStorageLayout).toMatchObject({+ finalized: true,+ })+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(deps.adapter.addTorrent).not.toHaveBeenCalled()+ expect(deps.adapter.removeDownloadResult).toHaveBeenCalledTimes(+ engineStatus === TaskStatus.Completed ? 1 : 0+ )+ await finalizeTask('t1', deps)+ expect(deps.adapter.getTaskStatus).toHaveBeenCalledTimes(1)+ }+ )+it('renames only the indexed payload and reseeds through the restored final name', async () => {const workspacePath = '/d/.motrix/0123456789abcdefabcd'const renameAtomic = vi.fn(async () => {})diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex f730d724..8034b0b4 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -21,9 +21,12 @@ import type Database from 'better-sqlite3'import type { AddTorrentParams } from '../../engine/engine-adapter'import { applyTerminalTransition } from '../apply-terminal-transition'import {+ buildBtDirectOutputPaths,buildFinalOutputFilePaths,+ getBtDirectStorageLayout,getBtPayloadPath,getBtStorageLayout,+ markBtDirectOutputFinalized,parseBtFileLayout,} from '../bt-storage-layout'import { settleBtUpload } from '../bt-upload-settlement'@@ -181,6 +184,7 @@ async function finalizeTaskSerialized(const task = structuredClone(publishedTask)const alreadyOutputReady =+ getBtDirectStorageLayout(task)?.finalized !== false &&task.transitionPhase === TransitionPhase.Idle &&task.diskPath === task.finalPath &&(task.status === TaskStatus.Completed || task.status === TaskStatus.Seeding)@@ -217,7 +221,8 @@ async function finalizeTaskSerialized(if (current?.transitionPhase === TransitionPhase.Renaming &¤t.status !== TaskStatus.Error &&- current.diskPath !== current.finalPath+ (current.diskPath !== current.finalPath ||+ getBtDirectStorageLayout(current)?.finalized === false)) {try {await failFinalize(structuredClone(current), deps, {@@ -531,6 +536,14 @@ async function finalizeBt(return}const desiredFinalPath = finalizeOutcome.finalFilePath ?? task.finalPath+ if (+ getBtDirectStorageLayout(task) &&+ desiredFinalPath === task.diskPath &&+ !finalizeOutcome.replacement+ ) {+ await finalizeBtInPlace(task, deps, finalizeOutcome, previousStatus)+ return+ }if (!deps.commitFinalizedArtifact) {await persistDesiredFinalPath(task, desiredFinalPath, deps)}@@ -678,6 +691,7 @@ function applyBtTaskAfterRename(): void {task.finalPath = desiredFinalPathtask.diskPath = desiredFinalPath+ markBtDirectOutputFinalized(task)// The instance rows must stop pointing at the `.motrix` container or// restore() resurrects it after a restart. Status is left alone here — the// task still heads into reseed and its terminal state is decided below.@@ -839,7 +853,11 @@ async function finalizeBtAfterRename(: undefinedtry {const storageLayout = getBtStorageLayout(task)- const parsedLayout = storageLayout ? await parseBtFileLayout(bytes) : null+ const directLayout = getBtDirectStorageLayout(task)+ const parsedLayout =+ storageLayout || directLayout?.torrentRootName+ ? await parseBtFileLayout(bytes)+ : nullconst actualGid = await deps.adapter.addTorrent({metadata: bytes,// aria2 lays files out at `<dir>/<info.name>/...` (multi-file) or@@ -847,15 +865,36 @@ 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: storageLayout ? path.dirname(task.finalPath) : task.finalPath,+ saveDir: directLayout+ ? buildBtDirectOutputPaths(+ task.finalPath,+ parsedLayout,+ task.torrentMetaPath+ ).saveDir+ : storageLayout+ ? path.dirname(task.finalPath)+ : task.finalPath,outputFilePaths:- storageLayout && parsedLayout- ? buildFinalOutputFilePaths(- parsedLayout,+ directLayout && parsedLayout+ ? buildBtDirectOutputPaths(task.finalPath,- storageLayout- )- : undefined,+ parsedLayout,+ task.torrentMetaPath+ ).outputFilePaths+ : storageLayout && parsedLayout+ ? buildFinalOutputFilePaths(+ parsedLayout,+ task.finalPath,+ storageLayout+ )+ : undefined,+ outputRoot: directLayout+ ? buildBtDirectOutputPaths(+ task.finalPath,+ parsedLayout,+ task.torrentMetaPath+ ).outputRoot+ : undefined,selectedFiles,seedTime: bt.seedTime,seedRatio: seedRatioForNewGid,@@ -937,6 +976,97 @@ async function finalizeBtAfterRename(// later via stopSeedingTask or aria2's natural seed-time/ratio eviction.}+/** Direct BT outputs keep their original engine identity through seeding. */+async function finalizeBtInPlace(+ task: DownloadTask,+ deps: FinalizeTaskDeps,+ outcome: BeforeFinalizeOutcomeCommit,+ statusBeforeFinalize: TaskStatus+): Promise<void> {+ const live = await deps.adapter.getTaskStatus(task.engineTaskId)+ if (live) {+ task.totalBytes = Math.max(task.totalBytes, live.totalBytes)+ task.downloadedBytes = Math.max(task.downloadedBytes, live.downloadedBytes)+ task.sizeWhenDone = Math.max(task.sizeWhenDone, live.sizeWhenDone)+ task.uploadedBytes = task.uploadedBytesBaseline + live.uploadedBytes+ }+ if (live?.status === TaskStatus.Error)+ throw new AppError(+ ErrorCode.TaskFinalizeFailed,+ live.errorMessage ?? 'Engine task failed'+ )+ if (!live) {+ // The old engine identity was lost before completion committed. Retain+ // its last observed upload contribution before assigning a fresh GID.+ settleBtUpload(+ task,+ Math.max(0, task.uploadedBytes - task.uploadedBytesBaseline),+ false+ )+ }+ const unselected = live ? await snapshotUnselectedRelPaths(task, deps) : []+ await cleanupUnselectedAfterRename(task, unselected, deps)+ const completedAt = Date.now()+ const previousStatus = task.status+ const nextStatus = !live+ ? TaskStatus.Finalizing+ : live.status === TaskStatus.Seeding ||+ live?.status === TaskStatus.Downloading+ ? TaskStatus.Seeding+ : live?.status === TaskStatus.Paused+ ? TaskStatus.Paused+ : TaskStatus.Completed+ markBtDirectOutputFinalized(task)+ setTaskTransitionPhase(+ task,+ live ? TransitionPhase.Idle : TransitionPhase.Reseeding+ )+ Object.assign(+ task,+ applyTerminalTransition(task, nextStatus, {}, completedAt)+ )+ syncPrimaryInstanceIdentity(task)+ syncCompletionMetrics(task)+ normalizeTerminalRuntimeMetrics(task)++ const occurrence = buildTerminalOccurrence(+ terminalSnapshotFromTask(task),+ previousStatus,+ 'finalize',+ completedAt+ )+ if (deps.commitFinalizedArtifact && outcome.metadataOps.length > 0) {+ await deps.commitFinalizedArtifact({+ task,+ occurrence,+ sourcePath: task.diskPath,+ targetPath: task.finalPath,+ metadataOps: outcome.metadataOps,+ contributors: outcome.contributors,+ })+ deps.taskManager.set(task.id, structuredClone(task))+ await recordTaskTransition(task, previousStatus, deps, completedAt)+ if (occurrence) await deps.occurrenceDispatcher?.dispatch(occurrence)+ } else {+ outcome.commit(() => {})+ await persistTaskTransition(task, previousStatus, deps, completedAt)+ }+ deps.activityRecorder.recordDownloadCompleted({+ taskId: task.id,+ occurredAt: completedAt,+ })+ deps.publishTaskUpdateNow()+ if (!live) {+ await finalizeBtAfterRename(task, deps, completedAt, [])+ return+ }+ if (nextStatus === TaskStatus.Completed) {+ await deps.adapter.removeDownloadResult(task.engineTaskId)+ if (statusBeforeFinalize !== TaskStatus.Completed)+ fireAfterComplete(deps, task, 'finalize')+ }+}+/*** The shared "finalize failed" terminal sequence: mark the detached* candidate Error, sync its instance rows, commit through thediff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex 51ee8141..46939e78 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -113,6 +113,37 @@ function makeDeps(task: DownloadTask | undefined) {}describe('reAddTask (BT path)', () => {+ it.each([TaskStatus.Error, TaskStatus.Completed])(+ 're-adds a direct single-file BT task at the same final path from %s',+ async (status) => {+ const task = withPrimaryInstance(+ makeBtTask({+ status,+ diskPath: '/tmp/chosen.iso',+ finalPath: '/tmp/chosen.iso',+ })+ )+ task.instances[0].payload.btStorageLayout = {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'original.iso',+ multiFile: false,+ finalized: status === TaskStatus.Completed,+ }+ const deps = makeDeps(task)+ vi.mocked(deps.torrentMetaStore.read).mockResolvedValue(+ buildSingleFileTorrent('original.iso')+ )+ await reAddTask('t1', deps)+ expect(deps.adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({+ saveDir: '/tmp',+ outputFilePaths: [{ fileIndex: 0, relativePath: 'chosen.iso' }],+ checkIntegrity: true,+ })+ )+ }+ )it('reads torrent metadata and calls addTorrent with checkIntegrity', async () => {const task = makeBtTask({ status: TaskStatus.Completed })const deps = makeDeps(task)diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 3346c168..7c73b54d 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -25,8 +25,10 @@ import type { Logger } from '../../logger'import { DirectRecoveryPlanner } from '../../session/direct-recovery-planner'import { applyTerminalTransition } from '../apply-terminal-transition'import {+ buildBtDirectOutputPaths,buildFinalOutputFilePaths,buildStagingOutputFilePaths,+ getBtDirectStorageLayout,getBtStorageLayout,parseBtFileLayout,shouldPrioritizeBtPreviewPieces,@@ -137,7 +139,11 @@ async function reAddBt(metadata: Uint8Array): Promise<string> {const storageLayout = getBtStorageLayout(task)- const parsedLayout = storageLayout ? await parseBtFileLayout(metadata) : null+ const directLayout = getBtDirectStorageLayout(task)+ const parsedLayout =+ storageLayout || directLayout?.torrentRootName+ ? await parseBtFileLayout(metadata)+ : nullconst completed = task.status === TaskStatus.Completedconst prioritizePreviewPieces =!completed &&@@ -147,21 +153,40 @@ async function reAddBt(const selectedFiles = task.bt?.selectedFilesreturn deps.adapter.addTorrent({metadata,- saveDir: storageLayout- ? completed- ? path.dirname(task.finalPath)- : storageLayout.workspacePath- : reAddSaveDir(task),- outputFilePaths:- storageLayout && parsedLayout+ saveDir: directLayout+ ? buildBtDirectOutputPaths(+ task.diskPath,+ parsedLayout,+ task.torrentMetaPath+ ).saveDir+ : storageLayout? completed- ? buildFinalOutputFilePaths(- parsedLayout,- task.finalPath,- storageLayout- )- : buildStagingOutputFilePaths(parsedLayout, storageLayout)- : undefined,+ ? path.dirname(task.finalPath)+ : storageLayout.workspacePath+ : reAddSaveDir(task),+ outputFilePaths:+ directLayout && parsedLayout+ ? buildBtDirectOutputPaths(+ task.diskPath,+ parsedLayout,+ task.torrentMetaPath+ ).outputFilePaths+ : storageLayout && parsedLayout+ ? completed+ ? buildFinalOutputFilePaths(+ parsedLayout,+ task.finalPath,+ storageLayout+ )+ : buildStagingOutputFilePaths(parsedLayout, storageLayout)+ : undefined,+ outputRoot: directLayout+ ? buildBtDirectOutputPaths(+ task.diskPath,+ parsedLayout,+ task.torrentMetaPath+ ).outputRoot+ : undefined,gid: reservedGid,// AddTorrentParams is engine-native; the task aggregate stays 0-based.selectedFiles: selectedFiles?.map((index) => index + 1),diff --git a/src/core/task/actions/remove-task.test.ts b/src/core/task/actions/remove-task.test.tsindex 61190e89..9b6b51c4 100644--- a/src/core/task/actions/remove-task.test.ts+++ b/src/core/task/actions/remove-task.test.ts@@ -1,3 +1,6 @@+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'import { ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'import {@@ -6,6 +9,7 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { describe, expect, it, vi } from 'vitest'import type { EngineAdapter } from '../../engine/engine-adapter'@@ -13,6 +17,7 @@ import type { EventBus } from '../../events/event-bus'import type { Logger } from '../../logger'import type { MagnetTracker } from '../../torrent/magnet-tracker'import type { FileCleanupService } from '../file-cleanup-service'+import { FileCleanupServiceImpl } from '../file-cleanup-service'import type { TaskManager } from '../task-manager'import type { TorrentMetaStore } from '../torrent-meta-store'import { type RemoveTaskDeps, removeTask } from './remove-task'@@ -734,3 +739,168 @@ describe('removeTask with magnet_metadata_resolution primary instance', () => {expect(deps.taskPersistence.runExclusivePersistence).toHaveBeenCalledOnce()})})++describe('direct BT output ownership during removal', () => {+ function reservedTask(multiFile = false) {+ const task = makeDownloadTask({+ id: 'partial',+ type: TaskType.Magnet,+ status: TaskStatus.MetadataReady,+ saveDir: '/downloads',+ finalPath: '/downloads',+ finalName: '',+ diskPath: '/tmp/metadata',+ torrentMetaPath: '/meta/partial.torrent',+ })+ task.instances = [+ {+ instanceId: 'meta:partial',+ motrixId: task.id,+ gid: 'old',+ phase: TaskInstancePhase.MagnetMetadataResolution,+ status: TaskStatus.MetadataReady,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: task.diskPath,+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {+ btOutputReservation: {+ finalPath: '/downloads/partial',+ infoHash: 'a'.repeat(40),+ multiFile,+ },+ },+ createdAt: 0,+ updatedAt: 0,+ },+ ]+ return task+ }++ it.each([false, true])(+ 'deletes failed magnet payload with multiFile=%s before its parent',+ async (multiFile) => {+ const deps = makeDeps()+ const task = reservedTask(multiFile)+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ await removeTask(task.id, { deleteWithFiles: true }, deps)+ expect(deps.fileCleanupService.cleanup).toHaveBeenCalledWith(+ '/downloads/partial',+ TaskType.Magnet,+ !multiFile+ )+ expect(deps.torrentMetaStore.remove).toHaveBeenCalledWith(+ task.torrentMetaPath+ )+ expect(+ vi.mocked(deps.fileCleanupService.cleanup).mock.invocationCallOrder[0]+ ).toBeLessThan(vi.mocked(deps.db.deleteTask).mock.invocationCallOrder[0])+ }+ )++ it.each(['engine', 'files'])(+ 'retains a retryable parent when %s cleanup fails',+ async (failure) => {+ const deps = makeDeps()+ const task = reservedTask()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ if (failure === 'engine')+ vi.mocked(deps.magnetTracker.cancel).mockResolvedValue('quarantined')+ else+ vi.mocked(deps.fileCleanupService.cleanup).mockRejectedValue(+ new Error('busy')+ )+ await expect(+ removeTask(task.id, { deleteWithFiles: true }, deps)+ ).rejects.toThrow()+ expect(deps.db.deleteTask).not.toHaveBeenCalled()+ expect(deps.taskManager.remove).not.toHaveBeenCalled()+ expect(deps.magnetTracker.markPendingUserDelete).not.toHaveBeenCalled()+ }+ )++ it('refuses deletion when another task owns the failed output', async () => {+ const deps = makeDeps()+ const task = reservedTask()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.taskManager.getAll).mockReturnValue([+ task,+ makeDownloadTask({+ id: 'other',+ finalName: 'partial',+ finalPath: '/downloads/partial',+ diskPath: '/downloads/partial',+ }),+ ])+ await expect(+ removeTask(task.id, { deleteWithFiles: true }, deps)+ ).rejects.toThrow()+ expect(deps.fileCleanupService.cleanup).not.toHaveBeenCalled()+ expect(deps.db.deleteTask).not.toHaveBeenCalled()+ })++ it('preserves failed output when deleting only the task', async () => {+ const deps = makeDeps()+ const task = reservedTask()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ await removeTask(task.id, { deleteWithFiles: false }, deps)+ expect(deps.fileCleanupService.cleanup).not.toHaveBeenCalled()+ expect(deps.eventBus.emit).toHaveBeenCalledWith(Events.ToastShow, {+ key: 'task.remove.orphanToast',+ params: { path: '/downloads/partial' },+ })+ })++ it('preserves another completed payload named like a single-file control file', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'bt-remove-sidecar-'))+ try {+ const file = path.join(root, 'foo')+ const otherFile = `${file}.aria2`+ await writeFile(file, 'partial')+ await writeFile(otherFile, 'other completed payload')+ const deps = makeDeps({+ fileCleanupService: new FileCleanupServiceImpl({+ removePathRecursive: (p) => rm(p, { recursive: true, force: true }),+ }),+ })+ const task = reservedTask()+ task.type = TaskType.Bt+ task.diskPath = task.finalPath = file+ task.finalName = 'foo'+ task.saveDir = root+ task.instances[0].phase = TaskInstancePhase.BtDownload+ task.instances[0].payload = {+ btStorageLayout: {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'foo',+ multiFile: false,+ finalized: false,+ },+ }+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.taskManager.getAll).mockReturnValue([+ task,+ makeDownloadTask({+ id: 'other',+ status: TaskStatus.Completed,+ finalName: 'foo.aria2',+ finalPath: otherFile,+ diskPath: otherFile,+ saveDir: root,+ }),+ ])+ await removeTask(task.id, { deleteWithFiles: true }, deps)+ await expect(readFile(otherFile, 'utf8')).resolves.toBe(+ 'other completed payload'+ )+ await expect(readFile(file)).rejects.toMatchObject({ code: 'ENOENT' })+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })+})diff --git a/src/core/task/actions/remove-task.ts b/src/core/task/actions/remove-task.tsindex 9424ea4e..556bf0b3 100644--- a/src/core/task/actions/remove-task.ts+++ b/src/core/task/actions/remove-task.ts@@ -1,7 +1,11 @@import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'-import { TaskInstancePhase, TaskStatus } from '@shared/types/task'+import {+ type DownloadTask,+ TaskInstancePhase,+ TaskStatus,+} from '@shared/types/task'import { isStoppedTaskStatus } from '@shared/types/task-actions'import type {TaskInstanceRow,@@ -14,7 +18,13 @@ import {withMagnetCleanupTombstoneHidden,} from '../../torrent/magnet-cleanup-quarantine'import type { MagnetTracker } from '../../torrent/magnet-tracker'+import { getBtOutputReservations } from '../bt-output-reservation'+import {+ getBtDirectStorageLayout,+ parseBtFileLayout,+} from '../bt-storage-layout'import type { FileCleanupService } from '../file-cleanup-service'+import { outputPathIdentity } from '../output-path-identity'import type { TorrentMetaStore } from '../torrent-meta-store'import { getTaskOrWarn, type TaskActionDeps } from './shared'@@ -119,6 +129,27 @@ async function removeTaskUnderMutation(// row can disappear. Keep ownership of that delete in this action.deleteTaskRow: false,})+ // A failed swap owns real payloads. Keep its visible, retryable parent+ // until engine absence and file cleanup have both succeeded.+ const restoredTask = deps.taskManager.getById(taskId) ?? task+ const reservations = getBtOutputReservations(restoredTask)+ if (result !== 'removed' && reservations.length > 0) {+ throw new AppError(+ ErrorCode.MagnetCleanupPending,+ 'BT output cleanup is waiting for engine removal'+ )+ }+ if (result === 'removed' && options.deleteWithFiles) {+ await cleanupReservedOutputs(restoredTask, deps)+ if (restoredTask.torrentMetaPath)+ await deps.torrentMetaStore.remove(restoredTask.torrentMetaPath)+ } else if (result === 'removed' && reservations.length > 0) {+ for (const reservation of reservations)+ deps.eventBus.emit(Events.ToastShow, {+ key: 'task.remove.orphanToast',+ params: { path: reservation.finalPath },+ })+ }const publishRemovalOrQuarantine = (): void => {if (result === 'removed') {deps.db.deleteTask(taskId)@@ -229,8 +260,12 @@ async function removeTaskUnderMutation(isSafeCleanupPath(task.diskPath, task.saveDir)if (shouldDeleteFiles) {+ await cleanupReservedOutputs(task, deps)await Promise.all([- deps.fileCleanupService.cleanup(task.diskPath, task.type),+ getBtDirectStorageLayout(task)?.multiFile === false &&+ !isClaimedByOtherTask(`${task.diskPath}.aria2`, task.id, deps)+ ? deps.fileCleanupService.cleanup(task.diskPath, task.type, true)+ : deps.fileCleanupService.cleanup(task.diskPath, task.type),task.torrentMetaPath? deps.torrentMetaStore.remove(task.torrentMetaPath): Promise.resolve(),@@ -261,6 +296,75 @@ async function removeTaskUnderMutation(deps.publishTaskUpdate()}+function isClaimedByOtherTask(+ candidate: string,+ taskId: string,+ deps: RemoveTaskDeps+): boolean {+ const identity = outputPathIdentity(candidate)+ return deps.taskManager.getAll().some((other) => {+ if (other.id === taskId || other.status === TaskStatus.Removed) return false+ const claimedPaths = [+ ...(other.finalName ? [other.finalPath, other.diskPath] : []),+ ...getBtOutputReservations(other).map((entry) => entry.finalPath),+ ]+ return claimedPaths.some((claimed) => {+ if (!claimed) return false+ const owner = outputPathIdentity(claimed)+ return (+ identity === owner ||+ identity.startsWith(`${owner}${path.sep}`) ||+ owner.startsWith(`${identity}${path.sep}`)+ )+ })+ })+}++async function cleanupReservedOutputs(+ task: DownloadTask,+ deps: RemoveTaskDeps+): Promise<void> {+ const reservations = getBtOutputReservations(task)+ if (reservations.length === 0) return+ // Old reservation rows omitted the shape. Read the durable torrent before+ // removing anything so a missing/corrupt source leaves a retryable owner.+ const parsed =+ reservations.some((entry) => typeof entry.multiFile !== 'boolean') &&+ task.torrentMetaPath+ ? await parseBtFileLayout(+ await deps.torrentMetaStore.read(task.torrentMetaPath)+ )+ : null+ for (const reservation of reservations) {+ if (+ !isSafeCleanupPath(reservation.finalPath, task.saveDir) ||+ isClaimedByOtherTask(reservation.finalPath, task.id, deps)+ ) {+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'BT output cleanup path overlaps another owner or the save root'+ )+ }+ if (+ typeof reservation.multiFile !== 'boolean' &&+ parsed?.infoHash !== reservation.infoHash+ )+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'BT output cleanup requires matching torrent metadata'+ )+ }+ for (const reservation of reservations) {+ const singleFile = (reservation.multiFile ?? parsed?.multiFile) === false+ await deps.fileCleanupService.cleanup(+ reservation.finalPath,+ task.type,+ singleFile &&+ !isClaimedByOtherTask(`${reservation.finalPath}.aria2`, task.id, deps)+ )+ }+}+function isSafeCleanupPath(diskPath: string, saveDir?: string): boolean {if (diskPath.trim() === '' || !path.isAbsolute(diskPath)) return falseconst normalized = path.resolve(diskPath)@@ -274,7 +378,7 @@ function isSafeCleanupPath(diskPath: string, saveDir?: string): boolean {if (saveDir &&saveDir.trim() !== '' &&- normalized === path.resolve(saveDir)+ outputPathIdentity(normalized) === outputPathIdentity(saveDir)) {return false}diff --git a/src/core/task/bt-direct-storage.integration.test.ts b/src/core/task/bt-direct-storage.integration.test.tsnew file mode 100644index 00000000..b18a832d--- /dev/null+++ b/src/core/task/bt-direct-storage.integration.test.ts@@ -0,0 +1,235 @@+// @vitest-environment node++import { createHash } from 'node:crypto'+import {+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ rm,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { TaskStatus } from '@shared/types/task'+import {+ type Aria2Handle,+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { afterEach, describe, expect, it } from 'vitest'+import {+ createBtDirectStoragePlan,+ parseBtFileLayout,+} from './bt-storage-layout'++type BencodeValue =+ | string+ | number+ | Buffer+ | BencodeValue[]+ | { [key: string]: BencodeValue }++function encode(value: BencodeValue): Buffer {+ if (typeof value === 'number') return Buffer.from(`i${value}e`)+ if (Array.isArray(value))+ return Buffer.concat([+ Buffer.from('l'),+ ...value.map(encode),+ Buffer.from('e'),+ ])+ if (typeof value === 'string' || Buffer.isBuffer(value)) {+ const bytes = Buffer.from(value)+ return Buffer.concat([Buffer.from(`${bytes.length}:`), bytes])+ }+ return Buffer.concat([+ Buffer.from('d'),+ ...Object.keys(value)+ .sort()+ .flatMap((key) => [encode(key), encode(value[key])]),+ Buffer.from('e'),+ ])+}++describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'direct BT output (real aria2)',+ () => {+ let root: string | undefined+ let handle: Aria2Handle | undefined+ let disconnect: (() => void) | undefined++ afterEach(async () => {+ disconnect?.()+ await handle?.kill()+ if (root) await rm(root, { recursive: true, force: true })+ })++ it.each([false, true])(+ 'checks and seeds final files with multiFile=%s',+ async (multiFile) => {+ root = await mkdtemp(path.join(tmpdir(), 'motrix-bt-direct-'))+ const first = Buffer.from('first payload')+ const second = Buffer.from('second payload')+ const data = multiFile ? Buffer.concat([first, second]) : first+ const info: { [key: string]: BencodeValue } = {+ name: 'original',+ 'piece length': 16384,+ pieces: createHash('sha1').update(data).digest(),+ ...(multiFile+ ? {+ files: [+ { length: first.length, path: ['nested', 'first.bin'] },+ { length: second.length, path: ['second.bin'] },+ ],+ }+ : { length: first.length }),+ }+ const metadata = encode({ info })+ const finalPath = path.join(+ root,+ multiFile ? 'Chosen folder' : 'chosen.bin'+ )+ const plan = createBtDirectStoragePlan(+ finalPath,+ await parseBtFileLayout(metadata),+ path.join(root, 'metadata', 'task.torrent')+ )+ if (multiFile) {+ await mkdir(path.join(finalPath, 'nested'), { recursive: true })+ await writeFile(path.join(finalPath, 'nested', 'first.bin'), first)+ await writeFile(path.join(finalPath, 'second.bin'), second)+ } else await writeFile(finalPath, first)+ handle = await spawnAria2ForTest({+ baseDir: root,+ extraArgs: [+ '--seed-time=60',+ '--seed-ratio=0',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ ],+ })+ const wired = await connectAdapter(handle)+ disconnect = wired.disconnect+ const params = {+ metadata,+ saveDir: plan.saveDir,+ outputFilePaths: plan.outputFilePaths,+ outputRoot: plan.outputRoot,+ checkIntegrity: true,+ seedTime: 60,+ seedRatio: 0,+ }+ const gid = await wired.adapter.addTorrent(params)+ await expect+ .poll(async () => (await wired.adapter.getTaskStatus(gid))?.status, {+ timeout: 10000,+ })+ .toBe(TaskStatus.Seeding)+ const files = await wired.adapter.getTaskFiles(gid)+ expect(files.map((file) => file.path)).toEqual(+ multiFile+ ? [+ path.join(finalPath, 'nested', 'first.bin'),+ path.join(finalPath, 'second.bin'),+ ]+ : [finalPath]+ )+ expect(+ (await readdir(root)).some(+ (name) => name === '.motrix' || name.endsWith('.motrix')+ )+ ).toBe(false)+ expect(await readFile(files[0].path)).toEqual(first)+ // Rechecking the same paths after removing the engine identity must+ // discover the completed bytes instead of allocating another output.+ await wired.adapter.forceRemoveTask(gid)+ await wired.adapter.removeDownloadResult(gid)+ const retryGid = await wired.adapter.addTorrent(params)+ await expect+ .poll(+ async () => (await wired.adapter.getTaskStatus(retryGid))?.status,+ { timeout: 10000 }+ )+ .toBe(TaskStatus.Seeding)+ expect(+ (await wired.adapter.getTaskFiles(retryGid)).map((file) => file.path)+ ).toEqual(files.map((file) => file.path))+ },+ 25000+ )+ }+)++it.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'seeds payload whose name matches an aria2 control file',+ async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-bt-control-'))+ let handle: Aria2Handle | undefined+ let disconnect: (() => void) | undefined+ try {+ const first = Buffer.from('payload that must remain intact')+ const second = Buffer.from('second payload')+ const metadata = encode({+ info: {+ name: 'bundle',+ 'piece length': 16384,+ pieces: createHash('sha1')+ .update(Buffer.concat([first, second]))+ .digest(),+ files: [+ { length: first.length, path: ['bundle.aria2'] },+ { length: second.length, path: ['second.bin'] },+ ],+ },+ })+ const finalPath = path.join(root, 'Chosen folder')+ const parsed = await parseBtFileLayout(metadata)+ const plan = createBtDirectStoragePlan(+ finalPath,+ parsed,+ path.join(root, 'metadata', 'task.torrent')+ )+ const payloadRoot = finalPath+ await mkdir(payloadRoot, { recursive: true })+ await writeFile(path.join(payloadRoot, 'bundle.aria2'), first)+ await writeFile(path.join(payloadRoot, 'second.bin'), second)+ handle = await spawnAria2ForTest({+ baseDir: root,+ extraArgs: [+ '--seed-time=60',+ '--seed-ratio=0',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ ],+ })+ const wired = await connectAdapter(handle)+ disconnect = wired.disconnect+ const gid = await wired.adapter.addTorrent({+ metadata,+ ...plan,+ checkIntegrity: true,+ seedTime: 60,+ seedRatio: 0,+ })+ await expect+ .poll(+ async () => {+ const task = await wired.adapter.getTaskStatus(gid)+ return `${task?.status}:${task?.errorMessage ?? ''}`+ },+ { timeout: 10000 }+ )+ .toBe('seeding:')+ expect(await readFile(path.join(payloadRoot, 'bundle.aria2'))).toEqual(+ first+ )+ } finally {+ disconnect?.()+ await handle?.kill()+ await rm(root, { recursive: true, force: true })+ }+ },+ 25000+)diff --git a/src/core/task/bt-duplicate-policy.test.ts b/src/core/task/bt-duplicate-policy.test.tsindex 854cb0ea..1ae13036 100644--- a/src/core/task/bt-duplicate-policy.test.ts+++ b/src/core/task/bt-duplicate-policy.test.ts@@ -234,3 +234,27 @@ it('normalizes base32 BTIH values to the canonical hexadecimal identity', () =>INFO_HASH)})++it('reserves all failed magnet targets even outside the original save root', () => {+ const task = btTask({+ id: 'partial',+ status: TaskStatus.MetadataReady,+ type: TaskType.Magnet,+ })+ task.instances[0].payload = {+ btOutputReservation: { finalPath: '/new/current', infoHash: INFO_HASH },+ btOutputReservations: [+ { finalPath: '/old/earlier', infoHash: INFO_HASH, multiFile: true },+ { finalPath: '/new/current', infoHash: INFO_HASH, multiFile: false },+ ],+ }+ expect(reservedBtFinalNames([task], '/new')).toEqual([+ 'current',+ 'current.aria2',+ ])+ expect(reservedBtFinalNames([task], '/old')).toEqual([+ 'earlier',+ 'earlier.aria2',+ ])+ expect(reservedBtFinalNames([task], '/new', task.id)).toEqual([])+})diff --git a/src/core/task/bt-duplicate-policy.ts b/src/core/task/bt-duplicate-policy.tsindex a5ed6951..574aefaf 100644--- a/src/core/task/bt-duplicate-policy.ts+++ b/src/core/task/bt-duplicate-policy.ts@@ -6,6 +6,9 @@ import type {} from '@shared/schemas/add-task'import type { DownloadTask } from '@shared/types/task'import { TaskInstancePhase, TaskStatus, TaskType } from '@shared/types/task'+import { getBtOutputReservations } from './bt-output-reservation'+import { getBtDirectStorageLayout } from './bt-storage-layout'+import { outputPathIdentity } from './output-path-identity'const HEX_INFO_HASH_RE = /^[a-f0-9]{40}$/iconst BASE32_INFO_HASH_RE = /^[a-z2-7]{32}$/i@@ -21,6 +24,24 @@ export async function acquireBtInfoHashAdmission(infoHash: string): Promise<() => void> {const key = normalizeBtInfoHash(infoHash) ?? infoHash.toLowerCase()+ return acquireBtAdmission(`hash:${key}`)+}++/** Final outputs cannot be shared by concurrently admitted torrents. */+export async function withBtOutputAdmission<T>(+ saveDir: string,+ operation: () => Promise<T>+): Promise<T> {+ const key = canonicalBtPath(saveDir)+ const release = await acquireBtAdmission(`output:${key}`)+ try {+ return await operation()+ } finally {+ release()+ }+}++async function acquireBtAdmission(key: string): Promise<() => void> {const previous = admissionTails.get(key) ?? Promise.resolve()let releaseCurrent!: () => voidconst current = new Promise<void>((resolve) => {@@ -190,13 +211,23 @@ export function reservedBtFinalNames(const targetDir = canonicalBtPath(saveDir)return tasks.filter(- (task) =>- task.id !== excludeTaskId &&- task.status !== TaskStatus.Removed &&- task.finalName.length > 0 &&- btTaskTargetDir(task) === targetDir+ (task) => task.id !== excludeTaskId && task.status !== TaskStatus.Removed)- .map((task) => task.finalName)+ .flatMap((task) => {+ const names: string[] = []+ if (task.finalName && btTaskTargetDir(task) === targetDir) {+ names.push(task.finalName)+ if (getBtDirectStorageLayout(task)?.multiFile === false)+ names.push(`${task.finalName}.aria2`)+ }+ for (const reservation of getBtOutputReservations(task)) {+ if (canonicalBtPath(path.dirname(reservation.finalPath)) !== targetDir)+ continue+ const name = path.basename(reservation.finalPath)+ names.push(name, `${name}.aria2`)+ }+ return names+ })}export function existingFilesConflict(@@ -263,8 +294,7 @@ export function btTaskTargetDir(task: DownloadTask): string {}export function canonicalBtPath(value: string): string {- const resolved = path.resolve(value)- return process.platform === 'win32' ? resolved.toLowerCase() : resolved+ return outputPathIdentity(value)}function normalizeSelection(values: readonly number[]): number[] {diff --git a/src/core/task/bt-output-admission.integration.test.ts b/src/core/task/bt-output-admission.integration.test.tsnew file mode 100644index 00000000..18bfcbda--- /dev/null+++ b/src/core/task/bt-output-admission.integration.test.ts@@ -0,0 +1,202 @@+// @vitest-environment node+import {+ access,+ mkdir,+ mkdtemp,+ readFile,+ rm,+ writeFile,+} from 'node:fs/promises'+import { createServer } from 'node:http'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { TaskStatus, TaskType } from '@shared/types/task'+import {+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { makeDownloadTask } from '@test-utils/task'+import { expect, it } from 'vitest'+import {+ reservedBtFinalNames,+ withBtOutputAdmission,+} from './bt-duplicate-policy'+import {+ createBtDirectStoragePlan,+ parseBtFileLayout,+} from './bt-storage-layout'+import { FileCleanupServiceImpl } from './file-cleanup-service'+import { FinalNamePickerImpl } from './final-name-picker'++async function exists(p: string) {+ try {+ await access(p)+ return true+ } catch {+ return false+ }+}++it('deleting a new single-file BT preserves another payload named foo.aria2', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'bt-sibling-review-'))+ try {+ const other = path.join(root, 'foo.aria2')+ await writeFile(other, 'another completed download')+ const picker = new FinalNamePickerImpl({ exists })+ const chosen = await picker.pick(root, 'foo', ['foo.aria2'], true)+ expect(chosen).toBe('foo (1)')+ const cleanup = new FileCleanupServiceImpl({+ removePathRecursive: (p) => rm(p, { recursive: true, force: true }),+ })+ await cleanup.cleanup(path.join(root, chosen), TaskType.Bt, true)+ await expect(readFile(other, 'utf8')).resolves.toBe(+ 'another completed download'+ )+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})++it('reserves case-insensitive pending BT output names', async (ctx) => {+ const root = await mkdtemp(path.join(tmpdir(), 'bt-case-review-'))+ try {+ const probe = path.join(root, 'CASE-PROBE')+ await writeFile(probe, 'x')+ if (!(await exists(path.join(root, 'case-probe')))) ctx.skip()+ await rm(probe)+ const picker = new FinalNamePickerImpl({ exists })+ const firstName = await withBtOutputAdmission(root, () =>+ picker.pick(root, 'Bundle')+ )+ const first = makeDownloadTask({+ id: 'first',+ type: TaskType.Bt,+ status: TaskStatus.Queued,+ infoHash: 'a'.repeat(40),+ saveDir: root,+ finalName: firstName,+ finalPath: path.join(root, firstName),+ diskPath: path.join(root, firstName),+ })+ const plan = createBtDirectStoragePlan(+ first.finalPath,+ {+ infoHash: 'a'.repeat(40),+ torrentRootName: 'Bundle',+ multiFile: true,+ isPrivate: false,+ files: [{ fileIndex: 0, pathInsideRoot: 'data.bin' }],+ },+ path.join(root, 'meta', 'first.torrent')+ )+ await mkdir(plan.saveDir, { recursive: true })+ expect(await exists(first.finalPath)).toBe(false)+ const secondName = await withBtOutputAdmission(root, () =>+ picker.pick(root, 'bundle', reservedBtFinalNames([first], root))+ )+ expect(secondName.toLowerCase()).not.toBe(firstName.toLowerCase())+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})++it.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'real queued torrents must not share a case-aliased output',+ async (ctx) => {+ const root = await mkdtemp(path.join(tmpdir(), 'bt-queued-review-'))+ let handle: Awaited<ReturnType<typeof spawnAria2ForTest>> | undefined+ let disconnect: (() => void) | undefined+ const entered = Promise.withResolvers<void>()+ const server = createServer((_req, _res) => entered.resolve())+ try {+ await writeFile(path.join(root, 'CASE'), 'x')+ if (!(await exists(path.join(root, 'case')))) ctx.skip()+ await rm(path.join(root, 'CASE'))+ await new Promise<void>((resolve) =>+ server.listen(0, '127.0.0.1', resolve)+ )+ const port = (server.address() as { port: number }).port+ handle = await spawnAria2ForTest({+ baseDir: root,+ extraArgs: [+ '--max-concurrent-downloads=1',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ ],+ })+ const wired = await connectAdapter(handle)+ disconnect = wired.disconnect+ await wired.adapter.createDownload({+ uris: [`http://127.0.0.1:${port}/hold`],+ saveDir: root,+ filename: 'blocker',+ })+ await entered.promise+ const picker = new FinalNamePickerImpl({ exists })+ const metadata = (name: string) =>+ Buffer.concat([+ Buffer.from(+ `d4:infod5:filesld6:lengthi1e4:pathl8:data.bineee4:name${name.length}:${name}12:piece lengthi16384e6:pieces20:`+ ),+ Buffer.alloc(20),+ Buffer.from('ee'),+ ])+ const firstMetadata = metadata('Bundle')+ const parsed = await parseBtFileLayout(firstMetadata)+ const firstName = await picker.pick(root, 'Bundle')+ const firstPath = path.join(root, firstName)+ const firstPlan = createBtDirectStoragePlan(+ firstPath,+ parsed,+ path.join(root, 'meta', 'first.torrent')+ )+ const firstGid = await wired.adapter.addTorrent({+ metadata: firstMetadata,+ ...firstPlan,+ })+ await expect+ .poll(async () => (await wired.adapter.getTaskStatus(firstGid))?.status)+ .toBe(TaskStatus.Queued)+ expect(await exists(firstPath)).toBe(false)+ const first = makeDownloadTask({+ id: 'first',+ type: TaskType.Bt,+ status: TaskStatus.Queued,+ infoHash: parsed.infoHash,+ saveDir: root,+ finalPath: firstPath,+ finalName: firstName,+ diskPath: firstPath,+ })+ const secondName = await picker.pick(+ root,+ 'bundle',+ reservedBtFinalNames([first], root)+ )+ const secondMetadata = metadata('bundle')+ const secondPlan = createBtDirectStoragePlan(+ path.join(root, secondName),+ await parseBtFileLayout(secondMetadata),+ path.join(root, 'meta', 'second.torrent')+ )+ const secondGid = await wired.adapter.addTorrent({+ metadata: secondMetadata,+ ...secondPlan,+ })+ const firstFiles = await wired.adapter.getTaskFiles(firstGid)+ const secondFiles = await wired.adapter.getTaskFiles(secondGid)+ expect(secondFiles[0].path.toLowerCase()).not.toBe(+ firstFiles[0].path.toLowerCase()+ )+ } finally {+ disconnect?.()+ await handle?.kill()+ server.closeAllConnections()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ await rm(root, { recursive: true, force: true })+ }+ },+ 15000+)diff --git a/src/core/task/bt-output-reservation.ts b/src/core/task/bt-output-reservation.tsnew file mode 100644index 00000000..ae2b7d6b--- /dev/null+++ b/src/core/task/bt-output-reservation.ts@@ -0,0 +1,41 @@+import path from 'node:path'+import type { DownloadTask } from '@shared/types/task'++export interface BtOutputReservation {+ finalPath: string+ infoHash: string+ multiFile?: boolean+}++/** Includes older single-reservation rows and failed attempts at other targets. */+export function getBtOutputReservations(+ task: Pick<DownloadTask, 'instances'>+): BtOutputReservation[] {+ const reservations = new Map<string, BtOutputReservation>()+ for (const instance of task.instances ?? []) {+ const payload = instance.payload ?? {}+ const values = [+ payload.btOutputReservation,+ ...(Array.isArray(payload.btOutputReservations)+ ? payload.btOutputReservations+ : []),+ ]+ for (const value of values) {+ if (!value || typeof value !== 'object') continue+ const reservation = value as Partial<BtOutputReservation>+ if (+ typeof reservation.finalPath === 'string' &&+ path.isAbsolute(reservation.finalPath) &&+ path.resolve(reservation.finalPath) !==+ path.parse(reservation.finalPath).root &&+ typeof reservation.infoHash === 'string' &&+ /^[a-f0-9]{40}$/i.test(reservation.infoHash)+ )+ reservations.set(+ reservation.finalPath,+ reservation as BtOutputReservation+ )+ }+ }+ return [...reservations.values()]+}diff --git a/src/core/task/bt-storage-layout.test.ts b/src/core/task/bt-storage-layout.test.tsindex 499de7a7..4183c507 100644--- a/src/core/task/bt-storage-layout.test.ts+++ b/src/core/task/bt-storage-layout.test.ts@@ -1,9 +1,10 @@import { readFileSync } from 'node:fs'import path from 'node:path'+import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'import { describe, expect, it } from 'vitest'import {buildFinalOutputFilePaths,- createBtStoragePlan,+ createBtDirectStoragePlan,getBtStorageLayout,parseBtFileLayout,shouldPrioritizeBtPreviewPieces,@@ -25,7 +26,7 @@ function singleFileTorrent(name: string): Uint8Array {)}-describe('BT indexed storage layout', () => {+describe('legacy 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))@@ -112,3 +113,40 @@ describe('BT indexed storage layout', () => {).toBeNull()})})++describe('direct BT storage layout', () => {+ it('writes a single file at its chosen final name from the start', async () => {+ const parsed = await parseBtFileLayout(singleFileTorrent('original.iso'))+ const plan = createBtDirectStoragePlan('/downloads/chosen.iso', parsed)+ expect(plan).toEqual({+ layout: {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'original.iso',+ multiFile: false,+ finalized: false,+ },+ saveDir: '/downloads',+ outputFilePaths: [{ fileIndex: 0, relativePath: 'chosen.iso' }],+ })+ })++ it('separates multi-file payloads from engine control files', async () => {+ const parsed = await parseBtFileLayout(+ new Uint8Array(readFileSync(FIXTURE_PATH))+ )+ const plan = createBtDirectStoragePlan(+ '/downloads/Chosen folder',+ parsed,+ '/metadata/task.torrent'+ )+ expect(plan.saveDir).toBe('/metadata/task.torrent.state')+ expect(plan.outputRoot).toBe('/downloads/Chosen folder')+ expect(plan.outputFilePaths).toEqual([+ { fileIndex: 0, relativePath: path.join('video', 'movie.mkv') },+ { fileIndex: 1, relativePath: 'readme.txt' },+ { fileIndex: 2, relativePath: 'cover.jpg' },+ ])+ expect(plan.layout).not.toHaveProperty('workspacePath')+ })+})diff --git a/src/core/task/bt-storage-layout.ts b/src/core/task/bt-storage-layout.tsindex 97880764..8570b179 100644--- a/src/core/task/bt-storage-layout.ts+++ b/src/core/task/bt-storage-layout.ts@@ -17,10 +17,105 @@ export interface BtStorageLayoutV1 {multiFile: boolean}+export interface BtDirectStorageLayout {+ version: 2+ strategy: 'direct'+ /** Null means the engine owns the paths inside the final container. */+ torrentRootName: string | null+ multiFile: boolean | null+ finalized: boolean+}++export function createBtDirectStoragePlan(+ finalPath: string,+ parsed: ParsedBtFileLayout | null,+ torrentMetaPath?: string | null+) {+ const layout: BtDirectStorageLayout = {+ version: 2,+ strategy: 'direct',+ torrentRootName: parsed?.torrentRootName ?? null,+ multiFile: parsed?.multiFile ?? null,+ finalized: false,+ }+ return {+ layout,+ ...buildBtDirectOutputPaths(finalPath, parsed, torrentMetaPath),+ }+}++/** Keep engine metadata separate while payloads go directly to final paths. */+export function buildBtDirectOutputPaths(+ finalPath: string,+ parsed: ParsedBtFileLayout | null,+ torrentMetaPath?: string | null+): {+ saveDir: string+ outputRoot?: string+ outputFilePaths?: BtOutputFilePath[]+} {+ if (!parsed) return { saveDir: finalPath }+ if (!parsed.multiFile)+ return {+ saveDir: path.dirname(finalPath),+ outputFilePaths: buildFinalOutputFilePaths(parsed, finalPath),+ }+ if (!torrentMetaPath)+ throw new Error('Multi-file BT requires a durable torrent metadata path')+ return {+ saveDir: `${torrentMetaPath}.state`,+ outputRoot: finalPath,+ outputFilePaths: parsed.files.map((file) => {+ if (!file.pathInsideRoot)+ throw new UnsafeTorrentPathError('Multi-file torrent has an empty path')+ return { fileIndex: file.fileIndex, relativePath: file.pathInsideRoot }+ }),+ }+}++export function getBtDirectStorageLayout(+ task: Pick<DownloadTask, 'instances'>+): BtDirectStorageLayout | null {+ for (const instance of task.instances ?? []) {+ const value = instance.payload?.[LAYOUT_KEY] as+ | Partial<BtDirectStorageLayout>+ | undefined+ if (+ value?.version === 2 &&+ value.strategy === 'direct' &&+ typeof value.finalized === 'boolean' &&+ ((value.torrentRootName === null && value.multiFile === null) ||+ (typeof value.torrentRootName === 'string' &&+ isSafePathComponent(value.torrentRootName) &&+ typeof value.multiFile === 'boolean'))+ )+ return value as BtDirectStorageLayout+ }+ return null+}++export function markBtDirectOutputFinalized(task: DownloadTask): void {+ if (!getBtDirectStorageLayout(task)) return+ for (const instance of task.instances) {+ const layout = instance.payload[LAYOUT_KEY]+ if (+ layout &&+ typeof layout === 'object' &&+ 'version' in layout &&+ layout.version === 2+ ) {+ instance.payload = {+ ...instance.payload,+ [LAYOUT_KEY]: { ...layout, finalized: true },+ }+ }+ }+}+export interface BtOutputFilePath {/** Domain-native, zero-based torrent file index. */fileIndex: number- /** Path relative to the engine add operation's saveDir. */+ /** Path relative to outputRoot, or the engine saveDir when absent. */relativePath: string}@@ -33,11 +128,6 @@ export interface ParsedBtFileLayout {files: Array<{ fileIndex: number; pathInsideRoot: string | null }>}-export interface BtStoragePlan {- layout: BtStorageLayoutV1- outputFilePaths: BtOutputFilePath[]-}-export class UnsafeTorrentPathError extends Error {constructor(message: string) {super(message)@@ -47,8 +137,8 @@ export class UnsafeTorrentPathError extends Error {/*** 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.+ * parse-torrent returns root-inclusive paths; validated relative paths are+ * mapped into the selected output directory.*/export async function parseBtFileLayout(metadata: Uint8Array@@ -126,25 +216,6 @@ export async function shouldPrioritizeBtPreviewPiecesFromMetadata(}}-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)@@ -187,7 +258,7 @@ export function buildFinalOutputFilePaths(}export function btStoragePayload(- layout: BtStorageLayoutV1+ layout: BtStorageLayoutV1 | BtDirectStorageLayout): Record<string, unknown> {return { [LAYOUT_KEY]: layout }}diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex b51a8ce1..1c4ba5b2 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -289,6 +289,38 @@ function lastAddedTask(deps: { add: ReturnType<typeof vi.fn> }): DownloadTask {}describe('handleCreateTask', () => {+ it('reserves different final outputs for concurrent torrents with the same chosen name', async () => {+ const deps = makeDeps()+ const owners: DownloadTask[] = []+ deps.add.mockImplementation((task: DownloadTask) => owners.push(task))+ vi.mocked(deps.taskManager.getAll).mockImplementation(() => owners)+ deps.finalNamePicker = new FinalNamePickerImpl({+ exists: async () => false,+ })+ await Promise.all(+ ['first.iso', 'second.iso'].map((name) => {+ const bytes = buildMinimalTorrentBytes(name, false)+ return handleCreateTask(+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: Buffer.from(bytes).toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/d',+ displayName: 'chosen.iso',+ },+ deps+ )+ })+ )+ expect(owners.map((task) => task.diskPath).sort()).toEqual([+ '/d/chosen (1).iso',+ '/d/chosen.iso',+ ])+ expect(owners.every((task) => task.diskPath === task.finalPath)).toBe(true)+ })it('dispatches cookies only to the engine and blocks credential-free probing and replay', async () => {const deps = makeDeps()const probe = vi.fn()@@ -913,19 +945,18 @@ describe('handleCreateTask', () => {)const task = lastAddedTask(deps)expect(task.finalName).toBe('ubuntu-25.10-desktop-amd64.iso')- expect(task.diskPath).toMatch(/^\/d\/\.motrix\/[a-f0-9]{20}$/)+ expect(task.diskPath).toBe(task.finalPath)expect(task.instances[0].payload.btStorageLayout).toMatchObject({- version: 1,- strategy: 'indexed-staging',- workspacePath: task.diskPath,- payloadEntry: 'p',+ version: 2,+ strategy: 'direct',+ finalized: false,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'],+ dir: '/d',+ 'index-out': ['1=ubuntu-25.10-desktop-amd64.iso'],})expect(options).not.toHaveProperty('bt-prioritize-piece')})@@ -1019,7 +1050,7 @@ describe('handleCreateTask', () => {})})-describe('handleCreateTask with incomplete-suffix', () => {+describe('handleCreateTask download paths', () => {it('HTTP task: taskManager receives task with diskPath=.motrix, finalPath clean', async () => {const deps = makeDeps()await handleCreateTask(@@ -1061,7 +1092,7 @@ describe('handleCreateTask with incomplete-suffix', () => {expect(options.out).toBe('foo.mp4.motrix')})- it('BT task: taskManager receives task with diskPath=<saveDir>/<name>.motrix', async () => {+ it('unparsed BT task: persists the final directory without a temporary output', async () => {const deps = makeDeps({persist: async (id) => `/torrents/${id}.torrent`,})@@ -1077,14 +1108,21 @@ describe('handleCreateTask with incomplete-suffix', () => {deps)const task = lastAddedTask(deps)- expect(task.diskPath).toBe('/d/mytorrent.motrix')+ expect(task.diskPath).toBe(task.finalPath)+ expect(task.diskPath).toBe(task.finalPath)+ expect(task.instances[0].diskPath).toBe(task.diskPath)+ expect(task.instances[0].payload.btStorageLayout).toMatchObject({+ version: 2,+ strategy: 'direct',+ torrentRootName: null,+ })expect(task.finalPath).toBe('/d/mytorrent')expect(task.finalName).toBe('mytorrent')expect(task.type).toBe(TaskType.Bt)expect(task.torrentMetaPath).toBe(`/torrents/${task.id}.torrent`)})- it('BT task: aria2 `dir` option points at the .motrix container and `out` is dropped', async () => {+ it('unparsed BT task: aria2 writes into the final directory without an output override', async () => {const deps = makeDeps()await handleCreateTask({@@ -1097,8 +1135,9 @@ describe('handleCreateTask with incomplete-suffix', () => {deps)const [, , options] = deps.addTorrent.mock.calls[0]- expect(options.dir).toBe('/d/mytorrent.motrix')+ expect(options.dir).toBe('/d/mytorrent')expect(options.out).toBeUndefined()+ expect(options).not.toHaveProperty('index-out')})it('Magnet task: derives name from dn= when no displayName provided', async () => {@@ -1117,7 +1156,9 @@ describe('handleCreateTask with incomplete-suffix', () => {)const task = lastAddedTask(deps)expect(task.finalName).toBe('Ubuntu 24.04')- expect(task.diskPath).toBe('/d/Ubuntu 24.04.motrix')+ expect(task.diskPath).toBe(task.finalPath)+ expect(task.instances[0].diskPath).toBe(task.diskPath)+ expect(deps.addUri.mock.calls[0][1].dir).toBe(task.diskPath)expect(task.type).toBe(TaskType.Magnet)// magnet payloads never persist torrentBytesexpect(task.torrentMetaPath).toBeNull()@@ -1716,7 +1757,7 @@ describe('handleCreateTask mkdir target by task type', () => {// — pre-creating the dir is required to keep that write from// silently failing (which would skip the sqlite3 task row and hit a// FK violation on the next pause).- it('BT task: mkdirs the .motrix container (diskPath)', async () => {+ it('BT task: mkdirs the final container (diskPath)', async () => {const deps = makeDeps()await handleCreateTask({@@ -1729,12 +1770,12 @@ describe('handleCreateTask mkdir target by task type', () => {deps)expect(mkdirMock).toHaveBeenCalledTimes(1)- expect(mkdirMock).toHaveBeenCalledWith('/d/mytorrent.motrix', {+ expect(mkdirMock).toHaveBeenCalledWith(lastAddedTask(deps).finalPath, {recursive: true,})})- it('Magnet task: mkdirs the .motrix container (diskPath)', async () => {+ it('Magnet task: mkdirs the final container (diskPath)', async () => {const deps = makeDeps({ addUriGid: 'gid-m' })await handleCreateTask({@@ -1749,7 +1790,7 @@ describe('handleCreateTask mkdir target by task type', () => {deps)expect(mkdirMock).toHaveBeenCalledTimes(1)- expect(mkdirMock).toHaveBeenCalledWith('/d/Ubuntu.motrix', {+ expect(mkdirMock).toHaveBeenCalledWith(lastAddedTask(deps).finalPath, {recursive: true,})})@@ -2816,3 +2857,46 @@ describe('handleCreateTask mux pre-resolve seam', () => {expect(deps.addUri).toHaveBeenCalledOnce()})})++it.each([+ ['foo', 'foo'],+ ['foo', 'foo.aria2'],+ ['foo.motrix', 'foo'],+])('isolates a pending BT %s from HTTP %s', async (btName, httpName) => {+ const deps = makeDeps()+ const owners: DownloadTask[] = []+ deps.add.mockImplementation((task: DownloadTask) => owners.push(task))+ vi.mocked(deps.taskManager.getAll).mockImplementation(() => owners)+ deps.finalNamePicker = new FinalNamePickerImpl({ exists: async () => false })+ const entered = Promise.withResolvers<void>()+ const release = Promise.withResolvers<void>()+ deps.addTorrent.mockImplementationOnce(async (_metadata, _uris, options) => {+ entered.resolve()+ await release.promise+ return options.gid+ })+ const bt = handleCreateTask(+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: Buffer.from(buildMinimalTorrentBytes('source', false)).toString(+ 'base64'+ ),+ },+ selectedFiles: [0],+ saveDir: '/d',+ displayName: btName,+ },+ deps+ )+ await entered.promise+ const http = handleCreateTask({ ...httpRequest(), filename: httpName }, deps)+ await Promise.resolve()+ expect(deps.addUri).not.toHaveBeenCalled()+ release.resolve()+ await Promise.all([bt, http])+ const httpTask = owners.find((task) => task.type === TaskType.Http)!+ expect(httpTask.finalName).not.toBe(httpName)+ expect(httpTask.diskPath).toBe(`${httpTask.finalPath}.motrix`)+})diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex af97abe5..3824cdf4 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -61,11 +61,11 @@ import {inspectBtDuplicate,reservedBtFinalNames,TorrentDuplicateConflictError,+ withBtOutputAdmission,} from './bt-duplicate-policy'import {- type BtStoragePlan,btStoragePayload,- createBtStoragePlan,+ createBtDirectStoragePlan,type ParsedBtFileLayout,parseBtFileLayout,shouldPrioritizeBtPreviewPieces,@@ -246,23 +246,55 @@ export async function handleCreateTask(// Keep a runtime guard for untyped composition code: missing policy// injection must disable metadata I/O instead of consulting newer,// potentially unapplied SettingsManager values.- return policy- ? policy.runWithSnapshot((snapshot, lease) =>- handleCreateTaskUnderAdmission(+ assertHttpTaskSourceAdmission(parsed.data.uris)+ const requestedDir =+ parsed.data.saveDir || deps.settingsManager.getApp().defaultSaveDir+ const preparedDir = deps.prepareSaveDir+ ? await deps.prepareSaveDir(requestedDir)+ : requestedDir+ return withBtOutputAdmission(preparedDir, () =>+ policy+ ? policy.runWithSnapshot((snapshot, lease) =>+ handleCreateTaskUnderAdmission(+ rawRequest,+ deps,+ opts,+ snapshot,+ lease.assertCurrent,+ preparedDir+ )+ )+ : handleCreateTaskUnderAdmission(rawRequest,deps,opts,- snapshot,- lease.assertCurrent+ null,+ undefined,+ preparedDir)- )- : handleCreateTaskUnderAdmission(rawRequest, deps, opts, null)+ )}if (!parsed.success || parsed.data.type !== 'bt') {return handleCreateTaskUnderAdmission(rawRequest, deps, opts)}const req = parsed.data+ const requestedSaveDir =+ req.saveDir || deps.settingsManager.getApp().defaultSaveDir+ const preparedSaveDir = deps.prepareSaveDir+ ? await deps.prepareSaveDir(requestedSaveDir)+ : requestedSaveDir+ const createBtTask = () =>+ withBtOutputAdmission(preparedSaveDir, () =>+ handleCreateTaskUnderAdmission(+ rawRequest,+ deps,+ opts,+ undefined,+ undefined,+ preparedSaveDir+ )+ )let infoHash =req.payload.kind === 'magnet'? extractMagnetInfoHash(req.payload.uri)@@ -275,11 +307,11 @@ export async function handleCreateTask(// The canonical create path below owns parse-error handling and logging.}}- if (!infoHash) return handleCreateTaskUnderAdmission(rawRequest, deps, opts)+ if (!infoHash) return createBtTask()const release = await acquireBtInfoHashAdmission(infoHash)try {- return await handleCreateTaskUnderAdmission(rawRequest, deps, opts)+ return await createBtTask()} finally {release()}@@ -290,7 +322,8 @@ async function handleCreateTaskUnderAdmission(deps: CreateTaskDeps,opts: CreateTaskOptions = {},appliedProxySnapshot?: AppliedDownloadProxySnapshot,- assertAppliedProxyCurrent?: () => void+ assertAppliedProxyCurrent?: () => void,+ preparedSaveDir?: string): Promise<TaskCreateSuccessResult> {const parsed = taskCreateRequestSchema.safeParse(rawRequest)if (!parsed.success) {@@ -307,9 +340,11 @@ async function handleCreateTaskUnderAdmission(if (req.type === 'http') assertHttpTaskSourceAdmission(req.uris)const requestedSaveDir = req.saveDir || appSettings.defaultSaveDir- const effectiveSaveDir = deps.prepareSaveDir- ? await deps.prepareSaveDir(requestedSaveDir)- : requestedSaveDir+ const effectiveSaveDir =+ preparedSaveDir ??+ (deps.prepareSaveDir+ ? await deps.prepareSaveDir(requestedSaveDir)+ : requestedSaveDir)const taskId = newTaskId()log.info(@@ -346,7 +381,7 @@ async function handleCreateTaskUnderAdmission(}log.warn({ err },- 'failed to parse torrent for indexed staging; falling back to legacy layout'+ 'failed to parse torrent paths; using engine paths inside the final directory')}}@@ -392,33 +427,36 @@ async function handleCreateTaskUnderAdmission(btInfoHash &&req.duplicatePolicy === 'reuse' &&deps.finalNamePicker.isTaken &&- (await deps.finalNamePicker.isTaken(effectiveSaveDir, desiredName))+ (await deps.finalNamePicker.isTaken(+ effectiveSaveDir,+ desiredName,+ parsedBtLayout?.multiFile === false+ ))) {throw existingFilesConflict(btInfoHash, effectiveSaveDir)}- const reservedNames =- req.type === 'bt'- ? reservedBtFinalNames(- deps.taskManager.getAll(),- effectiveSaveDir,- req.existingTaskId- )- : undefined+ const reservedNames = reservedBtFinalNames(+ deps.taskManager.getAll(),+ effectiveSaveDir,+ req.type === 'bt' ? req.existingTaskId : undefined+ )+ const pickHttpFinalName = (desired: string) =>+ reservedNames.length > 0+ ? deps.finalNamePicker.pick(effectiveSaveDir, desired, reservedNames)+ : deps.finalNamePicker.pick(effectiveSaveDir, desired)let finalName =req.type === 'bt'? await deps.finalNamePicker.pick(effectiveSaveDir,desiredName,- reservedNames+ reservedNames,+ parsedBtLayout?.multiFile === false)- : await deps.finalNamePicker.pick(effectiveSaveDir, desiredName)+ : await pickHttpFinalName(desiredName)const taskType = deriveTaskType(req)let finalPath = path.join(effectiveSaveDir, finalName)- const btStoragePlan: BtStoragePlan | null = parsedBtLayout- ? createBtStoragePlan(taskId, effectiveSaveDir, parsedBtLayout)- : null- let diskPath = btStoragePlan?.layout.workspacePath ?? toTempPath(finalPath)+ let diskPath = isTorrentLikeType(taskType) ? finalPath : 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.@@ -441,28 +479,16 @@ async function handleCreateTaskUnderAdmission(}}- // 2.5. Pre-create the on-disk slot before handing off to aria2.- // `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- // data-only `MetadataInfo` and the sqlite3 `task` row is never- // written, so the next pause hits a FOREIGN KEY violation when- // `task_progress` is upserted.- // - HTTP/FTP: `diskPath` IS the file aria2 will create- // (`dir = saveDir`, `out = <finalName>.motrix`). mkdir'ing it- // would race with aria2's open(2) for write — the path becomes- // a directory and aria2 fails the task with EISDIR. Pre-create- // `saveDir` instead so aria2's `dir` option is reachable.- // aria2_motrix has the matching mkdirs on its side, so an mkdir- // error here is logged but not fatal — defence-in-depth, not- // single point of failure.- const ensureDir = isTorrentLikeType(taskType) ? diskPath : effectiveSaveDir+ const btStoragePlan = isTorrentLikeType(taskType)+ ? createBtDirectStoragePlan(finalPath, parsedBtLayout, torrentMetaPath)+ : null++ // Create the engine's directory before admission so aria2 can persist its+ // torrent metadata. Multi-file BT uses its private metadata directory and+ // maps every payload into the final output root. Single-file BT uses the+ // destination parent; unresolved BT uses the final container. HTTP keeps+ // its incomplete suffix inside the chosen save root.+ const ensureDir = btStoragePlan?.saveDir ?? effectiveSaveDirtry {await mkdir(ensureDir, { recursive: true })} catch (cause) {@@ -474,7 +500,7 @@ async function handleCreateTaskUnderAdmission(// 3. Build engine-agnostic create params per task family and dispatch// through the EngineAdapter. For HTTP, dir=saveDir and out uses the- // incomplete suffix. For BT/magnet, dir=diskPath and `out` is absent;+ // incomplete suffix. BT uses its final output directory and no `out`;// parsed torrents additionally carry per-file output mappings. The adapter// is responsible for the aria2 wire shape.let pluginMetadataOps: readonly StagedMetadataOp[] = []@@ -534,10 +560,7 @@ async function handleCreateTaskUnderAdmission(let currentHttpDesiredName = desiredNameconst pickHttpName = async (nextDesiredName: string): Promise<void> => {if (nextDesiredName === currentHttpDesiredName) return- finalName = await deps.finalNamePicker.pick(- effectiveSaveDir,- nextDesiredName- )+ finalName = await pickHttpFinalName(nextDesiredName)currentHttpDesiredName = nextDesiredNamefinalPath = path.join(effectiveSaveDir, finalName)diskPath = toTempPath(finalPath)@@ -809,12 +832,12 @@ async function handleCreateTaskUnderAdmission(// are always present on the torrent-base64 path.const params: AddTorrentParams = {metadata: torrentBytes ?? decodeBase64ToBytes(req.payload.base64),- // applyPathOverrides BT equivalent: dir = diskPath, out dropped.- saveDir: diskPath,+ saveDir: btStoragePlan?.saveDir ?? diskPath,// 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,+ outputRoot: btStoragePlan?.outputRoot,dlLimit: req.dlLimit,ulLimit: req.ulLimit,seedRatio: req.seedRatio,diff --git a/src/core/task/file-cleanup-service.test.ts b/src/core/task/file-cleanup-service.test.tsindex f58c6156..0b4b5c76 100644--- a/src/core/task/file-cleanup-service.test.ts+++ b/src/core/task/file-cleanup-service.test.ts@@ -9,6 +9,18 @@ function makeFs() {}describe('FileCleanupService.cleanup', () => {+ it('removes a direct single-file BT output and its adjacent control file', async () => {+ const fs = makeFs()+ await new FileCleanupServiceImpl(fs).cleanup(+ '/d/movie.iso',+ TaskType.Bt,+ true+ )+ expect(fs.removePathRecursive.mock.calls).toEqual([+ ['/d/movie.iso'],+ ['/d/movie.iso.aria2'],+ ])+ })it('HTTP: removes diskPath and .aria2 sidecar', async () => {const fs = makeFs()const svc = new FileCleanupServiceImpl(fs)diff --git a/src/core/task/file-cleanup-service.ts b/src/core/task/file-cleanup-service.tsindex 5b62473b..163567cd 100644--- a/src/core/task/file-cleanup-service.ts+++ b/src/core/task/file-cleanup-service.ts@@ -6,23 +6,33 @@ export interface FsRemover {}export interface FileCleanupService {- cleanup(diskPath: string, taskType: TaskType): Promise<void>+ cleanup(+ diskPath: string,+ taskType: TaskType,+ singleFileBtOutput?: boolean+ ): Promise<void>}export class FileCleanupServiceImpl implements FileCleanupService {constructor(private readonly fs: FsRemover) {}- async cleanup(diskPath: string, taskType: TaskType): Promise<void> {+ async cleanup(+ diskPath: string,+ taskType: TaskType,+ singleFileBtOutput = false+ ): Promise<void> {// Remove the data file or container directoryawait this.fs.removePathRecursive(diskPath)// For HTTP/FTP tasks that still have a .motrix suffix,// also remove the aria2 sidecar sitting next to it.- // BT container dir's sidecars live inside the dir and are+ // Direct single-file BT has an adjacent control file too.+ // BT container directories keep their sidecars inside and are// gone via recursive removal.if (- (taskType === TaskType.Http || taskType === TaskType.Ftp) &&- isTempPath(diskPath)+ singleFileBtOutput ||+ ((taskType === TaskType.Http || taskType === TaskType.Ftp) &&+ isTempPath(diskPath))) {await this.fs.removePathRecursive(`${diskPath}.aria2`)}diff --git a/src/core/task/final-name-picker.test.ts b/src/core/task/final-name-picker.test.tsindex ac36dda7..39b64aa4 100644--- a/src/core/task/final-name-picker.test.ts+++ b/src/core/task/final-name-picker.test.ts@@ -83,3 +83,25 @@ describe('FinalNamePicker.pick', () => {await expect(picker.pick('/d', 'x.txt')).rejects.toThrow(AppError)})})++it.each(['darwin', 'win32'])(+ 'reserves equivalent names on %s',+ async (platform) => {+ vi.stubGlobal('process', { ...process, platform })+ try {+ const picker = new FinalNamePickerImpl(makeFs(new Set()))+ expect(await picker.pick('/d', 'bundle', ['Bundle'])).toBe('bundle (1)')+ expect(await picker.pick('/d', 'Café', ['Cafe\u0301'])).toBe('Café (1)')+ expect(await picker.pick('/d', 'foo', ['FOO.ARIA2'], true)).toBe(+ 'foo (1)'+ )+ } finally {+ vi.unstubAllGlobals()+ }+ }+)++it('avoids an adjacent control path even when it is not a registered task', async () => {+ const picker = new FinalNamePickerImpl(makeFs(new Set(['/d/foo.aria2'])))+ expect(await picker.pick('/d', 'foo', [], true)).toBe('foo (1)')+})diff --git a/src/core/task/final-name-picker.ts b/src/core/task/final-name-picker.tsindex 2a9c98e8..deac56fd 100644--- a/src/core/task/final-name-picker.ts+++ b/src/core/task/final-name-picker.ts@@ -4,6 +4,7 @@ import {MAX_DEDUP_ATTEMPTS,} from '@shared/constants/incomplete'import { AppError, ErrorCode } from '@shared/errors'+import { outputNameIdentity } from './output-path-identity'export interface FsProbe {exists(absPath: string): Promise<boolean>@@ -13,9 +14,14 @@ export interface FinalNamePicker {pick(saveDir: string,desiredName: string,- reservedNames?: readonly string[]+ reservedNames?: readonly string[],+ adjacentControlFile?: boolean): Promise<string>- isTaken?(dir: string, name: string): Promise<boolean>+ isTaken?(+ dir: string,+ name: string,+ adjacentControlFile?: boolean+ ): Promise<boolean>}export class FinalNamePickerImpl implements FinalNamePicker {@@ -24,12 +30,18 @@ export class FinalNamePickerImpl implements FinalNamePicker {async pick(saveDir: string,desiredName: string,- reservedNames: readonly string[] = []+ reservedNames: readonly string[] = [],+ adjacentControlFile = false): Promise<string> {- const reserved = new Set(reservedNames)+ const reserved = new Set(reservedNames.map(outputNameIdentity))+ const isReserved = (name: string): boolean =>+ reserved.has(outputNameIdentity(name)) ||+ reserved.has(outputNameIdentity(`${name}${INCOMPLETE_SUFFIX}`)) ||+ reserved.has(outputNameIdentity(`${name}${INCOMPLETE_SUFFIX}.aria2`)) ||+ (adjacentControlFile && reserved.has(outputNameIdentity(`${name}.aria2`)))if (- !reserved.has(desiredName) &&- !(await this.isTaken(saveDir, desiredName))+ !isReserved(desiredName) &&+ !(await this.isTaken(saveDir, desiredName, adjacentControlFile))) {return desiredName}@@ -39,8 +51,8 @@ export class FinalNamePickerImpl implements FinalNamePicker {for (let n = 1; n <= MAX_DEDUP_ATTEMPTS; n++) {const candidate = ext ? `${base} (${n})${ext}` : `${base} (${n})`if (- !reserved.has(candidate) &&- !(await this.isTaken(saveDir, candidate))+ !isReserved(candidate) &&+ !(await this.isTaken(saveDir, candidate, adjacentControlFile))) {return candidate}@@ -52,14 +64,19 @@ export class FinalNamePickerImpl implements FinalNamePicker {)}- async isTaken(dir: string, name: string): Promise<boolean> {+ async isTaken(+ dir: string,+ name: string,+ adjacentControlFile = false+ ): Promise<boolean> {const finalPath = path.join(dir, name)const tempPath = finalPath + INCOMPLETE_SUFFIX- const [f, t] = await Promise.all([+ const [f, t, c] = await Promise.all([this.fs.exists(finalPath),this.fs.exists(tempPath),+ adjacentControlFile ? this.fs.exists(`${finalPath}.aria2`) : false,])- return f || t+ return f || t || c}}diff --git a/src/core/task/output-path-identity.test.ts b/src/core/task/output-path-identity.test.tsnew file mode 100644index 00000000..cda3126e--- /dev/null+++ b/src/core/task/output-path-identity.test.ts@@ -0,0 +1,38 @@+// @vitest-environment node+import { mkdir, mkdtemp, rm, symlink } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { expect, it } from 'vitest'+import { withBtOutputAdmission } from './bt-duplicate-policy'+import { outputPathIdentity } from './output-path-identity'++it('serializes admissions through a symlink before either output exists', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'bt-output-alias-'))+ try {+ await mkdir(path.join(root, 'real'))+ await symlink(path.join(root, 'real'), path.join(root, 'alias'), 'junction')+ expect(outputPathIdentity(path.join(root, 'real', 'new', 'output'))).toBe(+ outputPathIdentity(path.join(root, 'alias', 'new', 'output'))+ )+ const release = Promise.withResolvers<void>()+ const entered = Promise.withResolvers<void>()+ const order: number[] = []+ const first = withBtOutputAdmission(path.join(root, 'real'), async () => {+ order.push(1)+ entered.resolve()+ await release.promise+ order.push(2)+ })+ await entered.promise+ const second = withBtOutputAdmission(path.join(root, 'alias'), async () => {+ order.push(3)+ })+ await Promise.resolve()+ expect(order).toEqual([1])+ release.resolve()+ await Promise.all([first, second])+ expect(order).toEqual([1, 2, 3])+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/src/core/task/output-path-identity.ts b/src/core/task/output-path-identity.tsnew file mode 100644index 00000000..3895d084--- /dev/null+++ b/src/core/task/output-path-identity.ts@@ -0,0 +1,25 @@+import { realpathSync } from 'node:fs'+import path from 'node:path'++/** Reserve conservatively on hosts that commonly use case-insensitive volumes. */+export function outputNameIdentity(value: string): string {+ return process.platform === 'darwin' || process.platform === 'win32'+ ? value.normalize('NFD').toLowerCase()+ : value+}++/** Resolve existing ancestors as well as aliases to not-yet-created outputs. */+export function outputPathIdentity(value: string): string {+ let ancestor = path.resolve(value)+ const suffix: string[] = []+ while (true) {+ try {+ return outputNameIdentity(path.join(realpathSync(ancestor), ...suffix))+ } catch {+ const parent = path.dirname(ancestor)+ if (parent === ancestor) return outputNameIdentity(path.resolve(value))+ suffix.unshift(path.basename(ancestor))+ ancestor = parent+ }+ }+}diff --git a/src/core/task/should-skip-engine-completion-finalize.test.ts b/src/core/task/should-skip-engine-completion-finalize.test.tsindex 9f430261..07d5eddb 100644--- a/src/core/task/should-skip-engine-completion-finalize.test.ts+++ b/src/core/task/should-skip-engine-completion-finalize.test.ts@@ -1,9 +1,51 @@-import { TaskStatus, TransitionPhase } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it } from 'vitest'import { shouldSkipEngineCompletionFinalize } from './should-skip-engine-completion-finalize'describe('shouldSkipEngineCompletionFinalize', () => {+ it.each([false, true])(+ 'uses the durable BT completion marker when finalized=%s',+ (finalized) => {+ const task = makeDownloadTask({+ diskPath: '/downloads/movie.iso',+ finalPath: '/downloads/movie.iso',+ })+ task.instances = [+ {+ instanceId: 'primary',+ motrixId: task.id,+ gid: task.engineTaskId,+ phase: TaskInstancePhase.BtDownload,+ status: task.status,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: task.diskPath,+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ createdAt: 0,+ updatedAt: 0,+ payload: {+ btStorageLayout: {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'movie.iso',+ multiFile: false,+ finalized,+ },+ },+ },+ ]+ expect(shouldSkipEngineCompletionFinalize(task)).toBe(finalized)+ }+ )it('allows the first completion event for an idle temporary output', () => {expect(shouldSkipEngineCompletionFinalize(diff --git a/src/core/task/should-skip-engine-completion-finalize.ts b/src/core/task/should-skip-engine-completion-finalize.tsindex ead6af7c..a53eb362 100644--- a/src/core/task/should-skip-engine-completion-finalize.ts+++ b/src/core/task/should-skip-engine-completion-finalize.ts@@ -1,10 +1,11 @@import type { DownloadTask } from '@shared/types/task'import { TaskStatus, TransitionPhase } from '@shared/types/task'+import { getBtDirectStorageLayout } from './bt-storage-layout'/*** Engine completion notifications are level-like and may repeat after BT- * reseed or startup. Only a task that has not reached its final path and has- * no durable transition intent may enter finalize from such a notification.+ * reseed or startup. Legacy temporary outputs and direct BT outputs with no+ * committed completion marker may enter finalize while their transition is idle.* Startup recovery invokes finalize directly after inspecting the filesystem,* so quarantined/non-idle tasks remain recoverable without event re-entry.*@@ -16,7 +17,8 @@ export function shouldSkipEngineCompletionFinalize(task: DownloadTask): boolean {return (- task.diskPath === task.finalPath ||+ (task.diskPath === task.finalPath &&+ getBtDirectStorageLayout(task)?.finalized !== false) ||task.status === TaskStatus.Finalizing ||task.transitionPhase !== TransitionPhase.Idle)diff --git a/src/core/task/task-recovery-service.test.ts b/src/core/task/task-recovery-service.test.tsindex dbcb7619..392c6d4e 100644--- a/src/core/task/task-recovery-service.test.ts+++ b/src/core/task/task-recovery-service.test.ts@@ -164,6 +164,57 @@ function makeDeps(overrides: Partial<RecoveryDeps> = {}): RecoveryDeps {}describe('TaskRecoveryServiceImpl.recoverOnStartup', () => {+ it.each([TransitionPhase.Idle, TransitionPhase.Renaming])(+ 'finishes direct BT completion in place after restart from %s',+ async (phase) => {+ const task = makeTask({+ id: 'direct-bt',+ type: TaskType.Bt,+ status: TaskStatus.Seeding,+ transitionPhase: phase,+ diskPath: '/d/movie.iso',+ finalPath: '/d/movie.iso',+ })+ task.instances = [+ {+ instanceId: 'primary',+ motrixId: task.id,+ gid: task.engineTaskId,+ phase: TaskInstancePhase.BtDownload,+ status: task.status,+ progress: 100,+ totalBytes: 1,+ downloadedBytes: 1,+ uploadedBytes: 0,+ diskPath: task.diskPath,+ transitionPhase: phase,+ uris: [],+ uriHash: null,+ createdAt: 0,+ updatedAt: 0,+ payload: {+ btStorageLayout: {+ version: 2,+ strategy: 'direct',+ torrentRootName: 'movie.iso',+ multiFile: false,+ finalized: false,+ },+ },+ },+ ]+ const deps = makeDeps({+ taskManager: { getAll: () => [task], persist: vi.fn(async () => {}) },+ fs: makeFs(new Set(['/d/movie.iso'])),+ })+ const report = await new TaskRecoveryServiceImpl(deps).recoverOnStartup()+ expect(report.recovered).toEqual([+ { taskId: task.id, action: RecoveryAction.ResumeFromRename },+ ])+ expect(deps.finalizeTask).toHaveBeenCalledWith(task.id)+ expect(task.transitionPhase).toBe(phase)+ }+ )it('reports 0 scanned and 0 recovered when no in-flight tasks', async () => {const deps = makeDeps({taskManager: {diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.tsindex 1a809770..d5f7be03 100644--- a/src/core/task/task-recovery-service.ts+++ b/src/core/task/task-recovery-service.ts@@ -16,7 +16,7 @@ import {type TaskTransitionRecordInput,} from './actions/shared'import { applyTerminalTransition } from './apply-terminal-transition'-import { getBtPayloadPath } from './bt-storage-layout'+import { getBtDirectStorageLayout, getBtPayloadPath } from './bt-storage-layout'import { applyDiagnosisUpgrade } from './diagnosis-upgrade'import { fireAfterComplete, fireOnError } from './hook-dispatch'import type { OccurrenceDispatcher } from './occurrences/occurrence-dispatcher'@@ -206,7 +206,10 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {(t) =>(taskId === undefined || t.id === taskId) &&(t.transitionPhase !== TransitionPhase.Idle ||- t.status === TaskStatus.Finalizing)+ t.status === TaskStatus.Finalizing ||+ (getBtDirectStorageLayout(t)?.finalized === false &&+ (t.status === TaskStatus.Seeding ||+ t.status === TaskStatus.Completed))))const inFlight = this.deps.taskManager.set? inFlightPublished.map((task) => structuredClone(task))@@ -340,12 +343,18 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {taskIdsByInfoHash)- const action = determineAction({- phase: task.transitionPhase,- fsState,- aria2HasMatchingInfoHash: matchingGid !== undefined,- taskType: task.type,- })+ const action =+ getBtDirectStorageLayout(task)?.finalized === false &&+ task.transitionPhase !== TransitionPhase.Reseeding &&+ task.diskPath === task.finalPath &&+ fsState === 'final_only'+ ? RecoveryAction.ResumeFromRename+ : determineAction({+ phase: task.transitionPhase,+ fsState,+ aria2HasMatchingInfoHash: matchingGid !== undefined,+ taskType: task.type,+ })await this.applyAction(task, action, fsState, matchingGid, report)}diff --git a/src/core/task/task-row-to-download-task.test.ts b/src/core/task/task-row-to-download-task.test.tsindex 1056b5c1..c37a13f8 100644--- a/src/core/task/task-row-to-download-task.test.ts+++ b/src/core/task/task-row-to-download-task.test.ts@@ -7,8 +7,9 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'import { describe, expect, it } from 'vitest'-import { btStoragePayload, createBtStoragePlan } from './bt-storage-layout'+import { btStoragePayload } from './bt-storage-layout'import { taskRowToDownloadTask } from './task-row-to-download-task'function makeTaskRow(overrides: Partial<TaskRow> = {}): TaskRow {diff --git a/src/core/task/torrent-meta-store.test.ts b/src/core/task/torrent-meta-store.test.tsindex eb90dd73..126a01aa 100644--- a/src/core/task/torrent-meta-store.test.ts+++ b/src/core/task/torrent-meta-store.test.ts@@ -1,4 +1,10 @@-import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs'import { tmpdir } from 'node:os'import path from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'@@ -26,6 +32,16 @@ describe('TorrentMetaStore', () => {expect(Array.from(read)).toEqual([0xde, 0xad, 0xbe, 0xef])})+ it('removes the task-owned engine state with its metadata', async () => {+ const meta = await store.persist('task-state', new Uint8Array([1]))+ mkdirSync(`${meta}.state`)+ writeFileSync(path.join(`${meta}.state`, 'bundle.aria2'), 'state')+ await store.remove(meta)+ expect(() =>+ readFileSync(path.join(`${meta}.state`, 'bundle.aria2'))+ ).toThrow()+ })+it('remove deletes the file', async () => {const bytes = new Uint8Array([0x01])const pathOut = await store.persist('task-2', bytes)diff --git a/src/core/task/torrent-meta-store.ts b/src/core/task/torrent-meta-store.tsindex 3127a5ac..c4aa06f6 100644--- a/src/core/task/torrent-meta-store.ts+++ b/src/core/task/torrent-meta-store.ts@@ -36,5 +36,6 @@ export class TorrentMetaStoreImpl implements TorrentMetaStore {const err = e as NodeJS.ErrnoExceptionif (err.code !== 'ENOENT') throw err}+ await fs.rm(`${metaPath}.state`, { recursive: true, force: true })}}diff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.tsindex 3a341e61..4703279e 100644--- a/src/core/torrent/magnet-tracker.test.ts+++ b/src/core/torrent/magnet-tracker.test.ts@@ -2864,205 +2864,242 @@ describe('MagnetTracker', () => {expect(db.getTask('m-quarantined')).toBeNull()})- it('recovers a failed-swap gid and its artifacts from a durable tombstone after restart', async () => {- const root = await makeTempDir()- const diskPath = path.join(root, 'resolved.motrix')- const torrentMetaPath = path.join(root, 'm-swap-restart.torrent')- await mkdir(diskPath)- await writeFile(path.join(diskPath, 'partial.bin'), 'partial')- await writeFile(torrentMetaPath, 'torrent')-- const originalTask: TaskRow = {- motrixId: 'm-swap-restart',- name: '[METADATA] resolved',- kind: TaskKind.Bt,- taskType: TaskType.Magnet,- category: null,- priority: 0,- tags: null,- createdAt: 1700000000,- updatedAt: 1700000001,- finalPath: root,- finalName: '',- torrentMetaPath: null,- infoHash: null,- totalBytes: 0,- downloadedBytes: 0,- sizeWhenDone: 0,- fileCount: 0,- isPrivate: false,- trackers: [],- pieceLength: 0,- aggStatus: TaskStatus.MetadataReady,- finishedAt: null,- errorMessage: null,- errorCode: null,- errorDetailKey: null,- errorDetailParams: null,- diagnosisRevision: 0,- uploadedBytesBaseline: 0,- source: 'user',- sourceMeta: null,- }- const originalInstance: TaskInstanceRow = {- instanceId: 'meta:m-swap-restart',- motrixId: 'm-swap-restart',- gid: 'g-meta-original',- phase: TaskInstancePhase.MagnetMetadataResolution,- status: TaskStatus.MetadataReady,- progress: 100,- totalBytes: 0,- downloadedBytes: 0,- uploadedBytes: 0,- diskPath: '/tmp/original-metadata',- transitionPhase: TransitionPhase.Idle,- uris: ['magnet:?xt=urn:btih:restart'],- uriHash: null,- payload: { metadataDir: '/tmp/original-metadata' },- createdAt: 1700000000,- updatedAt: 1700000001,- }- const originalFiles: TaskFileRow[] = [- { fileIndex: 7, path: '/old/selection.bin', size: 17, selected: true },- ]- const restoreGraph: TaskWithInstancesAndFiles = {- task: originalTask,- instances: [originalInstance],- files: originalFiles,- }- db.saveTaskWithInstancesAndFiles({- task: {- ...originalTask,- torrentMetaPath,- aggStatus: TaskStatus.Error,- finishedAt: 1700000001,- errorMessage: 'Magnet swap cleanup is quarantined',- },- instances: [- {- ...originalInstance,- gid: 'g-bt-orphan',- status: TaskStatus.Error,- diskPath,- payload: withMagnetCleanupRestoreGraph(- {- metadataDir: diskPath,- cleanupQuarantined: true,- cleanupTombstoneHidden: true,- cleanupArtifactPaths: [diskPath, torrentMetaPath],- },- restoreGraph- ),+ it.each([false, true])(+ 'recovers a failed swap after restart with directOutput=%s',+ async (directOutput) => {+ const root = await makeTempDir()+ const diskPath = path.join(+ root,+ directOutput ? 'resolved' : 'resolved.motrix'+ )+ const torrentMetaPath = path.join(root, 'm-swap-restart.torrent')+ await mkdir(diskPath)+ await writeFile(path.join(diskPath, 'partial.bin'), 'partial')+ await writeFile(torrentMetaPath, 'torrent')++ const originalTask: TaskRow = {+ motrixId: 'm-swap-restart',+ name: '[METADATA] resolved',+ kind: TaskKind.Bt,+ taskType: TaskType.Magnet,+ category: null,+ priority: 0,+ tags: null,+ createdAt: 1700000000,+ updatedAt: 1700000001,+ finalPath: root,+ finalName: '',+ torrentMetaPath: null,+ infoHash: null,+ totalBytes: 0,+ downloadedBytes: 0,+ sizeWhenDone: 0,+ fileCount: 0,+ isPrivate: false,+ trackers: [],+ pieceLength: 0,+ aggStatus: TaskStatus.MetadataReady,+ finishedAt: null,+ errorMessage: null,+ errorCode: null,+ errorDetailKey: null,+ errorDetailParams: null,+ diagnosisRevision: 0,+ uploadedBytesBaseline: 0,+ source: 'user',+ sourceMeta: null,+ }+ const originalInstance: TaskInstanceRow = {+ instanceId: 'meta:m-swap-restart',+ motrixId: 'm-swap-restart',+ gid: 'g-meta-original',+ phase: TaskInstancePhase.MagnetMetadataResolution,+ status: TaskStatus.MetadataReady,+ progress: 100,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/tmp/original-metadata',+ transitionPhase: TransitionPhase.Idle,+ uris: ['magnet:?xt=urn:btih:restart'],+ uriHash: null,+ payload: { metadataDir: '/tmp/original-metadata' },+ createdAt: 1700000000,+ updatedAt: 1700000001,+ }+ const originalFiles: TaskFileRow[] = [+ { fileIndex: 7, path: '/old/selection.bin', size: 17, selected: true },+ ]+ const restoreGraph: TaskWithInstancesAndFiles = {+ task: originalTask,+ instances: [originalInstance],+ files: originalFiles,+ }+ db.saveTaskWithInstancesAndFiles({+ task: {+ ...originalTask,+ torrentMetaPath,+ aggStatus: TaskStatus.Error,+ finishedAt: 1700000001,+ errorMessage: 'Magnet swap cleanup is quarantined',},- ],- files: originalFiles,- })-- const preRestartTracker = createMagnetTracker(- rpc as never,- eventBus as never,- settings as never,- db,- taskManager,- torrentParser,- NOOP_TASK_ACTIVITY_RECORDER,- { torrentMetaDir: root }- )- const cleanupReservation = {- taskId: 'm-swap-restart',- instanceId: 'meta:m-swap-restart',- gid: 'g-bt-orphan',- magnetUri: 'magnet:?xt=urn:btih:restart',- saveDir: root,- metadataDir: diskPath,- torrentMetaPath,- artifactPaths: [diskPath, torrentMetaPath],- restoreGraph,- }- preRestartTracker.reserveFailedSwapCleanup(cleanupReservation)- expect(preRestartTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(true)- expect(- preRestartTracker.observe({- gid: 'g-bt-orphan',- status: 'active',- } as never)- ).toBe(true)- preRestartTracker.releaseFailedSwapCleanup('m-swap-restart', 'g-bt-orphan')- expect(preRestartTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(- false- )+ instances: [+ {+ ...originalInstance,+ gid: 'g-bt-orphan',+ status: TaskStatus.Error,+ diskPath,+ payload: withMagnetCleanupRestoreGraph(+ {+ metadataDir: diskPath,+ cleanupQuarantined: true,+ cleanupTombstoneHidden: true,+ cleanupArtifactPaths: directOutput+ ? []+ : [diskPath, torrentMetaPath],+ },+ restoreGraph+ ),+ },+ ],+ files: originalFiles,+ })- preRestartTracker.registerFailedSwapCleanup({- ...cleanupReservation,- deleteParentOnSuccess: false,- })- expect(preRestartTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(true)- expect(- preRestartTracker.observe({+ const preRestartTracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser,+ NOOP_TASK_ACTIVITY_RECORDER,+ { torrentMetaDir: root }+ )+ const cleanupReservation = {+ taskId: 'm-swap-restart',+ instanceId: 'meta:m-swap-restart',gid: 'g-bt-orphan',- status: 'active',- } as never)- ).toBe(true)- await preRestartTracker.stopAndDrain()-- vi.mocked(db.saveTaskWithInstancesAndFiles).mockImplementationOnce(() => {- throw new Error('restore transaction busy')- })- const restartedTracker = createMagnetTracker(- rpc as never,- eventBus as never,- settings as never,- db,- taskManager,- torrentParser,- NOOP_TASK_ACTIVITY_RECORDER,- { torrentMetaDir: root }- )- restartedTracker.primeFromDatabase()+ magnetUri: 'magnet:?xt=urn:btih:restart',+ saveDir: root,+ metadataDir: diskPath,+ torrentMetaPath,+ artifactPaths: directOutput ? [] : [diskPath, torrentMetaPath],+ restoreGraph,+ }+ preRestartTracker.reserveFailedSwapCleanup(cleanupReservation)+ expect(preRestartTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(+ true+ )+ expect(+ preRestartTracker.observe({+ gid: 'g-bt-orphan',+ status: 'active',+ } as never)+ ).toBe(true)+ preRestartTracker.releaseFailedSwapCleanup(+ 'm-swap-restart',+ 'g-bt-orphan'+ )+ expect(preRestartTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(+ false+ )- expect(restartedTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(true)- expect(- restartedTracker.observe({- gid: 'g-bt-orphan',- status: 'active',- } as never)- ).toBe(true)+ preRestartTracker.registerFailedSwapCleanup({+ ...cleanupReservation,+ deleteParentOnSuccess: false,+ })+ expect(preRestartTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(+ true+ )+ expect(+ preRestartTracker.observe({+ gid: 'g-bt-orphan',+ status: 'active',+ } as never)+ ).toBe(true)+ await preRestartTracker.stopAndDrain()- await expect(- restartedTracker.cancel('m-swap-restart', { deleteTaskRow: false })- ).resolves.toBe('quarantined')+ vi.mocked(db.saveTaskWithInstancesAndFiles).mockImplementationOnce(() => {+ throw new Error('restore transaction busy')+ })+ const restartedTracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser,+ NOOP_TASK_ACTIVITY_RECORDER,+ { torrentMetaDir: root }+ )+ restartedTracker.primeFromDatabase()- expect(rpc.forceRemove).toHaveBeenCalledWith('g-bt-orphan')- expect(rpc.removeDownloadResult).toHaveBeenCalledWith('g-bt-orphan')- expect(restartedTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(true)- expect(db.getTask('m-swap-restart')?.task.aggStatus).toBe(TaskStatus.Error)+ expect(restartedTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(+ true+ )+ expect(+ restartedTracker.observe({+ gid: 'g-bt-orphan',+ status: 'active',+ } as never)+ ).toBe(true)- // The first durable restore failed after engine/artifact cleanup. The- // same cache owner must remain shielded and retry finalization.- expect(vi.getTimerCount()).toBeGreaterThan(0)- await vi.advanceTimersByTimeAsync(5_000)+ await expect(+ restartedTracker.cancel('m-swap-restart', { deleteTaskRow: false })+ ).resolves.toBe('quarantined')- vi.useRealTimers()- await vi.waitFor(async () => {- await expect(access(diskPath)).rejects.toMatchObject({ code: 'ENOENT' })- await expect(access(torrentMetaPath)).rejects.toMatchObject({- code: 'ENOENT',- })- expect(db.getTask('m-swap-restart')).toEqual({- task: originalTask,- instances: [originalInstance],- })- expect(db.getTaskFiles('m-swap-restart')).toEqual(originalFiles)- expect(taskManager.getById('m-swap-restart')).toMatchObject({- id: 'm-swap-restart',- status: TaskStatus.MetadataReady,- createdAt: originalTask.createdAt,- })+ expect(rpc.forceRemove).toHaveBeenCalledWith('g-bt-orphan')+ expect(rpc.removeDownloadResult).toHaveBeenCalledWith('g-bt-orphan')expect(restartedTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(- false+ true)- })- })+ expect(db.getTask('m-swap-restart')?.task.aggStatus).toBe(+ TaskStatus.Error+ )++ // The first durable restore failed after engine/artifact cleanup. The+ // same cache owner must remain shielded and retry finalization.+ expect(vi.getTimerCount()).toBeGreaterThan(0)+ await vi.advanceTimersByTimeAsync(5_000)++ vi.useRealTimers()+ await vi.waitFor(async () => {+ if (directOutput) {+ await expect(+ access(path.join(diskPath, 'partial.bin'))+ ).resolves.toBeUndefined()+ await expect(access(torrentMetaPath)).resolves.toBeUndefined()+ } else {+ await expect(access(diskPath)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(access(torrentMetaPath)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ }+ expect(db.getTask('m-swap-restart')).toEqual({+ task: originalTask,+ instances: [originalInstance],+ })+ expect(db.getTaskFiles('m-swap-restart')).toEqual(originalFiles)+ expect(taskManager.getById('m-swap-restart')).toMatchObject({+ id: 'm-swap-restart',+ status: TaskStatus.MetadataReady,+ createdAt: originalTask.createdAt,+ })+ expect(restartedTracker.hasPendingSwapCleanup('m-swap-restart')).toBe(+ false+ )+ })+ // Cache retirement precedes the last filesystem await. Drain it before+ // asserting preservation so a pending recursive delete cannot pass.+ await restartedTracker.stopAndDrain()+ if (directOutput)+ await expect(+ access(path.join(diskPath, 'partial.bin'))+ ).resolves.toBeUndefined()+ }+ )it('refuses failed-swap artifact paths outside trusted save and torrent roots', async () => {const root = await makeTempDir()diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex 60918229..ea02d231 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -288,7 +288,9 @@ export class MagnetTracker {torrentMetaPath: cleanupTorrentMetaPath,torrentMetaDir: this.lifecycle.torrentMetaDir ?? null,cleanupArtifactPaths,- failedSwapCleanup: isHiddenTombstone && cleanupArtifactPaths.length > 0,+ failedSwapCleanup:+ isHiddenTombstone &&+ (cleanupArtifactPaths.length > 0 || Boolean(restoreGraph)),hiddenTombstone: isHiddenTombstone,restoreGraph: restoreGraph ?? undefined,timeoutMultiplier: metadataTimeoutMultiplier(metaInst.payload),@@ -1774,7 +1776,7 @@ export class MagnetTracker {this.lifecycle.publishTaskUpdate()}}- if (entry.cleanupArtifactPaths.length === 0) {+ if (!entry.failedSwapCleanup && entry.cleanupArtifactPaths.length === 0) {await this.cleanupMetadataDir(entry.metadataDir)}}diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.tsindex b79f4347..4f96c6c5 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.atomicity.test.ts@@ -315,7 +315,7 @@ describe('swapMagnetMetadataForBt atomic commit', () => {payload: {cleanupQuarantined: true,cleanupTombstoneHidden: true,- cleanupArtifactPaths: [path.join(saveDir, 'resolved.torrent.motrix')],+ cleanupArtifactPaths: [],},})expect(db.getTaskFiles(taskId)).toEqual(initialFiles)@@ -332,7 +332,7 @@ describe('swapMagnetMetadataForBt atomic commit', () => {expect.objectContaining({taskId,gid: failedGid,- artifactPaths: [path.join(saveDir, 'resolved.torrent.motrix')],+ artifactPaths: [],}))expect(@@ -343,11 +343,7 @@ describe('swapMagnetMetadataForBt atomic commit', () => {expect(tracking.allEngineGids).toEqual(new Set([failedGid]))await expectPathExists(- path.join(- saveDir,- 'resolved.torrent.motrix',- `${failedGid}.aria2-artifact`- )+ path.join(saveDir, 'resolved.torrent', `${failedGid}.aria2-artifact`))await expectPathExists(path.join(torrentMetaDir, `${taskId}.torrent`))diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.tsindex 5d03d7cc..36654d7d 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts@@ -25,9 +25,11 @@ import {} from './swap-magnet-metadata-for-bt'// Stub node:fs/promises so the swap's `mkdir(diskPath, {recursive:true})`-// (the in-flight .motrix container pre-create) doesn't touch the real FS.+// (the final output directory pre-create) doesn't touch the real FS.const { mkdirMock, rmMock } = vi.hoisted(() => ({- mkdirMock: vi.fn(async () => undefined),+ mkdirMock: vi.fn<(dir: string, options?: unknown) => Promise<void>>(+ async () => {}+ ),rmMock: vi.fn(async () => undefined),}))vi.mock('node:fs/promises', () => ({@@ -330,7 +332,7 @@ describe('swapMagnetMetadataForBt', () => {}beforeEach(() => {- mkdirMock.mockClear()+ mkdirMock.mockReset().mockResolvedValue(undefined)rmMock.mockClear()db = createMockDb()taskManager = createMockTaskManager()@@ -351,7 +353,123 @@ describe('swapMagnetMetadataForBt', () => {})})- it('removes the prepared container when torrent metadata persistence rejects', async () => {+ it('retries metadata persistence failure in the same final directory', async () => {+ const createdDirs = new Set<string>()+ mkdirMock.mockImplementation(async (dir: string) => {+ createdDirs.add(dir)+ })+ const { readFileSync } = await import('node:fs')+ const { FinalNamePickerImpl } = await import('@core/task/final-name-picker')+ const base64 = readFileSync(+ `${__dirname}/__fixtures__/test.torrent`+ ).toString('base64')+ const picker = new FinalNamePickerImpl({+ exists: async (p: string) => createdDirs.has(p),+ })+ const deps = {+ db,+ taskManager,+ adapter: adapter as never,+ magnetTracker: magnetTracker as never as MagnetTracker,+ publishTaskUpdate: () => {},+ publishTaskUpdateNow: () => {},+ finalNamePicker: picker,+ torrentMetaStore: torrentMetaStore as never,+ runTaskMutation: runImmediately,+ runExclusivePersistence: persistImmediately,+ }+ const input = {+ taskId: 'm-mag',+ base64,+ selectedFiles: [0],+ saveDir: '/Downloads',+ name: 'review-bundle',+ }+ torrentMetaStore.persist.mockRejectedValueOnce(new Error('disk full'))+ await expect(swapMagnetMetadataForBt(input, deps)).rejects.toThrow(+ 'disk full'+ )+ expect(createdDirs.has('/Downloads/review-bundle')).toBe(false)+ await expect(swapMagnetMetadataForBt(input, deps)).resolves.toHaveProperty(+ 'taskId',+ 'm-mag'+ )+ })++ it('retries a compensated engine failure against its reserved partial output', async () => {+ const createdDirs = new Set<string>()+ mkdirMock.mockImplementation(async (dir) => {+ createdDirs.add(dir)+ })+ const { readFileSync } = await import('node:fs')+ const { FinalNamePickerImpl } = await import('@core/task/final-name-picker')+ const base64 = readFileSync(+ `${__dirname}/__fixtures__/test.torrent`+ ).toString('base64')+ const picker = new FinalNamePickerImpl({+ exists: async (p) => createdDirs.has(p),+ })+ const deps = {+ db,+ taskManager,+ adapter: adapter as never,+ magnetTracker: magnetTracker as never as MagnetTracker,+ publishTaskUpdate: () => {},+ publishTaskUpdateNow: () => {},+ finalNamePicker: picker,+ torrentMetaStore: torrentMetaStore as never,+ runTaskMutation: runImmediately,+ runExclusivePersistence: persistImmediately,+ }+ const input = {+ taskId: 'm-mag',+ base64,+ selectedFiles: [0],+ saveDir: '/Downloads',+ name: 'partial-bundle',+ }+ adapter.addTorrent.mockImplementationOnce(async () => {+ createdDirs.add('/Downloads/partial-bundle')+ throw new Error('reply lost after creating output')+ })+ await expect(swapMagnetMetadataForBt(input, deps)).rejects.toThrow(+ 'reply lost'+ )+ expect(db.getTask('m-mag')?.task.aggStatus).toBe(TaskStatus.MetadataReady)+ expect(db.getTask('m-mag')?.instances[0].payload).toHaveProperty(+ 'btOutputReservation'+ )+ adapter.addTorrent.mockImplementationOnce(async () => {+ createdDirs.add('/Downloads/other-bundle')+ throw new Error('second reply lost')+ })+ await expect(+ swapMagnetMetadataForBt({ ...input, name: 'other-bundle' }, deps)+ ).rejects.toThrow('second reply lost')+ expect(+ db.getTask('m-mag')?.instances[0].payload.btOutputReservations+ ).toEqual([+ expect.objectContaining({ finalPath: '/Downloads/partial-bundle' }),+ expect.objectContaining({ finalPath: '/Downloads/other-bundle' }),+ ])+ await expect(swapMagnetMetadataForBt(input, deps)).resolves.toHaveProperty(+ 'taskId',+ 'm-mag'+ )+ expect(+ db.getTask('m-mag')?.instances[0].payload.btOutputReservations+ ).toEqual([+ expect.objectContaining({ finalPath: '/Downloads/other-bundle' }),+ ])+ expect(adapter.addTorrent).toHaveBeenLastCalledWith(+ expect.objectContaining({+ outputRoot: '/Downloads/partial-bundle',+ checkIntegrity: true,+ })+ )+ })++ it('does not create a container when torrent metadata persistence rejects', async () => {torrentMetaStore.persist.mockRejectedValueOnce(new Error('torrent metadata write failed'))@@ -384,10 +502,7 @@ describe('swapMagnetMetadataForBt', () => {expect(adapter.addTorrent).not.toHaveBeenCalled()expect(magnetTracker.cancel).not.toHaveBeenCalled()expect(magnetTracker.reserveFailedSwapCleanup).not.toHaveBeenCalled()- expect(rmMock).toHaveBeenCalledWith('/Downloads/m-mag.motrix', {- recursive: true,- force: true,- })+ expect(rmMock).not.toHaveBeenCalled()expect(db.getTask('m-mag')).toMatchObject({task: {taskType: TaskType.Magnet,@@ -549,13 +664,15 @@ describe('swapMagnetMetadataForBt', () => {const firstSwap = swapMagnetMetadataForBt(input, deps)await cancelStarted.promiseconst duplicateSwap = swapMagnetMetadataForBt(input, deps)- await vi.waitFor(() => {- expect(- admission.calls.length === 2 ||- magnetTracker.cancel.mock.calls.length === 2- ).toBe(true)- })- releaseCancel.resolve()+ try {+ await Promise.resolve()+ // Output admission precedes task admission, so the queued confirmation+ // cannot hold the task lock while waiting for the destination directory.+ expect(admission.calls).toEqual([['m-mag']])+ expect(magnetTracker.cancel).toHaveBeenCalledTimes(1)+ } finally {+ releaseCancel.resolve()+ }const [first, duplicate] = await Promise.allSettled([firstSwap,@@ -951,10 +1068,7 @@ describe('swapMagnetMetadataForBt', () => {expect(adapter.forceRemoveTask).toHaveBeenCalledWith(reservedGid)expect(adapter.removeDownloadResult).toHaveBeenCalledWith(reservedGid)expect(torrentMetaStore.remove).not.toHaveBeenCalled()- expect(rmMock).toHaveBeenCalledWith('/Downloads/m-mag.motrix', {- recursive: true,- force: true,- })+ expect(rmMock).not.toHaveBeenCalled()})it('restores and retires when result purge proves absence after force-remove fails', async () => {@@ -1061,7 +1175,7 @@ describe('swapMagnetMetadataForBt', () => {)})- it('writes into a .motrix container, persists the path trio + torrent meta, and shows type BT', async () => {+ it('uses the final directory for unparsed metadata and persists BT recovery paths', async () => {// Mirrors createTaskHandler's BT branch. The pre-fix swap passed the bare// saveDir to aria2 (files loose in ~/Downloads, no in-flight container),// left finalPath=saveDir / finalName='' / torrentMetaPath=null — which@@ -1091,18 +1205,25 @@ describe('swapMagnetMetadataForBt', () => {})- // aria2's dir is the in-flight container, NOT the bare saveDir.+ const finalPath = '/Downloads/Movie'+ // The engine writes directly into the final container.expect(adapter.addTorrent).toHaveBeenCalledWith(- expect.objectContaining({ saveDir: '/Downloads/Movie.motrix' })+ expect.objectContaining({ saveDir: finalPath }))+ expect(adapter.addTorrent.mock.calls[0][0].outputFilePaths).toBeUndefined()// Container is pre-created so aria2's <dir>/<sha1>.torrent write succeeds.- expect(mkdirMock).toHaveBeenCalledWith('/Downloads/Movie.motrix', {+ expect(mkdirMock).toHaveBeenCalledWith(finalPath, {recursive: true,})const after = db.getTask('m-mag')- expect(after?.instances[0].diskPath).toBe('/Downloads/Movie.motrix')- // Path trio set so finalize renames container -> final on completion.+ expect(after?.instances[0].diskPath).toBe(finalPath)+ expect(after?.instances[0].payload.btStorageLayout).toMatchObject({+ version: 2,+ strategy: 'direct',+ torrentRootName: null,+ })+ // The download uses its final path from creation through completion.expect(after?.task.finalPath).toBe('/Downloads/Movie')expect(after?.task.finalName).toBe('Movie')// torrentMetaPath persisted so reseed / reAdd don't throw meta-missing.@@ -1116,7 +1237,7 @@ describe('swapMagnetMetadataForBt', () => {expect(tmTask.type).toBe(TaskType.Bt)})- it('uses indexed staging and persists a changed destination after magnet metadata resolves', async () => {+ it('maps files directly to a changed destination after magnet metadata resolves', async () => {const torrent = buildSingleFileTorrent('very-long-original-name.iso')const original = db.getTask('m-mag')if (!original) throw new Error('missing fixture')@@ -1147,17 +1268,21 @@ describe('swapMagnetMetadataForBt', () => {)const params = adapter.addTorrent.mock.calls[0][0]- expect(params.saveDir).toMatch(/^\/Selected\/\.motrix\/[a-f0-9]{20}$/)+ expect(params.saveDir).toBe('/Selected')+ expect(db.getTask('m-mag')?.instances[0].diskPath).toBe(+ '/Selected/User friendly name.iso'+ )expect(db.getTask('m-mag')?.task.saveDir).toBe('/Selected')expect(taskManager.getById('m-mag')?.saveDir).toBe('/Selected')expect(params.outputFilePaths).toEqual([- { fileIndex: 0, relativePath: 'p' },+ { fileIndex: 0, relativePath: 'User friendly name.iso' },])expect(db.getTask('m-mag')?.instances[0].payload.btStorageLayout).toMatchObject({- workspacePath: params.saveDir,- payloadEntry: 'p',+ version: 2,+ strategy: 'direct',+ finalized: false,torrentRootName: 'very-long-original-name.iso',})expect(params.prioritizePreviewPieces).toBeUndefined()diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.ts b/src/core/torrent/swap-magnet-metadata-for-bt.tsindex c2df981b..62de799b 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.ts@@ -1,5 +1,5 @@import { randomBytes } from 'node:crypto'-import { mkdir, rm } from 'node:fs/promises'+import { mkdir } from 'node:fs/promises'import path from 'node:path'import type { EngineAdapter } from '@core/engine/engine-adapter'import { getLogger } from '@core/logger'@@ -13,18 +13,22 @@ import type { TaskTransitionRecordInput } from '@core/task/actions/shared'import {existingFilesConflict,reservedBtFinalNames,+ withBtOutputAdmission,} from '@core/task/bt-duplicate-policy'+import { getBtOutputReservations } from '@core/task/bt-output-reservation'import {- type BtStoragePlan,btStoragePayload,- createBtStoragePlan,+ createBtDirectStoragePlan,type ParsedBtFileLayout,parseBtFileLayout,shouldPrioritizeBtPreviewPieces,UnsafeTorrentPathError,} from '@core/task/bt-storage-layout'import type { FinalNamePicker } from '@core/task/final-name-picker'-import { toTempPath } from '@core/task/paths'+import {+ outputNameIdentity,+ outputPathIdentity,+} from '@core/task/output-path-identity'import type { TaskManager } from '@core/task/task-manager'import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'import { restoreTaskSaveDirectory } from '@core/task/task-save-directory'@@ -107,8 +111,10 @@ export async function swapMagnetMetadataForBt(input: SwapMagnetMetadataInput,deps: SwapMagnetMetadataDeps): Promise<TaskCreateSuccessResult> {- return deps.runTaskMutation([input.taskId], () =>- swapMagnetMetadataForBtUnderMutation(input, deps)+ return withBtOutputAdmission(input.saveDir, () =>+ deps.runTaskMutation([input.taskId], () =>+ swapMagnetMetadataForBtUnderMutation(input, deps)+ ))}@@ -192,9 +198,8 @@ 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, a short- // indexed workspace when metadata is valid, and durable `.torrent` bytes.- let btStoragePlan: BtStoragePlan | null = null+ // Mirror createTaskHandler's BT branch: collision-safe final output,+ // indexed paths when metadata is valid, and durable `.torrent` bytes.let parsedBtLayout: ParsedBtFileLayout | null = nulltry {parsedBtLayout = await parseBtFileLayout(torrentBytes)@@ -208,54 +213,82 @@ async function swapMagnetMetadataForBtUnderMutation(}log.warn({ err, taskId },- 'failed to parse resolved magnet metadata for indexed staging; using legacy layout'+ 'failed to parse resolved magnet paths; using engine paths inside the final directory')}const desiredName = (name ?? existing.task.name).replace(METADATA_NAME_PREFIX,'')+ const reservedNames = reservedBtFinalNames(+ taskManager.getAll(),+ saveDir,+ taskId+ )+ const previousReservations = getBtOutputReservations(originalDownloadTask)+ const reservation = previousReservations.find(+ (entry) =>+ outputPathIdentity(entry.finalPath) ===+ outputPathIdentity(path.join(saveDir, desiredName))+ )+ const reuseOutput =+ duplicatePolicy === 'reuse' &&+ parsedBtLayout !== null &&+ reservation?.infoHash === parsedBtLayout.infoHash &&+ reservation !== undefined &&+ !reservedNames.some(+ (reserved) =>+ outputNameIdentity(reserved) === outputNameIdentity(desiredName) ||+ (parsedBtLayout.multiFile === false &&+ outputNameIdentity(reserved) ===+ outputNameIdentity(`${desiredName}.aria2`))+ )if (parsedBtLayout &&duplicatePolicy === 'reuse' &&+ !reuseOutput &&finalNamePicker.isTaken &&- (await finalNamePicker.isTaken(saveDir, desiredName))+ (await finalNamePicker.isTaken(+ saveDir,+ desiredName,+ parsedBtLayout.multiFile === false+ ))) {throw existingFilesConflict(parsedBtLayout.infoHash, saveDir)}- const finalName = await finalNamePicker.pick(- saveDir,- desiredName,- reservedBtFinalNames(taskManager.getAll(), saveDir, taskId)- )- const finalPath = path.join(saveDir, finalName)- if (parsedBtLayout) {- btStoragePlan = createBtStoragePlan(taskId, saveDir, parsedBtLayout)- }- const diskPath = btStoragePlan?.layout.workspacePath ?? toTempPath(finalPath)- let torrentMetaPath: string- try {- await mkdir(diskPath, { recursive: true })-- // Persist the .torrent bytes so finalize's reseed + reAddTask can recover- // them (both read torrentMetaPath); the pre-fix swap left it null and- // threw TaskFinalizeMetaMissing on completion.- torrentMetaPath = await torrentMetaStore.persist(taskId, torrentBytes)- } catch (cause) {- // Preparation precedes the durable GID reservation, so there is no- // tombstone/retry owner yet. Remove a directory that mkdir may have- // created before rejecting (or that was left after metadata persistence- // failed) so a retry does not acquire a collision-suffixed final name.- try {- await rm(diskPath, { recursive: true, force: true })- } catch (cleanupError) {- log.error(- { err: cleanupError, diskPath, taskId },- 'failed to remove prepared download directory after preparation failure'+ const finalName = reuseOutput+ ? desiredName+ : await finalNamePicker.pick(+ saveDir,+ desiredName,+ reservedNames,+ parsedBtLayout?.multiFile === false)- }- throw cause- }+ const finalPath = path.join(saveDir, finalName)+ const diskPath = finalPath+ const outputReservations = [+ ...previousReservations.filter(+ (entry) =>+ outputPathIdentity(entry.finalPath) !== outputPathIdentity(finalPath)+ ),+ ...(parsedBtLayout+ ? [+ {+ finalPath,+ infoHash: parsedBtLayout.infoHash,+ multiFile: parsedBtLayout.multiFile,+ },+ ]+ : []),+ ]+ // Persist metadata before creating any output or stopping metadata resolution.+ const torrentMetaPath = await torrentMetaStore.persist(taskId, torrentBytes)+ const btStoragePlan = createBtDirectStoragePlan(+ finalPath,+ parsedBtLayout,+ torrentMetaPath+ )+ await mkdir(btStoragePlan.saveDir, { recursive: true })// Make the durable `.torrent` a part of the MetadataReady rollback graph// before cancelling the old metadata GID. cancel() removes metadataDir; a@@ -269,7 +302,22 @@ async function swapMagnetMetadataForBtUnderMutation(saveDir: restoreTaskSaveDirectory(existing.task, existing.instances),torrentMetaPath,},- instances: existing.instances,+ instances: existing.instances.map((instance) => ({+ ...instance,+ payload: {+ ...instance.payload,+ ...(parsedBtLayout+ ? {+ btOutputReservation: {+ finalPath,+ infoHash: parsedBtLayout.infoHash,+ multiFile: parsedBtLayout.multiFile,+ },+ btOutputReservations: outputReservations,+ }+ : {}),+ },+ })),files: existingFiles,}const previousDownloadTask = taskRowToDownloadTask(@@ -344,9 +392,9 @@ async function swapMagnetMetadataForBtUnderMutation(}// The fallback torrent belongs to previousGraph now. Failed-swap cleanup- // removes only the new `.motrix` container; deleting torrentMetaPath would+ // preserves output files; deleting torrentMetaPath would// restore a MetadataReady row whose only readable selection source is gone.- const artifactPaths = [diskPath]+ const artifactPaths: string[] = []const newGid = randomBytes(8).toString('hex')const now = Date.now()// The confirmation dialog lets the user change saveDir after metadata@@ -379,8 +427,8 @@ async function swapMagnetMetadataForBtUnderMutation(withMagnetCleanupTombstoneHidden(withMagnetCleanupQuarantined({- ...previousMetadataInstance.payload,- ...(btStoragePlan ? btStoragePayload(btStoragePlan.layout) : {}),+ ...previousGraph.instances[0].payload,+ ...btStoragePayload(btStoragePlan.layout),metadataDir: diskPath,},true@@ -485,7 +533,12 @@ async function swapMagnetMetadataForBtUnderMutation(transitionPhase: TransitionPhase.Idle,uris: [],uriHash: null,- payload: btStoragePlan ? btStoragePayload(btStoragePlan.layout) : {},+ payload: {+ ...btStoragePayload(btStoragePlan.layout),+ btOutputReservations: outputReservations.filter(+ (entry) => entry.finalPath !== finalPath+ ),+ },createdAt: now,updatedAt: now,}@@ -532,12 +585,14 @@ async function swapMagnetMetadataForBtUnderMutation(try {const addedGid = await adapter.addTorrent({metadata: torrentBytes,- saveDir: diskPath,+ saveDir: btStoragePlan.saveDir,gid: newGid,// 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,+ outputFilePaths: btStoragePlan.outputFilePaths,+ outputRoot: btStoragePlan.outputRoot,+ checkIntegrity: reuseOutput,pause: false,isPrivate: parsedBtLayout?.isPrivate ?? false,...(parsedBtLayout && shouldPrioritizeBtPreviewPieces(parsedBtLayout)@@ -839,13 +894,8 @@ async function rollbackPreparedSwapBeforeMetadataCancel(async function cleanupPreparedSwapArtifacts(artifacts: Omit<FailedSwapArtifacts, 'adapter' | 'gid'>): Promise<void> {- const {- diskPath,- torrentMetaStore,- torrentMetaPath,- previousTorrentMetaPath,- taskId,- } = artifacts+ const { torrentMetaStore, torrentMetaPath, previousTorrentMetaPath, taskId } =+ artifactsif (torrentMetaPath !== previousTorrentMetaPath) {try {@@ -857,14 +907,6 @@ async function cleanupPreparedSwapArtifacts()}}- try {- await rm(diskPath, { recursive: true, force: true })- } catch (err) {- log.error(- { err, diskPath, taskId },- 'failed to remove prepared download directory after reservation rejection'- )- }}async function compensateFailedSwap(@@ -873,7 +915,6 @@ async function compensateFailedSwap(const {adapter,gid,- diskPath,torrentMetaStore,torrentMetaPath,previousTorrentMetaPath,@@ -916,15 +957,5 @@ async function compensateFailedSwap(}}- try {- await rm(diskPath, { recursive: true, force: true })- } catch (err) {- artifactCleanupComplete = false- log.error(- { err, diskPath, taskId },- 'failed magnet swap could not remove its download artifact'- )- }-return { complete: artifactCleanupComplete }}diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 82c402ef..55c90f90 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -518,13 +518,14 @@ describe('buildCommandHandlers', () => {expect(result).toMatchObject({gid: expect.stringMatching(/^[0-9a-f]{16}$/),})- // createTaskHandler writes BT tasks to <saveDir>/<finalName>.motrix as- // the container dir (incomplete-suffix). Assert the dir is rooted at- // the fallback /tmp path.+ // Unresolved BT writes directly inside its final container under the+ // fallback save root.expect(ctx.rpcClient.addUri).toHaveBeenCalledWith(['magnet:?xt=x'],expect.objectContaining({- dir: expect.stringMatching(/^\/tmp\/.+\.motrix$/) as unknown as string,+ dir: expect.stringMatching(+ /^\/tmp\/(?!.*\.motrix$).+$/+ ) as unknown as string,gid: result?.gid,}))diff --git a/src/test-utils/legacy-bt-storage.ts b/src/test-utils/legacy-bt-storage.tsnew file mode 100644index 00000000..15ac13a6--- /dev/null+++ b/src/test-utils/legacy-bt-storage.ts@@ -0,0 +1,26 @@+import {+ type BtStorageLayoutV1,+ btWorkspacePath,+ buildStagingOutputFilePaths,+ type ParsedBtFileLayout,+} from '@core/task/bt-storage-layout'++/** Construct persisted pre-retirement layouts for compatibility regressions. */+export function createBtStoragePlan(+ taskId: string,+ saveDir: string,+ parsed: ParsedBtFileLayout+) {+ const layout: BtStorageLayoutV1 = {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath: btWorkspacePath(taskId, saveDir),+ payloadEntry: 'p',+ torrentRootName: parsed.torrentRootName,+ multiFile: parsed.multiFile,+ }+ return {+ layout,+ outputFilePaths: buildStagingOutputFilePaths(parsed, layout),+ }+}