A full-featured download manager.
fix(bt): persist magnet file metadata (#1937)
Dr_rOot7e932e617a83
diff --git a/src/core/engine/aria2/aria2-adapter.integration.test.ts b/src/core/engine/aria2/aria2-adapter.integration.test.tsindex 1a96d41d..a0bb5473 100644--- a/src/core/engine/aria2/aria2-adapter.integration.test.ts+++ b/src/core/engine/aria2/aria2-adapter.integration.test.ts@@ -159,10 +159,12 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(return result.length === 2 ? result : null}, 3000)expect(files).toHaveLength(2)- const f1 = files.find((f) => f.index === 1)- const f2 = files.find((f) => f.index === 2)- expect(f1?.selected).toBe(true)- expect(f2?.selected).toBe(false)+ // AddTorrentParams is aria2-native (1-based), while TaskFile is a+ // domain model and therefore exposes 0-based indexes.+ const firstFile = files.find((f) => f.index === 0)+ const secondFile = files.find((f) => f.index === 1)+ expect(firstFile?.selected).toBe(true)+ expect(secondFile?.selected).toBe(false)await discardTask(adapter, gid)}, 10_000)diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 3c3a228a..8050662b 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -923,14 +923,14 @@ describe('Aria2Adapter', () => {expect(files).toHaveLength(2)expect(files[0]).toEqual({- index: 1,+ index: 0,path: '/tmp/downloads/file1.txt',size: 1048576,completedBytes: 524288,selected: true,})expect(files[1]).toEqual({- index: 2,+ index: 1,path: '/tmp/downloads/file2.txt',size: 2097152,completedBytes: 0,diff --git a/src/core/engine/aria2/translate.test.ts b/src/core/engine/aria2/translate.test.tsindex 5ea7e094..463d16b0 100644--- a/src/core/engine/aria2/translate.test.ts+++ b/src/core/engine/aria2/translate.test.ts@@ -130,6 +130,38 @@ describe('translateRawToTask path fields', () => {expect(task.finalName).toBe('my-torrent')})+ it('BT: normalizes aria2 selected file indices to 0-based domain indices', () => {+ const task = translateRawToTask(+ makeRaw({+ bittorrent: {+ announceList: [],+ mode: 'multi',+ info: { name: 'my-torrent' },+ },+ files: [+ {+ index: '1',+ path: '/downloads/my-torrent.motrix/a.bin',+ length: '400',+ completedLength: '0',+ selected: 'true',+ uris: [],+ },+ {+ index: '3',+ path: '/downloads/my-torrent.motrix/c.bin',+ length: '600',+ completedLength: '0',+ selected: 'true',+ uris: [],+ },+ ],+ })+ )++ expect(task.bt?.selectedFiles).toEqual([0, 2])+ })+// Adopted orphans (restore Pass 1 / poll discovery) mint their display// name from aria2's on-disk file name — which carries the `.motrix`// in-flight placeholder for HTTP tasks. The internal suffix must neverdiff --git a/src/core/engine/aria2/translate.ts b/src/core/engine/aria2/translate.tsindex fa6fd3c3..92354633 100644--- a/src/core/engine/aria2/translate.ts+++ b/src/core/engine/aria2/translate.ts@@ -218,7 +218,10 @@ export function translateBtExtension(trackers: (raw.bittorrent.announceList ?? []).flat(),selectedFiles: (raw.files ?? []).filter((f) => f.selected === 'true')- .map((f) => Number(f.index)),+ // aria2 numbers files from 1; the engine-neutral domain uses 0-based+ // indices (the same convention as TorrentFileInfo and selection+ // commands). Keep that engine detail inside this adapter boundary.+ .map((f) => Number(f.index) - 1),peersInSwarm: 0,seedsInSwarm: 0,announceList: raw.bittorrent.announceList ?? [],@@ -405,7 +408,8 @@ export function translateRawToTask(raw: Aria2RawStatus): DownloadTask {export function translateRawFile(raw: Aria2RawFile): TaskFile {return {- index: Number(raw.index),+ // aria2.getFiles is 1-based; TaskFile is engine-neutral and 0-based.+ index: Number(raw.index) - 1,path: raw.path,size: Number(raw.length),completedBytes: Number(raw.completedLength),diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 88c5c0de..f4a1d2f7 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -2378,7 +2378,7 @@ describe('SessionManager', () => {// override the bt block would carry [0, 1, 2].files: [{- index: '0',+ index: '1',path: '/tmp/multi/a.bin',length: '100',completedLength: '0',@@ -2386,7 +2386,7 @@ describe('SessionManager', () => {uris: [],},{- index: '1',+ index: '2',path: '/tmp/multi/b.bin',length: '200',completedLength: '0',@@ -2394,7 +2394,7 @@ describe('SessionManager', () => {uris: [],},{- index: '2',+ index: '3',path: '/tmp/multi/c.bin',length: '300',completedLength: '0',@@ -2490,7 +2490,7 @@ describe('SessionManager', () => {},files: [{- index: '0',+ index: '1',path: '/tmp/multi/a.bin',length: '100',completedLength: '0',@@ -2498,7 +2498,7 @@ describe('SessionManager', () => {uris: [],},{- index: '1',+ index: '2',path: '/tmp/multi/b.bin',length: '200',completedLength: '0',@@ -2506,7 +2506,7 @@ describe('SessionManager', () => {uris: [],},{- index: '2',+ index: '3',path: '/tmp/multi/c.bin',length: '300',completedLength: '0',diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex c1602d53..95aefe00 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -934,7 +934,7 @@ describe('finalizeTask BT branch', () => {expect(deps.adapter.addTorrent).toHaveBeenCalledWith({metadata: expect.any(Uint8Array),saveDir: '/d/torrent',- selectedFiles: [0, 1],+ selectedFiles: [1, 2],seedTime: 60,seedRatio: 1.5,btSeedUnverified: true,diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex 60519530..9083a73e 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -649,7 +649,7 @@ async function finalizeBtAfterRename()const selectedFiles = task.bt?.selectedFiles?.length- ? task.bt.selectedFiles+ ? task.bt.selectedFiles.map((index) => index + 1): undefinedtry {const storageLayout = getBtStorageLayout(task)diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex 88c42995..8a3070f8 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -116,7 +116,7 @@ describe('reAddTask (BT path)', () => {saveDir: '/tmp/sample',checkIntegrity: true,pause: false,- selectedFiles: [0],+ selectedFiles: [1],}))})@@ -687,9 +687,9 @@ describe('reAddTask reserved GID ownership', () => {})describe('characterization: reAddTask adapter call params', () => {- it('reAddBt passes selectedFiles AS STORED through to addTorrent (no transform)', async () => {- // Uses a non-trivial multi-index value to make the "passed through as-is"- // invariant unmistakable. Task 5 must not silently transform this array.+ it('reAddBt converts 0-based task selection to native 1-based indices', async () => {+ // Uses a non-trivial multi-index value so an accidental pass-through is+ // visible: the task aggregate is engine-neutral, AddTorrentParams is not.const task = makeBtTask({bt: makeDefaultBtExtension({ selectedFiles: [0, 2], isPrivate: true }),})@@ -697,7 +697,7 @@ describe('characterization: reAddTask adapter call params', () => {await reAddTask('t1', deps)const arg = (deps.adapter.addTorrent as ReturnType<typeof vi.fn>).mock.calls[0][0]- expect(arg.selectedFiles).toEqual(task.bt!.selectedFiles)+ expect(arg.selectedFiles).toEqual([1, 3])expect(arg.checkIntegrity).toBe(true)expect(arg.pause).toBe(false)expect(arg.isPrivate).toBe(task.bt!.isPrivate)diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex f1ef5b1d..0a54c569 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -116,6 +116,7 @@ async function reAddBt(const storageLayout = getBtStorageLayout(task)const parsedLayout = storageLayout ? await parseBtFileLayout(metadata) : nullconst completed = task.status === TaskStatus.Completed+ const selectedFiles = task.bt?.selectedFilesreturn deps.adapter.addTorrent({metadata,saveDir: storageLayout@@ -134,7 +135,8 @@ async function reAddBt(: buildStagingOutputFilePaths(parsedLayout, storageLayout): undefined,gid: reservedGid,- selectedFiles: task.bt?.selectedFiles,+ // AddTorrentParams is engine-native; the task aggregate stays 0-based.+ selectedFiles: selectedFiles?.map((index) => index + 1),checkIntegrity: true,pause: false,isPrivate: task.bt?.isPrivate ?? false,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 4c4ebae4..c0c1e301 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@@ -616,6 +616,7 @@ function createTrackingAdapter(options?: {return {adapter: {addTorrent,+ getTaskFiles: vi.fn(async () => []),forceRemoveTask,removeDownloadResult,} as unknown as EngineAdapter,diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.tsindex 456810ff..1372c4e7 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts@@ -250,6 +250,7 @@ function makeMetaInstance(motrixId: string, gid: string): TaskInstanceRow {interface MockAdapter {addTorrent: ReturnType<typeof vi.fn>+ getTaskFiles: ReturnType<typeof vi.fn>forceRemoveTask: ReturnType<typeof vi.fn>removeDownloadResult: ReturnType<typeof vi.fn>}@@ -260,6 +261,7 @@ function createMockAdapter(): MockAdapter {if (!params.gid) throw new Error('test expected a caller-reserved gid')return params.gid}),+ getTaskFiles: vi.fn(async () => []),forceRemoveTask: vi.fn().mockResolvedValue(undefined),removeDownloadResult: vi.fn().mockResolvedValue(undefined),}@@ -679,6 +681,66 @@ describe('swapMagnetMetadataForBt', () => {.calls[0][1]expect(tmTask.id).toBe('m-mag')expect(tmTask.createdAt).toBe(1700000000)+ expect(tmTask.bt.selectedFiles).toEqual([0, 1])+ })++ it('persists complete engine file metadata instead of index placeholders', async () => {+ adapter.getTaskFiles.mockResolvedValueOnce([+ {+ index: 0,+ path: '/Downloads/Show.motrix/episode-01.mkv',+ size: 1_500_000_000,+ completedBytes: 0,+ selected: true,+ },+ {+ index: 1,+ path: '/Downloads/Show.motrix/episode-02.mkv',+ size: 1_600_000_000,+ completedBytes: 0,+ selected: false,+ },+ ])++ const result = await swapMagnetMetadataForBt(+ {+ taskId: 'm-mag',+ base64: 'BASE64TORRENT==',+ selectedFiles: [0],+ saveDir: '/Downloads',+ name: 'Show',+ },+ {+ db,+ taskManager,+ adapter: adapter as never,+ magnetTracker: magnetTracker as never as MagnetTracker,+ publishTaskUpdate: () =>+ eventBus.emit(Events.TaskUpdated, taskManager.getAll()),+ publishTaskUpdateNow: () =>+ eventBus.emit(Events.TaskUpdated, taskManager.getAll()),+ finalNamePicker: finalNamePicker as never,+ torrentMetaStore: torrentMetaStore as never,+ runTaskMutation: runImmediately,+ runExclusivePersistence: persistImmediately,+ }+ )++ expect(adapter.getTaskFiles).toHaveBeenCalledWith(result.gid)+ expect(db.getTaskFiles('m-mag')).toEqual([+ {+ fileIndex: 0,+ path: '/Downloads/Show.motrix/episode-01.mkv',+ size: 1_500_000_000,+ selected: true,+ },+ {+ fileIndex: 1,+ path: '/Downloads/Show.motrix/episode-02.mkv',+ size: 1_600_000_000,+ selected: false,+ },+ ])})it('records MetadataReady-to-Downloading after durability and before publication', async () => {diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.ts b/src/core/torrent/swap-magnet-metadata-for-bt.tsindex 1d7d6878..e1ceccb4 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.ts@@ -473,17 +473,26 @@ async function swapMagnetMetadataForBtUnderMutation(errorCode: null,updatedAt: now,}- const selectedFileRows = selectedFiles.map((fileIndex) => ({+ // This is only a crash-safe fallback for the narrow window between engine+ // acceptance and the authoritative getFiles read below. The former code+ // persisted these placeholders as the final graph, while the background+ // sync treated any existing row as complete; Files then showed blank names+ // and 0 B forever.+ let taskFileRows = selectedFiles.map((fileIndex) => ({fileIndex,- // aria2 populates the actual path on next poll; persisting the user's- // selected indices is what matters here. The poller updates `path` and- // `size` when it observes the row.path: '',size: 0,selected: true,}))+ const restoredDownloadTask = taskRowToDownloadTask(updatedTask, [newInstance])const updatedDownloadTask = {- ...taskRowToDownloadTask(updatedTask, [newInstance]),+ ...restoredDownloadTask,+ bt: restoredDownloadTask.bt+ ? {+ ...restoredDownloadTask.bt,+ selectedFiles: [...selectedFiles],+ }+ : undefined,// Carry over original createdAt so the row stays in its list slot.createdAt: existing.task.createdAt,}@@ -504,11 +513,33 @@ async function swapMagnetMetadataForBtUnderMutation(`engine returned gid ${addedGid} instead of reserved gid ${newGid}`)}+ try {+ const liveFiles = await adapter.getTaskFiles(newGid)+ if (liveFiles.length > 0) {+ // Persist every torrent file, including unselected rows, so the Files+ // tab can render the complete structure and selection state before+ // the first polling tick.+ taskFileRows = liveFiles.map((file) => ({+ fileIndex: file.index,+ path: file.path,+ size: file.size,+ selected: file.selected,+ }))+ }+ } catch (err) {+ // Engine acceptance already succeeded. Keep the durable placeholder+ // graph and let the polling repair path retry rather than turning a+ // transient read failure into a destructive swap rollback.+ log.warn(+ { err, taskId, newGid },+ 'could not hydrate magnet swap file metadata; polling will retry'+ )+ }await deps.runExclusivePersistence(async () => {db.saveTaskWithInstancesAndFiles({task: updatedTask,instances: [newInstance],- files: selectedFileRows,+ files: taskFileRows,})if (recordTransition &&diff --git a/src/main/index.ts b/src/main/index.tsindex b407901d..159108ef 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -805,12 +805,12 @@ async function handlePolledTasks(// Sync task_files whenever the engine reports a non-empty file// list — covers BT/magnet metadata arrival, fresh tasks, AND// legacy tasks restored from a prior session where the auto-sync- // trigger never ran. The helper's own db-emptiness check serves- // as the early-exit, so the cost is ~one prepared-statement query- // per task per poll once synced.+ // trigger never ran, plus placeholder rows written by older magnet+ // swaps. The helper validates structural completeness before its+ // early-exit, so the steady-state cost remains ~one prepared query.if (merged.fileCount > 0) {runShellAsyncWork('task-files sync', () =>- syncTaskFilesIfMissing(existing.id, merged.engineTaskId)+ syncTaskFilesIfIncomplete(existing.id, merged.engineTaskId))}if (!publishedTerminal) taskManager.set(existing.id, merged)@@ -848,7 +848,7 @@ async function handlePolledTasks(// written immediately instead of waiting for a later batch save.if (translated.fileCount > 0) {runShellAsyncWork('task-files orphan sync', () =>- syncTaskFilesIfMissing(id, raw.gid)+ syncTaskFilesIfIncomplete(id, raw.gid))}dirty = true@@ -868,7 +868,7 @@ async function handlePolledTasks(if (dirty) publishTaskUpdate()}-async function syncTaskFilesIfMissing(+async function syncTaskFilesIfIncomplete(taskId: string,engineTaskId: string): Promise<void> {@@ -1139,7 +1139,7 @@ async function startEngineAndRestore(if (!task.bt) continueif (task.fileCount === 0) continuerunShellAsyncWork('startup task-files sync', () =>- syncTaskFilesIfMissing(task.id, task.engineTaskId)+ syncTaskFilesIfIncomplete(task.id, task.engineTaskId))}diff --git a/src/main/ipc/queries/get-task-files.test.ts b/src/main/ipc/queries/get-task-files.test.tsindex ef88fb04..187e1e6e 100644--- a/src/main/ipc/queries/get-task-files.test.ts+++ b/src/main/ipc/queries/get-task-files.test.ts@@ -183,6 +183,57 @@ describe('getTaskFiles handler', () => {expect(result[0]?.selected).toBe(true)})+ it('replaces persisted magnet placeholders from engine for a completed task', async () => {+ const db = {+ getTaskFiles: vi.fn(() => [+ { fileIndex: 0, path: '', size: 0, selected: true },+ { fileIndex: 1, path: '', size: 0, selected: true },+ ]),+ }+ const taskManager = {+ getById: vi.fn(() => mkTask({ status: TaskStatus.Completed })),+ }+ const engine = {+ getTaskFiles: vi.fn(async () => [+ {+ index: 0,+ path: '/Downloads/Show.motrix/episode-01.mkv',+ size: 1_500_000_000,+ completedBytes: 1_500_000_000,+ selected: true,+ },+ {+ index: 1,+ path: '/Downloads/Show.motrix/episode-02.mkv',+ size: 1_600_000_000,+ completedBytes: 1_600_000_000,+ selected: true,+ },+ ]),+ }+ const handler = createGetTaskFilesHandler({+ db,+ taskManager,+ engine,+ } as unknown as Parameters<typeof createGetTaskFilesHandler>[0])++ const result = await handler('t1')++ expect(result).toEqual([+ expect.objectContaining({+ index: 0,+ path: 'episode-01.mkv',+ size: 1_500_000_000,+ }),+ expect.objectContaining({+ index: 1,+ path: 'episode-02.mkv',+ size: 1_600_000_000,+ }),+ ])+ expect(engine.getTaskFiles).toHaveBeenCalledWith('gid1')+ })+it('relativizes absolute file path against task.diskPath (single-file BT)', async () => {// aria2 returns the absolute disk path including the .motrix container.// Provider must strip the diskPath prefix so the UI shows just thediff --git a/src/main/ipc/queries/get-task-files.ts b/src/main/ipc/queries/get-task-files.tsindex 560577c0..c50da6a4 100644--- a/src/main/ipc/queries/get-task-files.ts+++ b/src/main/ipc/queries/get-task-files.ts@@ -43,11 +43,18 @@ export function createGetTaskFilesHandler(deps: Deps) {}))if (!task) return base- if (task.status === TaskStatus.Completed) {+ // Magnet swaps in affected builds persisted selected-index placeholders+ // with empty paths and zero sizes. Treat those rows like an empty cache so+ // an available engine result can supply the real structure immediately;+ // the polling sync repairs the durable rows independently.+ const needsStructure =+ base.length === 0 || base.some((file) => file.path.length === 0)++ if (task.status === TaskStatus.Completed && !needsStructure) {for (const f of base) f.completedBytes = f.sizereturn base}- if (!ACTIVE_STATES.has(task.status)) {+ if (!ACTIVE_STATES.has(task.status) && !needsStructure) {return base}// Coordinator-managed media tasks (Mux/Hls) have no aria2 handle@@ -59,13 +66,11 @@ export function createGetTaskFilesHandler(deps: Deps) {}try {const live = await deps.engine.getTaskFiles(task.engineTaskId)- // db is the source of structure (path/size/selected) once the- // auto-sync trigger has run. Until then — i.e. on the first- // GetTaskFiles call after a fresh task starts, before the poll- // cycle has populated task_files — fall back to engine for the- // full structure too. The persistence-side write happens out of- // band in the poll handler; we don't side-effect from a query.- if (base.length === 0 && live.length > 0) {+ // db is the source of structure (path/size/selected) once the auto-sync+ // has produced complete rows. Before that — an empty fresh-task cache+ // or legacy magnet placeholders — fall back to engine for the full+ // structure. Persistence remains owned by polling; this query is pure.+ if (needsStructure && live.length > 0) {return live.map((f) => ({index: f.index,path: relativize(f.path, task),@@ -81,6 +86,9 @@ export function createGetTaskFilesHandler(deps: Deps) {} catch (err) {log.warn({ err, taskId }, 'engine.getTaskFiles failed; degrading to 0')}+ if (task.status === TaskStatus.Completed) {+ for (const f of base) f.completedBytes = f.size+ }return base}}diff --git a/src/shared/types/task.ts b/src/shared/types/task.tsindex 7310a914..fc67aa97 100644--- a/src/shared/types/task.ts+++ b/src/shared/types/task.ts@@ -150,6 +150,7 @@ export interface BtExtension {seeds: numberratio: numbertrackers: string[]+ /** Selected torrent files using the domain's 0-based indices. */selectedFiles: number[]peersInSwarm: number@@ -269,6 +270,7 @@ export interface BridgeSourceMeta {export type SourceMeta = BridgeSourceMeta | nullexport interface TaskFile {+ /** Engine-neutral 0-based file index. */index: numberpath: stringsize: number