Skip to content

A full-featured download manager.

fix(migration): avoid reserving unresolved magnet path hints (#2458)

Dr_rOot6aae74432187
diff --git a/e2e/legacy-import.spec.ts b/e2e/legacy-import.spec.ts
index 566116d2..080f7104 100644
--- a/e2e/legacy-import.spec.ts
+++ b/e2e/legacy-import.spec.ts
@@ -3,6 +3,7 @@ import path from 'node:path'
import type { ElectronApplication, Page } from '@playwright/test'
import { Commands } from '../src/shared/protocol/commands'
import { Queries } from '../src/shared/protocol/queries'
+import type { DownloadTask } from '../src/shared/types/task'
import {
expect,
launchMotrix,
@@ -323,6 +324,84 @@ test.describe('v1 task import', () => {
}
})
+ test('migrates 91 unnamed magnets from one download directory without claiming existing files', async ({
+ userDataDir,
+ rpcPort,
+ }, testInfo) => {
+ const source = await legacyProfile(userDataDir)
+ const downloads = path.join(source, 'downloads')
+ const original = path.join(downloads, 'Magnet')
+ await writeFile(original, 'unrelated original file')
+ const uris = Array.from(
+ { length: 91 },
+ (_, i) => `magnet:?xt=urn:btih:${(i + 1).toString(16).padStart(40, '0')}`
+ )
+ const session = uris
+ .map(
+ (uri, i) =>
+ `${uri}\n gid=${(i + 1).toString(16).padStart(16, '0')}\n pause=true\n`
+ )
+ .join('')
+ await writeFile(path.join(source, 'download.session'), session)
+ await writeFile(
+ path.join(source, 'system.json'),
+ JSON.stringify({
+ dir: downloads,
+ 'all-proxy': 'http://private-user:[email protected]:8080',
+ })
+ )
+ const app = await launchMotrix({
+ userDataDir,
+ rpcPort,
+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },
+ })
+ try {
+ const page = await firstPage(app)
+ await page.getByRole('button', { name: 'Continue', exact: true }).click()
+ await expandTaskGroups(page)
+ await expect(page.getByText(/^Selected 91 tasks\./)).toBeVisible()
+ await expect(
+ page.getByText('Another task uses this location', { exact: false })
+ ).toHaveCount(0)
+ await page.screenshot({
+ path: testInfo.outputPath('unnamed-magnets-selected.png'),
+ animations: 'disabled',
+ })
+ await page.getByRole('button', { name: 'Migrate', exact: true }).click()
+ await expect(
+ page
+ .getByLabel('Migration summary')
+ .getByText('91 tasks', { exact: true })
+ .first()
+ ).toBeVisible()
+ const tasks = (await invoke(page, Queries.ListTasks)) as DownloadTask[]
+ expect(tasks).toHaveLength(91)
+ expect(
+ tasks.every(
+ (task) =>
+ task.type === 'magnet' &&
+ task.status === 'paused' &&
+ task.engineTaskId === '' &&
+ task.instances[0].gid === null
+ )
+ ).toBe(true)
+ expect(tasks.flatMap((task) => task.uris).sort()).toEqual(
+ [...uris].sort()
+ )
+ expect(JSON.stringify(tasks)).not.toContain('old-proxy-secret')
+ await invoke(page, Commands.RemoveTask, {
+ taskId: tasks[0].id,
+ deleteWithFiles: true,
+ })
+ expect(await readFile(original, 'utf8')).toBe('unrelated original file')
+ expect(
+ await readFile(path.join(source, 'download.session'), 'utf8')
+ ).toBe(session)
+ } finally {
+ await app.close().catch(() => {})
+ }
+ })
+
test('retains invalid source paths and recovers through the native folder picker', async ({
userDataDir,
rpcPort,
diff --git a/src/core/legacy-import/bt-activation-service.test.ts b/src/core/legacy-import/bt-activation-service.test.ts
index 557628d1..864e6134 100644
--- a/src/core/legacy-import/bt-activation-service.test.ts
+++ b/src/core/legacy-import/bt-activation-service.test.ts
@@ -5,7 +5,12 @@ import type { EngineAdapter } from '@core/engine/engine-adapter'
import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'
import type { LegacyCheckpointReceipt } from '@shared/schemas/legacy-checkpoint'
import type { DownloadTask } from '@shared/types/task'
-import { TaskStatus } from '@shared/types/task'
+import {
+ TaskInstancePhase,
+ TaskKind,
+ TaskStatus,
+ TaskType,
+} from '@shared/types/task'
import { isLegacyImportInactive } from '@shared/types/task-actions'
import { legacyBtActivationFixture } from '@test-utils/legacy-bt-activation-fixture'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -133,6 +138,51 @@ async function fixture() {
}
describe('durable BT legacy activation', () => {
+ it.each([
+ 'placeholder',
+ 'engine owner',
+ 'metadata owner',
+ 'uncertain activation',
+ 'invalid marker',
+ 'missing payload',
+ ] as const)(
+ 'checks output ownership when a %s magnet has the same path hint',
+ async (state) => {
+ const f = await fixture()
+ const other = structuredClone(f.db.getTask(f.taskId)!)
+ other.task.motrixId = 'other-magnet'
+ other.task.taskType = TaskType.Magnet
+ other.task.kind = TaskKind.Bt
+ other.task.infoHash = null
+ other.task.torrentMetaPath =
+ state === 'metadata owner' ? '/metadata.torrent' : null
+ other.instances[0].instanceId = 'other-magnet-instance'
+ other.instances[0].motrixId = other.task.motrixId
+ other.instances[0].phase = TaskInstancePhase.BtDownload
+ other.instances[0].uris = [`magnet:?xt=urn:btih:${'a'.repeat(40)}`]
+ other.instances[0].gid =
+ state === 'engine owner' ? 'abababababababab' : null
+ if (state === 'uncertain activation')
+ other.instances[0].payload.legacyBtActivation = {}
+ if (state === 'invalid marker')
+ other.instances[0].payload.legacyImport = { version: 1 }
+ if (state === 'missing payload')
+ Reflect.set(other.instances[0], 'payload', null)
+ f.db.saveTaskWithInstances(other)
+ const operation = f.service.activate(f.taskId, async () => f.downloads)
+ if (state === 'placeholder') {
+ await expect(operation).resolves.toBe(true)
+ expect(f.adapter.resumeTask).toHaveBeenCalledOnce()
+ } else {
+ await expect(operation).rejects.toThrow(
+ 'legacyImport.errors.pathConflict'
+ )
+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()
+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()
+ }
+ }
+ )
+
it('binds exact original layout/selection before unpause and backs up actual control bytes', async () => {
const f = await fixture()
const original = await readFile(
diff --git a/src/core/legacy-import/bt-activation-service.ts b/src/core/legacy-import/bt-activation-service.ts
index 81d64af0..ad98d035 100644
--- a/src/core/legacy-import/bt-activation-service.ts
+++ b/src/core/legacy-import/bt-activation-service.ts
@@ -21,6 +21,7 @@ import type { LegacyCheckpointFile } from '@shared/schemas/legacy-checkpoint'
import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'
import { TaskStatus, TaskType } from '@shared/types/task'
import parseTorrent from 'parse-torrent'
+import { isUnresolvedLegacyMagnet } from './legacy-task-policy'
import { authorizeLegacySource, readLegacyFile } from './source-scanner'
export interface LegacyBtActivationDeps {
@@ -377,6 +378,7 @@ export class LegacyBtActivationService {
private async noConflicts(pair: TaskWithInstances): Promise<void> {
const target = outputPathIdentity(pair.task.finalPath)
for (const other of this.deps.db.getAllTasks()) {
+ if (isUnresolvedLegacyMagnet(other)) continue
if (other.task.motrixId === pair.task.motrixId) continue
const claimed = [
other.task.finalPath,
diff --git a/src/core/legacy-import/http-activation-service.test.ts b/src/core/legacy-import/http-activation-service.test.ts
index eb68dd2d..eddba06d 100644
--- a/src/core/legacy-import/http-activation-service.test.ts
+++ b/src/core/legacy-import/http-activation-service.test.ts
@@ -14,7 +14,13 @@ import { CompletedEngineTaskCleanup } from '@core/task/completed-engine-task-cle
import type { LegacyHttpContentVerificationInput } from '@core/task/direct-resource-validator'
import type { LegacyCheckpointReceipt } from '@shared/schemas/legacy-checkpoint'
import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'
-import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import {
+ type DownloadTask,
+ TaskInstancePhase,
+ TaskKind,
+ TaskStatus,
+ TaskType,
+} from '@shared/types/task'
import { canResume, isLegacyImportInactive } from '@shared/types/task-actions'
import {
LEGACY_HTTP_COMPLETED,
@@ -170,6 +176,51 @@ async function fixture(
}
describe('durable HTTP legacy activation', () => {
+ it.each([
+ 'placeholder',
+ 'engine owner',
+ 'metadata owner',
+ 'uncertain activation',
+ 'invalid marker',
+ 'missing payload',
+ ] as const)(
+ 'checks output ownership when a %s magnet has the same path hint',
+ async (state) => {
+ const f = await fixture()
+ const other = structuredClone(f.db.getTask(f.taskId)!)
+ other.task.motrixId = 'other-magnet'
+ other.task.taskType = TaskType.Magnet
+ other.task.kind = TaskKind.Bt
+ other.task.infoHash = null
+ other.task.torrentMetaPath =
+ state === 'metadata owner' ? '/metadata.torrent' : null
+ other.instances[0].instanceId = 'other-magnet-instance'
+ other.instances[0].motrixId = other.task.motrixId
+ other.instances[0].phase = TaskInstancePhase.BtDownload
+ other.instances[0].uris = [`magnet:?xt=urn:btih:${'a'.repeat(40)}`]
+ other.instances[0].gid =
+ state === 'engine owner' ? 'abababababababab' : null
+ if (state === 'uncertain activation')
+ other.instances[0].payload.legacyBtActivation = {}
+ if (state === 'invalid marker')
+ other.instances[0].payload.legacyImport = { version: 1 }
+ if (state === 'missing payload')
+ Reflect.set(other.instances[0], 'payload', null)
+ f.db.saveTaskWithInstances(other)
+ const operation = f.service.activate(f.taskId, async () => f.downloads)
+ if (state === 'placeholder') {
+ await expect(operation).resolves.toBe(true)
+ expect(f.adapter.resumeTask).toHaveBeenCalledOnce()
+ } else {
+ await expect(operation).rejects.toThrow(
+ 'legacyImport.errors.pathConflict'
+ )
+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()
+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()
+ }
+ }
+ )
+
it('replays completion emitted during first resume after the active marker is durable', async () => {
const f = await fixture()
let mutationTail = Promise.resolve()
diff --git a/src/core/legacy-import/http-activation-service.ts b/src/core/legacy-import/http-activation-service.ts
index a3577338..9eaa00af 100644
--- a/src/core/legacy-import/http-activation-service.ts
+++ b/src/core/legacy-import/http-activation-service.ts
@@ -25,6 +25,7 @@ import {
type LegacyHttpRequestContext,
resolveLegacyHttpRequestContext,
} from './http-request-context'
+import { isUnresolvedLegacyMagnet } from './legacy-task-policy'
import { authorizeLegacySource, readLegacyFile } from './source-scanner'
export interface LegacyHttpActivationDeps {
@@ -667,6 +668,7 @@ export class LegacyHttpActivationService {
)
}
for (const other of this.deps.db.getAllTasks()) {
+ if (isUnresolvedLegacyMagnet(other)) continue
if (
other.task.motrixId !== pair.task.motrixId &&
[
diff --git a/src/core/legacy-import/import-service-adversarial.test.ts b/src/core/legacy-import/import-service-adversarial.test.ts
index fa37fc8e..84473de3 100644
--- a/src/core/legacy-import/import-service-adversarial.test.ts
+++ b/src/core/legacy-import/import-service-adversarial.test.ts
@@ -14,7 +14,7 @@ import os from 'node:os'
import path from 'node:path'
import { MotrixDatabase } from '@core/session/motrix-database'
import { TaskManager } from '@core/task/task-manager'
-import { TaskStatus } from '@shared/types/task'
+import { TaskStatus, TaskType } from '@shared/types/task'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
LegacyImportService,
@@ -497,6 +497,143 @@ describe('legacy import service adversarial acceptance', () => {
})
})
+ it.each(['unnamed', 'same display name', 'same output hint'] as const)(
+ 'imports distinct magnets sharing a directory and %s without claiming files',
+ async (kind) => {
+ const f = await fixture()
+ const count = kind === 'unnamed' ? 101 : 2 // Cross the 100-record batch boundary.
+ const name = kind === 'unnamed' ? 'Magnet' : 'shared'
+ const original = path.join(f.downloads, name)
+ await writeFile(original, 'unrelated existing bytes')
+ const uris = Array.from(
+ { length: count },
+ (_, i) =>
+ `magnet:?xt=urn:btih:${(i + 1).toString(16).padStart(40, '0')}${kind === 'same display name' ? '&dn=shared' : ''}`
+ )
+ await writeFile(
+ f.sessionPath,
+ uris
+ .map(
+ (uri, i) =>
+ `${uri}\n gid=${(i + 1).toString(16).padStart(16, '0')}\n${kind === 'same output hint' ? ' out=shared\n' : ''}`
+ )
+ .join('')
+ )
+ const preview = await f.service.scan(f.source.sourceHandle)
+ expect(preview.items.filter((item) => item.selectable)).toHaveLength(
+ count
+ )
+ const run = await f.service.commit({
+ previewId: preview.previewId,
+ itemIds: preview.items.map((item) => item.itemId),
+ })
+ expect(await completed(f.service, run.runId)).toMatchObject({
+ stage: 'completed',
+ imported: count,
+ })
+ const tasks = f.db.getAllTasks()
+ expect(tasks).toHaveLength(count)
+ expect(
+ tasks
+ .flatMap(({ instances }) =>
+ instances.flatMap((instance) => instance.uris)
+ )
+ .sort()
+ ).toEqual([...uris].sort())
+ for (const { task, instances } of tasks) {
+ expect(task.taskType).toBe(TaskType.Magnet)
+ expect(task.aggStatus).toBe(TaskStatus.Paused)
+ expect(task.torrentMetaPath).toBeNull()
+ expect(instances[0].gid).toBeNull()
+ }
+ expect(await readFile(original, 'utf8')).toBe('unrelated existing bytes')
+ const repeated = await f.service.scan(f.source.sourceHandle)
+ expect(
+ repeated.items.every(
+ (item) => !item.selectable && item.reason === 'already-imported'
+ )
+ ).toBe(true)
+ }
+ )
+
+ it('does not let an earlier imported magnet hint block later magnets or real HTTP paths', async () => {
+ const f = await fixture()
+ const first = `magnet:?xt=urn:btih:${'1'.repeat(40)}\n gid=1111111111111111\n`
+ await writeFile(f.sessionPath, first)
+ let preview = await f.service.scan(f.source.sourceHandle)
+ let run = await f.service.commit({
+ previewId: preview.previewId,
+ itemIds: [preview.items[0].itemId],
+ })
+ expect((await completed(f.service, run.runId)).imported).toBe(1)
+ await writeFile(
+ f.sessionPath,
+ first +
+ `magnet:?xt=urn:btih:${'2'.repeat(40)}\n gid=2222222222222222\nhttps://example.test/Magnet\n gid=3333333333333333\n`
+ )
+ const restarted = new LegacyImportService(f.deps)
+ const source = await restarted.addSource(f.sourceRoot)
+ preview = await restarted.scan(source.sourceHandle)
+ expect(preview.items.map((item) => item.selectable)).toEqual([
+ false,
+ true,
+ true,
+ ])
+ run = await restarted.commit({
+ previewId: preview.previewId,
+ itemIds: preview.items
+ .filter((item) => item.selectable)
+ .map((item) => item.itemId),
+ })
+ expect(await completed(restarted, run.runId)).toMatchObject({
+ stage: 'completed',
+ imported: 2,
+ })
+ expect(f.db.getAllTasks()).toHaveLength(3)
+ await restarted.drain()
+ // A real HTTP target continues to reserve its path; another magnet is only a record.
+ await writeFile(
+ f.sessionPath,
+ `https://other.test/Magnet\n gid=4444444444444444\nmagnet:?xt=urn:btih:${'3'.repeat(40)}\n gid=5555555555555555\n`
+ )
+ preview = await f.service.scan(f.source.sourceHandle)
+ expect(preview.items[0]).toMatchObject({
+ selectable: false,
+ reason: 'path-conflict',
+ })
+ expect(preview.items[1]).toMatchObject({
+ selectable: true,
+ reason: 'metadata-required',
+ })
+ })
+
+ it('preserves GID-less magnet deletion identity when v1 rewrites its pause flag', async () => {
+ const f = await fixture()
+ const uri = `magnet:?xt=urn:btih:${'1'.repeat(40)}`
+ await writeFile(f.sessionPath, `${uri}\n pause=true\n`)
+ const preview = await f.service.scan(f.source.sourceHandle)
+ const run = await f.service.commit({
+ previewId: preview.previewId,
+ itemIds: [preview.items[0].itemId],
+ })
+ const report = await completed(f.service, run.runId)
+ f.db.deleteTask(report.items[0].taskId!)
+ await writeFile(
+ f.sessionPath,
+ `${uri}\n pause=false\nmagnet:?xt=urn:btih:${'2'.repeat(40)}\n`
+ )
+ const next = await f.service.scan(f.source.sourceHandle)
+ expect(next.items[0]).toMatchObject({
+ itemId: preview.items[0].itemId,
+ selectable: false,
+ reason: 'deleted-import',
+ })
+ expect(next.items[1]).toMatchObject({
+ selectable: true,
+ reason: 'metadata-required',
+ })
+ })
+
it('imports a proxy-dependent magnet inactive with stripped option names and no request secrets', async () => {
const f = await fixture()
const session = [
diff --git a/src/core/legacy-import/import-service.ts b/src/core/legacy-import/import-service.ts
index 653c7bf4..2bb072b0 100644
--- a/src/core/legacy-import/import-service.ts
+++ b/src/core/legacy-import/import-service.ts
@@ -25,6 +25,7 @@ import {
TaskType,
TransitionPhase,
} from '@shared/types/task'
+import { isUnresolvedLegacyMagnet } from './legacy-task-policy'
import {
authorizeLegacySource,
authorizeLegacyTorrent,
@@ -242,7 +243,11 @@ export class LegacyImportService {
: ledger.entry_digest !== candidate.entry.digest
? 'changed-source'
: 'already-imported'
- } else if (candidate.item.selectable && candidate.outputPath) {
+ } else if (
+ candidate.item.selectable &&
+ candidate.outputPath &&
+ candidate.item.type !== 'magnet'
+ ) {
if (this.overlaps(candidate.outputPath, [...claims, ...pendingPaths])) {
candidate.item.selectable = false
candidate.item.reason = 'path-conflict'
@@ -889,6 +894,7 @@ export class LegacyImportService {
private claimedPaths(): string[] {
return this.deps.db
.getAllTasks()
+ .filter((pair) => !isUnresolvedLegacyMagnet(pair))
.flatMap(({ task, instances }) => [
task.finalPath,
...instances.map((instance) => instance.diskPath),
@@ -916,7 +922,8 @@ export class LegacyImportService {
for (const candidate of candidates) {
if (
!candidate.outputPath ||
- this.overlaps(candidate.outputPath, claims) ||
+ (candidate.item.type !== 'magnet' &&
+ this.overlaps(candidate.outputPath, claims)) ||
this.deps.db.database
.prepare(
'SELECT 1 FROM legacy_import_ledger WHERE source_id=? AND item_key=?'
@@ -924,7 +931,7 @@ export class LegacyImportService {
.get(sourceId, candidate.entry.itemKey)
)
throw this.error('pathConflict')
- claims.push(candidate.outputPath)
+ if (candidate.item.type !== 'magnet') claims.push(candidate.outputPath)
}
}
diff --git a/src/core/legacy-import/legacy-task-policy.ts b/src/core/legacy-import/legacy-task-policy.ts
index 598a0636..036f9900 100644
--- a/src/core/legacy-import/legacy-task-policy.ts
+++ b/src/core/legacy-import/legacy-task-policy.ts
@@ -1,7 +1,9 @@
import { createHash } from 'node:crypto'
import type { EngineAdapter } from '@core/engine/engine-adapter'
+import type { TaskWithInstances } from '@core/session/motrix-database'
import { AppError, ErrorCode } from '@shared/errors'
import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'
+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'
import type { DownloadTask } from '@shared/types/task'
import { TaskInstancePhase, TaskType } from '@shared/types/task'
@@ -15,6 +17,31 @@ import {
isLegacyImportInactive as isInactiveLegacyTask,
} from '@shared/types/task-actions'
+/** A magnet's display/output hint cannot establish file ownership before metadata exists. */
+export function isUnresolvedLegacyMagnet({
+ task,
+ instances,
+}: TaskWithInstances): boolean {
+ const instance = instances[0]
+ const payload = instance?.payload ?? {}
+ if (
+ task.taskType !== TaskType.Magnet ||
+ task.torrentMetaPath ||
+ instances.length !== 1 ||
+ instance.gid ||
+ instance.phase !== TaskInstancePhase.BtDownload ||
+ Object.hasOwn(payload, 'legacyBtActivation') ||
+ Object.hasOwn(payload, 'legacyHttpActivation')
+ )
+ return false
+ const marker = legacyTaskMetadataSchema.safeParse(payload.legacyImport)
+ return (
+ marker.success &&
+ marker.data.activation === 'inactive' &&
+ marker.data.storagePolicy === 'legacy-read-only'
+ )
+}
+
export function assertLegacyTaskNotActivated(
task: Pick<DownloadTask, 'instances'>
): void {