A full-featured download manager.
feat(bt): relocate and verify existing torrent files (#2448)
Dr_rOotea53480f51b0
diff --git a/e2e/downloads-seeding.spec.ts b/e2e/downloads-seeding.spec.tsindex d7de0b62..2b379ff1 100644--- a/e2e/downloads-seeding.spec.ts+++ b/e2e/downloads-seeding.spec.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto'-import { readdir, readFile } from 'node:fs/promises'+import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'import path from 'node:path'import type { Page } from '@playwright/test'import { Commands } from '@shared/protocol/commands'@@ -161,3 +161,185 @@ test('unlimited BT seeding, inspector metrics and re-seeding survive engine restawait fixture.close()}})++test('completed BT files can move, relocate and recheck without losing the task', async ({+ electronApp,+ mainWindow,+ userDataDir,+ rpcPort,+}, testInfo) => {+ test.setTimeout(120_000)+ let page = mainWindow+ let restarted: Awaited<ReturnType<typeof launchMotrix>> | undefined+ try {+ await waitForEngineReady(page)+ const directories = ['original', 'moved', 'external'].map((name) =>+ path.join(userDataDir, name)+ )+ for (const directory of directories)+ await mkdir(directory, { recursive: true })+ const payload = Buffer.from('verified torrent content')+ const metadata = Buffer.concat([+ Buffer.from(+ `d4:infod6:lengthi${payload.length}e4:name8:seed.bin12:piece lengthi16384e6:pieces20:`+ ),+ createHash('sha1').update(payload).digest(),+ Buffer.from('7:privatei1eee'),+ ]).toString('base64')+ await writeFile(path.join(directories[0], 'seed.bin'), payload)+ const invoke = (+ channel:+ | (typeof Commands)[keyof typeof Commands]+ | (typeof Queries)[keyof typeof Queries],+ value?: unknown+ ) =>+ page.evaluate(+ ({ channel, value }) => window.motrix.invoke(channel, value),+ { channel, value }+ )+ await invoke(Commands.UpdateSettings, {+ engine: { seedTime: 0, seedRatio: 0 },+ })+ const request = {+ type: 'bt',+ payload: { kind: 'torrent-base64', base64: metadata },+ selectedFiles: [0],+ saveDir: directories[0],+ }+ expect(await invoke(Commands.CreateTask, request)).toMatchObject({+ outcome: 'conflict',+ conflict: { reason: 'existing-files' },+ })+ const created = (await invoke(Commands.CreateTask, {+ ...request,+ duplicatePolicy: 'use-existing',+ })) as { taskId: string }+ const readTask = async () =>+ ((await invoke(Queries.ListTasks)) as DownloadTask[]).find(+ (task) => task.id === created.taskId+ )!+ await expect.poll(async () => (await readTask())?.status).toBe('seeding')+ const original = await readTask()+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ const openStorage = async (label: string) => {+ await page+ .locator(`[data-task-id="${original.id}"]`)+ .click({ button: 'right' })+ await page.getByRole('menuitem', { name: label, exact: true }).click()+ return page.getByRole('dialog', { name: label, exact: true })+ }+ let dialog = await openStorage('Move files…')+ await electronApp.evaluate(({ dialog }, directory) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [directory],+ })+ }, directories[1])+ await dialog.getByRole('button', { name: 'Browse…', exact: true }).click()+ await expect(dialog.getByLabel('Folder', { exact: true })).toHaveValue(+ directories[1]+ )+ await dialog+ .getByRole('button', { name: 'Move files…', exact: true })+ .click()+ await expect(dialog.getByText('Seeding has resumed.')).toBeVisible({+ timeout: 30_000,+ })+ await expect+ .poll(async () => (await readTask()).finalPath)+ .toBe(path.join(directories[1], 'seed.bin'))+ await expect(+ readFile(path.join(directories[0], 'seed.bin'))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ await dialog+ .getByRole('button', { name: 'Close', exact: true })+ .last()+ .click()+ await invoke(Commands.StopSeedingTask, original.id)+ await expect.poll(async () => (await readTask()).status).toBe('completed')+ await rename(+ path.join(directories[1], 'seed.bin'),+ path.join(directories[2], 'renamed.bin')+ )+ dialog = await openStorage('Find existing files…')+ await electronApp.evaluate(({ dialog }, directory) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [directory],+ })+ }, directories[2])+ await dialog.getByRole('button', { name: 'Browse…', exact: true }).click()+ await expect(dialog.getByLabel('Folder', { exact: true })).toHaveValue(+ directories[2]+ )+ await dialog+ .getByLabel('File or folder name', { exact: true })+ .fill('renamed.bin')+ await dialog+ .getByRole('button', { name: 'Find existing files…', exact: true })+ .click()+ await expect(dialog.getByText('Seeding has resumed.')).toBeVisible({+ timeout: 30_000,+ })+ await expect.poll(async () => (await readTask()).status).toBe('seeding')+ expect(await readTask()).toMatchObject({+ id: original.id,+ createdAt: original.createdAt,+ finalPath: path.join(directories[2], 'renamed.bin'),+ })+ await page.screenshot({+ path: testInfo.outputPath('relocated-seeding.png'),+ })+ // Publishable dialog evidence uses sample paths instead of the test profile.+ await dialog.evaluate((element, privateRoot) => {+ for (const paragraph of element.querySelectorAll('p')) {+ if (paragraph.textContent?.includes(privateRoot))+ paragraph.textContent = paragraph.textContent.replaceAll(+ privateRoot,+ '/Downloads'+ )+ }+ for (const input of element.querySelectorAll('input')) {+ input.value = input.value.replaceAll(privateRoot, '/Downloads')+ if (input.title)+ input.title = input.title.replaceAll(privateRoot, '/Downloads')+ }+ }, userDataDir)+ await dialog.screenshot({+ path: testInfo.outputPath('relocation-dialog-public.png'),+ })+ await dialog+ .getByRole('button', { name: 'Close', exact: true })+ .last()+ .click()+ await electronApp.close()+ restarted = await launchMotrix({ userDataDir, rpcPort })+ page = await restarted.firstWindow()+ await waitForEngineReady(page)+ await expect.poll(async () => (await readTask())?.status).toBe('seeding')+ expect(await readTask()).toMatchObject({+ id: original.id,+ createdAt: original.createdAt,+ finalPath: path.join(directories[2], 'renamed.bin'),+ })+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ await invoke(Commands.StopSeedingTask, original.id)+ const corrupted = Buffer.alloc(payload.length, 0x78)+ await writeFile(path.join(directories[2], 'renamed.bin'), corrupted)+ dialog = await openStorage('Check files…')+ await dialog+ .getByRole('button', { name: 'Check files…', exact: true })+ .click()+ await expect(+ dialog.getByText(/Some files are missing or incomplete/)+ ).toBeVisible({+ timeout: 30_000,+ })+ expect(await readFile(path.join(directories[2], 'renamed.bin'))).toEqual(+ corrupted+ )+ expect((await readTask()).status).toBe('error')+ } finally {+ await restarted?.close()+ }+})diff --git a/screenshots/motrix-bt-relocation-en-light.png b/screenshots/motrix-bt-relocation-en-light.pngnew file mode 100644index 00000000..6d1719e9Binary files /dev/null and b/screenshots/motrix-bt-relocation-en-light.png differdiff --git a/scripts/vite-desktop-locales.ts b/scripts/vite-desktop-locales.tsindex 17b6e9cc..36ccba72 100644--- a/scripts/vite-desktop-locales.ts+++ b/scripts/vite-desktop-locales.ts@@ -1,7 +1,6 @@import type { Plugin } from 'vite'-/** The operator-admin CLI is a separate Server entrypoint. Keep its catalog- * out of the desktop main bundle while preserving all desktop translations. */+/** Keep Server-only and renderer-only catalogs out of the desktop main bundle. */export function desktopLocaleProjection(localeDirectory: string): Plugin {const prefix = `${localeDirectory.replaceAll('\\', '/')}/`return {@@ -12,6 +11,19 @@ export function desktopLocaleProjection(localeDirectory: string): Plugin {if (!file?.startsWith(prefix) || !file.endsWith('.json')) return nullconst catalog = JSON.parse(source) as Record<string, unknown>delete catalog.operatorAdmin+ const task = catalog.task as Record<string, unknown> | undefined+ const add = task?.add as Record<string, unknown> | undefined+ if (add) delete add.duplicate+ const storage = task?.storage as Record<string, unknown> | undefined+ if (task && storage) {+ // Dialogs load their full catalog in the renderer. Keep every key+ // emitted as a host-side error or persisted task diagnostic.+ task.storage = {+ incomplete: storage.incomplete,+ resumeFailed: storage.resumeFailed,+ errors: storage.errors,+ }+ }return { code: JSON.stringify(catalog), map: null }},}diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex 50538391..b041721e 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -926,6 +926,14 @@ export class Aria2Adapter implements EngineAdapter {opts[k] = v}}+ if (params.preserveExistingFiles)+ Object.assign(opts, {+ 'allow-overwrite': 'false',+ 'auto-file-renaming': 'false',+ 'check-integrity': 'true',+ 'bt-seed-unverified': 'false',+ 'bt-remove-unselected-file': 'false',+ })if (params.legacyCheckpointActivation) {if (!params.pause ||diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex 6d0073fa..583a3171 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -79,6 +79,8 @@ export interface AddTorrentParams {// not exist"). Used by SessionManager when re-adding a task whose data// file is still on disk from a prior session.checkIntegrity?: boolean+ /** Verified adoption must not inherit overwrite, rename or unchecked-seeding settings. */+ preserveExistingFiles?: booleanisPrivate?: boolean/** Prefer early and late pieces for a metadata-confirmed video-only* torrent. Concrete adapters translate this product policy. */diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.tsindex f6f67c71..f2284302 100644--- a/src/core/session/durable-finalize-runtime.ts+++ b/src/core/session/durable-finalize-runtime.ts@@ -38,6 +38,10 @@ export interface DurableFinalizeArtifactInput {postDeliveries: readonly PostDeliveryAdmission[]beforeCommit?: () => voidfileRebase?: { sourceRoot: string; targetRoot: string }+ /** Read-only payload validation while engine and plugin writers are quiesced. */+ verifySource?: () => Promise<void>+ /** Synchronous publication before another session snapshot can save stale paths. */+ onCommitted?: () => void}export interface DurableFinalizeRuntimeOptions {@@ -58,6 +62,18 @@ export class DurableFinalizeRuntime {this.now = options.now ?? Date.now}+ async withArtifactLease<T>(+ taskId: string,+ operation: () => Promise<T>+ ): Promise<T> {+ const lease = await this.leases.acquire(taskId)+ try {+ return await operation()+ } finally {+ await lease.release()+ }+ }+async commit(input: DurableFinalizeArtifactInput): Promise<FinalizeCommitResult> {@@ -97,6 +113,7 @@ export class DurableFinalizeRuntime {const lease = await this.leases.acquire(input.task.id)try {await this.createRecovery().recoverTask(input.task.id, lease)+ await input.verifySource?.()const pending = (await this.createRepository().listRecoverable(input.task.id)).find((record) => record.publicationIntent?.method === 'reserved_rename')@@ -196,6 +213,7 @@ export class DurableFinalizeRuntime {(pending.phase !== 'cleaned' && pending.phase !== 'db_committed'))throw new Error('reserved publication recovery did not commit')+ input.onCommitted?.()return {journalId: pending.journalId,targetPath: pending.plan.targetPath,@@ -223,7 +241,11 @@ export class DurableFinalizeRuntime {sameContent: artifactContentEquals,})input.beforeCommit?.()- return committer.commit(plan, lease)+ const result = await committer.commit(plan, lease)+ // SQLite's outer durable transaction has committed, but the session+ // persistence lane is still held. Publish before queued autosaves.+ input.onCommitted?.()+ return result})} finally {diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 42375e61..8ca8a21d 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -1659,10 +1659,43 @@ describe('SessionManager', () => {expect(restored?.downloadedBytes).toBe(250)// 250 / 1000 = 0.25 — derived from saved mirror, not hardcoded 0.expect(restored?.progress).toBe(0.25)+ expect(restored?.uploadedBytes).toBe(100)+ expect(restored?.uploadedBytesBaseline).toBe(100)+ expect(restored?.instances[0]?.uploadedBytes).toBe(0)fs.rmSync(tmpDir, { recursive: true, force: true })})+ it.each([TaskStatus.Completed, TaskStatus.Error])(+ 'retains settled upload after storage stops a %s torrent',+ async (status) => {+ for (const uploadedBytes of [0, 1000]) {+ const gid = `storage-${uploadedBytes}`+ seedAsPair(db, {+ motrixId: gid,+ gid,+ type: TaskType.Bt,+ status,+ totalBytes: 1000,+ downloadedBytes: 1000,+ uploadedBytes,+ uploadedBytesBaseline: 1000,+ payload: { btFinalizeUpload: { gid, bytes: 1000 } },+ })+ }+ rpc.tellActive = vi.fn(async () => [])+ rpc.tellWaiting = vi.fn(async () => [])+ rpc.tellStopped = vi.fn(async () => [])+ await sessionManager.restore()+ for (const uploadedBytes of [0, 1000]) {+ const restored = taskManager.getById(`storage-${uploadedBytes}`)+ expect(restored?.uploadedBytes).toBe(1000)+ expect(restored?.uploadedBytesBaseline).toBe(1000)+ expect(restored?.bt?.ratio).toBe(1)+ }+ }+ )+it('restores a live retiring GID without counting its settled upload twice', async () => {const gid = 'settled-finalize-gid'seedAsPair(db, {diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 372edf92..881d6d09 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -531,6 +531,27 @@ export class SessionManager {})}+ /** Rebind verified local files without emitting a second completion occurrence. */+ persistBtStorage(+ task: DownloadTask,+ sourceRoot: string,+ targetRoot: string+ ): Promise<void> {+ if (this.stopping)+ return Promise.reject(new Error('SessionManager is stopping'))+ return this.runExclusivePersistence(async () => {+ const payload = await this.buildTaskPayload(task, Date.now())+ this.db.commitTerminalHookBoundary({+ payload,+ occurrence: null,+ metadataOps: [],+ postDeliveries: [],+ fileRebase: { sourceRoot, targetRoot },+ })+ this.taskManager.set(task.id, structuredClone(task))+ })+ }+private observeAdmissionResults(deliveries: NonNullable<TerminalHookCommitInput['postDeliveries']>,summary: PostDeliveryAdmissionSummary@@ -1444,19 +1465,21 @@ export class SessionManager {const primary = pair.instances[0]const taskType = taskPart.taskTypeconst isBtLike = isTorrentLikeType(taskType)- // gid swap: lift baseline so cumulative upload survives across reAdd- // (the new aria2 row starts uploadLength at 0). When newGid === primary- // gid (Pass-2 Completed retention) keep baseline as is.+ // Restore the same settled-baseline + current-GID accounting used by the+ // canonical row mapper; retained terminal instances can have stale counters.+ const uploadedBytes =+ taskPart.uploadedBytesBaseline ++ unsettledBtUpload(+ pair.instances,+ primary?.gid ?? '',+ primary?.uploadedBytes ?? 0+ )const uploadedBytesBaseline =- newGid !== primary?.gid- ? Math.max(taskPart.uploadedBytesBaseline, primary?.uploadedBytes ?? 0)- : taskPart.uploadedBytesBaseline+ newGid !== primary?.gid ? uploadedBytes : taskPart.uploadedBytesBaselineconst bt = isBtLike? makeDefaultBtExtension({ratio:- taskPart.totalBytes > 0- ? (primary?.uploadedBytes ?? 0) / taskPart.totalBytes- : 0,+ taskPart.totalBytes > 0 ? uploadedBytes / taskPart.totalBytes : 0,trackers: taskPart.trackers.flat(),announceList: taskPart.trackers,isPrivate: taskPart.isPrivate,@@ -1496,10 +1519,7 @@ export class SessionManager {createdAt: taskPart.createdAt,updatedAt: retainedIdentity ? taskPart.updatedAt : now,uris: primary?.uris ?? [],- uploadedBytes:- newGid !== primary?.gid- ? uploadedBytesBaseline- : (primary?.uploadedBytes ?? 0),+ uploadedBytes,uploadedBytesBaseline,fileCount: taskPart.fileCount,connections: 0,@@ -1525,6 +1545,7 @@ export class SessionManager {? {...inst,gid: newGid,+ uploadedBytes: retainedIdentity ? inst.uploadedBytes : 0,status: nextStatus,updatedAt: retainedIdentity ? inst.updatedAt : now,}@@ -1605,6 +1626,7 @@ export class SessionManager {: undefined,pause: taskPart.aggStatus === TaskStatus.Paused,checkIntegrity: true,+ preserveExistingFiles: true,...(prioritizePreviewPieces? { prioritizePreviewPieces: true }: {}),diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex db7e23d9..a902b32f 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -195,6 +195,7 @@ async function reAddBt(// AddTorrentParams is engine-native; the task aggregate stays 0-based.selectedFiles: selectedFiles?.map((index) => index + 1),checkIntegrity: true,+ preserveExistingFiles: true,pause: false,isPrivate: task.bt?.isPrivate ?? false,...(prioritizePreviewPieces ? { prioritizePreviewPieces: true } : {}),diff --git a/src/core/task/actions/shared.test.ts b/src/core/task/actions/shared.test.tsindex 50d00b22..d05dcaf7 100644--- a/src/core/task/actions/shared.test.ts+++ b/src/core/task/actions/shared.test.ts@@ -433,6 +433,29 @@ describe('commitTaskUpdate', () => {})describe('commitPolledTerminalTransition', () => {+ it('drops a stale terminal snapshot after a storage mutation changed the task', async () => {+ let current = true+ const persistTaskWithOccurrence = vi.fn(async () => {})+ const publish = vi.fn()+ const result = await commitPolledTerminalTransition(+ TaskStatus.Seeding,+ makeDownloadTask({ status: TaskStatus.Completed, finishedAt: 10 }),+ {+ isCurrent: () => current,+ persistTaskWithOccurrence,+ publish,+ log: { warn: vi.fn() },+ runTaskMutation: async (_ids, operation) => {+ current = false+ return operation()+ },+ }+ )+ expect(result).toBe('stale')+ expect(persistTaskWithOccurrence).not.toHaveBeenCalled()+ expect(publish).not.toHaveBeenCalled()+ })+it('a poll-detected Error emits exactly one occurrence; a later commit of the same terminal state emits none', async () => {const persistTaskWithOccurrence = vi.fn(async () => undefined)const dispatch = vi.fn(async () => undefined)diff --git a/src/core/task/actions/shared.ts b/src/core/task/actions/shared.tsindex 7dfdbae1..eb931a46 100644--- a/src/core/task/actions/shared.ts+++ b/src/core/task/actions/shared.ts@@ -251,6 +251,8 @@ export function getTaskOrWarn(}export interface PollTerminalCommitDeps {+ /** Revalidate the snapshot after acquiring the task mutation lane. */+ isCurrent?: () => booleanpersistTaskWithOccurrence: (task: DownloadTask,occurrence: TaskOccurrence | null@@ -272,6 +274,7 @@ export interface PollTerminalCommitDeps {/*** `'not-terminal'` — nothing to commit; the caller publishes as usual.* `'published'` — durably written and published by this function.+ * `'stale'` — task ownership changed while this snapshot waited for its lock.* `'persist-failed'` — the write failed and nothing was published; the* caller must leave the previous in-memory state alone so the next poll* observes the same delta and retries.@@ -280,6 +283,7 @@ export type PolledTerminalCommitOutcome =| 'not-terminal'| 'published'| 'persist-failed'+ | 'stale'/*** Commit a poll-detected transition into Completed/Error through the@@ -320,6 +324,7 @@ export async function commitPolledTerminalTransition(if (!occurrence) return 'not-terminal'const commit = async (): Promise<PolledTerminalCommitOutcome> => {+ if (deps.isCurrent && !deps.isCurrent()) return 'stale'try {await deps.persistTaskWithOccurrence(task, occurrence)} catch (err) {diff --git a/src/core/task/active-downloads.ts b/src/core/task/active-downloads.tsindex 9a3a3a2b..f3d19633 100644--- a/src/core/task/active-downloads.ts+++ b/src/core/task/active-downloads.ts@@ -12,7 +12,9 @@ const ACTIVE_DOWNLOAD_STATUSES = new Set<TaskStatus>([])export function isActiveDownload(task: DownloadTask): boolean {- return ACTIVE_DOWNLOAD_STATUSES.has(task.status)+ return (+ task.storageOperation === true || ACTIVE_DOWNLOAD_STATUSES.has(task.status)+ )}export function countActiveDownloads(tasks: DownloadTask[]): number {diff --git a/src/core/task/bt-duplicate-policy.test.ts b/src/core/task/bt-duplicate-policy.test.tsindex dd78fdc6..8f56a020 100644--- a/src/core/task/bt-duplicate-policy.test.ts+++ b/src/core/task/bt-duplicate-policy.test.ts@@ -14,6 +14,8 @@ import {inspectBtDuplicate,normalizeBtInfoHash,reservedBtFinalNames,+ withBtOutputAdmission,+ withBtOutputAdmissions,} from './bt-duplicate-policy'const INFO_HASH = 'a03e3f9a05341aa336e9d9d3f06b33cddafe0bdc'@@ -309,3 +311,43 @@ it('reserves all failed magnet targets even outside the original save root', ()])expect(reservedBtFinalNames([task], '/new', task.id)).toEqual([])})++describe('hierarchical output admission', () => {+ it('blocks creation beneath either directory of a move and allows unrelated directories', async () => {+ const hold = Promise.withResolvers<void>()+ const entered = Promise.withResolvers<void>()+ const events: string[] = []+ const move = withBtOutputAdmissions(['/source', '/target'], async () => {+ events.push('move')+ entered.resolve()+ await hold.promise+ })+ await entered.promise+ const child = withBtOutputAdmission('/source/torrent/subdir', async () => {+ events.push('child')+ })+ const target = withBtOutputAdmission('/target/torrent', async () => {+ events.push('target')+ })+ await withBtOutputAdmission('/unrelated', async () => {+ events.push('unrelated')+ })+ expect(events).toEqual(['move', 'unrelated'])+ hold.resolve()+ await Promise.all([move, child, target])+ expect(events).toEqual(['move', 'unrelated', 'child', 'target'])+ })++ it('serializes reverse moves without acquiring directories in opposite orders', async () => {+ const events: number[] = []+ await Promise.all([+ withBtOutputAdmissions(['/a', '/b'], async () => {+ events.push(1)+ }),+ withBtOutputAdmissions(['/b', '/a'], async () => {+ events.push(2)+ }),+ ])+ expect(events).toEqual([1, 2])+ })+})diff --git a/src/core/task/bt-duplicate-policy.ts b/src/core/task/bt-duplicate-policy.tsindex d490d70a..1d72494a 100644--- a/src/core/task/bt-duplicate-policy.ts+++ b/src/core/task/bt-duplicate-policy.ts@@ -33,11 +33,50 @@ export async function withBtOutputAdmission<T>(saveDir: string,operation: () => Promise<T>): Promise<T> {- const key = canonicalBtPath(saveDir)- const release = await acquireBtAdmission(`output:${key}`)+ return withBtOutputAdmissions([saveDir], operation)+}++const outputAdmissions = new Set<{ roots: string[]; settled: Promise<void> }>()++function directoriesOverlap(a: string, b: string): boolean {+ const within = (root: string, candidate: string) => {+ const relative = path.relative(root, candidate)+ return (+ relative === '' ||+ (relative !== '..' &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative))+ )+ }+ return within(a, b) || within(b, a)+}++/** Atomically reserve both move roots, including descendant creation, without lock-order cycles. */+export async function withBtOutputAdmissions<T>(+ saveDirs: readonly string[],+ operation: () => Promise<T>+): Promise<T> {+ const roots = [...new Set(saveDirs.map(canonicalBtPath))]+ const predecessors = [...outputAdmissions].filter((entry) =>+ roots.some((root) =>+ entry.roots.some((other) => directoriesOverlap(root, other))+ )+ )+ let release!: () => void+ const entry = {+ roots,+ settled: new Promise<void>((resolve) => {+ release = resolve+ }),+ }+ // Register synchronously before yielding. Every dependency points backwards+ // in admission order, even for simultaneous A→B and B→A moves.+ outputAdmissions.add(entry)try {+ await Promise.all(predecessors.map((previous) => previous.settled))return await operation()} finally {+ outputAdmissions.delete(entry)release()}}diff --git a/src/core/task/bt-file-verifier.test.ts b/src/core/task/bt-file-verifier.test.tsnew file mode 100644index 00000000..2dce8f1d--- /dev/null+++ b/src/core/task/bt-file-verifier.test.ts@@ -0,0 +1,266 @@+import { writeFileSync } from 'node:fs'+// @vitest-environment node+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { storageTorrent } from '@test-utils/bt-storage'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { verifyBtFiles } from './bt-file-verifier'++describe('read-only torrent verification', () => {+ let root: string+ beforeEach(async () => {+ root = await realpath(+ await mkdtemp(path.join(tmpdir(), 'motrix-bt-verify-'))+ )+ })+ afterEach(async () => {+ await rm(root, { recursive: true, force: true })+ })++ it.each(['abcdefghij', 'x', ''])(+ 'checks a single-file torrent without changing its bytes (%s)',+ async (data) => {+ const payloadPath = path.join(root, 'file')+ await writeFile(payloadPath, data)+ const result = await verifyBtFiles({+ metadata: storageTorrent([{ name: 'original', data }]),+ payloadPath,+ })+ expect(result.complete).toBe(true)+ expect(result.validPieces).toBe(Math.ceil(data.length / 4))+ expect(await readFile(payloadPath, 'utf8')).toBe(data)+ }+ )++ it.each(['abcdefghXj', 'abc', 'abcdefghijEXTRA'])(+ 'reports changed or incorrectly sized files without repair (%s)',+ async (actual) => {+ const payloadPath = path.join(root, 'file')+ await writeFile(payloadPath, actual)+ const result = await verifyBtFiles({+ metadata: storageTorrent([{ name: 'file', data: 'abcdefghij' }]),+ payloadPath,+ })+ expect(result.complete).toBe(false)+ expect(await readFile(payloadPath, 'utf8')).toBe(actual)+ }+ )++ it('reports missing data without creating files', async () => {+ const payloadPath = path.join(root, 'file')+ const result = await verifyBtFiles({+ metadata: storageTorrent([{ name: 'file', data: 'abc' }]),+ payloadPath,+ })+ expect(result).toMatchObject({+ complete: false,+ missingFiles: ['file'],+ validPieces: 0,+ })+ await expect(readFile(payloadPath)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ })++ it('checks pieces spanning files, including empty files', async () => {+ const files = [+ { name: 'a', data: 'abc' },+ { name: 'empty', data: '' },+ { name: 'sub/b', data: 'defghi' },+ ]+ await mkdir(path.join(root, 'sub'))+ for (const file of files)+ await writeFile(path.join(root, file.name), file.data)+ expect(+ await verifyBtFiles({+ metadata: storageTorrent(files),+ payloadPath: root,+ })+ ).toMatchObject({ complete: true, totalPieces: 3 })+ })++ it('does not require unrelated unselected pieces', async () => {+ const files = [+ { name: 'a', data: 'abcdefgh' },+ { name: 'b', data: 'ijklmnop' },+ ]+ await writeFile(path.join(root, 'a'), files[0].data)+ expect(+ await verifyBtFiles({+ metadata: storageTorrent(files),+ payloadPath: root,+ selectedFiles: [0],+ })+ ).toMatchObject({ complete: true, totalPieces: 2 })+ })++ it('rejects an oversized unselected file without changing it', async () => {+ const files = [+ { name: 'a', data: 'aaaa' },+ { name: 'b', data: 'bbbb' },+ ]+ await writeFile(path.join(root, 'a'), 'aaaa')+ await writeFile(path.join(root, 'b'), 'unrelated data'.repeat(4))+ const before = await readFile(path.join(root, 'b'))+ expect(+ await verifyBtFiles({+ metadata: storageTorrent(files),+ payloadPath: root,+ selectedFiles: [0],+ })+ ).toMatchObject({ complete: false, invalidFiles: ['bundle/b'] })+ expect(await readFile(path.join(root, 'b'))).toEqual(before)+ })++ it.each(['leaf', 'ancestor'])(+ 'rejects an unselected %s symlink',+ async (kind) => {+ const outside = path.join(root, 'outside')+ const payloadPath = path.join(root, 'payload')+ await mkdir(outside)+ await mkdir(payloadPath)+ await writeFile(path.join(payloadPath, 'a'), 'aaaa')+ await writeFile(path.join(outside, 'b'), 'unrelated data')+ const relative = kind === 'leaf' ? 'b' : 'sub/b'+ await symlink(+ kind === 'leaf' ? path.join(outside, 'b') : outside,+ path.join(payloadPath, kind === 'leaf' ? 'b' : 'sub')+ )+ await expect(+ verifyBtFiles({+ metadata: storageTorrent([+ { name: 'a', data: 'aaaa' },+ { name: relative, data: 'bbbb' },+ ]),+ payloadPath,+ selectedFiles: [0],+ })+ ).rejects.toThrow(/unsafe|regular/)+ expect(await readFile(path.join(outside, 'b'), 'utf8')).toBe(+ 'unrelated data'+ )+ }+ )++ it('rechecks an unselected file changed while selected pieces were hashed', async () => {+ const files = [+ { name: 'a', data: 'aaaaaaaa' },+ { name: 'b', data: 'bbbb' },+ ]+ for (const file of files)+ await writeFile(path.join(root, file.name), file.data)+ let changed = false+ const result = await verifyBtFiles({+ metadata: storageTorrent(files),+ payloadPath: root,+ selectedFiles: [0],+ onProgress: () => {+ if (!changed) {+ changed = true+ writeFileSync(path.join(root, 'b'), 'changed unselected data')+ }+ },+ })+ expect(result).toMatchObject({+ complete: false,+ invalidFiles: ['bundle/b'],+ })+ expect(await readFile(path.join(root, 'b'), 'utf8')).toBe(+ 'changed unselected data'+ )+ })++ it('requires missing adjacent bytes needed by a selected piece', async () => {+ const files = [+ { name: 'a', data: 'abc' },+ { name: 'b', data: 'defgh' },+ ]+ await writeFile(path.join(root, 'a'), files[0].data)+ expect(+ await verifyBtFiles({+ metadata: storageTorrent(files),+ payloadPath: root,+ selectedFiles: [0],+ })+ ).toMatchObject({ complete: false, missingFiles: ['bundle/b'] })+ })++ it.each(['leaf', 'ancestor'])('rejects a symlink at the %s', async (kind) => {+ await mkdir(path.join(root, 'real'))+ await writeFile(path.join(root, 'real', 'file'), 'data')+ if (kind === 'leaf')+ await symlink(path.join(root, 'real', 'file'), path.join(root, 'link'))+ else await symlink(path.join(root, 'real'), path.join(root, 'link'))+ await expect(+ verifyBtFiles({+ metadata: storageTorrent(+ [{ name: kind === 'leaf' ? 'link' : 'link/file', data: 'data' }],+ true+ ),+ payloadPath: root,+ })+ ).rejects.toThrow(/unsafe|regular/)+ })++ it('rejects overlapping metadata paths before opening files', async () => {+ await expect(+ verifyBtFiles({+ metadata: storageTorrent([+ { name: 'a', data: 'a' },+ { name: 'a/b', data: 'b' },+ ]),+ payloadPath: root,+ })+ ).rejects.toThrow('Overlapping')+ })++ it('rejects out-of-range selected indices', async () => {+ await expect(+ verifyBtFiles({+ metadata: storageTorrent([{ name: 'a', data: 'a' }]),+ payloadPath: path.join(root, 'a'),+ selectedFiles: [3],+ })+ ).rejects.toThrow('selection')+ })++ it('rejects files changed after their first pieces were checked', async () => {+ const payloadPath = path.join(root, 'a')+ await writeFile(payloadPath, 'abcdefgh')+ let changed = false+ const result = await verifyBtFiles({+ metadata: storageTorrent([{ name: 'a', data: 'abcdefgh' }]),+ payloadPath,+ onProgress: () => {+ if (!changed) {+ changed = true+ writeFileSync(payloadPath, 'abcdEFGH')+ }+ },+ })+ expect(result.complete).toBe(false)+ })++ it('cancels between pieces without modifying data', async () => {+ const controller = new AbortController()+ await writeFile(path.join(root, 'a'), 'abcdefgh')+ await expect(+ verifyBtFiles({+ metadata: storageTorrent([{ name: 'a', data: 'abcdefgh' }]),+ payloadPath: path.join(root, 'a'),+ signal: controller.signal,+ onProgress: () => controller.abort(),+ })+ ).rejects.toMatchObject({ name: 'AbortError' })+ expect(await readFile(path.join(root, 'a'), 'utf8')).toBe('abcdefgh')+ })+})diff --git a/src/core/task/bt-file-verifier.ts b/src/core/task/bt-file-verifier.tsnew file mode 100644index 00000000..13e2028f--- /dev/null+++ b/src/core/task/bt-file-verifier.ts@@ -0,0 +1,276 @@+import { createHash } from 'node:crypto'+import { constants } from 'node:fs'+import { lstat, open, realpath } from 'node:fs/promises'+import path from 'node:path'+import type { BtVerificationResult } from '@shared/schemas/bt-storage'+import parseTorrent from 'parse-torrent'+import { parseBtFileLayout, UnsafeTorrentPathError } from './bt-storage-layout'++const READ_BYTES = 1024 * 1024+const MAX_EXAMPLES = 10++export interface VerifyBtFilesInput {+ metadata: Uint8Array+ /** Exact payload file or torrent root directory, not its parent. */+ payloadPath: string+ selectedFiles?: readonly number[]+ signal?: AbortSignal+ onProgress?: (checkedPieces: number, totalPieces: number) => void+}++/** Hashes local v1 torrent pieces without opening a writer or a network session. */+export async function verifyBtFiles(+ input: VerifyBtFilesInput+): Promise<BtVerificationResult> {+ input.signal?.throwIfAborted()+ const [layout, parsed] = await Promise.all([+ parseBtFileLayout(input.metadata),+ parseTorrent(input.metadata),+ ])+ const files = parsed.files ?? []+ const pieces = parsed.pieces ?? []+ const pieceLength = parsed.pieceLength ?? 0+ const totalLength = parsed.length ?? -1+ if (+ !Number.isSafeInteger(pieceLength) ||+ pieceLength <= 0 ||+ !Number.isSafeInteger(totalLength) ||+ totalLength < 0 ||+ pieces.length !== Math.ceil(totalLength / pieceLength) ||+ pieces.some((hash) => !/^[a-f0-9]{40}$/i.test(hash))+ )+ throw new UnsafeTorrentPathError('Invalid torrent piece table')++ const selected = new Set(+ input.selectedFiles?.length+ ? input.selectedFiles+ : files.map((_, index) => index)+ )+ if ([...selected].some((index) => !Number.isInteger(index) || !files[index]))+ throw new UnsafeTorrentPathError('Invalid torrent file selection')+ if (!path.isAbsolute(input.payloadPath) || input.payloadPath.includes('\0'))+ throw new UnsafeTorrentPathError('The payload path must be absolute')++ const root = path.resolve(input.payloadPath)+ const parent = await realpath(path.dirname(root))+ const payload = path.join(parent, path.basename(root))+ const names = new Set<string>()+ let offset = 0+ const ranges: Array<[number, number]> = []+ const entries = files.map((file, index) => {+ if (+ !Number.isSafeInteger(file.length) ||+ file.length < 0 ||+ file.offset !== offset+ )+ throw new UnsafeTorrentPathError('Invalid torrent file lengths')+ offset += file.length+ if (!Number.isSafeInteger(offset))+ throw new UnsafeTorrentPathError('Torrent length exceeds the safe range')+ const relative = layout.files[index].pathInsideRoot+ const key = (relative ?? path.basename(payload))+ .normalize('NFC')+ .toLowerCase()+ if (names.has(key))+ throw new UnsafeTorrentPathError('Overlapping torrent paths')+ names.add(key)+ if (selected.has(index) && file.length) {+ const start = Math.floor(file.offset / pieceLength)+ const end = Math.floor((offset - 1) / pieceLength)+ const last = ranges.at(-1)+ if (last && start <= last[1] + 1) last[1] = end+ else ranges.push([start, end])+ }+ return {+ ...file,+ relative,+ absolute: relative === null ? payload : path.join(payload, relative),+ }+ })+ if (offset !== totalLength)+ throw new UnsafeTorrentPathError('Invalid total torrent length')+ for (const name of names) {+ const parts = name.split(path.sep)+ for (let i = 1; i < parts.length; i++)+ if (names.has(parts.slice(0, i).join(path.sep)))+ throw new UnsafeTorrentPathError('Overlapping torrent paths')+ }++ const result: BtVerificationResult = {+ complete: false,+ checkedPieces: 0,+ totalPieces: ranges.reduce(+ (count, [start, end]) => count + end - start + 1,+ 0+ ),+ validPieces: 0,+ missingFiles: [],+ invalidFiles: [],+ }+ const addExample = (list: string[], name: string) => {+ if (list.length < MAX_EXAMPLES && !list.includes(name)) list.push(name)+ }+ const stamps = new Map<string, string>()+ const stamp = (s: Awaited<ReturnType<typeof statFile>>) =>+ `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`+ const missing = (error: unknown) =>+ ['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')+ const inspect = async (entry: (typeof entries)[number]) => {+ // Resolve user-selected parent aliases once; refuse links inside the payload.+ const components =+ entry.relative === null ? [] : entry.relative.split(path.sep).slice(0, -1)+ let directory = payload+ if (layout.multiFile) {+ for (const component of ['', ...components]) {+ if (component) directory = path.join(directory, component)+ const s = await lstat(directory)+ if (!s.isDirectory() || s.isSymbolicLink())+ throw new UnsafeTorrentPathError(+ 'Torrent payload contains an unsafe directory'+ )+ }+ }+ const named = await statFile(entry.absolute)+ if (!named.isFile() || named.isSymbolicLink())+ throw new UnsafeTorrentPathError('Torrent payload is not a regular file')+ if ((await realpath(entry.absolute)) !== entry.absolute)+ throw new UnsafeTorrentPathError('Torrent payload path changed')+ return named+ }++ // aria2 opens existing unselected files too and can truncate oversized ones.+ // Check the whole declared layout, while only hashing selected pieces.+ const inspectLayout = async (initial: boolean) => {+ for (const [index, entry] of entries.entries()) {+ input.signal?.throwIfAborted()+ const previous = stamps.get(entry.absolute)+ try {+ const current = await inspect(entry)+ if (current.size !== BigInt(entry.length))+ addExample(result.invalidFiles, entry.path)+ if (initial) stamps.set(entry.absolute, stamp(current))+ else if (previous !== stamp(current))+ addExample(result.invalidFiles, entry.path)+ } catch (error) {+ if (!missing(error)) throw error+ if (selected.has(index)) addExample(result.missingFiles, entry.path)+ else if (previous !== undefined)+ addExample(result.invalidFiles, entry.path)+ }+ }+ }+ await inspectLayout(true)+ if (result.missingFiles.length || result.invalidFiles.length) return result++ const buffer = Buffer.allocUnsafe(READ_BYTES)+ let current:+ | { index: number; handle: Awaited<ReturnType<typeof open>> }+ | undefined+ const close = async () => {+ const opened = current+ current = undefined+ await opened?.handle.close()+ }+ const read = async (+ index: number,+ position: number,+ length: number,+ hash: ReturnType<typeof createHash>+ ) => {+ const entry = entries[index]+ try {+ if (current?.index !== index) {+ await close()+ const named = await inspect(entry)+ if (named.size !== BigInt(entry.length)) {+ addExample(result.invalidFiles, entry.path)+ return false+ }+ const handle = await open(+ entry.absolute,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK+ )+ current = { index, handle }+ const opened = await handle.stat({ bigint: true })+ if (!opened.isFile() || stamp(named) !== stamp(opened))+ throw new Error('Torrent file changed while opening')+ const previous = stamps.get(entry.absolute)+ if (previous && previous !== stamp(opened))+ throw new Error('Torrent file changed while checking')+ stamps.set(entry.absolute, stamp(opened))+ }+ let remaining = length+ while (remaining > 0) {+ input.signal?.throwIfAborted()+ const { bytesRead } = await current.handle.read(+ buffer,+ 0,+ Math.min(buffer.length, remaining),+ position+ )+ if (bytesRead === 0) {+ addExample(result.invalidFiles, entry.path)+ return false+ }+ hash.update(buffer.subarray(0, bytesRead))+ position += bytesRead+ remaining -= bytesRead+ }+ return true+ } catch (error) {+ if (!missing(error)) throw error+ addExample(result.missingFiles, entry.path)+ return false+ }+ }++ let lastProgress = 0+ try {+ for (const [start, end] of ranges) {+ let fileIndex = entries.findIndex(+ (entry) => entry.offset + entry.length > start * pieceLength+ )+ for (let piece = start; piece <= end; piece++) {+ input.signal?.throwIfAborted()+ const hash = createHash('sha1')+ let position = piece * pieceLength+ const endOffset = Math.min(position + pieceLength, totalLength)+ let valid = true+ while (position < endOffset) {+ const entry = entries[fileIndex]+ if (entry.offset + entry.length <= position) {+ fileIndex+++ continue+ }+ const length =+ Math.min(endOffset, entry.offset + entry.length) - position+ if (!(await read(fileIndex, position - entry.offset, length, hash)))+ valid = false+ position += length+ }+ result.checkedPieces+++ if (valid && hash.digest('hex') === pieces[piece].toLowerCase())+ result.validPieces+++ if (Date.now() - lastProgress >= 200) {+ input.onProgress?.(result.checkedPieces, result.totalPieces)+ lastProgress = Date.now()+ }+ }+ }+ await close()+ await inspectLayout(false)+ input.signal?.throwIfAborted()+ result.complete =+ result.validPieces === result.totalPieces &&+ !result.missingFiles.length &&+ !result.invalidFiles.length+ input.onProgress?.(result.checkedPieces, result.totalPieces)+ return result+ } finally {+ await close()+ }+}++function statFile(filePath: string) {+ return lstat(filePath, { bigint: true })+}diff --git a/src/core/task/bt-output-reservation.ts b/src/core/task/bt-output-reservation.tsindex ae2b7d6b..33576b5b 100644--- a/src/core/task/bt-output-reservation.ts+++ b/src/core/task/bt-output-reservation.ts@@ -1,5 +1,12 @@+import { lstat } from 'node:fs/promises'import path from 'node:path'import type { DownloadTask } from '@shared/types/task'+import { TaskStatus, TaskType } from '@shared/types/task'+import {+ getBtDirectStorageLayout,+ getBtStorageLayout,+} from './bt-storage-layout'+import { outputPathIdentity } from './output-path-identity'export interface BtOutputReservation {finalPath: string@@ -7,6 +14,66 @@ export interface BtOutputReservation {multiFile?: boolean}+/** Single-file engines may read/write a sibling progress file even when metadata is separate. */+export function btOutputPaths(+ payloadPath: string,+ multiFile: boolean+): string[] {+ return multiFile ? [payloadPath] : [payloadPath, `${payloadPath}.aria2`]+}++export async function hasBtControlFile(payloadPath: string): Promise<boolean> {+ try {+ await lstat(`${payloadPath}.aria2`)+ return true+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false+ throw error+ }+}++/** Existing payload adoption/movement cannot take over another task's tree. */+export function hasReservedTaskOutput(+ tasks: readonly DownloadTask[],+ paths: readonly string[],+ excludeTaskId?: string+): boolean {+ const requested = paths.map(outputPathIdentity)+ const within = (root: string, candidate: string) => {+ const relative = path.relative(root, candidate)+ return (+ relative === '' ||+ (relative !== '..' &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative))+ )+ }+ return tasks.some((task) => {+ if (task.id === excludeTaskId || task.status === TaskStatus.Removed)+ return false+ const singleFile =+ getBtDirectStorageLayout(task)?.multiFile === false ||+ getBtStorageLayout(task)?.multiFile === false ||+ task.type === TaskType.Http ||+ task.type === TaskType.Ftp+ return [+ ...[task.finalPath, task.diskPath]+ .filter(Boolean)+ .flatMap((output) => btOutputPaths(output, !singleFile)),+ ...getBtOutputReservations(task).flatMap((entry) =>+ btOutputPaths(entry.finalPath, entry.multiFile === true)+ ),+ ]+ .filter(Boolean)+ .some((output) => {+ const owned = outputPathIdentity(output)+ return requested.some(+ (candidate) => within(owned, candidate) || within(candidate, owned)+ )+ })+ })+}+/** Includes older single-reservation rows and failed attempts at other targets. */export function getBtOutputReservations(task: Pick<DownloadTask, 'instances'>diff --git a/src/core/task/bt-storage-service.test.ts b/src/core/task/bt-storage-service.test.tsnew file mode 100644index 00000000..bf341ac3--- /dev/null+++ b/src/core/task/bt-storage-service.test.ts@@ -0,0 +1,489 @@+// @vitest-environment node+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rename,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { EventBus } from '@core/events/event-bus'+import type { Logger } from '@core/logger'+import type { DurableFinalizeArtifactInput } from '@core/session/durable-finalize-runtime'+import {+ makeDefaultBtExtension,+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { storageTorrent } from '@test-utils/bt-storage'+import { makeDownloadTask } from '@test-utils/task'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { parseBtFileLayout } from './bt-storage-layout'+import {+ authorizeBtDirectory,+ BtStorageService,+ type BtStorageServiceDeps,+} from './bt-storage-service'+import { TaskManager } from './task-manager'++describe('BT storage operations', () => {+ let root: string+ const metadata = storageTorrent([{ name: 'file', data: 'abcdefgh' }])+ beforeEach(async () => {+ root = await realpath(+ await mkdtemp(path.join(tmpdir(), 'motrix-bt-storage-'))+ )+ await mkdir(path.join(root, 'old'))+ await mkdir(path.join(root, 'new'))+ })+ afterEach(async () => {+ await rm(root, { recursive: true, force: true })+ })++ async function setup(status = TaskStatus.Completed) {+ const source = path.join(root, 'old', 'file')+ const target = path.join(root, 'new', 'file')+ await writeFile(source, 'abcdefgh')+ const task = makeDownloadTask({+ id: 'seed',+ type: TaskType.Bt,+ kind: TaskKind.Bt,+ status,+ engineTaskId: '0123456789abcdef',+ saveDir: path.dirname(source),+ diskPath: source,+ finalPath: source,+ finalName: 'file',+ name: 'display name',+ torrentMetaPath: path.join(root, 'metadata.torrent'),+ infoHash: (await parseBtFileLayout(metadata)).infoHash,+ createdAt: 42,+ finishedAt: 43,+ progress: 1,+ totalBytes: 8,+ downloadedBytes: 8,+ uploadedBytes: 20,+ bt: makeDefaultBtExtension({ selectedFiles: [0] }),+ instances: [+ {+ instanceId: 'instance',+ motrixId: 'seed',+ gid: '0123456789abcdef',+ phase: TaskInstancePhase.BtDownload,+ status,+ diskPath: source,+ transitionPhase: TransitionPhase.Idle,+ progress: 1,+ totalBytes: 8,+ downloadedBytes: 8,+ uploadedBytes: 20,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: 42,+ updatedAt: 43,+ },+ ],+ })+ const taskManager = new TaskManager()+ taskManager.add(task)+ const adapter = {+ listActiveAndWaiting: vi.fn(async () => []),+ forceRemoveTask: vi.fn(async () => {}),+ removeDownloadResult: vi.fn(async () => {}),+ getUploadLength: vi.fn(async () => 20),+ addTorrent: vi.fn(async () => 'fedcba9876543210'),+ getTaskStatus: vi.fn(async () => null),+ }+ const saved: unknown[] = []+ const deps: BtStorageServiceDeps = {+ taskManager,+ adapter: adapter as unknown as EngineAdapter,+ eventBus: new EventBus(),+ log: {+ warn: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ debug: vi.fn(),+ } as unknown as Logger,+ torrentMetaStore: {+ read: async () => metadata,+ persist: vi.fn(),+ remove: vi.fn(),+ },+ persistTask: vi.fn(async () => {}),+ persistStorage: vi.fn(async (next, sourceRoot, targetRoot) => {+ saved.push({ task: structuredClone(next), sourceRoot, targetRoot })+ taskManager.set(next.id, structuredClone(next))+ }),+ publishTaskUpdate: vi.fn(),+ publishTaskUpdateNow: vi.fn(),+ runTaskMutation: async (_ids, operation) => operation(),+ authorizeDirectory: authorizeBtDirectory,+ createEngineTaskId: () => 'fedcba9876543210',+ runtime: {+ hasPendingFinalization: vi.fn(async () => false),+ withArtifactLease: vi.fn(async (_id, operation) => operation()),+ commit: vi.fn(async (input: DurableFinalizeArtifactInput) => {+ await input.verifySource?.()+ await rename(input.sourcePath, input.targetPath)+ input.onCommitted?.()+ return {+ journalId: 'journal',+ targetPath: input.targetPath,+ targetIdentity: {+ kind: 'file' as const,+ size: 8,+ sha256: 'sha',+ platformFileId: 'id',+ },+ }+ }),+ },+ }+ return {+ service: new BtStorageService(deps),+ deps,+ task,+ source,+ target,+ adapter,+ saved,+ }+ }++ it('locates already moved files even when the old parent disappeared', async () => {+ const { service, task, source, target, deps, adapter } = await setup()+ await rename(source, target)+ await rm(path.dirname(source), { recursive: true })+ const result = await service.run({+ taskId: task.id,+ mode: 'locate',+ directory: path.dirname(target),+ name: 'file',+ })+ expect(result).toMatchObject({+ path: target,+ verification: { complete: true },+ resumed: false,+ })+ expect(deps.taskManager.getById(task.id)).toMatchObject({+ id: task.id,+ createdAt: 42,+ finishedAt: 43,+ finalPath: target,+ diskPath: target,+ uploadedBytes: 20,+ })+ expect(deps.taskManager.getById(task.id)?.storageOperation).toBeUndefined()+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ expect(deps.runtime.commit).not.toHaveBeenCalled()+ })++ it('moves through the durable runtime and retains identity and upload accounting when reseeding', async () => {+ const { service, task, source, target, deps, adapter } = await setup(+ TaskStatus.Seeding+ )+ const result = await service.run({+ taskId: task.id,+ mode: 'move',+ directory: path.dirname(target),+ name: 'file',+ resume: true,+ })+ expect(result).toMatchObject({ resumed: true, path: target })+ expect(await readFile(target, 'utf8')).toBe('abcdefgh')+ await expect(readFile(source)).rejects.toMatchObject({ code: 'ENOENT' })+ expect(deps.runtime.commit).toHaveBeenCalledWith(+ expect.objectContaining({+ occurrence: null,+ fileRebase: { sourceRoot: source, targetRoot: target },+ })+ )+ expect(adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({+ checkIntegrity: true,+ preserveExistingFiles: true,+ outputRoot: path.dirname(target),+ })+ )+ expect(deps.taskManager.getById(task.id)).toMatchObject({+ createdAt: 42,+ uploadedBytes: 20,+ status: TaskStatus.Seeding,+ })+ })++ it('resolves a selected source-parent alias before native movement', async () => {+ const { service, task, source, target, deps } = await setup()+ const alias = path.join(root, 'alias')+ await symlink(path.dirname(source), alias)+ const aliasedPath = path.join(alias, 'file')+ const owner = structuredClone(task)+ owner.finalPath = owner.diskPath = aliasedPath+ owner.saveDir = alias+ owner.instances[0].diskPath = aliasedPath+ deps.taskManager.set(owner.id, owner)+ expect(+ await service.run({+ taskId: owner.id,+ mode: 'move',+ directory: path.dirname(target),+ name: 'file',+ })+ ).toMatchObject({ path: target })+ expect(deps.runtime.commit).toHaveBeenCalledWith(+ expect.objectContaining({+ sourcePath: source,+ fileRebase: { sourceRoot: aliasedPath, targetRoot: target },+ })+ )+ expect(await readFile(target, 'utf8')).toBe('abcdefgh')+ })++ it('never replaces an occupied destination', async () => {+ const { service, task, source, target, deps, adapter } = await setup()+ await writeFile(target, 'unrelated')+ expect(+ await service.run({+ taskId: task.id,+ mode: 'move',+ directory: path.dirname(target),+ name: 'file',+ })+ ).toEqual({ error: 'destination' })+ expect(await readFile(target, 'utf8')).toBe('unrelated')+ expect(await readFile(source, 'utf8')).toBe('abcdefgh')+ expect(deps.runtime.commit).not.toHaveBeenCalled()+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ })++ it.each(['move', 'locate'] as const)(+ 'rejects a reserved adjacent control file for %s',+ async (mode) => {+ const { service, task, target, deps, adapter } = await setup()+ deps.taskManager.add(+ makeDownloadTask({+ id: 'other',+ finalPath: `${target}.aria2`,+ status: TaskStatus.Queued,+ })+ )+ expect(+ await service.run({+ taskId: task.id,+ mode,+ directory: path.dirname(target),+ name: 'file',+ resume: true,+ })+ ).toEqual({ error: 'conflict' })+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ }+ )++ it.each(['move', 'locate'] as const)(+ 'preserves an unowned adjacent control file for %s',+ async (mode) => {+ const { service, task, target, adapter } = await setup()+ await writeFile(`${target}.aria2`, 'unrelated content')+ expect(+ await service.run({+ taskId: task.id,+ mode,+ directory: path.dirname(target),+ name: 'file',+ resume: true,+ })+ ).toEqual({ error: 'destination' })+ expect(await readFile(`${target}.aria2`, 'utf8')).toBe(+ 'unrelated content'+ )+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ }+ )++ it('permits a same-location recheck with the task own control file', async () => {+ const { service, task, source } = await setup()+ await writeFile(`${source}.aria2`, 'owned checkpoint')+ expect(+ await service.run({ taskId: task.id, mode: 'recheck' })+ ).toMatchObject({ verification: { complete: true } })+ expect(await readFile(`${source}.aria2`, 'utf8')).toBe('owned checkpoint')+ })++ it('does not treat a source payload symlink as ownership of the target sidecar', async () => {+ const { service, task, source, target, adapter } = await setup()+ await rename(source, target)+ await symlink(target, source)+ await writeFile(`${target}.aria2`, 'unrelated content')+ expect(+ await service.run({+ taskId: task.id,+ mode: 'locate',+ directory: path.dirname(target),+ name: 'file',+ resume: true,+ })+ ).toEqual({ error: 'destination' })+ expect(await readFile(`${target}.aria2`, 'utf8')).toBe('unrelated content')+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ })++ it('reserves the control path of an older single-file storage layout', async () => {+ const { service, task, target, deps, adapter } = await setup()+ const owner = structuredClone(task)+ owner.id = 'older'+ owner.engineTaskId = 'older-gid'+ owner.saveDir = path.dirname(target)+ owner.finalPath = owner.diskPath = target+ owner.instances[0].motrixId = owner.id+ owner.instances[0].gid = owner.engineTaskId+ owner.instances[0].diskPath = target+ owner.instances[0].payload.btStorageLayout = {+ version: 1,+ strategy: 'indexed-staging',+ workspacePath: path.join(owner.saveDir, '.motrix', 'a'.repeat(20)),+ payloadEntry: 'p',+ torrentRootName: 'file',+ multiFile: false,+ }+ deps.taskManager.add(owner)+ expect(+ await service.run({+ taskId: task.id,+ mode: 'locate',+ directory: path.dirname(target),+ name: 'file.aria2',+ resume: true,+ })+ ).toEqual({ error: 'conflict' })+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ })++ it('leaves both locations intact when the new files fail verification', async () => {+ const { service, task, source, target, deps, adapter } = await setup()+ await writeFile(target, 'wrong!!!')+ const result = await service.run({+ taskId: task.id,+ mode: 'locate',+ directory: path.dirname(target),+ name: 'file',+ resume: true,+ })+ expect(result).toMatchObject({+ verification: { complete: false },+ path: source,+ resumed: false,+ })+ expect(deps.taskManager.getById(task.id)?.finalPath).toBe(source)+ expect(await readFile(target, 'utf8')).toBe('wrong!!!')+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ })++ it('keeps the new location after an engine admission failure', async () => {+ const { service, task, target, deps, adapter } = await setup()+ adapter.addTorrent.mockRejectedValue(new Error('offline'))+ const result = await service.run({+ taskId: task.id,+ mode: 'move',+ directory: path.dirname(target),+ name: 'file',+ resume: true,+ })+ expect(result).toMatchObject({+ resumeFailed: true,+ resumed: false,+ path: target,+ })+ expect(deps.taskManager.getById(task.id)?.finalPath).toBe(target)+ expect(await readFile(target, 'utf8')).toBe('abcdefgh')+ })++ it('accepts an already-stopped result only after cleanup proves it absent', async () => {+ const { service, task, target, adapter } = await setup()+ adapter.forceRemoveTask.mockRejectedValue(+ new Error('cannot remove stopped download')+ )+ await writeFile(target, 'abcdefgh')+ expect(+ await service.run({+ taskId: task.id,+ mode: 'locate',+ directory: path.dirname(target),+ name: 'file',+ })+ ).toMatchObject({ path: target, verification: { complete: true } })+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith(task.engineTaskId)+ })++ it('does not verify or move until the old engine owner is drained', async () => {+ const { service, task, target, deps, adapter } = await setup(+ TaskStatus.Seeding+ )+ adapter.removeDownloadResult.mockRejectedValue(new Error('still stopping'))+ expect(+ await service.run({+ taskId: task.id,+ mode: 'move',+ directory: path.dirname(target),+ name: 'file',+ })+ ).toEqual({ error: 'engine' })+ expect(deps.runtime.commit).not.toHaveBeenCalled()+ expect(deps.taskManager.getById(task.id)?.storageOperation).toBeUndefined()+ })++ it('rejects another task reserving a destination ancestor', async () => {+ const { service, task, target, deps } = await setup()+ deps.taskManager.add(+ makeDownloadTask({ id: 'other', finalPath: path.dirname(target) })+ )+ expect(+ await service.run({+ taskId: task.id,+ mode: 'locate',+ directory: path.dirname(target),+ name: 'file',+ })+ ).toEqual({ error: 'conflict' })+ })++ it('reports a failed recheck without starting repair downloads', async () => {+ const { service, task, source, deps, adapter } = await setup()+ await writeFile(source, 'broken!!')+ expect(+ await service.run({ taskId: task.id, mode: 'recheck', resume: true })+ ).toMatchObject({ verification: { complete: false }, resumed: false })+ expect(deps.taskManager.getById(task.id)?.status).toBe(TaskStatus.Error)+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ })++ it('cancels before filesystem publication and clears transient busy state', async () => {+ const { service, task, target, deps } = await setup()+ deps.verify = vi.fn(async (input) => {+ service.cancel(task.id)+ input.signal?.throwIfAborted()+ throw new Error('unreachable')+ })+ expect(+ await service.run({+ taskId: task.id,+ mode: 'move',+ directory: path.dirname(target),+ name: 'file',+ })+ ).toEqual({ error: 'cancelled' })+ await expect(readFile(target)).rejects.toMatchObject({ code: 'ENOENT' })+ expect(deps.taskManager.getById(task.id)?.storageOperation).toBeUndefined()+ })+})diff --git a/src/core/task/bt-storage-service.ts b/src/core/task/bt-storage-service.tsnew file mode 100644index 00000000..c184d9c6--- /dev/null+++ b/src/core/task/bt-storage-service.ts@@ -0,0 +1,438 @@+import { lstat, realpath } from 'node:fs/promises'+import path from 'node:path'+import { sanitizeFinalizeFilename } from '@core/fs/finalize-path'+import type { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'+import { DownloadErrorCode } from '@shared/errors'+import { Events } from '@shared/protocol/events'+import {+ type BtStorageCommandResult,+ type BtStorageFailureReason,+ type BtStorageProgress,+ type BtStorageRequest,+ type BtStorageResult,+ type BtVerificationResult,+ btStorageRequestSchema,+} from '@shared/schemas/bt-storage'+import {+ type DownloadTask,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'+import { canManageBtStorage } from '@shared/types/task-actions'+import type { ReAddTaskDeps } from './actions/re-add-task'+import { reAddTask } from './actions/re-add-task'+import {+ acquireBtInfoHashAdmission,+ normalizeBtInfoHash,+ withBtOutputAdmissions,+} from './bt-duplicate-policy'+import { verifyBtFiles } from './bt-file-verifier'+import {+ btOutputPaths,+ hasBtControlFile,+ hasReservedTaskOutput,+} from './bt-output-reservation'+import { btStoragePayload, parseBtFileLayout } from './bt-storage-layout'+import { settleBtUpload } from './bt-upload-settlement'+import { outputPathIdentity } from './output-path-identity'+import {+ collectTaskGids,+ pickPrimaryInstance,+ syncTerminalInstanceStatus,+} from './task-instance'++export interface BtStorageServiceDeps extends ReAddTaskDeps {+ runtime: Pick<+ DurableFinalizeRuntime,+ 'commit' | 'withArtifactLease' | 'hasPendingFinalization'+ >+ /** Both roots and task-file cache rebasing share the same database transaction. */+ persistStorage(+ task: DownloadTask,+ sourceRoot: string,+ targetRoot: string+ ): Promise<void>+ authorizeDirectory(directory: string): Promise<string>+ verify?: typeof verifyBtFiles+}++class StorageFault extends Error {+ constructor(readonly reason: BtStorageFailureReason) {+ super(reason)+ }+}+class IncompleteFiles extends Error {+ constructor(readonly verification: BtVerificationResult) {+ super('incomplete')+ }+}++function overlaps(a: string, b: string): boolean {+ const relative = path.relative(a, b)+ return (+ !relative ||+ (!relative.startsWith(`..${path.sep}`) &&+ relative !== '..' &&+ !path.isAbsolute(relative))+ )+}++/** Owns one quiesced BT task from verification through durable relocation. */+export class BtStorageService {+ private readonly running = new Map<+ string,+ { controller: AbortController; cancellable: boolean }+ >()+ constructor(private readonly deps: BtStorageServiceDeps) {}++ cancel(taskId: string): void {+ const running = this.running.get(taskId)+ if (running?.cancellable) running.controller.abort()+ }++ async run(+ raw: BtStorageRequest,+ admissionHeld = false+ ): Promise<BtStorageCommandResult> {+ const parsed = btStorageRequestSchema.safeParse(raw)+ if (!parsed.success) return { error: 'destination' }+ const request = parsed.data+ if (this.running.has(request.taskId)) return { error: 'busy' }+ const running = { controller: new AbortController(), cancellable: true }+ this.running.set(request.taskId, running)+ try {+ const task = this.deps.taskManager.getById(request.taskId)+ if (!task || !canManageBtStorage(task) || !task.infoHash)+ throw new StorageFault('unavailable')+ const directory = await this.deps.authorizeDirectory(+ request.mode === 'recheck'+ ? path.dirname(task.finalPath)+ : (request.directory ?? '')+ )+ const execute = () =>+ this.deps.runTaskMutation([task.id], () =>+ this.execute(request, directory, running, task.finalPath)+ )+ if (admissionHeld) return await execute()+ const release = await acquireBtInfoHashAdmission(task.infoHash)+ try {+ return await withBtOutputAdmissions(+ request.mode === 'move'+ ? [directory, path.dirname(task.finalPath)]+ : [directory],+ execute+ )+ } finally {+ release()+ }+ } catch (error) {+ if (running.controller.signal.aborted) return { error: 'cancelled' }+ this.deps.log.warn(+ { taskId: request.taskId, error },+ 'BT storage operation failed'+ )+ return { error: error instanceof StorageFault ? error.reason : 'failed' }+ } finally {+ const current = this.deps.taskManager.getById(request.taskId)+ if (current?.storageOperation) {+ const settled = { ...current }+ delete settled.storageOperation+ this.deps.taskManager.set(settled.id, settled)+ this.deps.publishTaskUpdateNow()+ }+ this.running.delete(request.taskId)+ }+ }++ private async execute(+ request: ReturnType<typeof btStorageRequestSchema.parse>,+ directory: string,+ running: { controller: AbortController; cancellable: boolean },+ expectedPath: string+ ): Promise<BtStorageResult> {+ const deps = this.deps+ const original = deps.taskManager.getById(request.taskId)+ if (!original || !canManageBtStorage(original) || !original.torrentMetaPath)+ throw new StorageFault('unavailable')+ if (await deps.runtime.hasPendingFinalization(original.id))+ throw new StorageFault('busy')+ if (original.finalPath !== expectedPath)+ throw new StorageFault('unavailable')+ if ((await deps.authorizeDirectory(directory)) !== directory)+ throw new StorageFault('destination')+ const metadata = await deps.torrentMetaStore.read(original.torrentMetaPath)+ const layout = await parseBtFileLayout(metadata)+ if (layout.infoHash !== normalizeBtInfoHash(original.infoHash ?? ''))+ throw new StorageFault('unavailable')+ const sourcePath = original.finalPath || original.diskPath+ if (+ !sourcePath ||+ outputPathIdentity(sourcePath) ===+ outputPathIdentity(path.parse(sourcePath).root)+ )+ throw new StorageFault('destination')+ // Authorize the old root too: Server must not move/read outside its current policy.+ const source =+ request.mode === 'locate'+ ? sourcePath+ : path.join(+ await deps.authorizeDirectory(path.dirname(sourcePath)),+ path.basename(sourcePath)+ )+ const name =+ request.mode === 'recheck' ? path.basename(source) : (request.name ?? '')+ if (+ !name ||+ name !== sanitizeFinalizeFilename(name) ||+ name === '.' ||+ name === '..'+ )+ throw new StorageFault('destination')+ const target = path.join(directory, name)+ const sourceIdentity = outputPathIdentity(source)+ const targetIdentity = outputPathIdentity(target)+ if (+ request.mode !== 'recheck' &&+ sourceIdentity !== targetIdentity &&+ (overlaps(sourceIdentity, targetIdentity) ||+ overlaps(targetIdentity, sourceIdentity))+ )+ throw new StorageFault('destination')+ if (request.mode === 'move' && sourceIdentity === targetIdentity)+ throw new StorageFault('destination')+ if (+ hasReservedTaskOutput(+ deps.taskManager.getAll(),+ (request.mode === 'move' ? [source, target] : [target]).flatMap(+ (output) => btOutputPaths(output, layout.multiFile)+ ),+ original.id+ )+ )+ throw new StorageFault('conflict')+ if (+ !layout.multiFile &&+ outputPathIdentity(`${sourcePath}.aria2`) !==+ outputPathIdentity(`${target}.aria2`) &&+ (await hasBtControlFile(target))+ )+ throw new StorageFault('destination')+ if (request.mode === 'move') {+ const occupied = await lstat(target).catch((error) => {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ return null+ })+ if (occupied) throw new StorageFault('destination')+ }+ const active = await deps.adapter.listActiveAndWaiting()+ const gids = collectTaskGids(original)+ if (+ active.some(+ (entry) =>+ entry.infoHash?.toLowerCase() === layout.infoHash &&+ !gids.has(entry.gid)+ )+ )+ throw new StorageFault('conflict')+ if (!pickPrimaryInstance(original.instances))+ throw new StorageFault('unavailable')+ running.controller.signal.throwIfAborted()+ deps.taskManager.set(original.id, { ...original, storageOperation: true })+ deps.publishTaskUpdateNow()+ let upload = 0+ try {+ upload = await deps.adapter.getUploadLength(original.engineTaskId)+ } catch {+ /* Retain observed total. */+ }+ // Completion alone is not proof that aria2 released its handles.+ try {+ for (const gid of gids) {+ try {+ await deps.adapter.forceRemoveTask(gid)+ } catch (error) {+ // aria2 rejects forceRemove on an already-stopped result. Result+ // cleanup and the live-owner check below are the absence proof.+ deps.log.debug(+ { gid, error },+ 'BT storage stop request was not accepted'+ )+ }+ await deps.adapter.removeDownloadResult(gid)+ }+ if (+ (await deps.adapter.listActiveAndWaiting()).some((entry) =>+ gids.has(entry.gid)+ )+ )+ throw new StorageFault('engine')+ } catch {+ throw new StorageFault('engine')+ }++ const stopped = structuredClone(original)+ stopped.storageOperation = true+ settleBtUpload(stopped, upload, false)+ stopped.downloadSpeed = 0+ stopped.uploadSpeed = 0+ if (+ stopped.status === TaskStatus.Seeding ||+ stopped.status === TaskStatus.Paused+ ) {+ stopped.status = TaskStatus.Completed+ syncTerminalInstanceStatus(stopped, TaskStatus.Completed)+ }+ // Do not emit another download completion or trigger completion plugins.+ await deps.persistStorage(stopped, sourcePath, sourcePath)+ deps.publishTaskUpdateNow()++ const progress = (+ phase: BtStorageProgress['phase'],+ checkedPieces = 0,+ totalPieces = 0+ ) =>+ deps.eventBus.emit(Events.BtStorageProgress, {+ taskId: stopped.id,+ phase,+ checkedPieces,+ totalPieces,+ } satisfies BtStorageProgress)+ const verify = async (payloadPath: string) => {+ progress('checking')+ if (+ (await deps.authorizeDirectory(path.dirname(payloadPath))) !==+ path.dirname(payloadPath)+ )+ throw new StorageFault('destination')+ const result = await (deps.verify ?? verifyBtFiles)({+ metadata,+ payloadPath,+ selectedFiles: stopped.bt?.selectedFiles,+ signal: running.controller.signal,+ onProgress: (checked, total) => progress('checking', checked, total),+ })+ if (+ (await deps.authorizeDirectory(path.dirname(payloadPath))) !==+ path.dirname(payloadPath)+ )+ throw new StorageFault('destination')+ if (!result.complete) throw new IncompleteFiles(result)+ return result+ }+ const candidate = structuredClone(stopped)+ candidate.saveDir = directory+ candidate.diskPath = target+ candidate.finalPath = target+ candidate.finalName = name+ candidate.filename = name+ if (request.mode !== 'recheck') candidate.name = name+ candidate.status = TaskStatus.Completed+ candidate.progress = 1+ candidate.downloadedBytes = candidate.totalBytes+ candidate.sizeWhenDone = candidate.totalBytes+ candidate.transitionPhase = TransitionPhase.Idle+ candidate.errorCode = null+ candidate.errorMessage = null+ candidate.errorDetailKey = null+ candidate.errorDetailParams = null+ candidate.updatedAt = Date.now()+ syncTerminalInstanceStatus(candidate, TaskStatus.Completed)+ const primary = pickPrimaryInstance(candidate.instances)+ if (!primary) throw new StorageFault('unavailable')+ primary.diskPath = target+ primary.transitionPhase = TransitionPhase.Idle+ primary.payload = {+ ...primary.payload,+ ...btStoragePayload({+ version: 2,+ strategy: 'direct',+ torrentRootName: layout.torrentRootName,+ multiFile: layout.multiFile,+ finalized: true,+ }),+ }+ // Failed output reservations are not permissions to delete earlier locations.+ delete primary.payload.btOutputReservation+ delete primary.payload.btOutputReservations+ let verification!: BtVerificationResult+ try {+ if (request.mode === 'move') {+ await deps.runtime.commit({+ task: candidate,+ occurrence: null,+ sourcePath: source,+ targetPath: target,+ metadataOps: [],+ contributors: [],+ postDeliveries: [],+ fileRebase: { sourceRoot: sourcePath, targetRoot: target },+ verifySource: async () => {+ verification = await verify(source)+ running.controller.signal.throwIfAborted()+ running.cancellable = false+ progress('moving')+ },+ onCommitted: () =>+ deps.taskManager.set(candidate.id, structuredClone(candidate)),+ })+ } else {+ await deps.runtime.withArtifactLease(stopped.id, async () => {+ verification = await verify(target)+ running.controller.signal.throwIfAborted()+ running.cancellable = false+ await deps.persistStorage(candidate, sourcePath, target)+ })+ }+ } catch (error) {+ if (!(error instanceof IncompleteFiles)) throw error+ if (request.mode === 'recheck') {+ const failed = structuredClone(stopped)+ failed.status = TaskStatus.Error+ syncTerminalInstanceStatus(failed, TaskStatus.Error)+ failed.errorCode = DownloadErrorCode.ChecksumMismatch+ failed.errorDetailKey = 'task.storage.incomplete'+ failed.errorDetailParams = null+ await deps.persistStorage(failed, sourcePath, sourcePath)+ deps.publishTaskUpdateNow()+ }+ return {+ taskId: stopped.id,+ path: sourcePath,+ verification: error.verification,+ resumed: false,+ }+ }+ deps.eventBus.emit(Events.TaskFilesUpdated, { taskId: candidate.id })+ deps.publishTaskUpdateNow()+ const result: BtStorageResult = {+ taskId: candidate.id,+ path: target,+ verification,+ resumed: false,+ }+ if (request.resume) {+ progress('resuming')+ try {+ await reAddTask(candidate.id, deps)+ result.resumed = true+ } catch (error) {+ deps.log.warn(+ { taskId: candidate.id, error },+ 'BT storage changed but resuming failed'+ )+ result.resumeFailed = true+ }+ }+ return result+ }+}++/** Desktop canonicalizes selected parent aliases; Server supplies its policy instead. */+export async function authorizeBtDirectory(directory: string): Promise<string> {+ if (!path.isAbsolute(directory) || directory.includes('\0'))+ throw new StorageFault('destination')+ const canonical = await realpath(directory)+ if (!(await lstat(canonical)).isDirectory())+ throw new StorageFault('destination')+ return canonical+}diff --git a/src/core/task/bt-storage.integration.test.ts b/src/core/task/bt-storage.integration.test.tsnew file mode 100644index 00000000..40c632ef--- /dev/null+++ b/src/core/task/bt-storage.integration.test.ts@@ -0,0 +1,274 @@+// @vitest-environment node+import { existsSync } from 'node:fs'+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import type { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { EventBus } from '@core/events/event-bus'+import { getLogger } from '@core/logger'+import { NativeFinalizeFilesystemAdapter } from '@core/plugin/finalize/filesystem-adapter'+import { NativeFinalizeArtifactOperations } from '@core/plugin/finalize/native-artifact-operations'+import { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'+import { MotrixDatabase } from '@core/session/motrix-database'+import { SessionManager } from '@core/session/session-manager'+import {+ makeDefaultBtExtension,+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { storageTorrent } from '@test-utils/bt-storage'+import { makeDownloadTask } from '@test-utils/task'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { parseBtFileLayout } from './bt-storage-layout'+import { authorizeBtDirectory, BtStorageService } from './bt-storage-service'+import { TaskManager } from './task-manager'+import { TorrentMetaStoreImpl } from './torrent-meta-store'++const binary = path.resolve(+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??+ 'packages/finalize-fs/target/debug/motrix-finalize-fs'+)+describe.skipIf(!existsSync(binary))(+ 'BT storage with native publication and SQLite',+ () => {+ const cleanups: Array<() => Promise<void>> = []+ afterEach(async () => {+ vi.restoreAllMocks()+ for (const cleanup of cleanups.splice(0)) await cleanup()+ })++ async function setup(multiFile: boolean) {+ const root = await realpath(+ await mkdtemp(path.join(tmpdir(), 'motrix-bt-native-'))+ )+ await mkdir(path.join(root, 'old'))+ await mkdir(path.join(root, 'new'))+ const source = path.join(root, 'old', 'payload')+ const target = path.join(root, 'new', 'payload')+ const data = 'complete torrent payload'+ const files = multiFile+ ? [+ { name: 'first', data: data.slice(0, 5) },+ { name: 'second', data: data.slice(5) },+ ]+ : [{ name: 'original', data }]+ const metadata = storageTorrent(files, multiFile)+ if (multiFile) {+ await mkdir(source)+ for (const file of files)+ await writeFile(path.join(source, file.name), file.data)+ } else await writeFile(source, data)+ const store = new TorrentMetaStoreImpl(path.join(root, 'metadata'))+ const task = makeDownloadTask({+ id: 'task',+ engineTaskId: '0123456789abcdef',+ type: TaskType.Bt,+ kind: TaskKind.Bt,+ status: TaskStatus.Completed,+ finalPath: source,+ diskPath: source,+ saveDir: path.dirname(source),+ finalName: 'payload',+ name: 'payload',+ torrentMetaPath: await store.persist('task', metadata),+ infoHash: (await parseBtFileLayout(metadata)).infoHash,+ totalBytes: data.length,+ downloadedBytes: data.length,+ progress: 1,+ createdAt: 100,+ finishedAt: 200,+ bt: makeDefaultBtExtension({+ selectedFiles: files.map((_, index) => index),+ }),+ instances: [+ {+ instanceId: 'primary:task',+ motrixId: 'task',+ gid: '0123456789abcdef',+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Completed,+ diskPath: source,+ transitionPhase: TransitionPhase.Idle,+ progress: 1,+ totalBytes: data.length,+ downloadedBytes: data.length,+ uploadedBytes: 0,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: 100,+ updatedAt: 200,+ },+ ],+ })+ const taskManager = new TaskManager()+ taskManager.add(task)+ const adapter = {+ listActiveAndWaiting: async () => [],+ forceRemoveTask: async () => {},+ removeDownloadResult: async () => {},+ getUploadLength: async () => 0,+ } as unknown as EngineAdapter+ const db = new MotrixDatabase(path.join(root, 'motrix.db'))+ db.init()+ const session = new SessionManager(+ taskManager,+ {} as Aria2RpcClient,+ db,+ adapter+ )+ await session.persistTask(task)+ db.replaceTaskFiles(+ task.id,+ files.map((file, fileIndex) => ({+ fileIndex,+ path: multiFile ? path.join(source, file.name) : source,+ size: file.data.length,+ selected: true,+ }))+ )+ const setTask = taskManager.set.bind(taskManager)+ vi.spyOn(taskManager, 'set').mockImplementation((id, next) => {+ if (next.finalPath === target)+ expect(db.database.inTransaction).toBe(false)+ setTask(id, next)+ })+ const native = new NativeFinalizeFilesystemAdapter(binary)+ const fs = new NativeFinalizeArtifactOperations(native)+ const runtime = new DurableFinalizeRuntime({+ db: db.database,+ session,+ fs,+ })+ const service = new BtStorageService({+ taskManager,+ adapter,+ runtime,+ torrentMetaStore: store,+ log: getLogger('storage-test'),+ eventBus: new EventBus(),+ publishTaskUpdate: () => {},+ publishTaskUpdateNow: () => {},+ persistTask: (next) => session.persistTask(next),+ persistStorage: (next, from, to) =>+ session.persistBtStorage(next, from, to),+ authorizeDirectory: authorizeBtDirectory,+ runTaskMutation: async (_ids, operation) => operation(),+ })+ cleanups.push(async () => {+ await native.dispose()+ db.close()+ await rm(root, { recursive: true, force: true })+ })+ return {+ root,+ source,+ target,+ task,+ files,+ data,+ db,+ service,+ fs,+ runtime,+ session,+ taskManager,+ }+ }++ it.each([false, true])(+ 'publishes the payload and file-cache paths atomically (multi-file=%s)',+ async (multiFile) => {+ const f = await setup(multiFile)+ expect(+ await f.service.run({+ taskId: 'task',+ mode: 'move',+ directory: path.dirname(f.target),+ name: 'payload',+ })+ ).toMatchObject({ path: f.target, verification: { complete: true } })+ expect(existsSync(f.source)).toBe(false)+ expect(+ await readFile(+ multiFile ? path.join(f.target, 'second') : f.target,+ 'utf8'+ )+ ).toBe(multiFile ? f.data.slice(5) : f.data)+ expect(f.db.getTask('task')?.task).toMatchObject({+ motrixId: 'task',+ finalPath: f.target,+ createdAt: 100,+ finishedAt: 200,+ })+ expect(f.db.getTask('task')?.instances[0].diskPath).toBe(f.target)+ expect(+ f.db+ .getTaskFiles('task')+ .every((file) => file.path.startsWith(f.target))+ ).toBe(true)+ await f.runtime.recoverAll()+ expect(f.taskManager.getById('task')?.finalPath).toBe(f.target)+ }+ )++ it('uses the verified copy protocol across filesystems', async () => {+ const f = await setup(false)+ vi.spyOn(f.fs, 'sameFilesystem').mockResolvedValue(false)+ const copy = vi.spyOn(f.fs, 'materializePrivate')+ expect(+ await f.service.run({+ taskId: 'task',+ mode: 'move',+ directory: path.dirname(f.target),+ name: 'payload',+ })+ ).toMatchObject({ path: f.target })+ expect(copy).toHaveBeenCalled()+ expect(await readFile(f.target, 'utf8')).toBe(f.data)+ expect(existsSync(f.source)).toBe(false)+ })++ it('restores the original payload and paths when the database commit fails', async () => {+ const f = await setup(true)+ const commit = f.db.commitTerminalHookBoundary.bind(f.db)+ vi.spyOn(f.db, 'commitTerminalHookBoundary').mockImplementation(+ (input) => {+ if (input.payload.task.finalPath === f.target)+ throw new Error('database full')+ return commit(input)+ }+ )+ expect(+ await f.service.run({+ taskId: 'task',+ mode: 'move',+ directory: path.dirname(f.target),+ name: 'payload',+ })+ ).toEqual({ error: 'failed' })+ await f.runtime.recoverAll()+ expect(await readFile(path.join(f.source, 'first'), 'utf8')).toBe(+ f.data.slice(0, 5)+ )+ expect(existsSync(f.target)).toBe(false)+ expect(f.db.getTask('task')?.task.finalPath).toBe(f.source)+ expect(+ f.db+ .getTaskFiles('task')+ .every((file) => file.path.startsWith(f.source))+ ).toBe(true)+ })+ }+)diff --git a/src/core/task/completion-shutdown-controller.test.ts b/src/core/task/completion-shutdown-controller.test.tsindex 752ed95a..9e61a09b 100644--- a/src/core/task/completion-shutdown-controller.test.ts+++ b/src/core/task/completion-shutdown-controller.test.ts@@ -48,6 +48,20 @@ describe('CompletionShutdownController', () => {beforeEach(() => vi.useFakeTimers())afterEach(() => vi.useRealTimers())+ it('does not shut down while verified files are being relocated', async () => {+ const f = fixture()+ await f.controller.setEnabled(true)+ f.setTasks([+ { ...task('one', TaskStatus.Completed), storageOperation: true },+ ])+ await vi.advanceTimersByTimeAsync(90_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ f.controller.dispose()+ })+it('retains tasks that finish while authorization is pending', async () => {const f = fixture()const authorization = Promise.withResolvers<void>()diff --git a/src/core/task/completion-shutdown-controller.ts b/src/core/task/completion-shutdown-controller.tsindex f4b2c5dd..995d838f 100644--- a/src/core/task/completion-shutdown-controller.ts+++ b/src/core/task/completion-shutdown-controller.ts@@ -27,6 +27,7 @@ const COUNTDOWN_MS = 60_000function isFinished(task: DownloadTask): boolean {return (+ !task.storageOperation &&(task.status === TaskStatus.Completed ||task.status === TaskStatus.Seeding) &&task.transitionPhase === TransitionPhase.Idlediff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 3b7981df..e3587e2f 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -22,12 +22,17 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeDownloadTask as makeTestTask } from '@test-utils/task'import { v7 as uuidv7 } from 'uuid'import { beforeEach, describe, expect, it, vi } from 'vitest'import { Aria2Adapter } from '../engine/aria2/aria2-adapter'import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'+import { verifyBtFiles } from './bt-file-verifier'import { parseBtFileLayout } from './bt-storage-layout'import { handleCreateTask } from './create-task-handler'++vi.mock('./bt-file-verifier', () => ({ verifyBtFiles: vi.fn() }))+import {DirectResourceValidatorService,sanitizeRemoteFilename,@@ -56,6 +61,9 @@ const { mkdirMock, fsStub } = vi.hoisted(() => {access: vi.fn(async () => {throw Object.assign(new Error('missing file'), { code: 'ENOENT' })}),+ lstat: vi.fn(async (): Promise<unknown> => {+ throw Object.assign(new Error('missing file'), { code: 'ENOENT' })+ }),mkdir: mkdirMock,stat: vi.fn(async (): Promise<{ isDirectory(): boolean }> => {throw Object.assign(new Error('missing directory'), { code: 'ENOENT' })@@ -3225,3 +3233,174 @@ it.each([expect(httpTask.finalName).not.toBe(httpName)expect(httpTask.diskPath).toBe(`${httpTask.finalPath}.motrix`)})++describe('verified existing torrent adoption', () => {+ const complete = {+ complete: true,+ checkedPieces: 1,+ totalPieces: 1,+ validPieces: 1,+ missingFiles: [],+ invalidFiles: [],+ }+ const request = () => ({+ type: 'bt' as const,+ payload: {+ kind: 'torrent-base64' as const,+ base64: Buffer.from(makePublicTorrentFixture()).toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/d',+ duplicatePolicy: 'use-existing' as const,+ })++ it('verifies the exact existing path before engine admission without allocating a suffix', async () => {+ const deps = makeDeps()+ deps.finalNamePicker.isTaken = vi.fn(async () => true)+ vi.mocked(verifyBtFiles).mockResolvedValue(complete)+ await handleCreateTask(request(), deps)+ expect(verifyBtFiles).toHaveBeenCalledWith(+ expect.objectContaining({+ payloadPath: '/d/public-torrent',+ selectedFiles: [0],+ })+ )+ expect(deps.pick).not.toHaveBeenCalled()+ expect(deps.addTorrent).toHaveBeenCalledWith(+ expect.any(String),+ [],+ expect.objectContaining({+ 'check-integrity': 'true',+ 'allow-overwrite': 'false',+ 'bt-seed-unverified': 'false',+ })+ )+ expect(lastAddedTask(deps).finalPath).toBe('/d/public-torrent')+ })++ it('does not adopt a directory containing another task output', async () => {+ const deps = makeDeps()+ vi.mocked(deps.taskManager.getAll).mockReturnValue([+ makeTestTask({ id: 'other', finalPath: '/d/public-torrent/owned.bin' }),+ ])+ await expect(handleCreateTask(request(), deps)).rejects.toThrow(+ 'task.storage.errors.conflict'+ )+ expect(deps.addTorrent).not.toHaveBeenCalled()+ })++ it('does not adopt over another task pending control-file name', async () => {+ const deps = makeDeps()+ vi.mocked(verifyBtFiles).mockResolvedValue(complete)+ vi.mocked(deps.taskManager.getAll).mockReturnValue([+ makeTestTask({+ id: 'other',+ finalPath: '/d/public-torrent.aria2',+ status: TaskStatus.Queued,+ }),+ ])+ await expect(handleCreateTask(request(), deps)).rejects.toThrow(+ 'task.storage.errors.conflict'+ )+ expect(deps.addTorrent).not.toHaveBeenCalled()+ })++ it('does not adopt files beside an unowned existing control file', async () => {+ const deps = makeDeps()+ fsStub.lstat.mockResolvedValueOnce({})+ await expect(handleCreateTask(request(), deps)).rejects.toThrow(+ 'task.storage.errors.conflict'+ )+ expect(deps.addTorrent).not.toHaveBeenCalled()+ expect(deps.persist).not.toHaveBeenCalled()+ })++ it('does not adopt a payload named as another task control file', async () => {+ const deps = makeDeps()+ vi.mocked(deps.taskManager.getAll).mockReturnValue([+ makeTestTask({+ id: 'other',+ finalPath: '/d/public-torrent',+ status: TaskStatus.Queued,+ }),+ ])+ await expect(+ handleCreateTask(+ { ...request(), displayName: 'public-torrent.aria2' },+ deps+ )+ ).rejects.toThrow('task.storage.errors.conflict')+ expect(deps.addTorrent).not.toHaveBeenCalled()+ })++ it('does not create a task or start the engine for damaged existing files', async () => {+ const deps = makeDeps()+ vi.mocked(verifyBtFiles).mockResolvedValue({+ ...complete,+ complete: false,+ validPieces: 0,+ })+ await expect(handleCreateTask(request(), deps)).rejects.toThrow(+ 'task.storage.incomplete'+ )+ expect(deps.addTorrent).not.toHaveBeenCalled()+ expect(deps.persist).not.toHaveBeenCalled()+ expect(deps.taskManager.add).not.toHaveBeenCalled()+ })++ it('uses the original task ID and relocation service for an unambiguous old location', async () => {+ const deps = makeDeps()+ const infoHash = (await parseBtFileLayout(makePublicTorrentFixture()))+ .infoHash+ const task = makeDownloadTask({+ id: 'original',+ type: TaskType.Bt,+ status: TaskStatus.Completed,+ name: 'original',+ saveDir: '/old',+ createdAt: 1,+ updatedAt: 1,+ diskPath: '/old/public-torrent',+ filename: 'public-torrent',+ finalName: 'public-torrent',+ instances: [],+ kind: TaskKind.Bt,+ source: 'user',+ sourceMeta: null,+ infoHash,+ torrentMetaPath: '/metadata.torrent',+ finalPath: '/old/public-torrent',+ bt: makeDefaultBtExtension({ selectedFiles: [0] }),+ })+ vi.mocked(deps.taskManager.getAll).mockReturnValue([task])+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ deps.relocateExistingBt = vi.fn(async () => {})+ expect(await handleCreateTask(request(), deps)).toMatchObject({+ outcome: 'rechecked',+ taskId: 'original',+ })+ expect(deps.relocateExistingBt).toHaveBeenCalledWith(+ 'original',+ '/d',+ 'public-torrent'+ )+ expect(deps.addTorrent).not.toHaveBeenCalled()+ })++ it('refuses metadata-only magnets for explicit existing-file adoption', async () => {+ const deps = makeDeps()+ await expect(+ handleCreateTask(+ {+ ...request(),+ payload: {+ kind: 'magnet',+ uri: `magnet:?xt=urn:btih:${'a'.repeat(40)}`,+ },+ },+ deps+ )+ ).rejects.toThrow('Invalid task create request')+ expect(deps.addUri).not.toHaveBeenCalled()+ })+})diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 66934650..ee512d48 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -13,6 +13,7 @@ import type {} from '@core/engine/engine-adapter'import { DIRECT_RESOURCE_METADATA_PROFILE } from '@core/engine/engine-adapter'import { ensureDirectory } from '@core/fs/ensure-directory'+import { sanitizeFinalizeFilename } from '@core/fs/finalize-path'import { newEngineTaskId, newTaskId } from '@core/lib/ids'import { getLogger } from '@core/logger'import type { HookAuditLog } from '@core/plugin/hooks/audit-log'@@ -51,7 +52,10 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'-import { isTorrentLikeType } from '@shared/types/task-actions'+import {+ canManageBtStorage,+ isTorrentLikeType,+} from '@shared/types/task-actions'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type Database from 'better-sqlite3'import {@@ -63,6 +67,12 @@ import {TorrentDuplicateConflictError,withBtOutputAdmission,} from './bt-duplicate-policy'+import { verifyBtFiles } from './bt-file-verifier'+import {+ btOutputPaths,+ hasBtControlFile,+ hasReservedTaskOutput,+} from './bt-output-reservation'import {btStoragePayload,createBtDirectStoragePlan,@@ -209,6 +219,12 @@ export interface CreateTaskDeps {/** 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>+ /** Called with content and destination admission already held. */+ relocateExistingBt?: (+ taskId: string,+ directory: string,+ name: string+ ) => Promise<void>}export interface CreateTaskOptions {@@ -451,12 +467,63 @@ async function handleCreateTaskUnderAdmission(? extractMagnetInfoHash(req.payload.uri): null))+ const useExistingFiles =+ req.type === 'bt' && req.duplicatePolicy === 'use-existing'+ if (+ useExistingFiles &&+ req.type === 'bt' &&+ parsedBtLayout &&+ btInfoHash &&+ deps.relocateExistingBt+ ) {+ const matching = deps.taskManager+ .getAll()+ .filter(+ (task) =>+ task.status !== TaskStatus.Removed &&+ task.infoHash?.toLowerCase() === btInfoHash+ )+ const sameSelection = (values: readonly number[]) =>+ [...new Set(values)].sort((a, b) => a - b).join(',')+ const owner = matching.length === 1 ? matching[0] : undefined+ if (+ owner &&+ canManageBtStorage(owner) &&+ sameSelection(owner.bt?.selectedFiles ?? []) ===+ sameSelection(req.selectedFiles)+ ) {+ await deps.relocateExistingBt(+ owner.id,+ effectiveSaveDir,+ sanitizeFinalizeFilename(deriveDesiredName(req, torrentInfoName))+ )+ return {+ outcome: 'rechecked',+ taskId: owner.id,+ gid:+ deps.taskManager.getById(owner.id)?.engineTaskId ??+ owner.engineTaskId,+ }+ }+ if (matching.length > 0)+ throw new TorrentDuplicateConflictError({+ reason: 'active-info-hash',+ infoHash: btInfoHash,+ targetDir: effectiveSaveDir,+ existingTaskId: matching[0].id,+ existingTaskName: matching[0].name,+ existingTaskStatus: matching[0].status,+ canCreateCopy: false,+ })+ }+if (req.type === 'bt' && btInfoHash) {const admission = inspectBtDuplicate(deps.taskManager.getAll(), {infoHash: btInfoHash,saveDir: effectiveSaveDir,selectedFiles: req.selectedFiles,- duplicatePolicy: req.duplicatePolicy,+ duplicatePolicy:+ req.duplicatePolicy === 'use-existing' ? 'reuse' : req.duplicatePolicy,excludeTaskId: req.existingTaskId,})if (admission.action === 'conflict') {@@ -479,6 +546,7 @@ async function handleCreateTaskUnderAdmission(// 1. Decide final on-disk name (handles collisions).const desiredName = deriveDesiredName(req, torrentInfoName)+ const existingName = sanitizeFinalizeFilename(desiredName)if (req.type === 'bt' &&btInfoHash &&@@ -501,8 +569,9 @@ async function handleCreateTaskUnderAdmission(reservedNames.length > 0? deps.finalNamePicker.pick(effectiveSaveDir, desired, reservedNames): deps.finalNamePicker.pick(effectiveSaveDir, desired)- let finalName =- req.type === 'bt'+ let finalName = useExistingFiles+ ? existingName+ : req.type === 'bt'? await deps.finalNamePicker.pick(effectiveSaveDir,desiredName,@@ -511,6 +580,33 @@ async function handleCreateTaskUnderAdmission(): await pickHttpFinalName(desiredName)+ if (useExistingFiles) {+ if (!torrentBytes || !parsedBtLayout || req.type !== 'bt')+ throw new AppError(+ ErrorCode.TorrentParseFailed,+ 'task.storage.errors.unavailable'+ )+ const output = path.join(effectiveSaveDir, existingName)+ if (+ hasReservedTaskOutput(+ deps.taskManager.getAll(),+ btOutputPaths(output, parsedBtLayout.multiFile)+ ) ||+ (!parsedBtLayout.multiFile && (await hasBtControlFile(output)))+ )+ throw new AppError(+ ErrorCode.TorrentDuplicateConflict,+ 'task.storage.errors.conflict'+ )+ const verification = await verifyBtFiles({+ metadata: torrentBytes,+ payloadPath: output,+ selectedFiles: req.selectedFiles,+ })+ if (!verification.complete)+ throw new AppError(ErrorCode.TaskNotRetryable, 'task.storage.incomplete')+ }+const taskType = deriveTaskType(req)let finalPath = path.join(effectiveSaveDir, finalName)let diskPath = isTorrentLikeType(taskType) ? finalPath : toTempPath(finalPath)@@ -539,6 +635,7 @@ async function handleCreateTaskUnderAdmission(const btStoragePlan = isTorrentLikeType(taskType)? createBtDirectStoragePlan(finalPath, parsedBtLayout, torrentMetaPath): null+ if (useExistingFiles && btStoragePlan) btStoragePlan.layout.finalized = true// Fail before a single byte moves when a destination cannot be opened at// all. The engine opens Windows paths past MAX_PATH (agalwood/Motrix#2183),@@ -951,6 +1048,9 @@ async function handleCreateTaskUnderAdmission(// are always present on the torrent-base64 path.const params: AddTorrentParams = {metadata: torrentBytes ?? decodeBase64ToBytes(req.payload.base64),+ ...(useExistingFiles+ ? { checkIntegrity: true, preserveExistingFiles: true }+ : {}),saveDir: btStoragePlan?.saveDir ?? diskPath,// CREATE-PATH +1: req indices are 0-based; aria2 select-file is// 1-based, and addTorrent serializes selectedFiles with a raw join.diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex f35123ee..9ba0acc0 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -20,6 +20,7 @@ export function mergeEngineTask(engineTask: DownloadTask,now = Date.now()): DownloadTask {+ if (existing.storageOperation) return existing// Engine session replay and delayed notifications cannot reopen durable// direct history. Explicit re-add changes ownership/state before merging.if (diff --git a/src/main/index.ts b/src/main/index.tsindex e9b2f056..5705e7c0 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -973,6 +973,7 @@ async function handlePolledTasks(existing.status,merged,{+ isCurrent: () => taskManager.getById(existing.id) === existing,persistTaskWithOccurrence,occurrenceDispatcher,publish: (task) => taskManager.set(task.id, task),@@ -992,7 +993,7 @@ async function handlePolledTasks(// Nothing was published and nothing is durable: leave the prior// in-memory state (and its aria2 row) alone so the next poll// observes the same delta and retries.- if (outcome === 'persist-failed') continue+ if (outcome === 'persist-failed' || outcome === 'stale') continuepublishedTerminal = outcome === 'published'if (outcome === 'not-terminal' &&@@ -1054,6 +1055,8 @@ async function handlePolledTasks(// 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 (!publishedTerminal && taskManager.getById(existing.id) !== existing)+ continueif (merged.fileCount > 0) {runShellAsyncWork('task-files sync', () =>syncTaskFilesIfIncomplete(existing.id, merged.engineTaskId)@@ -3028,6 +3031,9 @@ async function initializeMainProcess(): Promise<void> {})const disposeCommandHandlers = registerCommandHandlers({+ btStorageRuntime: pluginRuntime.finalize,+ persistBtStorage: (task, source, target) =>+ sessionManager.persistBtStorage(task, source, target),rendererRecovery,operationService: pluginRuntime.operations,mediaMetaStore,diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 1b121c06..cd43147f 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -3205,3 +3205,28 @@ it('rejects system association commands from a portable profile', async () => {setPortableProfile(null)}})++describe('BT storage command contract', () => {+ it('validates destination requests before invoking storage', async () => {+ const handlers = buildCommandHandlers(+ fakeCtx() as unknown as CommandContext+ )+ await expect(+ handlers[Commands.ChangeBtStorage]?.({ taskId: 'bt', mode: 'move' })+ ).rejects.toThrow()+ })+ it('reports unavailable storage and accepts a harmless cancellation', async () => {+ const handlers = buildCommandHandlers(+ fakeCtx() as unknown as CommandContext+ )+ expect(+ await handlers[Commands.ChangeBtStorage]?.({+ taskId: 'bt',+ mode: 'recheck',+ })+ ).toEqual({ error: 'unavailable' })+ expect(await handlers[Commands.CancelBtStorage]?.('bt')).toEqual({+ ok: true,+ })+ })+})diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex c147f31a..4363b2d0 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -43,6 +43,7 @@ import {type AppliedDownloadProxyPolicy,UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,} from '@core/proxy/applied-download-proxy-policy'+import type { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'import type { MotrixDatabase } from '@core/session/motrix-database'import type { SessionManager } from '@core/session/session-manager'import { applySavedSettings } from '@core/settings/apply-saved-settings'@@ -73,6 +74,10 @@ import {taskCreateConflictResult,} from '@core/task/bt-duplicate-policy'import { parseBtFileLayout } from '@core/task/bt-storage-layout'+import {+ authorizeBtDirectory,+ BtStorageService,+} from '@core/task/bt-storage-service'import {type CreateTaskDeps,handleCreateTask,@@ -112,6 +117,7 @@ import {torrentBatchCreateOptionsSchema,} from '@shared/schemas/add-task'import { appImageNativeHostActionSchema } from '@shared/schemas/appimage-native-host'+import { btStorageRequestSchema } from '@shared/schemas/bt-storage'import {removeTasksPayloadSchema,taskIdsPayloadSchema,@@ -183,6 +189,15 @@ const cliInstallRequestSchema = z.strict()export interface CommandContext {+ btStorageRuntime?: Pick<+ DurableFinalizeRuntime,+ 'commit' | 'withArtifactLease' | 'hasPendingFinalization'+ >+ persistBtStorage?: (+ task: DownloadTask,+ sourceRoot: string,+ targetRoot: string+ ) => Promise<void>rendererRecovery?: ReturnType<typeof createRendererRecoveryRuntime>operationService?: OperationServicecliToolService: Pick<CliToolService, 'install'>@@ -485,7 +500,38 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {directResourceProxyPolicy:appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,}+ const btStorage =+ ctx.btStorageRuntime && ctx.persistBtStorage+ ? new BtStorageService({+ ...reAddDeps,+ runtime: ctx.btStorageRuntime,+ persistStorage: ctx.persistBtStorage,+ authorizeDirectory: authorizeBtDirectory,+ })+ : nullcreateDeps.reuseExistingBt = (taskId) => reAddTask(taskId, reAddDeps)+ if (btStorage)+ createDeps.relocateExistingBt = async (taskId, directory, name) => {+ const result = await btStorage.run(+ { taskId, mode: 'locate', directory, name, resume: true },+ true+ )+ if ('error' in result)+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `task.storage.errors.${result.error}`+ )+ if (!result.verification.complete)+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ 'task.storage.incomplete'+ )+ if (result.resumeFailed)+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ 'task.storage.resumeFailed'+ )+ }// 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))@@ -798,6 +844,17 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {// Plural task commands (option C): one IPC request per multi-select// action. Per-task outcomes come back IPC-safe; the bulk close inside// runBulkTaskAction forces one immediate snapshot flush.+ [Commands.ChangeBtStorage]: async (rawPayload: unknown) => {+ const request = btStorageRequestSchema.parse(rawPayload)+ await supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS)+ await waitForTasksReady?.()+ return btStorage ? btStorage.run(request) : { error: 'unavailable' }+ },+ [Commands.CancelBtStorage]: async (taskId: unknown) => {+ btStorage?.cancel(z.string().min(1).parse(taskId))+ return { ok: true }+ },+[Commands.MoveTasks]: async (rawPayload: unknown) =>moveTasks(moveTasksPayloadSchema.parse(rawPayload), pauseResumeDeps),@@ -973,7 +1030,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {infoHash: layout.infoHash,saveDir: req.saveDir,selectedFiles: req.selectedFiles,- duplicatePolicy: req.duplicatePolicy,+ duplicatePolicy:+ req.duplicatePolicy === 'use-existing'+ ? 'reuse'+ : req.duplicatePolicy,excludeTaskId: req.existingTaskId,}): { action: 'create' as const }@@ -1005,7 +1065,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {selectedFiles: req.selectedFiles,saveDir: req.saveDir,name: req.displayName,- duplicatePolicy: req.duplicatePolicy,+ duplicatePolicy:+ req.duplicatePolicy === 'use-existing'+ ? 'reuse'+ : req.duplicatePolicy,},{db: motrixDatabase,diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsxindex eed23386..afc2118f 100644--- a/src/renderer/components/add-task/add-task-form.tsx+++ b/src/renderer/components/add-task/add-task-form.tsx@@ -116,6 +116,15 @@ function notifyTaskCreateFailure(notify: PlatformServices['notify'],reason: string | null): void {+ if (+ reason &&+ /^task\.storage\.(incomplete|resumeFailed|errors\.(unavailable|busy|destination|conflict|engine|failed|cancelled))$/.test(+ reason+ )+ ) {+ notify('error', reason)+ return+ }if (!reason) {notify('error', 'task.add.createFailed')return@@ -679,36 +688,44 @@ export function AddTaskForm({[duplicateConflict, form, completeCurrentSubmission])- const createSeparateCopy = useCallback(async () => {- if (!active || !duplicateConflict) return- setSubmitting(true)- try {- const result = (await transport.invoke(Commands.CreateTask, {- ...duplicateConflict.request,- duplicatePolicy: 'create-copy',- })) as TaskCreateCommandResult- if (result.outcome === 'invalid-source') {+ const createSeparateCopy = useCallback(+ async (policy: 'create-copy' | 'use-existing' = 'create-copy') => {+ if (!active || !duplicateConflict) return+ setSubmitting(true)+ try {+ const result = (await transport.invoke(Commands.CreateTask, {+ ...duplicateConflict.request,+ duplicatePolicy: policy,+ })) as TaskCreateCommandResult+ if (result.outcome === 'invalid-source') {+ platform.notify(+ 'error',+ `task.add.sourceErrors.${result.failure.diagnostic.reason}`+ )+ return+ }+ if (result.outcome === 'conflict') {+ setDuplicateConflict({ ...duplicateConflict, result })+ return+ }+ invalidateTaskList()+ setDuplicateConflict(null)platform.notify(- 'error',- `task.add.sourceErrors.${result.failure.diagnostic.reason}`+ 'info',+ policy === 'use-existing'+ ? 'task.storage.resumed'+ : 'task.add.createdCopy')- return- }- if (result.outcome === 'conflict') {- setDuplicateConflict({ ...duplicateConflict, result })- return+ await completeConflict(result.taskId)+ } catch (error) {+ console.error(error)+ notifyTaskCreateFailure(platform.notify, taskCreateFailureReason(error))+ } finally {+ setSubmitting(false)}- invalidateTaskList()- setDuplicateConflict(null)- platform.notify('info', 'task.add.createdCopy')- await completeConflict(result.taskId)- } catch (error) {- console.error(error)- notifyTaskCreateFailure(platform.notify, taskCreateFailureReason(error))- } finally {- setSubmitting(false)- }- }, [active, completeConflict, duplicateConflict, platform])+ },+ [active, completeConflict, duplicateConflict, platform]+ )// ⌘↵ / Ctrl+Enter submituseEffect(() => {@@ -792,10 +809,12 @@ export function AddTaskForm({</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>+ <AlertDialogCancel disabled={submitting}>+ {t('common.cancel')}+ </AlertDialogCancel>{conflictPresentation?.result.conflict.existingTaskId && (<AlertDialogAction- disabled={!duplicateConflict}+ disabled={!duplicateConflict || submitting}onClick={() => {const taskId =duplicateConflict?.result.conflict.existingTaskId@@ -806,10 +825,29 @@ export function AddTaskForm({{t('task.add.duplicate.showExisting')}</AlertDialogAction>)}+ {conflictPresentation?.request.type === 'bt' &&+ !conflictPresentation.request.existingTaskId &&+ conflictPresentation.request.payload.kind ===+ 'torrent-base64' &&+ conflictPresentation.result.conflict.reason ===+ 'existing-files' && (+ <AlertDialogAction+ disabled={!duplicateConflict || submitting}+ onClick={(event) => {+ event.preventDefault()+ void createSeparateCopy('use-existing')+ }}+ >+ {t('task.storage.useExisting')}+ </AlertDialogAction>+ )}{conflictPresentation?.result.conflict.canCreateCopy && (<AlertDialogAction- disabled={!duplicateConflict}- onClick={() => void createSeparateCopy()}+ disabled={!duplicateConflict || submitting}+ onClick={(event) => {+ event.preventDefault()+ void createSeparateCopy()+ }}>{t('task.add.duplicate.createCopy')}</AlertDialogAction>diff --git a/src/renderer/routes/downloads/bt-storage-dialog.test.tsx b/src/renderer/routes/downloads/bt-storage-dialog.test.tsxnew file mode 100644index 00000000..46eb58fb--- /dev/null+++ b/src/renderer/routes/downloads/bt-storage-dialog.test.tsx@@ -0,0 +1,122 @@+import '@renderer/lib/i18n'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Events } from '@shared/protocol/events'+import type { BtStorageCommandResult } from '@shared/schemas/bt-storage'+import { TaskStatus, TaskType } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { BtStorageDialog } from './bt-storage-dialog'++vi.mock('@renderer/lib/transport', () => ({+ transport: { platform: 'web', invoke: vi.fn(), on: vi.fn(), off: vi.fn() },+}))+vi.mock('@renderer/hooks/use-task-list', () => ({+ invalidateTaskList: vi.fn(),+}))+const task = makeDownloadTask({+ id: 'bt',+ type: TaskType.Bt,+ status: TaskStatus.Completed,+ name: 'movie',+ finalName: 'movie',+ saveDir: '/downloads',+ finalPath: '/downloads/movie',+})+const complete: BtStorageCommandResult = {+ taskId: task.id,+ path: task.finalPath,+ verification: {+ complete: true,+ totalPieces: 10,+ checkedPieces: 10,+ validPieces: 10,+ missingFiles: [],+ invalidFiles: [],+ },+ resumed: false,+}++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++describe('BT storage dialog', () => {+ it('runs a recheck without requesting repair or automatic seeding', async () => {+ vi.mocked(transport.invoke).mockResolvedValue(complete)+ render(<BtStorageDialog task={task} mode="recheck" onClose={vi.fn()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Check files…' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.ChangeBtStorage,+ expect.objectContaining({+ taskId: 'bt',+ mode: 'recheck',+ resume: false,+ })+ )+ )+ expect(+ await screen.findByText('Your files are ready to seed.')+ ).toBeTruthy()+ })++ it('shows verification failure without claiming seeding resumed', async () => {+ vi.mocked(transport.invoke).mockResolvedValue({+ ...complete,+ verification: {+ ...complete.verification,+ complete: false,+ validPieces: 3,+ },+ })+ render(<BtStorageDialog task={task} mode="recheck" onClose={vi.fn()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Check files…' }))+ expect(+ await screen.findByText(/Some files are missing or incomplete/)+ ).toBeTruthy()+ expect(screen.getByText('Verified: 30%')).toBeTruthy()+ })++ it('keeps the dialog open while checking, permits cancellation and removes its event listener', async () => {+ let finish!: (result: BtStorageCommandResult) => void+ vi.mocked(transport.invoke).mockImplementation(async (command) =>+ command === Commands.ChangeBtStorage+ ? new Promise((resolve) => {+ finish = resolve+ })+ : { ok: true }+ )+ const onClose = vi.fn()+ const { unmount } = render(+ <BtStorageDialog task={task} mode="recheck" onClose={onClose} />+ )+ fireEvent.click(screen.getByRole('button', { name: 'Check files…' }))+ const cancel = await screen.findByRole('button', { name: 'Cancel' })+ fireEvent.click(cancel)+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.CancelBtStorage,+ 'bt'+ )+ expect(onClose).not.toHaveBeenCalled()+ await act(async () => finish({ error: 'cancelled' }))+ expect(await screen.findByText('Check cancelled.')).toBeTruthy()+ const listener = vi+ .mocked(transport.on)+ .mock.calls.find(([event]) => event === Events.BtStorageProgress)?.[1]+ unmount()+ expect(transport.off).toHaveBeenCalledWith(+ Events.BtStorageProgress,+ listener+ )+ })+})diff --git a/src/renderer/routes/downloads/bt-storage-dialog.tsx b/src/renderer/routes/downloads/bt-storage-dialog.tsxnew file mode 100644index 00000000..b212c0fd--- /dev/null+++ b/src/renderer/routes/downloads/bt-storage-dialog.tsx@@ -0,0 +1,222 @@+import { DirectoryPicker } from '@renderer/components/desktop-kit/directory-picker'+import { Button } from '@renderer/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/components/ui/dialog'+import { Input } from '@renderer/components/ui/input'+import { Label } from '@renderer/components/ui/label'+import { Switch } from '@renderer/components/ui/switch'+import { invalidateTaskList } from '@renderer/hooks/use-task-list'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Events } from '@shared/protocol/events'+import type {+ BtStorageCommandResult,+ BtStorageProgress,+ BtStorageRequest,+} from '@shared/schemas/bt-storage'+import { type DownloadTask, TaskStatus } from '@shared/types/task'+import { useEffect, useId, useState } from 'react'+import { FormProvider, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'++export function BtStorageDialog({+ task,+ mode,+ onClose,+}: {+ task: DownloadTask+ mode: BtStorageRequest['mode']+ onClose: () => void+}) {+ const { t } = useTranslation()+ const id = useId()+ const form = useForm({+ defaultValues: {+ directory: task.saveDir,+ name: task.finalName || task.name,+ },+ })+ const [resume, setResume] = useState(+ mode === 'locate' || task.status === TaskStatus.Seeding+ )+ const [busy, setBusy] = useState(false)+ const [progress, setProgress] = useState<BtStorageProgress | null>(null)+ const [result, setResult] = useState<BtStorageCommandResult | null>(null)+ useEffect(() => {+ const listener = (...args: unknown[]) => {+ const value = args[0] as BtStorageProgress+ if (value.taskId === task.id) setProgress(value)+ }+ transport.on(Events.BtStorageProgress, listener)+ return () => transport.off(Events.BtStorageProgress, listener)+ }, [task.id])++ const submit = form.handleSubmit(async (values) => {+ if (busy) return+ setBusy(true)+ setResult(null)+ setProgress({+ taskId: task.id,+ phase: 'checking',+ checkedPieces: 0,+ totalPieces: 0,+ })+ try {+ setResult(+ (await transport.invoke(Commands.ChangeBtStorage, {+ taskId: task.id,+ mode,+ ...values,+ resume,+ })) as BtStorageCommandResult+ )+ invalidateTaskList()+ } catch {+ setResult({ error: 'failed' })+ } finally {+ setBusy(false)+ }+ })+ const message =+ result &&+ ('error' in result+ ? t(`task.storage.errors.${result.error}`)+ : !result.verification.complete+ ? t('task.storage.incomplete')+ : result.resumeFailed+ ? t('task.storage.resumeFailed')+ : t(+ result.resumed ? 'task.storage.resumed' : 'task.storage.verified'+ ))+ const verification =+ result && !('error' in result) ? result.verification : null+ const verifiedPercent = verification?.complete+ ? 100+ : verification &&+ verification.totalPieces > 0 &&+ verification.validPieces < verification.totalPieces+ ? Math.floor((verification.validPieces / verification.totalPieces) * 100)+ : null++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !busy) onClose()+ }}+ >+ <DialogContent className="sm:max-w-lg" showCloseButton={!busy}>+ <DialogHeader>+ <DialogTitle>{t(`task.storage.${mode}`)}</DialogTitle>+ <DialogDescription>+ {t(`task.storage.${mode}Description`)}+ </DialogDescription>+ </DialogHeader>+ <FormProvider {...form}>+ <form onSubmit={submit} className="space-y-4">+ <p className="break-all text-xs text-muted-foreground">+ {result && !('error' in result) ? result.path : task.finalPath}+ </p>+ {mode !== 'recheck' && (+ <>+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-directory`}>+ {t('task.storage.directory')}+ </Label>+ <DirectoryPicker+ name="directory"+ disabled={busy}+ inputProps={{ id: `${id}-directory` }}+ recordRecent={false}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-name`}>{t('task.storage.name')}</Label>+ <Input+ id={`${id}-name`}+ {...form.register('name', { required: true })}+ disabled={busy}+ />+ </div>+ </>+ )}+ <div className="flex items-center justify-between gap-4">+ <Label htmlFor={`${id}-resume`}>{t('task.storage.resume')}</Label>+ <Switch+ id={`${id}-resume`}+ checked={resume}+ onCheckedChange={setResume}+ disabled={busy}+ />+ </div>+ {busy && (+ <div role="status" className="space-y-2 text-xs">+ <p>{t(`task.storage.${progress?.phase ?? 'checking'}`)}</p>+ {progress?.phase === 'checking' && progress.totalPieces > 0 && (+ <progress+ className="h-2 w-full"+ aria-label={t('task.storage.checking')}+ value={progress.checkedPieces}+ max={progress.totalPieces}+ />+ )}+ </div>+ )}+ {message && (+ <div+ role="status"+ className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1"+ >+ <p className="min-w-0 flex-[1_1_16rem] text-sm">{message}</p>+ {verification && (+ <p className="ms-auto shrink-0 text-xs text-muted-foreground tabular-nums">+ {verifiedPercent === null+ ? t('task.storage.checkFailed')+ : t('task.storage.verifiedPercent', {+ percent: verifiedPercent,+ })}+ </p>+ )}+ </div>+ )}+ <DialogFooter>+ {busy ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={progress?.phase !== 'checking'}+ onClick={() => {+ void transport+ .invoke(Commands.CancelBtStorage, task.id)+ .catch(() => setResult({ error: 'failed' }))+ }}+ >+ {t('common.cancel')}+ </Button>+ ) : (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={onClose}+ >+ {t('common.close')}+ </Button>+ )}+ <Button type="submit" size="sm" disabled={busy}>+ {t(`task.storage.${mode}`)}+ </Button>+ </DialogFooter>+ </form>+ </FormProvider>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsxindex f556ebb5..aa9e3414 100644--- a/src/renderer/routes/downloads/task-actions-menu.tsx+++ b/src/renderer/routes/downloads/task-actions-menu.tsx@@ -31,10 +31,12 @@ import { transport } from '@renderer/lib/transport'import { CommandIds } from '@shared/commands-catalog'import { formatNativePath } from '@shared/lib/path-display'import { Commands } from '@shared/protocol/commands'+import type { BtStorageRequest } from '@shared/schemas/bt-storage'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'import {type BulkTaskCommandResult,+ canManageBtStorage,canOpenTaskFile,canSelectTaskFiles,} from '@shared/types/task-actions'@@ -50,6 +52,7 @@ import {useSyncExternalStore,} from 'react'import { useTranslation } from 'react-i18next'+import { BtStorageDialog } from './bt-storage-dialog'import { DownloadsToolbarButton } from './downloads-toolbar-button'import { canRevealTaskFolder } from './inspector/can-reveal-task-folder'import { copyTaskUrls } from './inspector/task-copy-url'@@ -116,6 +119,17 @@ export function TaskActionsMenu({() => tasks.filter((task) => (targetIds ?? selectedIds).has(task.id)),[tasks, targetIds, selectedIds])+ const [storageDialog, setStorageDialog] = useState<{+ task: DownloadTask+ mode: BtStorageRequest['mode']+ } | null>(null)+ const storage = storageDialog ? (+ <BtStorageDialog+ key={`${storageDialog.task.id}-${storageDialog.mode}`}+ {...storageDialog}+ onClose={() => setStorageDialog(null)}+ />+ ) : nullconst [menuOpen, setMenuOpen] = useState(false)const pendingRef = useRef(false)const [pending, setPending] = useState(false)@@ -132,6 +146,7 @@ export function TaskActionsMenu({0 ||single?.status === TaskStatus.MetadataReady ||canChooseFiles ||+ (single && canManageBtStorage(single)) ||actions.moveCount > 0const { open: inspectorVisible } = useTaskInspectorState(selection, tasks)const macOS =@@ -352,6 +367,16 @@ export function TaskActionsMenu({{t('panel.downloads.action.reseed')}</DropdownMenuItem>)}+ {single &&+ canManageBtStorage(single) &&+ (['move', 'locate', 'recheck'] as const).map((mode) => (+ <DropdownMenuItem+ key={mode}+ onClick={() => setStorageDialog({ task: single, mode })}+ >+ {t(`task.storage.${mode}`)}+ </DropdownMenuItem>+ ))}{single?.status === TaskStatus.MetadataReady && (<DropdownMenuItemdisabled={pending}@@ -509,7 +534,47 @@ export function TaskActionsMenu({const presentation = useExitSnapshot(menuOpen, items)if (children)return (- <ContextMenu+ <>+ {' '}+ {storage}+ <ContextMenu+ open={menuOpen}+ onOpenChange={(open) => {+ if (open) prepare()+ else setTargetIds(null)+ setMenuOpen(open)+ }}+ >+ <ContextMenuTrigger+ render={children}+ onKeyDownCapture={handleShortcut}+ onCopyCapture={handleCopy}+ onContextMenuCapture={(event) => {+ const row = (event.target as Element).closest<HTMLElement>(+ '[data-task-id]'+ )+ if (!row?.dataset.taskId) return+ const state = selection.getState()+ if (!state.selectedIds.has(row.dataset.taskId))+ state.select(row.dataset.taskId)+ state.focus(row.dataset.taskId)+ prepare()+ }}+ />+ <ContextMenuContent+ onKeyDownCapture={handleShortcut}+ onCopyCapture={handleCopy}+ className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"+ >+ {presentation}+ </ContextMenuContent>+ </ContextMenu>+ </>+ )+ return (+ <>+ {storage}+ <DropdownMenuopen={menuOpen}onOpenChange={(open) => {if (open) prepare()@@ -517,62 +582,29 @@ export function TaskActionsMenu({setMenuOpen(open)}}>- <ContextMenuTrigger- render={children}+ <DropdownMenuTriggeronKeyDownCapture={handleShortcut}onCopyCapture={handleCopy}- onContextMenuCapture={(event) => {- const row = (event.target as Element).closest<HTMLElement>(- '[data-task-id]'- )- if (!row?.dataset.taskId) return- const state = selection.getState()- if (!state.selectedIds.has(row.dataset.taskId))- state.select(row.dataset.taskId)- state.focus(row.dataset.taskId)- prepare()- }}- />- <ContextMenuContent+ render={+ <DownloadsToolbarButton+ aria-label={t('panel.downloads.view.taskActions')}+ title={t('panel.downloads.view.taskActions')}+ ref={triggerRef}+ />+ }+ >+ <MoreIcon className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContentonKeyDownCapture={handleShortcut}onCopyCapture={handleCopy}+ align="end"+ data-menu-density="compact"className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]">{presentation}- </ContextMenuContent>- </ContextMenu>- )- return (- <DropdownMenu- open={menuOpen}- onOpenChange={(open) => {- if (open) prepare()- else setTargetIds(null)- setMenuOpen(open)- }}- >- <DropdownMenuTrigger- onKeyDownCapture={handleShortcut}- onCopyCapture={handleCopy}- render={- <DownloadsToolbarButton- aria-label={t('panel.downloads.view.taskActions')}- title={t('panel.downloads.view.taskActions')}- ref={triggerRef}- />- }- >- <MoreIcon className="size-4" />- </DropdownMenuTrigger>- <DropdownMenuContent- onKeyDownCapture={handleShortcut}- onCopyCapture={handleCopy}- align="end"- data-menu-density="compact"- className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"- >- {presentation}- </DropdownMenuContent>- </DropdownMenu>+ </DropdownMenuContent>+ </DropdownMenu>+ </>)}diff --git a/src/server/index.ts b/src/server/index.tsindex 3507ba87..376ff843 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -993,6 +993,7 @@ async function main() {const outcome =existing.status !== merged.status? await commitPolledTerminalTransition(existing.status, merged, {+ isCurrent: () => taskManager.getById(existing.id) === existing,persistTaskWithOccurrence,occurrenceDispatcher,publish: (task) => taskManager.set(task.id, task),@@ -1006,8 +1007,11 @@ async function main() {: 'not-terminal'// Nothing was published and nothing is durable: leave the prior// in-memory state alone so the next poll retries.- if (outcome === 'persist-failed') continue- if (outcome !== 'published') taskManager.set(existing.id, merged)+ if (outcome === 'persist-failed' || outcome === 'stale') continue+ if (outcome !== 'published') {+ if (taskManager.getById(existing.id) !== existing) continue+ taskManager.set(existing.id, merged)+ }dirty = true} else {const id = newTaskId()@@ -1174,6 +1178,9 @@ async function main() {// ─── HTTP App ─────────────────────────────────────────────────const serverDirectoryService = new ServerDirectoryService(downloadPathPolicy)const commandHandlers = buildServerCommandHandlers({+ btStorageRuntime: durableFinalizeRuntime,+ persistBtStorage: (task, source, target) =>+ sessionManager.persistBtStorage(task, source, target),operationService: pluginRuntime.operations,mediaMetaStore,serverDirectoryService,diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex e009d4f5..48a8a9b8 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -2110,3 +2110,65 @@ describe('plugin diagnostic mode command', () => {})})++describe('BT storage command contract', () => {+ it('authorizes a relocation destination before stopping or inspecting any files', async () => {+ const ctx = makeFakeCtx() as ServerCommandContext+ const authorizeDirectory = vi.fn(async () => {+ throw new Error('outside allowed roots')+ })+ ctx.downloadPathPolicy = { ...ctx.downloadPathPolicy, authorizeDirectory }+ ctx.btStorageRuntime = {+ commit: vi.fn(),+ withArtifactLease: vi.fn(),+ hasPendingFinalization: vi.fn(),+ }+ ctx.persistBtStorage = vi.fn()+ ctx.adapter.forceRemoveTask = vi.fn()+ vi.mocked(ctx.taskManager.getById).mockReturnValue(+ makeDownloadTask({+ id: 'bt',+ type: TaskType.Bt,+ status: TaskStatus.Completed,+ finalPath: '/old/file',+ infoHash: 'a'.repeat(40),+ torrentMetaPath: '/metadata.torrent',+ })+ )+ const handlers = buildServerCommandHandlers(ctx)+ expect(+ await handlers[Commands.ChangeBtStorage]?.({+ taskId: 'bt',+ mode: 'locate',+ directory: '/forbidden',+ name: 'file',+ })+ ).toEqual({ error: 'failed' })+ expect(authorizeDirectory).toHaveBeenCalledWith('/forbidden')+ expect(ctx.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(ctx.persistBtStorage).not.toHaveBeenCalled()+ })++ it('validates destination requests before invoking storage', async () => {+ const handlers = buildServerCommandHandlers(+ makeFakeCtx() as ServerCommandContext+ )+ await expect(+ handlers[Commands.ChangeBtStorage]?.({ taskId: 'bt', mode: 'move' })+ ).rejects.toThrow()+ })+ it('reports unavailable storage and accepts a harmless cancellation', async () => {+ const handlers = buildServerCommandHandlers(+ makeFakeCtx() as ServerCommandContext+ )+ expect(+ await handlers[Commands.ChangeBtStorage]?.({+ taskId: 'bt',+ mode: 'recheck',+ })+ ).toEqual({ error: 'unavailable' })+ expect(await handlers[Commands.CancelBtStorage]?.('bt')).toEqual({+ ok: true,+ })+ })+})diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 705dd5be..5716ae52 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -30,6 +30,7 @@ import {type AppliedDownloadProxyPolicy,UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,} from '@core/proxy/applied-download-proxy-policy'+import type { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'import type { MotrixDatabase } from '@core/session/motrix-database'import type { SessionManager } from '@core/session/session-manager'import { applySavedSettings } from '@core/settings/apply-saved-settings'@@ -60,6 +61,7 @@ import {taskCreateConflictResult,} from '@core/task/bt-duplicate-policy'import { parseBtFileLayout } from '@core/task/bt-storage-layout'+import { BtStorageService } from '@core/task/bt-storage-service'import {type CreateTaskDeps,handleCreateTask,@@ -85,6 +87,7 @@ import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import type { CommandHandlerMap } from '@shared/protocol/handler-types'import { taskCreateRequestSchema } from '@shared/schemas/add-task'+import { btStorageRequestSchema } from '@shared/schemas/bt-storage'import {removeTasksPayloadSchema,taskIdsPayloadSchema,@@ -114,6 +117,15 @@ import type { ServerDirectoryService } from '../server-directory-service'import { unsupportedLegacyImportCommands } from './legacy-import'export interface ServerCommandContext {+ btStorageRuntime?: Pick<+ DurableFinalizeRuntime,+ 'commit' | 'withArtifactLease' | 'hasPendingFinalization'+ >+ persistBtStorage?: (+ task: DownloadTask,+ sourceRoot: string,+ targetRoot: string+ ) => Promise<void>operationService?: OperationServicesupervisor: EngineSupervisorsettingsManager: SettingsManager@@ -349,7 +361,40 @@ export function buildServerCommandHandlers(directResourceProxyPolicy:appliedDownloadProxyPolicy ?? UNAVAILABLE_APPLIED_DOWNLOAD_PROXY_POLICY,}+ const btStorage =+ ctx.btStorageRuntime && ctx.persistBtStorage+ ? new BtStorageService({+ ...reAddDeps,+ runtime: ctx.btStorageRuntime,+ persistStorage: ctx.persistBtStorage,+ authorizeDirectory: async (directory: string) =>+ (await downloadPathPolicy.authorizeDirectory(directory))+ .canonicalPath,+ })+ : nullcreateDeps.reuseExistingBt = (taskId) => reAddTask(taskId, reAddDeps)+ if (btStorage)+ createDeps.relocateExistingBt = async (taskId, directory, name) => {+ const result = await btStorage.run(+ { taskId, mode: 'locate', directory, name, resume: true },+ true+ )+ if ('error' in result)+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ `task.storage.errors.${result.error}`+ )+ if (!result.verification.complete)+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ 'task.storage.incomplete'+ )+ if (result.resumeFailed)+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ 'task.storage.resumeFailed'+ )+ }// 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))@@ -546,7 +591,10 @@ export function buildServerCommandHandlers(infoHash: layout.infoHash,saveDir,selectedFiles: req.selectedFiles,- duplicatePolicy: req.duplicatePolicy,+ duplicatePolicy:+ req.duplicatePolicy === 'use-existing'+ ? 'reuse'+ : req.duplicatePolicy,excludeTaskId: req.existingTaskId,}): { action: 'create' as const }@@ -578,7 +626,10 @@ export function buildServerCommandHandlers(selectedFiles: req.selectedFiles,saveDir,name: req.displayName,- duplicatePolicy: req.duplicatePolicy,+ duplicatePolicy:+ req.duplicatePolicy === 'use-existing'+ ? 'reuse'+ : req.duplicatePolicy,},{db: motrixDatabase,@@ -630,6 +681,16 @@ export function buildServerCommandHandlers(// Plural task commands (option C): one IPC request per multi-select// action from the web renderer. Same handlers as desktop.+ [Commands.ChangeBtStorage]: async (rawPayload: unknown) => {+ const request = btStorageRequestSchema.parse(rawPayload)+ await supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS)+ return btStorage ? btStorage.run(request) : { error: 'unavailable' }+ },+ [Commands.CancelBtStorage]: async (taskId: unknown) => {+ btStorage?.cancel(z.string().min(1).parse(taskId))+ return { ok: true }+ },+[Commands.MoveTasks]: async (rawPayload: unknown) =>moveTasks(moveTasksPayloadSchema.parse(rawPayload), pauseResumeDeps),diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 64cc8a13..5cbd5db6 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -3034,6 +3034,36 @@"image": "صورة","selectAll": "تحديد الكل","video": "فيديو"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 826ed9db..7c39b600 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -2946,6 +2946,36 @@"image": "Изображение","selectAll": "Избиране на всички","video": "Видео"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex 5da81ff9..4cb32c75 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -2968,6 +2968,36 @@"image": "Imatge","selectAll": "Seleccionar-los tots","video": "Vídeo"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex 5dc20c86..e94878b0 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -1218,6 +1218,36 @@"tooManyRedirects": "Der Quelllink ist möglicherweise ungültig. Versuchen Sie einen anderen Link","btMetadataFailed": "Prüfen Sie den Magnet-Link oder fügen Sie weitere Tracker hinzu und versuchen Sie es erneut"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex a5e881e2..8bc24abf 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -2946,6 +2946,36 @@"image": "Εικόνα","selectAll": "Επιλογή όλων","video": "Βίντεο"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex b3bc28e4..80c4a7a1 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1218,6 +1218,36 @@"tooManyRedirects": "The source link may be broken; try a different link","btMetadataFailed": "Check the magnet link or add more trackers, then retry"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex ad7f51bb..d8820e31 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -1232,6 +1232,36 @@"tooManyRedirects": "El enlace de origen podría no funcionar; prueba otro enlace","btMetadataFailed": "Comprueba el enlace magnet o añade más trackers y reintenta"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex 663e31aa..686ac0df 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -2946,6 +2946,36 @@"image": "تصویر","selectAll": "انتخاب همه","video": "ویدیو"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex ea0a3810..584b5bf2 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -2968,6 +2968,36 @@"image": "Image","selectAll": "Tout sélectionner","video": "Vidéo"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex 65533c13..5a13498d 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -1218,6 +1218,36 @@"tooManyRedirects": "A forráshivatkozás hibás lehet; próbálj másik hivatkozást","btMetadataFailed": "Ellenőrizd a magnet hivatkozást, vagy adj hozzá további trackereket, majd próbáld újra"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex 2af892e5..27198278 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -1204,6 +1204,36 @@"tooManyRedirects": "Tautan sumber mungkin rusak; coba tautan lain","btMetadataFailed": "Periksa tautan magnet atau tambahkan pelacak, lalu coba lagi"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex b872e8b2..1518866f 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -1232,6 +1232,36 @@"tooManyRedirects": "Il link di origine potrebbe non funzionare; prova un altro link","btMetadataFailed": "Controlla il link magnet o aggiungi altri tracker, quindi riprova"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex 7f8e744d..ce9296eb 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -1204,6 +1204,36 @@"tooManyRedirects": "リンク先に問題がある可能性があります。別のリンクをお試しください","btMetadataFailed": "マグネットリンクを確認するか、トラッカーを追加してから再試行してください"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex 9889d8b4..6c252af1 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -1204,6 +1204,36 @@"tooManyRedirects": "원본 링크에 문제가 있을 수 있습니다. 다른 링크를 사용해 보세요","btMetadataFailed": "마그넷 링크를 확인하거나 트래커를 추가한 후 다시 시도하세요"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex 33237a5b..da40b512 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -2946,6 +2946,36 @@"image": "Bilde","selectAll": "Velg alle","video": "Video"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 3a9bbbfa..c67151da 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -2946,6 +2946,36 @@"image": "Afbeelding","selectAll": "Alles selecteren","video": "Video"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex af5495a6..88e85e5f 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -1246,6 +1246,36 @@"tooManyRedirects": "Link źródłowy może być nieprawidłowy; spróbuj użyć innego","btMetadataFailed": "Sprawdź link magnet lub dodaj więcej trackerów, a następnie spróbuj ponownie"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex b904fef6..5964b656 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -1232,6 +1232,36 @@"tooManyRedirects": "O link de origem pode estar inválido; tente outro link","btMetadataFailed": "Verifique o link magnet ou adicione mais rastreadores e tente novamente"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex 51eedff1..b6410280 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -2968,6 +2968,36 @@"image": "Imagine","selectAll": "Selectează tot","video": "Video"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex cc1e811e..9d1e4fcc 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -1246,6 +1246,36 @@"tooManyRedirects": "Исходная ссылка может быть недействительна; попробуйте другую","btMetadataFailed": "Проверьте magnet-ссылку или добавьте больше трекеров и повторите попытку"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex 334fdb61..df4cd0c8 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -2924,6 +2924,36 @@"image": "รูปภาพ","selectAll": "เลือกทั้งหมด","video": "วิดีโอ"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex b486119f..7e286785 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -1218,6 +1218,36 @@"tooManyRedirects": "Kaynak bağlantı bozuk olabilir; başka bir bağlantı deneyin","btMetadataFailed": "Magnet bağlantısını kontrol edin veya daha fazla izleyici ekleyip tekrar deneyin"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex bfb895db..db27797b 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -2990,6 +2990,36 @@"image": "Зображення","selectAll": "Вибрати все","video": "Відео"+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"trackers": {diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex 505be35c..5d38d5bf 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -1204,6 +1204,36 @@"tooManyRedirects": "Liên kết nguồn có thể bị hỏng; hãy thử liên kết khác","btMetadataFailed": "Kiểm tra liên kết magnet hoặc thêm máy chủ theo dõi rồi thử lại"}+ },+ "storage": {+ "move": "Move files…",+ "locate": "Find existing files…",+ "recheck": "Check files…",+ "moveDescription": "Choose a new folder for your downloaded files. Seeding pauses while they move.",+ "locateDescription": "Choose where your downloaded files are now. Motrix will check them so you can continue seeding.",+ "recheckDescription": "Check that your downloaded files are complete. This will not change the files or download them again.",+ "directory": "Folder",+ "name": "File or folder name",+ "resume": "Continue seeding after checking",+ "checking": "Checking files…",+ "moving": "Moving files…",+ "resuming": "Starting seeding…",+ "verifiedPercent": "Verified: {{percent}}%",+ "checkFailed": "Check failed",+ "verified": "Your files are ready to seed.",+ "resumed": "Seeding has resumed.",+ "incomplete": "Some files are missing or incomplete. Check that you selected the right folder and try again.",+ "resumeFailed": "The new location is saved. Select Re-seed to try sharing the files again.",+ "useExisting": "Check and use these files",+ "errors": {+ "unavailable": "This task cannot be moved or checked yet.",+ "busy": "Another file operation is still running. Please wait for it to finish.",+ "destination": "Choose a different folder or file name. The location may already contain these files or be inside the current folder.",+ "conflict": "Another download is using these files. Open that task to change their location.",+ "engine": "Motrix could not stop this task. Please try again.",+ "failed": "Motrix could not access or move the files. Check the folder, available space, and permission to use it.",+ "cancelled": "Check cancelled."+ }}},"settings": {diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 76609979..f3eff177 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1204,6 +1204,36 @@"tooManyRedirects": "该链接可能已失效,请尝试更换下载链接","btMetadataFailed": "检查磁力链接或添加更多 Tracker 后重试"}+ },+ "storage": {+ "move": "移动文件…",+ "locate": "查找已有文件…",+ "recheck": "检查文件…",+ "moveDescription": "为下载好的文件选择新位置。移动期间会暂停做种。",+ "locateDescription": "指定文件现在的位置,检查完整后即可继续做种。",+ "recheckDescription": "检查下载的文件是否完整。检查不会修改文件或重新下载。",+ "directory": "所在文件夹",+ "name": "文件或文件夹名称",+ "resume": "检查通过后继续做种",+ "checking": "正在检查文件…",+ "moving": "正在移动文件…",+ "resuming": "正在启动做种…",+ "verifiedPercent": "检查通过 {{percent}}%",+ "checkFailed": "检查未通过",+ "verified": "文件完整,可以开始做种。",+ "resumed": "已恢复做种。",+ "incomplete": "部分文件缺失或不完整,请确认文件夹选择正确后重试。",+ "resumeFailed": "新位置已保存。可以点击“重新做种”再试一次。",+ "useExisting": "检查并使用这些文件",+ "errors": {+ "unavailable": "这个任务暂时无法移动或检查。",+ "busy": "还有文件操作正在进行,请稍后再试。",+ "destination": "请换一个文件夹或名称。所选位置可能已有同名文件,或位于当前文件夹内。",+ "conflict": "另一个下载任务正在使用这些文件,请打开对应任务更改位置。",+ "engine": "未能停止当前任务,请重试。",+ "failed": "无法访问或移动文件,请检查文件夹、可用空间和访问权限。",+ "cancelled": "已取消检查。"+ }}},"settings": {diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 5d74d069..9577627b 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1204,6 +1204,36 @@"tooManyRedirects": "來源連結可能失效,請嘗試其他連結","btMetadataFailed": "請檢查 Magnet 連結或新增更多 Tracker,然後重試"}+ },+ "storage": {+ "move": "移動檔案…",+ "locate": "尋找現有檔案…",+ "recheck": "檢查檔案…",+ "moveDescription": "為下載好的檔案選擇新位置。移動期間會暫停做種。",+ "locateDescription": "指定檔案目前的位置,檢查完整後即可繼續做種。",+ "recheckDescription": "檢查下載的檔案是否完整。檢查不會修改檔案或重新下載。",+ "directory": "所在資料夾",+ "name": "檔案或資料夾名稱",+ "resume": "檢查通過後繼續做種",+ "checking": "正在檢查檔案…",+ "moving": "正在移動檔案…",+ "resuming": "正在啟動做種…",+ "verifiedPercent": "檢查通過 {{percent}}%",+ "checkFailed": "檢查未通過",+ "verified": "檔案完整,可以開始做種。",+ "resumed": "已恢復做種。",+ "incomplete": "部分檔案遺失或不完整,請確認資料夾選擇正確後重試。",+ "resumeFailed": "新位置已儲存。可以點選「重新做種」再試一次。",+ "useExisting": "檢查並使用這些檔案",+ "errors": {+ "unavailable": "這個任務暫時無法移動或檢查。",+ "busy": "還有檔案操作正在進行,請稍後再試。",+ "destination": "請換一個資料夾或名稱。所選位置可能已有同名檔案,或位於目前資料夾內。",+ "conflict": "另一個下載任務正在使用這些檔案,請開啟對應任務變更位置。",+ "engine": "未能停止目前任務,請重試。",+ "failed": "無法存取或移動檔案,請檢查資料夾、可用空間和存取權限。",+ "cancelled": "已取消檢查。"+ }}},"settings": {diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex b52fd83c..8481fe42 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -50,6 +50,8 @@ export const Commands = {PauseTasks: 'command:pauseTasks',ResumeTasks: 'command:resumeTasks',MoveTasks: 'command:moveTasks',+ ChangeBtStorage: 'command:changeBtStorage',+ CancelBtStorage: 'command:cancelBtStorage',RemoveTasks: 'command:removeTasks',ReAddTasks: 'command:reAddTasks',// Generic user Retry. Shell handlers route sidecar-backed torrents todiff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.tsindex 82e0595c..9aae437c 100644--- a/src/shared/protocol/events.ts+++ b/src/shared/protocol/events.ts@@ -16,6 +16,7 @@ export const Events = {CompletionShutdownChanged: 'event:completionShutdownChanged',TaskUpdated: 'event:taskUpdated',TaskFilesUpdated: 'event:taskFilesUpdated',+ BtStorageProgress: 'event:btStorageProgress',TaskActivityUpdated: 'event:taskActivityUpdated',TaskInspectorActivityUpdated: 'event:taskInspectorActivityUpdated',StatsUpdated: 'event:statsUpdated',diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.tsindex 2d9cb4bb..fe84ec35 100644--- a/src/shared/protocol/forwardable-events.ts+++ b/src/shared/protocol/forwardable-events.ts@@ -4,6 +4,7 @@ import { Events } from './events'export const ForwardableEvents = [Events.TaskUpdated,Events.TaskFilesUpdated,+ Events.BtStorageProgress,Events.TaskActivityUpdated,Events.TaskInspectorActivityUpdated,Events.MagnetFileSelection,diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.tsindex 8fdba8dd..4f75f72d 100644--- a/src/shared/schemas/add-task.ts+++ b/src/shared/schemas/add-task.ts@@ -123,9 +123,20 @@ const btTaskRequestSchema = zexistingTaskId: 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'),+ duplicatePolicy: z+ .enum(['reuse', 'create-copy', 'use-existing'])+ .default('reuse'),}).superRefine((value, ctx) => {+ if (+ value.duplicatePolicy === 'use-existing' &&+ (value.payload.kind !== 'torrent-base64' ||+ value.existingTaskId !== undefined)+ )+ ctx.addIssue({+ code: 'custom',+ message: 'Existing files require resolved torrent metadata',+ })if (value.payload.kind === 'torrent-base64' &&value.selectedFiles.length === 0diff --git a/src/shared/schemas/bt-storage.ts b/src/shared/schemas/bt-storage.tsnew file mode 100644index 00000000..81c96544--- /dev/null+++ b/src/shared/schemas/bt-storage.ts@@ -0,0 +1,54 @@+import { z } from 'zod'++export const btStorageRequestSchema = z+ .object({+ taskId: z.string().min(1),+ mode: z.enum(['move', 'locate', 'recheck']),+ directory: z.string().min(1).optional(),+ name: z.string().min(1).optional(),+ resume: z.boolean().default(false),+ })+ .strict()+ .superRefine((value, ctx) => {+ if (value.mode !== 'recheck' && (!value.directory || !value.name))+ ctx.addIssue({ code: 'custom', message: 'A destination is required' })+ })++export type BtStorageRequest = z.input<typeof btStorageRequestSchema>++export interface BtVerificationResult {+ complete: boolean+ checkedPieces: number+ totalPieces: number+ validPieces: number+ /** Bounded examples; piece counts remain authoritative. */+ missingFiles: string[]+ invalidFiles: string[]+}++export interface BtStorageResult {+ taskId: string+ path: string+ verification: BtVerificationResult+ resumed: boolean+ resumeFailed?: boolean+}++export type BtStorageFailureReason =+ | 'unavailable'+ | 'busy'+ | 'destination'+ | 'conflict'+ | 'engine'+ | 'failed'+ | 'cancelled'+export type BtStorageCommandResult =+ | BtStorageResult+ | { error: BtStorageFailureReason }++export interface BtStorageProgress {+ taskId: string+ phase: 'checking' | 'moving' | 'resuming'+ checkedPieces: number+ totalPieces: number+}diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex 6be1c54b..268315bf 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -123,6 +123,21 @@ export function canReseed(t: DownloadTask): boolean {)}+/** Storage changes require resolved metadata and no download/finalization in flight. */+export function canManageBtStorage(t: DownloadTask): boolean {+ return (+ !t.storageOperation &&+ !hasLegacyImport(t) &&+ isTorrentLikeType(t.type) &&+ t.torrentMetaPath != null &&+ t.transitionPhase === TransitionPhase.Idle &&+ ([TaskStatus.Completed, TaskStatus.Seeding, TaskStatus.Error].includes(+ t.status+ ) ||+ (t.status === TaskStatus.Paused && t.progress === 1))+ )+}+/** Completed regular downloads can be downloaded again. */export function canRedownload(t: DownloadTask): boolean {return (diff --git a/src/shared/types/task.ts b/src/shared/types/task.tsindex 532050ef..7acbbd32 100644--- a/src/shared/types/task.ts+++ b/src/shared/types/task.ts@@ -74,6 +74,8 @@ export interface TaskInstance {}export interface DownloadTask {+ /** Transient storage work; never restored as an engine task after restart. */+ storageOperation?: booleanid: stringengineTaskId: stringname: stringdiff --git a/src/test-utils/bt-storage.ts b/src/test-utils/bt-storage.tsnew file mode 100644index 00000000..61f6970b--- /dev/null+++ b/src/test-utils/bt-storage.ts@@ -0,0 +1,58 @@+import { createHash } from 'node:crypto'++type Encodable =+ | string+ | number+ | Buffer+ | Encodable[]+ | { [key: string]: Encodable }+function encode(value: Encodable): Buffer {+ if (typeof value === 'number') return Buffer.from(`i${value}e`)+ if (Array.isArray(value))+ return Buffer.concat([+ Buffer.from('l'),+ ...value.map(encode),+ Buffer.from('e'),+ ])+ if (typeof value === 'string' || Buffer.isBuffer(value)) {+ const data = Buffer.from(value)+ return Buffer.concat([Buffer.from(`${data.length}:`), data])+ }+ return Buffer.concat([+ Buffer.from('d'),+ ...Object.keys(value)+ .sort()+ .flatMap((key) => [encode(key), encode(value[key])]),+ Buffer.from('e'),+ ])+}++export function storageTorrent(+ files: Array<{ name: string; data: string | Buffer }>,+ multiFile = files.length > 1,+ pieceLength = 4+): Buffer {+ const data = Buffer.concat(files.map((file) => Buffer.from(file.data)))+ const hashes: Buffer[] = []+ for (let offset = 0; offset < data.length; offset += pieceLength)+ hashes.push(+ createHash('sha1')+ .update(data.subarray(offset, offset + pieceLength))+ .digest()+ )+ return encode({+ info: {+ name: multiFile ? 'bundle' : files[0].name,+ 'piece length': pieceLength,+ pieces: Buffer.concat(hashes),+ ...(multiFile+ ? {+ files: files.map((file) => ({+ path: file.name.split('/'),+ length: Buffer.byteLength(file.data),+ })),+ }+ : { length: data.length }),+ },+ })+}diff --git a/tests/scripts/vite-desktop-locales.test.ts b/tests/scripts/vite-desktop-locales.test.tsindex 6c604446..88c8e20a 100644--- a/tests/scripts/vite-desktop-locales.test.ts+++ b/tests/scripts/vite-desktop-locales.test.ts@@ -11,7 +11,7 @@ describe('desktop main locale projection', () => {id: string) => { code: string } | null- it('removes only the Server CLI catalog from every locale', () => {+ it('omits non-main UI catalogs while preserving host errors in every locale', () => {for (const file of readdirSync(root).filter((name) =>name.endsWith('.json'))) {@@ -20,8 +20,23 @@ describe('desktop main locale projection', () => {expect(original.operatorAdmin).toBeDefined()const result = JSON.parse(transform(source, path.join(root, file))!.code)expect(result.operatorAdmin).toBeUndefined()+ expect(result.task.add.duplicate).toBeUndefined()+ expect(result.task.storage).toEqual({+ incomplete: original.task.storage.incomplete,+ resumeFailed: original.task.storage.resumeFailed,+ errors: original.task.storage.errors,+ })delete original.operatorAdmin+ delete original.task.add.duplicate+ original.task.storage = {+ incomplete: original.task.storage.incomplete,+ resumeFailed: original.task.storage.resumeFailed,+ errors: original.task.storage.errors,+ }expect(result).toEqual(original)+ // The source catalogs, consumed by renderer and Server, stay complete.+ expect(JSON.parse(source).task.storage.move).toBeDefined()+ expect(JSON.parse(source).task.add.duplicate).toBeDefined()}})