A full-featured download manager.
fix(bt): prevent duplicate torrent tasks and path conflicts (#1939)
Dr_rOota6efe1ef5d06
diff --git a/src/core/task/bt-duplicate-policy.test.ts b/src/core/task/bt-duplicate-policy.test.tsnew file mode 100644index 00000000..854cb0ea--- /dev/null+++ b/src/core/task/bt-duplicate-policy.test.ts@@ -0,0 +1,236 @@+import path from 'node:path'+import {+ type DownloadTask,+ makeDefaultBtExtension,+ makeDownloadTask,+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { describe, expect, it } from 'vitest'+import {+ inspectBtDuplicate,+ normalizeBtInfoHash,+ reservedBtFinalNames,+} from './bt-duplicate-policy'++const INFO_HASH = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'++function btTask(+ overrides: Partial<DownloadTask> & Pick<DownloadTask, 'id' | 'status'>+): DownloadTask {+ const saveDir = overrides.saveDir ?? '/downloads'+ const finalName = overrides.finalName ?? 'sample-data'+ const now = 1+ return makeDownloadTask({+ ...overrides,+ id: overrides.id,+ engineTaskId: `${overrides.id}-gid`,+ name: finalName,+ kind: TaskKind.Bt,+ type: overrides.type ?? TaskType.Bt,+ status: overrides.status,+ saveDir,+ createdAt: now,+ updatedAt: now,+ filename: finalName,+ diskPath: overrides.diskPath ?? path.join(saveDir, '.motrix', overrides.id),+ finalPath: overrides.finalPath ?? path.join(saveDir, finalName),+ finalName,+ infoHash: INFO_HASH,+ bt: makeDefaultBtExtension({ selectedFiles: [0, 2] }),+ source: 'user',+ sourceMeta: null,+ instances: [+ {+ instanceId: `primary:${overrides.id}`,+ motrixId: overrides.id,+ gid: `${overrides.id}-gid`,+ phase:+ overrides.type === TaskType.Magnet+ ? TaskInstancePhase.MagnetMetadataResolution+ : TaskInstancePhase.BtDownload,+ status: overrides.status,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath:+ overrides.diskPath ?? path.join(saveDir, '.motrix', overrides.id),+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: now,+ updatedAt: now,+ },+ ],+ })+}++describe('inspectBtDuplicate', () => {+ it('reuses an exact active task without starting another info hash owner', () => {+ const task = btTask({ id: 'seed', status: TaskStatus.Seeding })++ expect(+ inspectBtDuplicate([task], {+ infoHash: INFO_HASH.toUpperCase(),+ saveDir: '/downloads',+ selectedFiles: [2, 0, 2],+ duplicatePolicy: 'reuse',+ })+ ).toEqual({ action: 'reuse', task, recheck: false })+ })++ it('reuses a completed task through an integrity recheck', () => {+ const task = btTask({ id: 'done', status: TaskStatus.Completed })++ expect(+ inspectBtDuplicate([task], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [0, 2],+ duplicatePolicy: 'reuse',+ })+ ).toEqual({ action: 'reuse', task, recheck: true })+ })++ it('does not recheck a terminal duplicate while a legacy live owner exists', () => {+ const completed = btTask({ id: 'done', status: TaskStatus.Completed })+ const active = btTask({+ id: 'active-other-dir',+ status: TaskStatus.Downloading,+ saveDir: '/other',+ finalPath: '/other/sample-data',+ })++ expect(+ inspectBtDuplicate([completed, active], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [0, 2],+ duplicatePolicy: 'reuse',+ })+ ).toMatchObject({+ action: 'conflict',+ conflict: {+ reason: 'active-info-hash',+ existingTaskId: active.id,+ canCreateCopy: false,+ },+ })+ })++ it('requires an explicit copy for a different selection in one directory', () => {+ const task = btTask({ id: 'done', status: TaskStatus.Completed })++ const result = inspectBtDuplicate([task], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [1],+ duplicatePolicy: 'reuse',+ })++ expect(result).toMatchObject({+ action: 'conflict',+ conflict: {+ reason: 'selection-mismatch',+ existingTaskId: 'done',+ canCreateCopy: true,+ },+ })+ })++ it('blocks an independent copy while aria2 has the info hash registered', () => {+ const task = btTask({+ id: 'active-other-dir',+ status: TaskStatus.Downloading,+ saveDir: '/other',+ finalPath: '/other/sample-data',+ })++ const result = inspectBtDuplicate([task], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [0, 2],+ duplicatePolicy: 'create-copy',+ })++ expect(result).toMatchObject({+ action: 'conflict',+ conflict: { reason: 'active-info-hash', canCreateCopy: false },+ })+ })++ it('treats an Error owner as registered until retry or removal cleans it', () => {+ const task = btTask({+ id: 'quarantined-error',+ status: TaskStatus.Error,+ saveDir: '/other',+ finalPath: '/other/sample-data',+ })++ expect(+ inspectBtDuplicate([task], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [0, 2],+ duplicatePolicy: 'create-copy',+ })+ ).toMatchObject({+ action: 'conflict',+ conflict: { reason: 'active-info-hash', canCreateCopy: false },+ })+ })++ it('allows the same content in a different directory after it is terminal', () => {+ const task = btTask({+ id: 'done-other-dir',+ status: TaskStatus.Completed,+ saveDir: '/other',+ finalPath: '/other/sample-data',+ })++ expect(+ inspectBtDuplicate([task], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [0, 2],+ duplicatePolicy: 'reuse',+ })+ ).toEqual({ action: 'create' })+ })++ it('allows a different directory after metadata-only aria2 cleanup', () => {+ const task = btTask({+ id: 'metadata-ready-other-dir',+ status: TaskStatus.MetadataReady,+ type: TaskType.Magnet,+ saveDir: '/other',+ finalName: '',+ finalPath: '/other',+ })++ expect(+ inspectBtDuplicate([task], {+ infoHash: INFO_HASH,+ saveDir: '/downloads',+ selectedFiles: [0, 2],+ duplicatePolicy: 'reuse',+ })+ ).toEqual({ action: 'create' })+ })+})++it('reserves final names that are still hidden in indexed workspaces', () => {+ const task = btTask({ id: 'hidden', status: TaskStatus.Downloading })+ expect(reservedBtFinalNames([task], '/downloads')).toEqual(['sample-data'])+})++it('normalizes base32 BTIH values to the canonical hexadecimal identity', () => {+ expect(normalizeBtInfoHash('UA7D7GQFGQNKGNXJ3HJ7A2ZTZXNP4C64')).toBe(+ INFO_HASH+ )+})diff --git a/src/core/task/bt-duplicate-policy.ts b/src/core/task/bt-duplicate-policy.tsnew file mode 100644index 00000000..a5ed6951--- /dev/null+++ b/src/core/task/bt-duplicate-policy.ts@@ -0,0 +1,276 @@+import path from 'node:path'+import { AppError, ErrorCode } from '@shared/errors'+import type {+ TaskCreateCommandResult,+ TorrentDuplicateConflict,+} from '@shared/schemas/add-task'+import type { DownloadTask } from '@shared/types/task'+import { TaskInstancePhase, TaskStatus, TaskType } from '@shared/types/task'++const HEX_INFO_HASH_RE = /^[a-f0-9]{40}$/i+const BASE32_INFO_HASH_RE = /^[a-z2-7]{32}$/i+const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'+const admissionTails = new Map<string, Promise<void>>()++/**+ * Serialize inspection plus engine admission for one content identity. aria2+ * registers info hashes globally, so two otherwise-valid requests must not+ * both observe an empty TaskManager before either publishes its owner.+ */+export async function acquireBtInfoHashAdmission(+ infoHash: string+): Promise<() => void> {+ const key = normalizeBtInfoHash(infoHash) ?? infoHash.toLowerCase()+ const previous = admissionTails.get(key) ?? Promise.resolve()+ let releaseCurrent!: () => void+ const current = new Promise<void>((resolve) => {+ releaseCurrent = resolve+ })+ admissionTails.set(key, current)+ await previous++ let released = false+ return () => {+ if (released) return+ released = true+ releaseCurrent()+ if (admissionTails.get(key) === current) admissionTails.delete(key)+ }+}++export class TorrentDuplicateConflictError extends AppError {+ constructor(public readonly conflict: TorrentDuplicateConflict) {+ super(+ ErrorCode.TorrentDuplicateConflict,+ `Torrent duplicate conflict: ${conflict.reason}`+ )+ this.name = 'TorrentDuplicateConflictError'+ }+}++export function taskCreateConflictResult(+ error: unknown+): Extract<TaskCreateCommandResult, { outcome: 'conflict' }> | null {+ return error instanceof TorrentDuplicateConflictError+ ? { outcome: 'conflict', conflict: error.conflict }+ : null+}++export type BtDuplicateAdmission =+ | { action: 'create' }+ | { action: 'reuse'; task: DownloadTask; recheck: boolean }+ | { action: 'conflict'; conflict: TorrentDuplicateConflict }++export interface InspectBtDuplicateInput {+ infoHash: string+ saveDir: string+ selectedFiles: readonly number[]+ duplicatePolicy: 'reuse' | 'create-copy'+ excludeTaskId?: string+}++/** Normalize a magnet/torrent BTIH to the 40-character domain form. */+export function normalizeBtInfoHash(value: string): string | null {+ const trimmed = value.trim()+ if (HEX_INFO_HASH_RE.test(trimmed)) return trimmed.toLowerCase()+ if (!BASE32_INFO_HASH_RE.test(trimmed)) return null++ let bits = 0+ let bitCount = 0+ const bytes: number[] = []+ for (const char of trimmed.toUpperCase()) {+ const digit = BASE32_ALPHABET.indexOf(char)+ if (digit < 0) return null+ bits = (bits << 5) | digit+ bitCount += 5+ while (bitCount >= 8) {+ bitCount -= 8+ bytes.push((bits >> bitCount) & 0xff)+ bits &= (1 << bitCount) - 1+ }+ }+ if (bytes.length !== 20) return null+ return bytes.map((byte) => byte.toString(16).padStart(2, '0')).join('')+}++export function extractMagnetInfoHash(uri: string): string | null {+ try {+ const params = new URL(uri).searchParams+ for (const xt of params.getAll('xt')) {+ const match = /^urn:btih:(.+)$/i.exec(xt)+ if (match) return normalizeBtInfoHash(match[1])+ }+ } catch {+ // Invalid magnet URIs are rejected by the request schema/engine path.+ }+ return null+}++export function inspectBtDuplicate(+ tasks: readonly DownloadTask[],+ input: InspectBtDuplicateInput+): BtDuplicateAdmission {+ const infoHash = normalizeBtInfoHash(input.infoHash)+ if (!infoHash) return { action: 'create' }+ const targetDir = canonicalBtPath(input.saveDir)+ const requestedSelection = normalizeSelection(input.selectedFiles)+ const candidates = tasks.filter(+ (task) =>+ task.id !== input.excludeTaskId &&+ normalizeBtInfoHash(task.infoHash ?? '') === infoHash &&+ task.status !== TaskStatus.Removed+ )+ if (candidates.length === 0) return { action: 'create' }++ const sameDir = candidates.filter(+ (task) => btTaskTargetDir(task) === targetDir+ )+ const exact = sameDir.find((task) => {+ const existingSelection = normalizeSelection(task.bt?.selectedFiles ?? [])+ return (+ requestedSelection.length > 0 &&+ selectionsEqual(existingSelection, requestedSelection)+ )+ })++ if (+ input.duplicatePolicy === 'reuse' &&+ exact &&+ exact.status !== TaskStatus.Error &&+ isBtInfoHashRegistered(exact)+ ) {+ return {+ action: 'reuse',+ task: exact,+ recheck: false,+ }+ }++ // A terminal exact match is reusable only when no other legacy duplicate+ // still owns the hash in aria2. This matters for pre-policy databases that+ // may already contain both an errored/completed row and a live downloader.+ const active = candidates.find(+ (task) => task.id !== exact?.id && isBtInfoHashRegistered(task)+ )+ if (active) {+ return conflict('active-info-hash', infoHash, targetDir, active, false)+ }++ if (+ input.duplicatePolicy === 'reuse' &&+ exact &&+ (exact.status === TaskStatus.Completed || exact.status === TaskStatus.Error)+ ) {+ return { action: 'reuse', task: exact, recheck: true }+ }++ const exactOrOtherActive = candidates.find(isBtInfoHashRegistered)+ if (exactOrOtherActive) {+ return conflict(+ 'active-info-hash',+ infoHash,+ targetDir,+ exactOrOtherActive,+ false+ )+ }++ if (input.duplicatePolicy === 'reuse' && sameDir.length > 0) {+ return conflict('selection-mismatch', infoHash, targetDir, sameDir[0], true)+ }++ return { action: 'create' }+}++export function reservedBtFinalNames(+ tasks: readonly DownloadTask[],+ saveDir: string,+ excludeTaskId?: string+): string[] {+ const targetDir = canonicalBtPath(saveDir)+ return tasks+ .filter(+ (task) =>+ task.id !== excludeTaskId &&+ task.status !== TaskStatus.Removed &&+ task.finalName.length > 0 &&+ btTaskTargetDir(task) === targetDir+ )+ .map((task) => task.finalName)+}++export function existingFilesConflict(+ infoHash: string,+ targetDir: string+): TorrentDuplicateConflictError {+ const normalized = normalizeBtInfoHash(infoHash) ?? infoHash.toLowerCase()+ return new TorrentDuplicateConflictError({+ reason: 'existing-files',+ infoHash: normalized,+ targetDir: canonicalBtPath(targetDir),+ existingTaskId: null,+ existingTaskName: null,+ existingTaskStatus: null,+ canCreateCopy: true,+ })+}++function conflict(+ reason: TorrentDuplicateConflict['reason'],+ infoHash: string,+ targetDir: string,+ task: DownloadTask,+ canCreateCopy: boolean+): BtDuplicateAdmission {+ return {+ action: 'conflict',+ conflict: {+ reason,+ infoHash,+ targetDir,+ existingTaskId: task.id,+ existingTaskName: task.name,+ existingTaskStatus: task.status,+ canCreateCopy,+ },+ }+}++export function isBtInfoHashRegistered(task: DownloadTask): boolean {+ // MetadataReady has already purged its metadata-only aria2 result. Error is+ // deliberately conservative: a quarantined metadata cleanup can expose an+ // Error task while its engine row is still alive, so a new owner must wait+ // for retry/removal instead of gambling on aria2 accepting the hash.+ return ![+ TaskStatus.Completed,+ TaskStatus.MetadataReady,+ TaskStatus.Removed,+ ].includes(task.status)+}++export function btTaskTargetDir(task: DownloadTask): string {+ const metadataOnly =+ task.type === TaskType.Magnet &&+ task.instances.some(+ (instance) =>+ instance.phase === TaskInstancePhase.MagnetMetadataResolution+ )+ if (metadataOnly && !task.finalName) {+ return canonicalBtPath(task.finalPath || task.saveDir)+ }+ if (task.finalPath) return canonicalBtPath(path.dirname(task.finalPath))+ return canonicalBtPath(task.saveDir)+}++export function canonicalBtPath(value: string): string {+ const resolved = path.resolve(value)+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved+}++function normalizeSelection(values: readonly number[]): number[] {+ return [...new Set(values)].sort((a, b) => a - b)+}++function selectionsEqual(a: readonly number[], b: readonly number[]): boolean {+ return a.length === b.length && a.every((value, index) => value === b[index])+}diff --git a/src/core/task/bt-storage-layout.ts b/src/core/task/bt-storage-layout.tsindex 723b81d9..b1abf083 100644--- a/src/core/task/bt-storage-layout.ts+++ b/src/core/task/bt-storage-layout.ts@@ -24,6 +24,8 @@ export interface BtOutputFilePath {}export interface ParsedBtFileLayout {+ /** Canonical lowercase hexadecimal BitTorrent content identity. */+ infoHash: stringtorrentRootName: stringmultiFile: booleanisPrivate: boolean@@ -51,6 +53,12 @@ export async function parseBtFileLayout(metadata: Uint8Array): Promise<ParsedBtFileLayout> {const parsed = await parseTorrent(metadata)+ if (+ typeof parsed.infoHash !== 'string' ||+ !/^[a-f0-9]{40}$/i.test(parsed.infoHash)+ ) {+ throw new UnsafeTorrentPathError('Torrent contains no valid info hash')+ }const torrentRootName = validatePathComponent(parsed.name, 'torrent name')const parsedFiles = parsed.files ?? []if (parsedFiles.length === 0) {@@ -85,6 +93,7 @@ export async function parseBtFileLayout(})return {+ infoHash: parsed.infoHash.toLowerCase(),torrentRootName,multiFile,isPrivate: parsed.private === true,diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 8c16018f..c4425021 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -2,9 +2,18 @@ import { initLogger } from '@core/logger'import { AppError, ErrorCode } from '@shared/errors'import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'import type { DownloadTask } from '@shared/types/task'-import { TaskType, TransitionPhase } from '@shared/types/task'+import {+ makeDefaultBtExtension,+ makeDownloadTask,+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'import { beforeEach, describe, expect, it, vi } from 'vitest'import { Aria2Adapter } from '../engine/aria2/aria2-adapter'+import { parseBtFileLayout } from './bt-storage-layout'import { handleCreateTask } from './create-task-handler'// Stub `mkdir` (and the other `fs.*` calls inadvertently dragged@@ -186,7 +195,7 @@ function makeDeps(overrides: DepOverrides = {}): Deps & {set,add,remove,- getAll: vi.fn(),+ getAll: vi.fn(() => []),getById: vi.fn(),getByEngineTaskId: vi.fn(),clear: vi.fn(),@@ -242,6 +251,101 @@ function lastAddedTask(deps: { add: ReturnType<typeof vi.fn> }): DownloadTask {}describe('handleCreateTask', () => {+ it('reuses an exact active torrent before allocating storage or an engine gid', async () => {+ const bytes = makePublicTorrentFixture()+ const parsed = await parseBtFileLayout(bytes)+ const deps = makeDeps()+ const existing = makeDownloadTask({+ id: 'existing-task',+ engineTaskId: 'existing-gid',+ name: 'public-torrent',+ kind: TaskKind.Bt,+ type: TaskType.Bt,+ status: TaskStatus.Seeding,+ saveDir: '/d',+ createdAt: 1,+ updatedAt: 1,+ filename: 'public-torrent',+ diskPath: '/d/public-torrent',+ finalPath: '/d/public-torrent',+ finalName: 'public-torrent',+ infoHash: parsed.infoHash,+ bt: makeDefaultBtExtension({ selectedFiles: [0] }),+ source: 'user',+ sourceMeta: null,+ instances: [+ {+ instanceId: 'primary:existing-task',+ motrixId: 'existing-task',+ gid: 'existing-gid',+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Seeding,+ progress: 1,+ totalBytes: 1024,+ downloadedBytes: 1024,+ uploadedBytes: 0,+ diskPath: '/d/public-torrent',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: 1,+ updatedAt: 1,+ },+ ],+ })+ vi.mocked(deps.taskManager.getAll).mockReturnValue([existing])+ vi.mocked(deps.taskManager.getById).mockReturnValue(existing)++ await expect(+ handleCreateTask(+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: Buffer.from(bytes).toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/d',+ },+ deps+ )+ ).resolves.toEqual({+ outcome: 'reused',+ gid: 'existing-gid',+ taskId: 'existing-task',+ })+ expect(deps.addTorrent).not.toHaveBeenCalled()+ expect(deps.pick).not.toHaveBeenCalled()+ expect(deps.persist).not.toHaveBeenCalled()+ })++ it('does not silently suffix orphaned torrent files without confirmation', async () => {+ const bytes = makePublicTorrentFixture()+ const deps = makeDeps()+ deps.finalNamePicker.isTaken = vi.fn(async () => true)++ await expect(+ handleCreateTask(+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: Buffer.from(bytes).toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/d',+ },+ deps+ )+ ).rejects.toMatchObject({+ conflict: { reason: 'existing-files', canCreateCopy: true },+ })+ expect(deps.addTorrent).not.toHaveBeenCalled()+ expect(deps.pick).not.toHaveBeenCalled()+ expect(deps.persist).not.toHaveBeenCalled()+ })+it('rejects invalid payload with AppError', async () => {await expect(handleCreateTask({ junk: true }, makeDeps())).rejects.toThrow(AppErrordiff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex e518c7ea..42cb70b5 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -18,7 +18,10 @@ import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { SettingsManager } from '@core/settings/settings-manager'import { INCOMPLETE_SUFFIX } from '@shared/constants/incomplete'import { AppError, ErrorCode } from '@shared/errors'-import type { TaskCreateRequest } from '@shared/schemas/add-task'+import type {+ TaskCreateRequest,+ TaskCreateSuccessResult,+} from '@shared/schemas/add-task'import { taskCreateRequestSchema } from '@shared/schemas/add-task'import type { BeforeCreateHttpContextDTO } from '@shared/types/plugin-hooks'import type {@@ -39,6 +42,14 @@ import {import { isTorrentLikeType } from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type Database from 'better-sqlite3'+import {+ acquireBtInfoHashAdmission,+ existingFilesConflict,+ extractMagnetInfoHash,+ inspectBtDuplicate,+ reservedBtFinalNames,+ TorrentDuplicateConflictError,+} from './bt-duplicate-policy'import {type BtStoragePlan,btStoragePayload,@@ -129,6 +140,9 @@ export interface CreateTaskDeps {/** Dispatch an AdaptedMux to the shared MuxPipeline. Must be paired with* resolveToMux — both present or both absent. */dispatchMux?: (adapted: AdaptedMux) => Promise<{ taskId: string }>+ /** Re-adds a terminal BT task against its final layout with integrity+ * checking. Shell command handlers inject the existing reAddTask action. */+ reuseExistingBt?: (taskId: string) => Promise<void>}export interface CreateTaskOptions {@@ -164,7 +178,40 @@ export async function handleCreateTask(rawRequest: unknown,deps: CreateTaskDeps,opts: CreateTaskOptions = {}-): Promise<{ gid: string; taskId: string }> {+): Promise<TaskCreateSuccessResult> {+ const parsed = taskCreateRequestSchema.safeParse(rawRequest)+ if (!parsed.success || parsed.data.type !== 'bt') {+ return handleCreateTaskUnderAdmission(rawRequest, deps, opts)+ }++ const req = parsed.data+ let infoHash =+ req.payload.kind === 'magnet'+ ? extractMagnetInfoHash(req.payload.uri)+ : null+ if (!infoHash && req.payload.kind === 'torrent-base64') {+ try {+ const bytes = req.torrentBytes ?? decodeBase64ToBytes(req.payload.base64)+ infoHash = (await parseBtFileLayout(bytes)).infoHash+ } catch {+ // The canonical create path below owns parse-error handling and logging.+ }+ }+ if (!infoHash) return handleCreateTaskUnderAdmission(rawRequest, deps, opts)++ const release = await acquireBtInfoHashAdmission(infoHash)+ try {+ return await handleCreateTaskUnderAdmission(rawRequest, deps, opts)+ } finally {+ release()+ }+}++async function handleCreateTaskUnderAdmission(+ rawRequest: unknown,+ deps: CreateTaskDeps,+ opts: CreateTaskOptions = {}+): Promise<TaskCreateSuccessResult> {const parsed = taskCreateRequestSchema.safeParse(rawRequest)if (!parsed.success) {throw new AppError(@@ -222,12 +269,67 @@ export async function handleCreateTask(}}+ const btInfoHash =+ req.type !== 'bt'+ ? null+ : (parsedBtLayout?.infoHash ??+ (req.payload.kind === 'magnet'+ ? extractMagnetInfoHash(req.payload.uri)+ : null))++ if (req.type === 'bt' && btInfoHash) {+ const admission = inspectBtDuplicate(deps.taskManager.getAll(), {+ infoHash: btInfoHash,+ saveDir: effectiveSaveDir,+ selectedFiles: req.selectedFiles,+ duplicatePolicy: req.duplicatePolicy,+ excludeTaskId: req.existingTaskId,+ })+ if (admission.action === 'conflict') {+ throw new TorrentDuplicateConflictError(admission.conflict)+ }+ if (admission.action === 'reuse') {+ const didRecheck = admission.recheck && Boolean(deps.reuseExistingBt)+ if (didRecheck) {+ await deps.reuseExistingBt?.(admission.task.id)+ }+ const owner =+ deps.taskManager.getById(admission.task.id) ?? admission.task+ return {+ outcome: didRecheck ? 'rechecked' : 'reused',+ gid: owner.engineTaskId,+ taskId: owner.id,+ }+ }+ }+// 1. Decide final on-disk name (handles collisions).const desiredName = deriveDesiredName(req, torrentInfoName)- const finalName = await deps.finalNamePicker.pick(- effectiveSaveDir,- desiredName- )+ if (+ req.type === 'bt' &&+ btInfoHash &&+ req.duplicatePolicy === 'reuse' &&+ deps.finalNamePicker.isTaken &&+ (await deps.finalNamePicker.isTaken(effectiveSaveDir, desiredName))+ ) {+ throw existingFilesConflict(btInfoHash, effectiveSaveDir)+ }+ const reservedNames =+ req.type === 'bt'+ ? reservedBtFinalNames(+ deps.taskManager.getAll(),+ effectiveSaveDir,+ req.existingTaskId+ )+ : undefined+ const finalName =+ req.type === 'bt'+ ? await deps.finalNamePicker.pick(+ effectiveSaveDir,+ desiredName,+ reservedNames+ )+ : await deps.finalNamePicker.pick(effectiveSaveDir, desiredName)const taskType = deriveTaskType(req)const finalPath = path.join(effectiveSaveDir, finalName)@@ -392,6 +494,7 @@ export async function handleCreateTask(}const muxDispatchResult = await deps.dispatchMux(adaptedMux)return {+ outcome: 'created',gid: muxDispatchResult.taskId,taskId: muxDispatchResult.taskId,}@@ -604,12 +707,16 @@ export async function handleCreateTask(finalPath,finalName,torrentMetaPath,+ infoHash: btInfoHash,// For BT/Magnet, seed bt.isPrivate at creation time so SessionManager.save()// persists is_private to db. Other bt fields are filled in by the next poll// cycle via translateBtExtension; mergeTask preserves isPrivate via the// saved.isPrivate injection wired in Task 4.bt: isBtLike- ? makeDefaultBtExtension({ isPrivate: isPrivateFromTorrent })+ ? makeDefaultBtExtension({+ isPrivate: isPrivateFromTorrent,+ selectedFiles: req.type === 'bt' ? req.selectedFiles : [],+ }): undefined,// Provenance: defaults to 'user'. Bridge receiver passes 'bridge' +// BridgeSourceMeta via CreateTaskOptions to attribute rows correctly.@@ -617,10 +724,7 @@ export async function handleCreateTask(sourceMeta: opts.sourceMeta ?? null,instances: [primaryInstance],})- const createReservedTask = async (): Promise<{- gid: string- taskId: string- }> => {+ const createReservedTask = async (): Promise<TaskCreateSuccessResult> => {deps.taskManager.reserveEngineTaskId(gid)const persistParent = async (): Promise<void> => {@@ -741,7 +845,7 @@ export async function handleCreateTask(// initial Queued/zero state, handlePolledTasks's dirty guard might// not emit either).- return { gid, taskId }+ return { outcome: 'created', gid, taskId }}return deps.runTaskMutation@@ -822,11 +926,6 @@ function extractMagnetDn(uri: string): string | null {}}-function extractMagnetInfoHash(uri: string): string | null {- const match = uri.match(/xt=urn:btih:([A-Za-z0-9]+)/)- return match ? match[1] : null-}-function decodeBase64ToBytes(b64: string): Uint8Array {return Uint8Array.from(Buffer.from(b64, 'base64'))}diff --git a/src/core/task/final-name-picker.test.ts b/src/core/task/final-name-picker.test.tsindex 8445e218..ac36dda7 100644--- a/src/core/task/final-name-picker.test.ts+++ b/src/core/task/final-name-picker.test.ts@@ -26,6 +26,11 @@ describe('FinalNamePicker.pick', () => {expect(await picker.pick('/d', 'foo.mp4')).toBe('foo (1).mp4')})+ it('reserves names owned by tasks whose payload is still staged elsewhere', async () => {+ const picker = new FinalNamePickerImpl(makeFs(new Set()))+ expect(await picker.pick('/d', 'foo.mp4', ['foo.mp4'])).toBe('foo (1).mp4')+ })+it('increments through (1), (2), (3)', async () => {const picker = new FinalNamePickerImpl(makeFs(new Set(['/d/foo.mp4', '/d/foo (1).mp4', '/d/foo (2).mp4']))diff --git a/src/core/task/final-name-picker.ts b/src/core/task/final-name-picker.tsindex 8b994f05..2a9c98e8 100644--- a/src/core/task/final-name-picker.ts+++ b/src/core/task/final-name-picker.ts@@ -10,14 +10,27 @@ export interface FsProbe {}export interface FinalNamePicker {- pick(saveDir: string, desiredName: string): Promise<string>+ pick(+ saveDir: string,+ desiredName: string,+ reservedNames?: readonly string[]+ ): Promise<string>+ isTaken?(dir: string, name: string): Promise<boolean>}export class FinalNamePickerImpl implements FinalNamePicker {constructor(private readonly fs: FsProbe) {}- async pick(saveDir: string, desiredName: string): Promise<string> {- if (!(await this.isTaken(saveDir, desiredName))) {+ async pick(+ saveDir: string,+ desiredName: string,+ reservedNames: readonly string[] = []+ ): Promise<string> {+ const reserved = new Set(reservedNames)+ if (+ !reserved.has(desiredName) &&+ !(await this.isTaken(saveDir, desiredName))+ ) {return desiredName}@@ -25,7 +38,10 @@ export class FinalNamePickerImpl implements FinalNamePicker {for (let n = 1; n <= MAX_DEDUP_ATTEMPTS; n++) {const candidate = ext ? `${base} (${n})${ext}` : `${base} (${n})`- if (!(await this.isTaken(saveDir, candidate))) {+ if (+ !reserved.has(candidate) &&+ !(await this.isTaken(saveDir, candidate))+ ) {return candidate}}@@ -36,7 +52,7 @@ export class FinalNamePickerImpl implements FinalNamePicker {)}- private async isTaken(dir: string, name: string): Promise<boolean> {+ async isTaken(dir: string, name: string): Promise<boolean> {const finalPath = path.join(dir, name)const tempPath = finalPath + INCOMPLETE_SUFFIXconst [f, t] = await Promise.all([diff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.tsindex ba03d4e3..1befbc4e 100644--- a/src/core/torrent/magnet-tracker.test.ts+++ b/src/core/torrent/magnet-tracker.test.ts@@ -19,6 +19,8 @@ import { Events } from '@shared/protocol/events'import { magnetFileSelectionPayloadSchema } from '@shared/schemas/add-task'import type { DownloadTask } from '@shared/types/task'import {+ makeDefaultBtExtension,+ makeDownloadTask,TaskInstancePhase,TaskKind,TaskStatus,@@ -409,6 +411,76 @@ describe('MagnetTracker', () => {})})+ it('reuses a same-directory seed and rejects a second active directory', async () => {+ const dir = await makeTempDir()+ const infoHash = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ const existing = makeDownloadTask({+ id: 'existing-seed',+ engineTaskId: 'existing-gid',+ name: 'sample-data',+ kind: TaskKind.Bt,+ type: TaskType.Bt,+ status: TaskStatus.Seeding,+ saveDir: dir,+ createdAt: 1,+ updatedAt: 1,+ filename: 'sample-data',+ diskPath: path.join(dir, 'sample-data'),+ finalPath: path.join(dir, 'sample-data'),+ finalName: 'sample-data',+ infoHash,+ bt: makeDefaultBtExtension({ selectedFiles: [0] }),+ source: 'user',+ sourceMeta: null,+ instances: [+ {+ instanceId: 'primary:existing-seed',+ motrixId: 'existing-seed',+ gid: 'existing-gid',+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Seeding,+ progress: 1,+ totalBytes: 1024,+ downloadedBytes: 1024,+ uploadedBytes: 0,+ diskPath: path.join(dir, 'sample-data'),+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: 1,+ updatedAt: 1,+ },+ ],+ })+ taskManager.set(existing.id, existing)+ const tracker = createMagnetTracker(+ rpc as never,+ eventBus as never,+ settings as never,+ db,+ taskManager,+ torrentParser+ )++ await expect(+ tracker.submit(`magnet:?xt=urn:btih:${infoHash}`, dir)+ ).resolves.toBe(existing.id)+ expect(rpc.addUri).not.toHaveBeenCalled()++ const otherDir = await makeTempDir()+ await expect(+ tracker.submit(`magnet:?xt=urn:btih:${infoHash}`, otherDir)+ ).rejects.toMatchObject({+ conflict: {+ reason: 'active-info-hash',+ existingTaskId: existing.id,+ canCreateCopy: false,+ },+ })+ expect(rpc.addUri).not.toHaveBeenCalled()+ })+it('reserves and silently owns the caller GID before aria2 can expose it', async () => {const dir = await makeTempDir()let resolveAdd!: (gid: string) => voiddiff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex 57a0120f..8bf2308c 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -25,6 +25,14 @@ import {applyTerminalTransition,terminalFieldsFromRow,} from '@core/task/apply-terminal-transition'+import {+ acquireBtInfoHashAdmission,+ btTaskTargetDir,+ canonicalBtPath,+ isBtInfoHashRegistered,+ normalizeBtInfoHash,+ TorrentDuplicateConflictError,+} from '@core/task/bt-duplicate-policy'import { btWorkspacePath } from '@core/task/bt-storage-layout'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'import type { TaskManager } from '@core/task/task-manager'@@ -404,6 +412,24 @@ export class MagnetTracker {uri: string,saveDir: string,provenance?: { source?: TaskSource; sourceMeta?: SourceMeta }+ ): Promise<string> {+ const requestedInfoHash = extractInfoHash(uri)+ if (requestedInfoHash === UNKNOWN_INFO_HASH) {+ return this.submitUnderAdmission(uri, saveDir, provenance)+ }++ const release = await acquireBtInfoHashAdmission(requestedInfoHash)+ try {+ return await this.submitUnderAdmission(uri, saveDir, provenance)+ } finally {+ release()+ }+ }++ private async submitUnderAdmission(+ uri: string,+ saveDir: string,+ provenance?: { source?: TaskSource; sourceMeta?: SourceMeta }): Promise<string> {if (this.stopped) {throw new Error('MagnetTracker is stopped')@@ -417,6 +443,41 @@ export class MagnetTracker {return ''}+ const requestedInfoHash = extractInfoHash(uri)+ if (requestedInfoHash !== UNKNOWN_INFO_HASH) {+ const requestedDir = canonicalBtPath(saveDir)+ const sameContent = this.taskManager+ .getAll()+ .filter(+ (task) =>+ normalizeBtInfoHash(task.infoHash ?? '') === requestedInfoHash &&+ task.status !== TaskStatus.Removed+ )+ const sameDirectory = sameContent.find(+ (task) => btTaskTargetDir(task) === requestedDir+ )+ if (sameDirectory) {+ log.info(+ { infoHash: requestedInfoHash, taskId: sameDirectory.id },+ 'magnet submit reused existing content owner'+ )+ return sameDirectory.id+ }++ const active = sameContent.find(isBtInfoHashRegistered)+ if (active) {+ throw new TorrentDuplicateConflictError({+ reason: 'active-info-hash',+ infoHash: requestedInfoHash,+ targetDir: requestedDir,+ existingTaskId: active.id,+ existingTaskName: active.name,+ existingTaskStatus: active.status,+ canCreateCopy: false,+ })+ }+ }+const metadataDir = await mkdtemp(join(tmpdir(), 'motrix-magnet-metadata-'))if (this.stopped) {await this.cleanupMetadataDir(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 c0c1e301..b2a5fd9a 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@@ -178,7 +178,9 @@ describe('swapMagnetMetadataForBt atomic commit', () => {removeFaultTrigger(db, seam)await expect(swapMagnetMetadataForBt(input, deps)).resolves.toEqual({+ outcome: 'created',gid: expect.stringMatching(/^[0-9a-f]{16}$/),+ taskId,})const secondGid = tracking.addedGids[1]diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.tsindex 1372c4e7..61673e00 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts@@ -681,7 +681,7 @@ describe('swapMagnetMetadataForBt', () => {.calls[0][1]expect(tmTask.id).toBe('m-mag')expect(tmTask.createdAt).toBe(1700000000)- expect(tmTask.bt.selectedFiles).toEqual([0, 1])+ expect(tmTask.bt?.selectedFiles).toEqual([0, 1])})it('persists complete engine file metadata instead of index placeholders', async () => {@@ -879,7 +879,11 @@ describe('swapMagnetMetadataForBt', () => {expect(queuedAutosaveStarted).toBe(false)releaseActivity()- await expect(swapPromise).resolves.toEqual({ gid: reservedGid })+ await expect(swapPromise).resolves.toEqual({+ outcome: 'created',+ gid: reservedGid,+ taskId: 'm-mag',+ })await queuedAutosaveexpect(taskManager.getByEngineTaskId(reservedGid)?.id).toBe('m-mag')@@ -1045,7 +1049,9 @@ describe('swapMagnetMetadataForBt', () => {})).resolves.toEqual({+ outcome: 'created',gid: expect.stringMatching(/^[0-9a-f]{16}$/),+ taskId: 'm-mag',})expect(taskManager.set).toHaveBeenCalled()diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.ts b/src/core/torrent/swap-magnet-metadata-for-bt.tsindex e1ceccb4..4740dc7e 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.ts@@ -10,6 +10,10 @@ import type {TaskWithInstancesAndFiles,} from '@core/session/motrix-database'import type { TaskTransitionRecordInput } from '@core/task/actions/shared'+import {+ existingFilesConflict,+ reservedBtFinalNames,+} from '@core/task/bt-duplicate-policy'import {type BtStoragePlan,btStoragePayload,@@ -24,6 +28,7 @@ import type { TaskManager } from '@core/task/task-manager'import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'import type { TorrentMetaStore } from '@core/task/torrent-meta-store'import { AppError, ErrorCode } from '@shared/errors'+import type { TaskCreateSuccessResult } from '@shared/schemas/add-task'import type { DownloadTask } from '@shared/types/task'import {TaskInstancePhase,@@ -55,6 +60,7 @@ export interface SwapMagnetMetadataInput {/** Resolved torrent display name. When provided, replaces the* `[METADATA] …` placeholder name on the task row. */name?: string+ duplicatePolicy?: 'reuse' | 'create-copy'}export interface SwapMagnetMetadataDeps {@@ -98,7 +104,7 @@ export interface SwapMagnetMetadataDeps {export async function swapMagnetMetadataForBt(input: SwapMagnetMetadataInput,deps: SwapMagnetMetadataDeps-): Promise<{ gid: string }> {+): Promise<TaskCreateSuccessResult> {return deps.runTaskMutation([input.taskId], () =>swapMagnetMetadataForBtUnderMutation(input, deps))@@ -114,8 +120,15 @@ export async function swapMagnetMetadataForBt(async function swapMagnetMetadataForBtUnderMutation(input: SwapMagnetMetadataInput,deps: SwapMagnetMetadataDeps-): Promise<{ gid: string }> {- const { taskId, base64, selectedFiles, saveDir, name } = input+): Promise<TaskCreateSuccessResult> {+ const {+ taskId,+ base64,+ selectedFiles,+ saveDir,+ name,+ duplicatePolicy = 'reuse',+ } = inputconst {db,taskManager,@@ -179,17 +192,10 @@ async function swapMagnetMetadataForBtUnderMutation(//// Mirror createTaskHandler's BT branch: collision-safe final name, a short// indexed workspace when metadata is valid, and durable `.torrent` bytes.- const desiredName = (name ?? existing.task.name).replace(- METADATA_NAME_PREFIX,- ''- )- const finalName = await finalNamePicker.pick(saveDir, desiredName)- const finalPath = path.join(saveDir, finalName)let btStoragePlan: BtStoragePlan | null = nulllet parsedBtLayout: ParsedBtFileLayout | null = nulltry {parsedBtLayout = await parseBtFileLayout(torrentBytes)- btStoragePlan = createBtStoragePlan(taskId, saveDir, parsedBtLayout)} catch (err) {if (err instanceof UnsafeTorrentPathError) {throw new AppError(@@ -203,6 +209,27 @@ async function swapMagnetMetadataForBtUnderMutation('failed to parse resolved magnet metadata for indexed staging; using legacy layout')}+ const desiredName = (name ?? existing.task.name).replace(+ METADATA_NAME_PREFIX,+ ''+ )+ if (+ parsedBtLayout &&+ duplicatePolicy === 'reuse' &&+ finalNamePicker.isTaken &&+ (await finalNamePicker.isTaken(saveDir, desiredName))+ ) {+ 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: stringtry {@@ -466,6 +493,7 @@ async function swapMagnetMetadataForBtUnderMutation(finalPath,finalName,torrentMetaPath,+ infoHash: parsedBtLayout?.infoHash ?? existing.task.infoHash,isPrivate: parsedBtLayout?.isPrivate ?? existing.task.isPrivate,aggStatus: TaskStatus.Downloading,finishedAt: null,@@ -737,7 +765,7 @@ async function swapMagnetMetadataForBtUnderMutation('magnet metadata swapped for bt_download instance')- return { gid: newGid }+ return { outcome: 'created', gid: newGid, taskId }}interface FailedSwapArtifacts {diff --git a/src/main/index.ts b/src/main/index.tsindex 159108ef..928c1923 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -62,6 +62,7 @@ import {} from '@core/stats'import {pauseTask as pauseTaskAction,+ reAddTask as reAddTaskAction,resumeTask as resumeTaskAction,} from '@core/task/actions'import { finalizeTask } from '@core/task/actions/finalize-task'@@ -2023,6 +2024,25 @@ async function initializeMainProcess(): Promise<void> {const nativeMessagingInstaller = createNativeMessagingInstaller()const createBridgeRuntime = async () => {+ const bridgeReAddDeps = {+ taskManager,+ adapter,+ eventBus,+ log,+ persistTask,+ persistTaskWithOccurrence,+ occurrenceDispatcher,+ recordTransition: (input: RuntimeTransitionInput) =>+ activeTaskInspectorActivityRuntime.recordTransition(input),+ runTaskMutation: <T>(+ taskIds: readonly string[],+ operation: () => Promise<T>+ ) =>+ activeTaskInspectorActivityRuntime.runTaskMutation(taskIds, operation),+ publishTaskUpdate,+ publishTaskUpdateNow,+ torrentMetaStore,+ }const createTaskDeps = {adapter,settingsManager,@@ -2059,6 +2079,8 @@ async function initializeMainProcess(): Promise<void> {await supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS)await mainProcessWork.waitForStartup()},+ reuseExistingBt: (taskId: string) =>+ reAddTaskAction(taskId, bridgeReAddDeps),}// Deps for the deleteFiles-aware task/remove (Spec 4) — a SEPARATE path// from the extension download/cancel closure below (which is alwaysdiff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex bddfb7fd..7195722a 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -51,7 +51,16 @@ import type {TaskActionDeps,TaskTransitionRecordInput,} from '@core/task/actions/shared'-import { handleCreateTask } from '@core/task/create-task-handler'+import {+ acquireBtInfoHashAdmission,+ inspectBtDuplicate,+ taskCreateConflictResult,+} from '@core/task/bt-duplicate-policy'+import { parseBtFileLayout } from '@core/task/bt-storage-layout'+import {+ type CreateTaskDeps,+ handleCreateTask,+} from '@core/task/create-task-handler'import type { FileCleanupService } from '@core/task/file-cleanup-service'import type { FinalNamePicker } from '@core/task/final-name-picker'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'@@ -67,6 +76,7 @@ import { EXTERNAL_URLS } from '@shared/external-urls'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import type { CommandHandlerMap } from '@shared/protocol/handler-types'+import type { TaskCreateCommandResult } from '@shared/schemas/add-task'import { taskCreateRequestSchema } from '@shared/schemas/add-task'import {removeTasksPayloadSchema,@@ -83,6 +93,7 @@ import {import { EngineRecoveryAction } from '@shared/types/engine'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'+import { TaskStatus } from '@shared/types/task'import { canRetryMagnetMetadata } from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type { TaskOccurrence } from '@shared/types/task-occurrence'@@ -320,7 +331,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {auditLog: hookAuditLog,})- const createDeps = {+ const createDeps: CreateTaskDeps = {adapter,settingsManager,finalNamePicker,@@ -425,6 +436,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {publishTaskUpdate,publishTaskUpdateNow,}+ createDeps.reuseExistingBt = (taskId) => reAddTask(taskId, reAddDeps)// The DNS fallback consumer retries through the same deps bundle as// Commands.ReAddTasks so the automatic and user-initiated paths match.bindTaskRetry?.((id) => reAddTask(id, reAddDeps))@@ -590,8 +602,15 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {*/async function createAndPersist(request: Parameters<typeof handleCreateTask>[0]- ): Promise<{ gid: string }> {- const result = await handleCreateTask(request, createDeps)+ ): Promise<TaskCreateCommandResult> {+ let result: Awaited<ReturnType<typeof handleCreateTask>>+ try {+ result = await handleCreateTask(request, createDeps)+ } catch (error) {+ const conflict = taskCreateConflictResult(error)+ if (conflict) return conflict+ throw error+ }try {await sessionManager.requestSave()} catch (err) {@@ -823,11 +842,39 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {req.selectedFiles.length === 0 &&settingsManager.getApp().magnetFileSelection) {- await magnetTracker.submit(- req.payload.uri,- req.saveDir || settingsManager.getApp().defaultSaveDir- )- return { ok: true }+ let taskId: string+ try {+ taskId = await magnetTracker.submit(+ req.payload.uri,+ req.saveDir || settingsManager.getApp().defaultSaveDir+ )+ } catch (error) {+ const conflict = taskCreateConflictResult(error)+ if (conflict) return conflict+ throw error+ }+ if (!taskId) return { ok: true }+ const existing = taskManager.getById(taskId)+ if (+ existing?.status === TaskStatus.Completed ||+ existing?.status === TaskStatus.Error+ ) {+ await reAddTask(taskId, reAddDeps)+ const owner = taskManager.getById(taskId) ?? existing+ return {+ outcome: 'rechecked',+ gid: owner.engineTaskId,+ taskId,+ }+ }+ return {+ outcome:+ existing?.status === TaskStatus.FetchingMetadata+ ? 'created'+ : 'reused',+ gid: existing?.engineTaskId ?? '',+ taskId,+ }}} else {await activatePluginsForTask('bt', '')@@ -837,29 +884,75 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {// the task identity, name, and Downloads list position// survive — instead of creating a duplicate task.if (req.payload.kind === 'torrent-base64' && req.existingTaskId) {- return swapMagnetMetadataForBt(- {- taskId: req.existingTaskId,- base64: req.payload.base64,- selectedFiles: req.selectedFiles,- saveDir: req.saveDir,- name: req.displayName,- },- {- db: motrixDatabase,- taskManager,- adapter,- magnetTracker,- finalNamePicker,- torrentMetaStore,- publishTaskUpdate,- publishTaskUpdateNow,- recordTransition,- runTaskMutation,- runExclusivePersistence: (operation) =>- sessionManager.runExclusivePersistence(operation),+ const layout = await parseBtFileLayout(+ Buffer.from(req.payload.base64, 'base64')+ ).catch(() => null)+ const releaseAdmission = layout+ ? await acquireBtInfoHashAdmission(layout.infoHash)+ : null+ try {+ const admission = layout+ ? inspectBtDuplicate(taskManager.getAll(), {+ infoHash: layout.infoHash,+ saveDir: req.saveDir,+ selectedFiles: req.selectedFiles,+ duplicatePolicy: req.duplicatePolicy,+ excludeTaskId: req.existingTaskId,+ })+ : { action: 'create' as const }+ if (admission.action === 'conflict') {+ return { outcome: 'conflict', conflict: admission.conflict }}- )+ if (admission.action === 'reuse') {+ await removeTask(+ req.existingTaskId,+ { deleteWithFiles: false },+ removeDeps+ )+ if (admission.recheck) {+ await reAddTask(admission.task.id, reAddDeps)+ }+ const owner =+ taskManager.getById(admission.task.id) ?? admission.task+ return {+ outcome: admission.recheck ? 'rechecked' : 'reused',+ gid: owner.engineTaskId,+ taskId: owner.id,+ }+ }+ try {+ return await swapMagnetMetadataForBt(+ {+ taskId: req.existingTaskId,+ base64: req.payload.base64,+ selectedFiles: req.selectedFiles,+ saveDir: req.saveDir,+ name: req.displayName,+ duplicatePolicy: req.duplicatePolicy,+ },+ {+ db: motrixDatabase,+ taskManager,+ adapter,+ magnetTracker,+ finalNamePicker,+ torrentMetaStore,+ publishTaskUpdate,+ publishTaskUpdateNow,+ recordTransition,+ runTaskMutation,+ runExclusivePersistence: (operation) =>+ sessionManager.runExclusivePersistence(operation),+ }+ )+ } catch (error) {+ const conflict = taskCreateConflictResult(error)+ if (conflict) return conflict+ throw error+ }+ } finally {+ releaseAdmission?.()+ }}}}diff --git a/src/main/ipc/commands/reveal-in-folder.test.ts b/src/main/ipc/commands/reveal-in-folder.test.tsindex c6f8d60e..45a7ba02 100644--- a/src/main/ipc/commands/reveal-in-folder.test.ts+++ b/src/main/ipc/commands/reveal-in-folder.test.ts@@ -8,7 +8,10 @@ describe('revealInFolder', () => {shell,getTask: (taskId) =>taskId === 'task-1'- ? { diskPath: '/Users/me/Downloads/file.iso' }+ ? {+ diskPath: '/Users/me/Downloads/file.iso',+ finalPath: '/Users/me/Downloads/file.iso',+ }: undefined,})@@ -19,6 +22,23 @@ describe('revealInFolder', () => {)})+ it('hides an indexed BT workspace behind its stable final path', async () => {+ const shell = { showItemInFolder: vi.fn() }+ const handler = createRevealInFolderHandler({+ shell,+ getTask: () => ({+ diskPath: '/Users/me/Downloads/.motrix/61282448e78c1fc29ac1/p',+ finalPath: '/Users/me/Downloads/sample-data',+ }),+ })++ await handler({ taskId: 'task-bt' })++ expect(shell.showItemInFolder).toHaveBeenCalledWith(+ '/Users/me/Downloads/sample-data'+ )+ })+it('rejects an unknown task instead of accepting a renderer path', async () => {const shell = { showItemInFolder: vi.fn() }const handler = createRevealInFolderHandler({@@ -37,7 +57,7 @@ describe('revealInFolder', () => {const shell = { showItemInFolder: vi.fn() }const handler = createRevealInFolderHandler({shell,- getTask: () => ({ diskPath }),+ getTask: () => ({ diskPath, finalPath: '' }),})await handler({ taskId: 'task-unc' })@@ -54,7 +74,7 @@ describe('revealInFolder', () => {const shell = { showItemInFolder: vi.fn() }const handler = createRevealInFolderHandler({shell,- getTask: () => ({ diskPath }),+ getTask: () => ({ diskPath, finalPath: '' }),})await expect(handler({ taskId: 'task-device' })).rejects.toThrow(@@ -67,7 +87,10 @@ describe('revealInFolder', () => {const shell = { showItemInFolder: vi.fn() }const handler = createRevealInFolderHandler({shell,- getTask: () => ({ diskPath: '../downloads/file.iso' }),+ getTask: () => ({+ diskPath: '../downloads/file.iso',+ finalPath: '',+ }),})await expect(handler({ taskId: 'task-relative' })).rejects.toThrow(diff --git a/src/main/ipc/commands/reveal-in-folder.ts b/src/main/ipc/commands/reveal-in-folder.tsindex 8036c500..ff35ca4f 100644--- a/src/main/ipc/commands/reveal-in-folder.ts+++ b/src/main/ipc/commands/reveal-in-folder.ts@@ -4,7 +4,9 @@ import type { DownloadTask } from '@shared/types/task'export interface RevealInFolderDeps {shell: { showItemInFolder: (path: string) => void }- getTask: (taskId: string) => Pick<DownloadTask, 'diskPath'> | undefined+ getTask: (+ taskId: string+ ) => Pick<DownloadTask, 'diskPath' | 'finalPath'> | undefined}export interface RevealInFolderPayload {@@ -36,7 +38,12 @@ export function createRevealInFolderHandler(deps: RevealInFolderDeps) {throw new AppError(ErrorCode.TaskNotFound, `Task not found: ${taskId}`)}- const taskPath = task.diskPath+ // Indexed BT downloads intentionally live in an internal+ // `.motrix/<workspace>/p` staging tree until finalization. Revealing that+ // path leaks an implementation identifier and disagrees with the target+ // path shown by the Inspector, so user-facing navigation follows the+ // stable final destination whenever one is known.+ const taskPath = task.finalPath || task.diskPathif (typeof taskPath !== 'string' ||taskPath.trim() === '' ||diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsxindex fc17b9e8..02ee552a 100644--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx@@ -57,7 +57,7 @@ function renderWithRouter() {<Routes><Route path="/" element={null} /><Route- path="/downloads"+ path="/downloads/all"element={<div data-testid="downloads-route" />}/></Routes>@@ -87,7 +87,7 @@ describe('AddTaskDialogHost', () => {expect(screen.getByRole('dialog')).toBeInTheDocument()})- it('navigates to /downloads and closes dialog on submit success', () => {+ it('navigates to the stable task and closes on submit success', () => {useAddTaskDialogStore.setState({ open: true, prefill: undefined })renderWithRouter()expect(screen.queryByTestId('downloads-route')).toBeNull()diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsxindex 9c4cee59..ccbda711 100644--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx@@ -43,11 +43,14 @@ export function AddTaskDialogHost() {// ~300-500ms, and the user can close the dialog (Esc / outside-click)// during that window. If they did, the store is already closed —// navigating would yank them off whatever route they switched to.- const onSubmitSuccess = useCallback(() => {- if (!useAddTaskDialogStore.getState().open) return- close()- navigate('/downloads')- }, [close, navigate])+ const onSubmitSuccess = useCallback(+ (taskId: string) => {+ if (!useAddTaskDialogStore.getState().open) return+ close()+ navigate(`/downloads/all?task=${encodeURIComponent(taskId)}`)+ },+ [close, navigate]+ )// Register the web close handler so webServices.closeHost() works.useEffect(() => {diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsxindex ceb883df..59df84a2 100644--- a/src/renderer/components/add-task/add-task-form.test.tsx+++ b/src/renderer/components/add-task/add-task-form.test.tsx@@ -254,4 +254,58 @@ describe('AddTaskForm', () => {)expect(onSubmitSuccess).toHaveBeenCalledWith('ok-gid')})++ it('requires confirmation before creating a renamed torrent copy', async () => {+ const onSubmitSuccess = vi.fn()+ const user = userEvent.setup()+ const { transport } = await import('@renderer/lib/transport')+ let createCalls = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {+ if (channel === 'query:getSettings') return { app: {} }+ createCalls += 1+ if (createCalls === 1) {+ return {+ outcome: 'conflict',+ conflict: {+ reason: 'selection-mismatch',+ infoHash: 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc',+ targetDir: '/d',+ existingTaskId: 'existing-task',+ existingTaskName: 'sample-data',+ existingTaskStatus: 'completed',+ canCreateCopy: true,+ },+ }+ }+ return {+ outcome: 'created',+ gid: 'copy-gid',+ taskId: 'copy-task',+ }+ })+ renderForm({ onSubmitSuccess })++ await user.type(+ screen.getByRole('textbox'),+ 'magnet:?xt=urn:btih:a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'+ )+ await user.click(screen.getByRole('button', { name: /download/i }))++ expect(+ await screen.findByRole('heading', {+ name: 'This torrent already exists',+ })+ ).toBeInTheDocument()+ await user.click(+ screen.getByRole('button', { name: 'Create separate copy' })+ )++ await waitFor(() =>+ expect(transport.invoke).toHaveBeenLastCalledWith(+ 'command:createTask',+ expect.objectContaining({ duplicatePolicy: 'create-copy' })+ )+ )+ expect(onSubmitSuccess).toHaveBeenCalledWith('copy-task')+ })})diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsxindex e2f369b4..82236ecd 100644--- a/src/renderer/components/add-task/add-task-form.tsx+++ b/src/renderer/components/add-task/add-task-form.tsx@@ -1,4 +1,14 @@import { zodResolver } from '@hookform/resolvers/zod'+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@renderer/components/ui/alert-dialog'import {Tabs,TabsContent,@@ -13,6 +23,8 @@ import {type AddTaskFormValues,addTaskFormSchema,formValuesToTaskCreateRequests,+ type TaskCreateCommandResult,+ type TaskCreateRequest,} from '@shared/schemas/add-task'import { useCallback, useEffect, useRef, useState } from 'react'import {@@ -32,7 +44,7 @@ import { useExternalHydration } from './use-external-hydration'interface AddTaskFormProps {defaultValues?: DeepPartial<AddTaskFormValues>- onSubmitSuccess?: (gid: string) => void+ onSubmitSuccess?: (taskId: string) => voidonCancel: () => voidsubscribeEvents?: boolean}@@ -51,7 +63,12 @@ export function AddTaskForm({subscribeEvents = true,}: AddTaskFormProps) {const platform = usePlatformServices()+ const { t } = useTranslation()const [submitting, setSubmitting] = useState(false)+ const [duplicateConflict, setDuplicateConflict] = useState<{+ request: TaskCreateRequest+ result: Extract<TaskCreateCommandResult, { outcome: 'conflict' }>+ } | null>(null)const form = useForm<AddTaskFormValues>({resolver: zodResolver(addTaskFormSchema) as Resolver<AddTaskFormValues>,@@ -137,38 +154,72 @@ export function AddTaskForm({setSubmitting(true)try {const requests = formValuesToTaskCreateRequests(values)- const gids: string[] = []+ const successes: Array<+ Extract<TaskCreateCommandResult, { gid: string }>+ > = []let failed = 0+ let blockedByConflict = falsefor (const request of requests) {try {const result = (await transport.invoke(Commands.CreateTask,request- )) as { gid: string }- gids.push(result.gid)+ )) as TaskCreateCommandResult+ if (result.outcome === 'conflict') {+ setDuplicateConflict({ request, result })+ blockedByConflict = true+ break+ }+ successes.push(result)} catch (err) {failed += 1console.error(err)}}- if (failed === 0) {+ if (blockedByConflict) return+ if (failed === 0 && successes.length > 0) {platform.notify('info', 'task.add.created')- } else if (gids.length > 0) {+ } else if (successes.length > 0) {platform.notify('warn', 'task.add.createdPartial', {- ok: gids.length,+ ok: successes.length,failed,})- } else {+ } else if (failed > 0) {platform.notify('error', 'task.add.createFailed')}- if (gids.length > 0) onSubmitSuccess?.(gids[0])+ if (successes.length > 0) {+ onSubmitSuccess?.(successes[0].taskId ?? successes[0].gid)+ }} finally {setSubmitting(false)}},- [platform, onSubmitSuccess]+ [onSubmitSuccess, platform])+ const createSeparateCopy = useCallback(async () => {+ if (!duplicateConflict) return+ setSubmitting(true)+ try {+ const result = (await transport.invoke(Commands.CreateTask, {+ ...duplicateConflict.request,+ duplicatePolicy: 'create-copy',+ })) as TaskCreateCommandResult+ if (result.outcome === 'conflict') {+ setDuplicateConflict({ request: duplicateConflict.request, result })+ return+ }+ setDuplicateConflict(null)+ platform.notify('info', 'task.add.createdCopy')+ onSubmitSuccess?.(result.taskId)+ } catch (error) {+ console.error(error)+ platform.notify('error', 'task.add.createFailed')+ } finally {+ setSubmitting(false)+ }+ }, [duplicateConflict, onSubmitSuccess, platform])+// ⌘↵ / Ctrl+Enter submituseEffect(() => {const handler = (e: KeyboardEvent) => {@@ -195,6 +246,46 @@ export function AddTaskForm({submitting={submitting}/></div>+ <AlertDialog+ open={duplicateConflict !== null}+ onOpenChange={(open) => !open && setDuplicateConflict(null)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t('task.add.duplicate.title')}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ `task.add.duplicate.${duplicateConflict?.result.conflict.reason}`,+ {+ name:+ duplicateConflict?.result.conflict.existingTaskName ??+ t('task.add.duplicate.filesOnDisk'),+ }+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>+ {duplicateConflict?.result.conflict.existingTaskId && (+ <AlertDialogAction+ onClick={() => {+ const taskId =+ duplicateConflict.result.conflict.existingTaskId+ setDuplicateConflict(null)+ if (taskId) onSubmitSuccess?.(taskId)+ }}+ >+ {t('task.add.duplicate.showExisting')}+ </AlertDialogAction>+ )}+ {duplicateConflict?.result.conflict.canCreateCopy && (+ <AlertDialogAction onClick={() => void createSeparateCopy()}>+ {t('task.add.duplicate.createCopy')}+ </AlertDialogAction>+ )}+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></FormProvider>)}diff --git a/src/renderer/components/add-task/file-type-filters.tsx b/src/renderer/components/add-task/file-type-filters.tsxindex dc308619..45c933c7 100644--- a/src/renderer/components/add-task/file-type-filters.tsx+++ b/src/renderer/components/add-task/file-type-filters.tsx@@ -1,4 +1,10 @@import { Button } from '@renderer/components/ui/button'+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '@renderer/components/ui/tooltip'import type { AddTaskFormValues } from '@shared/schemas/add-task'import { FileText, Film, Image, Music } from 'lucide-react'import type { ReactNode } from 'react'@@ -68,21 +74,32 @@ export function FileTypeFilters() {}return (- <div className="flex gap-1">- {FILTERS.map(({ id, icon, exts }) => (- <Button- key={id}- type="button"- variant="outline"- size="icon-sm"- onClick={() => addByExts(exts)}- aria-label={t(`task.add.filterBy.${id}`)}- title={t(`task.add.filterBy.${id}`)}- className="h-7 gap-0.5 px-2 text-muted-foreground hover:text-foreground"- >- {icon}- </Button>- ))}- </div>+ <TooltipProvider>+ <div className="flex gap-1">+ {FILTERS.map(({ id, icon, exts }) => {+ const label = t(`task.add.filterBy.${id}`)++ return (+ <Tooltip key={id}>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ onClick={() => addByExts(exts)}+ aria-label={label}+ className="h-7 gap-0.5 px-2 text-muted-foreground hover:text-foreground"+ />+ }+ >+ {icon}+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ )+ })}+ </div>+ </TooltipProvider>)}diff --git a/src/renderer/components/add-task/torrent-summary-controls.test.tsx b/src/renderer/components/add-task/torrent-summary-controls.test.tsxindex 08a1f9fb..542df97d 100644--- a/src/renderer/components/add-task/torrent-summary-controls.test.tsx+++ b/src/renderer/components/add-task/torrent-summary-controls.test.tsx@@ -68,4 +68,15 @@ describe('torrent summary controls', () => {expect(screen.getByTestId('selected-files')).toHaveTextContent('4,1,2,3')})++ it('shows a tooltip for each file type filter', async () => {+ const user = userEvent.setup()+ render(<TorrentControls onClear={vi.fn()} />)++ for (const label of ['Video', 'Audio', 'Image', 'Document']) {+ await user.hover(screen.getByRole('button', { name: label }))+ expect(await screen.findByRole('tooltip')).toHaveTextContent(label)+ await user.unhover(screen.getByRole('button', { name: label }))+ }+ })})diff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsxindex e76ce2b3..8aeea175 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx@@ -249,6 +249,28 @@ describe('TaskInspectorDrawer', () => {expect(screen.queryByRole('button', { name: '/' })).toBeNull()})+ it('shows the final BT destination instead of its internal workspace', () => {+ const selection = createSelectionStore<DownloadTask>((t) => t.id)+ const tasks = [+ fake({+ id: 'a',+ type: TaskType.Bt,+ kind: TaskKind.Bt,+ diskPath: '/downloads/.motrix/61282448e78c1fc29ac1/p',+ finalPath: '/downloads/sample-data',+ }),+ ]+ selection.getState().setItems([...tasks])+ selection.getState().select('a')++ render(<TestHarness selection={selection} tasks={tasks} />)++ expect(screen.getByText('/downloads/sample-data')).toBeInTheDocument()+ expect(+ screen.queryByText('/downloads/.motrix/61282448e78c1fc29ac1/p')+ ).not.toBeInTheDocument()+ })+it('does not switch inspector content during marquee preview', () => {const selection = createSelectionStore<DownloadTask>((t) => t.id)const tasks = [diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex 9c3d2ace..e878ca1d 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -149,12 +149,14 @@ export function TaskInspectorDrawer({}><HardDrive className="mr-1 size-3.5 shrink-0 text-muted-foreground" />- <span className="truncate">{single.diskPath}</span>+ <span className="truncate">+ {single.finalPath || single.diskPath}+ </span></Button><CopyButtonvariant="ghost"className="ml-1 h-4.5 w-4.5 shrink-0 rounded-md p-0 has-[>svg]:px-0 [&_svg:not([class*='size-'])]:size-3"- content={single.diskPath}+ content={single.finalPath || single.diskPath}/></div>)}diff --git a/src/renderer/windows/add-task-window.tsx b/src/renderer/windows/add-task-window.tsxindex 8b847e98..40ecd46f 100644--- a/src/renderer/windows/add-task-window.tsx+++ b/src/renderer/windows/add-task-window.tsx@@ -41,10 +41,10 @@ export function AddTaskWindow() {<PlatformServicesProvider services={electronServices}><AddTaskFormdefaultValues={defaultValues}- onSubmitSuccess={() =>+ onSubmitSuccess={(taskId) =>void electronServices.closeHost({showMain: true,- navigateMainTo: '/downloads',+ navigateMainTo: `/downloads/all?task=${encodeURIComponent(taskId)}`,})}onCancel={() => void electronServices.closeHost({ showMain: true })}diff --git a/src/server/index.ts b/src/server/index.tsindex 1066d078..d8bc7cc2 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -63,6 +63,7 @@ import {} from '@core/stats'import {pauseTask as pauseTaskAction,+ reAddTask as reAddTaskAction,resumeTask as resumeTaskAction,} from '@core/task/actions'import { finalizeTask } from '@core/task/actions/finalize-task'@@ -1424,6 +1425,11 @@ async function main() {supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),prepareSaveDir: (requested: string) =>downloadPathPolicy.prepareSaveDir(requested),+ reuseExistingBt: (taskId: string) =>+ reAddTaskAction(taskId, {+ ...taskActionDeps,+ torrentMetaStore,+ }),}const taskActionDeps = {taskManager,diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 15441f15..7c429624 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -35,7 +35,16 @@ import type {TaskActionDeps,TaskTransitionRecordInput,} from '@core/task/actions/shared'-import { handleCreateTask } from '@core/task/create-task-handler'+import {+ acquireBtInfoHashAdmission,+ inspectBtDuplicate,+ taskCreateConflictResult,+} from '@core/task/bt-duplicate-policy'+import { parseBtFileLayout } from '@core/task/bt-storage-layout'+import {+ type CreateTaskDeps,+ handleCreateTask,+} from '@core/task/create-task-handler'import type { FileCleanupService } from '@core/task/file-cleanup-service'import type { FinalNamePicker } from '@core/task/final-name-picker'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'@@ -57,6 +66,7 @@ import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'import { EngineRecoveryAction } from '@shared/types/engine'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'+import { TaskStatus } from '@shared/types/task'import { canRetryMagnetMetadata } from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type { TaskOccurrence } from '@shared/types/task-occurrence'@@ -202,7 +212,7 @@ export function buildServerCommandHandlers(auditLog: hookAuditLog,})- const createDeps = {+ const createDeps: CreateTaskDeps = {adapter,settingsManager,finalNamePicker,@@ -271,6 +281,7 @@ export function buildServerCommandHandlers(publishTaskUpdate,publishTaskUpdateNow,}+ createDeps.reuseExistingBt = (taskId) => reAddTask(taskId, reAddDeps)// The DNS fallback consumer retries through the same deps bundle as// Commands.ReAddTasks so the automatic and user-initiated paths match.bindTaskRetry?.((id) => reAddTask(id, reAddDeps))@@ -371,8 +382,36 @@ export function buildServerCommandHandlers(const saveDir = await downloadPathPolicy.prepareSaveDir(req.saveDir || settingsManager.getApp().defaultSaveDir)- await magnetTracker.submit(req.payload.uri, saveDir)- return { ok: true }+ let taskId: string+ try {+ taskId = await magnetTracker.submit(req.payload.uri, saveDir)+ } catch (error) {+ const conflict = taskCreateConflictResult(error)+ if (conflict) return conflict+ throw error+ }+ if (!taskId) return { ok: true }+ const existing = taskManager.getById(taskId)+ if (+ existing?.status === TaskStatus.Completed ||+ existing?.status === TaskStatus.Error+ ) {+ await reAddTask(taskId, reAddDeps)+ const owner = taskManager.getById(taskId) ?? existing+ return {+ outcome: 'rechecked',+ gid: owner.engineTaskId,+ taskId,+ }+ }+ return {+ outcome:+ existing?.status === TaskStatus.FetchingMetadata+ ? 'created'+ : 'reused',+ gid: existing?.engineTaskId ?? '',+ taskId,+ }}} else {await activatePluginsForTask('bt', '')@@ -383,33 +422,85 @@ export function buildServerCommandHandlers(// survive (no duplicate row appears).if (req.payload.kind === 'torrent-base64' && req.existingTaskId) {const saveDir = await downloadPathPolicy.prepareSaveDir(req.saveDir)- return swapMagnetMetadataForBt(- {- taskId: req.existingTaskId,- base64: req.payload.base64,- selectedFiles: req.selectedFiles,- saveDir,- name: req.displayName,- },- {- db: motrixDatabase,- taskManager,- adapter,- magnetTracker,- finalNamePicker,- torrentMetaStore,- publishTaskUpdate,- publishTaskUpdateNow,- recordTransition,- runTaskMutation,- runExclusivePersistence: (operation) =>- taskPersistence.runExclusivePersistence(operation),+ const layout = await parseBtFileLayout(+ Buffer.from(req.payload.base64, 'base64')+ ).catch(() => null)+ const releaseAdmission = layout+ ? await acquireBtInfoHashAdmission(layout.infoHash)+ : null+ try {+ const admission = layout+ ? inspectBtDuplicate(taskManager.getAll(), {+ infoHash: layout.infoHash,+ saveDir,+ selectedFiles: req.selectedFiles,+ duplicatePolicy: req.duplicatePolicy,+ excludeTaskId: req.existingTaskId,+ })+ : { action: 'create' as const }+ if (admission.action === 'conflict') {+ return { outcome: 'conflict', conflict: admission.conflict }}- )+ if (admission.action === 'reuse') {+ await removeTask(+ req.existingTaskId,+ { deleteWithFiles: false },+ removeDeps+ )+ if (admission.recheck) {+ await reAddTask(admission.task.id, reAddDeps)+ }+ const owner =+ taskManager.getById(admission.task.id) ?? admission.task+ return {+ outcome: admission.recheck ? 'rechecked' : 'reused',+ gid: owner.engineTaskId,+ taskId: owner.id,+ }+ }+ try {+ return await swapMagnetMetadataForBt(+ {+ taskId: req.existingTaskId,+ base64: req.payload.base64,+ selectedFiles: req.selectedFiles,+ saveDir,+ name: req.displayName,+ duplicatePolicy: req.duplicatePolicy,+ },+ {+ db: motrixDatabase,+ taskManager,+ adapter,+ magnetTracker,+ finalNamePicker,+ torrentMetaStore,+ publishTaskUpdate,+ publishTaskUpdateNow,+ recordTransition,+ runTaskMutation,+ runExclusivePersistence: (operation) =>+ taskPersistence.runExclusivePersistence(operation),+ }+ )+ } catch (error) {+ const conflict = taskCreateConflictResult(error)+ if (conflict) return conflict+ throw error+ }+ } finally {+ releaseAdmission?.()+ }}}}- return handleCreateTask(request, createDeps)+ try {+ return await handleCreateTask(request, createDeps)+ } catch (error) {+ const conflict = taskCreateConflictResult(error)+ if (conflict) return conflict+ throw error+ }},[Commands.PauseTask]: async (taskId: string) => {diff --git a/src/shared/errors.ts b/src/shared/errors.tsindex ac315df2..11547fcc 100644--- a/src/shared/errors.ts+++ b/src/shared/errors.ts@@ -35,6 +35,7 @@ export enum ErrorCode {StunDetectionFailed = 'STUN_DETECTION_FAILED',// TorrentTorrentParseFailed = 'TORRENT_PARSE_FAILED',+ TorrentDuplicateConflict = 'TORRENT_DUPLICATE_CONFLICT',MagnetResolveFailed = 'MAGNET_RESOLVE_FAILED',MagnetResolveTimeout = 'MAGNET_RESOLVE_TIMEOUT',/** Plan B: aria2 cleanup of the magnet metadata fetch is stilldiff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 9fd65228..ddc1f99e 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -808,7 +808,17 @@"saveDirEmpty": "Choose a folder…","changeSaveDir": "Change save directory","created": "Task added",+ "createdCopy": "Separate copy added","createdPartial": "{{ok}} added · {{failed}} failed",+ "duplicate": {+ "title": "This torrent already exists",+ "active-info-hash": "{{name}} is already active. aria2 cannot run the same torrent content twice at the same time.",+ "selection-mismatch": "{{name}} uses the same destination with a different file selection. Motrix will not overwrite it or silently create a renamed copy.",+ "existing-files": "{{name}} already exists in this destination, but its task record is unavailable. Motrix will not overwrite it.",+ "filesOnDisk": "Torrent files",+ "showExisting": "Show existing task",+ "createCopy": "Create separate copy"+ },"adding": "Adding…","interpretedMagnet": "Magnet link detected","interpretedCurl": "cURL command parsed",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 745c80a8..1ea91d36 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -796,7 +796,17 @@"saveDirEmpty": "选择文件夹…","changeSaveDir": "更改保存目录","created": "任务已添加",+ "createdCopy": "独立副本已添加","createdPartial": "已添加 {{ok}} 个,{{failed}} 个失败",+ "duplicate": {+ "title": "此种子已经存在",+ "active-info-hash": "“{{name}}”正在运行。aria2 无法同时运行两个内容相同的种子任务。",+ "selection-mismatch": "“{{name}}”使用了相同保存目录,但文件选择不同。Motrix 不会覆盖它,也不会静默创建重命名副本。",+ "existing-files": "目标位置已经存在“{{name}}”,但对应任务记录不可用。Motrix 不会覆盖这些文件。",+ "filesOnDisk": "种子文件",+ "showExisting": "查看已有任务",+ "createCopy": "创建独立副本"+ },"adding": "添加中…","interpretedMagnet": "已识别磁力链接","interpretedCurl": "已解析 cURL 命令",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 287db88d..65545249 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -796,7 +796,17 @@"saveDirEmpty": "選擇資料夾...","changeSaveDir": "變更儲存目錄","created": "已新增任務",+ "createdCopy": "已新增獨立副本","createdPartial": "已新增 {{ok}} 個,{{failed}} 個失敗",+ "duplicate": {+ "title": "此 Torrent 已經存在",+ "active-info-hash": "「{{name}}」正在執行。aria2 無法同時執行兩個內容相同的 Torrent 任務。",+ "selection-mismatch": "「{{name}}」使用相同儲存目錄,但檔案選取不同。Motrix 不會覆寫它,也不會靜默建立重新命名的副本。",+ "existing-files": "目標位置已存在「{{name}}」,但對應的任務記錄無法使用。Motrix 不會覆寫這些檔案。",+ "filesOnDisk": "Torrent 檔案",+ "showExisting": "顯示現有任務",+ "createCopy": "建立獨立副本"+ },"adding": "正在新增...","interpretedMagnet": "已偵測到 Magnet 連結","interpretedCurl": "已解析 cURL 命令",diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.tsindex d8ea9579..141bd5ff 100644--- a/src/shared/schemas/add-task.ts+++ b/src/shared/schemas/add-task.ts@@ -107,6 +107,9 @@ const btTaskRequestSchema = z// meaningful for torrent-base64 payloads originating from a// MagnetFileSelection event flow.existingTaskId: z.string().min(1).optional(),+ // Duplicate torrent handling is conservative by default. A separate copy+ // is created only after the user explicitly confirms the conflict.+ duplicatePolicy: z.enum(['reuse', 'create-copy']).default('reuse'),}).superRefine((value, ctx) => {if (@@ -125,7 +128,34 @@ export const taskCreateRequestSchema = z.discriminatedUnion('type', [httpTaskRequestSchema,btTaskRequestSchema,])-export type TaskCreateRequest = z.infer<typeof taskCreateRequestSchema>+export type TaskCreateRequest = z.input<typeof taskCreateRequestSchema>++export const torrentDuplicateConflictSchema = z.object({+ reason: z.enum(['active-info-hash', 'selection-mismatch', 'existing-files']),+ infoHash: z.string().length(40),+ targetDir: z.string(),+ existingTaskId: z.string().nullable(),+ existingTaskName: z.string().nullable(),+ existingTaskStatus: z.string().nullable(),+ canCreateCopy: z.boolean(),+})++export type TorrentDuplicateConflict = z.infer<+ typeof torrentDuplicateConflictSchema+>++export type TaskCreateSuccessResult = {+ outcome: 'created' | 'reused' | 'rechecked'+ gid: string+ taskId: string+}++export type TaskCreateCommandResult =+ | TaskCreateSuccessResult+ | {+ outcome: 'conflict'+ conflict: TorrentDuplicateConflict+ }// ── URL params ──────────────────────────────────────────────