A full-featured download manager.
fix(migration): resume verified legacy http downloads (#2420)
Dr_rOot6a1949a6e239
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 95915b98..6e728769 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -481,11 +481,13 @@ jobs:pnpm run build:native-host -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}pnpm run build:finalize-fs -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}- - name: Finalize filesystem runtime integration+ - name: Native runtime integrationenv:+ MOTRIX_LEGACY_CHECKPOINT_ENGINE: ${{ github.workspace }}/extra/${{ matrix.platform }}/${{ matrix.arch }}/${{ matrix.platform == 'win32' && 'aria2c.exe' || 'aria2c' }}MOTRIX_FINALIZE_FS_TEST_BIN: packages/finalize-fs/dist/${{ matrix.platform }}-${{ matrix.arch }}/${{ matrix.platform == 'win32' && 'motrix-finalize-fs.exe' || 'motrix-finalize-fs' }}run: >-pnpm exec vitest run+ src/core/legacy-import/http-activation.integration.test.tssrc/core/plugin/finalize/native-artifact-operations.integration.test.tssrc/core/plugin/finalize/finalize-adversarial.integration.test.tssrc/core/plugin/finalize/finalize-smb-recovery.integration.test.tsdiff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.ymlindex 4d8f2e4b..9937201a 100644--- a/.github/workflows/flatpak.yml+++ b/.github/workflows/flatpak.yml@@ -348,7 +348,7 @@ jobs:-path "*/native-messaging-hosts/*" \\) -print -quit)"output="$("$aria2c" --version)"- printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.19"+ printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.20"printf "%s\n" "$output" | grep -qF "Async DNS"printf "%s\n" "$output" | grep -qF "BitTorrent"printf "%s\n" "$output" | grep -qF "HTTPS"diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 58cccfd6..11a139fe 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -254,11 +254,13 @@ jobs:pnpm run build:native-host -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}pnpm run build:finalize-fs -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}- - name: Finalize filesystem runtime integration+ - name: Native runtime integrationenv:+ MOTRIX_LEGACY_CHECKPOINT_ENGINE: ${{ github.workspace }}/extra/${{ matrix.platform }}/${{ matrix.arch }}/${{ matrix.platform == 'win32' && 'aria2c.exe' || 'aria2c' }}MOTRIX_FINALIZE_FS_TEST_BIN: packages/finalize-fs/dist/${{ matrix.platform }}-${{ matrix.arch }}/${{ matrix.platform == 'win32' && 'motrix-finalize-fs.exe' || 'motrix-finalize-fs' }}run: >-pnpm exec vitest run+ src/core/legacy-import/http-activation.integration.test.tssrc/core/plugin/finalize/native-artifact-operations.integration.test.tssrc/core/plugin/finalize/finalize-adversarial.integration.test.tssrc/core/plugin/finalize/finalize-smb-recovery.integration.test.ts@@ -926,7 +928,7 @@ jobs:EXPECTED_COMMIT: ${{ github.sha }}EXPECTED_PLATFORM: ${{ matrix.platform }}# Updated only after reviewing the verifier source itself.- VERIFIER_SHA256: 4d7b6c9cc9ecb4b8df13df35b0ce13fc3e384841236abe900d82004bfb46ca7b+ VERIFIER_SHA256: 6a66bf08bdb8725e51f58a8b7e09217750b318bae5109fce5d01502683809940run: |const crypto = require('node:crypto')const fs = require('node:fs')diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 37743bc7..8306e4c8 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -102,8 +102,8 @@ must obtain permission or replace the font before distributing the build.Desktop builds bundle an `aria2c` executable pinned by`scripts/engine.lock.json`:-- **Version:** 1.37.0-motrix.19-- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.19>+- **Version:** 1.37.0-motrix.20+- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.20>- **License:** GNU General Public License v2.0 or later (`GPL-2.0-or-later`)- **Full license text:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL exception / notice:**diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.mdindex 0fca987c..5d179a2d 100644--- a/THIRD_PARTY_NOTICES.zh-CN.md+++ b/THIRD_PARTY_NOTICES.zh-CN.md@@ -87,8 +87,8 @@ Safari 图标是从 macOS 27.0(26A428)自带的 Safari 27.0 中 `Safari.app/桌面版随应用打包 `aria2c` 可执行文件,版本由 `scripts/engine.lock.json` 固定:-- **版本:** 1.37.0-motrix.19-- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.19>+- **版本:** 1.37.0-motrix.20+- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.20>- **许可证:** GNU General Public License v2.0 or later(`GPL-2.0-or-later`)- **完整许可证文本:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL 例外条款 / 声明:**diff --git a/e2e/legacy-http-activation.spec.ts b/e2e/legacy-http-activation.spec.tsnew file mode 100644index 00000000..b0f6d15b--- /dev/null+++ b/e2e/legacy-http-activation.spec.ts@@ -0,0 +1,214 @@+import { createHash } from 'node:crypto'+import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'+import { createServer } from 'node:http'+import path from 'node:path'+import { gunzipSync } from 'node:zlib'+import type { Page } from '@playwright/test'+import { Commands } from '../src/shared/protocol/commands'+import { Queries } from '../src/shared/protocol/queries'+import type { DownloadTask } from '../src/shared/types/task'+import {+ expect,+ launchMotrix,+ test,+ waitForEngineReady,+} from './fixtures/electron-app'++async function invoke(+ page: Page,+ channel: string,+ input?: unknown+): Promise<unknown> {+ return page.evaluate(+ async ({ channel, input }) => {+ return (+ window as unknown as {+ motrix: {+ invoke: (channel: string, input?: unknown) => Promise<unknown>+ }+ }+ ).motrix.invoke(channel, input)+ },+ { channel, input }+ )+}++for (const mismatch of [false, true]) {+ test(`HTTP legacy content ${mismatch ? 'mismatch keeps original files without downloading' : 'verification resumes original file and survives restart'}`, async ({+ userDataDir,+ rpcPort,+ }, testInfo) => {+ test.skip(+ process.env.MOTRIX_E2E_LEGACY_HTTP !== '1',+ 'Requires the native HTTP redirect policy engine'+ )+ const total = 4194304+ const completed = 1638400+ const payload = Buffer.alloc(total)+ for (let index = 0; index < total; index++) payload[index] = index % 251+ if (mismatch) payload[completed - 1] ^= 255+ const ranges: string[] = []+ const server = createServer((request, response) => {+ const range = request.headers.range ?? ''+ ranges.push(range)+ if (+ request.headers.cookie !== 'session=e2e-fixture' ||+ request.headers['accept-encoding'] !== 'identity'+ ) {+ response.writeHead(403).end()+ return+ }+ const match = /^bytes=(\d+)-(\d*)$/.exec(range)+ const start = match ? Number(match[1]) : 0+ const end = match?.[2] ? Number(match[2]) : total - 1+ response.writeHead(match ? 206 : 200, {+ ETag: '"http-legacy-v1"',+ 'Accept-Ranges': 'bytes',+ 'Content-Length': end - start + 1,+ ...(match ? { 'Content-Range': `bytes ${start}-${end}/${total}` } : {}),+ })+ response.end(payload.subarray(start, end + 1))+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const address = server.address()+ if (!address || typeof address === 'string')+ throw new Error('Missing local server')+ const source = path.join(userDataDir, 'legacy-http-profile')+ const downloads = path.join(userDataDir, 'original-downloads')+ await mkdir(source)+ await mkdir(downloads)+ const original = gunzipSync(+ await readFile(+ 'tests/fixtures/legacy-v1/generated/downloads/partial.bin.gz'+ )+ )+ const control = await readFile(+ 'tests/fixtures/legacy-v1/generated/downloads/partial.bin.aria2'+ )+ const target = path.join(downloads, 'partial.bin')+ await writeFile(target, original, { mode: 0o600 })+ await writeFile(`${target}.aria2`, control, { mode: 0o600 })+ const inode = (await stat(target)).ino+ await writeFile(+ path.join(source, 'user.json'),+ JSON.stringify({ theme: 'auto' })+ )+ await writeFile(+ path.join(source, 'system.json'),+ JSON.stringify({ dir: downloads })+ )+ await writeFile(+ path.join(source, 'download.session'),+ `http://127.0.0.1:${address.port}/partial.bin\n gid=1234567890abcdef\n out=partial.bin\n pause=true\n header=Cookie: session=e2e-fixture\n`+ )+ let app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const page = await app.firstWindow()+ await page.waitForLoadState('domcontentloaded')+ await waitForEngineReady(page)+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await page.getByRole('button', { name: 'Migrate', exact: true }).click()+ await page.getByRole('button', { name: 'View downloads' }).click()+ const tasks = (await invoke(page, Queries.ListTasks)) as DownloadTask[]+ expect(tasks).toHaveLength(1)+ const taskId = tasks[0].id+ await page.locator(`[data-task-id="${taskId}"]`).dblclick()+ const activate = page.getByRole('button', {+ name: 'Verify and continue',+ exact: true,+ })+ await expect(activate).toBeEnabled()+ await app.evaluate(({ dialog }, directory) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [directory],+ })+ }, downloads)+ await activate.click()+ if (mismatch) {+ await expect(+ page.getByText(+ 'The downloaded data differs from the server content.',+ { exact: true }+ )+ ).toBeVisible()+ expect(await readFile(target)).toEqual(original)+ expect(+ ((await invoke(page, Queries.ListTasks)) as DownloadTask[])[0]+ ).toMatchObject({ engineTaskId: '', status: 'paused' })+ expect(ranges).not.toContain(`bytes=${completed}-${total - 1}`)+ expect(+ await app.evaluate(({ BrowserWindow }) =>+ BrowserWindow.getAllWindows().some(+ (window) =>+ window.webContents.getURL().includes('w=add-task') &&+ window.isVisible()+ )+ )+ ).toBe(false)+ } else {+ await expect+ .poll(+ async () =>+ ((await invoke(page, Queries.ListTasks)) as DownloadTask[])[0]+ )+ .toMatchObject({+ status: 'completed',+ totalBytes: total,+ downloadedBytes: total,+ })+ expect(ranges).toContain(`bytes=${completed}-${total - 1}`)+ expect(+ createHash('sha256')+ .update(await readFile(target))+ .digest('hex')+ ).toBe(createHash('sha256').update(payload).digest('hex'))+ expect((await stat(target)).ino).toBe(inode)+ await page.screenshot({+ path: testInfo.outputPath('http-resumed.png'),+ animations: 'disabled',+ })+ await page.locator(`[data-task-id="${taskId}"]`).screenshot({+ path: testInfo.outputPath('http-resumed-row.png'),+ animations: 'disabled',+ })+ await app.close()+ app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ const restarted = await app.firstWindow()+ await restarted.waitForLoadState('domcontentloaded')+ await waitForEngineReady(restarted)+ await expect+ .poll(+ async () =>+ (+ (await invoke(restarted, Queries.ListTasks)) as DownloadTask[]+ )[0]+ )+ .toMatchObject({+ status: 'completed',+ totalBytes: total,+ downloadedBytes: total,+ })+ await invoke(restarted, Commands.RemoveTask, {+ taskId,+ deleteWithFiles: true,+ })+ expect(await invoke(restarted, Queries.ListTasks)).toEqual([])+ expect((await readFile(target)).equals(payload)).toBe(true)+ }+ expect(await readFile(`${target}.aria2`)).toEqual(control)+ } finally {+ server.closeAllConnections()+ await app.close().catch(() => {})+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ })+}diff --git a/e2e/legacy-import.spec.ts b/e2e/legacy-import.spec.tsindex 3cbc4ec4..e2b2f62d 100644--- a/e2e/legacy-import.spec.ts+++ b/e2e/legacy-import.spec.ts@@ -69,6 +69,140 @@ async function expandTaskGroups(page: Page) {}test.describe('v1 task import', () => {+ test('migrates paused HTTP tasks with request settings while preserving blocked records and original files', async ({+ userDataDir,+ rpcPort,+ }, testInfo) => {+ const source = await legacyProfile(userDataDir)+ const sessionPath = path.join(source, 'download.session')+ const session = `${await readFile(sessionPath, 'utf8')} header=Authorization: Bearer LEGACY_AUTH_SECRET\n header=Referer: https://example.invalid/private-page\nhttps://example.invalid/blocked.zip\n gid=2234567890abcdef\n out=blocked.zip\n on-download-complete=LEGACY_COMMAND_SECRET\n`+ await writeFile(sessionPath, session)+ await writeFile(+ path.join(source, 'system.json'),+ JSON.stringify({+ dir: path.join(source, 'downloads'),+ 'all-proxy': 'http://user:[email protected]:8080',+ })+ )+ const app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const page = await firstPage(app)+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await expandTaskGroups(page)+ const archive = page.getByRole('checkbox', {+ name: 'archive.zip',+ exact: true,+ })+ await expect(archive).toBeEnabled()+ await expect(archive).toBeChecked()+ await expect(+ page.getByRole('checkbox', { name: 'blocked.zip', exact: true })+ ).toBeDisabled()+ await expect(page.locator('[data-import-group="http"]')).toBeVisible()+ const body = await page.locator('body').innerText()+ for (const secret of [+ 'LEGACY_AUTH_SECRET',+ 'LEGACY_PROXY_SECRET',+ 'LEGACY_COMMAND_SECRET',+ ])+ expect(body).not.toContain(secret)+ await page.screenshot({+ path: testInfo.outputPath('request-settings-preview.png'),+ })+ await page.getByRole('button', { name: 'Migrate', exact: true }).click()+ await expect(+ page+ .getByLabel('Migration summary')+ .getByText('1 task', { exact: true })+ .first()+ ).toBeVisible()+ const tasks = (await invoke(page, Queries.ListTasks)) as Array<{+ id: string+ instances: Array<{+ gid: string | null+ payload: Record<string, unknown>+ }>+ }>+ expect(tasks).toEqual([+ expect.objectContaining({+ name: 'archive.zip',+ status: 'paused',+ engineTaskId: '',+ }),+ ])+ expect(tasks[0].instances[0].payload.legacyImport).toMatchObject({+ activation: 'inactive',+ reason: 'request-settings-required',+ requestOptions: expect.arrayContaining(['header', 'all-proxy']),+ })+ await expect(+ invoke(page, Commands.ResumeTask, tasks[0].id)+ ).rejects.toThrow()+ expect(JSON.stringify(tasks)).not.toContain('LEGACY_AUTH_SECRET')+ expect(JSON.stringify(tasks)).not.toContain('LEGACY_PROXY_SECRET')+ expect(await readFile(sessionPath, 'utf8')).toBe(session)+ expect(+ await readFile(path.join(source, 'downloads', 'archive.zip'), 'utf8')+ ).toBe('original v1 bytes')+ await page.getByRole('button', { name: 'View downloads' }).click()+ await page.locator(`[data-task-id="${tasks[0].id}"]`).dblclick()+ await page+ .getByRole('button', { name: 'Reconfigure and download…' })+ .click()+ const confirmation = page.getByRole('alertdialog')+ await expect(confirmation).toContainText(+ 'The old request settings were not copied.'+ )+ await app.evaluate(({ dialog }, directory) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [directory],+ })+ }, userDataDir)+ await confirmation+ .getByRole('button', { name: 'Choose another location…' })+ .click()+ await expect+ .poll(() =>+ app.windows().some((window) => window.url().includes('w=add-task'))+ )+ .toBe(true)+ const addTask = app+ .windows()+ .find((window) => window.url().includes('w=add-task'))+ expect(addTask).toBeDefined()+ if (!addTask) throw new Error('Add-task window did not open')+ await expect(addTask.getByRole('alert')).toContainText(+ 'Saved request settings: header, all-proxy'+ )+ await expect(+ addTask.getByRole('button', { name: 'Advanced', exact: true })+ ).toHaveAttribute('aria-expanded', 'true')+ await expect(+ addTask.getByRole('button', { name: 'Add header' })+ ).toBeVisible()+ await addTask.getByRole('button', { name: 'Add header' }).click()+ await addTask+ .getByLabel('Header name', { exact: true })+ .fill('X-Download-Key')+ await addTask+ .getByLabel('Header value', { exact: true })+ .fill('new-value')+ await addTask.screenshot({+ path: testInfo.outputPath('request-settings-form.png'),+ })+ expect((await invoke(page, Queries.ListTasks)) as unknown[]).toHaveLength(+ 1+ )+ } finally {+ await app.close().catch(() => {})+ }+ })+test('retains invalid source paths and recovers through the native folder picker', async ({userDataDir,rpcPort,diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.ymlindex f62db491..af7e5acf 100644--- a/flatpak/app.motrix.native.yml+++ b/flatpak/app.motrix.native.yml@@ -101,7 +101,7 @@ modules:set -eoutput="$(src/aria2c --version)"printf '%s\n' "$output"- printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.19'+ printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.20'for feature in \'Async DNS' \'BitTorrent' \@@ -123,8 +123,8 @@ modules:sources:- type: giturl: https://github.com/motrixapp/aria2.git- tag: v1.37.0-motrix.19- commit: 5c636cc13753a3b3384ec7f51a2587f851d2e4bd+ tag: v1.37.0-motrix.20+ commit: da03d2971965f40d9ecbcf2a329f16758db33e97x-checker-data:type: gittag-pattern: ^v([\d.]+-motrix\.\d+)$@@ -136,9 +136,9 @@ modules:commands:- |sed -i -E \- 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.19]/' \+ 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.20]/' \configure.ac- grep -qF 'AC_INIT([aria2],[1.37.0-motrix.19]' configure.ac+ grep -qF 'AC_INIT([aria2],[1.37.0-motrix.20]' configure.ac- type: scriptdest-filename: autogen.shcommands:diff --git a/scripts/check-boundaries.mjs b/scripts/check-boundaries.mjsindex 4d3bd39f..af918ea6 100644--- a/scripts/check-boundaries.mjs+++ b/scripts/check-boundaries.mjs@@ -48,7 +48,13 @@ const rules = ['add-task UI must not import transport or protocol commands (except the IPC-aware hook/dialog/form)',pattern: `from ['"](@renderer/lib/transport|@shared/protocol/commands)['"]`,dir: 'src/renderer/components/add-task/',- except: ['use-external-hydration.ts', 'drop-zone.tsx', 'add-task-form.tsx'],+ except: [+ 'use-external-hydration.ts',+ 'drop-zone.tsx',+ 'add-task-form.tsx',+ // The form's integration tests assert its IPC contract.+ 'add-task-form.test.tsx',+ ],},{label: 'web-services must not reference Electron-only command symbols',diff --git a/scripts/electron-package-size-budgets.json b/scripts/electron-package-size-budgets.jsonindex 77e16ba3..96cb0676 100644--- a/scripts/electron-package-size-budgets.json+++ b/scripts/electron-package-size-budgets.json@@ -1,6 +1,6 @@{"schemaVersion": 1,- "payloadBytes": 28311552,+ "payloadBytes": 31457280,"betterSqlite3Bytes": 4194304,"unexpectedPackageNames": 0,"foreignBetterSqlite3Prebuilds": 0,diff --git a/scripts/engine.lock.json b/scripts/engine.lock.jsonindex 0bacd6cf..fa047ea8 100644--- a/scripts/engine.lock.json+++ b/scripts/engine.lock.json@@ -1,56 +1,56 @@{"engine": "aria2","repo": "motrixapp/aria2",- "tag": "v1.37.0-motrix.19",- "version": "1.37.0-motrix.19",+ "tag": "v1.37.0-motrix.20",+ "version": "1.37.0-motrix.20","assets": {"darwin-arm64": {- "file": "aria2c-1.37.0-motrix.19-darwin-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.20-darwin-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "c564bf41994626a78ee69d316d3e0d4257b168a2bcf57805ca9923de081203da",- "binarySha256": "ef5708614ef2a7423d17e3697c2272fd288ab49cba4589bc5ff732d52aa78a61"+ "archiveSha256": "add9cfc30c195cf3fd07362eb6e2f5ce0f2f6383e7d4e491edf762663bd168b0",+ "binarySha256": "65e87b8fde23d67047f3a5c74a57828f720c4b5f93cde492ad54271fbabe9875"},"darwin-x64": {- "file": "aria2c-1.37.0-motrix.19-darwin-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.20-darwin-x64.tar.gz","bin": "aria2c",- "archiveSha256": "441f54e2424e71c717a014ebb6916d42cb602a68b95dfdd7d5b76ef327c8fabc",- "binarySha256": "4be7906ac4fbf86ff243b5b759aef099661a416eaea64e3669883514f372e866"+ "archiveSha256": "44103184d56b86e51622f00722ad22520a55953b31befbf4872b3a12f158dbc2",+ "binarySha256": "05936e14ff5c238a7788a7e815fea192e3d5d305046df65ffa243d4ade82daed"},"win32-arm64": {- "file": "aria2c-1.37.0-motrix.19-win32-arm64.zip",+ "file": "aria2c-1.37.0-motrix.20-win32-arm64.zip","bin": "aria2c.exe",- "archiveSha256": "1c1e96304bee4a9e32728839f62751d359f48e28f1d78c724271cf8443769718",- "binarySha256": "ae5fff45eff6f86b14da86344a644ca557d6c86973a863d3924607d0cc7417d8"+ "archiveSha256": "24d52fc6cba11d61e80bf4ce94f4310ab56e6704c29930b3e49b5b984b18f894",+ "binarySha256": "591aa58c51371f13710dd94af040a6d041ea500e70148e5a14560fabef4365c9"},"win32-x64": {- "file": "aria2c-1.37.0-motrix.19-win32-x64.zip",+ "file": "aria2c-1.37.0-motrix.20-win32-x64.zip","bin": "aria2c.exe",- "archiveSha256": "9a03827fb170062cff886125382e72f525102df1dd5cf95f945c02ebb569e18f",- "binarySha256": "0bd858816412abba22a3d417bba3d0f1196e9b7156d8d0745920f618cd6a51bc"+ "archiveSha256": "995b0684531972737035ba51388b1ae8d316b5de72bb769153af54c725104a15",+ "binarySha256": "f9b00b9c1243059ec2a44baf0438d5af3e5b6208c319ef068a6812b19e1661bf"},"win32-ia32": {- "file": "aria2c-1.37.0-motrix.19-win32-ia32.zip",+ "file": "aria2c-1.37.0-motrix.20-win32-ia32.zip","bin": "aria2c.exe",- "archiveSha256": "dc0700a60cbd1e39de2839fa0f85ea738b1843abc9f43062264766f9585ca4f8",- "binarySha256": "74b887855c00ece41753a090fb6ec2dfd658b83d74c258b53d5ec37f029c20ab"+ "archiveSha256": "f88cbd091dd8fb1f50ba78afd7445ff7e93a8c794a42d25d142fec5bf1b4c300",+ "binarySha256": "c41bb02cc49171d1aebeae4e5236d87a4701115a003f798da4b6ed52210e1efc"},"linux-x64": {- "file": "aria2c-1.37.0-motrix.19-linux-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.20-linux-x64.tar.gz","bin": "aria2c",- "archiveSha256": "1f36d1bc98b31ac1df0fb060d47624aa27e3e802ed1e1c375a515a505354e342",- "binarySha256": "164e909adadc01024e8dae80061d1698502b0f7f83d314fe7f28ed1845034d21"+ "archiveSha256": "92658ec45eb6edf1fcc958c333c1db7e5bbbf23f11d38da52c1510f5fce84b77",+ "binarySha256": "36ffdac301cfad089ca50b5c2ac6a1794d20783f7f58f7209e942df90052a53f"},"linux-arm64": {- "file": "aria2c-1.37.0-motrix.19-linux-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.20-linux-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "7ccba6e77a38c516fc9a67c530765b5ebf00084dfaad1295939d8e6a018e7297",- "binarySha256": "d9161b9bc97afb409d00273a8de3f89fd550ec928a542ec3c5a68ed8fb5ba151"+ "archiveSha256": "528367b8f4eaf7a708b2615d9eef60c69c0b9a4645eb06ca81665c8f2f09ceb7",+ "binarySha256": "d11ac0903232baf1b9d2afa7e2ffe2dab593eb14411b35ed3a3b76a6c74213cc"},"linux-arm": {- "file": "aria2c-1.37.0-motrix.19-linux-armv7l.tar.gz",+ "file": "aria2c-1.37.0-motrix.20-linux-armv7l.tar.gz","bin": "aria2c",- "archiveSha256": "be3b64bd84d343bc30693e45974613817e99602a53bced96f7361a618f82e71d",- "binarySha256": "235ed2fdddaaef6b34564eadbee0d76d0b724c852f8b36381d44f25618ede8ee"+ "archiveSha256": "14909afebd70a729b938ad81f7ca008f4dd7d3e9dc55e04b6d71ec0e8b1f8910",+ "binarySha256": "cda8dc145f6a183d973aba33972de5872b4b36edcc38167af8093107792796fd"}}}diff --git a/scripts/release-signing-input.mjs b/scripts/release-signing-input.mjsindex cf694ed6..cafa4b73 100644--- a/scripts/release-signing-input.mjs+++ b/scripts/release-signing-input.mjs@@ -67,7 +67,7 @@ const TRUSTED_INPUT_SHA256 = Object.freeze({'signing-tool/package-lock.json':'359d233c92ee582748bde268af57dbca239c3391753e072263fa1a1180fc362f','scripts/electron-package-size-budgets.json':- '6a7585a5f922cfc5a90e83ac778bcd46efae90ba9079853e3a66ad275b2438c7',+ 'c9a7b04ab93071809f9dca3d5ece6a2e7daa8fd211c34a1c9087eadef9f5fc89','scripts/electron-package-utils.mjs':'8834f6e22db4212655368a31815c7f86ac16c3065aacabb99e83878b9df43831','scripts/before-build-use-staged-dependencies.mjs':diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjsindex 6452cb95..e7dea402 100644--- a/scripts/verify-flatpak-packaging.mjs+++ b/scripts/verify-flatpak-packaging.mjs@@ -18,8 +18,8 @@ export const FLATPAK_BUILDER_TOOLS_COMMIT =// tag resolves to is pinned by hand (and cross-checked against the manifest).export const ARIA2_SOURCE = Object.freeze({url: 'https://github.com/motrixapp/aria2.git',- // v1.37.0-motrix.19 — current Motrix aria2 fork release- commit: '5c636cc13753a3b3384ec7f51a2587f851d2e4bd',+ // v1.37.0-motrix.20 — current Motrix aria2 fork release+ commit: 'da03d2971965f40d9ecbcf2a329f16758db33e97',})const PNPM_SOURCE = Object.freeze({diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex d6723adb..a70d3d96 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -67,6 +67,43 @@ function featureReport(// ─── Fixtures ───────────────────────────────────────────────+describe('legacy HTTP activation capability', () => {+ it('requires native redirect enforcement and rejects cumulative ambient headers', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)+ vi.mocked(rpc.getVersion).mockResolvedValue({+ version: 'test',+ enabledFeatures: ['SQLite3-Persistence', 'LegacyCheckpointImportV1'],+ })+ vi.mocked(rpc.getGlobalOption).mockResolvedValue({})+ expect(await adapter.supportsLegacyHttpActivation()).toBe(false)+ vi.mocked(rpc.getVersion).mockResolvedValue({+ version: 'test',+ enabledFeatures: [+ 'SQLite3-Persistence',+ 'LegacyCheckpointImportV1',+ 'HttpRedirectPolicyV1',+ ],+ })+ expect(await adapter.supportsLegacyHttpActivation()).toBe(true)+ vi.mocked(rpc.getGlobalOption).mockResolvedValue({+ header: 'Authorization: ambient-secret',+ })+ expect(await adapter.supportsLegacyHttpActivation()).toBe(false)+ await expect(+ adapter.createDownload({+ uris: ['https://example.test/file'],+ saveDir: '/tmp',+ legacyCheckpointActivation: {+ token: 'legacy_http_token_1234',+ targetPath: '/tmp/file',+ },+ })+ ).rejects.toThrow('httpRequestUnsupported')+ expect(rpc.addUri).not.toHaveBeenCalled()+ })+})+const RAW_HTTP_ACTIVE: Aria2RawStatus = {gid: '2089b05ecca3d829',status: 'active',diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex aa9fa588..50538391 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -39,9 +39,14 @@ import type {DownloadCookie,EngineAdapter,LegacyBtBindingProof,+ LegacyHttpBindingProof,} from '../engine-adapter'import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine-adapter'import { Aria2LegacyCheckpoint } from './aria2-legacy-checkpoint'+import {+ pinLegacyHttpOptions,+ verifyLegacyHttpBinding,+} from './aria2-legacy-http'import { legacyWirePath } from './aria2-legacy-path'import type { Aria2RpcClient } from './aria2-rpc-client'import { recommend } from './aria2-tuning'@@ -414,6 +419,14 @@ export class Aria2Adapter implements EngineAdapter {}async createDownload(params: CreateDownloadParams): Promise<string> {+ if (+ params.legacyCheckpointActivation &&+ !(await this.supportsLegacyHttpActivation())+ )+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.httpRequestUnsupported'+ )params = {...params,uris: admitDownloadSources(params.uris, 'engine').map(@@ -587,6 +600,11 @@ export class Aria2Adapter implements EngineAdapter {options['always-resume'] = 'true'}options.continue = resumePolicy === 'sequential-prefix' ? 'true' : 'false'+ await pinLegacyHttpOptions(+ params,+ options,+ new Aria2LegacyCheckpoint(this.rpc)+ )// A magnet can spawn a BT payload with HTTP Web Seeds. Their 404s must// not halt the entire torrent before a healthy source sends any data.@@ -799,6 +817,33 @@ export class Aria2Adapter implements EngineAdapter {)}+ async verifyLegacyHttpBinding(+ input: LegacyHttpBindingProof+ ): Promise<boolean> {+ if (!(await this.supportsLegacyHttpActivation())) return false+ return verifyLegacyHttpBinding(this.rpc, input)+ }++ async supportsLegacyHttpActivation(): Promise<boolean> {+ if (!(await this.supportsLegacyCheckpointImport())) return false+ if (+ !(await this.rpc.getVersion()).enabledFeatures.includes(+ 'HttpRedirectPolicyV1'+ )+ )+ return false+ const options = await this.rpc.getGlobalOption()+ const header = options.header as unknown+ // aria2 accumulates global and per-task header options. An empty Cookie+ // suppresses CookieStorage, but cannot remove inherited header lines.+ return (+ header === undefined ||+ header === '' ||+ (Array.isArray(header) &&+ header.every((line) => typeof line === 'string' && !line.trim()))+ )+ }+async addTorrent(params: AddTorrentParams): Promise<string> {const legacyMetadata = params.legacyCheckpointActivation? Buffer.from(params.metadata)diff --git a/src/core/engine/aria2/aria2-legacy-http.test.ts b/src/core/engine/aria2/aria2-legacy-http.test.tsnew file mode 100644index 00000000..abf7741f--- /dev/null+++ b/src/core/engine/aria2/aria2-legacy-http.test.ts@@ -0,0 +1,206 @@+// @vitest-environment node+import {+ lstat,+ mkdtemp,+ realpath,+ rename,+ rm,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import type {+ CreateDownloadParams,+ LegacyHttpBindingProof,+} from '../engine-adapter'+import type { Aria2LegacyCheckpoint } from './aria2-legacy-checkpoint'+import {+ pinLegacyHttpOptions,+ verifyLegacyHttpBinding,+} from './aria2-legacy-http'+import { legacyWirePath } from './aria2-legacy-path'+import type { Aria2RpcClient } from './aria2-rpc-client'++const roots: string[] = []+afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))+ )+})++async function fixture() {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'legacy-http-adapter-'))+ )+ roots.push(root)+ const filename = path.join(root, 'partial.bin')+ await writeFile(filename, Buffer.alloc(64), { mode: 0o600 })+ const stat = await lstat(filename, { bigint: true })+ const input: LegacyHttpBindingProof = {+ engineTaskId: '1234567890abcdef',+ saveDir: root,+ targetPath: filename,+ uri: 'https://example.test/file.bin',+ expected: { totalBytes: 128, pieceBytes: 64 },+ entityTag: '"version-1"',+ fileIdentity: { device: String(stat.dev), inode: String(stat.ino) },+ }+ const params: CreateDownloadParams = {+ uris: [input.uri],+ saveDir: root,+ filename: 'partial.bin',+ gid: input.engineTaskId,+ pause: true,+ resumePolicy: 'checkpoint',+ cookies: [],+ legacyCheckpointActivation: {+ token: 'legacy_http_token_1234',+ targetPath: filename,+ },+ }+ const options: Record<string, string | string[]> = {+ 'piece-length': '64',+ header: ['If-Match: "version-1"', 'Accept-Encoding: identity'],+ 'allow-overwrite': 'true',+ 'http-user': 'ambient-secret',+ 'http-proxy': 'http://ambient.test',+ }+ const reconcile = vi.fn(async () => ({+ status: 'created',+ engineTaskId: input.engineTaskId,+ }))+ const checkpoint = { reconcile } as unknown as Aria2LegacyCheckpoint+ return { root, filename, input, params, options, reconcile, checkpoint }+}++describe('legacy HTTP dispatch and binding', () => {+ it('pins the original output, checkpoint and request semantics after passthrough', async () => {+ const f = await fixture()+ await pinLegacyHttpOptions(f.params, f.options, f.checkpoint)+ expect(f.options).toMatchObject({+ dir: legacyWirePath(f.root),+ out: 'partial.bin',+ gid: f.input.engineTaskId,+ pause: 'true',+ 'always-resume': 'true',+ continue: 'false',+ 'allow-overwrite': 'false',+ 'auto-file-renaming': 'false',+ 'remove-control-file': 'false',+ 'file-allocation': 'none',+ 'follow-torrent': 'false',+ 'follow-metalink': 'false',+ 'http-user': '',+ 'http-passwd': '',+ 'all-proxy': '',+ 'http-proxy': '',+ 'no-netrc': 'true',+ header: [+ 'If-Match: "version-1"',+ 'Accept-Encoding: identity',+ 'Cookie: ',+ ],+ })+ })++ it.each(['consumed', 'absent', 'wrong-gid'])(+ 'does not dispatch from an unowned or consumed receipt: %s',+ async (status) => {+ const f = await fixture()+ f.reconcile.mockResolvedValue({+ status,+ engineTaskId:+ status === 'wrong-gid' ? 'ffffffffffffffff' : f.input.engineTaskId,+ })+ await expect(+ pinLegacyHttpOptions(f.params, f.options, f.checkpoint)+ ).rejects.toThrow('activationUncertain')+ }+ )++ it.each([+ ['missing version', []],+ ['weak version', ['If-Match: W/"version-1"', 'Accept-Encoding: identity']],+ [+ 'duplicate version',+ [+ 'If-Match: "version-1"',+ 'if-match: "other"',+ 'Accept-Encoding: identity',+ ],+ ],+ ['encoded response', ['If-Match: "version-1"', 'Accept-Encoding: gzip']],+ ])('rejects %s before native dispatch', async (_label, headers) => {+ const f = await fixture()+ f.options.header = headers+ await expect(+ pinLegacyHttpOptions(f.params, f.options, f.checkpoint)+ ).rejects.toThrow('activationUncertain')+ expect(f.reconcile).not.toHaveBeenCalled()+ })++ it('rejects output relocation', async () => {+ const f = await fixture()+ f.params.filename = 'other.bin'+ await expect(+ pinLegacyHttpOptions(f.params, f.options, f.checkpoint)+ ).rejects.toThrow('activationUncertain')+ })++ it('proves a paused zero-length native row, rejects changed ownership and unsafe options', async () => {+ const f = await fixture()+ await pinLegacyHttpOptions(f.params, f.options, f.checkpoint)+ const raw = {+ gid: f.input.engineTaskId,+ status: 'paused',+ totalLength: '0',+ files: [+ {+ path: legacyWirePath(f.filename),+ length: '0',+ uris: [{ uri: f.input.uri, status: 'waiting' }],+ },+ ],+ }+ const rpc = {+ tellStatus: vi.fn(async () => raw),+ getOption: vi.fn(async () => f.options),+ } as unknown as Aria2RpcClient+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(true)+ raw.files[0].uris.push({ uri: f.input.uri, status: 'used' })+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(true)+ raw.files[0].uris[1].uri = 'https://different.test/file.bin'+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ raw.files[0].uris.pop()+ f.input.request = {+ headers: {},+ userAgent: 'verified-agent',+ proxy: '',+ noProxy: '',+ }+ f.options['user-agent'] = 'verified-agent'+ f.options.header = `${(f.options.header as string[]).join('\n')}\nAccept: */*\n`+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(true)+ const verifiedHeaders = f.options.header+ f.options.header += 'Authorization: unexpected\n'+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ f.options.header = verifiedHeaders+ f.options['user-agent'] = 'other-agent'+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ f.options['user-agent'] = 'verified-agent'+ delete f.input.request+ f.options['allow-overwrite'] = 'true'+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ f.options['allow-overwrite'] = 'false'+ raw.files[0].uris[0].uri = 'https://other.test/file.bin'+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ raw.files[0].uris[0].uri = f.input.uri+ f.options.header = ['If-Match: "other"', 'Accept-Encoding: identity']+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ f.options.header = ['If-Match: "version-1"', 'Accept-Encoding: identity']+ await rename(f.filename, `${f.filename}.original`)+ await writeFile(f.filename, Buffer.alloc(64), { mode: 0o600 })+ expect(await verifyLegacyHttpBinding(rpc, f.input)).toBe(false)+ })+})diff --git a/src/core/engine/aria2/aria2-legacy-http.ts b/src/core/engine/aria2/aria2-legacy-http.tsnew file mode 100644index 00000000..26c2fbdb--- /dev/null+++ b/src/core/engine/aria2/aria2-legacy-http.ts@@ -0,0 +1,257 @@+import { lstat, realpath } from 'node:fs/promises'+import path from 'node:path'+import {+ extractAria2ProxyCredentials,+ normalizeAria2TaskProxyUrl,+} from '@core/proxy/aria2-proxy-routing'+import { admitDownloadSources } from '@core/task/source-admission'+import { AppError, ErrorCode } from '@shared/errors'+import type { EngineTaskOptions } from '@shared/types/engine-task-options'+import type {+ CreateDownloadParams,+ LegacyHttpBindingProof,+} from '../engine-adapter'+import type { Aria2LegacyCheckpoint } from './aria2-legacy-checkpoint'+import { legacyWirePath } from './aria2-legacy-path'+import type { Aria2RpcClient } from './aria2-rpc-client'++const fixedOptions = {+ 'always-resume': 'true',+ continue: 'false',+ 'allow-overwrite': 'false',+ 'auto-file-renaming': 'false',+ 'remove-control-file': 'false',+ 'file-allocation': 'none',+ 'follow-torrent': 'false',+ 'follow-metalink': 'false',+ 'check-integrity': 'false',+ 'http-accept-gzip': 'false',+ 'no-want-digest-header': 'false',+ 'proxy-method': 'get',+ 'max-http-redirect': '0',+ 'no-netrc': 'true',+ 'http-user': '',+ 'http-passwd': '',+ 'http-auth-challenge': 'false',+ 'conditional-get': 'false',+ 'http-no-cache': 'false',+ 'use-head': 'false',+ 'dry-run': 'false',+ referer: '',+ 'load-cookies': '',+ 'http-proxy': '',+ 'http-proxy-user': '',+ 'http-proxy-passwd': '',+ 'https-proxy': '',+ 'https-proxy-user': '',+ 'https-proxy-passwd': '',+ 'ftp-proxy': '',+ 'ftp-proxy-user': '',+ 'ftp-proxy-passwd': '',+} as const++function headerValues(+ header: EngineTaskOptions['header'],+ name: string+): string[] {+ const lines = Array.isArray(header) ? header : (header ?? '').split('\n')+ return lines.flatMap((line) => {+ const colon = line.indexOf(':')+ return colon >= 0 && line.slice(0, colon).trim().toLowerCase() === name+ ? [line.slice(colon + 1).trim()]+ : []+ })+}++function validEntityTag(value: string): boolean {+ return (+ value.length >= 2 &&+ value.length <= 512 &&+ value.startsWith('"') &&+ value.endsWith('"') &&+ [...value.slice(1, -1)].every(+ (character) =>+ character !== '"' &&+ character.charCodeAt(0) > 32 &&+ character.charCodeAt(0) !== 127+ )+ )+}++function invalid(): AppError {+ return new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.activationUncertain'+ )+}++function requestMatches(+ options: EngineTaskOptions,+ input: LegacyHttpBindingProof+): boolean {+ if (!input.request) return true+ const expected = new Map<string, string>()+ for (const [name, value] of Object.entries(input.request.headers ?? {})) {+ const key = name.toLowerCase()+ if (expected.has(key)) return false+ if (!['range', 'if-range', 'if-match', 'accept-encoding'].includes(key))+ expected.set(key, value.trim())+ }+ expected.set('if-match', input.entityTag)+ expected.set('accept-encoding', 'identity')+ if (!expected.has('cookie')) expected.set('cookie', '')+ if (!expected.has('accept')) expected.set('accept', '*/*')+ const lines = Array.isArray(options.header)+ ? options.header+ : (options.header ?? '').split('\n')+ const actual = new Map<string, string>()+ for (const line of lines) {+ if (!line.trim()) continue+ const colon = line.indexOf(':')+ if (colon <= 0) return false+ const key = line.slice(0, colon).trim().toLowerCase()+ if (actual.has(key)) return false+ actual.set(key, line.slice(colon + 1).trim())+ }+ if (+ actual.size !== expected.size ||+ [...expected].some(([key, value]) => actual.get(key) !== value)+ )+ return false+ if (+ options['user-agent'] !== input.request.userAgent ||+ (options['no-proxy'] ?? '') !== (input.request.noProxy ?? '')+ )+ return false+ const proxy = input.request.proxy?.trim()+ if (!proxy)+ return (+ !options['all-proxy'] &&+ !options['all-proxy-user'] &&+ !options['all-proxy-passwd']+ )+ const expectedProxy = normalizeAria2TaskProxyUrl(proxy)+ const credentials = extractAria2ProxyCredentials(proxy)+ const actualProxy =+ typeof options['all-proxy'] === 'string'+ ? normalizeAria2TaskProxyUrl(options['all-proxy'])+ : null+ if (!expectedProxy || !actualProxy || !credentials) return false+ expectedProxy.username = expectedProxy.password = ''+ return (+ expectedProxy.href === actualProxy.href &&+ (options['all-proxy-user'] ?? '') === credentials.username &&+ (options['all-proxy-passwd'] ?? '') === credentials.password+ )+}++/** Pin the verified request and original output after all caller passthrough options. */+export async function pinLegacyHttpOptions(+ params: CreateDownloadParams,+ options: Record<string, string | string[]>,+ checkpoint: Aria2LegacyCheckpoint+): Promise<void> {+ const context = params.legacyCheckpointActivation+ if (!context) return+ const tags = headerValues(options.header, 'if-match')+ const encoding = headerValues(options.header, 'accept-encoding')+ const pieceLength = Number(options['piece-length'])+ if (+ !params.gid ||+ !/^[a-f0-9]{16}$/.test(params.gid) ||+ /^0+$/.test(params.gid) ||+ params.uris.length !== 1 ||+ !/^https?:\/\//i.test(params.uris[0]) ||+ !params.filename ||+ path.basename(params.filename) !== params.filename ||+ !path.isAbsolute(params.saveDir) ||+ path.resolve(params.saveDir) !== params.saveDir ||+ path.join(params.saveDir, params.filename) !== context.targetPath ||+ params.resumePolicy !== 'checkpoint' ||+ params.pause !== true ||+ !Number.isSafeInteger(pieceLength) ||+ pieceLength <= 0 ||+ pieceLength > 2147483647 ||+ tags.length !== 1 ||+ !validEntityTag(tags[0]) ||+ encoding.length !== 1 ||+ encoding[0] !== 'identity' ||+ params.cookies?.length+ )+ throw invalid()+ const receipt = await checkpoint.reconcile(context)+ if (receipt.status !== 'created' || receipt.engineTaskId !== params.gid)+ throw invalid()+ Object.assign(options, fixedOptions, {+ dir: legacyWirePath(params.saveDir),+ out: params.filename,+ gid: params.gid,+ pause: 'true',+ // One range at a time also limits pressure while safely reusing sparse blocks.+ split: '1',+ 'max-connection-per-server': '1',+ 'piece-length': String(pieceLength),+ 'no-proxy': params.noProxy ?? '',+ })+ if (!params.proxy?.trim()) {+ options['all-proxy'] = ''+ options['all-proxy-user'] = ''+ options['all-proxy-passwd'] = ''+ }+ const headers = Array.isArray(options.header) ? [...options.header] : []+ if (!headerValues(headers, 'cookie').length) headers.push('Cookie: ')+ options.header = headers+}++/** Never infer ownership from GID or checkpoint receipt alone. */+export async function verifyLegacyHttpBinding(+ rpc: Pick<Aria2RpcClient, 'tellStatus' | 'getOption'>,+ input: LegacyHttpBindingProof+): Promise<boolean> {+ try {+ const [raw, rawOptions, stat, canonical] = await Promise.all([+ rpc.tellStatus(input.engineTaskId),+ rpc.getOption(input.engineTaskId),+ lstat(input.targetPath, { bigint: true }),+ realpath(input.targetPath),+ ])+ const options = rawOptions as unknown as EngineTaskOptions+ const files = raw.files ?? []+ const expectedUri = admitDownloadSources([input.uri], 'engine')[0]+ .requestUrl+ const tags = headerValues(options.header, 'if-match')+ const encoding = headerValues(options.header, 'accept-encoding')+ return (+ raw.gid === input.engineTaskId &&+ !raw.bittorrent &&+ canonical === input.targetPath &&+ stat.isFile() &&+ !stat.isSymbolicLink() &&+ stat.nlink === 1n &&+ String(stat.dev) === input.fileIdentity.device &&+ String(stat.ino) === input.fileIdentity.inode &&+ files.length === 1 &&+ files[0].path === legacyWirePath(input.targetPath) &&+ files[0].uris.length > 0 &&+ files[0].uris.every((source) => source.uri === expectedUri) &&+ (Number(raw.totalLength) === 0 ||+ Number(raw.totalLength) === input.expected.totalBytes) &&+ (Number(files[0].length) === 0 ||+ Number(files[0].length) === input.expected.totalBytes) &&+ options.dir === legacyWirePath(input.saveDir) &&+ options.out === path.basename(input.targetPath) &&+ Number(options['piece-length']) === input.expected.pieceBytes &&+ Object.entries(fixedOptions).every(+ ([key, value]) => (options[key] ?? '') === value+ ) &&+ tags.length === 1 &&+ tags[0] === input.entityTag &&+ validEntityTag(input.entityTag) &&+ encoding.length === 1 &&+ encoding[0] === 'identity' &&+ requestMatches(options, input)+ )+ } catch {+ return false+ }+}diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex dcc7d4e1..6d0073fa 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -106,6 +106,8 @@ export interface DownloadCookie {}export interface CreateDownloadParams {+ /** Explicit in-place legacy HTTP activation after content verification. */+ legacyCheckpointActivation?: { token: string; targetPath: string }uris: string[]saveDir: string/** Optional caller-reserved aria2 GID. aria2 accepts exactly 16@@ -129,6 +131,8 @@ export interface CreateDownloadParams {* max-connection-per-server. Caller is responsible for clamping. */connections?: numberproxy?: string+ /** Explicit bypass context for verified legacy HTTP restoration. */+ noProxy?: string/** Engine-agnostic passthrough for shell-supplied options, such as a* referer. The adapter honors keys it understands. */extraEngineOptions?: Record<string, string | string[]>@@ -170,7 +174,24 @@ export interface LegacyBtBindingProof {trackers: string[]isPrivate: boolean}+export interface LegacyHttpBindingProof {+ engineTaskId: string+ saveDir: string+ targetPath: string+ uri: string+ expected: { totalBytes: number; pieceBytes: number }+ entityTag: string+ fileIdentity: { device: string; inode: string }+ /** Ephemeral original context required before the first unpause; never persisted. */+ request?: Pick<+ CreateDownloadParams,+ 'headers' | 'userAgent' | 'proxy' | 'noProxy'+ >+}+export interface EngineAdapter {+ /** Prove the original output, source and version-pinned HTTP request belong to this GID. */+ verifyLegacyHttpBinding?(input: LegacyHttpBindingProof): Promise<boolean>/** Prove exact native BT ownership, selection and safe restoration options. */verifyLegacyBtBinding?(input: LegacyBtBindingProof): Promise<boolean>configureBtTrackerPolicy?(policy: BtTrackerPolicy): void@@ -297,6 +318,8 @@ export interface EngineAdapter {/** Live capability check; compiled-in support alone does not authorize import. */supportsLegacyCheckpointImport?(): Promise<boolean>+ /** HTTP checkpoint import is available and ambient cumulative headers are absent. */+ supportsLegacyHttpActivation?(): Promise<boolean>/** Both checkpoint import and read-only torrent restoration are available live. */supportsLegacyBtActivation?(): Promise<boolean>/** Inspect bounded opaque legacy bytes without opening or writing payloads. */diff --git a/src/core/legacy-import/http-activation-service.test.ts b/src/core/legacy-import/http-activation-service.test.tsnew file mode 100644index 00000000..55d0389e--- /dev/null+++ b/src/core/legacy-import/http-activation-service.test.ts@@ -0,0 +1,957 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import {+ link,+ readFile,+ rename,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { CompletedEngineTaskCleanup } from '@core/task/completed-engine-task-cleanup'+import type { LegacyHttpContentVerificationInput } from '@core/task/direct-resource-validator'+import type { LegacyCheckpointReceipt } from '@shared/schemas/legacy-checkpoint'+import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'+import { type DownloadTask, TaskStatus } from '@shared/types/task'+import { canResume, isLegacyImportInactive } from '@shared/types/task-actions'+import {+ LEGACY_HTTP_COMPLETED,+ LEGACY_HTTP_TOTAL,+ legacyHttpActivationFixture,+} from '@test-utils/legacy-http-service'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LegacyHttpActivationService } from './http-activation-service'++const cleanup: Array<() => Promise<void>> = []+afterEach(async () => {+ for (const fn of cleanup.splice(0).reverse()) await fn()+})+async function fixture(+ options: { requestLines?: string; system?: Record<string, unknown> } = {}+) {+ let receipt: LegacyCheckpointReceipt | null = null+ let engine: DownloadTask | null = null+ let loseImport = false+ let loseCreate = false+ let binding = true+ let f: Awaited<ReturnType<typeof legacyHttpActivationFixture>>+ const verifier = {+ verifyLegacyContent: vi.fn(+ async (input: LegacyHttpContentVerificationInput) => {+ expect(input.ranges).toEqual([+ { offset: 0, length: LEGACY_HTTP_COMPLETED },+ ])+ expect(+ Buffer.from(await input.read(0, LEGACY_HTTP_COMPLETED)).equals(+ f.payload+ )+ ).toBe(true)+ return {+ validator: {+ kind: 'strong-etag' as const,+ value: '"fixture"',+ contentLength: LEGACY_HTTP_TOTAL,+ capturedAt: 1,+ },+ requestHeaders: {+ 'If-Match': '"fixture"',+ 'Accept-Encoding': 'identity',+ },+ }+ }+ ),+ }+ const adapter = {+ supportsLegacyCheckpointImport: vi.fn(async () => true),+ supportsLegacyHttpActivation: vi.fn(async () => true),+ inspectLegacyCheckpoint: vi.fn(async (bytes: Uint8Array) => ({+ type: 'http',+ totalBytes: LEGACY_HTTP_TOTAL,+ pieceBytes: 1048576,+ infoHash: null,+ completedBytes: LEGACY_HTTP_COMPLETED,+ uploadedBytes: 0,+ ranges: [{ offset: 0, length: LEGACY_HTTP_COMPLETED }],+ sourceDigest: createHash('sha256').update(bytes).digest('hex'),+ })),+ reconcileLegacyCheckpoint: vi.fn(+ async (input) => receipt ?? { ...input, status: 'absent' }+ ),+ importLegacyCheckpoint: vi.fn(async (input) => {+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'import-uncertain', token: input.token })+ receipt = {+ status: 'created',+ token: input.token,+ engineTaskId: input.engineTaskId,+ targetPath: input.targetPath,+ sourceDigest: input.sourceDigest,+ }+ if (loseImport) {+ loseImport = false+ throw new Error('Lost import response')+ }+ return receipt+ }),+ createDownload: vi.fn(async (params) => {+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'create-uncertain', engineTaskId: params.gid })+ expect(params).toMatchObject({+ saveDir: f.downloads,+ filename: 'partial.bin',+ pause: true,+ resumePolicy: 'checkpoint',+ fileAllocation: 'none',+ headers: { 'If-Match': '"fixture"', 'Accept-Encoding': 'identity' },+ })+ expect(f.taskManager.isEngineTaskIdRetired(params.gid)).toBe(true)+ engine = {+ ...f.taskManager.getById(f.taskId),+ engineTaskId: params.gid,+ status: TaskStatus.Paused,+ } as DownloadTask+ if (loseCreate) {+ loseCreate = false+ throw new Error('Lost create response')+ }+ return params.gid+ }),+ getTaskStatus: vi.fn(async () => engine),+ getTaskFiles: vi.fn(async () => []),+ listActiveAndWaiting: vi.fn(async () =>+ engine ? [{ gid: engine.engineTaskId }] : []+ ),+ listStopped: vi.fn(async () => []),+ verifyLegacyHttpBinding: vi.fn(async () => binding),+ pauseTask: vi.fn(async () => {+ if (engine) engine.status = TaskStatus.Paused+ }),+ resumeTask: vi.fn(async () => {+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'resume-uncertain' })+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyImport+ ).toMatchObject({+ activation: 'active',+ storagePolicy: 'legacy-http-in-place',+ })+ if (engine) engine.status = TaskStatus.Downloading+ }),+ } as unknown as EngineAdapter+ f = await legacyHttpActivationFixture({ adapter, verifier, ...options })+ cleanup.push(f.dispose)+ return {+ ...f,+ adapter,+ verifier,+ loseImport: () => {+ loseImport = true+ },+ loseCreate: () => {+ loseCreate = true+ },+ disappear: () => {+ engine = null+ },+ badBinding: () => {+ binding = false+ },+ recover: async () => {+ const service = new LegacyHttpActivationService(f.deps)+ await service.recover()+ return service+ },+ }+}++describe('durable HTTP legacy activation', () => {+ it('replays completion emitted during first resume after the active marker is durable', async () => {+ const f = await fixture()+ let mutationTail = Promise.resolve()+ const runTaskMutation = <T>(+ _ids: readonly string[],+ operation: () => Promise<T>+ ): Promise<T> => {+ const next = mutationTail.then(operation)+ mutationTail = next.then(+ () => {},+ () => {}+ )+ return next+ }+ f.deps.runTaskMutation = runTaskMutation+ const finalize = vi.fn(async (taskId: string) => {+ expect(+ f.db.getTask(taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'active' })+ const current = f.taskManager.getById(taskId) as DownloadTask+ expect(isLegacyImportInactive(current)).toBe(false)+ f.taskManager.set(taskId, { ...current, status: TaskStatus.Completed })+ })+ const adapter = {+ forceRemoveTask: vi.fn(async () => {}),+ removeDownloadResult: vi.fn(async () => {}),+ }+ const completion = new CompletedEngineTaskCleanup({+ taskManager: f.taskManager,+ adapter,+ mintTaskId: () => 'unexpected-adoption',+ persist: vi.fn(async () => {}),+ adopt: vi.fn(async () => {}),+ publish: vi.fn(),+ dispatch: vi.fn(async () => {}),+ runTaskMutation,+ finalizeLegacyHttp: finalize,+ log: { warn: vi.fn() },+ })+ cleanup.push(() => completion.stopAndDrain())+ let observation: Promise<boolean> | undefined+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ const owner = f.taskManager.getByEngineTaskId(gid) as DownloadTask+ expect(isLegacyImportInactive(owner)).toBe(true)+ expect(owner.instances[0].payload.legacyHttpActivation).toMatchObject({+ stage: 'resume-uncertain',+ })+ const live = await f.adapter.getTaskStatus(gid)+ if (live) live.status = TaskStatus.Completed+ // As in the desktop completion listener, observe without awaiting the+ // activation's own mutation lane from inside its resume RPC.+ observation = completion.observe({+ ...owner,+ status: TaskStatus.Completed,+ })+ expect(finalize).not.toHaveBeenCalled()+ })++ expect(await f.service.activate(f.taskId, async () => f.downloads)).toBe(+ true+ )+ await expect(observation).resolves.toBe(true)++ expect(finalize).toHaveBeenCalledOnce()+ expect(f.taskManager.getById(f.taskId)?.status).toBe(TaskStatus.Completed)+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()+ })++ it('verifies every completed byte and binds the original target before resuming once', async () => {+ const f = await fixture()+ expect(await f.service.activate(f.taskId, async () => f.downloads)).toBe(+ true+ )+ const pair = f.db.getTask(f.taskId)+ const intent = legacyHttpActivationSchema.parse(+ pair?.instances[0].payload.legacyHttpActivation+ )+ expect(intent.stage).toBe('active')+ expect(pair?.task).toMatchObject({+ totalBytes: LEGACY_HTTP_TOTAL,+ downloadedBytes: LEGACY_HTTP_COMPLETED,+ finalPath: f.target,+ pieceLength: 1048576,+ })+ expect(pair?.instances[0].diskPath).toBe(f.target)+ expect(pair?.instances[0].progress).toBe(+ (LEGACY_HTTP_COMPLETED / LEGACY_HTTP_TOTAL) * 100+ )+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ expect(await readFile(`${f.target}.aria2`)).toEqual(f.control)+ expect(await readFile(intent.controlBackupPath)).toEqual(f.control)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ expect(+ isLegacyImportInactive(f.taskManager.getById(f.taskId) as DownloadTask)+ ).toBe(false)+ })+ it('uses one request context for verification and native add without persisting credentials', async () => {+ const f = await fixture({+ requestLines:+ ' header=Cookie: token=private-cookie\n referer=https://example.com/private-page\n http-user=private-user\n http-passwd=private-password\n',+ system: {+ 'user-agent': 'Legacy-Agent',+ 'all-proxy': 'http://private-user:proxy-secret@localhost:8080',+ },+ })+ await f.service.activate(f.taskId, async () => f.downloads)+ const options = f.verifier.verifyLegacyContent.mock.calls[0][0].options+ expect(f.adapter.createDownload).toHaveBeenCalledWith(+ expect.objectContaining({+ userAgent: options?.userAgent,+ proxy: options?.proxy,+ headers: expect.objectContaining(options?.headers),+ })+ )+ expect(f.adapter.verifyLegacyHttpBinding).toHaveBeenCalledWith(+ expect.objectContaining({+ request: expect.objectContaining(options ?? {}),+ })+ )+ const serialized = JSON.stringify(f.db.getTask(f.taskId))+ for (const secret of [+ 'private-cookie',+ 'private-page',+ 'private-user',+ 'private-password',+ 'proxy-secret',+ 'Legacy-Agent',+ ])+ expect(serialized).not.toContain(secret)+ })+ it('leaves originals and the engine untouched when remote bytes mismatch', async () => {+ const f = await fixture()+ f.verifier.verifyLegacyContent.mockRejectedValueOnce(+ new Error('httpContentChanged')+ )+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('httpContentChanged')+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toBeUndefined()+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ expect(f.adapter.createDownload).not.toHaveBeenCalled()+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ expect(await readFile(`${f.target}.aria2`)).toEqual(f.control)+ })+ it('rejects a payload replaced while its old read handle is being verified', async () => {+ const f = await fixture()+ const verify = f.verifier.verifyLegacyContent.getMockImplementation()+ f.verifier.verifyLegacyContent.mockImplementationOnce(async (input) => {+ const result = await verify?.(input)+ await rename(f.target, `${f.target}.old`)+ await writeFile(f.target, f.payload)+ if (!result) throw new Error('No verifier')+ return result+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('changedSource')+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ })+ it.each(['control', 'profile'] as const)(+ 'rejects %s changes during verification before importing anything',+ async (kind) => {+ const f = await fixture()+ const verify = f.verifier.verifyLegacyContent.getMockImplementation()+ f.verifier.verifyLegacyContent.mockImplementationOnce(async (input) => {+ const result = await verify?.(input)+ await writeFile(+ kind === 'control'+ ? `${f.target}.aria2`+ : path.join(f.profile, 'system.json'),+ 'changed'+ )+ if (!result) throw new Error('No verifier')+ return result+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('changedSource')+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ }+ )+ it('keeps lost import recovery passive and revalidates on explicit retry', async () => {+ const f = await fixture()+ f.loseImport()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost import response')+ const service = await f.recover()+ expect(f.adapter.createDownload).not.toHaveBeenCalled()+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ await service.activate(f.taskId, async () => f.downloads)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(2)+ expect(f.adapter.importLegacyCheckpoint).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ })+ it('binds a lost create response during recovery without requesting bytes or resuming', async () => {+ const f = await fixture()+ f.loseCreate()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost create response')+ await f.recover()+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'bound' })+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ })+ it.each(['response', 'persist'] as const)(+ 'recovers first-resume progress after losing the final %s without re-adding or remote verification',+ async (lost) => {+ const f = await fixture()+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ await writeFile(+ f.target,+ Buffer.concat([f.payload, Buffer.alloc(32768, 1)])+ )+ if (lost === 'response') throw new Error('Lost resume response')+ })+ const save = f.db.saveTaskWithInstances.bind(f.db)+ vi.spyOn(f.db, 'saveTaskWithInstances').mockImplementation((pair) => {+ if (+ lost === 'persist' &&+ (pair.instances[0].payload.legacyHttpActivation as { stage: string })+ .stage === 'active'+ )+ throw new Error('Lost active save')+ return save(pair)+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow(+ lost === 'response' ? 'Lost resume response' : 'Lost active save'+ )+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({+ stage: 'resume-uncertain',+ retainedContentDigest: createHash('sha256')+ .update(f.payload)+ .digest('hex'),+ })+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ vi.mocked(f.db.saveTaskWithInstances).mockImplementation(save)+ await f.recover()+ expect(f.adapter.pauseTask).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'active' })+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ true+ )+ }+ )+ it('keeps first unpause undispatched when its durable uncertain save fails', async () => {+ const f = await fixture()+ const save = f.db.saveTaskWithInstances.bind(f.db)+ vi.spyOn(f.db, 'saveTaskWithInstances').mockImplementation((pair) => {+ if (+ (pair.instances[0].payload.legacyHttpActivation as { stage: string })+ .stage === 'resume-uncertain'+ )+ throw new Error('Uncertain save failed')+ return save(pair)+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Uncertain save failed')+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'bound' })+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ })+ it.each([false, true])(+ 'pauses a cancelled first unpause even when its response is lost: %s',+ async (loseResponse) => {+ const f = await fixture()+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ await writeFile(+ f.target,+ Buffer.concat([f.payload, Buffer.alloc(32768)])+ )+ f.service.cancel(f.taskId)+ if (loseResponse) throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('httpVerificationCancelled')+ expect(f.adapter.pauseTask).toHaveBeenCalledTimes(1)+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'resume-uncertain' })+ await f.recover()+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ true+ )+ }+ )+ it('rejects a same-inode edit to retained bytes after an uncertain first unpause', async () => {+ const f = await fixture()+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ await writeFile(f.target, Buffer.concat([f.payload, Buffer.alloc(32768)]))+ throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ const changed = await readFile(f.target)+ changed[LEGACY_HTTP_COMPLETED - 1] ^= 255+ await writeFile(f.target, changed)+ const recovered = await f.recover()+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ await expect(+ recovered.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('changedSource')+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ })+ it.each([+ ['initial', 'acknowledged'],+ ['retry', 'acknowledged'],+ ['initial', 'lost-response'],+ ['retry', 'still-running'],+ ['initial', 'completed'],+ ['retry', 'save-failed'],+ ] as const)(+ 'handles cancellation during %s final persistence with %s pause outcome',+ async (attempt, outcome) => {+ const f = await fixture()+ let service = f.service+ if (attempt === 'retry') {+ f.loseCreate()+ await expect(+ service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost create response')+ service = await f.recover()+ }+ let resumed = false+ let release = () => {}+ let reached = () => {}+ const held = new Promise<void>((resolve) => {+ release = resolve+ })+ const entered = new Promise<void>((resolve) => {+ reached = resolve+ })+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementation(async (gid) => {+ await resume?.(gid)+ resumed = true+ })+ const pause = vi.mocked(f.adapter.pauseTask).getMockImplementation()+ if (outcome === 'lost-response')+ vi.mocked(f.adapter.pauseTask).mockImplementation(async (gid) => {+ await pause?.(gid)+ throw new Error('Lost pause response')+ })+ else if (outcome === 'still-running')+ vi.mocked(f.adapter.pauseTask).mockImplementation(async () => {})+ f.deps.runExclusivePersistence = async (operation) => {+ if (resumed) {+ reached()+ await held+ if (outcome === 'save-failed') throw new Error('Active save failed')+ }+ return operation()+ }+ const activation = service.activate(f.taskId, async () => f.downloads)+ await entered+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ if (outcome === 'completed') {+ const engine = await f.adapter.getTaskStatus(intent.engineTaskId)+ if (!engine) throw new Error('Missing native task')+ engine.status = TaskStatus.Completed+ }+ service.cancel(f.taskId)+ release()+ await expect(activation).rejects.toThrow(+ outcome === 'still-running'+ ? 'activationUncertain'+ : 'httpVerificationCancelled'+ )+ expect(f.adapter.pauseTask).toHaveBeenCalledTimes(+ outcome === 'completed' ? 0 : 1+ )+ expect((await f.adapter.getTaskStatus(intent.engineTaskId))?.status).toBe(+ outcome === 'still-running'+ ? TaskStatus.Downloading+ : outcome === 'completed'+ ? TaskStatus.Completed+ : TaskStatus.Paused+ )+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ }+ )+ it('does not accept uncertain progress until the native owner is confirmed paused', async () => {+ const f = await fixture()+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ vi.mocked(f.adapter.pauseTask).mockImplementation(async () => {})+ const recovered = await f.recover()+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ await expect(+ recovered.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('activationUncertain')+ expect(f.adapter.inspectLegacyCheckpoint).toHaveBeenCalledTimes(1)+ })+ it.each(['missing-owner', 'different-owner', 'changed-backup'] as const)(+ 'does not recreate or resume an uncertain first unpause with %s',+ async (invalid) => {+ const f = await fixture()+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ if (invalid === 'missing-owner') f.disappear()+ else if (invalid === 'different-owner') f.badBinding()+ else {+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ await writeFile(intent.controlBackupPath, 'changed backup')+ }+ const recovered = await f.recover()+ await expect(+ recovered.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow(+ invalid === 'changed-backup' ? 'changedSource' : 'activationUncertain'+ )+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ }+ )+ it.each(['retained-range', 'unfinished-gap'] as const)(+ 'checks an uncertain sparse checkpoint after a %s edit',+ async (changed) => {+ const f = await fixture()+ const ranges = [+ { offset: 0, length: 16 },+ { offset: 1024, length: 16 },+ ]+ const inspect = vi+ .mocked(f.adapter.inspectLegacyCheckpoint!)+ .getMockImplementation()+ vi.mocked(f.adapter.inspectLegacyCheckpoint!).mockImplementation(+ async (bytes) => ({+ ...(await inspect!(bytes)),+ ranges,+ completedBytes: 32,+ })+ )+ f.verifier.verifyLegacyContent.mockImplementation(async (input) => {+ for (const range of input.ranges)+ expect(+ Buffer.from(await input.read(range.offset, range.length))+ ).toEqual(+ f.payload.subarray(range.offset, range.offset + range.length)+ )+ return {+ validator: {+ kind: 'strong-etag',+ value: '"fixture"',+ contentLength: LEGACY_HTTP_TOTAL,+ capturedAt: 1,+ },+ requestHeaders: {+ 'If-Match': '"fixture"',+ 'Accept-Encoding': 'identity',+ },+ }+ })+ const resume = vi.mocked(f.adapter.resumeTask).getMockImplementation()+ vi.mocked(f.adapter.resumeTask).mockImplementationOnce(async (gid) => {+ await resume?.(gid)+ const bytes = Buffer.from(f.payload)+ bytes[changed === 'retained-range' ? 1039 : 1000] ^= 255+ await writeFile(f.target, bytes)+ throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ expect(intent.retainedContentDigest).toBe(+ createHash('sha256')+ .update(f.payload.subarray(0, 16))+ .update(f.payload.subarray(1024, 1040))+ .digest('hex')+ )+ const recovered = await f.recover()+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ changed === 'unfinished-gap'+ )+ if (changed === 'retained-range')+ await expect(+ recovered.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('changedSource')+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).toHaveBeenCalledTimes(1)+ }+ )+ it('never blindly retries an uncertain create when the engine GID disappeared', async () => {+ const f = await fixture()+ f.loseCreate()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow()+ f.disappear()+ const service = await f.recover()+ await expect(+ service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('activationUncertain')+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(+ isLegacyImportInactive(f.taskManager.getById(f.taskId) as DownloadTask)+ ).toBe(true)+ })+ it('refuses ambient engine headers before verification or any native mutation', async () => {+ const f = await fixture()+ vi.mocked(f.adapter.supportsLegacyHttpActivation!).mockResolvedValue(false)+ expect(await f.service.availability(f.taskId)).toMatchObject({+ available: false,+ reason: 'legacyImport.errors.httpRequestUnsupported',+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('httpRequestUnsupported')+ expect(f.verifier.verifyLegacyContent).not.toHaveBeenCalled()+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ expect(f.adapter.createDownload).not.toHaveBeenCalled()+ })+ it.each(['missing', 'malformed'] as const)(+ 'continues startup recovery past a %s migration marker',+ async (kind) => {+ const f = await fixture()+ f.loseCreate()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost create response')+ const valid = f.db.getTask(f.taskId)+ if (!valid) throw new Error('Missing fixture row')+ const corrupt = structuredClone(valid)+ corrupt.task.motrixId = 'corrupt'+ corrupt.task.finalName = 'other.bin'+ corrupt.task.finalPath = path.join(f.downloads, 'other.bin')+ corrupt.instances[0].motrixId = 'corrupt'+ corrupt.instances[0].diskPath = corrupt.task.finalPath+ if (kind === 'missing') delete corrupt.instances[0].payload.legacyImport+ else+ corrupt.instances[0].payload.legacyImport = {+ version: 999,+ activation: 'active',+ }+ f.rows.clear()+ f.rows.set('corrupt', corrupt)+ f.rows.set(f.taskId, valid)+ await expect(f.recover()).resolves.toBeInstanceOf(+ LegacyHttpActivationService+ )+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'bound' })+ expect(f.db.getTask('corrupt')).toEqual(corrupt)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ }+ )+ it.each(['create-uncertain', 'bound'] as const)(+ 'quarantines in-place edits before first unpause from %s',+ async (stage) => {+ const f = await fixture()+ f.loseCreate()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost create response')+ if (stage === 'bound') await f.recover()+ const changed = Buffer.from(f.payload)+ changed[0] ^= 255+ await writeFile(f.target, changed)+ const service = await f.recover()+ expect(+ isLegacyImportInactive(f.taskManager.getById(f.taskId) as DownloadTask)+ ).toBe(true)+ await expect(+ service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('changedSource')+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ }+ )+ it('retains started state so legitimate continued bytes do not invalidate later recovery', async () => {+ const f = await fixture()+ await f.service.activate(f.taskId, async () => f.downloads)+ await writeFile(f.target, Buffer.alloc(LEGACY_HTTP_TOTAL, 1))+ const service = await f.recover()+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'active' })+ vi.mocked(f.adapter.resumeTask).mockImplementation(async () => {})+ await expect(+ service.activate(f.taskId, async () => f.downloads)+ ).resolves.toBe(true)+ expect(f.verifier.verifyLegacyContent).toHaveBeenCalledTimes(1)+ expect(f.adapter.createDownload).toHaveBeenCalledTimes(1)+ })+ it('requires a live binding proof before enabling ordinary task actions', async () => {+ const f = await fixture()+ f.badBinding()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('activationUncertain')+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(+ isLegacyImportInactive(f.taskManager.getById(f.taskId) as DownloadTask)+ ).toBe(true)+ })+ it('still requires the full request proof before the first unpause', async () => {+ const f = await fixture()+ vi.mocked(f.adapter.verifyLegacyHttpBinding!).mockImplementation(+ async (input) => !input.request+ )+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('activationUncertain')+ expect(f.adapter.verifyLegacyHttpBinding).toHaveBeenCalledWith(+ expect.objectContaining({ request: expect.any(Object) })+ )+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ })+ it('rejects unsupported request dependencies before any network or import', async () => {+ const f = await fixture({+ requestLines: ' load-cookies=/tmp/private-cookies\n',+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('httpRequestUnsupported')+ expect(f.verifier.verifyLegacyContent).not.toHaveBeenCalled()+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ })+ it.each(['symlink', 'hardlink'] as const)(+ 'refuses a %s payload',+ async (kind) => {+ const f = await fixture()+ await rename(f.target, `${f.target}.old`)+ await (kind === 'symlink' ? symlink : link)(`${f.target}.old`, f.target)+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow(kind === 'symlink' ? 'unsafePath' : 'payloadUnsafe')+ expect(f.verifier.verifyLegacyContent).not.toHaveBeenCalled()+ }+ )+ it('requires the original directory and available payload/control', async () => {+ const f = await fixture()+ expect(await f.service.activate(f.taskId, async () => null)).toBe(false)+ await expect(+ f.service.activate(f.taskId, async () => f.root)+ ).rejects.toThrow('originalDirectoryRequired')+ await rm(`${f.target}.aria2`)+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('controlRequired')+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ })+ it('cancels verification without importing and admits a later explicit retry', async () => {+ const f = await fixture()+ let reached: () => void = () => {}+ const started = new Promise<void>((resolve) => {+ reached = resolve+ })+ f.verifier.verifyLegacyContent.mockImplementationOnce(+ async ({ signal }) => {+ reached()+ await new Promise<void>((resolve) =>+ signal?.addEventListener('abort', () => resolve(), { once: true })+ )+ throw new Error('aborted')+ }+ )+ const activation = f.service.activate(f.taskId, async () => f.downloads)+ await started+ f.service.cancel(f.taskId)+ await expect(activation).rejects.toThrow('httpVerificationCancelled')+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ expect(await f.service.activate(f.taskId, async () => f.downloads)).toBe(+ true+ )+ })+ it('cancels the initial directory picker and discards its later result', async () => {+ const f = await fixture()+ let reached: () => void = () => {}+ let choose: (directory: string) => void = () => {}+ const started = new Promise<void>((resolve) => {+ reached = resolve+ })+ const activation = f.service.activate(f.taskId, async () => {+ reached()+ return new Promise<string>((resolve) => {+ choose = resolve+ })+ })+ await started+ f.service.cancel(f.taskId)+ expect(await activation).toBe(false)+ choose(f.downloads)+ await Promise.resolve()+ expect(f.verifier.verifyLegacyContent).not.toHaveBeenCalled()+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ expect(f.adapter.createDownload).not.toHaveBeenCalled()+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toBeUndefined()+ })+ it('drains an open picker without leaving shutdown waiting for user input', async () => {+ const f = await fixture()+ let reached: () => void = () => {}+ const started = new Promise<void>((resolve) => {+ reached = resolve+ })+ const activation = f.service.activate(f.taskId, async () => {+ reached()+ return new Promise<string>(() => {})+ })+ await started+ await f.service.drain()+ expect(await activation).toBe(false)+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ })+})diff --git a/src/core/legacy-import/http-activation-service.ts b/src/core/legacy-import/http-activation-service.tsnew file mode 100644index 00000000..aa97d9b5--- /dev/null+++ b/src/core/legacy-import/http-activation-service.ts@@ -0,0 +1,1026 @@+import { createHash, randomUUID } from 'node:crypto'+import { type BigIntStats, constants } from 'node:fs'+import { lstat, mkdir, open, realpath } from 'node:fs/promises'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { newEngineTaskId } from '@core/lib/ids'+import type {+ MotrixDatabase,+ TaskWithInstances,+} from '@core/session/motrix-database'+import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'+import { outputPathIdentity } from '@core/task/output-path-identity'+import type { TaskManager } from '@core/task/task-manager'+import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'+import { AppError, ErrorCode } from '@shared/errors'+import { legacyCheckpointInspectionSchema } from '@shared/schemas/legacy-checkpoint'+import {+ type LegacyHttpActivation,+ legacyHttpActivationSchema,+} from '@shared/schemas/legacy-http-activation'+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'+import { TaskStatus, TaskType } from '@shared/types/task'+import {+ type LegacyHttpRequestContext,+ resolveLegacyHttpRequestContext,+} from './http-request-context'+import { authorizeLegacySource, readLegacyFile } from './source-scanner'++export interface LegacyHttpActivationDeps {+ db: MotrixDatabase+ taskManager: TaskManager+ adapter: EngineAdapter+ backupRoot: string+ isProcessRunning: (pid: number) => boolean | Promise<boolean>+ publishTasks: () => void+ runTaskMutation: <T>(+ taskIds: readonly string[],+ operation: () => Promise<T>+ ) => Promise<T>+ runExclusivePersistence: <T>(operation: () => T | Promise<T>) => Promise<T>+ verifier?: Pick<DirectResourceValidatorService, 'verifyLegacyContent'>+}+const sha256 = (bytes: Uint8Array | string) =>+ createHash('sha256').update(bytes).digest('hex')+const failure = (key: string) =>+ new AppError(ErrorCode.InvalidSelection, `legacyImport.errors.${key}`)+const identity = (stat: BigIntStats) => ({+ device: String(stat.dev),+ inode: String(stat.ino),+ size: String(stat.size),+ mtimeNs: String(stat.mtimeNs),+ ctimeNs: String(stat.ctimeNs),+})+const sameIdentity = (+ left: ReturnType<typeof identity>,+ right: ReturnType<typeof identity>+) =>+ Object.keys(left).every(+ (key) => left[key as keyof typeof left] === right[key as keyof typeof right]+ )++/** In-place HTTP authorization binds every retained byte before native import. */+export class LegacyHttpActivationService {+ private admission: Promise<unknown> | null = null+ private stopping = false+ private currentTaskId: string | null = null+ private controller: AbortController | null = null+ private cancelPicker: (() => void) | null = null+ private readonly verifier: Pick<+ DirectResourceValidatorService,+ 'verifyLegacyContent'+ >+ constructor(private readonly deps: LegacyHttpActivationDeps) {+ this.verifier =+ deps.verifier ?? new DirectResourceValidatorService(undefined, 30_000)+ }++ async availability(taskId: string) {+ const pair = this.deps.db.getTask(taskId)+ const marker = legacyTaskMetadataSchema.safeParse(+ pair?.instances[0]?.payload.legacyImport+ )+ let reason: string | null = null+ if (+ !pair ||+ !marker.success ||+ pair.task.taskType !== TaskType.Http ||+ pair.instances.length !== 1+ )+ reason = 'activationSourceMissing'+ else if (pair.instances[0].uris.length !== 1) reason = 'mirrorsUnsupported'+ else if (!marker.data.origin) reason = 'activationSourceMissing'+ else if (+ !this.deps.adapter.verifyLegacyHttpBinding ||+ !(await this.deps.adapter.supportsLegacyCheckpointImport?.())+ )+ reason = 'checkpointUnavailable'+ else if (!(await this.deps.adapter.supportsLegacyHttpActivation?.()))+ reason = 'httpRequestUnsupported'+ return {+ available: reason === null,+ reason: reason ? `legacyImport.errors.${reason}` : null,+ directory: pair?.task.saveDir ?? '',+ }+ }++ activate(+ taskId: string,+ chooseDirectory: (directory: string) => Promise<string | null>+ ): Promise<boolean> {+ if (this.stopping || this.admission) return Promise.reject(failure('busy'))+ this.currentTaskId = taskId+ const controller = new AbortController()+ this.controller = controller+ const operation = this.deps.runTaskMutation([taskId], async () => {+ const pair = this.requireTask(taskId)+ const previous = pair.instances[0].payload.legacyHttpActivation+ if (previous !== undefined) {+ await this.reconcile(pair, true, controller.signal)+ return true+ }+ const available = await this.availability(taskId)+ if (!available.available)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ available.reason ?? 'legacyImport.errors.failed'+ )+ if (this.stopping || controller.signal.aborted) return false+ const picked = await Promise.race([+ chooseDirectory(available.directory),+ new Promise<null>((resolve) => {+ this.cancelPicker = () => resolve(null)+ }),+ ])+ this.cancelPicker = null+ if (!picked || this.stopping || controller.signal.aborted) return false+ if (JSON.stringify(this.requireTask(taskId)) !== JSON.stringify(pair))+ throw failure('changedSource')+ const prepared = await this.prepare(pair, picked, controller.signal)+ this.checkCancelled(controller.signal)+ this.deps.taskManager.reserveEngineTaskId(prepared.intent.engineTaskId)+ await this.persist(pair, prepared.intent, false)+ await this.reconcile(+ this.requireTask(taskId),+ true,+ controller.signal,+ prepared.context+ )+ return true+ })+ this.admission = operation+ void operation+ .finally(() => {+ this.admission = null+ this.cancelPicker = null+ this.currentTaskId = null+ this.controller = null+ })+ .catch(() => {})+ return operation+ }++ cancel(taskId: string): void {+ if (this.currentTaskId !== taskId) return+ this.controller?.abort()+ this.cancelPicker?.()+ }++ /** Passive startup recovery never imports, adds, verifies remotely, or unpauses. */+ async recover(): Promise<void> {+ for (const pair of this.deps.db.getAllTasks()) {+ if (+ !Object.hasOwn(+ pair.instances[0]?.payload ?? {},+ 'legacyHttpActivation'+ ) ||+ pair.task.aggStatus === TaskStatus.Completed ||+ pair.task.taskType !== TaskType.Http ||+ pair.instances.length !== 1 ||+ !legacyTaskMetadataSchema.safeParse(+ pair.instances[0]?.payload.legacyImport+ ).success+ )+ continue+ try {+ await this.deps.runTaskMutation([pair.task.motrixId], () =>+ this.reconcile(pair, false)+ )+ } catch {+ const intent = legacyHttpActivationSchema.safeParse(+ pair.instances[0].payload.legacyHttpActivation+ )+ if (+ intent.success &&+ legacyTaskMetadataSchema.safeParse(+ pair.instances[0]?.payload.legacyImport+ ).success+ )+ await this.persist(pair, intent.data, false)+ }+ }+ }++ async drain(): Promise<void> {+ this.stopping = true+ this.controller?.abort()+ this.cancelPicker?.()+ await this.admission?.catch(() => {})+ }++ private async requireCapability(): Promise<void> {+ if (+ !this.deps.adapter.verifyLegacyHttpBinding ||+ !(await this.deps.adapter.supportsLegacyCheckpointImport?.())+ )+ throw failure('checkpointUnavailable')+ if (!(await this.deps.adapter.supportsLegacyHttpActivation?.()))+ throw failure('httpRequestUnsupported')+ }++ private checkCancelled(signal?: AbortSignal): void {+ if (this.stopping || signal?.aborted)+ throw failure('httpVerificationCancelled')+ }++ private async checkCancelledAfterResume(+ engineTaskId: string,+ signal?: AbortSignal+ ): Promise<void> {+ if (!signal?.aborted && !this.stopping) return+ let stopped = await this.deps.adapter.getTaskStatus(engineTaskId)+ const isStopped = () =>+ stopped?.engineTaskId === engineTaskId &&+ [TaskStatus.Paused, TaskStatus.Completed, TaskStatus.Error].includes(+ stopped.status+ )+ if (!isStopped() && stopped?.engineTaskId === engineTaskId) {+ // A lost pause response is safe only when a later status proves that+ // the intended task is paused or has already finished.+ await this.deps.adapter.pauseTask(engineTaskId).catch(() => {})+ stopped = await this.deps.adapter.getTaskStatus(engineTaskId)+ }+ if (!isStopped()) throw failure('activationUncertain')+ this.checkCancelled(signal)+ }++ private requireTask(taskId: string): TaskWithInstances {+ const pair = this.deps.db.getTask(taskId)+ if (+ pair?.instances.length !== 1 ||+ pair.task.taskType !== TaskType.Http ||+ !legacyTaskMetadataSchema.safeParse(+ pair.instances[0].payload.legacyImport+ ).success+ )+ throw failure('activationSourceMissing')+ if (pair.instances[0].uris.length !== 1) throw failure('mirrorsUnsupported')+ return pair+ }++ private async sourceContext(+ pair: TaskWithInstances+ ): Promise<LegacyHttpRequestContext> {+ const marker = legacyTaskMetadataSchema.parse(+ pair.instances[0].payload.legacyImport+ )+ const origin = marker.origin+ if (!origin) throw failure('activationSourceMissing')+ const source = await authorizeLegacySource(origin.root)+ if (source.identity !== origin.identity || source.root !== origin.root)+ throw failure('changedSource')+ const profiles = new Map<string, Uint8Array>()+ for (const file of origin.profileFiles) {+ if (+ !['download.session', 'system.json', 'user.json'].includes(+ file.relativePath+ ) ||+ profiles.has(file.relativePath)+ )+ throw failure('changedSource')+ const read = await readLegacyFile(source, file.relativePath, true)+ if (!read || read.digest !== file.digest) throw failure('changedSource')+ profiles.set(file.relativePath, read.bytes)+ }+ const session = profiles.get('download.session')+ const system = profiles.get('system.json')+ if (+ profiles.size !== 3 ||+ !session ||+ !system ||+ sha256(session) !== origin.sessionDigest+ )+ throw failure('changedSource')+ const pidFile = await readLegacyFile(source, 'engine.pid', true)+ if (pidFile) {+ const pid = Number(pidFile.bytes.toString('utf8').trim())+ if (+ Number.isSafeInteger(pid) &&+ pid > 0 &&+ (await this.deps.isProcessRunning(pid))+ )+ throw failure('running')+ }+ return resolveLegacyHttpRequestContext({+ session,+ system,+ itemKey: marker.itemKey,+ uris: pair.instances[0].uris,+ targetPath: pair.task.finalPath,+ })+ }++ private async prepare(+ pair: TaskWithInstances,+ picked: string,+ signal: AbortSignal+ ) {+ const saveDir = await realpath(picked)+ if (+ saveDir !== pair.task.saveDir ||+ path.join(saveDir, pair.task.finalName) !== pair.task.finalPath+ )+ throw failure('originalDirectoryRequired')+ const context = await this.sourceContext(pair)+ const root = await this.safeStat(saveDir, true)+ await this.noConflicts(pair)+ const control = await this.originalControl(pair)+ const inspected = await this.deps.adapter.inspectLegacyCheckpoint?.(+ new Uint8Array(control.bytes)+ )+ const parsed = legacyCheckpointInspectionSchema.safeParse(inspected)+ if (!parsed.success) throw failure('checkpointUnavailable')+ const inspection = parsed.data+ if (+ inspection.type !== 'http' ||+ inspection.infoHash !== null ||+ inspection.sourceDigest !== control.digest ||+ inspection.totalBytes <= 0+ )+ throw failure('changedSource')+ const fileIdentity = await this.verifyPayload(+ pair.task.finalPath,+ inspection.totalBytes,+ inspection.ranges,+ context,+ signal+ )+ const validated = fileIdentity.validator+ await this.checkOriginal(+ pair,+ `${root.dev}:${root.ino}`,+ control.digest,+ control.identity,+ fileIdentity.identity+ )+ await this.sourceContext(pair)+ this.checkCancelled(signal)+ const controlBackupPath = await this.saveControl(control.bytes)+ return {+ context,+ intent: legacyHttpActivationSchema.parse({+ version: 1,+ stage: 'import-uncertain',+ token: `http_${randomUUID().replaceAll('-', '_')}`,+ engineTaskId: newEngineTaskId(undefined, 'legacy HTTP activation'),+ targetPath: pair.task.finalPath,+ saveDir,+ rootIdentity: `${root.dev}:${root.ino}`,+ controlBackupPath,+ controlDigest: control.digest,+ controlIdentity: control.identity,+ uriDigest: sha256(context.uri),+ expected: {+ type: 'http',+ totalBytes: inspection.totalBytes,+ pieceBytes: inspection.pieceBytes,+ infoHash: null,+ },+ files: [+ {+ path: pair.task.finalPath,+ offset: 0,+ length: inspection.totalBytes,+ identity: fileIdentity.identity,+ },+ ],+ completedBytes: inspection.completedBytes,+ retainedContentDigest: fileIdentity.retainedContentDigest,+ resourceValidator: validated,+ }),+ }+ }++ private async verifyPayload(+ target: string,+ totalBytes: number,+ ranges: readonly { offset: number; length: number }[],+ context: LegacyHttpRequestContext,+ signal?: AbortSignal+ ) {+ this.checkCancelled(signal)+ await this.requireCapability()+ const before = await this.safeStat(target, false).catch((error) => {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')+ throw failure('payloadMissing')+ throw error+ })+ if (+ before.size > BigInt(totalBytes) ||+ ranges.some((range) => BigInt(range.offset + range.length) > before.size)+ )+ throw failure('changedSource')+ const handle = await open(+ target,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)+ )+ try {+ const opened = await handle.stat({ bigint: true })+ if (+ !sameIdentity(identity(before), identity(opened)) ||+ !opened.isFile() ||+ opened.nlink !== 1n+ )+ throw failure('changedSource')+ const retainedContentHash = createHash('sha256')+ let rangeIndex = 0+ let rangeOffset = ranges[0]?.offset ?? 0+ const result = await this.verifier.verifyLegacyContent({+ uri: context.uri,+ totalBytes,+ ranges,+ options: context,+ signal,+ read: async (offset, length) => {+ this.checkCancelled(signal)+ const range = ranges[rangeIndex]+ // Hash exactly the ordered bytes compared by remote verification.+ if (+ !range ||+ offset !== rangeOffset ||+ length <= 0 ||+ length > range.offset + range.length - offset+ )+ throw failure('changedSource')+ const bytes = Buffer.alloc(length)+ let cursor = 0+ while (cursor < length) {+ const { bytesRead } = await handle.read(+ bytes,+ cursor,+ length - cursor,+ offset + cursor+ )+ if (!bytesRead) throw failure('changedSource')+ cursor += bytesRead+ }+ retainedContentHash.update(bytes)+ rangeOffset += length+ if (rangeOffset === range.offset + range.length) {+ rangeIndex+++ rangeOffset = ranges[rangeIndex]?.offset ?? 0+ }+ return bytes+ },+ })+ this.checkCancelled(signal)+ if (+ rangeIndex !== ranges.length ||+ !sameIdentity(+ identity(opened),+ identity(await handle.stat({ bigint: true }))+ ) ||+ !sameIdentity(+ identity(opened),+ identity(await this.safeStat(target, false))+ )+ )+ throw failure('changedSource')+ return {+ identity: identity(opened),+ retainedContentDigest: retainedContentHash.digest('hex'),+ validator: result.validator,+ }+ } catch (error) {+ this.checkCancelled(signal)+ throw error+ } finally {+ await handle.close()+ }+ }++ private async retainedContentDigest(+ intent: LegacyHttpActivation,+ signal?: AbortSignal+ ): Promise<string> {+ const control = await this.backupFile(intent.controlBackupPath)+ if (control.digest !== intent.controlDigest) throw failure('changedSource')+ const inspection = legacyCheckpointInspectionSchema.parse(+ await this.deps.adapter.inspectLegacyCheckpoint?.(+ new Uint8Array(control.bytes)+ )+ )+ if (+ inspection.sourceDigest !== intent.controlDigest ||+ inspection.type !== 'http' ||+ inspection.totalBytes !== intent.expected.totalBytes ||+ inspection.pieceBytes !== intent.expected.pieceBytes ||+ inspection.completedBytes !== intent.completedBytes+ )+ throw failure('changedSource')+ const root = await this.safeStat(intent.saveDir, true)+ const before = await this.safeStat(intent.targetPath, false)+ if (+ `${root.dev}:${root.ino}` !== intent.rootIdentity ||+ String(before.dev) !== intent.files[0].identity.device ||+ String(before.ino) !== intent.files[0].identity.inode ||+ before.size > BigInt(intent.expected.totalBytes) ||+ inspection.ranges.some(+ (range) => BigInt(range.offset + range.length) > before.size+ )+ )+ throw failure('changedSource')+ const handle = await open(+ intent.targetPath,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)+ )+ try {+ if (+ !sameIdentity(+ identity(before),+ identity(await handle.stat({ bigint: true }))+ )+ )+ throw failure('changedSource')+ const hash = createHash('sha256')+ const buffer = Buffer.alloc(1024 * 1024)+ for (const range of inspection.ranges) {+ let offset = range.offset+ const end = range.offset + range.length+ while (offset < end) {+ this.checkCancelled(signal)+ const { bytesRead } = await handle.read(+ buffer,+ 0,+ Math.min(buffer.length, end - offset),+ offset+ )+ if (!bytesRead) throw failure('changedSource')+ hash.update(buffer.subarray(0, bytesRead))+ offset += bytesRead+ }+ }+ if (+ !sameIdentity(+ identity(before),+ identity(await handle.stat({ bigint: true }))+ ) ||+ !sameIdentity(+ identity(before),+ identity(await this.safeStat(intent.targetPath, false))+ )+ )+ throw failure('changedSource')+ this.checkCancelled(signal)+ return hash.digest('hex')+ } finally {+ await handle.close()+ }+ }++ private async originalControl(pair: TaskWithInstances) {+ const control = await readLegacyFile(+ await authorizeLegacySource(pair.task.saveDir ?? ''),+ `${pair.task.finalName}.aria2`,+ true+ )+ if (!control) throw failure('controlRequired')+ if (!control.identity) throw failure('changedSource')+ return { ...control, identity: control.identity }+ }++ private async checkOriginal(+ pair: TaskWithInstances,+ rootIdentity: string,+ controlDigest: string,+ controlIdentity: string,+ fileIdentity: ReturnType<typeof identity>+ ) {+ const root = await this.safeStat(pair.task.saveDir ?? '', true)+ const control = await this.originalControl(pair)+ if (+ `${root.dev}:${root.ino}` !== rootIdentity ||+ control.digest !== controlDigest ||+ control.identity !== controlIdentity ||+ !sameIdentity(+ identity(await this.safeStat(pair.task.finalPath, false)),+ fileIdentity+ )+ )+ throw failure('changedSource')+ }++ private async safeStat(filename: string, directory: boolean) {+ if (+ !path.isAbsolute(filename) ||+ path.resolve(filename) !== filename ||+ (await realpath(filename)) !== filename+ )+ throw failure('unsafePath')+ let current = path.parse(filename).root+ for (const part of filename.slice(current.length).split(path.sep)) {+ current = path.join(current, part)+ const stat = await lstat(current)+ if (+ stat.isSymbolicLink() ||+ (current !== filename && !stat.isDirectory())+ )+ throw failure('unsafePath')+ }+ const stat = await lstat(filename, { bigint: true })+ if (+ directory+ ? !stat.isDirectory()+ : !stat.isFile() ||+ stat.nlink !== 1n ||+ (process.platform !== 'win32' && (stat.mode & 0o022n) !== 0n) ||+ (process.getuid && BigInt(process.getuid()) !== stat.uid)+ )+ throw failure('payloadUnsafe')+ return stat+ }++ private async noConflicts(pair: TaskWithInstances): Promise<void> {+ const target = outputPathIdentity(pair.task.finalPath)+ const overlaps = (filename: string) => {+ const other = outputPathIdentity(filename)+ return (+ target === other ||+ target.startsWith(`${other}${path.sep}`) ||+ other.startsWith(`${target}${path.sep}`)+ )+ }+ for (const other of this.deps.db.getAllTasks()) {+ if (+ other.task.motrixId !== pair.task.motrixId &&+ [+ other.task.finalPath,+ ...other.instances.map((instance) => instance.diskPath),+ ]+ .filter(Boolean)+ .some(overlaps)+ )+ throw failure('pathConflict')+ }+ const owned = legacyHttpActivationSchema.safeParse(+ pair.instances[0].payload.legacyHttpActivation+ )+ const rows = [+ ...(await this.deps.adapter.listActiveAndWaiting()),+ ...(await this.deps.adapter.listStopped()),+ ]+ for (const row of rows) {+ if (owned.success && row.gid === owned.data.engineTaskId) continue+ const task = await this.deps.adapter.getTaskStatus(row.gid)+ if (task?.diskPath && overlaps(task.diskPath))+ throw failure('pathConflict')+ const files = await this.deps.adapter.getTaskFiles(row.gid)+ if (files.some((file) => file.path && overlaps(file.path)))+ throw failure('pathConflict')+ }+ }++ private async saveControl(bytes: Uint8Array): Promise<string> {+ const source = await authorizeLegacySource(this.deps.backupRoot)+ if (source.root !== path.resolve(this.deps.backupRoot))+ throw failure('unsafeBackup')+ const directory = path.join(source.root, `activation-${randomUUID()}`)+ await mkdir(directory, { mode: 0o700 })+ const filename = path.join(directory, 'control.snapshot')+ const file = await open(+ filename,+ constants.O_WRONLY |+ constants.O_CREAT |+ constants.O_EXCL |+ (constants.O_NOFOLLOW ?? 0),+ 0o600+ )+ try {+ await file.writeFile(bytes)+ await file.sync()+ } finally {+ await file.close()+ }+ if (process.platform !== 'win32') {+ for (const name of [directory, source.root]) {+ const handle = await open(+ name,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)+ )+ try {+ await handle.sync()+ } finally {+ await handle.close()+ }+ }+ }+ return filename+ }++ private async backupFile(filename: string) {+ const source = await authorizeLegacySource(this.deps.backupRoot)+ const relative = path.relative(source.root, filename)+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative))+ throw failure('unsafeBackup')+ const file = await readLegacyFile(source, relative)+ if (!file) throw failure('activationSourceMissing')+ return file+ }++ private async persist(+ pair: TaskWithInstances,+ intent: LegacyHttpActivation,+ bound: boolean+ ): Promise<TaskWithInstances> {+ const next = structuredClone(pair)+ const instance = next.instances[0]+ const marker = legacyTaskMetadataSchema.parse(instance.payload.legacyImport)+ instance.payload = {+ ...instance.payload,+ legacyHttpActivation: structuredClone(intent),+ legacyImport: {+ ...marker,+ activation: bound ? 'active' : 'activating',+ storagePolicy: 'legacy-http-in-place',+ },+ }+ if (bound) {+ instance.gid = intent.engineTaskId+ instance.diskPath = intent.targetPath+ next.task.saveDir = intent.saveDir+ next.task.totalBytes = instance.totalBytes = intent.expected.totalBytes+ next.task.downloadedBytes = instance.downloadedBytes = Math.max(+ instance.downloadedBytes,+ intent.completedBytes+ )+ next.task.sizeWhenDone = intent.expected.totalBytes+ next.task.pieceLength = intent.expected.pieceBytes+ instance.progress = (instance.downloadedBytes / instance.totalBytes) * 100+ }+ next.task.updatedAt = instance.updatedAt = Date.now()+ await this.deps.runExclusivePersistence(() =>+ this.deps.db.saveTaskWithInstances(next)+ )+ this.deps.taskManager.set(+ next.task.motrixId,+ taskRowToDownloadTask(next.task, next.instances)+ )+ this.deps.publishTasks()+ return next+ }++ private async reconcile(+ pair: TaskWithInstances,+ resume: boolean,+ signal?: AbortSignal,+ verifiedContext?: LegacyHttpRequestContext+ ): Promise<void> {+ const intent = legacyHttpActivationSchema.parse(+ pair.instances[0].payload.legacyHttpActivation+ )+ await this.requireCapability()+ if (+ pair.task.finalPath !== intent.targetPath ||+ pair.task.saveDir !== intent.saveDir ||+ pair.instances[0].uris.length !== 1 ||+ sha256(pair.instances[0].uris[0]) !== intent.uriDigest+ )+ throw failure('changedSource')+ const receipt = await this.deps.adapter.reconcileLegacyCheckpoint?.({+ token: intent.token,+ targetPath: intent.targetPath,+ })+ if (!receipt) throw failure('checkpointUnavailable')+ if (+ receipt.status !== 'absent' &&+ (receipt.engineTaskId !== intent.engineTaskId ||+ receipt.sourceDigest !== intent.controlDigest)+ )+ throw failure('changedSource')+ let engine = await this.deps.adapter.getTaskStatus(intent.engineTaskId)+ if (engine) {+ if (+ !['create-uncertain', 'bound', 'resume-uncertain', 'active'].includes(+ intent.stage+ ) ||+ receipt.status === 'absent' ||+ engine.engineTaskId !== intent.engineTaskId+ )+ throw failure('activationUncertain')+ const binding = {+ engineTaskId: intent.engineTaskId,+ saveDir: intent.saveDir,+ targetPath: intent.targetPath,+ uri: pair.instances[0].uris[0],+ expected: intent.expected,+ entityTag: intent.resourceValidator.value,+ fileIdentity: {+ device: intent.files[0].identity.device,+ inode: intent.files[0].identity.inode,+ },+ }+ // Prove ownership and stop an uncertain writer before reading the old+ // profile: missing credentials must not leave that owner downloading.+ if (!(await this.deps.adapter.verifyLegacyHttpBinding?.(binding)))+ throw failure('activationUncertain')+ if (+ (!resume || intent.stage !== 'active' || signal?.aborted) &&+ ![TaskStatus.Paused, TaskStatus.Completed, TaskStatus.Error].includes(+ engine.status+ )+ ) {+ await this.deps.adapter.pauseTask(intent.engineTaskId)+ engine = await this.deps.adapter.getTaskStatus(intent.engineTaskId)+ }+ if (!engine || engine.engineTaskId !== intent.engineTaskId)+ throw failure('activationUncertain')+ if (resume) this.checkCancelled(signal)+ if (+ intent.stage !== 'active' &&+ ![TaskStatus.Paused, TaskStatus.Completed, TaskStatus.Error].includes(+ engine.status+ )+ )+ throw failure('activationUncertain')+ if (intent.stage !== 'active') {+ const request = verifiedContext ?? (await this.sourceContext(pair))+ if (+ !(await this.deps.adapter.verifyLegacyHttpBinding?.({+ ...binding,+ request,+ }))+ )+ throw failure('activationUncertain')+ }+ if (intent.stage === 'resume-uncertain') {+ // The first unpause may have written new bytes before its response or+ // final app save was lost. Only the exact paused native owner may keep+ // that progress, and every previously verified byte must still match.+ if (+ (await this.retainedContentDigest(intent, signal)) !==+ intent.retainedContentDigest+ )+ throw failure('changedSource')+ intent.stage = 'active'+ }+ if (+ intent.stage !== 'active' &&+ !sameIdentity(+ identity(await this.safeStat(intent.targetPath, false)),+ intent.files[0].identity+ )+ )+ throw failure('changedSource')+ await this.noConflicts(pair)+ // Keep evidence that this task has already started: its payload may+ // legitimately have grown since the original verified checkpoint.+ if (intent.stage !== 'active') intent.stage = 'bound'+ pair = await this.persist(pair, intent, true)+ if (resume && engine.status === TaskStatus.Paused) {+ if (intent.stage !== 'active') {+ intent.retainedContentDigest ??= await this.retainedContentDigest(+ intent,+ signal+ )+ intent.stage = 'resume-uncertain'+ pair = await this.persist(pair, intent, true)+ }+ this.checkCancelled(signal)+ try {+ await this.deps.adapter.resumeTask(intent.engineTaskId)+ this.checkCancelled(signal)+ intent.stage = 'active'+ await this.persist(pair, intent, true)+ } catch (error) {+ await this.checkCancelledAfterResume(intent.engineTaskId, signal)+ throw error+ }+ // The RPC and the final save are both cancellation points.+ await this.checkCancelledAfterResume(intent.engineTaskId, signal)+ }+ return+ }+ if (+ receipt.status === 'consumed' ||+ ['create-uncertain', 'bound', 'resume-uncertain', 'active'].includes(+ intent.stage+ )+ )+ throw failure('activationUncertain')+ // Import and add are user-triggered mutations, never startup recovery work.+ if (!resume) {+ await this.persist(pair, intent, false)+ return+ }+ this.checkCancelled(signal)+ let context = verifiedContext ?? (await this.sourceContext(pair))+ await this.noConflicts(pair)+ await this.checkOriginal(+ pair,+ intent.rootIdentity,+ intent.controlDigest,+ intent.controlIdentity,+ intent.files[0].identity+ )+ const control = await this.backupFile(intent.controlBackupPath)+ if (control.digest !== intent.controlDigest) throw failure('changedSource')+ if (!verifiedContext) {+ const inspection = legacyCheckpointInspectionSchema.parse(+ await this.deps.adapter.inspectLegacyCheckpoint?.(+ new Uint8Array(control.bytes)+ )+ )+ if (+ inspection.sourceDigest !== intent.controlDigest ||+ inspection.type !== 'http' ||+ inspection.totalBytes !== intent.expected.totalBytes ||+ inspection.pieceBytes !== intent.expected.pieceBytes ||+ inspection.completedBytes !== intent.completedBytes+ )+ throw failure('changedSource')+ const verified = await this.verifyPayload(+ intent.targetPath,+ intent.expected.totalBytes,+ inspection.ranges,+ context,+ signal+ )+ if (!sameIdentity(verified.identity, intent.files[0].identity))+ throw failure('changedSource')+ intent.resourceValidator = verified.validator+ intent.retainedContentDigest = verified.retainedContentDigest+ pair = await this.persist(pair, intent, false)+ }+ context = await this.sourceContext(pair)+ await this.checkOriginal(+ pair,+ intent.rootIdentity,+ intent.controlDigest,+ intent.controlIdentity,+ intent.files[0].identity+ )+ this.checkCancelled(signal)+ await this.requireCapability()+ if (receipt.status === 'absent') {+ if (intent.stage !== 'import-uncertain')+ throw failure('activationUncertain')+ const imported = await this.deps.adapter.importLegacyCheckpoint?.({+ token: intent.token,+ engineTaskId: intent.engineTaskId,+ targetPath: intent.targetPath,+ controlFile: new Uint8Array(control.bytes),+ sourceDigest: intent.controlDigest,+ expected: intent.expected,+ files: intent.files,+ })+ if (imported?.status !== 'created') throw failure('activationUncertain')+ }+ intent.stage = 'checkpoint'+ pair = await this.persist(pair, intent, false)+ this.checkCancelled(signal)+ context = await this.sourceContext(pair)+ await this.checkOriginal(+ pair,+ intent.rootIdentity,+ intent.controlDigest,+ intent.controlIdentity,+ intent.files[0].identity+ )+ // The durable unknown-create state forbids blind retries after lost responses.+ intent.stage = 'create-uncertain'+ pair = await this.persist(pair, intent, false)+ if (this.stopping || signal?.aborted) {+ // No create was dispatched, so a later explicit retry may safely reverify.+ intent.stage = 'checkpoint'+ await this.persist(pair, intent, false)+ this.checkCancelled(signal)+ }+ if (+ !this.deps.taskManager.isEngineTaskIdRetired(intent.engineTaskId) &&+ !this.deps.taskManager.getByEngineTaskId(intent.engineTaskId)+ )+ this.deps.taskManager.reserveEngineTaskId(intent.engineTaskId)+ const gid = await this.deps.adapter.createDownload({+ uris: [context.uri],+ saveDir: intent.saveDir,+ filename: pair.task.finalName,+ gid: intent.engineTaskId,+ headers: {+ ...context.headers,+ 'If-Match': intent.resourceValidator.value,+ 'Accept-Encoding': 'identity',+ },+ userAgent: context.userAgent,+ proxy: context.proxy,+ noProxy: context.noProxy,+ pause: true,+ resumePolicy: 'checkpoint',+ fileAllocation: 'none',+ totalSizeBytes: intent.expected.totalBytes,+ extraEngineOptions: {+ 'piece-length': String(intent.expected.pieceBytes),+ },+ legacyCheckpointActivation: {+ token: intent.token,+ targetPath: intent.targetPath,+ },+ })+ if (gid !== intent.engineTaskId) throw failure('activationUncertain')+ await this.reconcile(+ pair,+ resume && !signal?.aborted && !this.stopping,+ signal+ )+ this.checkCancelled(signal)+ }+}diff --git a/src/core/legacy-import/http-activation.integration.test.ts b/src/core/legacy-import/http-activation.integration.test.tsnew file mode 100644index 00000000..3fc6f90b--- /dev/null+++ b/src/core/legacy-import/http-activation.integration.test.ts@@ -0,0 +1,713 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import { readFile, rm, writeFile } from 'node:fs/promises'+import { createServer } from 'node:http'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'+import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'+import { type DownloadTask, TaskStatus } from '@shared/types/task'+import { canResume } from '@shared/types/task-actions'+import {+ type Aria2Handle,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import {+ LEGACY_HTTP_COMPLETED,+ LEGACY_HTTP_TOTAL,+ legacyHttpActivationFixture,+} from '@test-utils/legacy-http-service'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LegacyHttpActivationService } from './http-activation-service'+import { assertLegacyTaskNotActivated } from './legacy-task-policy'++const binaryPath = process.env.MOTRIX_LEGACY_CHECKPOINT_ENGINE+const cleanup: Array<() => Promise<void>> = []+afterEach(async () => {+ for (const fn of cleanup.splice(0).reverse()) await fn()+})+async function nativeFixture(+ options: {+ corruptRemote?: boolean+ redirectAfterVerification?: boolean+ changeAfterVerification?: boolean+ holdDownload?: boolean+ } = {}+) {+ const payload = Buffer.alloc(LEGACY_HTTP_TOTAL)+ for (let index = 0; index < payload.length; index++)+ payload[index] = index % 251+ if (options.corruptRemote) payload[LEGACY_HTTP_COMPLETED - 1] ^= 255+ let verified = false+ let redirectedRequests = 0+ let holdDownload = options.holdDownload+ const heldResponses = new Set<() => void>()+ const requests: Array<{+ phase: 'verify' | 'download'+ start: number+ end: number+ ifMatch?: string+ ranged: boolean+ cookie?: string+ encoding?: string+ }> = []+ const server = createServer((request, response) => {+ if (request.url === '/redirected.bin') redirectedRequests+++ const entityTag =+ verified && options.changeAfterVerification+ ? '"changed-fixture"'+ : '"legacy-fixture"'+ const match = /^bytes=(\d+)-(\d*)$/.exec(request.headers.range ?? '')+ const start = match ? Number(match[1]) : 0+ const end = match?.[2] ? Number(match[2]) : LEGACY_HTTP_TOTAL - 1+ requests.push({+ phase: verified ? 'download' : 'verify',+ start,+ end,+ ifMatch: request.headers['if-match'],+ ranged: Boolean(match),+ cookie: request.headers.cookie,+ encoding: request.headers['accept-encoding'],+ })+ if (+ request.headers.cookie !== 'session=fixture-secret' ||+ request.headers['accept-encoding'] !== 'identity' ||+ (request.headers['if-match'] && request.headers['if-match'] !== entityTag)+ ) {+ response.writeHead(412).end()+ return+ }+ if (+ verified &&+ options.redirectAfterVerification &&+ request.url !== '/redirected.bin'+ ) {+ response.writeHead(302, { Location: '/redirected.bin' }).end()+ return+ }+ response.writeHead(match ? 206 : 200, {+ 'Accept-Ranges': 'bytes',+ ETag: entityTag,+ 'Content-Length': end - start + 1,+ ...(match+ ? { 'Content-Range': `bytes ${start}-${end}/${LEGACY_HTTP_TOTAL}` }+ : {}),+ })+ if (verified && match && holdDownload) {+ const split = Math.min(start + 65536, end + 1)+ response.write(payload.subarray(start, split))+ const finish = () => response.end(payload.subarray(split, end + 1))+ heldResponses.add(finish)+ response.once('close', () => heldResponses.delete(finish))+ } else response.end(payload.subarray(start, end + 1))+ })+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', resolve)+ })+ cleanup.push(async () => {+ server.closeAllConnections()+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve()))+ )+ })+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('No HTTP port')+ const verifier = new DirectResourceValidatorService(undefined, 10_000)+ const f = await legacyHttpActivationFixture({+ adapter: {} as EngineAdapter,+ uri: `http://127.0.0.1:${address.port}/partial.bin`,+ requestLines: ' header=Cookie: session=fixture-secret\n',+ verifier: {+ verifyLegacyContent: async (input) => {+ const result = await verifier.verifyLegacyContent(input)+ verified = true+ return result+ },+ },+ })+ cleanup.push(f.dispose)+ let handle: Aria2Handle | undefined+ let wired: Awaited<ReturnType<typeof connectAdapter>> | undefined+ const stop = async () => {+ wired?.disconnect()+ wired = undefined+ await handle?.kill()+ handle = undefined+ }+ cleanup.push(stop)+ const start = async () => {+ handle = await spawnAria2ForTest({+ baseDir: f.root,+ binaryPath,+ extraArgs: [+ '--enable-sqlite3-persistence=true',+ `--sqlite3-db-path=${path.join(f.root, 'engine.db')}`,+ '--force-save=true',+ '--pause=true',+ '--continue=false',+ '--split=1',+ '--max-connection-per-server=1',+ '--file-allocation=none',+ '--max-tries=1',+ '--user-agent=ambient-agent',+ '--http-accept-gzip=true',+ ],+ })+ wired = await connectAdapter(handle)+ f.deps.adapter = wired.adapter+ return wired+ }+ return {+ ...f,+ requests,+ payload,+ start,+ stop,+ crash: async () => {+ wired?.disconnect()+ wired = undefined+ const proc = handle?.proc+ if (proc && proc.exitCode === null && proc.signalCode === null)+ await new Promise<void>((resolve) => {+ proc.once('exit', () => resolve())+ proc.kill('SIGKILL')+ })+ handle = undefined+ },+ releaseDownload: () => {+ holdDownload = false+ for (const finish of heldResponses) finish()+ heldResponses.clear()+ },+ redirectedRequests: () => redirectedRequests,+ }+}+async function progressed(adapter: EngineAdapter, gid: string) {+ const deadline = Date.now() + 10_000+ while (Date.now() < deadline) {+ const task = await adapter.getTaskStatus(gid)+ if (task && task.downloadedBytes > LEGACY_HTTP_COMPLETED) return task+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+ throw new Error('Native first unpause did not retain new bytes')+}+async function completed(adapter: EngineAdapter, gid: string) {+ const deadline = Date.now() + 20_000+ while (Date.now() < deadline) {+ const task = await adapter.getTaskStatus(gid)+ if (+ task?.status === TaskStatus.Completed ||+ task?.status === TaskStatus.Error+ )+ return task+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+ throw new Error('HTTP checkpoint continuation timed out')+}++describe.skipIf(!binaryPath)('real native HTTP migration activation', () => {+ it('compares all old bytes, then downloads only missing ranges into the original file', async () => {+ const f = await nativeFixture()+ const { adapter } = await f.start()+ await f.service.activate(f.taskId, async () => f.downloads)+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ const task = await completed(adapter, intent.engineTaskId)+ expect(+ task.status,+ JSON.stringify({ error: task.errorMessage, requests: f.requests })+ ).toBe(TaskStatus.Completed)+ expect(task.totalBytes).toBe(LEGACY_HTTP_TOTAL)+ const completedBinding = await adapter.verifyLegacyHttpBinding({+ engineTaskId: intent.engineTaskId,+ saveDir: intent.saveDir,+ targetPath: intent.targetPath,+ uri: task.uris[0],+ expected: intent.expected,+ entityTag: intent.resourceValidator.value,+ fileIdentity: {+ device: intent.files[0].identity.device,+ inode: intent.files[0].identity.inode,+ },+ })+ expect(completedBinding).toBe(true)+ expect(+ f.requests+ .filter((request) => request.phase === 'verify')+ .reduce((sum, request) => sum + request.end - request.start + 1, 0)+ ).toBe(LEGACY_HTTP_COMPLETED + 1)+ const downloads = f.requests.filter(+ (request) => request.phase === 'download' && request.ranged+ )+ // Native aria2 may first obtain the length through one GET, then applies+ // the imported checkpoint to its actual transfer ranges.+ expect(+ f.requests.filter(+ (request) => request.phase === 'download' && !request.ranged+ ).length+ ).toBeLessThanOrEqual(1)+ expect(+ f.requests+ .filter((request) => request.phase === 'download')+ .every(+ (request) =>+ request.ifMatch === '"legacy-fixture"' &&+ request.encoding === 'identity' &&+ request.cookie === 'session=fixture-secret'+ )+ ).toBe(true)+ expect(downloads.length).toBeGreaterThan(0)+ expect(+ downloads.every(+ (request) =>+ request.start >= LEGACY_HTTP_COMPLETED &&+ request.ifMatch === '"legacy-fixture"'+ )+ ).toBe(true)+ expect(+ downloads.reduce(+ (sum, request) => sum + request.end - request.start + 1,+ 0+ )+ ).toBe(LEGACY_HTTP_TOTAL - LEGACY_HTTP_COMPLETED)+ expect(+ createHash('sha256')+ .update(await readFile(f.target))+ .digest('hex')+ ).toBe(createHash('sha256').update(f.payload).digest('hex'))+ expect(await readFile(`${f.target}.aria2`)).toEqual(f.control)+ expect(+ await adapter.reconcileLegacyCheckpoint?.({+ token: intent.token,+ targetPath: f.target,+ })+ ).toMatchObject({ status: 'consumed' })+ expect(JSON.stringify(f.db.getTask(f.taskId))).not.toContain(+ 'fixture-secret'+ )+ }, 30_000)++ it('recovers a lost create response across native restart without automatic network activity', async () => {+ const f = await nativeFixture()+ let wired = await f.start()+ const create = wired.adapter.createDownload.bind(wired.adapter)+ wired.adapter.createDownload = async (input) => {+ await create(input)+ throw new Error('Lost create response')+ }+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost create response')+ const before = f.requests.length+ await wired.rpc.saveSession()+ await f.stop()+ wired = await f.start()+ const recovered = new LegacyHttpActivationService(f.deps)+ await recovered.recover()+ expect(f.requests).toHaveLength(before)+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ expect(intent.stage).toBe('bound')+ const boundTask = f.taskManager.getById(f.taskId) as DownloadTask+ expect(canResume(boundTask)).toBe(false)+ expect(() => assertLegacyTaskNotActivated(boundTask)).toThrow(+ 'legacyImport.activationRequired'+ )+ expect(+ (await wired.adapter.getTaskStatus(intent.engineTaskId))?.status+ ).toBe(TaskStatus.Paused)+ await recovered.activate(f.taskId, async () => f.downloads)+ expect((await completed(wired.adapter, intent.engineTaskId)).status).toBe(+ TaskStatus.Completed+ )+ expect(+ f.requests+ .filter((request) => request.phase === 'download' && request.ranged)+ .every((request) => request.start >= LEGACY_HTTP_COMPLETED)+ ).toBe(true)+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ }, 30_000)++ it.each(['response', 'persist'] as const)(+ 'recovers native completion after losing the first-resume %s',+ async (lost) => {+ const f = await nativeFixture()+ const { adapter } = await f.start()+ const resume = adapter.resumeTask.bind(adapter)+ const resumeSpy = vi+ .spyOn(adapter, 'resumeTask')+ .mockImplementation(async (gid) => {+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'resume-uncertain' })+ await resume(gid)+ expect((await completed(adapter, gid)).status).toBe(+ TaskStatus.Completed+ )+ if (lost === 'response') throw new Error('Lost resume response')+ })+ const save = f.db.saveTaskWithInstances.bind(f.db)+ const saveSpy = vi+ .spyOn(f.db, 'saveTaskWithInstances')+ .mockImplementation((pair) => {+ if (+ lost === 'persist' &&+ (+ pair.instances[0].payload.legacyHttpActivation as {+ stage: string+ }+ ).stage === 'active'+ )+ throw new Error('Lost active save')+ return save(pair)+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow(+ lost === 'response' ? 'Lost resume response' : 'Lost active save'+ )+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'resume-uncertain' })+ saveSpy.mockImplementation(save)+ const requests = f.requests.length+ const recovered = new LegacyHttpActivationService(f.deps)+ await recovered.recover()+ expect(f.requests).toHaveLength(requests)+ expect(resumeSpy).toHaveBeenCalledTimes(1)+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toMatchObject({ stage: 'active' })+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ },+ 30_000+ )++ it('recovers persisted native progress after a crash with an uncertain first unpause', async () => {+ const f = await nativeFixture({ holdDownload: true })+ let wired = await f.start()+ const resume = wired.adapter.resumeTask.bind(wired.adapter)+ wired.adapter.resumeTask = async (gid) => {+ await resume(gid)+ await progressed(wired.adapter, gid)+ throw new Error('Lost resume response')+ }+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ await wired.rpc.saveSession()+ await f.crash()+ const requests = f.requests.length+ wired = await f.start()+ const recovered = new LegacyHttpActivationService(f.deps)+ await recovered.recover()+ expect(f.requests).toHaveLength(requests)+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ expect(intent.stage).toBe('active')+ expect(+ (await wired.adapter.getTaskStatus(intent.engineTaskId))?.status+ ).toBe(TaskStatus.Paused)+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ true+ )+ f.releaseDownload()+ await wired.adapter.resumeTask(intent.engineTaskId)+ expect((await completed(wired.adapter, intent.engineTaskId)).status).toBe(+ TaskStatus.Completed+ )+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ expect(+ f.requests+ .filter((request) => request.phase === 'verify')+ .reduce((sum, request) => sum + request.end - request.start + 1, 0)+ ).toBe(LEGACY_HTTP_COMPLETED + 1)+ expect(+ f.requests+ .filter((request) => request.phase === 'download' && request.ranged)+ .every((request) => request.start >= LEGACY_HTTP_COMPLETED)+ ).toBe(true)+ }, 30_000)++ it.each([false, true])(+ 'keeps native progress paused after first-unpause cancellation with a lost response: %s',+ async (lostResponse) => {+ const f = await nativeFixture({ holdDownload: true })+ const { adapter } = await f.start()+ const resume = adapter.resumeTask.bind(adapter)+ const resumeSpy = vi+ .spyOn(adapter, 'resumeTask')+ .mockImplementationOnce(async (gid) => {+ await resume(gid)+ await progressed(adapter, gid)+ f.service.cancel(f.taskId)+ if (lostResponse) throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('httpVerificationCancelled')+ const uncertain = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ expect(uncertain.stage).toBe('resume-uncertain')+ expect(+ (await adapter.getTaskStatus(uncertain.engineTaskId))?.status+ ).toBe(TaskStatus.Paused)+ const requests = f.requests.length+ const recovered = new LegacyHttpActivationService(f.deps)+ await recovered.recover()+ expect(f.requests).toHaveLength(requests)+ expect(resumeSpy).toHaveBeenCalledTimes(1)+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ true+ )+ f.releaseDownload()+ await adapter.resumeTask(uncertain.engineTaskId)+ expect((await completed(adapter, uncertain.engineTaskId)).status).toBe(+ TaskStatus.Completed+ )+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ },+ 30_000+ )++ it('quarantines same-inode edits to old bytes despite a valid native binding and real progress', async () => {+ const f = await nativeFixture({ holdDownload: true })+ const { adapter } = await f.start()+ const resume = adapter.resumeTask.bind(adapter)+ const resumeSpy = vi+ .spyOn(adapter, 'resumeTask')+ .mockImplementationOnce(async (gid) => {+ await resume(gid)+ await progressed(adapter, gid)+ await adapter.pauseTask(gid)+ throw new Error('Lost resume response')+ })+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ const bytes = await readFile(f.target)+ bytes[LEGACY_HTTP_COMPLETED - 1] ^= 255+ await writeFile(f.target, bytes)+ expect(+ await adapter.verifyLegacyHttpBinding?.({+ engineTaskId: intent.engineTaskId,+ saveDir: intent.saveDir,+ targetPath: intent.targetPath,+ uri: f.db.getTask(f.taskId)!.instances[0].uris[0],+ expected: intent.expected,+ entityTag: intent.resourceValidator.value,+ fileIdentity: intent.files[0].identity,+ })+ ).toBe(true)+ const requests = f.requests.length+ const recovered = new LegacyHttpActivationService(f.deps)+ await recovered.recover()+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ await expect(+ recovered.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('changedSource')+ expect(f.requests).toHaveLength(requests)+ expect(resumeSpy).toHaveBeenCalledTimes(1)+ expect(await readFile(f.target)).toEqual(bytes)+ }, 30_000)++ it.each(['initial', 'retry-lost-pause-response'] as const)(+ 'pauses the native owner when cancelling during %s final persistence',+ async (attempt) => {+ const f = await nativeFixture({ holdDownload: true })+ const { adapter } = await f.start()+ let service = f.service+ if (attempt === 'retry-lost-pause-response') {+ const create = adapter.createDownload.bind(adapter)+ vi.spyOn(adapter, 'createDownload').mockImplementationOnce(+ async (input) => {+ await create(input)+ throw new Error('Lost create response')+ }+ )+ await expect(+ service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost create response')+ service = new LegacyHttpActivationService(f.deps)+ await service.recover()+ const pause = adapter.pauseTask.bind(adapter)+ vi.spyOn(adapter, 'pauseTask').mockImplementationOnce(async (gid) => {+ await pause(gid)+ throw new Error('Lost pause response')+ })+ }+ let resumed = false+ let reached = () => {}+ let release = () => {}+ const entered = new Promise<void>((resolve) => {+ reached = resolve+ })+ const held = new Promise<void>((resolve) => {+ release = resolve+ })+ const resume = adapter.resumeTask.bind(adapter)+ vi.spyOn(adapter, 'resumeTask').mockImplementationOnce(async (gid) => {+ await resume(gid)+ await progressed(adapter, gid)+ resumed = true+ })+ f.deps.runExclusivePersistence = async (operation) => {+ if (resumed) {+ reached()+ await held+ }+ return operation()+ }+ const activation = service.activate(f.taskId, async () => f.downloads)+ await entered+ service.cancel(f.taskId)+ release()+ await expect(activation).rejects.toThrow('httpVerificationCancelled')+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ expect(intent.stage).toBe('active')+ expect((await adapter.getTaskStatus(intent.engineTaskId))?.status).toBe(+ TaskStatus.Paused+ )+ expect(+ (await readFile(f.target)).subarray(0, LEGACY_HTTP_COMPLETED)+ ).toEqual(f.payload.subarray(0, LEGACY_HTTP_COMPLETED))+ f.releaseDownload()+ await adapter.resumeTask(intent.engineTaskId)+ expect((await completed(adapter, intent.engineTaskId)).status).toBe(+ TaskStatus.Completed+ )+ expect((await readFile(f.target)).equals(f.payload)).toBe(true)+ },+ 30_000+ )++ it.each(['changed-profile', 'missing-profile', 'wrong-binding'] as const)(+ 'stops only the proven uncertain owner before an explicit retry with %s',+ async (invalid) => {+ const f = await nativeFixture({ holdDownload: true })+ const { adapter } = await f.start()+ const resume = adapter.resumeTask.bind(adapter)+ const resumeSpy = vi+ .spyOn(adapter, 'resumeTask')+ .mockImplementationOnce(async (gid) => {+ await resume(gid)+ await progressed(adapter, gid)+ throw new Error('Lost resume response')+ })+ const pauseSpy = vi.spyOn(adapter, 'pauseTask')+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost resume response')+ const pair = f.db.getTask(f.taskId)+ if (!pair) throw new Error('Missing migrated task')+ const intent = legacyHttpActivationSchema.parse(+ pair.instances[0].payload.legacyHttpActivation+ )+ expect(intent.stage).toBe('resume-uncertain')+ if (invalid === 'missing-profile')+ await rm(path.join(f.profile, 'system.json'))+ else+ await writeFile(+ path.join(f.profile, 'system.json'),+ JSON.stringify({ changed: true })+ )+ if (invalid === 'wrong-binding') {+ pair.instances[0].uris[0] += '?different-source'+ intent.uriDigest = createHash('sha256')+ .update(pair.instances[0].uris[0])+ .digest('hex')+ pair.instances[0].payload.legacyHttpActivation = intent+ f.db.saveTaskWithInstances(pair)+ }+ const requests = f.requests.length+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow(+ invalid === 'wrong-binding' ? 'activationUncertain' : 'changedSource'+ )+ expect(pauseSpy).toHaveBeenCalledTimes(+ invalid === 'wrong-binding' ? 0 : 1+ )+ expect((await adapter.getTaskStatus(intent.engineTaskId))?.status).toBe(+ invalid === 'wrong-binding' ? TaskStatus.Downloading : TaskStatus.Paused+ )+ expect(canResume(f.taskManager.getById(f.taskId) as DownloadTask)).toBe(+ false+ )+ expect(resumeSpy).toHaveBeenCalledTimes(1)+ expect(f.requests).toHaveLength(requests)+ expect(+ (await readFile(f.target)).subarray(0, LEGACY_HTTP_COMPLETED)+ ).toEqual(f.payload.subarray(0, LEGACY_HTTP_COMPLETED))+ },+ 30_000+ )++ it('refuses a redirect introduced after verification without requesting its target or altering old data', async () => {+ const f = await nativeFixture({ redirectAfterVerification: true })+ const { adapter } = await f.start()+ const original = await readFile(f.target)+ await f.service.activate(f.taskId, async () => f.downloads)+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ const task = await completed(adapter, intent.engineTaskId)+ expect(task.status).toBe(TaskStatus.Error)+ expect(f.requests.some((request) => request.phase === 'download')).toBe(+ true+ )+ expect(f.redirectedRequests()).toBe(0)+ expect((await readFile(f.target)).equals(original)).toBe(true)+ expect(await readFile(`${f.target}.aria2`)).toEqual(f.control)+ }, 30_000)++ it('fails a post-verification ETag change with 412 and preserves all old bytes', async () => {+ const f = await nativeFixture({ changeAfterVerification: true })+ const { adapter } = await f.start()+ const original = await readFile(f.target)+ await f.service.activate(f.taskId, async () => f.downloads)+ const intent = legacyHttpActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ )+ const task = await completed(adapter, intent.engineTaskId)+ expect(task.status).toBe(TaskStatus.Error)+ expect(task.errorMessage).toContain('412')+ const downloads = f.requests.filter(+ (request) => request.phase === 'download'+ )+ expect(downloads.length).toBeGreaterThan(0)+ expect(+ downloads.every((request) => request.ifMatch === '"legacy-fixture"')+ ).toBe(true)+ expect((await readFile(f.target)).equals(original)).toBe(true)+ expect(await readFile(`${f.target}.aria2`)).toEqual(f.control)+ }, 30_000)++ it('rejects a mismatch in the last old byte without importing or creating a native task', async () => {+ const f = await nativeFixture({ corruptRemote: true })+ const { adapter } = await f.start()+ const original = await readFile(f.target)+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('httpContentChanged')+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyHttpActivation+ ).toBeUndefined()+ expect(await adapter.listActiveAndWaiting()).toEqual([])+ expect((await readFile(f.target)).equals(original)).toBe(true)+ expect(await readFile(`${f.target}.aria2`)).toEqual(f.control)+ }, 30_000)+})diff --git a/src/core/legacy-import/http-request-context.test.ts b/src/core/legacy-import/http-request-context.test.tsnew file mode 100644index 00000000..db34173d--- /dev/null+++ b/src/core/legacy-import/http-request-context.test.ts@@ -0,0 +1,185 @@+// @vitest-environment node+import path from 'node:path'+import { extractAria2ProxyCredentials } from '@core/proxy/aria2-proxy-routing'+import { describe, expect, it } from 'vitest'+import { resolveLegacyHttpRequestContext } from './http-request-context'+import { digestBytes, parseLegacySession } from './session-parser'++const directory = path.resolve('/tmp/legacy-http-context')+const uri = 'https://example.com/file.bin'+const target = path.join(directory, 'file.bin')+function resolve(options = '', system: Record<string, unknown> = {}) {+ return resolveLegacyHttpRequestContext({+ session: Buffer.from(+ `magnet:?xt=urn:btih:1111111111111111111111111111111111111111\n gid=1111222233334444\n${uri}\n gid=0123456789abcdef\n dir=${directory}\n out=file.bin\n no-netrc=true\n${options}`+ ),+ system: Buffer.from(JSON.stringify({ dir: directory, ...system })),+ itemKey: 'gid:0123456789abcdef',+ uris: [uri],+ targetPath: target,+ })+}+describe('legacy HTTP request context', () => {+ it.each([true, false])(+ 'ignores unrelated malformed HTTP paths when the selected task has GID: %s',+ (hasGid) => {+ const selected = `${uri}\n${hasGid ? ' gid=0123456789abcdef\n' : ''} dir=${directory}\n out=file.bin\n no-netrc=true\n`+ const context = resolveLegacyHttpRequestContext({+ session: Buffer.from(+ `https://example.com/%ZZ\n gid=ffffffffffffffff\nhttps://example.com/%ZZ\n${selected}`+ ),+ system: Buffer.from(JSON.stringify({ dir: directory })),+ uris: [uri],+ targetPath: target,+ itemKey: hasGid+ ? 'gid:0123456789abcdef'+ : `entry:${digestBytes(JSON.stringify(['http', target, [uri]]))}`,+ })+ expect(context.uri).toBe(uri)+ }+ )++ it('restores only verified headers, referer, user agent, basic auth, and the effective proxy', () => {+ const context = resolve(+ ' header=Cookie: session=secret\n referer=https://example.com/list\n http-user=user\n http-passwd=secret\n',+ {+ 'all-proxy': 'http://proxy.example:8080',+ 'all-proxy-user': 'proxy-user',+ 'all-proxy-passwd': 'proxy-secret',+ 'no-proxy': 'localhost',+ 'user-agent': 'Legacy Browser',+ }+ )+ expect(context).toEqual({+ uri,+ headers: {+ cookie: 'session=secret',+ referer: 'https://example.com/list',+ authorization: `Basic ${Buffer.from('user:secret').toString('base64')}`,+ },+ proxy: 'http://proxy-user:[email protected]:8080/',+ noProxy: 'localhost',+ userAgent: 'Legacy Browser',+ })+ })+ it.each([+ ['proxy%40user', 'password%21'],+ ["代理@ user:/?#[]!$&'()*+,;=%", "密碼@ pass:/?#[]!$&'()*+,;=%"],+ ])(+ 'preserves raw dedicated proxy credential bytes: %s',+ (username, password) => {+ const context = resolve('', {+ 'all-proxy': 'http://proxy.example:8080',+ 'all-proxy-user': username,+ 'all-proxy-passwd': password,+ })+ expect(extractAria2ProxyCredentials(context.proxy)).toEqual({+ username,+ password,+ })+ expect(context.headers).toEqual({})+ }+ )+ it.each([+ {+ options: { 'all-proxy-user': 'new%40user' },+ expected: { username: 'new%40user', password: 'uri%21pass' },+ },+ {+ options: { 'all-proxy-passwd': 'new%21pass' },+ expected: { username: 'uri%40user', password: 'new%21pass' },+ },+ {+ options: { 'all-proxy-user': '' },+ expected: { username: '', password: '' },+ },+ {+ options: { 'all-proxy-passwd': '' },+ expected: { username: 'uri%40user', password: '' },+ },+ ])(+ 'overrides only defined URI credential fields: $options',+ ({ options, expected }) => {+ const context = resolve('', {+ 'all-proxy': 'http://uri%2540user:uri%[email protected]:8080',+ ...options,+ })+ expect(extractAria2ProxyCredentials(context.proxy)).toEqual(expected)+ }+ )+ it('honors an explicitly empty task password over inherited credentials', () => {+ const context = resolve(' all-proxy-passwd=\n', {+ 'all-proxy': 'http://uri-user:[email protected]:8080',+ 'all-proxy-user': 'global%40user',+ 'all-proxy-passwd': 'global-pass',+ })+ expect(extractAria2ProxyCredentials(context.proxy)).toEqual({+ username: 'global%40user',+ password: '',+ })+ })+ it('keeps reconstructed proxy credentials out of preview data', () => {+ const options =+ ' all-proxy=http://proxy.example:8080\n all-proxy-user=private%40user\n all-proxy-passwd=private%21password\n'+ expect(extractAria2ProxyCredentials(resolve(options).proxy)).toEqual({+ username: 'private%40user',+ password: 'private%21password',+ })+ const preview = JSON.stringify(+ parseLegacySession(Buffer.from(`${uri}\n${options}`))+ )+ expect(preview).not.toContain('private')+ })+ it.each(['private\npassword', 'private\ud800password'])(+ 'rejects invalid credential text without exposing it',+ (password) => {+ expect(() =>+ resolve('', {+ 'all-proxy': 'http://proxy.example:8080',+ 'all-proxy-user': 'private-user',+ 'all-proxy-passwd': password,+ })+ ).toThrow(/^legacyImport\.errors\.httpRequestUnsupported$/)+ }+ )+ it.each([+ ' load-cookies=/secret/cookies.txt\n',+ ' no-netrc=false\n',+ ' header=Authorization: a\n header=authorization: b\n',+ ' header=Proxy-Authorization: private\n',+ ' http-proxy=http://proxy.example:8080\n',+ ' referer=*\n',+ ])('rejects request contexts that cannot be mirrored: %s', (options) => {+ expect(() => resolve(options)).toThrow('httpRequestUnsupported')+ })+ it('leaves range and representation conditions owned by verification', () => {+ expect(+ resolve(+ ' header=Range: bytes=0-9\n header=If-Match: old\n header=Accept-Encoding: gzip\n'+ ).headers+ ).toEqual({})+ })+ it('combines distinct global and task headers as the original engine did', () => {+ expect(+ resolve(' header=Cookie: private\n', { header: ['X-Source: legacy'] })+ .headers+ ).toEqual({ 'x-source': 'legacy', cookie: 'private' })+ })+ it('rejects a conflicting global and per-task header collection', () => {+ expect(() =>+ resolve(' header=Cookie: changed\n', { header: ['Cookie: old'] })+ ).toThrow('httpRequestUnsupported')+ })+ it('uses the migration stable key when the original session has no GID', () => {+ const context = resolveLegacyHttpRequestContext({+ session: Buffer.from(+ `${uri}\n dir=${directory}\n out=file.bin\n no-netrc=true\n`+ ),+ system: Buffer.from(JSON.stringify({ dir: directory })),+ uris: [uri],+ targetPath: target,+ itemKey: `entry:${digestBytes(JSON.stringify(['http', target, [uri]]))}`,+ })+ expect(context.uri).toBe(uri)+ })+})diff --git a/src/core/legacy-import/http-request-context.ts b/src/core/legacy-import/http-request-context.tsnew file mode 100644index 00000000..110d5835--- /dev/null+++ b/src/core/legacy-import/http-request-context.ts@@ -0,0 +1,256 @@+import path from 'node:path'+import { normalizeAria2TaskProxyUrl } from '@core/proxy/aria2-proxy-routing'+import type { DirectResourceRequestOptions } from '@core/task/direct-resource-validator'+import { AppError, ErrorCode } from '@shared/errors'+import {+ digestBytes,+ parseLegacySession,+ safeLegacyOutput,+} from './session-parser'++const failure = () =>+ new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.httpRequestUnsupported'+ )+const changed = () =>+ new AppError(ErrorCode.InvalidSelection, 'legacyImport.errors.changedSource')++export interface LegacyHttpRequestContext extends DirectResourceRequestOptions {+ uri: string+ headers: Record<string, string>+ proxy: string+ noProxy: string+ userAgent: string+}++/** Read only a digest-verified profile. Never return raw engine options for replay. */+export function resolveLegacyHttpRequestContext(input: {+ session: Uint8Array+ system: Uint8Array+ itemKey: string+ uris: string[]+ targetPath: string+}): LegacyHttpRequestContext {+ if (input.uris.length !== 1)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.mirrorsUnsupported'+ )+ let system: Record<string, unknown>+ try {+ system = JSON.parse(+ new TextDecoder('utf-8', { fatal: true }).decode(input.system)+ )+ if (!system || Array.isArray(system) || typeof system !== 'object')+ throw failure()+ } catch {+ throw failure()+ }+ const entries = parseLegacySession(input.session)+ const matches = entries.filter((entry) => {+ if (entry.gid) return entry.itemKey === input.itemKey+ if (+ !input.itemKey.startsWith('entry:') ||+ !/^https?:\/\//i.test(entry.uris[0] ?? '')+ )+ return false+ try {+ const filename =+ entry.options.out ||+ decodeURIComponent(+ new URL(entry.uris[0]).pathname.split('/').at(-1) || 'download'+ )+ const dir = entry.options.dir ?? system.dir+ const target =+ typeof dir === 'string' ? safeLegacyOutput(dir, filename) : null+ return (+ `entry:${digestBytes(JSON.stringify(['http', target, [...entry.uris].sort()]))}` ===+ input.itemKey+ )+ } catch {+ // An unrelated invalid record does not invalidate the selected task.+ return false+ }+ })+ if (matches.length !== 1) throw changed()+ const entry = matches[0]+ if (+ (entry.reason && entry.reason !== 'request-settings-required') ||+ entry.uris.length !== 1 ||+ entry.uris[0] !== input.uris[0] ||+ safeLegacyOutput(+ entry.options.dir ?? String(system.dir),+ entry.options.out ||+ decodeURIComponent(+ new URL(entry.uris[0]).pathname.split('/').at(-1) || 'download'+ )+ ) !== input.targetPath+ )+ throw changed()+ const uri = entry.uris[0]+ const url = new URL(uri)+ if (+ !['http:', 'https:'].includes(url.protocol) ||+ url.username ||+ url.password+ )+ throw failure()++ // Use the parser's exact block digest to retrieve request values without+ // ever adding credentials to its preview/database-facing representation.+ const blocks: string[][] = []+ for (const line of new TextDecoder('utf-8', { fatal: true })+ .decode(input.session)+ .split(/\r?\n/)) {+ if (!line.trim() || line.startsWith('#')) continue+ if (!/^\s/.test(line)) blocks.push([line])+ else blocks.at(-1)?.push(line)+ }+ const block = blocks.find(+ (lines) => digestBytes(lines.join('\n')) === entry.digest+ )+ if (!block) throw changed()+ const task: Record<string, string[]> = Object.create(null)+ for (const line of block.slice(1)) {+ const match = /^\s+([a-z0-9-]+)=(.*)$/.exec(line)+ if (!match) throw failure()+ task[match[1]] ??= []+ task[match[1]].push(match[2])+ }+ const values = (key: string): string[] => {+ const raw = task[key] ?? system[key]+ if (raw === undefined || raw === null) return []+ const list = Array.isArray(raw) ? raw : [raw]+ if (+ list.some(+ (value) =>+ typeof value !== 'string' &&+ typeof value !== 'boolean' &&+ typeof value !== 'number'+ )+ )+ throw failure()+ return list.map(String)+ }+ const value = (key: string, fallback = ''): string => {+ const list = values(key)+ if (list.length > 1) throw failure()+ const result = list[0] ?? fallback+ if (+ [...result].some(+ (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127+ )+ )+ throw failure()+ return result+ }+ if (+ value('load-cookies') ||+ value('netrc-path') ||+ value('no-netrc') === 'false'+ )+ throw failure()+ for (const [key, baseline] of [+ ['http-accept-gzip', 'false'],+ ['http-auth-challenge', 'false'],+ ['http-no-cache', 'false'],+ ['conditional-get', 'false'],+ ['proxy-method', 'get'],+ ])+ if (value(key, baseline) !== baseline) throw failure()++ const headers: Record<string, string> = Object.create(null)+ const putHeader = (name: string, content: string) => {+ const key = name.trim().toLowerCase()+ if (+ !/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(key) ||+ Object.hasOwn(headers, key) ||+ [...content].some(+ (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127+ )+ )+ throw failure()+ if (['range', 'if-range', 'if-match', 'accept-encoding'].includes(key))+ return+ if (+ [+ 'host',+ 'connection',+ 'content-length',+ 'transfer-encoding',+ 'proxy-authorization',+ ].includes(key)+ )+ throw failure()+ headers[key] = content+ }+ const inheritedHeaders =+ system.header === undefined || system.header === null+ ? []+ : Array.isArray(system.header)+ ? system.header+ : [system.header]+ if (inheritedHeaders.some((value) => typeof value !== 'string'))+ throw failure()+ for (const line of [+ ...(inheritedHeaders as string[]),+ ...(task.header ?? []),+ ].filter((part) => part.trim())) {+ const colon = line.indexOf(':')+ if (colon <= 0) throw failure()+ putHeader(line.slice(0, colon), line.slice(colon + 1).trim())+ }+ const referer = value('referer')+ if (referer) {+ if (referer === '*') throw failure()+ putHeader('referer', referer)+ }+ const username = value('http-user')+ const password = value('http-passwd')+ if (username || password) {+ if (!username || username.includes(':')) throw failure()+ putHeader(+ 'authorization',+ `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`+ )+ }+ const userAgent = headers['user-agent'] ?? value('user-agent', 'aria2/1.36.0')+ const proxyFor = (prefix: string) => {+ const raw = value(prefix)+ if (!raw) {+ if (value(`${prefix}-user`) || value(`${prefix}-passwd`)) throw failure()+ return ''+ }+ const proxy = normalizeAria2TaskProxyUrl(raw)+ if (!proxy) throw failure()+ const userKey = `${prefix}-user`+ const passKey = `${prefix}-passwd`+ const user = value(userKey)+ const pass = value(passKey)+ try {+ // Dedicated options are raw values and override each URI field only+ // when defined, including an explicitly empty value.+ if (values(userKey).length) proxy.username = encodeURIComponent(user)+ if (values(passKey).length) proxy.password = encodeURIComponent(pass)+ } catch {+ throw failure()+ }+ // aria2 omits userinfo entirely when the resulting username is empty.+ if (!proxy.username) proxy.password = ''+ return proxy.href+ }+ const allProxy = proxyFor('all-proxy')+ const httpProxy = proxyFor('http-proxy') || allProxy+ const httpsProxy = proxyFor('https-proxy') || allProxy+ // Redirects can change protocol. One explicit route must describe both.+ if (httpProxy !== httpsProxy) throw failure()+ if (path.dirname(input.targetPath) === input.targetPath) throw changed()+ return {+ uri,+ headers,+ userAgent,+ proxy: httpProxy,+ noProxy: value('no-proxy'),+ }+}diff --git a/src/core/legacy-import/import-service-adversarial.test.ts b/src/core/legacy-import/import-service-adversarial.test.tsindex 378e6291..c158e3c0 100644--- a/src/core/legacy-import/import-service-adversarial.test.ts+++ b/src/core/legacy-import/import-service-adversarial.test.ts@@ -301,6 +301,76 @@ describe('legacy import service adversarial acceptance', () => {}})+ it('imports request-dependent HTTP records inactive without persisting request secrets', async () => {+ const f = await fixture()+ const session = [+ 'https://example.test/file-0.zip',+ ' gid=0000000000000001',+ ' out=file-0.zip',+ ' pause=true',+ ' header=Authorization: Bearer LEGACY_AUTH_SECRET',+ ' header=Cookie: session=LEGACY_COOKIE_SECRET',+ '',+ ].join('\n')+ await writeFile(f.sessionPath, session)+ await writeFile(+ path.join(f.sourceRoot, 'system.json'),+ JSON.stringify({+ dir: f.downloads,+ 'all-proxy': 'http://user:[email protected]:8080',+ })+ )+ const preview = await f.service.scan(f.source.sourceHandle)+ expect(preview.items[0]).toMatchObject({+ type: 'http',+ selectable: true,+ reason: 'request-settings-required',+ requestOptions: expect.arrayContaining(['header', 'all-proxy']),+ })+ const run = await f.service.commit({+ previewId: preview.previewId,+ itemIds: [preview.items[0].itemId],+ })+ const report = await completed(f.service, run.runId)+ expect(report.imported).toBe(1)+ const [task] = f.taskManager.getAll()+ expect(task.status).toBe(TaskStatus.Paused)+ expect(task.instances[0].gid).toBeNull()+ expect(task.instances[0].payload.legacyImport).toMatchObject({+ activation: 'inactive',+ storagePolicy: 'legacy-read-only',+ reason: 'request-settings-required',+ requestOptions: expect.arrayContaining(['header', 'all-proxy']),+ })+ const persisted = JSON.stringify({+ tasks: f.db.getAllTasks(),+ report: f.service.getRun(run.runId),+ preview,+ })+ for (const secret of [+ 'LEGACY_AUTH_SECRET',+ 'LEGACY_COOKIE_SECRET',+ 'LEGACY_PROXY_SECRET',+ ])+ expect(persisted).not.toContain(secret)+ expect(await readFile(f.sessionPath, 'utf8')).toBe(session)+ expect(await readFile(path.join(f.downloads, 'file-0.zip'), 'utf8')).toBe(+ 'original payload'+ )+ expect(+ await readFile(+ path.join(f.deps.backupRoot, run.runId, 'download.session'),+ 'utf8'+ )+ ).toBe(session)+ expect(+ (await f.service.scan(f.source.sourceHandle)).items[0]+ ).toMatchObject({+ selectable: false,+ reason: 'already-imported',+ })+ })+it('rejects a stale preview before committing records', async () => {const f = await fixture()await writeFile(diff --git a/src/core/legacy-import/import-service.ts b/src/core/legacy-import/import-service.tsindex 53edc559..299fe55c 100644--- a/src/core/legacy-import/import-service.ts+++ b/src/core/legacy-import/import-service.ts@@ -665,6 +665,9 @@ export class LegacyImportService {activation: 'inactive',storagePolicy: 'legacy-read-only',reason: candidate.item.reason,+ ...(candidate.item.requestOptions?.length+ ? { requestOptions: candidate.item.requestOptions }+ : {}),selectionKnown: candidate.selectionKnown,selectedFiles: candidate.selectedFiles,},diff --git a/src/core/legacy-import/legacy-task-policy.test.ts b/src/core/legacy-import/legacy-task-policy.test.tsnew file mode 100644index 00000000..3e5a6cfb--- /dev/null+++ b/src/core/legacy-import/legacy-task-policy.test.ts@@ -0,0 +1,34 @@+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'+import { describe, expect, it } from 'vitest'+import {+ getLegacyHttpBindingInput,+ getLegacyQuarantinedGids,+} from './legacy-task-policy'++describe('HTTP migration binding identity', () => {+ it('uses the original instance URI after the public engine URI changes', () => {+ const task = makeLegacyHttpTask()+ task.uris = ['https://redirect.example/temporary']+ expect(getLegacyHttpBindingInput(task)?.uri).toBe(+ 'https://example.com/file.bin'+ )+ task.instances[0].uris = ['https://redirect.example/temporary']+ expect(getLegacyHttpBindingInput(task)).toBeNull()+ })++ it('quarantines both the instance and raw HTTP intent GIDs when the intent is corrupt', () => {+ const task = makeLegacyHttpTask()+ task.instances[0].payload.legacyHttpActivation = {+ version: 99,+ engineTaskId: 'abcdef1234567890',+ }+ expect(getLegacyQuarantinedGids(task)).toEqual(+ new Set([task.engineTaskId, 'abcdef1234567890'])+ )+ expect(getLegacyHttpBindingInput(task)).toBeNull()+ })++ it('does not quarantine a confirmed active binding', () => {+ expect(getLegacyQuarantinedGids(makeLegacyHttpTask()).size).toBe(0)+ })+})diff --git a/src/core/legacy-import/legacy-task-policy.ts b/src/core/legacy-import/legacy-task-policy.tsindex 13271d38..598a0636 100644--- a/src/core/legacy-import/legacy-task-policy.ts+++ b/src/core/legacy-import/legacy-task-policy.ts@@ -1,12 +1,19 @@+import { createHash } from 'node:crypto'+import type { EngineAdapter } from '@core/engine/engine-adapter'import { AppError, ErrorCode } from '@shared/errors'+import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'import type { DownloadTask } from '@shared/types/task'+import { TaskInstancePhase, TaskType } from '@shared/types/task'export {hasLegacyImport,isLegacyImportInactive as isInactiveLegacyTask,} from '@shared/types/task-actions'-import { isLegacyImportInactive as isInactiveLegacyTask } from '@shared/types/task-actions'+import {+ hasLegacyImport,+ isLegacyImportInactive as isInactiveLegacyTask,+} from '@shared/types/task-actions'export function assertLegacyTaskNotActivated(task: Pick<DownloadTask, 'instances'>@@ -22,11 +29,7 @@ export function assertLegacyTaskNotActivated(export function assertLegacyTaskNotRecreated(task: Pick<DownloadTask, 'instances'>): void {- if (- (task.instances ?? []).some((instance) =>- Object.hasOwn(instance.payload ?? {}, 'legacyImport')- )- )+ if (hasLegacyImport(task))throw new AppError(ErrorCode.EngineFeatureUnavailable,'legacyImport.activationRequired'@@ -41,14 +44,56 @@ export function getLegacyQuarantinedGids(if (!isInactiveLegacyTask(task)) return resultfor (const instance of task.instances ?? []) {if (instance.gid) result.add(instance.gid)- const activation = instance.payload?.legacyBtActivation as- | { engineTaskId?: unknown }- | undefined- if (- typeof activation?.engineTaskId === 'string' &&- /^[a-f0-9]{16}$/.test(activation.engineTaskId)- )- result.add(activation.engineTaskId)+ for (const candidate of [+ instance.payload?.legacyBtActivation,+ instance.payload?.legacyHttpActivation,+ ]) {+ const activation = candidate as { engineTaskId?: unknown } | undefined+ if (+ typeof activation?.engineTaskId === 'string' &&+ /^[a-f0-9]{16}$/.test(activation.engineTaskId)+ )+ result.add(activation.engineTaskId)+ }}return result}++/** Reconstruct only the validated identity needed to prove an engine binding. */+export function getLegacyHttpBindingInput(+ task: DownloadTask+): Parameters<NonNullable<EngineAdapter['verifyLegacyHttpBinding']>>[0] | null {+ if (task.type !== TaskType.Http || task.instances.length !== 1) return null+ const instance = task.instances[0]+ const parsed = legacyHttpActivationSchema.safeParse(+ instance.payload.legacyHttpActivation+ )+ if (!parsed.success || instance.phase !== TaskInstancePhase.HttpDownload)+ return null+ const intent = parsed.data+ const uri = instance.uris[0]+ if (+ instance.uris.length !== 1 ||+ !uri ||+ createHash('sha256').update(uri).digest('hex') !== intent.uriDigest ||+ (task.engineTaskId && task.engineTaskId !== intent.engineTaskId) ||+ task.diskPath !== intent.targetPath ||+ task.finalPath !== intent.targetPath+ )+ return null+ return {+ engineTaskId: intent.engineTaskId,+ saveDir: intent.saveDir,+ targetPath: intent.targetPath,+ uri,+ expected: {+ totalBytes: intent.expected.totalBytes,+ pieceBytes: intent.expected.pieceBytes,+ },+ entityTag: intent.resourceValidator.value,+ fileIdentity: {+ device: intent.files[0].identity.device,+ inode: intent.files[0].identity.inode,+ },+ }+}diff --git a/src/core/legacy-import/parser-adversarial.test.ts b/src/core/legacy-import/parser-adversarial.test.tsindex 9df87225..92f8e908 100644--- a/src/core/legacy-import/parser-adversarial.test.ts+++ b/src/core/legacy-import/parser-adversarial.test.ts@@ -28,7 +28,7 @@ describe('legacy session adversarial parsing', () => {expect(entry.reason).toBeNull()})- it.each(['false', '0', '1', ''])(+ it.each(['0', '1', ''])('does not enable ambient netrc credentials through no-netrc=%s',(value) => {const [entry] = parseLegacySession(@@ -38,6 +38,86 @@ describe('legacy session adversarial parsing', () => {})+ it.each([+ ['header', 'Authorization: Bearer private-token'],+ ['referer', 'https://private.test/source'],+ ['all-proxy', 'http://private-user:[email protected]:8080'],+ ['load-cookies', '/private/cookies.txt'],+ ['no-netrc', 'false'],+ ])(+ 'keeps only the name of request option %s for reconfiguration',+ (key, value) => {+ const [entry] = parseLegacySession(+ encode(`https://example.test/a\n ${key}=${value}\n`)+ )+ expect(entry.reason).toBe('request-settings-required')+ expect(entry.requestOptions).toEqual([key])+ expect(entry.options[key]).toBeUndefined()+ expect(entry.optionPairs).toEqual([])+ expect(JSON.stringify(entry)).not.toContain(value)+ }+ )++ it('deduplicates repeated request names without retaining any of their values', () => {+ const [entry] = parseLegacySession(+ encode(+ 'https://example.test/a\n header=Cookie: private-cookie\n header=Authorization: private-token\n header=\n'+ )+ )+ expect(entry.requestOptions).toEqual(['header'])+ expect(entry.reason).toBe('request-settings-required')+ expect(JSON.stringify(entry)).not.toMatch(/private-cookie|private-token/)+ })++ it('ignores empty known request options but rejects empty unknown options', () => {+ const [empty, unknown] = parseLegacySession(+ encode(+ 'https://example.test/a\n header=\n referer= \n all-proxy=\nhttps://example.test/b\n unsafe-option=\n'+ )+ )+ expect(empty.reason).toBeNull()+ expect(empty.requestOptions).toEqual([])+ expect(unknown.reason).toBe('unsupported-options')+ expect(unknown.unsupportedOptions).toEqual(['unsafe-option'])+ })++ it('bounds safe diagnostic names while preserving unsupported rejection', () => {+ const [entry] = parseLegacySession(+ encode(+ `https://example.test/a\n ${'x'.repeat(65)}=private\n${Array.from({ length: 70 }, (_, index) => ` unknown-${index}=private`).join('\n')}\n`+ )+ )+ expect(entry.reason).toBe('unsupported-options')+ expect(entry.unsupportedOptions).toHaveLength(64)+ expect(entry.unsupportedOptions.every((key) => key.length <= 64)).toBe(true)+ expect(JSON.stringify(entry)).not.toContain('private')+ })++ it.each([+ ['malformed option', ' bad option=value\n unsupported=value\n'],+ ['oversized line', ` header=${'x'.repeat(16384)}\n unsupported=value\n`],+ ['invalid gid', ' gid=invalid\n header=private\n'],+ ])(+ 'retains invalid-record precedence for %s after unsafe options',+ (_label, options) => {+ const [entry] = parseLegacySession(+ encode(`https://example.test/a\n${options}`)+ )+ expect(entry.reason).toBe('invalid-record')+ }+ )++ it('rejects repeated GIDs even when both records only need request settings', () => {+ const entries = parseLegacySession(+ encode(+ 'https://example.test/a\n gid=0123456789abcdef\n header=private\nhttps://example.test/b\n gid=0123456789abcdef\n header=private\n'+ )+ )+ expect(entries.every((entry) => entry.reason === 'invalid-record')).toBe(+ true+ )+ })+it('preserves cumulative tracker pairs while applying singleton last-value semantics', () => {const [entry] = parseLegacySession(encode(@@ -55,16 +135,16 @@ describe('legacy session adversarial parsing', () => {it.each(['on-download-complete=/tmp/run','input-file=/tmp/other',- 'load-cookies=/tmp/cookies','rpc-secret=private',- 'header=Authorization: Bearer private',])('does not replay executable, remote-control or credential options: %s',(option) => {const [entry] = parseLegacySession(encode(`https://example.test/a\n ${option}\n out=a.zip\n`))- expect(entry.reason).not.toBeNull()+ expect(entry.reason).toBe('unsupported-options')+ expect(entry.unsupportedOptions).toEqual([option.split('=')[0]])+ expect(entry.options[option.split('=')[0]]).toBeUndefined()})diff --git a/src/core/legacy-import/session-parser.ts b/src/core/legacy-import/session-parser.tsindex 6af7039f..367f38e6 100644--- a/src/core/legacy-import/session-parser.ts+++ b/src/core/legacy-import/session-parser.ts@@ -26,7 +26,7 @@ const OPTIONS = new Set(['allow-overwrite','auto-file-renaming','file-allocation',- // Only explicit true is accepted: it disables ambient netrc credentials.+ // Only explicit true is retained: it disables ambient netrc credentials.'no-netrc',// Declarative options emitted by the v1.8.19 bundled engine even when the// user did not customize a task. None is applied during scan or import.@@ -41,6 +41,24 @@ const OPTIONS = new Set(['bt-tracker',])+/** Only names survive parsing; old credentials and request values are never replayed. */+export const LEGACY_REQUEST_OPTIONS = new Set([+ 'header',+ 'referer',+ 'all-proxy',+ 'all-proxy-user',+ 'all-proxy-passwd',+ 'http-proxy',+ 'http-proxy-user',+ 'http-proxy-passwd',+ 'https-proxy',+ 'https-proxy-user',+ 'https-proxy-passwd',+ 'http-user',+ 'http-passwd',+ 'load-cookies',+])+export interface LegacySessionEntry {itemKey: stringdigest: string@@ -48,6 +66,8 @@ export interface LegacySessionEntry {uris: string[]options: Record<string, string>optionPairs: Array<readonly [string, string]>+ requestOptions: string[]+ unsupportedOptions: string[]reason: LegacyReason | null}@@ -71,6 +91,8 @@ export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {const uris = lines[0].trim().split(/\t+/).filter(Boolean)const options: Record<string, string> = Object.create(null)const optionPairs: Array<readonly [string, string]> = []+ const requestOptions = new Set<string>()+ const unsupportedOptions = new Set<string>()let reason: LegacyReason | null =lines.some((line) => line.length > MAX_LINE) || uris.length > 16? 'invalid-record'@@ -81,14 +103,25 @@ export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {reason = 'invalid-record'continue}- if (!OPTIONS.has(match[1])) reason = 'unsupported-options'- else if (match[1] === 'no-netrc' && match[2].trim() !== 'true')- reason = 'unsupported-options'- else {- optionPairs.push([match[1], match[2]])- options[match[1]] = match[2]+ const [, key, value] = match+ if (+ LEGACY_REQUEST_OPTIONS.has(key) ||+ (key === 'no-netrc' && value.trim() === 'false')+ ) {+ if (value.trim()) requestOptions.add(key)+ } else if (+ !OPTIONS.has(key) ||+ (key === 'no-netrc' && value.trim() !== 'true')+ ) {+ if (reason !== 'invalid-record') reason = 'unsupported-options'+ if (key.length <= 64 && unsupportedOptions.size < 64)+ unsupportedOptions.add(key)+ } else {+ optionPairs.push([key, value])+ options[key] = value}}+ if (!reason && requestOptions.size) reason = 'request-settings-required'const gid =options.gid && /^[a-f\d]{16}$/i.test(options.gid)? options.gid.toLowerCase()@@ -96,7 +129,17 @@ export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {if (options.gid && !gid) reason = 'invalid-record'const digest = digestBytes(raw)const itemKey = gid ? `gid:${gid}` : `entry:${digest}`- entries.push({ itemKey, digest, gid, uris, options, optionPairs, reason })+ entries.push({+ itemKey,+ digest,+ gid,+ uris,+ options,+ optionPairs,+ requestOptions: [...requestOptions],+ unsupportedOptions: [...unsupportedOptions],+ reason,+ })lines = []}for (const line of text.split(/\r?\n/)) {diff --git a/src/core/legacy-import/source-scanner-adversarial.test.ts b/src/core/legacy-import/source-scanner-adversarial.test.tsindex 7ccb688a..1e307f1c 100644--- a/src/core/legacy-import/source-scanner-adversarial.test.ts+++ b/src/core/legacy-import/source-scanner-adversarial.test.ts@@ -97,18 +97,63 @@ describe('legacy source adversarial boundaries', () => {).rejects.toThrow()})- it('blocks a task whose old request depended on a header without exposing that value', async () => {+ it('keeps a paused HTTP task selectable without requiring request settings', async () => {const { source } = await fixture(- 'https://example.test/file.zip\n header=Authorization: Bearer private-token\n out=file.zip\n'+ 'https://example.test/video.mp4\n gid=0123456789abcdef\n pause=true\n out=下载视频.mp4\n')const scan = await scanLegacySource(source, () => false)- expect(scan.candidates[0].item.selectable).toBe(false)- expect(- JSON.stringify(scan.candidates.map(({ item }) => item))- ).not.toContain('private-token')+ expect(scan.candidates[0].item).toMatchObject({+ type: 'http',+ name: '下载视频.mp4',+ selectable: true,+ reason: 'verification-required',+ })+ expect(scan.candidates[0].item.requestOptions).toBeUndefined()+ })++ it('accepts repeated v1 request headers for inactive import without exposing their values', async () => {+ const { source } = await fixture(+ 'https://example.test/video.mp4\t\n gid=0123456789abcdef\n pause=true\n header=Authorization: Bearer private-token\n header=Cookie: private-cookie\n referer=https://private.test/source\n no-netrc=true\n user-agent=aria2/1.36.0\n out=下载视频.mp4\n'+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ type: 'http',+ name: '下载视频.mp4',+ selectable: true,+ reason: 'request-settings-required',+ requestOptions: ['header', 'referer'],+ })+ expect(JSON.stringify(scan.candidates.map(({ item }) => item))).not.toMatch(+ /private-token|private-cookie|private\.test/+ )})- it('blocks inherited request credentials instead of treating the task as URI-only', async () => {+ it('blocks HTTP mirrors that cannot be reconfigured through the fresh-download form', async () => {+ const { source } = await fixture(+ 'https://example.test/file.zip\thttps://mirror.test/file.zip\n header=private\n'+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ type: 'http',+ selectable: false,+ reason: 'mirrors-unsupported',+ requestOptions: ['header'],+ })+ })++ it('preserves existing URI-only HTTP mirror import behavior', async () => {+ const { source } = await fixture(+ 'https://example.test/file.zip\thttps://mirror.test/file.zip\n'+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ type: 'http',+ selectable: true,+ reason: 'verification-required',+ })+ })++ it('requires new settings for inherited proxy and credentials without exposing them', async () => {const { root, sourceRoot, source } = await fixture()await writeFile(path.join(sourceRoot, 'system.json'),@@ -116,15 +161,130 @@ describe('legacy source adversarial boundaries', () => {dir: path.join(root, 'downloads'),'http-user': 'private-user','http-passwd': 'private-pass',+ 'all-proxy': 'http://private-proxy.test:8080',}))const scan = await scanLegacySource(source, () => false)- expect(scan.candidates[0].item.selectable).toBe(false)- expect(- JSON.stringify(scan.candidates.map(({ item }) => item))- ).not.toContain('private-pass')+ expect(scan.candidates[0].item).toMatchObject({+ type: 'http',+ selectable: true,+ reason: 'request-settings-required',+ requestOptions: expect.arrayContaining([+ 'http-user',+ 'http-passwd',+ 'all-proxy',+ ]),+ })+ expect(JSON.stringify(scan.candidates.map(({ item }) => item))).not.toMatch(+ /private-user|private-pass|private-proxy/+ )+ })++ it('ignores empty session and inherited request settings', async () => {+ const { root, sourceRoot, source } = await fixture(+ 'https://example.test/file.zip\n header=\n referer= \n all-proxy=\n'+ )+ await writeFile(+ path.join(sourceRoot, 'system.json'),+ JSON.stringify({+ dir: path.join(root, 'downloads'),+ header: ['', ' '],+ referer: '',+ 'all-proxy': null,+ 'http-user': [],+ })+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ selectable: true,+ reason: 'verification-required',+ })+ expect(scan.candidates[0].item.requestOptions).toBeUndefined()})+ it.each([false, 'false'])(+ 'requires new settings for inherited no-netrc=%s',+ async (value) => {+ const { root, sourceRoot, source } = await fixture()+ await writeFile(+ path.join(sourceRoot, 'system.json'),+ JSON.stringify({ dir: path.join(root, 'downloads'), 'no-netrc': value })+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ selectable: true,+ reason: 'request-settings-required',+ requestOptions: ['no-netrc'],+ })+ }+ )++ it.each([+ 'on-download-complete=private-command',+ 'input-file=private-path',+ 'rpc-secret=private-secret',+ 'unknown-option=',+ ])(+ 'keeps unsafe HTTP option %s disabled while retaining its type',+ async (option) => {+ const { source } = await fixture(+ `https://example.test/file.zip\n header=private-header\n ${option}\n`+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ type: 'http',+ selectable: false,+ reason: 'unsupported-options',+ unsupportedOptions: [option.split('=')[0]],+ })+ expect(JSON.stringify(scan.candidates[0].item)).not.toContain('private')+ }+ )++ it.each([+ ['https://user:[email protected]/a', '', 'invalid-record'],+ ['https://example.test/a\tftp://mirror.test/a', '', 'invalid-record'],+ ['https://example.test/a', ' out=../unsafe\n', 'unsafe-path'],+ ['https://example.test/a', ' dir=relative\n', 'unsafe-path'],+ ['https://example.test/a', ' gid=invalid\n', 'invalid-record'],+ ])(+ 'still validates request-dependent task %s%s',+ async (uri, options, reason) => {+ const { source } = await fixture(`${uri}\n header=private\n${options}`)+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ selectable: false,+ reason,+ })+ }+ )++ it.each([+ [+ 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=bundle',+ 'magnet',+ ],+ ['/outside/metadata.torrent', 'bt'],+ ['metadata.torrent', 'bt'],+ ])(+ 'keeps request-dependent %s blocked without reading metadata',+ async (uri, type) => {+ const { source } = await fixture(`${uri}\n header=private\n`)+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates[0].item).toMatchObject({+ type,+ selectable: false,+ reason: 'unsupported-options',+ requestOptions: ['header'],+ unsupportedOptions: ['header'],+ })+ expect(scan.candidates[0].torrent).toBeNull()+ expect(scan.files.map(({ relativePath }) => relativePath).sort()).toEqual(+ ['download.session', 'system.json', 'user.json']+ )+ }+ )+it('does not choose an arbitrary winner among conflicting entries with one old GID', async () => {const { source } = await fixture('https://example.test/a.zip\n gid=0123456789abcdef\n out=a.zip\nhttps://example.test/b.zip\n gid=0123456789abcdef\n out=b.zip\n'@@ -134,6 +294,37 @@ describe('legacy source adversarial boundaries', () => {expect(scan.candidates.every(({ item }) => !item.selectable)).toBe(true)})+ it('keeps output identity stable when request settings are added to a task without a GID', async () => {+ const session = 'https://example.test/file.zip\n out=file.zip\n'+ const { sourceRoot, source } = await fixture(session)+ const original = await scanLegacySource(source, () => false)+ await writeFile(+ path.join(sourceRoot, 'download.session'),+ `${session} header=private\n`+ )+ const changed = await scanLegacySource(source, () => false)+ expect(changed.candidates[0].item.itemId).toBe(+ original.candidates[0].item.itemId+ )+ expect(changed.candidates[0].outputPath).toBe(+ original.candidates[0].outputPath+ )+ expect(changed.candidates[0].item.reason).toBe('request-settings-required')+ })++ it('rejects duplicate task identities when only their request values differ', async () => {+ const { source } = await fixture(+ 'https://example.test/file.zip\n header=first-private\nhttps://example.test/file.zip\n header=second-private\n'+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates).toHaveLength(2)+ expect(+ scan.candidates.every(+ ({ item }) => !item.selectable && item.reason === 'invalid-record'+ )+ ).toBe(true)+ })+it('keeps the same URL in two output directories as distinct import candidates', async () => {const { root, sourceRoot, source } = await fixture()await writeFile(diff --git a/src/core/legacy-import/source-scanner.ts b/src/core/legacy-import/source-scanner.tsindex a4f0441e..bdfc3d72 100644--- a/src/core/legacy-import/source-scanner.ts+++ b/src/core/legacy-import/source-scanner.ts@@ -11,6 +11,7 @@ import parseTorrent from 'parse-torrent'import { parseBtFileLayout } from '../task/bt-storage-layout'import {digestBytes,+ LEGACY_REQUEST_OPTIONS,type LegacySessionEntry,MAX_LEGACY_BYTES,parseLegacySession,@@ -277,6 +278,23 @@ function selection(return { files: [...result].sort((a, b) => a - b), known: true }}+function hasRequestValue(value: unknown): boolean {+ const values = Array.isArray(value) ? value : [value]+ return values.some(+ (part) =>+ part !== undefined &&+ part !== null &&+ (typeof part !== 'string' || part.trim().length > 0)+ )+}++function recognizableType(first: string | undefined): LegacyImportItem['type'] {+ if (!first) return 'unknown'+ if (/^https?:\/\//i.test(first)) return 'http'+ if (first.startsWith('magnet:?')) return 'magnet'+ return first.endsWith('.torrent') ? 'bt' : 'unknown'+}+export async function scanLegacySource(source: LegacySource,isProcessRunning: (pid: number) => boolean | Promise<boolean>,@@ -306,16 +324,28 @@ export async function scanLegacySource(pid > 0 &&(await isProcessRunning(pid))const candidates: LegacyCandidate[] = []+ const inheritedRequestOptions = [...LEGACY_REQUEST_OPTIONS].filter((key) =>+ hasRequestValue(system[key])+ )+ if (system['no-netrc'] === false || system['no-netrc'] === 'false')+ inheritedRequestOptions.push('no-netrc')let snapshotBytes = files.reduce((sum, file) => sum + file.bytes.length, 0)const torrentByPath = new Map<string, LegacySnapshotFile>()for (const entry of parseLegacySession(session.bytes)) {+ const requestOptions = [+ ...new Set([...entry.requestOptions, ...inheritedRequestOptions]),+ ]const item: LegacyImportItem = {itemId: entry.itemKey,name: entry.options.out || '—',saveDir: safeLegacyDirectory(entry.options.dir ?? (system.dir as string)),- type: 'unknown',+ type: recognizableType(entry.uris[0]),selectable: true,reason: 'fresh-download-required',+ ...(requestOptions.length ? { requestOptions } : {}),+ ...(entry.unsupportedOptions.length+ ? { unsupportedOptions: entry.unsupportedOptions }+ : {}),}const candidate: LegacyCandidate = {item,@@ -329,11 +359,19 @@ export async function scanLegacySource(}candidates.push(candidate)try {- if (entry.reason) {+ if (entry.reason && entry.reason !== 'request-settings-required') {item.selectable = falseitem.reason = entry.reasoncontinue}+ if (requestOptions.length && item.type !== 'http') {+ // Request recovery is only implemented for HTTP. Do not open torrent+ // metadata or relax verification and activation for other task types.+ item.selectable = false+ item.reason = 'unsupported-options'+ item.unsupportedOptions = requestOptions+ continue+ }const first = entry.uris[0]if (!first) throw new Error('invalid')const dir = entry.options.dir ?? (system.dir as string)@@ -362,35 +400,6 @@ export async function scanLegacySource(}))throw new Error('invalid')- if (- [- 'header',- 'http-user',- 'http-passwd',- 'all-proxy-user',- 'all-proxy-passwd',- 'http-proxy',- 'http-proxy-user',- 'http-proxy-passwd',- 'https-proxy',- 'https-proxy-user',- 'https-proxy-passwd',- 'load-cookies',- 'referer',- 'all-proxy',- ].some(- (key) =>- system[key] !== undefined &&- system[key] !== null &&- system[key] !== '' &&- (!Array.isArray(system[key]) ||- (system[key] as unknown[]).length !== 0)- )- ) {- item.selectable = false- item.reason = 'unsupported-options'- continue- }item.type = 'http'item.name =entry.options.out ||@@ -398,7 +407,13 @@ export async function scanLegacySource(new URL(first).pathname.split('/').at(-1) || 'download')candidate.outputPath = safeLegacyOutput(dir, item.name)- item.reason = 'fresh-download-required'+ item.reason = requestOptions.length+ ? 'request-settings-required'+ : 'verification-required'+ if (requestOptions.length && entry.uris.length > 1) {+ item.selectable = false+ item.reason = 'mirrors-unsupported'+ }} else {const filename = first.startsWith('file:')? fileURLToPath(first)diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 3c1cd95b..42375e61 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -14,15 +14,19 @@ import {} from '@shared/types/task'import type { TaskTerminalOccurrence } from '@shared/types/task-occurrence'import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'import { makeMediaProgress } from '@test-utils/media-progress'import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'+import { PollingScheduler } from '../engine/aria2/polling-scheduler'import type { Aria2RawStatus } from '../engine/aria2/types'import type { EngineAdapter } from '../engine/engine-adapter'import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'+import { EventBus } from '../events/event-bus'import { assertValidHookPlan } from '../plugin/finalize/hook-plan'import { clearStoppedTasks } from '../task/actions/clear-stopped-tasks'+import { finalizeTask } from '../task/actions/finalize-task'import { stopSeedingTask } from '../task/actions/stop-seeding-task'import {btStoragePayload,@@ -30,6 +34,7 @@ import {getBtPayloadPath,parseBtFileLayout,} from '../task/bt-storage-layout'+import { CompletedEngineTaskCleanup } from '../task/completed-engine-task-cleanup'import { getMediaMetaPath } from '../task/media-task-files'import { TaskManager } from '../task/task-manager'import { computeUriHash } from './content-key'@@ -159,13 +164,13 @@ function createMockDb(): MotrixDatabase {}function createMockRpc(- opts: { activeTasks?: Aria2RawStatus[] } = {}+ opts: { activeTasks?: Aria2RawStatus[]; stoppedTasks?: Aria2RawStatus[] } = {}): Aria2RpcClient {return {tellStatus: vi.fn().mockRejectedValue(new Error('tellStatus not mocked')),tellActive: vi.fn().mockResolvedValue(opts.activeTasks ?? []),tellWaiting: vi.fn().mockResolvedValue([]),- tellStopped: vi.fn().mockResolvedValue([]),+ tellStopped: vi.fn().mockResolvedValue(opts.stoppedTasks ?? []),multicall: vi.fn().mockResolvedValue([[], [], []]),} as unknown as Aria2RpcClient}@@ -4500,32 +4505,326 @@ it('restores an existing paused direct BT download with internal engine metadata}})-it('quarantines a durable pending migration GID during restore and later authoritative polls', async () => {+it.each([+ ['legacyBtActivation', true],+ ['legacyHttpActivation', true],+ ['legacyHttpActivation', false],+] as const)(+ 'quarantines a corrupt %s GID with marker=%s during restore and later authoritative polls',+ async (activationKey, hasMarker) => {+ const manager = new TaskManager()+ const db = createMockDb()+ const gid = '1122334455667788'+ seedAsPair(db, {+ motrixId: 'pending-legacy',+ gid: null,+ type:+ activationKey === 'legacyHttpActivation' ? TaskType.Http : TaskType.Bt,+ status: TaskStatus.Paused,+ infoHash: 'a'.repeat(40),+ diskPath: '/original/bundle',+ finalPath: '/original/bundle',+ payload: {+ ...(hasMarker ? { legacyImport: { version: 99 } } : {}),+ [activationKey]: { engineTaskId: gid },+ },+ })+ const adapter = createMockAdapter()+ const rpc = createMockRpc({+ activeTasks: [+ createRawStatus({ gid, status: 'paused', infoHash: 'a'.repeat(40) }),+ ],+ })+ await new SessionManager(manager, rpc, db, adapter).restore()+ expect(manager.getAll().map((task) => task.id)).toEqual(['pending-legacy'])+ expect(manager.isEngineTaskIdRetired(gid)).toBe(true)+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ }+)++it('restores HTTP migration source identity and delegates completion without ordinary retirement', async () => {const manager = new TaskManager()const db = createMockDb()- const gid = '1122334455667788'+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })seedAsPair(db, {- motrixId: 'pending-legacy',- gid: null,- type: TaskType.Bt,- status: TaskStatus.Paused,- infoHash: 'a'.repeat(40),- diskPath: '/original/bundle',- finalPath: '/original/bundle',- payload: {- legacyImport: { version: 99 },- legacyBtActivation: { engineTaskId: gid },- },+ motrixId: task.id,+ gid: task.engineTaskId,+ type: TaskType.Http,+ status: task.status,+ diskPath: task.diskPath,+ finalPath: task.finalPath,+ uris: task.uris,+ totalBytes: task.totalBytes,+ downloadedBytes: task.downloadedBytes,+ payload: task.instances[0].payload,})const adapter = createMockAdapter()const rpc = createMockRpc({- activeTasks: [- createRawStatus({ gid, status: 'paused', infoHash: 'a'.repeat(40) }),+ stoppedTasks: [+ createRawStatus({+ gid: task.engineTaskId,+ status: 'complete',+ totalLength: '1024',+ completedLength: '1024',+ files: [+ {+ index: '1',+ path: task.finalPath,+ length: '1024',+ completedLength: '1024',+ selected: 'true',+ uris: [+ { uri: 'https://redirect.example/temporary', status: 'used' },+ ],+ },+ ],+ }),],})- await new SessionManager(manager, rpc, db, adapter).restore()- expect(manager.getAll().map((task) => task.id)).toEqual(['pending-legacy'])- expect(manager.isEngineTaskIdRetired(gid)).toBe(true)- expect(adapter.addTorrent).not.toHaveBeenCalled()+ const observeCompleted = vi.fn(async (snapshot: DownloadTask) => {+ expect(manager.getById(task.id)?.status).toBe(TaskStatus.Downloading)+ expect(manager.getById(task.id)?.uris).toEqual(task.uris)+ expect(snapshot).toMatchObject({+ id: task.id,+ engineTaskId: task.engineTaskId,+ type: TaskType.Http,+ status: TaskStatus.Completed,+ downloadedBytes: 1024,+ instances: [+ {+ payload: {+ legacyImport: { storagePolicy: 'legacy-http-in-place' },+ legacyHttpActivation: { engineTaskId: task.engineTaskId },+ },+ },+ ],+ })+ expect(snapshot.uris).toEqual(task.uris)+ })+ const session = new SessionManager(manager, rpc, db, adapter)+ await session.restore(undefined, observeCompleted)+ expect(observeCompleted).toHaveBeenCalledOnce()+ expect(manager.getById(task.id)?.instances[0].uris).toEqual(task.uris)+ expect(manager.getById(task.id)?.downloadedBytes).toBe(1024)+ expect(manager.isEngineTaskIdRetired(task.engineTaskId)).toBe(false)+ expect(session.getCompletedDirectEngineTaskIds().size).toBe(0)+ expect(adapter.createDownload).not.toHaveBeenCalled()expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()})++it.each(['throw', 'reject'])(+ 'restores unrelated history when an imported HTTP completion observer fails: %s',+ async (failure) => {+ const manager = new TaskManager()+ const db = createMockDb()+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ seedAsPair(db, {+ motrixId: task.id,+ gid: task.engineTaskId,+ type: TaskType.Http,+ status: task.status,+ diskPath: task.diskPath,+ finalPath: task.finalPath,+ uris: task.uris,+ totalBytes: task.totalBytes,+ downloadedBytes: task.downloadedBytes,+ payload: task.instances[0].payload,+ })+ seedAsPair(db, {+ motrixId: 'unrelated-history',+ gid: 'aaaaaaaaaaaaaaaa',+ type: TaskType.Http,+ status: TaskStatus.Completed,+ diskPath: '/elsewhere/history.bin',+ finalPath: '/elsewhere/history.bin',+ uris: ['https://example.com/history.bin'],+ })+ const adapter = createMockAdapter()+ const rpc = createMockRpc({+ stoppedTasks: [+ createRawStatus({+ gid: task.engineTaskId,+ status: 'complete',+ totalLength: '1024',+ completedLength: '1024',+ }),+ ],+ })+ const session = new SessionManager(manager, rpc, db, adapter)+ const observeCompleted = vi.fn(() => {+ const error = new Error('transient completion failure')+ if (failure === 'throw') throw error+ return Promise.reject(error)+ })++ await expect(+ session.restore(undefined, observeCompleted)+ ).resolves.toBeUndefined()++ expect(observeCompleted).toHaveBeenCalledOnce()+ expect(manager.getById(task.id)).toMatchObject({+ status: TaskStatus.Downloading,+ engineTaskId: task.engineTaskId,+ })+ expect(manager.getById('unrelated-history')?.status).toBe(+ TaskStatus.Completed+ )+ expect(db.getTask('unrelated-history')).not.toBeNull()+ expect(manager.isEngineTaskIdRetired(task.engineTaskId)).toBe(false)+ expect(adapter.createDownload).not.toHaveBeenCalled()+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()+ }+)++it.each(['rpc', 'binding probe', 'persistence'])(+ 'starts polling and autosave while a restored HTTP completion retries a transient %s failure',+ async (failure) => {+ vi.useFakeTimers()+ const manager = new TaskManager()+ const db = createMockDb()+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ seedAsPair(db, {+ motrixId: task.id,+ gid: task.engineTaskId,+ type: TaskType.Http,+ status: task.status,+ diskPath: task.diskPath,+ finalPath: task.finalPath,+ uris: task.uris,+ totalBytes: task.totalBytes,+ downloadedBytes: task.downloadedBytes,+ payload: task.instances[0].payload,+ })+ seedAsPair(db, {+ motrixId: 'unrelated-history',+ gid: 'aaaaaaaaaaaaaaaa',+ type: TaskType.Http,+ status: TaskStatus.Completed,+ diskPath: '/elsewhere/history.bin',+ finalPath: '/elsewhere/history.bin',+ uris: ['https://example.com/history.bin'],+ })+ const adapter = createMockAdapter()+ vi.mocked(adapter.getTaskStatus).mockResolvedValue({+ ...task,+ status: TaskStatus.Completed,+ downloadedBytes: task.totalBytes,+ })+ adapter.verifyLegacyHttpBinding = vi.fn().mockResolvedValue(true)+ if (failure === 'rpc') {+ vi.mocked(adapter.getTaskStatus).mockRejectedValueOnce(+ new Error('RPC unavailable')+ )+ } else if (failure === 'binding probe') {+ vi.mocked(adapter.verifyLegacyHttpBinding).mockResolvedValueOnce(false)+ } else {+ vi.mocked(db.persistTaskWithOccurrence).mockImplementationOnce(() => {+ throw new Error('database busy')+ })+ }+ const rpc = createMockRpc({+ stoppedTasks: [+ createRawStatus({+ gid: task.engineTaskId,+ status: 'complete',+ totalLength: '1024',+ completedLength: '1024',+ }),+ ],+ })+ vi.mocked(rpc.multicall).mockResolvedValue([+ {+ downloadSpeed: '0',+ uploadSpeed: '0',+ numActive: '0',+ numWaiting: '0',+ numStopped: '1',+ numStoppedTotal: '1',+ },+ [],+ [],+ ])+ const session = new SessionManager(manager, rpc, db, adapter)+ const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+ const publish = vi.fn()+ const eventBus = new EventBus()+ const cleanup = new CompletedEngineTaskCleanup({+ taskManager: manager,+ adapter,+ mintTaskId: () => 'unexpected-adoption',+ persist: async (candidate, occurrence) =>+ session.persistTaskWithOccurrence(candidate, occurrence),+ adopt: async (_candidate, persist) => persist(),+ publish,+ dispatch: async () => {},+ runTaskMutation: async (_ids, operation) => operation(),+ finalizeLegacyHttp: (taskId) =>+ finalizeTask(taskId, {+ taskManager: {+ getById: (id) => manager.getById(id),+ getAll: () => manager.getAll(),+ set: (id, candidate) => manager.set(id, candidate),+ setReservedEngineTaskOwner: (id, candidate, gid) =>+ manager.setReservedEngineTaskOwner(id, candidate, gid),+ reserveEngineTaskId: (gid) => manager.reserveEngineTaskId(gid),+ releaseEngineTaskIdReservation: (gid) =>+ manager.releaseEngineTaskIdReservation(gid),+ retireEngineTaskIdReservation: (gid) =>+ manager.retireEngineTaskIdReservation(gid),+ persist: (candidate) => session.persistTask(candidate),+ },+ adapter,+ persistTaskWithOccurrence: (candidate, occurrence) =>+ session.persistTaskWithOccurrence(candidate, occurrence),+ publishTaskUpdate: publish,+ publishTaskUpdateNow: publish,+ fs: { renameAtomic: vi.fn(), removePathRecursive: vi.fn() },+ torrentMetaStore: { read: vi.fn() },+ settings: { get: () => ({ bt: { seedTime: 0, seedRatio: 0 } }) },+ eventBus,+ activityRecorder: {+ recordSubmitted: vi.fn(),+ recordDownloadCompleted: vi.fn(),+ },+ log,+ }),+ log,+ })+ const onPolledTasks = vi.fn()+ const polling = new PollingScheduler(rpc, eventBus, vi.fn(), onPolledTasks)+ const startAutoSave = vi.spyOn(session, 'startAutoSave')++ try {+ await session.restore(undefined, (snapshot) => cleanup.observe(snapshot))+ session.startAutoSave(60000)+ polling.start()+ await vi.advanceTimersByTimeAsync(0)++ expect(startAutoSave).toHaveBeenCalledOnce()+ expect(onPolledTasks).toHaveBeenCalledOnce()+ expect(manager.getById('unrelated-history')?.status).toBe(+ TaskStatus.Completed+ )+ expect(manager.getById(task.id)?.status).toBe(TaskStatus.Downloading)+ expect(db.getTask(task.id)?.task.aggStatus).toBe(TaskStatus.Downloading)+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(1000)++ expect(manager.getById(task.id)?.status).toBe(TaskStatus.Completed)+ expect(db.getTask(task.id)?.task.aggStatus).toBe(TaskStatus.Completed)+ expect(adapter.verifyLegacyHttpBinding).toHaveBeenCalled()+ expect(manager.isEngineTaskIdRetired(task.engineTaskId)).toBe(false)+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()+ } finally {+ await polling.stopAndDrain()+ await cleanup.stopAndDrain()+ session.stopAutoSave()+ vi.useRealTimers()+ }+ }+)diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 062d9928..4704ceac 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -1,6 +1,7 @@import fs from 'node:fs'import path from 'node:path'import {+ getLegacyQuarantinedGids,hasLegacyImport,isInactiveLegacyTask,} from '@core/legacy-import/legacy-task-policy'@@ -18,7 +19,6 @@ import {DownloadSourceError,} from '@core/task/source-admission'import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'-import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'import type { DownloadTask } from '@shared/types/task'import {makeDefaultBtExtension,@@ -664,24 +664,7 @@ export class SessionManager {for (const pair of persisted) {byMotrixId.set(pair.task.motrixId, pair)- for (const instance of pair.instances) {- const activation = legacyBtActivationSchema.safeParse(- instance.payload.legacyBtActivation- )- if (isInactiveLegacyTask(pair)) {- const raw = instance.payload.legacyBtActivation as- | { engineTaskId?: unknown }- | undefined- if (instance.gid) migrationGids.add(instance.gid)- if (activation.success)- migrationGids.add(activation.data.engineTaskId)- else if (- typeof raw?.engineTaskId === 'string' &&- /^[a-f0-9]{16}$/.test(raw.engineTaskId)- )- migrationGids.add(raw.engineTaskId)- }- }+ for (const gid of getLegacyQuarantinedGids(pair)) migrationGids.add(gid)if (isInactiveLegacyTask(pair)) continueif (pair.task.infoHash && !hasLegacyImport(pair)) {const infoHash = pair.task.infoHash.toLowerCase()@@ -740,10 +723,10 @@ export class SessionManager {this.taskManager.clear()const consumedMotrixIds = new Set<string>()- // Engine-row evictions collected during Pass 1. Each chain preserves- // its own force-remove → purge order and never rejects; batching them- // lets N evictions overlap each other and the later passes instead of- // serializing 2×N RPC round-trips inline.+ // Completion observations and engine-row evictions collected during Pass 1.+ // Each eviction preserves its own force-remove → purge order; batching lets+ // these operations overlap the later passes without blocking unrelated+ // history restoration on one task's completion work.const evictions: Promise<void>[] = []const retireCompleted = (raw: Aria2RawStatus): Promise<void> =>observeCompletedTask@@ -905,7 +888,35 @@ export class SessionManager {}this.taskManager.set(task.id, task)consumedMotrixIds.add(parent.task.motrixId)- if (isCompletedDirectOutput(task)) {+ if (+ hasLegacyImport(parent) &&+ task.type === TaskType.Http &&+ aria2.status === 'complete'+ ) {+ // Keep the durable owner and migration provenance on this observation.+ // A raw translation only carries the GID and would route this through+ // ordinary direct cleanup instead of verified in-place finalization.+ if (observeCompletedTask) {+ evictions.push(+ Promise.resolve()+ .then(() =>+ observeCompletedTask({+ ...task,+ status: TaskStatus.Completed,+ })+ )+ .then(+ () => {},+ (err) => {+ log.warn(+ { err, taskId: task.id },+ 'restore: legacy HTTP completion observation failed'+ )+ }+ )+ )+ }+ } else if (isCompletedDirectOutput(task)) {evictions.push(retireCompleted(aria2))}} else {@@ -1334,7 +1345,14 @@ export class SessionManager {})}- const status = translateStatus(aria2)+ const engineStatus = translateStatus(aria2)+ // HTTP migration completion still needs its exact live binding verified.+ const status =+ hasLegacyImport(pair) &&+ taskPart.taskType === TaskType.Http &&+ engineStatus === TaskStatus.Completed+ ? taskPart.aggStatus+ : engineStatusconst terminalFields = applyTerminalTransition(terminalFieldsFromRow(taskPart),status,@@ -1390,7 +1408,7 @@ export class SessionManager {saveDir: restoreTaskSaveDirectory(taskPart, pair.instances, aria2.dir),createdAt: taskPart.createdAt,updatedAt: now,- uris: extractUris(aria2),+ uris: hasLegacyImport(pair) ? (primary?.uris ?? []) : extractUris(aria2),uploadedBytes,uploadedBytesBaseline,fileCount,diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex 65c2a97c..ea36f4ab 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -8,6 +8,7 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { describe, expect, it, vi } from 'vitest'@@ -112,6 +113,90 @@ function buildSingleFileTorrent(name: string): Uint8Array {)}+describe('finalizeTask legacy HTTP binding', () => {+ it('completes the original file only after exact live progress and binding proof', async () => {+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const deps = makeDeps({ persistTaskWithOccurrence: vi.fn() })+ deps.adapter.verifyLegacyHttpBinding = vi.fn().mockResolvedValue(true)+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue({+ ...task,+ status: TaskStatus.Completed,+ downloadedBytes: task.totalBytes,+ })++ await finalizeTask(task.id, deps)++ expect(deps.adapter.verifyLegacyHttpBinding).toHaveBeenCalledWith({+ engineTaskId: task.engineTaskId,+ saveDir: '/original',+ targetPath: '/original/file.bin',+ uri: task.uris[0],+ expected: { totalBytes: 1024, pieceBytes: 512 },+ entityTag: '"original"',+ fileIdentity: { device: '1', inode: '2' },+ })+ expect(task.status).toBe(TaskStatus.Completed)+ expect(task.downloadedBytes).toBe(1024)+ expect(task.diskPath).toBe('/original/file.bin')+ expect(task.instances[0]).toMatchObject({+ status: TaskStatus.Completed,+ diskPath: '/original/file.bin',+ downloadedBytes: 1024,+ progress: 100,+ })+ expect(deps.persistTaskWithOccurrence).toHaveBeenCalledOnce()+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()+ expect(deps.fs.removePathRecursive).not.toHaveBeenCalled()+ expect(deps.adapter.removeDownloadResult).not.toHaveBeenCalled()+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()+ })++ it.each([+ { status: TaskStatus.Downloading, totalBytes: 1024, downloadedBytes: 1024 },+ { status: TaskStatus.Completed, totalBytes: 1024, downloadedBytes: 512 },+ { status: TaskStatus.Completed, totalBytes: 2048, downloadedBytes: 2048 },+ { status: TaskStatus.Completed, totalBytes: 1024, downloadedBytes: 2048 },+ ])('does not finalize a mismatched engine completion %j', async (live) => {+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const deps = makeDeps({ persistTaskWithOccurrence: vi.fn() })+ deps.adapter.verifyLegacyHttpBinding = vi.fn().mockResolvedValue(true)+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue({+ ...task,+ ...live,+ })+ await finalizeTask(task.id, deps)+ expect(task.status).toBe(TaskStatus.Downloading)+ expect(deps.persistTaskWithOccurrence).not.toHaveBeenCalled()+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()+ })++ it.each(['binding', 'uri', 'path'])(+ 'does not finalize when the original %s cannot be proved',+ async (failure) => {+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ if (failure === 'uri')+ task.instances[0].uris = ['https://changed.example/file']+ if (failure === 'path') task.finalPath = '/original/another.bin'+ const deps = makeDeps({ persistTaskWithOccurrence: vi.fn() })+ deps.adapter.verifyLegacyHttpBinding = vi.fn().mockResolvedValue(false)+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue({+ ...task,+ status: TaskStatus.Completed,+ downloadedBytes: task.totalBytes,+ })+ await finalizeTask(task.id, deps)+ expect(task.status).toBe(TaskStatus.Downloading)+ expect(deps.persistTaskWithOccurrence).not.toHaveBeenCalled()+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()+ if (failure !== 'binding')+ expect(deps.adapter.verifyLegacyHttpBinding).not.toHaveBeenCalled()+ }+ )+})+describe('finalizeTask HTTP/FTP branch', () => {it.each([TaskType.Http, TaskType.Ftp])('publishes %s Finalizing with idle transfer metrics before a slow artifact commit',diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex d0affce1..21ad5fe9 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -1,6 +1,7 @@import path from 'node:path'import type { EngineAdapter } from '@core/engine/engine-adapter'import {+ getLegacyHttpBindingInput,hasLegacyImport,isInactiveLegacyTask,} from '@core/legacy-import/legacy-task-policy'@@ -16,7 +17,7 @@ import type {PluginHookTask,} from '@shared/types/plugin-hooks'import type { DownloadTask, TaskFile } from '@shared/types/task'-import { TaskStatus, TransitionPhase } from '@shared/types/task'+import { TaskStatus, TaskType, TransitionPhase } from '@shared/types/task'import { isTorrentLike } from '@shared/types/task-actions'import {TaskActivityAccuracy,@@ -101,6 +102,7 @@ export interface FinalizeTaskDeps {publishTaskUpdateNow: () => voidadapter: {verifyLegacyBtBinding?: EngineAdapter['verifyLegacyBtBinding']+ verifyLegacyHttpBinding?: EngineAdapter['verifyLegacyHttpBinding']removeDownloadResult(engineTaskId: string): Promise<void>forceRemoveTask(engineTaskId: string): Promise<void>getUploadLength(engineTaskId: string): Promise<number>@@ -211,31 +213,50 @@ async function finalizeTaskSerialized(live.downloadedBytes < live.totalBytes)return- const intent = legacyBtActivationSchema.safeParse(- task.instances[0]?.payload.legacyBtActivation- )- if (- !intent.success ||- task.engineTaskId !== intent.data.engineTaskId ||- task.finalPath !== intent.data.targetPath ||- !(await deps.adapter.verifyLegacyBtBinding?.({- engineTaskId: intent.data.engineTaskId,- saveDir: intent.data.saveDir,- infoHash: intent.data.expected.infoHash ?? '',- files: intent.data.files,- selectedFiles: intent.data.selectedFiles,- trackers: intent.data.trackers,- isPrivate: intent.data.isPrivate,- }))- )- return+ if (task.type === TaskType.Http) {+ const binding = getLegacyHttpBindingInput(task)+ if (+ !binding ||+ live.totalBytes !== binding.expected.totalBytes ||+ live.downloadedBytes !== binding.expected.totalBytes ||+ !(await deps.adapter.verifyLegacyHttpBinding?.(binding))+ )+ return+ } else {+ const intent = legacyBtActivationSchema.safeParse(+ task.instances[0]?.payload.legacyBtActivation+ )+ if (+ !intent.success ||+ task.engineTaskId !== intent.data.engineTaskId ||+ task.finalPath !== intent.data.targetPath ||+ !(await deps.adapter.verifyLegacyBtBinding?.({+ engineTaskId: intent.data.engineTaskId,+ saveDir: intent.data.saveDir,+ infoHash: intent.data.expected.infoHash ?? '',+ files: intent.data.files,+ selectedFiles: intent.data.selectedFiles,+ trackers: intent.data.trackers,+ isPrivate: intent.data.isPrivate,+ }))+ )+ return+ }const previous = task.statusObject.assign(task, applyTerminalTransition(task, TaskStatus.Completed))task.downloadedBytes = live.downloadedBytestask.totalBytes = live.totalBytestask.progress = 1- for (const instance of task.instances)+ task.downloadSpeed = 0+ task.uploadSpeed = 0+ task.etaSeconds = 0+ task.connections = 0+ for (const instance of task.instances) {instance.status = TaskStatus.Completed+ instance.totalBytes = live.totalBytes+ instance.downloadedBytes = live.downloadedBytes+ instance.progress = 100+ }await persistTaskTransition(task, previous, deps)deps.publishTaskUpdateNow()returndiff --git a/src/core/task/actions/remove-task.test.ts b/src/core/task/actions/remove-task.test.tsindex 7ef53406..ef119a55 100644--- a/src/core/task/actions/remove-task.test.ts+++ b/src/core/task/actions/remove-task.test.ts@@ -9,6 +9,7 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { describe, expect, it, vi } from 'vitest'@@ -106,6 +107,68 @@ function mediaTaskWithMetadata() {}describe('removeTask', () => {+ it.each([false, true])(+ 'preserves HTTP migration bytes and control files when deleteWithFiles=%s',+ async (deleteWithFiles) => {+ const directory = await mkdtemp(+ path.join(tmpdir(), 'legacy-http-remove-')+ )+ const target = path.join(directory, 'file.bin')+ const task = makeLegacyHttpTask({ finalPath: target })+ const deps = makeDeps()+ deps.adapter.getTaskStatus = vi.fn().mockResolvedValue(task)+ deps.adapter.verifyLegacyHttpBinding = vi.fn().mockResolvedValue(true)+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.db.getTask).mockReturnValue({} as never)+ await writeFile(target, 'original partial bytes')+ await writeFile(`${target}.aria2`, 'original control bytes')+ try {+ await removeTask(task.id, { deleteWithFiles }, deps)+ expect(deps.adapter.verifyLegacyHttpBinding).toHaveBeenCalledOnce()+ expect(deps.adapter.forceRemoveTask).toHaveBeenCalledWith(+ task.engineTaskId+ )+ expect(deps.adapter.removeDownloadResult).toHaveBeenCalledWith(+ task.engineTaskId+ )+ expect(deps.db.deleteTask).toHaveBeenCalledWith(task.id)+ expect(deps.fileCleanupService.cleanup).not.toHaveBeenCalled()+ expect(deps.torrentMetaStore.remove).not.toHaveBeenCalled()+ expect(await readFile(target, 'utf8')).toBe('original partial bytes')+ expect(await readFile(`${target}.aria2`, 'utf8')).toBe(+ 'original control bytes'+ )+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+ }+ )++ it.each(['binding', 'uri', 'corrupt-intent'])(+ 'retains a legacy HTTP owner without %s proof',+ async (failure) => {+ const task = makeLegacyHttpTask()+ if (failure === 'uri')+ task.instances[0].uris = ['https://wrong.example/file']+ if (failure === 'corrupt-intent')+ task.instances[0].payload.legacyHttpActivation = {+ engineTaskId: task.engineTaskId,+ }+ const deps = makeDeps()+ deps.adapter.getTaskStatus = vi.fn().mockResolvedValue(task)+ deps.adapter.verifyLegacyHttpBinding = vi.fn().mockResolvedValue(false)+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.db.getTask).mockReturnValue({} as never)+ await expect(+ removeTask(task.id, { deleteWithFiles: true }, deps)+ ).rejects.toThrow('legacyImport.errors.activationUncertain')+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(deps.adapter.removeDownloadResult).not.toHaveBeenCalled()+ expect(deps.db.deleteTask).not.toHaveBeenCalled()+ expect(deps.fileCleanupService.cleanup).not.toHaveBeenCalled()+ }+ )+it('retains the task and torrent metadata when file cleanup fails', async () => {const deps = makeDeps()const task = makeDownloadTask({diff --git a/src/core/task/actions/remove-task.ts b/src/core/task/actions/remove-task.tsindex a59d46b1..71540df9 100644--- a/src/core/task/actions/remove-task.ts+++ b/src/core/task/actions/remove-task.ts@@ -1,5 +1,8 @@import path from 'node:path'-import { hasLegacyImport } from '@core/legacy-import/legacy-task-policy'+import {+ getLegacyHttpBindingInput,+ hasLegacyImport,+} from '@core/legacy-import/legacy-task-policy'import { AppError, ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'@@ -7,6 +10,7 @@ import {type DownloadTask,TaskInstancePhase,TaskStatus,+ TaskType,} from '@shared/types/task'import { isStoppedTaskStatus } from '@shared/types/task-actions'import type {@@ -123,9 +127,11 @@ async function removeTaskUnderMutation(// Imported paths belong to v1; every removal request is metadata-only.if (hasLegacyImport(task)) {const pair = deps.db.getTask(taskId)- const candidate = task.instances[0]?.payload.legacyBtActivation as- | { engineTaskId?: unknown }- | undefined+ const candidate = (+ task.type === TaskType.Http+ ? task.instances[0]?.payload.legacyHttpActivation+ : task.instances[0]?.payload.legacyBtActivation+ ) as { engineTaskId?: unknown } | undefined// Even an uncertain paused add belongs to this migration. Confirm its absence// before deleting the sole durable owner; original payloads are never cleanup targets.const gid =@@ -136,20 +142,29 @@ async function removeTaskUnderMutation(if (gid) {const engine = await deps.adapter.getTaskStatus(gid)if (engine) {- const intent = legacyBtActivationSchema.safeParse(candidate)- if (- !pair ||- !intent.success ||- !(await deps.adapter.verifyLegacyBtBinding?.({- engineTaskId: intent.data.engineTaskId,- saveDir: intent.data.saveDir,- infoHash: intent.data.expected.infoHash ?? '',- files: intent.data.files,- selectedFiles: intent.data.selectedFiles,- trackers: intent.data.trackers,- isPrivate: intent.data.isPrivate,- }))- )+ const verifyBinding = async (): Promise<boolean> => {+ if (!pair) return false+ if (task.type === TaskType.Http) {+ const input = getLegacyHttpBindingInput(task)+ return Boolean(+ input && (await deps.adapter.verifyLegacyHttpBinding?.(input))+ )+ }+ const intent = legacyBtActivationSchema.safeParse(candidate)+ return Boolean(+ intent.success &&+ (await deps.adapter.verifyLegacyBtBinding?.({+ engineTaskId: intent.data.engineTaskId,+ saveDir: intent.data.saveDir,+ infoHash: intent.data.expected.infoHash ?? '',+ files: intent.data.files,+ selectedFiles: intent.data.selectedFiles,+ trackers: intent.data.trackers,+ isPrivate: intent.data.isPrivate,+ }))+ )+ }+ if (!(await verifyBinding()))throw new AppError(ErrorCode.InvalidSelection,'legacyImport.errors.activationUncertain'@@ -163,16 +178,7 @@ async function removeTaskUnderMutation(const stopped = await deps.adapter.getTaskStatus(gid)if (stopped &&- (!isStoppedTaskStatus(stopped.status) ||- !(await deps.adapter.verifyLegacyBtBinding?.({- engineTaskId: intent.data.engineTaskId,- saveDir: intent.data.saveDir,- infoHash: intent.data.expected.infoHash ?? '',- files: intent.data.files,- selectedFiles: intent.data.selectedFiles,- trackers: intent.data.trackers,- isPrivate: intent.data.isPrivate,- })))+ (!isStoppedTaskStatus(stopped.status) || !(await verifyBinding())))throw error}diff --git a/src/core/task/completed-direct-task-policy.test.ts b/src/core/task/completed-direct-task-policy.test.tsnew file mode 100644index 00000000..0b835955--- /dev/null+++ b/src/core/task/completed-direct-task-policy.test.ts@@ -0,0 +1,20 @@+import { TaskStatus } from '@shared/types/task'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'+import { describe, expect, it } from 'vitest'+import {+ isCompletedDirectOutput,+ isDirectFinalOutput,+} from './completed-direct-task-policy'++describe('completed direct task ownership', () => {+ it('excludes completed HTTP migration originals from ordinary result retirement', () => {+ const legacy = makeLegacyHttpTask({ status: TaskStatus.Completed })+ expect(isDirectFinalOutput(legacy)).toBe(false)+ expect(isCompletedDirectOutput(legacy)).toBe(false)+ delete legacy.instances[0].payload.legacyImport+ expect(isCompletedDirectOutput(legacy)).toBe(false)+ delete legacy.instances[0].payload.legacyHttpActivation+ expect(isDirectFinalOutput(legacy)).toBe(true)+ expect(isCompletedDirectOutput(legacy)).toBe(true)+ })+})diff --git a/src/core/task/completed-direct-task-policy.ts b/src/core/task/completed-direct-task-policy.tsindex 75608b45..39fe1cee 100644--- a/src/core/task/completed-direct-task-policy.ts+++ b/src/core/task/completed-direct-task-policy.ts@@ -6,10 +6,12 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { hasLegacyImport } from '@shared/types/task-actions'/** Final-path RPC downloads need no rename, but still need durable retirement. */export function isDirectFinalOutput(task: DownloadTask): boolean {return (+ !hasLegacyImport(task) &&task.kind === TaskKind.Direct &&(task.type === TaskType.Http || task.type === TaskType.Ftp) &&task.diskPath.length > 0 &&diff --git a/src/core/task/completed-engine-task-cleanup.test.ts b/src/core/task/completed-engine-task-cleanup.test.tsindex 49e7747b..92e9c067 100644--- a/src/core/task/completed-engine-task-cleanup.test.ts+++ b/src/core/task/completed-engine-task-cleanup.test.ts@@ -1,9 +1,11 @@+import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'import {TaskKind,TaskStatus,TaskType,TransitionPhase,} from '@shared/types/task'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'import { makeDownloadTask } from '@test-utils/task'import { afterEach, describe, expect, it, vi } from 'vitest'import { CompletedEngineTaskCleanup } from './completed-engine-task-cleanup'@@ -20,7 +22,22 @@ const output = (overrides = {}) =>...overrides,})-function harness(initial = true) {+function pendingResumeTask() {+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ task.instances[0].payload.legacyHttpActivation = {+ ...legacyHttpActivationSchema.parse(+ task.instances[0].payload.legacyHttpActivation+ ),+ stage: 'resume-uncertain',+ retainedContentDigest: 'a'.repeat(64),+ }+ return task+}++function harness(+ initial = true,+ finalizeLegacyHttp?: (taskId: string) => Promise<void>+) {const taskManager = new TaskManager()if (initial)taskManager.set(@@ -46,6 +63,7 @@ function harness(initial = true) {prepareFiles: vi.fn(async () => {order.push('files')}),+ finalizeLegacyHttp,adapter: {forceRemoveTask: vi.fn(async () => {order.push('stop')@@ -58,12 +76,253 @@ function harness(initial = true) {fn(),log: { warn: vi.fn() },}- return { ...deps, order, cleanup: new CompletedEngineTaskCleanup(deps) }+ const runTaskMutation = vi.spyOn(deps, 'runTaskMutation')+ return {+ ...deps,+ runTaskMutation,+ order,+ cleanup: new CompletedEngineTaskCleanup(deps),+ }}afterEach(() => vi.useRealTimers())describe('CompletedEngineTaskCleanup', () => {+ it('retains completion observed before the first HTTP resume becomes durable', async () => {+ vi.useFakeTimers()+ const active = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const uncertain = pendingResumeTask()+ const finalize = vi.fn(async (taskId: string) => {+ h.taskManager.set(taskId, { ...active, status: TaskStatus.Completed })+ })+ const h = harness(false, finalize)+ h.taskManager.set(uncertain.id, uncertain)+ expect(h.taskManager.isEngineTaskIdRetired(uncertain.engineTaskId)).toBe(+ true+ )++ await expect(+ h.cleanup.observe({ ...uncertain, status: TaskStatus.Completed })+ ).resolves.toBe(true)+ await vi.advanceTimersByTimeAsync(1000)+ expect(finalize).not.toHaveBeenCalled()+ expect(h.taskManager.getById(active.id)?.status).toBe(+ TaskStatus.Downloading+ )++ h.taskManager.set(active.id, active)+ await vi.advanceTimersByTimeAsync(2000)++ expect(finalize).toHaveBeenCalledOnce()+ expect(h.taskManager.getById(active.id)?.status).toBe(TaskStatus.Completed)+ expect(h.adopt).not.toHaveBeenCalled()+ expect(h.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()+ await h.cleanup.stopAndDrain()+ })++ it.each(['removed', 'taken over', 'still uncertain'])(+ 'never finalizes a pending resume that is %s',+ async (state) => {+ vi.useFakeTimers()+ const uncertain = pendingResumeTask()+ const finalize = vi.fn(async () => {})+ const h = harness(false, finalize)+ h.taskManager.set(uncertain.id, uncertain)+ await h.cleanup.observe({ ...uncertain, status: TaskStatus.Completed })++ if (state === 'removed') h.taskManager.remove(uncertain.id)+ else if (state === 'taken over') {+ // Keep the old row too: its stale GID alone is insufficient ownership.+ h.taskManager.set(+ uncertain.id,+ makeLegacyHttpTask({ status: TaskStatus.Downloading })+ )+ const replacement = makeLegacyHttpTask({+ id: 'replacement-owner',+ status: TaskStatus.Downloading,+ })+ h.taskManager.set(replacement.id, replacement)+ }++ await vi.advanceTimersByTimeAsync(61000)++ expect(finalize).not.toHaveBeenCalled()+ expect(h.adopt).not.toHaveBeenCalled()+ expect(h.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()+ await h.cleanup.stopAndDrain()+ }+ )++ it.each(['marker', 'digest', 'gid', 'path'])(+ 'does not retain an invalid pending resume with a mismatched %s',+ async (field) => {+ const uncertain = pendingResumeTask()+ if (field === 'marker')+ uncertain.instances[0].payload.legacyImport = { version: 99 }+ else if (field === 'digest') {+ const activation = uncertain.instances[0].payload+ .legacyHttpActivation as Record<string, unknown>+ delete activation.retainedContentDigest+ } else if (field === 'gid')+ uncertain.instances[0].gid = 'aaaaaaaaaaaaaaaa'+ else uncertain.finalPath = '/original/other.bin'+ const finalize = vi.fn(async () => {})+ const h = harness(false, finalize)+ h.taskManager.set(uncertain.id, uncertain)++ expect(+ await h.cleanup.observe({ ...uncertain, status: TaskStatus.Completed })+ ).toBe(false)+ expect(finalize).not.toHaveBeenCalled()+ expect(h.adopt).not.toHaveBeenCalled()+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()+ await h.cleanup.stopAndDrain()+ }+ )++ it.each(['RPC unavailable', 'database busy'])(+ 'retries an owned HTTP migration completion after %s without retiring its engine row',+ async (message) => {+ vi.useFakeTimers()+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const finalize = vi.fn(async (taskId: string) => {+ h.taskManager.set(+ taskId,+ makeLegacyHttpTask({ status: TaskStatus.Completed })+ )+ })+ const h = harness(false, finalize)+ h.taskManager.set(task.id, task)+ finalize.mockRejectedValueOnce(new Error(message))+ const snapshot = { ...task, status: TaskStatus.Completed }++ await expect(h.cleanup.observe(snapshot)).resolves.toBe(true)+ expect(h.taskManager.getById(task.id)?.status).toBe(+ TaskStatus.Downloading+ )+ expect(finalize).toHaveBeenCalledOnce()+ await vi.advanceTimersByTimeAsync(999)+ expect(finalize).toHaveBeenCalledOnce()+ await vi.advanceTimersByTimeAsync(1)++ expect(finalize).toHaveBeenCalledTimes(2)+ expect(h.taskManager.getById(task.id)?.status).toBe(TaskStatus.Completed)+ await h.cleanup.observe(snapshot)+ expect(finalize).toHaveBeenCalledTimes(2)+ expect(h.persist).not.toHaveBeenCalled()+ expect(h.adopt).not.toHaveBeenCalled()+ expect(h.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()+ await h.cleanup.stopAndDrain()+ }+ )++ it.each(['removed', 'replaced', 'quarantined', 'error'])(+ 'rechecks migration ownership under the mutation lock before retrying a %s owner',+ async (change) => {+ vi.useFakeTimers()+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const finalize = vi.fn().mockRejectedValue(new Error('RPC unavailable'))+ const h = harness(false, finalize)+ h.taskManager.set(task.id, task)+ await h.cleanup.observe({ ...task, status: TaskStatus.Completed })+ h.runTaskMutation.mockImplementationOnce(async (_ids, operation) => {+ if (change === 'removed') h.taskManager.remove(task.id)+ else if (change === 'replaced') {+ h.taskManager.set(+ task.id,+ makeLegacyHttpTask({ engineTaskId: 'aaaaaaaaaaaaaaaa' })+ )+ } else if (change === 'quarantined') {+ const quarantined = makeLegacyHttpTask()+ quarantined.instances[0].payload.legacyImport = { version: 99 }+ h.taskManager.set(task.id, quarantined)+ } else {+ h.taskManager.set(+ task.id,+ makeLegacyHttpTask({ status: TaskStatus.Error })+ )+ }+ return operation()+ })++ await vi.advanceTimersByTimeAsync(60000)++ expect(finalize).toHaveBeenCalledOnce()+ expect(h.adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()+ await h.cleanup.stopAndDrain()+ }+ )++ it('does not adopt an ownerless migration or run it without its verified finalizer', async () => {+ const task = makeLegacyHttpTask({ status: TaskStatus.Completed })+ const finalize = vi.fn(async () => {})+ const ownerless = harness(false, finalize)+ expect(await ownerless.cleanup.observe(task)).toBe(false)+ expect(finalize).not.toHaveBeenCalled()+ expect(ownerless.adopt).not.toHaveBeenCalled()+ const unsupported = harness(false)+ unsupported.taskManager.set(task.id, task)+ expect(await unsupported.cleanup.observe(task)).toBe(false)+ expect(unsupported.adapter.removeDownloadResult).not.toHaveBeenCalled()+ await ownerless.cleanup.stopAndDrain()+ await unsupported.cleanup.stopAndDrain()+ })++ it('backs off an unconfirmed migration completion while preserving its owner', async () => {+ vi.useFakeTimers()+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const finalize = vi.fn(async () => {})+ const h = harness(false, finalize)+ h.taskManager.set(task.id, task)+ await h.cleanup.observe({ ...task, status: TaskStatus.Completed })++ await vi.advanceTimersByTimeAsync(61000)+ expect(finalize).toHaveBeenCalledTimes(7)+ await vi.advanceTimersByTimeAsync(29999)+ expect(finalize).toHaveBeenCalledTimes(7)+ await vi.advanceTimersByTimeAsync(1)+ expect(finalize).toHaveBeenCalledTimes(8)+ expect(h.taskManager.getById(task.id)?.status).toBe(TaskStatus.Downloading)+ expect(h.adapter.removeDownloadResult).not.toHaveBeenCalled()++ await h.cleanup.stopAndDrain()+ await vi.advanceTimersByTimeAsync(60000)+ expect(finalize).toHaveBeenCalledTimes(8)+ })++ it('drains migration finalization and cancels its pending retry on shutdown', async () => {+ vi.useFakeTimers()+ const task = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ let reject!: (error: Error) => void+ const finalize = vi.fn(+ () =>+ new Promise<void>((_resolve, fail) => {+ reject = fail+ })+ )+ const h = harness(false, finalize)+ h.taskManager.set(task.id, task)+ const observed = h.cleanup.observe({+ ...task,+ status: TaskStatus.Completed,+ })+ let drained = false+ const drain = h.cleanup.stopAndDrain().then(() => {+ drained = true+ })+ await Promise.resolve()+ expect(drained).toBe(false)+ reject(new Error('RPC unavailable'))+ await Promise.all([observed, drain])+ await vi.advanceTimersByTimeAsync(60000)+ expect(drained).toBe(true)+ expect(finalize).toHaveBeenCalledOnce()+ })+it('persists final-path completion and files before purging the engine', async () => {const h = harness()expect(await h.cleanup.observe(output())).toBe(true)diff --git a/src/core/task/completed-engine-task-cleanup.ts b/src/core/task/completed-engine-task-cleanup.tsindex d821bf3f..268a5db3 100644--- a/src/core/task/completed-engine-task-cleanup.ts+++ b/src/core/task/completed-engine-task-cleanup.ts@@ -1,5 +1,12 @@import type { EngineAdapter } from '@core/engine/engine-adapter'-import { type DownloadTask, TaskStatus } from '@shared/types/task'+import {+ getLegacyHttpBindingInput,+ hasLegacyImport,+ isInactiveLegacyTask,+} from '@core/legacy-import/legacy-task-policy'+import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'+import { type DownloadTask, TaskStatus, TaskType } from '@shared/types/task'import type { TaskOccurrence } from '@shared/types/task-occurrence'import {buildTerminalOccurrence,@@ -28,6 +35,8 @@ interface CleanupDeps {publish: () => voiddispatch: (occurrence: TaskOccurrence) => Promise<void>prepareFiles?: (task: DownloadTask) => Promise<void>+ /** Runs under the task mutation lock; verifies and persists without eviction. */+ finalizeLegacyHttp?: (taskId: string) => Promise<void>runTaskMutation: <T>(ids: readonly string[],operation: () => Promise<T>@@ -39,10 +48,31 @@ interface PendingCompletion {snapshot: DownloadTaskownerId: stringadopted: boolean+ legacyHttp: booleanattempts: numberretryAt: number}+function isPendingLegacyHttpResume(task: DownloadTask): boolean {+ if (task.type !== TaskType.Http || task.instances.length !== 1) return false+ const instance = task.instances[0]+ const marker = legacyTaskMetadataSchema.safeParse(+ instance.payload.legacyImport+ )+ const activation = legacyHttpActivationSchema.safeParse(+ instance.payload.legacyHttpActivation+ )+ return (+ marker.success &&+ marker.data.activation === 'active' &&+ marker.data.storagePolicy === 'legacy-http-in-place' &&+ activation.success &&+ activation.data.stage === 'resume-uncertain' &&+ instance.gid === task.engineTaskId &&+ getLegacyHttpBindingInput(task)?.engineTaskId === task.engineTaskId+ )+}+function completeMetrics(task: DownloadTask): void {task.totalBytes = Math.max(task.totalBytes, task.downloadedBytes)task.downloadedBytes = task.totalBytes@@ -74,7 +104,17 @@ export class CompletedEngineTaskCleanup {async observe(snapshot: DownloadTask): Promise<boolean> {const gid = snapshot.engineTaskIdconst owner = this.deps.taskManager.getByEngineTaskId(gid)- if (!gid || !isDirectFinalOutput(owner ?? snapshot)) return false+ const pendingResume = owner && isPendingLegacyHttpResume(owner)+ const legacyHttp = Boolean(+ this.deps.finalizeLegacyHttp &&+ owner &&+ owner.type === TaskType.Http &&+ hasLegacyImport(owner) &&+ (!isInactiveLegacyTask(owner) || pendingResume) &&+ snapshot.status === TaskStatus.Completed+ )+ if (!gid || (!legacyHttp && !isDirectFinalOutput(owner ?? snapshot)))+ return falseif (!isCompletedDirectOutput(owner ?? snapshot) &&snapshot.status !== TaskStatus.Completed@@ -86,8 +126,12 @@ export class CompletedEngineTaskCleanup {owner?.status === TaskStatus.Removed)return false- if (this.stopped || this.deps.taskManager.isEngineTaskIdRetired(gid))+ if (+ this.stopped ||+ (this.deps.taskManager.isEngineTaskIdRetired(gid) && !pendingResume)+ )return true+ if (legacyHttp && owner?.status === TaskStatus.Completed) return trueconst completionKey = owner ? `${owner.id}:${owner.finishedAt}` : ''if (@@ -101,6 +145,7 @@ export class CompletedEngineTaskCleanup {snapshot: structuredClone(snapshot),ownerId: owner?.id ?? previous?.ownerId ?? this.deps.mintTaskId(),adopted: owner !== undefined || previous?.adopted === true,+ legacyHttp,attempts: previous?.attempts ?? 0,retryAt: 0,})@@ -152,7 +197,54 @@ export class CompletedEngineTaskCleanup {gid: string,pending: PendingCompletion): Promise<void> {- if (this.deps.taskManager.isEngineTaskIdRetired(gid)) return+ if (!pending.legacyHttp && this.deps.taskManager.isEngineTaskIdRetired(gid))+ return+ if (pending.legacyHttp) {+ await this.deps.runTaskMutation([pending.ownerId], async () => {+ const current = this.deps.taskManager.getById(pending.ownerId)+ if (+ !current ||+ current.engineTaskId !== gid ||+ this.deps.taskManager.getByEngineTaskId(gid)?.id !==+ pending.ownerId ||+ current.type !== TaskType.Http ||+ !hasLegacyImport(current) ||+ [TaskStatus.Completed, TaskStatus.Error, TaskStatus.Removed].includes(+ current.status+ )+ )+ return+ // The first unpause can complete before its active marker is committed.+ // Retain that observation, but never finalize an uncertain binding.+ if (isPendingLegacyHttpResume(current)) {+ throw new Error('Legacy HTTP resume is not yet durable')+ }+ if (+ this.deps.taskManager.isEngineTaskIdRetired(gid) ||+ isInactiveLegacyTask(current)+ )+ return+ // Native migration keeps its original row and paths. Only its verified+ // finalizer may publish completion; ordinary adoption/purge cannot run.+ await this.deps.finalizeLegacyHttp?.(current.id)+ const after = this.deps.taskManager.getById(pending.ownerId)+ if (+ after?.engineTaskId === gid &&+ hasLegacyImport(after) &&+ !isInactiveLegacyTask(after) &&+ ![+ TaskStatus.Completed,+ TaskStatus.Error,+ TaskStatus.Removed,+ ].includes(after.status)+ ) {+ // Binding probes may return false for transient RPC/filesystem errors.+ // A resolved finalizer is insufficient until its completion is durable.+ throw new Error('Legacy HTTP completion could not be verified')+ }+ })+ return+ }if (!pending.adopted) {const existing = this.deps.taskManager.getByEngineTaskId(gid)if (existing) {diff --git a/src/core/task/direct-resource-validator.ts b/src/core/task/direct-resource-validator.tsindex 436870b4..fc39b43c 100644--- a/src/core/task/direct-resource-validator.ts+++ b/src/core/task/direct-resource-validator.ts@@ -3,6 +3,7 @@ import {INCOMPLETE_SUFFIX,MAX_DEDUP_ATTEMPTS,} from '@shared/constants/incomplete'+import { AppError, ErrorCode } from '@shared/errors'import { analyzeDownloadSource } from '@shared/lib/download-source'import type { DirectResourceValidator } from '@shared/schemas/direct-replay-recipe'import type { EngineFeatureReport } from '@shared/types/engine'@@ -15,6 +16,7 @@ import {const DEFAULT_TIMEOUT_MS = 3_000const MAX_FILENAME_REDIRECTS = 5+const MAX_LEGACY_VERIFICATION_BYTES = 1024 * 1024const ARIA2_REDIRECT_STATUSES = new Set([300, 301, 302, 303, 307, 308])const ARIA2_WANT_DIGEST = 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1'const MAX_FILESYSTEM_NAME_BYTES = 255@@ -33,6 +35,7 @@ type UndiciRequestLike = typeof import('undici').requestinterface ResourceHttpResponse {status: numberheaders: Headers+ bytes(signal: AbortSignal): AsyncIterable<Uint8Array>cancel(): Promise<void> | void}@@ -69,6 +72,20 @@ export interface DirectResourceRequestOptionsheaders?: Readonly<Record<string, string>>}+export interface LegacyHttpContentVerificationInput {+ uri: string+ totalBytes: number+ ranges: readonly { offset: number; length: number }[]+ read: (offset: number, length: number) => Promise<Uint8Array>+ options?: DirectResourceRequestOptions+ signal?: AbortSignal+}++export interface LegacyHttpContentVerificationResult {+ validator: Extract<DirectResourceValidator, { kind: 'strong-etag' }>+ requestHeaders: Record<string, string>+}+export type DirectResourceProxyOptionsProvider =() => DirectResourceProxyOptions | null@@ -326,9 +343,9 @@ export interface DirectResourceValidationResult {}/**- * Captures and verifies non-secret HTTP validators for URI-only direct tasks.- * Every request uses GET like aria2 and cancels the response body immediately- * after headers; resume verification additionally requests a one-byte range.+ * Captures and verifies non-secret HTTP validators using GET requests like aria2.+ * Metadata probes cancel bodies after headers. Legacy recovery additionally+ * compares completed local bytes with bounded, conditionally requested ranges.*/export class DirectResourceValidatorService {constructor(@@ -464,6 +481,149 @@ export class DirectResourceValidatorService {}}+ /** Bind every completed legacy byte to one strong representation before reuse. */+ async verifyLegacyContent(+ input: LegacyHttpContentVerificationInput+ ): Promise<LegacyHttpContentVerificationResult> {+ const { uri, totalBytes, ranges, read, signal } = input+ const options = input.options ?? {}+ const initialUrl = parseHttpUrl(uri)+ const headers = probeHeaders(options.headers, options.userAgent)+ if (+ !initialUrl ||+ !headers ||+ !Number.isSafeInteger(totalBytes) ||+ totalBytes <= 0 ||+ ranges.some(+ ({ offset, length }) =>+ !Number.isSafeInteger(offset) ||+ !Number.isSafeInteger(length) ||+ offset < 0 ||+ length <= 0 ||+ length > totalBytes - offset+ ) ||+ signal?.aborted+ ) {+ throw legacyHttpFailure('httpVerificationFailed')+ }+ // These request fields are owned by verification, never by legacy input.+ headers['accept-encoding'] = 'identity'+ delete headers['if-range']+ delete headers['if-match']+ const client = await this.resolveHttpClient(options)+ if (!client) throw legacyHttpFailure('httpVerificationFailed')++ const verifyRange = async (+ offset: number,+ length: number,+ expectedTag?: string,+ compareLocal = false+ ) => {+ const controller = new AbortController()+ const abort = () => controller.abort()+ signal?.addEventListener('abort', abort, { once: true })+ if (signal?.aborted) abort()+ const timeout = setTimeout(abort, this.timeoutMs)+ let response: ResourceHttpResponse | undefined+ try {+ if (controller.signal.aborted) {+ throw legacyHttpFailure('httpVerificationFailed')+ }+ const local = compareLocal+ ? await abortable(read(offset, length), controller.signal)+ : null+ if (compareLocal && (!local || local.byteLength !== length)) {+ throw legacyHttpFailure('httpVerificationFailed')+ }+ const requestHeaders = {+ ...headers,+ range: `bytes=${offset}-${offset + length - 1}`,+ ...(expectedTag ? { 'if-match': expectedTag } : {}),+ }+ const resolved = await this.requestFollowingRedirects(+ initialUrl,+ uri,+ requestHeaders,+ client,+ controller.signal,+ true+ )+ if (!resolved) throw legacyHttpFailure('httpVerificationFailed')+ response = resolved.response+ const validator = validateLegacyRangeResponse(+ response,+ offset,+ length,+ totalBytes,+ expectedTag,+ this.now()+ )+ let received = 0+ for await (const bytes of response.bytes(controller.signal)) {+ if (bytes.byteLength > length - received) {+ throw legacyHttpFailure('httpVerificationFailed')+ }+ if (local) {+ for (let index = 0; index < bytes.byteLength; index++) {+ if (bytes[index] !== local[received + index]) {+ throw legacyHttpFailure('httpContentChanged')+ }+ }+ }+ received += bytes.byteLength+ }+ if (received !== length || controller.signal.aborted) {+ throw legacyHttpFailure('httpVerificationFailed')+ }+ return validator+ } finally {+ try {+ if (response) {+ await abortable(+ cancelResourceResponse(response),+ controller.signal+ ).catch(() => {})+ }+ } finally {+ clearTimeout(timeout)+ signal?.removeEventListener('abort', abort)+ }+ }+ }++ try {+ // A new ETag alone proves nothing about legacy bytes. Establish the+ // representation, then compare every completed checkpoint range to it.+ const validator = await verifyRange(0, 1)+ for (const range of ranges) {+ for (+ let offset = range.offset;+ offset < range.offset + range.length;+ ) {+ const length = Math.min(+ MAX_LEGACY_VERIFICATION_BYTES,+ range.offset + range.length - offset+ )+ await verifyRange(offset, length, validator.value, true)+ offset += length+ }+ }+ return {+ validator,+ requestHeaders: {+ 'If-Match': validator.value,+ 'Accept-Encoding': 'identity',+ },+ }+ } catch (error) {+ if (error instanceof LegacyHttpVerificationError) throw error+ // HTTP errors may contain signed URLs, proxy credentials or headers.+ throw legacyHttpFailure('httpVerificationFailed')+ } finally {+ await closeHttpClient(client)+ }+ }+private async requestMetadata(initialUrl: URL,initialRequestUrl: string,@@ -471,6 +631,32 @@ export class DirectResourceValidatorService {client: ResourceHttpClient,signal: AbortSignal): Promise<ResourceMetadata | null> {+ const resolved = await this.requestFollowingRedirects(+ initialUrl,+ initialRequestUrl,+ initialHeaders,+ client,+ signal+ )+ if (!resolved) return null+ const { response, finalUrl } = resolved+ const metadata = {+ finalUrl,+ headers: response.headers,+ status: response.status,+ }+ await cancelResourceResponse(response)+ return metadata+ }++ private async requestFollowingRedirects(+ initialUrl: URL,+ initialRequestUrl: string,+ initialHeaders: Record<string, string>,+ client: ResourceHttpClient,+ signal: AbortSignal,+ rejectRedirects = false+ ): Promise<{ response: ResourceHttpResponse; finalUrl: string } | null> {let currentUrl = initialUrllet currentRequestUrl = requestUrlPreservingAuthority(initialRequestUrl,@@ -482,19 +668,40 @@ export class DirectResourceValidatorService {for (let redirects = 0; redirects <= MAX_FILENAME_REDIRECTS; redirects++) {let response: ResourceHttpResponsetry {- response = await issueResourceRequest(client, currentRequestUrl, {- method: 'GET',- headers,- redirect: 'manual',- signal,- })+ response = await abortable(+ issueResourceRequest(client, currentRequestUrl, {+ method: 'GET',+ headers,+ redirect: 'manual',+ signal,+ }).then(async (result) => {+ if (signal.aborted) {+ await cancelResourceResponse(result)+ throw legacyHttpFailure('httpVerificationFailed')+ }+ return result+ }),+ signal+ )} catch {return null}+ if (rejectRedirects && response.status >= 300 && response.status < 400) {+ // Strong entity tags belong to a resource, not a redirect chain. Two+ // targets can legitimately share a tag while containing different bytes.+ await abortable(cancelResourceResponse(response), signal).catch(+ () => {}+ )+ throw legacyHttpFailure('httpRedirectUnsupported')+ }const location = response.headers.get('location')if (ARIA2_REDIRECT_STATUSES.has(response.status) && location) {- await cancelResourceResponse(response)+ try {+ await abortable(cancelResourceResponse(response), signal)+ } catch {+ return null+ }if (redirects === MAX_FILENAME_REDIRECTS) return nulllet nextUrl: URLtry {@@ -517,13 +724,7 @@ export class DirectResourceValidatorService {continue}- const metadata = {- finalUrl: currentUrl.toString(),- headers: response.headers,- status: response.status,- }- await cancelResourceResponse(response)- return metadata+ return { response, finalUrl: currentUrl.toString() }}return null@@ -940,11 +1141,7 @@ async function issueResourceRequest(if (client.request) return client.request(input, init)if (!client.fetch) throw new TypeError('HTTP client has no request method')const response = await client.fetch(input, init)- return {- status: response.status,- headers: response.headers,- cancel: () => cancelBody(response),- }+ return fetchResourceResponse(response)}async function requestResource(@@ -971,11 +1168,7 @@ async function requestResource(// Contract tests retain their Response-based seam; production takes the// lower-level Undici response branch and never applies Fetch defaults.if (response instanceof Response) {- return {- status: response.status,- headers: response.headers,- cancel: () => cancelBody(response),- }+ return fetchResourceResponse(response)}const headers = new Headers()@@ -989,10 +1182,123 @@ async function requestResource(return {status: response.statusCode,headers,+ bytes: (signal) => responseBytes(response.body, signal),cancel: () => destroyResponseBody(response.body),}}+function fetchResourceResponse(response: Response): ResourceHttpResponse {+ return {+ status: response.status,+ headers: response.headers,+ bytes: async function* (signal) {+ if (!response.body) return+ const reader = response.body.getReader()+ try {+ while (true) {+ const result = await abortable(reader.read(), signal)+ if (result.done) return+ yield result.value+ }+ } finally {+ // Do not hold up timeout/cancellation on an uncooperative body source.+ void reader.cancel().catch(() => {})+ reader.releaseLock()+ }+ },+ cancel: () => cancelBody(response),+ }+}++async function* responseBytes(+ body: AsyncIterable<Uint8Array>,+ signal: AbortSignal+): AsyncIterable<Uint8Array> {+ const iterator = body[Symbol.asyncIterator]()+ try {+ while (true) {+ const result = await abortable(iterator.next(), signal)+ if (result.done) return+ yield result.value+ }+ } finally {+ void iterator.return?.().catch(() => {})+ }+}++function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const abort = () => {+ signal.removeEventListener('abort', abort)+ reject(legacyHttpFailure('httpVerificationFailed'))+ }+ signal.addEventListener('abort', abort, { once: true })+ void operation.then(resolve, reject).finally(() => {+ signal.removeEventListener('abort', abort)+ })+ if (signal.aborted) abort()+ })+}++class LegacyHttpVerificationError extends AppError {}++function legacyHttpFailure(+ key:+ | 'httpContentChanged'+ | 'httpRangeUnsupported'+ | 'httpRedirectUnsupported'+ | 'httpValidatorRequired'+ | 'httpVerificationFailed'+): AppError {+ return new LegacyHttpVerificationError(+ ErrorCode.InvalidSelection,+ `legacyImport.errors.${key}`+ )+}++function validateLegacyRangeResponse(+ response: ResourceHttpResponse,+ offset: number,+ length: number,+ totalBytes: number,+ expectedTag: string | undefined,+ capturedAt: number+): LegacyHttpContentVerificationResult['validator'] {+ if (response.status === 412) throw legacyHttpFailure('httpContentChanged')+ if (response.status === 200 || response.status === 416) {+ throw legacyHttpFailure('httpRangeUnsupported')+ }+ if (response.status !== 206) throw legacyHttpFailure('httpVerificationFailed')+ const validator = readValidator(response.headers, capturedAt, totalBytes)+ if (validator?.kind !== 'strong-etag') {+ throw legacyHttpFailure('httpValidatorRequired')+ }+ if (expectedTag && validator.value !== expectedTag) {+ throw legacyHttpFailure('httpContentChanged')+ }+ const match = /^bytes ([0-9]+)-([0-9]+)\/([0-9]+)$/.exec(+ response.headers.get('content-range') ?? ''+ )+ const start = parseContentLength(match?.[1] ?? null)+ const end = parseContentLength(match?.[2] ?? null)+ const total = parseContentLength(match?.[3] ?? null)+ if (total !== null && total !== totalBytes) {+ throw legacyHttpFailure('httpContentChanged')+ }+ if (+ start !== offset ||+ end !== offset + length - 1 ||+ total !== totalBytes ||+ parseContentLength(response.headers.get('content-length')) !== length ||+ !['', 'identity'].includes(+ response.headers.get('content-encoding')?.trim().toLowerCase() ?? ''+ )+ ) {+ throw legacyHttpFailure('httpVerificationFailed')+ }+ return validator+}+async function destroyResponseBody(body: import('node:stream').Readable): Promise<void> {diff --git a/src/core/task/legacy-http-content-verifier.test.ts b/src/core/task/legacy-http-content-verifier.test.tsnew file mode 100644index 00000000..75920ffc--- /dev/null+++ b/src/core/task/legacy-http-content-verifier.test.ts@@ -0,0 +1,606 @@+// @vitest-environment node+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { AppError, ErrorCode } from '@shared/errors'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ DirectResourceValidatorService,+ type LegacyHttpContentVerificationInput,+} from './direct-resource-validator'++const URI = 'https://files.example/download?token=private'+const ETAG = '"release-v1"'+const data = new TextEncoder().encode('the old partly downloaded content')+const failure = (key = 'httpVerificationFailed') => ({+ code: ErrorCode.InvalidSelection,+ message: `legacyImport.errors.${key}`,+})++function requestedRange(init?: RequestInit): {+ offset: number+ length: number+} {+ const range = new Headers(init?.headers).get('range') ?? ''+ const match = /^bytes=(\d+)-(\d+)$/.exec(range)+ if (!match) throw new Error('Expected a byte range')+ const offset = Number(match[1])+ return { offset, length: Number(match[2]) - offset + 1 }+}++function rangeResponse(+ bytes: Uint8Array,+ offset: number,+ length: number,+ overrides: Record<string, string> = {},+ body: BodyInit = bytes.slice(offset, offset + length)+) {+ return new Response(body, {+ status: 206,+ headers: {+ ETag: ETAG,+ 'Content-Length': String(length),+ 'Content-Range': `bytes ${offset}-${offset + length - 1}/${bytes.length}`,+ ...overrides,+ },+ })+}++function input(+ overrides: Partial<LegacyHttpContentVerificationInput> = {}+): LegacyHttpContentVerificationInput {+ return {+ uri: URI,+ totalBytes: data.length,+ ranges: [{ offset: 2, length: 9 }],+ read: vi.fn(async (offset, length) => data.slice(offset, offset + length)),+ ...overrides,+ }+}++function matchingFetch(bytes = data) {+ return vi.fn(async (_uri: string | URL, init?: RequestInit) => {+ const { offset, length } = requestedRange(init)+ return rangeResponse(bytes, offset, length)+ })+}++let server: Server | undefined++afterEach(async () => {+ const current = server+ server = undefined+ if (current?.listening) {+ current.closeAllConnections()+ await new Promise<void>((resolve, reject) => {+ current.close((error) => (error ? reject(error) : resolve()))+ })+ }+})++describe('legacy HTTP completed content verification', () => {+ it('streams every noncontiguous completed range through real HTTP using bounded requests', async () => {+ const chunkBytes = 1024 * 1024+ const bytes = Uint8Array.from(+ { length: chunkBytes + 128 },+ (_, index) => index % 251+ )+ const requests: { range: string; ifMatch?: string; encoding?: string }[] =+ []+ server = createServer((request, response) => {+ const range = String(request.headers.range)+ const match = /^bytes=(\d+)-(\d+)$/.exec(range)+ if (!match) {+ response.writeHead(400).end()+ return+ }+ const offset = Number(match[1])+ const end = Number(match[2])+ requests.push({+ range,+ ifMatch: request.headers['if-match'],+ encoding: request.headers['accept-encoding'],+ })+ response.writeHead(206, {+ ETag: ETAG,+ 'Content-Length': String(end - offset + 1),+ 'Content-Range': `bytes ${offset}-${end}/${bytes.length}`,+ })+ response.end(bytes.subarray(offset, end + 1))+ })+ await new Promise<void>((resolve, reject) => {+ server?.once('error', reject)+ server?.listen(0, '127.0.0.1', resolve)+ })+ const read = vi.fn(async (offset: number, length: number) =>+ bytes.slice(offset, offset + length)+ )+ const service = new DirectResourceValidatorService(+ undefined,+ 3_000,+ () => 123+ )+ const result = await service.verifyLegacyContent(+ input({+ uri: `http://127.0.0.1:${(server.address() as AddressInfo).port}/file`,+ totalBytes: bytes.length,+ ranges: [+ { offset: 3, length: chunkBytes + 5 },+ { offset: chunkBytes + 50, length: 17 },+ ],+ read,+ })+ )+ expect(result).toEqual({+ validator: {+ kind: 'strong-etag',+ value: ETAG,+ contentLength: bytes.length,+ capturedAt: 123,+ },+ requestHeaders: { 'If-Match': ETAG, 'Accept-Encoding': 'identity' },+ })+ expect(read.mock.calls).toEqual([+ [3, chunkBytes],+ [chunkBytes + 3, 5],+ [chunkBytes + 50, 17],+ ])+ expect(requests).toEqual([+ { range: 'bytes=0-0', encoding: 'identity' },+ {+ range: `bytes=3-${chunkBytes + 2}`,+ ifMatch: ETAG,+ encoding: 'identity',+ },+ {+ range: `bytes=${chunkBytes + 3}-${chunkBytes + 7}`,+ ifMatch: ETAG,+ encoding: 'identity',+ },+ {+ range: `bytes=${chunkBytes + 50}-${chunkBytes + 66}`,+ ifMatch: ETAG,+ encoding: 'identity',+ },+ ])+ })++ it('requires a validated one-byte response even with no completed bytes', async () => {+ const fetch = matchingFetch()+ const read = vi.fn()+ await new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({ ranges: [], read })+ )+ expect(fetch).toHaveBeenCalledOnce()+ expect(read).not.toHaveBeenCalled()+ })++ it('rejects changed old bytes even when the new ETag and total size are stable', async () => {+ const service = new DirectResourceValidatorService(matchingFetch())+ await expect(+ service.verifyLegacyContent(+ input({ read: async (_offset, length) => new Uint8Array(length) })+ )+ ).rejects.toMatchObject(failure('httpContentChanged'))+ })++ it.each(['"release-v2"', 'precondition-failed'])(+ 'rejects a representation changing during comparison: %s',+ async (change) => {+ const fetch = matchingFetch()+ fetch.mockImplementationOnce(async () => rangeResponse(data, 0, 1))+ fetch.mockImplementationOnce(async (_uri, init) => {+ const { offset, length } = requestedRange(init)+ return change === 'precondition-failed'+ ? new Response(null, { status: 412 })+ : rangeResponse(data, offset, length, { ETag: change })+ })+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure('httpContentChanged'))+ }+ )++ it.each(['', 'W/"release-v1"', '"one", "two"'])(+ 'requires one strong ETag and rejects %s',+ async (etag) => {+ const response = rangeResponse(data, 0, 1, { ETag: etag })+ if (!etag) response.headers.delete('etag')+ await expect(+ new DirectResourceValidatorService(+ async () => response+ ).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure('httpValidatorRequired'))+ }+ )++ it.each([200, 416])(+ 'rejects unavailable byte ranges (%s)',+ async (status) => {+ await expect(+ new DirectResourceValidatorService(+ async () => new Response(null, { status })+ ).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure('httpRangeUnsupported'))+ }+ )++ it.each<Record<string, string>>([+ { 'Content-Range': `bytes 1-1/${data.length}` },+ { 'Content-Range': `bytes 0-1/${data.length}` },+ { 'Content-Range': 'bytes 0-0/*' },+ { 'Content-Range': `bytes 0-0/${data.length}, bytes 1-1/${data.length}` },+ { 'Content-Length': '2' },+ { 'Content-Length': '1, 1' },+ { 'Content-Encoding': 'gzip' },+ ])(+ 'rejects malformed or nonidentity response metadata: %j',+ async (headers) => {+ await expect(+ new DirectResourceValidatorService(async () =>+ rangeResponse(data, 0, 1, headers)+ ).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure())+ }+ )++ it('rejects a changed resource length', async () => {+ await expect(+ new DirectResourceValidatorService(async () =>+ rangeResponse(data, 0, 1, {+ 'Content-Range': `bytes 0-0/${data.length + 1}`,+ })+ ).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure('httpContentChanged'))+ })++ it.each(['truncated', 'excess'])(+ 'rejects %s response bytes despite valid headers',+ async (kind) => {+ const fetch = matchingFetch()+ fetch.mockImplementationOnce(async () => rangeResponse(data, 0, 1))+ fetch.mockImplementationOnce(async (_uri, init) => {+ const { offset, length } = requestedRange(init)+ return rangeResponse(+ data,+ offset,+ length,+ {},+ data.slice(offset, offset + length + (kind === 'excess' ? 1 : -1))+ )+ })+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure())+ }+ )++ it('detects a mismatch at the last byte of a later completed range', async () => {+ const fetch = matchingFetch()+ const ranges = [+ { offset: 0, length: 3 },+ { offset: 28, length: 5 },+ ]+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({+ ranges,+ read: async (offset, length) => {+ const bytes = data.slice(offset, offset + length)+ if (offset === 28) bytes[length - 1] = (bytes[length - 1] ?? 0) ^ 1+ return bytes+ },+ })+ )+ ).rejects.toMatchObject(failure('httpContentChanged'))+ expect(fetch).toHaveBeenCalledTimes(3)+ })++ it('rejects a missing Content-Length and a short local read', async () => {+ const response = rangeResponse(data, 0, 1)+ response.headers.delete('content-length')+ await expect(+ new DirectResourceValidatorService(+ async () => response+ ).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure())+ await expect(+ new DirectResourceValidatorService(matchingFetch()).verifyLegacyContent(+ input({ read: async () => new Uint8Array(0) })+ )+ ).rejects.toMatchObject(failure())+ })++ it('compares fragmented response chunks without depending on network chunk boundaries', async () => {+ const fetch = matchingFetch()+ fetch.mockImplementationOnce(async () => rangeResponse(data, 0, 1))+ fetch.mockImplementationOnce(async (_uri, init) => {+ const { offset, length } = requestedRange(init)+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ for (let index = offset; index < offset + length; index++) {+ controller.enqueue(data.slice(index, index + 1))+ }+ controller.close()+ },+ })+ return rangeResponse(data, offset, length, {}, body)+ })+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(input())+ ).resolves.toHaveProperty('validator.value', ETAG)+ })++ it('aborts a stalled body, cancels it and closes its proxy client', async () => {+ const controller = new AbortController()+ const cancel = vi.fn()+ const close = vi.fn(async () => undefined)+ const body = new ReadableStream<Uint8Array>({ cancel })+ const fetch = vi.fn(async () => {+ queueMicrotask(() => controller.abort())+ return rangeResponse(data, 0, 1, {}, body)+ })+ const service = new DirectResourceValidatorService(+ undefined,+ 3_000,+ Date.now,+ async () => ({ fetch, close })+ )+ await expect(+ service.verifyLegacyContent(+ input({+ signal: controller.signal,+ options: { proxy: 'http://proxy.example' },+ })+ )+ ).rejects.toMatchObject(failure())+ expect(cancel).toHaveBeenCalledOnce()+ expect(close).toHaveBeenCalledOnce()+ })++ it('bounds an unresponsive request even when the HTTP client ignores its abort signal', async () => {+ const close = vi.fn(async () => undefined)+ const fetch = vi.fn(() => new Promise<Response>(() => {}))+ const service = new DirectResourceValidatorService(+ undefined,+ 15,+ Date.now,+ async () => ({ fetch, close })+ )+ await expect(+ service.verifyLegacyContent(+ input({ options: { proxy: 'http://proxy.example' } })+ )+ ).rejects.toMatchObject(failure())+ expect(close).toHaveBeenCalledOnce()+ })++ it('bounds a response that sends headers but never finishes its body', async () => {+ const cancel = vi.fn()+ const service = new DirectResourceValidatorService(+ async () =>+ rangeResponse(+ data,+ 0,+ 1,+ {},+ new ReadableStream<Uint8Array>({ cancel })+ ),+ 15+ )+ await expect(service.verifyLegacyContent(input())).rejects.toMatchObject(+ failure()+ )+ expect(cancel).toHaveBeenCalledOnce()+ })++ it('bounds cancellation even if an invalid response refuses to finish cancelling', async () => {+ const cancel = vi.fn(() => new Promise<void>(() => {}))+ const response = new Response(new ReadableStream<Uint8Array>({ cancel }), {+ status: 200,+ })+ const service = new DirectResourceValidatorService(async () => response, 15)+ await expect(service.verifyLegacyContent(input())).rejects.toMatchObject(+ failure('httpRangeUnsupported')+ )+ expect(cancel).toHaveBeenCalledOnce()+ })++ it('cancels pending local reads without sending another request', async () => {+ const controller = new AbortController()+ const fetch = matchingFetch()+ const read = vi.fn(() => {+ controller.abort()+ return new Promise<Uint8Array>(() => {})+ })+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({+ read,+ signal: controller.signal,+ })+ )+ ).rejects.toMatchObject(failure())+ expect(fetch).toHaveBeenCalledOnce()+ })++ it('does no network or local reads after an already cancelled request', async () => {+ const fetch = matchingFetch()+ const request = input({ signal: AbortSignal.abort() })+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(request)+ ).rejects.toMatchObject(failure())+ expect(fetch).not.toHaveBeenCalled()+ expect(request.read).not.toHaveBeenCalled()+ })++ it('retains original credentials on same-origin requests and pins verification controls', async () => {+ const fetch = matchingFetch()+ await new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({+ options: {+ headers: {+ Authorization: 'Bearer private',+ Cookie: 'session=private',+ Range: 'bytes=99-100',+ 'If-Match': '"untrusted"',+ 'If-Range': '"untrusted"',+ 'Accept-Encoding': 'gzip',+ },+ },+ })+ )+ const headers = new Headers(fetch.mock.calls[1]?.[1]?.headers)+ expect(headers.get('authorization')).toBe('Bearer private')+ expect(headers.get('cookie')).toBe('session=private')+ expect(headers.get('range')).toBe('bytes=2-10')+ expect(headers.get('if-match')).toBe(ETAG)+ expect(headers.get('if-range')).toBeNull()+ expect(headers.get('accept-encoding')).toBe('identity')+ })++ it('does not forward credentials across redirect origins', async () => {+ const fetch = vi.fn(+ async () =>+ new Response(null, {+ status: 302,+ headers: { Location: 'https://elsewhere.example/file' },+ })+ )+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({+ options: { headers: { Authorization: 'Bearer private' } },+ })+ )+ ).rejects.toMatchObject(failure('httpRedirectUnsupported'))+ expect(fetch).toHaveBeenCalledOnce()+ })++ it.each([300, 301, 302, 303, 307, 308])(+ 'rejects an initial %s redirect without requesting its target',+ async (status) => {+ const cancel = vi.fn()+ const fetch = vi.fn(+ async (_uri: string | URL) =>+ new Response(new ReadableStream<Uint8Array>({ cancel }), {+ status,+ headers: { Location: 'https://cdn.example/file' },+ })+ )+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure('httpRedirectUnsupported'))+ expect(fetch).toHaveBeenCalledOnce()+ expect(String(fetch.mock.calls[0]?.[0])).toBe(URI)+ expect(cancel).toHaveBeenCalledOnce()+ }+ )++ it('rejects same-origin redirects because ETags are scoped to each resource', async () => {+ const fetch = vi.fn(+ async () =>+ new Response(null, {+ status: 302,+ headers: { Location: '/other-file', ETag: ETAG },+ })+ )+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(input())+ ).rejects.toMatchObject(failure('httpRedirectUnsupported'))+ expect(fetch).toHaveBeenCalledOnce()+ })++ it('rejects a later completed-range redirect even when its ETag has not changed', async () => {+ const fetch = matchingFetch()+ fetch.mockImplementationOnce(async () => rangeResponse(data, 0, 1))+ fetch.mockImplementationOnce(async () => rangeResponse(data, 0, 3))+ fetch.mockImplementationOnce(+ async () =>+ new Response(null, {+ status: 307,+ headers: { Location: 'https://cdn.example/other-file', ETag: ETAG },+ })+ )+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({+ ranges: [+ { offset: 0, length: 3 },+ { offset: 28, length: 5 },+ ],+ })+ )+ ).rejects.toMatchObject(failure('httpRedirectUnsupported'))+ expect(fetch).toHaveBeenCalledTimes(3)+ expect(fetch.mock.calls.every(([uri]) => String(uri) === URI)).toBe(true)+ expect(new Headers(fetch.mock.calls[2]?.[1]?.headers).get('if-match')).toBe(+ ETAG+ )+ })++ it('never silently bypasses an unavailable configured proxy', async () => {+ const fetch = matchingFetch()+ const factory = vi.fn(async () => null)+ await expect(+ new DirectResourceValidatorService(+ fetch,+ 100,+ Date.now,+ factory+ ).verifyLegacyContent(+ input({+ options: {+ proxy: 'http://user:[email protected]',+ noProxy: 'localhost',+ },+ })+ )+ ).rejects.toMatchObject(failure())+ expect(factory).toHaveBeenCalledWith({+ proxy: 'http://user:[email protected]',+ noProxy: 'localhost',+ })+ expect(fetch).not.toHaveBeenCalled()+ })++ it('redacts raw network and file errors, including foreign AppErrors', async () => {+ const secret = 'https://private.example/?token=secret Authorization: secret'+ for (const service of [+ new DirectResourceValidatorService(async () => {+ throw new Error(secret)+ }),+ new DirectResourceValidatorService(matchingFetch()),+ ]) {+ const error = await service+ .verifyLegacyContent(+ input({+ read: async () => {+ throw new AppError(ErrorCode.TaskOpenFailed, secret)+ },+ })+ )+ .catch((caught: unknown) => caught)+ expect(error).toMatchObject(failure())+ expect(error).toHaveProperty('cause', undefined)+ expect(String(error)).not.toContain('secret')+ }+ })++ it.each([+ [{ offset: -1, length: 1 }],+ [{ offset: 0, length: data.length + 1 }],+ [{ offset: data.length, length: 1 }],+ [{ offset: 0, length: Number.NaN }],+ ])(+ 'rejects invalid completed ranges before requests: %j',+ async (...ranges) => {+ const fetch = matchingFetch()+ await expect(+ new DirectResourceValidatorService(fetch).verifyLegacyContent(+ input({ ranges })+ )+ ).rejects.toMatchObject(failure())+ expect(fetch).not.toHaveBeenCalled()+ }+ )+})diff --git a/src/core/task/merge-engine-task.test.ts b/src/core/task/merge-engine-task.test.tsindex 834d5845..f8259e83 100644--- a/src/core/task/merge-engine-task.test.ts+++ b/src/core/task/merge-engine-task.test.ts@@ -6,6 +6,7 @@ import {TaskStatus,TransitionPhase,} from '@shared/types/task'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it } from 'vitest'import { mergeEngineTask } from './merge-engine-task'@@ -35,6 +36,21 @@ function instance(status: TaskStatus, index = 0): TaskInstance {}describe('mergeEngineTask', () => {+ it('retains the original HTTP migration URI and status until completion is verified', () => {+ const existing = makeLegacyHttpTask({ status: TaskStatus.Downloading })+ const merged = mergeEngineTask(existing, {+ ...existing,+ status: TaskStatus.Completed,+ downloadedBytes: existing.totalBytes,+ uris: ['https://redirect.example.com/temporary-signed-url'],+ })+ expect(merged.uris).toEqual(existing.uris)+ expect(merged.instances[0].uris).toEqual(existing.instances[0].uris)+ expect(merged.status).toBe(TaskStatus.Downloading)+ expect(merged.instances[0].status).toBe(TaskStatus.Downloading)+ expect(merged.finishedAt).toBeNull()+ expect(merged.downloadedBytes).toBe(existing.totalBytes)+ })it.each([TaskStatus.Completed, TaskStatus.Error])('preserves imported %s history against a late paused replay',(status) => {diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex 6580ff57..f35123ee 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -1,6 +1,6 @@import { hasLegacyImport } from '@core/legacy-import/legacy-task-policy'import type { DownloadTask } from '@shared/types/task'-import { TaskStatus, TransitionPhase } from '@shared/types/task'+import { TaskStatus, TaskType, TransitionPhase } from '@shared/types/task'import { shareRatio } from '@shared/utils/share-ratio'import { applyTerminalTransition } from './apply-terminal-transition'import { unsettledBtUpload } from './bt-upload-settlement'@@ -58,7 +58,10 @@ export function mergeEngineTask(// metrics, but do not let that engine snapshot publish a status ahead of// the application-owned transition.const nextStatus =- existing.transitionPhase !== TransitionPhase.Idle+ existing.transitionPhase !== TransitionPhase.Idle ||+ (hasLegacyImport(existing) &&+ existing.type === TaskType.Http &&+ protected_.status === TaskStatus.Completed)? existing.status: protected_.statusconst terminalFields = applyTerminalTransition(@@ -88,7 +91,10 @@ export function mergeEngineTask(uploadedBytesBaseline: existing.uploadedBytesBaseline,fileCount: protected_.fileCount,infoHash: protected_.infoHash ?? existing.infoHash,- uris: protected_.uris.length > 0 ? protected_.uris : existing.uris,+ uris:+ !hasLegacyImport(existing) && protected_.uris.length > 0+ ? protected_.uris+ : existing.uris,bt: bt? {...bt,diff --git a/src/main/index.ts b/src/main/index.tsindex bd9a1433..63947ec4 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -37,6 +37,7 @@ import {taskInspectorActivityEnvironment,} from '@core/inspector-activity'import { LegacyBtActivationService } from '@core/legacy-import/bt-activation-service'+import { LegacyHttpActivationService } from '@core/legacy-import/http-activation-service'import { LegacyImportService } from '@core/legacy-import/import-service'import {getLegacyQuarantinedGids,@@ -537,6 +538,7 @@ let segmentClient: Aria2SegmentClient | null = nulllet disposeIpcIngress: (() => void) | null = nulllet legacyImportService: LegacyImportService | null = nulllet legacyBtActivationService: LegacyBtActivationService | null = null+let legacyHttpActivationService: LegacyHttpActivationService | null = nulllet pendingDisclaimerGate: DisclaimerGate | null = nullconst mainProcessWork = new MainProcessWorkCoordinator()const pollingNotificationUnsubscribers: Array<() => void> = []@@ -590,6 +592,7 @@ function performCleanup(): Promise<void> {// the drain: startup can be blocked on the engine/plugin/session that only// those teardown operations can release.void legacyBtActivationService?.drain()+ void legacyHttpActivationService?.drain()const acceptedWorkDrain = mainProcessWork.stopAndDrain()postDeliveryAbortController?.abort()await ingressClose@@ -667,6 +670,9 @@ function performCleanup(): Promise<void> {await safely('legacy-bt-activation', () =>legacyBtActivationService?.drain())+ await safely('legacy-http-activation', () =>+ legacyHttpActivationService?.drain()+ )await safely('legacy-import', () => legacyImportService?.drain())await safely('database', () => {if (motrixDb?.database.open) motrixDb.close()@@ -943,6 +949,7 @@ async function handlePolledTasks()}if (+ !hasLegacyImport(existing) &&shouldEvictFromEngine(existing.status, merged.status, existing.type)) {// Either BT/Magnet seeding just satisfied its ratio/time target,@@ -1341,6 +1348,7 @@ async function startEngineAndRestore(await appliedDownloadProxyPolicy.runWithSnapshot(async (_snapshot, lease) => {await legacyBtActivationService?.recover()+ await legacyHttpActivationService?.recover()await sessionManager.restore(lease.assertCurrent, (snapshot) =>completedEngineTaskCleanup.observe(snapshot))@@ -1520,6 +1528,13 @@ async function startEngineAndRestore() {return}+ if (hasLegacyImport(task) && task.type === TaskType.Http) {+ await completedEngineTaskCleanup.observe({+ ...task,+ status: TaskStatus.Completed,+ })+ return+ }if (shouldSkipEngineCompletionFinalize(task)) returntry {await finalizeTask(task.id, finalizeDepsFactory())@@ -1843,8 +1858,31 @@ async function initializeMainProcess(): Promise<void> {}return legacyBtActivationService}+ const getLegacyHttpActivationService = () => {+ if (!legacyHttpActivationService) {+ getLegacyImportService()+ legacyHttpActivationService = new LegacyHttpActivationService({+ db: motrixDb,+ taskManager,+ adapter,+ backupRoot: legacyBackupRoot,+ isProcessRunning: legacyPidRunning,+ publishTasks: publishTaskUpdateNow,+ runTaskMutation: (taskIds, operation) =>+ taskInspectorActivityRuntime+ ? taskInspectorActivityRuntime.runTaskMutation(taskIds, operation)+ : operation(),+ runExclusivePersistence: (operation) =>+ sessionManager+ ? sessionManager.runExclusivePersistence(operation)+ : Promise.resolve().then(operation),+ })+ }+ return legacyHttpActivationService+ }const disposeLegacyImportIpc = registerLegacyImportIpc({getActivationService: getLegacyBtActivationService,+ getHttpActivationService: getLegacyHttpActivationService,getService: getLegacyImportService,hasConsent: () => gate.isAccepted() && mainProcessWork.isAccepting(),getTask: (taskId) => taskManager.getById(taskId),@@ -1976,6 +2014,7 @@ async function initializeMainProcess(): Promise<void> {if (!legacyImportService) motrixDb.init()getLegacyBtActivationService()+ getLegacyHttpActivationService()legacyImportService?.setPersistenceLane((operation) =>sessionManager? sessionManager.runExclusivePersistence(operation)@@ -2206,6 +2245,12 @@ async function initializeMainProcess(): Promise<void> {dispatch: (occurrence) => occurrenceDispatcher.dispatch(occurrence),prepareFiles: (task) =>syncTaskFilesIfIncomplete(task.id, task.engineTaskId),+ // Cleanup owns the mutation lock across its exact-owner check and retry.+ finalizeLegacyHttp: (taskId) =>+ finalizeTask(taskId, {+ ...buildFinalizeDeps(adapter),+ runTaskMutation: undefined,+ }),runTaskMutation: (ids, operation) =>activeTaskInspectorActivityRuntime.runTaskMutation(ids, operation),log,diff --git a/src/main/legacy-import/desktop-import.test.ts b/src/main/legacy-import/desktop-import.test.tsindex 4aac8127..f0565c3f 100644--- a/src/main/legacy-import/desktop-import.test.ts+++ b/src/main/legacy-import/desktop-import.test.ts@@ -11,6 +11,7 @@ import { syncBuiltinESMExports } from 'node:module'import os from 'node:os'import path from 'node:path'import { Aria2ProcessInspector } from '@core/engine/aria2/aria2-process-inspector'+import type { LegacyHttpActivationService } from '@core/legacy-import/http-activation-service'import type { LegacyImportService } from '@core/legacy-import/import-service'import { TorrentParser } from '@core/torrent/torrent-parser'import { Commands } from '@shared/protocol/commands'@@ -234,7 +235,10 @@ describe('desktop legacy import', () => {Commands.CommitLegacyImport,Commands.RetryLegacyImport,Commands.ActivateLegacyBt,+ Commands.ActivateLegacyHttp,+ Commands.CancelLegacyHttpActivation,Queries.GetLegacyBtActivationAvailability,+ Queries.GetLegacyHttpActivationAvailability,Queries.GetLegacyImportNavigation,])await expect(@@ -292,6 +296,66 @@ describe('desktop legacy import', () => {expect(await readFile(oldPath, 'utf8')).toBe('original bytes')})+ it('authorizes the original HTTP directory and admits cancellation without waiting for activation', async () => {+ const f = await fixture()+ const available = vi.fn(async () => ({+ available: true,+ reason: null,+ directory: f.root,+ }))+ let finish!: () => void+ const pending = new Promise<void>((resolve) => {+ finish = resolve+ })+ const activate = vi.fn(+ async (+ _id: string,+ pick: (directory: string) => Promise<string | null>+ ) => {+ expect(await pick(f.root)).toBe(f.root)+ await pending+ return true+ }+ )+ const cancel = vi.fn(() => finish())+ registerLegacyImportIpc({+ getService: () => ({}) as LegacyImportService,+ getHttpActivationService: () =>+ ({+ availability: available,+ activate,+ cancel,+ }) as unknown as LegacyHttpActivationService,+ hasConsent: () => true,+ getTask: () => f.task,+ backupRoot: path.join(f.root, 'backups'),+ finishInvitation: vi.fn(),+ })+ await expect(+ mocks.handlers.get(Queries.GetLegacyHttpActivationAvailability)?.(+ f.event,+ { taskId: f.task.id }+ )+ ).resolves.toMatchObject({ available: true })+ const running = mocks.handlers.get(Commands.ActivateLegacyHttp)?.(f.event, {+ taskId: f.task.id,+ })+ await vi.waitFor(() => expect(activate).toHaveBeenCalledOnce())+ await mocks.handlers.get(Commands.CancelLegacyHttpActivation)?.(f.event, {+ taskId: f.task.id,+ })+ await expect(running).resolves.toBe(true)+ expect(cancel).toHaveBeenCalledWith(f.task.id)+ expect(mocks.pick).toHaveBeenCalledWith(+ mocks.owner,+ expect.objectContaining({+ defaultPath: f.root,+ properties: ['openDirectory'],+ })+ )+ expect(await readFile(f.oldPath, 'utf8')).toBe('original bytes')+ })+it('prepares a fresh download under an existing volume root without trying to create the root', async () => {const { root, oldPath, task, event } = await fixture()const realMkdir = filesystem.mkdir@@ -317,6 +381,30 @@ describe('desktop legacy import', () => {expect(mkdirSpy).not.toHaveBeenCalledWith(root, expect.anything())})+ it('carries a request-settings reminder into the fresh draft without request values', async () => {+ const { root, oldPath, task, event } = await fixture()+ const marker = task.instances[0].payload.legacyImport as Record<+ string,+ unknown+ >+ marker.reason = 'request-settings-required'+ marker.requestOptions = ['header', 'all-proxy']+ const result = (await mocks.handlers.get(+ Commands.PrepareLegacyFreshDownload+ )?.(event, { taskId: task.id })) as { saveDir: string }+ expect(result).toEqual({+ tab: 'links',+ urls: task.uris[0],+ filename: task.finalName,+ saveDir: expect.any(String),+ legacyRequestOptions: ['header', 'all-proxy'],+ })+ expect(path.dirname(result.saveDir)).toBe(root)+ expect(path.basename(result.saveDir)).toMatch(/^Motrix-new-/)+ expect(task.instances[0].gid).toBeNull()+ expect(await readFile(oldPath, 'utf8')).toBe('original bytes')+ })+it('rejects mirror re-add before a picker instead of turning one task into several downloads', async () => {const { task, event } = await fixture()task.uris.push('https://mirror.invalid/old.zip')diff --git a/src/main/legacy-import/desktop-import.ts b/src/main/legacy-import/desktop-import.tsindex 38379d22..f39b603d 100644--- a/src/main/legacy-import/desktop-import.ts+++ b/src/main/legacy-import/desktop-import.ts@@ -3,6 +3,7 @@ import os from 'node:os'import path from 'node:path'import { Aria2ProcessInspector } from '@core/engine/aria2/aria2-process-inspector'import type { LegacyBtActivationService } from '@core/legacy-import/bt-activation-service'+import type { LegacyHttpActivationService } from '@core/legacy-import/http-activation-service'import type { LegacyImportService } from '@core/legacy-import/import-service'import { isInactiveLegacyTask } from '@core/legacy-import/legacy-task-policy'import {@@ -78,6 +79,7 @@ export async function legacyPidRunning(pid: number): Promise<boolean> {interface DesktopImportDeps {getService: () => LegacyImportServicegetActivationService?: () => LegacyBtActivationService+ getHttpActivationService?: () => LegacyHttpActivationServicehasConsent: () => booleangetTask: (taskId: string) => DownloadTask | undefinedbackupRoot: string@@ -107,6 +109,45 @@ export function registerLegacyImportIpc(deps: DesktopImportDeps): () => void {string,(event: Electron.IpcMainInvokeEvent, input?: unknown) => Promise<unknown>> = {+ [Queries.GetLegacyHttpActivationAvailability]: async (_event, input) => {+ await readyService()+ if (!deps.getHttpActivationService)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.checkpointUnavailable'+ )+ return deps+ .getHttpActivationService()+ .availability(legacyTaskRequestSchema.parse(input).taskId)+ },+ [Commands.ActivateLegacyHttp]: async (event, input) => {+ await readyService()+ const { taskId } = legacyTaskRequestSchema.parse(input)+ const owner = BrowserWindow.fromWebContents(event.sender)+ if (!owner || !deps.getHttpActivationService)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.checkpointUnavailable'+ )+ return deps+ .getHttpActivationService()+ .activate(taskId, async (directory) => {+ const result = await dialog.showOpenDialog(owner, {+ title: i18n.t('legacyImport.authorizeOriginalDirectory'),+ defaultPath: directory,+ properties: ['openDirectory'],+ })+ return result.canceled || result.filePaths.length !== 1+ ? null+ : result.filePaths[0]+ })+ },+ [Commands.CancelLegacyHttpActivation]: async (_event, input) => {+ service()+ deps+ .getHttpActivationService?.()+ .cancel(legacyTaskRequestSchema.parse(input).taskId)+ },[Queries.GetLegacyImportNavigation]: async () => {service()return (@@ -266,6 +307,7 @@ export function registerLegacyImportIpc(deps: DesktopImportDeps): () => void {Commands.CommitLegacyImport,Commands.RetryLegacyImport,Commands.ActivateLegacyBt,+ Commands.ActivateLegacyHttp,])for (const [channel, handler] of Object.entries(handlers))registerTrustedIpcHandler(channel, (event, input) =>@@ -354,7 +396,14 @@ async function prepareFreshDownload(ErrorCode.InvalidSelection,'legacyImport.errors.unsafeSource')- prefill = { tab: 'links', urls: task.uris[0], filename: task.finalName }+ prefill = {+ tab: 'links',+ urls: task.uris[0],+ filename: task.finalName,+ ...(marker.reason === 'request-settings-required'+ ? { legacyRequestOptions: marker.requestOptions ?? [] }+ : {}),+ }}const owner = BrowserWindow.fromWebContents(event.sender)if (!owner) return nulldiff --git a/src/main/main-process-work-coordinator.test.ts b/src/main/main-process-work-coordinator.test.tsindex bf6114a9..bc9bdbfc 100644--- a/src/main/main-process-work-coordinator.test.ts+++ b/src/main/main-process-work-coordinator.test.ts@@ -273,6 +273,43 @@ describe('MainProcessWorkCoordinator', () => {expect(publish).toBeGreaterThan(recovery)})+ it('routes restored and notified HTTP migrations through the drained completion retry owner', () => {+ const source = readFileSync(+ path.resolve(process.cwd(), 'src/main/index.ts'),+ 'utf8'+ )+ const restore = source.indexOf('await sessionManager.restore(')+ const restoreEnd = source.indexOf(+ 'await sessionManager.recoverLegacyTaskLost',+ restore+ )+ const notification = source.indexOf('adapter.onDownloadComplete(')+ const autoSave = source.indexOf(+ 'sessionManager.startAutoSave(',+ notification+ )+ const polling = source.indexOf('pollingScheduler.start()', autoSave)+ const cleanup = source.indexOf('new CompletedEngineTaskCleanup(')+ const cleanupEnd = source.indexOf('supervisor.setStartupGuard(', cleanup)++ expect(source.slice(restore, restoreEnd)).toContain(+ 'completedEngineTaskCleanup.observe(snapshot)'+ )+ expect(source.slice(restore, restoreEnd)).not.toContain('finalizeTask(')+ expect(source.slice(notification, autoSave)).toContain(+ 'await completedEngineTaskCleanup.observe('+ )+ expect(autoSave).toBeGreaterThan(restoreEnd)+ expect(polling).toBeGreaterThan(autoSave)+ expect(source.slice(cleanup, cleanupEnd)).toContain('finalizeLegacyHttp:')+ // The queue holds the mutation lock while checking its owner. The verified+ // finalizer must not acquire the same non-reentrant lock a second time.+ expect(source.slice(cleanup, cleanupEnd)).toContain(+ 'runTaskMutation: undefined'+ )+ expect(source).toContain('completedEngineTaskCleanup?.stopAndDrain()')+ })+it('anchors an authoritative reconnect poll before recording its samples', () => {const source = readFileSync(path.resolve(process.cwd(), 'src/main/index.ts'),diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsxindex 1e5ef527..f504a945 100644--- a/src/renderer/components/add-task/add-task-form.test.tsx+++ b/src/renderer/components/add-task/add-task-form.test.tsx@@ -7,6 +7,7 @@ import '@renderer/lib/i18n'import { readTorrentFile } from '@renderer/lib/parse-torrent-file'import type { PlatformServices } from '@renderer/platform/services'import { PlatformServicesProvider } from '@renderer/platform/services'+import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import { holdExitAnimation } from '@test-utils/hold-exit-animation'import { AddTaskForm } from './add-task-form'@@ -69,6 +70,130 @@ function renderForm(props = {}, services: PlatformServices = mockServices) {}describe('AddTaskForm', () => {+ it('explains an unnamed header and allows removing it before submission', async () => {+ renderForm({+ defaultValues: {+ tab: 'links',+ urls: 'https://example.com/archive.zip',+ saveDir: '/new/downloads',+ },+ })+ await userEvent.click(screen.getByRole('button', { name: 'Advanced' }))+ await userEvent.click(screen.getByRole('button', { name: 'Add header' }))+ await userEvent.type(screen.getByLabelText('Header value'), 'fresh-value')+ await userEvent.click(screen.getByRole('button', { name: 'Download' }))+ expect(+ await screen.findByText('Enter a header name or remove this header.')+ ).toBeVisible()+ expect(screen.getByLabelText('Header name')).toHaveAccessibleDescription(+ 'Enter a header name or remove this header.'+ )+ expect(+ invokeMock.mock.calls.filter(+ ([channel]) => channel === Commands.CreateTask+ )+ ).toHaveLength(0)+ await userEvent.click(screen.getByRole('button', { name: 'Remove header' }))+ await userEvent.click(screen.getByRole('button', { name: 'Download' }))+ await waitFor(() =>+ expect(invokeMock).toHaveBeenCalledWith(+ Commands.CreateTask,+ expect.objectContaining({ headers: [] })+ )+ )+ })++ it('keeps migration guidance visible while editing and submits only newly entered request settings', async () => {+ renderForm({+ defaultValues: {+ tab: 'links',+ urls: 'https://example.com/archive.zip',+ saveDir: '/new/downloads',+ legacyRequestOptions: ['header', 'all-proxy'],+ },+ })+ expect(screen.getByRole('button', { name: 'Advanced' })).toHaveAttribute(+ 'aria-expanded',+ 'true'+ )+ expect(+ screen.getByText('Saved request settings: header, all-proxy')+ ).toBeVisible()+ expect(screen.getByLabelText('Cookie')).toHaveValue('')+ expect(+ invokeMock.mock.calls.filter(+ ([channel]) => channel === Commands.CreateTask+ )+ ).toHaveLength(0)+ await userEvent.click(screen.getByRole('button', { name: 'Add header' }))+ await userEvent.type(screen.getByLabelText('Header name'), 'X-Download-Key')+ await userEvent.type(screen.getByLabelText('Header value'), 'fresh-value')+ await userEvent.type(screen.getByLabelText('Cookie'), 'session=fresh')+ await userEvent.type(+ screen.getByLabelText('Proxy'),+ 'http://localhost:8080'+ )+ await userEvent.click(screen.getByRole('button', { name: 'Advanced' }))+ expect(+ screen.getByText('The old request settings were not copied.', {+ exact: false,+ })+ ).toBeVisible()+ await userEvent.click(screen.getByRole('button', { name: 'Download' }))+ await waitFor(() =>+ expect(invokeMock).toHaveBeenCalledWith(+ Commands.CreateTask,+ expect.objectContaining({+ headers: [+ { name: 'X-Download-Key', value: 'fresh-value' },+ { name: 'Cookie', value: 'session=fresh' },+ ],+ proxy: 'http://localhost:8080',+ })+ )+ )+ const request = invokeMock.mock.calls.find(+ ([channel]) => channel === Commands.CreateTask+ )?.[1]+ expect(request).not.toHaveProperty('legacyRequestOptions')+ })++ it('hydrates a migration reminder without names and removes it for the next ordinary draft', async () => {+ const { transport } = await import('@renderer/lib/transport')+ renderForm({ subscribeEvents: true })+ const setModeListener = vi+ .mocked(transport.on)+ .mock.calls.find(([channel]) => channel === Events.SetAddTaskMode)?.[1]+ await act(async () => {+ setModeListener?.({+ tab: 'links',+ urls: 'https://example.com/archive.zip',+ saveDir: '/new/downloads',+ legacyRequestOptions: [],+ })+ })+ expect(screen.getByRole('button', { name: 'Advanced' })).toHaveAttribute(+ 'aria-expanded',+ 'true'+ )+ expect(+ screen.getByText('The old request settings were not copied.', {+ exact: false,+ })+ ).toBeVisible()+ await act(async () => {+ setModeListener?.({+ tab: 'links',+ urls: 'https://example.com/ordinary.zip',+ })+ })+ expect(+ screen.queryByText('The old request settings were not copied.', {+ exact: false,+ })+ ).not.toBeInTheDocument()+ })+it('submits only valid lines and retains rejected input', async () => {const onSubmitSuccess = vi.fn()renderForm({diff --git a/src/renderer/components/add-task/advanced-panel.tsx b/src/renderer/components/add-task/advanced-panel.tsxindex ca4e5864..395da158 100644--- a/src/renderer/components/add-task/advanced-panel.tsx+++ b/src/renderer/components/add-task/advanced-panel.tsx@@ -1,4 +1,8 @@-import { ChevronRightIcon, HelpIcon } from '@renderer/components/icons'+import {+ ChevronRightIcon,+ HelpIcon,+ RemoveIcon,+} from '@renderer/components/icons'import { Button } from '@renderer/components/ui/button'import {Collapsible,@@ -10,6 +14,7 @@ import {FormField,FormItem,FormLabel,+ useFormField,} from '@renderer/components/ui/form'import { Input } from '@renderer/components/ui/input'import { Textarea } from '@renderer/components/ui/textarea'@@ -18,7 +23,7 @@ import { cn } from '@renderer/lib/utils'import { EXTERNAL_URLS } from '@shared/external-urls'import type { AddTaskFormValues } from '@shared/schemas/add-task'import { type ReactNode, useLayoutEffect, useState } from 'react'-import { useFormContext, useWatch } from 'react-hook-form'+import { useFieldArray, useFormContext, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { useAddTaskLayoutChange } from './add-task-layout-context'@@ -27,6 +32,13 @@ export function AdvancedPanel() {const [open, setOpen] = useState(false)const onLayoutChange = useAddTaskLayoutChange()const tab = useWatch<AddTaskFormValues, 'tab'>({ name: 'tab' })+ const requestOptions = useWatch<AddTaskFormValues, 'legacyRequestOptions'>({+ name: 'legacyRequestOptions',+ })++ useLayoutEffect(() => {+ if (tab === 'links' && requestOptions !== undefined) setOpen(true)+ }, [requestOptions, tab])useLayoutEffect(() => {onLayoutChange?.(open)@@ -101,6 +113,7 @@ function LinksAdvancedFields() {name="authorization"label={t('task.add.authorization')}/>+ <ExtraHeadersFields /><DenseFieldcontrol={control}name="allProxy"@@ -122,6 +135,90 @@ function LinksAdvancedFields() {)}+function ExtraHeadersFields() {+ const { t } = useTranslation()+ const { control } = useFormContext<AddTaskFormValues>()+ const { fields, append, remove } = useFieldArray({+ control,+ name: 'extraHeaders',+ })+ return (+ <fieldset className="space-y-2">+ <legend className="text-xs text-muted-foreground">+ {t('task.add.extraHeaders')}+ </legend>+ {fields.map((field, index) => (+ <div key={field.id} className="flex min-w-0 items-center gap-2">+ <FormField+ control={control}+ name={`extraHeaders.${index}.name`}+ render={({ field: nameField }) => (+ <FormItem className="min-w-0 flex-1">+ <FormLabel className="sr-only">+ {t('task.add.headerName')}+ </FormLabel>+ <FormControl>+ <Input+ {...nameField}+ placeholder={t('task.add.headerName')}+ className="h-8 text-xs"+ />+ </FormControl>+ <HeaderNameError />+ </FormItem>+ )}+ />+ <FormField+ control={control}+ name={`extraHeaders.${index}.value`}+ render={({ field: valueField }) => (+ <FormItem className="min-w-0 flex-[2]">+ <FormLabel className="sr-only">+ {t('task.add.headerValue')}+ </FormLabel>+ <FormControl>+ <Input+ {...valueField}+ placeholder={t('task.add.headerValue')}+ className="h-8 text-xs"+ />+ </FormControl>+ </FormItem>+ )}+ />+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label={t('task.add.removeHeader')}+ onClick={() => remove(index)}+ >+ <RemoveIcon aria-hidden="true" />+ </Button>+ </div>+ ))}+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => append({ name: '', value: '' })}+ >+ {t('task.add.addHeader')}+ </Button>+ </fieldset>+ )+}++function HeaderNameError() {+ const { t } = useTranslation()+ const { error, formMessageId } = useFormField()+ return error ? (+ <p id={formMessageId} role="alert" className="text-xs text-destructive">+ {t('task.add.errors.headerNameRequired')}+ </p>+ ) : null+}+function TorrentAdvancedFields() {const { unitSystem, formatByteUnit } = useByteFormat()const scale = unitSystem === 'binary' ? 1024 : 1000diff --git a/src/renderer/components/add-task/links-tab-panel.tsx b/src/renderer/components/add-task/links-tab-panel.tsxindex 6c91f3c0..18bd9526 100644--- a/src/renderer/components/add-task/links-tab-panel.tsx+++ b/src/renderer/components/add-task/links-tab-panel.tsx@@ -1,12 +1,41 @@import { DirectoryPicker } from '@renderer/components/desktop-kit/directory-picker'+import { Alert, AlertDescription } from '@renderer/components/ui/alert'+import type { AddTaskFormValues } from '@shared/schemas/add-task'+import { useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { AdvancedPanel } from './advanced-panel'import { UrlTextarea } from './url-textarea'export function LinksTabPanel() {const { t } = useTranslation()+ const requestOptions = useWatch<AddTaskFormValues, 'legacyRequestOptions'>({+ name: 'legacyRequestOptions',+ })return (<div className="flex min-h-0 min-w-0 flex-1 flex-col gap-3">+ {requestOptions !== undefined && (+ <Alert>+ <AlertDescription className="space-y-1 text-xs">+ <p>{t('legacyImport.requestSettingsDescription')}</p>+ {requestOptions.length > 0 && (+ <p className="break-words">+ {t('legacyImport.requestOptions', {+ options: requestOptions.join(', '),+ })}+ </p>+ )}+ {requestOptions.some(+ (name) =>+ [+ 'load-cookies',+ 'http-user',+ 'http-passwd',+ 'no-netrc',+ ].includes(name) || name.includes('proxy')+ ) && <p>{t('legacyImport.requestSettingsHelp')}</p>}+ </AlertDescription>+ </Alert>+ )}<UrlTextarea name="urls" autoFocus /><DirectoryPickername="saveDir"diff --git a/src/renderer/features/legacy-import/import-task-info.tsx b/src/renderer/features/legacy-import/import-task-info.tsxindex 102ff3fa..e1c1ef3c 100644--- a/src/renderer/features/legacy-import/import-task-info.tsx+++ b/src/renderer/features/legacy-import/import-task-info.tsx@@ -12,7 +12,20 @@ export function ImportTaskInfo({showReason?: boolean}) {const { t } = useTranslation()- const reason = t(`legacyImport.reasons.${item.reason}`)+ const optionNames =+ item.reason === 'unsupported-options'+ ? item.unsupportedOptions+ : item.reason === 'request-settings-required'+ ? item.requestOptions+ : undefined+ const reason = optionNames?.length+ ? t(+ item.reason === 'unsupported-options'+ ? 'legacyImport.unsupportedOptions'+ : 'legacyImport.requestOptions',+ { options: optionNames.join(', ') }+ )+ : t(`legacyImport.reasons.${item.reason}`)return (<div className="min-w-0 flex-1 space-y-0.5"><div className="flex min-w-0 items-center gap-2">diff --git a/src/renderer/features/legacy-import/legacy-fresh-download.test.tsx b/src/renderer/features/legacy-import/legacy-fresh-download.test.tsxindex fbeb5954..5a05b019 100644--- a/src/renderer/features/legacy-import/legacy-fresh-download.test.tsx+++ b/src/renderer/features/legacy-import/legacy-fresh-download.test.tsx@@ -1,12 +1,19 @@import '@test-utils/dom-animations'import '@renderer/lib/i18n'import '@testing-library/jest-dom/vitest'+import { toast } from '@renderer/components/ui/toast'+import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'-import { TaskStatus, TaskType } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { LegacyFreshDownload } from './legacy-fresh-download'@@ -16,6 +23,9 @@ vi.mock('@renderer/lib/transport', () => ({vi.mock('@renderer/lib/open-add-task-dialog', () => ({openAddTaskDialog: vi.fn(),}))+vi.mock('@renderer/components/ui/toast', () => ({+ toast: { add: vi.fn() },+}))const task = makeDownloadTask({id: 'legacy-bt',type: TaskType.Bt,@@ -25,6 +35,7 @@ const task = makeDownloadTask({describe('legacy BT activation entry', () => {beforeEach(() => {vi.mocked(transport.invoke).mockReset()+ vi.mocked(openAddTaskDialog).mockReset()})it('shows the original directory and only sends opaque task identity on explicit activation', async () => {vi.mocked(transport.invoke).mockImplementation(async (channel) =>@@ -97,3 +108,329 @@ describe('legacy BT activation entry', () => {await waitFor(() => expect(button).toBeEnabled())})})++describe('legacy HTTP activation and explicit fresh download', () => {+ const httpTask = makeDownloadTask({+ id: 'legacy-http',+ type: TaskType.Http,+ status: TaskStatus.Paused,+ saveDir: '/original/downloads',+ instances: [+ {+ instanceId: 'legacy-http-instance',+ motrixId: 'legacy-http',+ gid: null,+ phase: TaskInstancePhase.HttpDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/original/downloads',+ transitionPhase: TransitionPhase.Idle,+ uris: ['https://example.com/file.zip'],+ uriHash: null,+ createdAt: 0,+ updatedAt: 0,+ payload: {+ legacyImport: {+ version: 1,+ sourceId: 'source',+ itemKey: 'item',+ activation: 'inactive',+ storagePolicy: 'legacy-read-only',+ reason: 'request-settings-required',+ requestOptions: ['header', 'all-proxy'],+ selectionKnown: true,+ selectedFiles: [],+ },+ },+ },+ ],+ })++ beforeEach(() => {+ vi.mocked(transport.invoke).mockReset()+ vi.mocked(openAddTaskDialog).mockReset()+ vi.mocked(toast.add).mockReset()+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyHttpActivationAvailability+ ? { available: true, reason: null, directory: httpTask.saveDir }+ : false+ )+ })++ it('checks HTTP availability and resumes with only the task identity after an explicit click', async () => {+ render(<LegacyFreshDownload task={httpTask} />)+ const button = screen.getByRole('button', { name: 'Verify and continue' })+ await waitFor(() => expect(button).toBeEnabled())+ expect(transport.invoke).toHaveBeenCalledExactlyOnceWith(+ Queries.GetLegacyHttpActivationAvailability,+ { taskId: httpTask.id }+ )+ expect(screen.getByText(httpTask.saveDir)).toBeVisible()+ expect(+ screen.getByText('Saved request settings: header, all-proxy')+ ).toBeVisible()+ expect(+ screen.getByText('Motrix will compare all downloaded ranges', {+ exact: false,+ })+ ).toHaveTextContent('saved request settings stay in memory.')+ expect(+ screen.queryByText('The old request settings were not copied.', {+ exact: false,+ })+ ).not.toBeInTheDocument()+ fireEvent.click(button)+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.ActivateLegacyHttp,+ {+ taskId: httpTask.id,+ }+ )+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.PrepareLegacyFreshDownload,+ expect.anything()+ )+ expect(openAddTaskDialog).not.toHaveBeenCalled()+ })++ it('offers verification for HTTP records without custom request settings', async () => {+ render(<LegacyFreshDownload task={{ ...httpTask, instances: [] }} />)+ const button = screen.getByRole('button', { name: 'Verify and continue' })+ await waitFor(() => expect(button).toBeEnabled())+ expect(+ screen.getByRole('button', { name: 'Download again…' })+ ).toBeEnabled()+ fireEvent.click(button)+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.ActivateLegacyHttp,+ {+ taskId: httpTask.id,+ }+ )+ )+ })++ it('disables unavailable HTTP resume and keeps a manual fallback without launching it', async () => {+ vi.mocked(transport.invoke).mockResolvedValue({+ available: false,+ reason: 'legacyImport.errors.controlRequired',+ directory: httpTask.saveDir,+ })+ render(<LegacyFreshDownload task={httpTask} />)+ await screen.findByText(+ 'The saved download progress is missing. Download again in a new folder.'+ )+ expect(+ screen.getByRole('button', { name: 'Verify and continue' })+ ).toBeDisabled()+ expect(+ screen.getByRole('button', { name: 'Reconfigure and download…' })+ ).toBeEnabled()+ expect(transport.invoke).toHaveBeenCalledTimes(1)+ expect(openAddTaskDialog).not.toHaveBeenCalled()+ })++ it('explains verification traffic, blocks duplicate activation, and permits cancellation', async () => {+ let complete: (value: boolean) => void = () => {}+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetLegacyHttpActivationAvailability)+ return { available: true, reason: null, directory: httpTask.saveDir }+ if (channel === Commands.ActivateLegacyHttp)+ return new Promise((resolve) => {+ complete = resolve+ })+ return true+ })+ render(<LegacyFreshDownload task={httpTask} />)+ const button = screen.getByRole('button', { name: 'Verify and continue' })+ await waitFor(() => expect(button).toBeEnabled())+ fireEvent.click(button)+ fireEvent.click(button)+ expect(screen.getByRole('status')).toHaveTextContent(+ 'Preparing or verifying…'+ )+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(+ ([channel]) => channel === Commands.ActivateLegacyHttp+ )+ ).toHaveLength(1)+ expect(+ screen.getByRole('button', { name: 'Reconfigure and download…' })+ ).toBeDisabled()+ const cancel = screen.getByRole('button', { name: 'Cancel' })+ fireEvent.click(cancel)+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.CancelLegacyHttpActivation,+ { taskId: httpTask.id }+ )+ )+ expect(cancel).toBeDisabled()+ await act(async () => complete(false))+ expect(button).toBeEnabled()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ expect(openAddTaskDialog).not.toHaveBeenCalled()+ })++ it.each([TaskType.Http, TaskType.Bt, TaskType.Magnet])(+ 'keeps cancellation bound to its original HTTP task after selecting %s',+ async (nextType) => {+ let complete: (value: boolean) => void = () => {}+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Commands.ActivateLegacyHttp)+ return new Promise((resolve) => {+ complete = resolve+ })+ if (channel === Commands.CancelLegacyHttpActivation) return true+ return { available: true, reason: null, directory: httpTask.saveDir }+ })+ const { rerender } = render(<LegacyFreshDownload task={httpTask} />)+ const start = screen.getByRole('button', { name: 'Verify and continue' })+ await waitFor(() => expect(start).toBeEnabled())+ fireEvent.click(start)+ const next = makeDownloadTask({+ id: 'other-task',+ name: 'other-file',+ type: nextType,+ })+ rerender(<LegacyFreshDownload task={next} />)+ expect(screen.getByRole('status')).toHaveTextContent(httpTask.name)+ expect(screen.getByRole('status')).not.toHaveTextContent('other-file')+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.CancelLegacyHttpActivation,+ { taskId: httpTask.id }+ )+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.CancelLegacyHttpActivation,+ { taskId: next.id }+ )+ await act(async () => complete(false))+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ }+ )++ it.each([+ [+ 'httpContentChanged',+ 'The downloaded data differs from the server content.',+ ],+ [+ 'httpRangeUnsupported',+ 'The server does not support the required byte ranges.',+ ],+ [+ 'httpValidatorRequired',+ 'The server does not provide a strong resource version.',+ ],+ ['httpVerificationFailed', 'Could not verify the downloaded data.'],+ [+ 'httpRequestUnsupported',+ 'The engine or request settings do not support safe resume.',+ ],+ ['httpVerificationCancelled', 'Verification cancelled.'],+ [+ 'httpRedirectUnsupported',+ 'Redirected links cannot be safely resumed in place.',+ ],+ ])(+ 'reports %s and never starts a new download automatically',+ async (code, message) => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetLegacyHttpActivationAvailability)+ return { available: true, reason: null, directory: httpTask.saveDir }+ throw new Error(`legacyImport.errors.${code}`)+ })+ render(<LegacyFreshDownload task={httpTask} />)+ const button = screen.getByRole('button', { name: 'Verify and continue' })+ await waitFor(() => expect(button).toBeEnabled())+ fireEvent.click(button)+ await waitFor(() =>+ expect(toast.add).toHaveBeenCalledWith({+ type: 'error',+ title: expect.stringContaining(message),+ description: 'Your existing files were kept.',+ })+ )+ expect(button).toBeEnabled()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.PrepareLegacyFreshDownload,+ expect.anything()+ )+ expect(openAddTaskDialog).not.toHaveBeenCalled()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ }+ )++ it('requires confirmation and hands the settings reminder to the download form', async () => {+ const prefill = {+ tab: 'links' as const,+ urls: 'https://example.com/file.zip',+ saveDir: '/new/downloads',+ legacyRequestOptions: ['header', 'all-proxy'],+ }+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyHttpActivationAvailability+ ? { available: true, reason: null, directory: httpTask.saveDir }+ : prefill+ )+ render(<LegacyFreshDownload task={httpTask} />)+ await waitFor(() => expect(transport.invoke).toHaveBeenCalledTimes(1))+ fireEvent.click(+ screen.getByRole('button', { name: 'Reconfigure and download…' })+ )+ expect(screen.getByRole('alertdialog')).toHaveTextContent(+ 'The old request settings were not copied.'+ )+ expect(screen.getByRole('alertdialog')).toHaveTextContent(+ 'It will start from the beginning and leave your old files untouched.'+ )+ expect(transport.invoke).toHaveBeenCalledTimes(1)+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(transport.invoke).toHaveBeenCalledTimes(1)+ fireEvent.click(+ screen.getByRole('button', { name: 'Reconfigure and download…' })+ )+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ await waitFor(() => expect(openAddTaskDialog).toHaveBeenCalledWith(prefill))+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.PrepareLegacyFreshDownload,+ { taskId: httpTask.id }+ )+ expect(transport.invoke).toHaveBeenCalledTimes(2)+ })++ it('keeps the confirmation open when choosing a new destination is cancelled', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyHttpActivationAvailability+ ? { available: true, reason: null, directory: httpTask.saveDir }+ : null+ )+ render(<LegacyFreshDownload task={httpTask} />)+ fireEvent.click(+ screen.getByRole('button', { name: 'Reconfigure and download…' })+ )+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ await waitFor(() =>+ expect(+ screen.getByRole('button', { name: 'Choose another location…' })+ ).toBeEnabled()+ )+ expect(screen.getByRole('alertdialog')).toBeVisible()+ expect(openAddTaskDialog).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/features/legacy-import/legacy-fresh-download.tsx b/src/renderer/features/legacy-import/legacy-fresh-download.tsxindex 0ab62184..37055f85 100644--- a/src/renderer/features/legacy-import/legacy-fresh-download.tsx+++ b/src/renderer/features/legacy-import/legacy-fresh-download.tsx@@ -14,26 +14,57 @@ import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'import { legacyBtAvailabilitySchema } from '@shared/schemas/legacy-bt-activation'+import { legacyHttpAvailabilitySchema } from '@shared/schemas/legacy-http-activation'+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'import type { AddTaskPrefill } from '@shared/schemas/show-add-task-window'import type { DownloadTask } from '@shared/types/task'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+type PendingOperation = Pick<DownloadTask, 'id' | 'name' | 'type'> & {+ kind: 'activate' | 'prepare'+}+export function LegacyFreshDownload({ task }: { task: DownloadTask }) {const { t } = useTranslation()+ const marker = legacyTaskMetadataSchema.safeParse(+ task.instances[0]?.payload.legacyImport+ )+ const requiresRequestSettings =+ task.type === 'http' &&+ marker.success &&+ marker.data.reason === 'request-settings-required'+ const requestOptions = marker.success ? marker.data.requestOptions : undefined+ const freshDownloadLabel = t(+ requiresRequestSettings+ ? 'legacyImport.reconfigureDownload'+ : 'legacyImport.freshDownload'+ )const [open, setOpen] = useState(false)- const [busy, setBusy] = useState(false)- const inFlight = useRef(false)+ const [operation, setOperation] = useState<PendingOperation | null>(null)+ const [cancelling, setCancelling] = useState(false)+ const busy = operation !== null+ const inFlight = useRef<PendingOperation | null>(null)const [availability, setAvailability] = useState<ReturnType<typeof legacyBtAvailabilitySchema.parse> | null>(null)useEffect(() => {let current = truesetAvailability(null)+ if (task.type !== 'bt' && task.type !== 'http') return+ const schema =+ task.type === 'http'+ ? legacyHttpAvailabilitySchema+ : legacyBtAvailabilitySchemavoid transport- .invoke(Queries.GetLegacyBtActivationAvailability, { taskId: task.id })+ .invoke(+ task.type === 'http'+ ? Queries.GetLegacyHttpActivationAvailability+ : Queries.GetLegacyBtActivationAvailability,+ { taskId: task.id }+ ).then((value) => {- if (current) setAvailability(legacyBtAvailabilitySchema.parse(value))+ if (current) setAvailability(schema.parse(value))}).catch(() => {if (current)@@ -46,28 +77,72 @@ export function LegacyFreshDownload({ task }: { task: DownloadTask }) {return () => {current = false}- }, [task.id, task.saveDir])+ }, [task.id, task.saveDir, task.type])const activate = async () => {if (inFlight.current) return- inFlight.current = true- setBusy(true)+ const pending: PendingOperation = {+ id: task.id,+ name: task.name,+ type: task.type,+ kind: 'activate',+ }+ inFlight.current = pending+ setOperation(pending)+ setCancelling(false)try {- await transport.invoke(Commands.ActivateLegacyBt, { taskId: task.id })+ await transport.invoke(+ task.type === 'http'+ ? Commands.ActivateLegacyHttp+ : Commands.ActivateLegacyBt,+ { taskId: task.id }+ )} catch (cause) {const key = String(cause).match(/legacyImport\.errors\.[a-zA-Z]+/)?.[0]toast.add({title: key ? t(key) : t('legacyImport.errors.failed'),+ ...(task.type === 'http' && {+ description: t('legacyImport.httpOriginalFilesKept'),+ }),type: 'error',})} finally {- inFlight.current = false- setBusy(false)+ inFlight.current = null+ setOperation(null)+ setCancelling(false)+ }+ }+ const cancelActivation = async () => {+ if (+ operation?.kind !== 'activate' ||+ cancelling ||+ operation.type !== 'http'+ )+ return+ const pending = operation+ setCancelling(true)+ try {+ await transport.invoke(Commands.CancelLegacyHttpActivation, {+ taskId: pending.id,+ })+ } catch (cause) {+ const key = String(cause).match(/legacyImport\.errors\.[a-zA-Z]+/)?.[0]+ toast.add({+ title: key ? t(key) : t('legacyImport.errors.failed'),+ type: 'error',+ })+ if (inFlight.current === pending) setCancelling(false)}}const prepare = async () => {if (inFlight.current) return- inFlight.current = true- setBusy(true)+ const pending: PendingOperation = {+ id: task.id,+ name: task.name,+ type: task.type,+ kind: 'prepare',+ }+ inFlight.current = pending+ setOperation(pending)try {const prefill = (await transport.invoke(Commands.PrepareLegacyFreshDownload,@@ -84,24 +159,33 @@ export function LegacyFreshDownload({ task }: { task: DownloadTask }) {type: 'error',})} finally {- inFlight.current = false- setBusy(false)+ inFlight.current = null+ setOperation(null)}}return (<><div className="space-y-3 rounded-md border p-3"><p className="text-xs leading-5 text-muted-foreground">- {task.type === 'bt'- ? availability?.available- ? t('legacyImport.verifyReady')- : t(availability?.reason ?? 'legacyImport.loading')- : t('legacyImport.capabilityLimit')}+ {availability?.available+ ? t('legacyImport.verifyReady')+ : t(availability?.reason ?? 'legacyImport.loading')}</p>- {task.type === 'bt' && (+ {requiresRequestSettings && Boolean(requestOptions?.length) && (+ <p className="break-words text-xs leading-5 text-muted-foreground">+ {t('legacyImport.requestOptions', {+ options: requestOptions?.join(', '),+ })}+ </p>+ )}+ {(task.type === 'bt' || task.type === 'http') && (<div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">- {t('legacyImport.verifyDescription')}+ {t(+ task.type === 'http'+ ? 'legacyImport.httpResumeDescription'+ : 'legacyImport.verifyDescription'+ )}</p><p className="min-w-0 text-xs"><MiddleEllipsis@@ -119,13 +203,34 @@ export function LegacyFreshDownload({ task }: { task: DownloadTask }) {</Button></div>)}+ {operation?.type === 'http' && operation.kind === 'activate' && (+ <div className="space-y-2">+ <p+ role="status"+ className="text-xs leading-5 text-muted-foreground"+ >+ <span className="block font-medium">+ <MiddleEllipsis text={operation.name} className="font-sans!" />+ </span>+ {t('legacyImport.httpVerifying')}+ </p>+ <Button+ size="sm"+ variant="outline"+ disabled={cancelling}+ onClick={() => void cancelActivation()}+ >+ {t('common.cancel')}+ </Button>+ </div>+ )}<Buttonsize="sm"variant="outline"onClick={() => setOpen(true)}disabled={busy}>- {t('legacyImport.freshDownload')}+ {freshDownloadLabel}</Button></div><AlertDialog@@ -136,11 +241,14 @@ export function LegacyFreshDownload({ task }: { task: DownloadTask }) {><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>- {t('legacyImport.freshDownload')}- </AlertDialogTitle>+ <AlertDialogTitle>{freshDownloadLabel}</AlertDialogTitle><AlertDialogDescription>{t('legacyImport.freshDescription')}+ {requiresRequestSettings && (+ <span className="mt-2 block">+ {t('legacyImport.requestSettingsDescription')}+ </span>+ )}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsxindex 07d074ec..0edb9537 100644--- a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx+++ b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx@@ -97,6 +97,70 @@ describe('legacy import dialog', () => {})})+ it('selects HTTP records with saved request settings and explains verification and blocked options', async () => {+ const originalInvoke = vi.mocked(transport.invoke).getMockImplementation()+ vi.mocked(transport.invoke).mockImplementation(async (channel, payload) => {+ if (channel === Queries.ScanLegacyImport)+ return {+ ...preview,+ items: [+ {+ ...items[0],+ reason: 'request-settings-required',+ requestOptions: ['header', 'all-proxy'],+ },+ {+ ...items[0],+ itemId: 'blocked',+ name: 'blocked.zip',+ selectable: false,+ reason: 'unsupported-options',+ unsupportedOptions: ['on-download-complete'],+ },+ {+ ...items[0],+ itemId: 'old-preview',+ name: 'old-preview.zip',+ selectable: false,+ reason: 'unsupported-options',+ },+ ],+ }+ return originalInvoke?.(channel, payload)+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ expect(screen.getByRole('checkbox', { name: 'archive.zip' })).toBeChecked()+ expect(+ screen.getByRole('checkbox', { name: 'archive.zip' })+ ).not.toHaveAttribute('aria-disabled', 'true')+ expect(+ screen.getByRole('checkbox', { name: 'blocked.zip' })+ ).toHaveAttribute('aria-disabled', 'true')+ expect(+ screen.getByText('Saved request settings: header, all-proxy')+ ).toBeVisible()+ expect(+ screen.getByText('Unsupported options: on-download-complete')+ ).toBeVisible()+ expect(screen.getByText('Unsupported download options')).toBeVisible()+ expect(+ screen.getByText('Motrix will compare all downloaded ranges', {+ exact: false,+ })+ ).toBeVisible()+ fireEvent.click(screen.getByRole('button', { name: 'Migrate' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ {+ previewId,+ itemIds: [items[0].itemId],+ }+ )+ )+ })+it('starts at source for manual entry and preserves deselection when returning to the same source', async () => {render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)expect(diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.tsxindex c07a61a3..1126778d 100644--- a/src/renderer/features/legacy-import/legacy-import-dialog.tsx+++ b/src/renderer/features/legacy-import/legacy-import-dialog.tsx@@ -846,6 +846,18 @@ function LegacyImportDialogContent({className="pt-4 pb-5"/>{errorNotice}+ {preview?.items.some(+ (item) => item.type === 'http' && item.selectable+ ) && (+ <Alert+ role="note"+ className="mx-auto mb-3 w-full max-w-160 shrink-0"+ >+ <AlertDescription className="text-xs">+ {t('legacyImport.httpResumeDescription')}+ </AlertDescription>+ </Alert>+ )}{preview?.running && (<Alert className="mx-auto mb-3 w-full max-w-160 shrink-0"><WarningIcon aria-hidden="true" />diff --git a/src/server/ipc/legacy-import.test.ts b/src/server/ipc/legacy-import.test.tsindex 889445c2..b44d86a1 100644--- a/src/server/ipc/legacy-import.test.ts+++ b/src/server/ipc/legacy-import.test.ts@@ -12,7 +12,7 @@ describe('server legacy import boundary', () => {...unsupportedLegacyImportCommands(),...unsupportedLegacyImportQueries(),}- expect(Object.keys(handlers)).toHaveLength(16)+ expect(Object.keys(handlers)).toHaveLength(19)await expect(handlers[Queries.GetLegacyImportNavigation]?.()).resolves.toEqual({ detected: false, invitationPending: false })diff --git a/src/server/ipc/legacy-import.ts b/src/server/ipc/legacy-import.tsindex aafd2701..c6a44dbf 100644--- a/src/server/ipc/legacy-import.ts+++ b/src/server/ipc/legacy-import.ts@@ -17,6 +17,8 @@ async function desktopOnly(): Promise<never> {export function unsupportedLegacyImportCommands(): CommandHandlerMap {return {[Commands.ActivateLegacyBt]: desktopOnly,+ [Commands.ActivateLegacyHttp]: desktopOnly,+ [Commands.CancelLegacyHttpActivation]: desktopOnly,[Commands.PickLegacyImportSource]: desktopOnly,[Commands.RevealLegacyImportSource]: desktopOnly,[Commands.PickLegacyTorrentMetadata]: desktopOnly,@@ -37,6 +39,7 @@ export function unsupportedLegacyImportQueries(): QueryHandlerMap {invitationPending: false,}),[Queries.GetLegacyBtActivationAvailability]: desktopOnly,+ [Queries.GetLegacyHttpActivationAvailability]: desktopOnly,[Queries.DiscoverLegacyImport]: desktopOnly,[Queries.ScanLegacyImport]: desktopOnly,[Queries.GetLegacyImportRun]: desktopOnly,diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 0577dabc..eed6968c 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -2811,6 +2811,11 @@},"task": {"add": {+ "extraHeaders": "ترويسات إضافية",+ "headerName": "اسم الترويسة",+ "headerValue": "قيمة الترويسة",+ "addHeader": "إضافة ترويسة",+ "removeHeader": "إزالة الترويسة","adding": "جارٍ الإضافة…","advanced": "متقدم","allProxy": "الوكيل",@@ -2841,6 +2846,7 @@"title": "هذا التورنت موجود بالفعل"},"errors": {+ "headerNameRequired": "أدخل اسم الترويسة أو أزل هذه الترويسة.","missingSource": "يلزم ملف تورنت أو رابط magnet","noFilesSelected": "حدد ملفًا واحدًا على الأقل","saveDirRequired": "يلزم تحديد مجلد الحفظ",@@ -3234,12 +3240,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "بالنسبة إلى ملفات تعريف الارتباط القديمة، أدخل ترويسة Cookie المطلوبة. ولأسماء مستخدمي HTTP وكلمات مرورهم، أدخل ترويسة Authorization المكافئة. أدخل بيانات اعتماد الوكيل في عنوان URL للوكيل.",+ "unsupportedOptions": "الخيارات غير المدعومة: {{options}}",+ "requestOptions": "إعدادات الطلب المحفوظة: {{options}}",+ "requestSettingsDescription": "لم تُنسخ إعدادات الطلب القديمة. أدخلها مجددًا في الإعدادات المتقدمة قبل التنزيل إلى مجلد جديد.",+ "reconfigureDownload": "إعادة الإعداد والتنزيل…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "سيتم فحص إعدادات الطلب المحفوظة قبل الاستئناف",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "خيارات تنزيل غير مدعومة","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3282,14 +3295,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "تختلف البيانات المنزّلة عن محتوى الخادم.",+ "httpRangeUnsupported": "لا يدعم الخادم نطاقات البايت المطلوبة.",+ "httpValidatorRequired": "لا يوفر الخادم معرّفًا موثوقًا لإصدار المورد.",+ "httpVerificationFailed": "تعذر التحقق من البيانات المنزّلة.",+ "httpRequestUnsupported": "لا يدعم المحرك أو إعدادات الطلب الاستئناف الآمن.",+ "httpVerificationCancelled": "تم إلغاء التحقق.",+ "httpRedirectUnsupported": "لا يمكن استئناف الروابط المعاد توجيهها بأمان في الموقع الأصلي."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "افتح تفاصيل المهمة للتحقق من التنزيل واستئنافه.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "التحقق والمتابعة","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3407,7 +3427,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "سيقارن Motrix جميع النطاقات المنزّلة بالخادم ثم يتابع في المجلد الأصلي. ينقل التحقق هذه النطاقات مجددًا؛ وتبقى إعدادات الطلب المحفوظة في الذاكرة.",+ "httpVerifying": "جارٍ الإعداد أو التحقق…",+ "httpOriginalFilesKept": "تم الاحتفاظ بملفاتك الموجودة."},"rendererRecovery": {"title": "تحتاج الواجهة إلى الاستعادة",diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 3746e78f..b07e189b 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -2731,6 +2731,11 @@},"task": {"add": {+ "extraHeaders": "Допълнителни заглавки",+ "headerName": "Име на заглавката",+ "headerValue": "Стойност на заглавката",+ "addHeader": "Добавяне на заглавка",+ "removeHeader": "Премахване на заглавка","adding": "Добавяне…","advanced": "Разширени","allProxy": "Прокси",@@ -2761,6 +2766,7 @@"title": "Този торент вече съществува"},"errors": {+ "headerNameRequired": "Въведете име на заглавката или я премахнете.","missingSource": "Необходим е торент файл или magnet връзка","noFilesSelected": "Изберете поне един файл","saveDirRequired": "Необходима е папка за запазване",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "За старите файлове с бисквитки въведете необходимата заглавка Cookie. За HTTP потребителски имена и пароли въведете еквивалентна заглавка Authorization. Въведете данните за достъп до прокси сървъра в неговия URL адрес.",+ "unsupportedOptions": "Неподдържани опции: {{options}}",+ "requestOptions": "Запазени настройки на заявките: {{options}}",+ "requestSettingsDescription": "Старите настройки на заявките не са копирани. Въведете ги отново в разширените настройки, преди да изтеглите в нова папка.",+ "reconfigureDownload": "Настройване отново и изтегляне…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Запазените настройки на заявките ще бъдат проверени преди продължаване",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Неподдържани опции за изтегляне","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Изтеглените данни се различават от съдържанието на сървъра.",+ "httpRangeUnsupported": "Сървърът не поддържа необходимите диапазони от байтове.",+ "httpValidatorRequired": "Сървърът не предоставя надежден идентификатор на версията на ресурса.",+ "httpVerificationFailed": "Изтеглените данни не могат да бъдат проверени.",+ "httpRequestUnsupported": "Модулът или настройките на заявките не поддържат безопасно продължаване.",+ "httpVerificationCancelled": "Проверката е отменена.",+ "httpRedirectUnsupported": "Пренасочени връзки не могат да продължат безопасно на оригиналното място."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Отворете подробностите за задачата, за да проверите и продължите изтеглянето.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Проверка и продължаване","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix ще сравни всички изтеглени диапазони със сървъра и ще продължи в оригиналната папка. Проверката прехвърля тези диапазони отново; запазените настройки на заявките остават в паметта.",+ "httpVerifying": "Подготовка или проверка…",+ "httpOriginalFilesKept": "Съществуващите файлове са запазени."},"rendererRecovery": {"title": "Интерфейсът трябва да бъде възстановен",diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex aa599058..267afc74 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -2751,6 +2751,11 @@},"task": {"add": {+ "extraHeaders": "Capçaleres addicionals",+ "headerName": "Nom de la capçalera",+ "headerValue": "Valor de la capçalera",+ "addHeader": "Afegeix una capçalera",+ "removeHeader": "Elimina la capçalera","adding": "S'està afegint…","advanced": "Opcions avançades","allProxy": "Servidor intermediari",@@ -2781,6 +2786,7 @@"title": "Aquest torrent ja existeix"},"errors": {+ "headerNameRequired": "Introduïu un nom per a la capçalera o elimineu-la.","missingSource": "Cal un fitxer torrent o un enllaç magnet","noFilesSelected": "Seleccioneu almenys un fitxer","saveDirRequired": "Cal una carpeta de destinació",@@ -3168,12 +3174,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Per als fitxers de galetes anteriors, introduïu la capçalera Cookie necessària. Per als noms d’usuari i contrasenyes HTTP, introduïu una capçalera Authorization equivalent. Introduïu les credencials del servidor intermediari a l’URL del servidor intermediari.",+ "unsupportedOptions": "Opcions no compatibles: {{options}}",+ "requestOptions": "Configuració de petició desada: {{options}}",+ "requestSettingsDescription": "La configuració antiga de petició no s’ha copiat. Torna-la a introduir a Avançat abans de baixar en una carpeta nova.",+ "reconfigureDownload": "Torna a configurar i baixa…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Es comprovarà la configuració de petició desada abans de reprendre",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Opcions de baixada no compatibles","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3216,14 +3229,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Les dades baixades difereixen del contingut del servidor.",+ "httpRangeUnsupported": "El servidor no admet els intervals de bytes necessaris.",+ "httpValidatorRequired": "El servidor no proporciona un identificador fiable de la versió del recurs.",+ "httpVerificationFailed": "No s’han pogut verificar les dades baixades.",+ "httpRequestUnsupported": "El motor o la configuració de petició no permeten reprendre amb seguretat.",+ "httpVerificationCancelled": "Verificació cancel·lada.",+ "httpRedirectUnsupported": "Els enllaços redirigits no es poden reprendre amb seguretat a la ubicació original."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Obre els detalls de la tasca per verificar i reprendre la baixada.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Verifica i continua","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3335,7 +3355,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix compararà tots els intervals baixats amb el servidor i continuarà a la carpeta original. La verificació torna a transferir aquests intervals; la configuració de petició desada roman a la memòria.",+ "httpVerifying": "Preparant o verificant…",+ "httpOriginalFilesKept": "S’han conservat els fitxers existents."},"rendererRecovery": {"title": "Cal recuperar la interfície",diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex 02980ea7..bd336d37 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -1021,6 +1021,11 @@},"task": {"add": {+ "extraHeaders": "Zusätzliche Header",+ "headerName": "Headername",+ "headerValue": "Headerwert",+ "addHeader": "Header hinzufügen",+ "removeHeader": "Header entfernen","title": "Neue Aufgabe","links": "Links","torrent": "Torrent",@@ -1114,6 +1119,7 @@"doc": "Dokument"},"errors": {+ "headerNameRequired": "Geben Sie einen Headernamen ein oder entfernen Sie diesen Header.","urlsRequired": "Mindestens eine URL ist erforderlich","saveDirRequired": "Ein Speicherordner ist erforderlich","noFilesSelected": "Wählen Sie mindestens eine Datei aus",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Geben Sie für alte Cookie-Dateien den benötigten Cookie-Header ein. Geben Sie für HTTP-Benutzernamen und -Passwörter einen entsprechenden Authorization-Header ein. Tragen Sie Proxy-Zugangsdaten in die Proxy-URL ein.",+ "unsupportedOptions": "Nicht unterstützte Optionen: {{options}}",+ "requestOptions": "Gespeicherte Anfrageeinstellungen: {{options}}",+ "requestSettingsDescription": "Die alten Anfrageeinstellungen wurden nicht kopiert. Gib sie unter Erweitert erneut ein, bevor du in einen neuen Ordner herunterlädst.",+ "reconfigureDownload": "Neu konfigurieren und herunterladen…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Gespeicherte Anfrageeinstellungen werden vor dem Fortsetzen geprüft",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Nicht unterstützte Downloadoptionen","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Die geladenen Daten unterscheiden sich vom Serverinhalt.",+ "httpRangeUnsupported": "Der Server unterstützt die erforderlichen Bytebereiche nicht.",+ "httpValidatorRequired": "Der Server liefert keine verlässliche Ressourcenversionskennung.",+ "httpVerificationFailed": "Die geladenen Daten konnten nicht geprüft werden.",+ "httpRequestUnsupported": "Die Engine oder Anfrageeinstellungen unterstützen keine sichere Fortsetzung.",+ "httpVerificationCancelled": "Prüfung abgebrochen.",+ "httpRedirectUnsupported": "Weitergeleitete Links können nicht sicher am ursprünglichen Ort fortgesetzt werden."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Öffne die Aufgabendetails, um den Download zu prüfen und fortzusetzen.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Prüfen und fortsetzen","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix vergleicht alle geladenen Bereiche mit dem Server und fährt dann im ursprünglichen Ordner fort. Die Prüfung überträgt diese Bereiche erneut; gespeicherte Anfrageeinstellungen bleiben im Arbeitsspeicher.",+ "httpVerifying": "Wird vorbereitet oder geprüft…",+ "httpOriginalFilesKept": "Die vorhandenen Dateien wurden beibehalten."},"rendererRecovery": {"title": "Die Oberfläche muss wiederhergestellt werden",diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex 77586548..8a473059 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -2731,6 +2731,11 @@},"task": {"add": {+ "extraHeaders": "Πρόσθετες κεφαλίδες",+ "headerName": "Όνομα κεφαλίδας",+ "headerValue": "Τιμή κεφαλίδας",+ "addHeader": "Προσθήκη κεφαλίδας",+ "removeHeader": "Αφαίρεση κεφαλίδας","adding": "Προσθήκη…","advanced": "Για προχωρημένους","allProxy": "Διακομιστής μεσολάβησης",@@ -2761,6 +2766,7 @@"title": "Αυτό το torrent υπάρχει ήδη"},"errors": {+ "headerNameRequired": "Εισαγάγετε όνομα κεφαλίδας ή αφαιρέστε αυτήν την κεφαλίδα.","missingSource": "Απαιτείται αρχείο torrent ή σύνδεσμος magnet","noFilesSelected": "Επιλέξτε τουλάχιστον ένα αρχείο","saveDirRequired": "Απαιτείται φάκελος αποθήκευσης",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Για παλιά αρχεία cookie, εισαγάγετε την απαιτούμενη κεφαλίδα Cookie. Για ονόματα χρήστη και κωδικούς HTTP, εισαγάγετε μια αντίστοιχη κεφαλίδα Authorization. Εισαγάγετε τα διαπιστευτήρια του διακομιστή μεσολάβησης στη διεύθυνση URL του.",+ "unsupportedOptions": "Μη υποστηριζόμενες επιλογές: {{options}}",+ "requestOptions": "Αποθηκευμένες ρυθμίσεις αιτήματος: {{options}}",+ "requestSettingsDescription": "Οι παλιές ρυθμίσεις αιτήματος δεν αντιγράφηκαν. Εισαγάγετέ τις ξανά στις σύνθετες ρυθμίσεις πριν από τη λήψη σε νέο φάκελο.",+ "reconfigureDownload": "Νέα ρύθμιση και λήψη…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Οι αποθηκευμένες ρυθμίσεις αιτήματος θα ελεγχθούν πριν από τη συνέχιση",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Μη υποστηριζόμενες επιλογές λήψης","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Τα ληφθέντα δεδομένα διαφέρουν από το περιεχόμενο του διακομιστή.",+ "httpRangeUnsupported": "Ο διακομιστής δεν υποστηρίζει τα απαιτούμενα εύρη byte.",+ "httpValidatorRequired": "Ο διακομιστής δεν παρέχει αξιόπιστο αναγνωριστικό έκδοσης του πόρου.",+ "httpVerificationFailed": "Δεν ήταν δυνατή η επαλήθευση των ληφθέντων δεδομένων.",+ "httpRequestUnsupported": "Η μηχανή ή οι ρυθμίσεις αιτήματος δεν επιτρέπουν ασφαλή συνέχιση.",+ "httpVerificationCancelled": "Η επαλήθευση ακυρώθηκε.",+ "httpRedirectUnsupported": "Οι σύνδεσμοι με ανακατεύθυνση δεν μπορούν να συνεχιστούν με ασφάλεια στην αρχική θέση."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Ανοίξτε τις λεπτομέρειες της εργασίας για επαλήθευση και συνέχιση της λήψης.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Επαλήθευση και συνέχεια","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Το Motrix θα συγκρίνει όλα τα ληφθέντα τμήματα με τον διακομιστή και θα συνεχίσει στον αρχικό φάκελο. Η επαλήθευση μεταφέρει ξανά αυτά τα τμήματα· οι αποθηκευμένες ρυθμίσεις αιτήματος παραμένουν στη μνήμη.",+ "httpVerifying": "Προετοιμασία ή επαλήθευση…",+ "httpOriginalFilesKept": "Τα υπάρχοντα αρχεία διατηρήθηκαν."},"rendererRecovery": {"title": "Η διεπαφή χρειάζεται επαναφορά",diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 49dd3cc4..124ee0b6 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1021,6 +1021,11 @@},"task": {"add": {+ "extraHeaders": "Extra headers",+ "headerName": "Header name",+ "headerValue": "Header value",+ "addHeader": "Add header",+ "removeHeader": "Remove header","title": "New Task","links": "Links","torrent": "Torrent",@@ -1114,6 +1119,7 @@"doc": "Document"},"errors": {+ "headerNameRequired": "Enter a header name or remove this header.","urlsRequired": "At least one URL is required","saveDirRequired": "Save directory is required","noFilesSelected": "Select at least one file",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "For old cookie files, enter the needed Cookie header. For HTTP usernames and passwords, enter an equivalent Authorization header. Enter proxy credentials in the proxy URL.",+ "unsupportedOptions": "Unsupported options: {{options}}",+ "requestOptions": "Saved request settings: {{options}}",+ "requestSettingsDescription": "The old request settings were not copied. Enter them again in Advanced before downloading in a new folder.",+ "reconfigureDownload": "Reconfigure and download…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Saved request settings will be checked before resuming",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Unsupported download options","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,11 +3207,18 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "The downloaded data differs from the server content.",+ "httpRangeUnsupported": "The server does not support the required byte ranges.",+ "httpValidatorRequired": "The server does not provide a strong resource version.",+ "httpVerificationFailed": "Could not verify the downloaded data.",+ "httpRequestUnsupported": "The engine or request settings do not support safe resume.",+ "httpVerificationCancelled": "Verification cancelled.",+ "httpRedirectUnsupported": "Redirected links cannot be safely resumed in place."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Open task details to verify and resume the download.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file","verifyAndContinue": "Verify and continue",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix will compare all downloaded ranges with the server, then continue in the original folder. Verification transfers those ranges again; saved request settings stay in memory.",+ "httpVerifying": "Preparing or verifying…",+ "httpOriginalFilesKept": "Your existing files were kept."},"rendererRecovery": {"title": "The interface needs to recover",diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex 22203590..9fa8ef8b 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -1033,6 +1033,11 @@},"task": {"add": {+ "extraHeaders": "Cabeceras adicionales",+ "headerName": "Nombre de la cabecera",+ "headerValue": "Valor de la cabecera",+ "addHeader": "Añadir cabecera",+ "removeHeader": "Eliminar cabecera","title": "Nueva tarea","links": "Enlaces","torrent": "Torrent",@@ -1126,6 +1131,7 @@"doc": "Documento"},"errors": {+ "headerNameRequired": "Introduce un nombre para la cabecera o elimínala.","urlsRequired": "Se requiere al menos una URL","saveDirRequired": "Se requiere una carpeta de destino","noFilesSelected": "Selecciona al menos un archivo",@@ -3168,12 +3174,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Para los archivos de cookies anteriores, introduce la cabecera Cookie necesaria. Para los nombres de usuario y contraseñas HTTP, introduce una cabecera Authorization equivalente. Introduce las credenciales del proxy en su URL.",+ "unsupportedOptions": "Opciones no compatibles: {{options}}",+ "requestOptions": "Ajustes de solicitud guardados: {{options}}",+ "requestSettingsDescription": "Los ajustes de solicitud anteriores no se copiaron. Vuelve a introducirlos en Avanzado antes de descargar en una carpeta nueva.",+ "reconfigureDownload": "Volver a configurar y descargar…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Se comprobarán los ajustes de solicitud guardados antes de reanudar",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Opciones de descarga no compatibles","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3216,14 +3229,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Los datos descargados no coinciden con el contenido del servidor.",+ "httpRangeUnsupported": "El servidor no admite los rangos de bytes necesarios.",+ "httpValidatorRequired": "El servidor no proporciona un identificador fiable de la versión del recurso.",+ "httpVerificationFailed": "No se pudieron verificar los datos descargados.",+ "httpRequestUnsupported": "El motor o los ajustes de solicitud no permiten reanudar de forma segura.",+ "httpVerificationCancelled": "Verificación cancelada.",+ "httpRedirectUnsupported": "Los enlaces redirigidos no pueden reanudarse de forma segura en la ubicación original."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Abre los detalles de la tarea para verificar y reanudar la descarga.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Verificar y continuar","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3335,7 +3355,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix comparará todos los rangos descargados con el servidor y continuará en la carpeta original. La verificación vuelve a transferir esos rangos; los ajustes de solicitud guardados permanecen en memoria.",+ "httpVerifying": "Preparando o verificando…",+ "httpOriginalFilesKept": "Se conservaron tus archivos existentes."},"rendererRecovery": {"title": "Es necesario recuperar la interfaz",diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex 21ddffa1..d1f7409c 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -2731,6 +2731,11 @@},"task": {"add": {+ "extraHeaders": "سرآیندهای اضافی",+ "headerName": "نام سرآیند",+ "headerValue": "مقدار سرآیند",+ "addHeader": "افزودن سرآیند",+ "removeHeader": "حذف سرآیند","adding": "در حال افزودن…","advanced": "پیشرفته","allProxy": "پروکسی",@@ -2761,6 +2766,7 @@"title": "این تورنت از قبل وجود دارد"},"errors": {+ "headerNameRequired": "نام سرآیند را وارد کنید یا این سرآیند را حذف کنید.","missingSource": "فایل تورنت یا پیوند magnet لازم است","noFilesSelected": "حداقل یک فایل انتخاب کنید","saveDirRequired": "پوشهٔ ذخیره لازم است",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "برای فایلهای کوکی قبلی، سرآیند Cookie موردنیاز را وارد کنید. برای نام کاربری و گذرواژهٔ HTTP، سرآیند Authorization معادل را وارد کنید. اطلاعات ورود پروکسی را در نشانی URL پروکسی وارد کنید.",+ "unsupportedOptions": "گزینههای پشتیبانینشده: {{options}}",+ "requestOptions": "تنظیمات ذخیرهشدهٔ درخواست: {{options}}",+ "requestSettingsDescription": "تنظیمات قدیمی درخواست کپی نشدهاند. پیش از دانلود در پوشهای جدید، آنها را دوباره در بخش پیشرفته وارد کنید.",+ "reconfigureDownload": "تنظیم دوباره و دانلود…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "تنظیمات ذخیرهشدهٔ درخواست پیش از ادامه بررسی میشوند",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "گزینههای دانلود پشتیبانینشده","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "دادههای دانلودشده با محتوای سرور متفاوتاند.",+ "httpRangeUnsupported": "سرور از بازههای بایتی موردنیاز پشتیبانی نمیکند.",+ "httpValidatorRequired": "سرور شناسهٔ قابلاعتمادی برای نسخهٔ منبع ارائه نمیکند.",+ "httpVerificationFailed": "بررسی دادههای دانلودشده ممکن نشد.",+ "httpRequestUnsupported": "موتور یا تنظیمات درخواست از ادامهٔ امن پشتیبانی نمیکنند.",+ "httpVerificationCancelled": "بررسی لغو شد.",+ "httpRedirectUnsupported": "پیوندهای هدایتشده را نمیتوان با ایمنی در محل اصلی ادامه داد."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "جزئیات کار را برای بررسی و ادامهٔ دانلود باز کنید.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "بررسی و ادامه","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix همهٔ بازههای دانلودشده را با سرور مقایسه میکند و در پوشهٔ اصلی ادامه میدهد. بررسی، این بازهها را دوباره منتقل میکند؛ تنظیمات ذخیرهشدهٔ درخواست در حافظه میمانند.",+ "httpVerifying": "در حال آمادهسازی یا بررسی…",+ "httpOriginalFilesKept": "فایلهای موجود حفظ شدند."},"rendererRecovery": {"title": "رابط کاربری نیاز به بازیابی دارد",diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex b2cc3a08..4b0ddaf8 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -2751,6 +2751,11 @@},"task": {"add": {+ "extraHeaders": "En-têtes supplémentaires",+ "headerName": "Nom de l’en-tête",+ "headerValue": "Valeur de l’en-tête",+ "addHeader": "Ajouter un en-tête",+ "removeHeader": "Supprimer l’en-tête","adding": "Ajout…","advanced": "Avancé","allProxy": "Proxy",@@ -2781,6 +2786,7 @@"title": "Ce torrent existe déjà"},"errors": {+ "headerNameRequired": "Saisissez un nom d’en-tête ou supprimez cet en-tête.","missingSource": "Un fichier torrent ou un lien magnet est requis","noFilesSelected": "Sélectionnez au moins un fichier","saveDirRequired": "Le dossier de destination est requis",@@ -3168,12 +3174,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Pour les anciens fichiers de cookies, saisissez l’en-tête Cookie nécessaire. Pour les identifiants HTTP, saisissez un en-tête Authorization équivalent. Saisissez les identifiants du proxy dans son URL.",+ "unsupportedOptions": "Options non prises en charge : {{options}}",+ "requestOptions": "Paramètres de requête enregistrés : {{options}}",+ "requestSettingsDescription": "Les anciens paramètres de requête n’ont pas été copiés. Saisissez-les à nouveau dans Avancé avant de télécharger dans un nouveau dossier.",+ "reconfigureDownload": "Reconfigurer et télécharger…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Les paramètres de requête enregistrés seront vérifiés avant la reprise",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Options de téléchargement non prises en charge","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3216,14 +3229,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Les données téléchargées diffèrent du contenu du serveur.",+ "httpRangeUnsupported": "Le serveur ne prend pas en charge les plages d’octets requises.",+ "httpValidatorRequired": "Le serveur ne fournit pas d’identifiant fiable de version de la ressource.",+ "httpVerificationFailed": "Impossible de vérifier les données téléchargées.",+ "httpRequestUnsupported": "Le moteur ou les paramètres de requête ne permettent pas une reprise sûre.",+ "httpVerificationCancelled": "Vérification annulée.",+ "httpRedirectUnsupported": "Les liens redirigés ne peuvent pas être repris sur place de façon sûre."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Ouvrez les détails de la tâche pour vérifier et reprendre le téléchargement.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Vérifier et continuer","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3335,7 +3355,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix comparera toutes les plages téléchargées au serveur, puis reprendra dans le dossier d’origine. La vérification retransfère ces plages ; les paramètres de requête enregistrés restent en mémoire.",+ "httpVerifying": "Préparation ou vérification…",+ "httpOriginalFilesKept": "Vos fichiers existants ont été conservés."},"rendererRecovery": {"title": "L’interface doit être restaurée",diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex bfc8a1d4..1885ef93 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -1021,6 +1021,11 @@},"task": {"add": {+ "extraHeaders": "További fejlécek",+ "headerName": "Fejléc neve",+ "headerValue": "Fejléc értéke",+ "addHeader": "Fejléc hozzáadása",+ "removeHeader": "Fejléc eltávolítása","title": "Új feladat","links": "Hivatkozások","torrent": "Torrent",@@ -1114,6 +1119,7 @@"doc": "Dokumentum"},"errors": {+ "headerNameRequired": "Adja meg a fejléc nevét, vagy távolítsa el ezt a fejlécet.","urlsRequired": "Legalább egy URL megadása szükséges","saveDirRequired": "Mentési mappa megadása szükséges","noFilesSelected": "Válassz ki legalább egy fájlt",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "A korábbi sütifájlok helyett adja meg a szükséges Cookie fejlécet. A HTTP-felhasználónevek és -jelszavak helyett adjon meg egy megfelelő Authorization fejlécet. A proxy hitelesítési adatait a proxy URL-jében adja meg.",+ "unsupportedOptions": "Nem támogatott beállítások: {{options}}",+ "requestOptions": "Mentett kérésbeállítások: {{options}}",+ "requestSettingsDescription": "A régi kérésbeállítások nem lettek átmásolva. Add meg őket újra a Speciális részben, mielőtt új mappába töltenél le.",+ "reconfigureDownload": "Újrakonfigurálás és letöltés…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "A mentett kérésbeállításokat folytatás előtt ellenőrizzük",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Nem támogatott letöltési beállítások","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "A letöltött adatok eltérnek a szerver tartalmától.",+ "httpRangeUnsupported": "A szerver nem támogatja a szükséges bájttartományokat.",+ "httpValidatorRequired": "A szerver nem ad megbízható erőforrásverzió-azonosítót.",+ "httpVerificationFailed": "Nem sikerült ellenőrizni a letöltött adatokat.",+ "httpRequestUnsupported": "A motor vagy a kérésbeállítások nem támogatják a biztonságos folytatást.",+ "httpVerificationCancelled": "Az ellenőrzés megszakítva.",+ "httpRedirectUnsupported": "Az átirányított hivatkozások nem folytathatók biztonságosan az eredeti helyen."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Nyisd meg a feladat részleteit a letöltés ellenőrzéséhez és folytatásához.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Ellenőrzés és folytatás","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "A Motrix összehasonlítja az összes letöltött tartományt a szerverrel, majd az eredeti mappában folytatja. Az ellenőrzés újra továbbítja ezeket a tartományokat; a mentett kérésbeállítások a memóriában maradnak.",+ "httpVerifying": "Előkészítés vagy ellenőrzés…",+ "httpOriginalFilesKept": "A meglévő fájlok megmaradtak."},"rendererRecovery": {"title": "A felületet helyre kell állítani",diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex d23215c6..b63b6579 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -1009,6 +1009,11 @@},"task": {"add": {+ "extraHeaders": "Header tambahan",+ "headerName": "Nama header",+ "headerValue": "Nilai header",+ "addHeader": "Tambah header",+ "removeHeader": "Hapus header","title": "Tugas baru","links": "Tautan","torrent": "Torrent",@@ -1101,6 +1106,7 @@"doc": "Dokumen"},"errors": {+ "headerNameRequired": "Masukkan nama header atau hapus header ini.","urlsRequired": "Setidaknya satu URL diperlukan","saveDirRequired": "Folder penyimpanan diperlukan","noFilesSelected": "Pilih setidaknya satu berkas",@@ -3124,12 +3130,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Untuk file cookie lama, masukkan header Cookie yang diperlukan. Untuk nama pengguna dan kata sandi HTTP, masukkan header Authorization yang setara. Masukkan kredensial proksi di URL proksi.",+ "unsupportedOptions": "Opsi yang tidak didukung: {{options}}",+ "requestOptions": "Pengaturan permintaan tersimpan: {{options}}",+ "requestSettingsDescription": "Pengaturan permintaan lama tidak disalin. Masukkan kembali di bagian Lanjutan sebelum mengunduh ke folder baru.",+ "reconfigureDownload": "Atur ulang dan unduh…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Pengaturan permintaan tersimpan akan diperiksa sebelum melanjutkan",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Opsi unduhan tidak didukung","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3172,14 +3185,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Data yang diunduh berbeda dari konten server.",+ "httpRangeUnsupported": "Server tidak mendukung rentang byte yang diperlukan.",+ "httpValidatorRequired": "Server tidak menyediakan pengenal versi sumber daya yang andal.",+ "httpVerificationFailed": "Data yang diunduh tidak dapat diverifikasi.",+ "httpRequestUnsupported": "Mesin atau pengaturan permintaan tidak mendukung kelanjutan yang aman.",+ "httpVerificationCancelled": "Verifikasi dibatalkan.",+ "httpRedirectUnsupported": "Tautan yang dialihkan tidak dapat dilanjutkan dengan aman di lokasi asli."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Buka detail tugas untuk memverifikasi dan melanjutkan unduhan.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Verifikasi dan lanjutkan","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3287,7 +3307,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix akan membandingkan semua rentang yang diunduh dengan server, lalu melanjutkan di folder asli. Verifikasi mentransfer ulang rentang tersebut; pengaturan permintaan tersimpan tetap di memori.",+ "httpVerifying": "Menyiapkan atau memverifikasi…",+ "httpOriginalFilesKept": "Berkas yang ada dipertahankan."},"rendererRecovery": {"title": "Antarmuka perlu dipulihkan",diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex f535b4cb..c3482904 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -1033,6 +1033,11 @@},"task": {"add": {+ "extraHeaders": "Intestazioni aggiuntive",+ "headerName": "Nome dell’intestazione",+ "headerValue": "Valore dell’intestazione",+ "addHeader": "Aggiungi intestazione",+ "removeHeader": "Rimuovi intestazione","title": "Nuova attività","links": "Link","torrent": "Torrent",@@ -1127,6 +1132,7 @@"doc": "Documento"},"errors": {+ "headerNameRequired": "Inserisci un nome per l’intestazione o rimuovila.","urlsRequired": "È richiesto almeno un URL","saveDirRequired": "È richiesta una cartella di salvataggio","noFilesSelected": "Seleziona almeno un file",@@ -3168,12 +3174,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Per i vecchi file cookie, inserisci l’intestazione Cookie necessaria. Per nomi utente e password HTTP, inserisci un’intestazione Authorization equivalente. Inserisci le credenziali del proxy nel relativo URL.",+ "unsupportedOptions": "Opzioni non supportate: {{options}}",+ "requestOptions": "Impostazioni di richiesta salvate: {{options}}",+ "requestSettingsDescription": "Le vecchie impostazioni di richiesta non sono state copiate. Reinseriscile in Avanzate prima di scaricare in una nuova cartella.",+ "reconfigureDownload": "Riconfigura e scarica…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Le impostazioni di richiesta salvate verranno controllate prima della ripresa",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Opzioni di download non supportate","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3216,14 +3229,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "I dati scaricati differiscono dal contenuto del server.",+ "httpRangeUnsupported": "Il server non supporta gli intervalli di byte richiesti.",+ "httpValidatorRequired": "Il server non fornisce un identificatore affidabile della versione della risorsa.",+ "httpVerificationFailed": "Impossibile verificare i dati scaricati.",+ "httpRequestUnsupported": "Il motore o le impostazioni di richiesta non consentono una ripresa sicura.",+ "httpVerificationCancelled": "Verifica annullata.",+ "httpRedirectUnsupported": "I collegamenti reindirizzati non possono essere ripresi in sicurezza nella posizione originale."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Apri i dettagli dell’attività per verificare e riprendere il download.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Verifica e continua","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3335,7 +3355,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix confronterà tutti gli intervalli scaricati con il server, poi riprenderà nella cartella originale. La verifica trasferisce di nuovo questi intervalli; le impostazioni di richiesta salvate restano in memoria.",+ "httpVerifying": "Preparazione o verifica…",+ "httpOriginalFilesKept": "I file esistenti sono stati conservati."},"rendererRecovery": {"title": "L’interfaccia deve essere ripristinata",diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex 259b157b..a9ee9ff8 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -1009,6 +1009,11 @@},"task": {"add": {+ "extraHeaders": "追加ヘッダー",+ "headerName": "ヘッダー名",+ "headerValue": "ヘッダー値",+ "addHeader": "ヘッダーを追加",+ "removeHeader": "ヘッダーを削除","title": "新規タスク","links": "リンク","torrent": "トレント",@@ -1101,6 +1106,7 @@"doc": "文書"},"errors": {+ "headerNameRequired": "ヘッダー名を入力するか、このヘッダーを削除してください。","urlsRequired": "URL を 1 件以上入力してください","saveDirRequired": "保存先フォルダーを指定してください","noFilesSelected": "ファイルを 1 個以上選択してください",@@ -3124,12 +3130,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "以前の Cookie ファイルについては、必要な Cookie ヘッダーを入力してください。HTTP のユーザー名とパスワードについては、同等の Authorization ヘッダーを入力してください。プロキシの認証情報はプロキシ URL に入力してください。",+ "unsupportedOptions": "未対応のオプション:{{options}}",+ "requestOptions": "保存されたリクエスト設定:{{options}}",+ "requestSettingsDescription": "以前のリクエスト設定はコピーされていません。新しいフォルダーにダウンロードする前に、詳細設定で再入力してください。",+ "reconfigureDownload": "再設定してダウンロード…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "再開前に保存されたリクエスト設定を確認します",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "未対応のダウンロードオプション","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3172,14 +3185,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "ダウンロード済みのデータがサーバーの内容と一致しません。",+ "httpRangeUnsupported": "サーバーが必要なバイト範囲に対応していません。",+ "httpValidatorRequired": "サーバーが確実なリソースバージョン識別子を提供していません。",+ "httpVerificationFailed": "ダウンロード済みのデータを検証できませんでした。",+ "httpRequestUnsupported": "エンジンまたはリクエスト設定が安全な再開に対応していません。",+ "httpVerificationCancelled": "検証をキャンセルしました。",+ "httpRedirectUnsupported": "リダイレクトされるリンクは元の場所で安全に再開できません。"},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "タスクの詳細を開き、検証してダウンロードを再開してください。","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "検証して続行","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3287,7 +3307,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix はダウンロード済みの全範囲をサーバーと照合し、元のフォルダーで再開します。検証ではその範囲を再転送します。保存されたリクエスト設定はメモリ内でのみ使用します。",+ "httpVerifying": "準備または検証中…",+ "httpOriginalFilesKept": "元のファイルを保持しました。"},"rendererRecovery": {"title": "画面の復旧が必要です",diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex 678f72be..2240d2f3 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -1009,6 +1009,11 @@},"task": {"add": {+ "extraHeaders": "추가 헤더",+ "headerName": "헤더 이름",+ "headerValue": "헤더 값",+ "addHeader": "헤더 추가",+ "removeHeader": "헤더 제거","title": "새 작업","links": "링크","torrent": "토렌트",@@ -1101,6 +1106,7 @@"doc": "문서"},"errors": {+ "headerNameRequired": "헤더 이름을 입력하거나 이 헤더를 제거하세요.","urlsRequired": "URL을 하나 이상 입력하세요","saveDirRequired": "저장 폴더를 지정하세요","noFilesSelected": "파일을 하나 이상 선택하세요",@@ -3124,12 +3130,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "이전 쿠키 파일을 사용했다면 필요한 Cookie 헤더를 입력하세요. HTTP 사용자 이름과 비밀번호를 사용했다면 이에 해당하는 Authorization 헤더를 입력하세요. 프록시 인증 정보는 프록시 URL에 입력하세요.",+ "unsupportedOptions": "지원하지 않는 옵션: {{options}}",+ "requestOptions": "저장된 요청 설정: {{options}}",+ "requestSettingsDescription": "이전 요청 설정은 복사되지 않았습니다. 새 폴더에 다운로드하기 전에 고급 설정에서 다시 입력하세요.",+ "reconfigureDownload": "다시 설정하고 다운로드…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "재개 전에 저장된 요청 설정을 확인합니다",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "지원하지 않는 다운로드 옵션","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3172,14 +3185,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "다운로드한 데이터가 서버 내용과 다릅니다.",+ "httpRangeUnsupported": "서버가 필요한 바이트 범위를 지원하지 않습니다.",+ "httpValidatorRequired": "서버가 신뢰할 수 있는 리소스 버전 식별자를 제공하지 않습니다.",+ "httpVerificationFailed": "다운로드한 데이터를 검증하지 못했습니다.",+ "httpRequestUnsupported": "엔진 또는 요청 설정이 안전한 재개를 지원하지 않습니다.",+ "httpVerificationCancelled": "검증을 취소했습니다.",+ "httpRedirectUnsupported": "리디렉션되는 링크는 원래 위치에서 안전하게 재개할 수 없습니다."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "작업 상세 정보를 열어 검증 후 다운로드를 재개하세요.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "검증 후 계속","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3287,7 +3307,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix는 다운로드한 모든 범위를 서버와 비교한 후 원래 폴더에서 계속합니다. 검증 시 해당 범위를 다시 전송하며, 저장된 요청 설정은 메모리에서만 사용합니다.",+ "httpVerifying": "준비 또는 검증 중…",+ "httpOriginalFilesKept": "원본 파일을 보존했습니다."},"rendererRecovery": {"title": "화면을 복구해야 합니다",diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex d7080879..73553762 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -2731,6 +2731,11 @@},"task": {"add": {+ "extraHeaders": "Ekstra headere",+ "headerName": "Headernavn",+ "headerValue": "Headerverdi",+ "addHeader": "Legg til header",+ "removeHeader": "Fjern header","adding": "Legger til…","advanced": "Avansert","allProxy": "Mellomtjener",@@ -2761,6 +2766,7 @@"title": "Denne torrenten finnes allerede"},"errors": {+ "headerNameRequired": "Angi et headernavn eller fjern denne headeren.","missingSource": "En torrentfil eller magnetlenke kreves","noFilesSelected": "Velg minst én fil","saveDirRequired": "Lagringsmappe kreves",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "For gamle informasjonskapselfiler angir du den nødvendige Cookie-headeren. For HTTP-brukernavn og -passord angir du en tilsvarende Authorization-header. Angi proxyens påloggingsinformasjon i proxy-URL-en.",+ "unsupportedOptions": "Alternativer som ikke støttes: {{options}}",+ "requestOptions": "Lagrede forespørselsinnstillinger: {{options}}",+ "requestSettingsDescription": "De gamle forespørselsinnstillingene ble ikke kopiert. Skriv dem inn på nytt under Avansert før du laster ned til en ny mappe.",+ "reconfigureDownload": "Konfigurer på nytt og last ned…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Lagrede forespørselsinnstillinger kontrolleres før gjenopptakelse",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Nedlastingsalternativer som ikke støttes","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "De nedlastede dataene er forskjellige fra serverinnholdet.",+ "httpRangeUnsupported": "Serveren støtter ikke de nødvendige byteområdene.",+ "httpValidatorRequired": "Serveren oppgir ingen pålitelig identifikator for ressursversjonen.",+ "httpVerificationFailed": "De nedlastede dataene kunne ikke kontrolleres.",+ "httpRequestUnsupported": "Motoren eller forespørselsinnstillingene støtter ikke trygg gjenopptakelse.",+ "httpVerificationCancelled": "Kontrollen ble avbrutt.",+ "httpRedirectUnsupported": "Videresendte lenker kan ikke gjenopptas trygt på det opprinnelige stedet."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Åpne oppgavedetaljene for å kontrollere og gjenoppta nedlastingen.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Kontroller og fortsett","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix sammenligner alle nedlastede områder med serveren og fortsetter deretter i den opprinnelige mappen. Kontrollen overfører områdene på nytt; lagrede forespørselsinnstillinger forblir i minnet.",+ "httpVerifying": "Forbereder eller kontrollerer…",+ "httpOriginalFilesKept": "De eksisterende filene ble beholdt."},"rendererRecovery": {"title": "Grensesnittet må gjenopprettes",diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 6528f612..444cfe66 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -2731,6 +2731,11 @@},"task": {"add": {+ "extraHeaders": "Extra headers",+ "headerName": "Headernaam",+ "headerValue": "Headerwaarde",+ "addHeader": "Header toevoegen",+ "removeHeader": "Header verwijderen","adding": "Toevoegen…","advanced": "Geavanceerd","allProxy": "Proxy",@@ -2761,6 +2766,7 @@"title": "Deze torrent bestaat al"},"errors": {+ "headerNameRequired": "Voer een headernaam in of verwijder deze header.","missingSource": "Er is een torrentbestand of magnetlink nodig","noFilesSelected": "Selecteer minstens één bestand","saveDirRequired": "Er is een opslagmap nodig",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Voer voor oude cookiebestanden de benodigde Cookie-header in. Voer voor HTTP-gebruikersnamen en -wachtwoorden een gelijkwaardige Authorization-header in. Voer proxy-inloggegevens in de proxy-URL in.",+ "unsupportedOptions": "Niet-ondersteunde opties: {{options}}",+ "requestOptions": "Opgeslagen verzoekinstellingen: {{options}}",+ "requestSettingsDescription": "De oude verzoekinstellingen zijn niet gekopieerd. Vul ze opnieuw in bij Geavanceerd voordat je naar een nieuwe map downloadt.",+ "reconfigureDownload": "Opnieuw configureren en downloaden…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Opgeslagen verzoekinstellingen worden vóór het hervatten gecontroleerd",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Niet-ondersteunde downloadopties","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "De gedownloade gegevens wijken af van de serverinhoud.",+ "httpRangeUnsupported": "De server ondersteunt de vereiste bytebereiken niet.",+ "httpValidatorRequired": "De server geeft geen betrouwbare identificatie van de bronversie.",+ "httpVerificationFailed": "De gedownloade gegevens konden niet worden gecontroleerd.",+ "httpRequestUnsupported": "De engine of verzoekinstellingen ondersteunen geen veilige hervatting.",+ "httpVerificationCancelled": "Controle geannuleerd.",+ "httpRedirectUnsupported": "Doorgestuurde links kunnen niet veilig op de oorspronkelijke locatie worden hervat."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Open de taakdetails om de download te controleren en te hervatten.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Controleren en doorgaan","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix vergelijkt alle gedownloade bereiken met de server en hervat daarna in de oorspronkelijke map. De controle haalt deze bereiken opnieuw op; opgeslagen verzoekinstellingen blijven in het geheugen.",+ "httpVerifying": "Voorbereiden of controleren…",+ "httpOriginalFilesKept": "Je bestaande bestanden zijn behouden."},"rendererRecovery": {"title": "De interface moet worden hersteld",diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex e3bb42f0..e008298d 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -1045,6 +1045,11 @@},"task": {"add": {+ "extraHeaders": "Dodatkowe nagłówki",+ "headerName": "Nazwa nagłówka",+ "headerValue": "Wartość nagłówka",+ "addHeader": "Dodaj nagłówek",+ "removeHeader": "Usuń nagłówek","title": "Nowe zadanie","links": "Linki","torrent": "Torrent",@@ -1140,6 +1145,7 @@"doc": "Dokument"},"errors": {+ "headerNameRequired": "Wprowadź nazwę nagłówka lub usuń ten nagłówek.","urlsRequired": "Wymagany jest co najmniej jeden adres URL","saveDirRequired": "Wymagany jest folder zapisu","noFilesSelected": "Wybierz co najmniej jeden plik",@@ -3190,12 +3196,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "W przypadku starych plików cookie wprowadź wymagany nagłówek Cookie. W przypadku nazw użytkowników i haseł HTTP wprowadź równoważny nagłówek Authorization. Dane uwierzytelniające serwera proxy wpisz w jego adresie URL.",+ "unsupportedOptions": "Nieobsługiwane opcje: {{options}}",+ "requestOptions": "Zapisane ustawienia żądania: {{options}}",+ "requestSettingsDescription": "Stare ustawienia żądania nie zostały skopiowane. Wprowadź je ponownie w ustawieniach zaawansowanych przed pobraniem do nowego folderu.",+ "reconfigureDownload": "Skonfiguruj ponownie i pobierz…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Zapisane ustawienia żądania zostaną sprawdzone przed wznowieniem",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Nieobsługiwane opcje pobierania","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3238,14 +3251,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Pobrane dane różnią się od zawartości serwera.",+ "httpRangeUnsupported": "Serwer nie obsługuje wymaganych zakresów bajtów.",+ "httpValidatorRequired": "Serwer nie udostępnia wiarygodnego identyfikatora wersji zasobu.",+ "httpVerificationFailed": "Nie udało się zweryfikować pobranych danych.",+ "httpRequestUnsupported": "Silnik lub ustawienia żądania nie umożliwiają bezpiecznego wznowienia.",+ "httpVerificationCancelled": "Weryfikację anulowano.",+ "httpRedirectUnsupported": "Przekierowanych linków nie można bezpiecznie wznowić w pierwotnej lokalizacji."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Otwórz szczegóły zadania, aby zweryfikować i wznowić pobieranie.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Zweryfikuj i kontynuuj","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3359,7 +3379,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix porówna wszystkie pobrane zakresy z serwerem, a potem wznowi w oryginalnym folderze. Weryfikacja ponownie przesyła te zakresy; zapisane ustawienia żądania pozostają w pamięci.",+ "httpVerifying": "Przygotowywanie lub weryfikowanie…",+ "httpOriginalFilesKept": "Istniejące pliki zachowano."},"rendererRecovery": {"title": "Interfejs wymaga przywrócenia",diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex 40cf5e10..f1a0d8a3 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -1033,6 +1033,11 @@},"task": {"add": {+ "extraHeaders": "Cabeçalhos adicionais",+ "headerName": "Nome do cabeçalho",+ "headerValue": "Valor do cabeçalho",+ "addHeader": "Adicionar cabeçalho",+ "removeHeader": "Remover cabeçalho","title": "Nova tarefa","links": "Links","torrent": "Torrent",@@ -1127,6 +1132,7 @@"doc": "Documento"},"errors": {+ "headerNameRequired": "Insira um nome para o cabeçalho ou remova-o.","urlsRequired": "É necessário pelo menos um URL","saveDirRequired": "A pasta de destino é obrigatória","noFilesSelected": "Selecione pelo menos um arquivo",@@ -3168,12 +3174,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Para arquivos de cookies antigos, insira o cabeçalho Cookie necessário. Para nomes de usuário e senhas HTTP, insira um cabeçalho Authorization equivalente. Insira as credenciais do proxy na URL do proxy.",+ "unsupportedOptions": "Opções não compatíveis: {{options}}",+ "requestOptions": "Configurações de solicitação salvas: {{options}}",+ "requestSettingsDescription": "As configurações antigas de solicitação não foram copiadas. Insira-as novamente em Avançado antes de baixar em uma nova pasta.",+ "reconfigureDownload": "Reconfigurar e baixar…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "As configurações de solicitação salvas serão verificadas antes de retomar",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Opções de download não compatíveis","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3216,14 +3229,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Os dados baixados diferem do conteúdo do servidor.",+ "httpRangeUnsupported": "O servidor não oferece suporte aos intervalos de bytes necessários.",+ "httpValidatorRequired": "O servidor não fornece um identificador confiável da versão do recurso.",+ "httpVerificationFailed": "Não foi possível verificar os dados baixados.",+ "httpRequestUnsupported": "O mecanismo ou as configurações de solicitação não permitem retomar com segurança.",+ "httpVerificationCancelled": "Verificação cancelada.",+ "httpRedirectUnsupported": "Links redirecionados não podem ser retomados com segurança no local original."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Abra os detalhes da tarefa para verificar e retomar o download.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Verificar e continuar","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3335,7 +3355,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "O Motrix comparará todos os intervalos baixados com o servidor e continuará na pasta original. A verificação transfere esses intervalos novamente; as configurações de solicitação salvas ficam na memória.",+ "httpVerifying": "Preparando ou verificando…",+ "httpOriginalFilesKept": "Seus arquivos existentes foram preservados."},"rendererRecovery": {"title": "A interface precisa ser recuperada",diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex e2629584..d9a51803 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -2751,6 +2751,11 @@},"task": {"add": {+ "extraHeaders": "Antete suplimentare",+ "headerName": "Numele antetului",+ "headerValue": "Valoarea antetului",+ "addHeader": "Adăugați un antet",+ "removeHeader": "Eliminați antetul","adding": "Se adaugă…","advanced": "Avansat","allProxy": "Proxy",@@ -2781,6 +2786,7 @@"title": "Acest torrent există deja"},"errors": {+ "headerNameRequired": "Introduceți un nume pentru antet sau eliminați acest antet.","missingSource": "Este necesar un fișier torrent sau un link magnet","noFilesSelected": "Selectează cel puțin un fișier","saveDirRequired": "Este necesar un dosar de salvare",@@ -3168,12 +3174,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Pentru vechile fișiere cookie, introduceți antetul Cookie necesar. Pentru numele de utilizator și parolele HTTP, introduceți un antet Authorization echivalent. Introduceți datele de autentificare ale proxy-ului în URL-ul acestuia.",+ "unsupportedOptions": "Opțiuni neacceptate: {{options}}",+ "requestOptions": "Setări de cerere salvate: {{options}}",+ "requestSettingsDescription": "Setările vechi de cerere nu au fost copiate. Introdu-le din nou în Avansat înainte de a descărca într-un dosar nou.",+ "reconfigureDownload": "Reconfigurați și descărcați…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Setările de cerere salvate vor fi verificate înainte de reluare",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Opțiuni de descărcare neacceptate","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3216,14 +3229,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Datele descărcate diferă de conținutul serverului.",+ "httpRangeUnsupported": "Serverul nu acceptă intervalele de octeți necesare.",+ "httpValidatorRequired": "Serverul nu oferă un identificator fiabil al versiunii resursei.",+ "httpVerificationFailed": "Datele descărcate nu au putut fi verificate.",+ "httpRequestUnsupported": "Motorul sau setările de cerere nu permit reluarea în siguranță.",+ "httpVerificationCancelled": "Verificare anulată.",+ "httpRedirectUnsupported": "Linkurile redirecționate nu pot fi reluate în siguranță în locația originală."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Deschide detaliile sarcinii pentru a verifica și relua descărcarea.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Verifică și continuă","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3335,7 +3355,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix va compara toate intervalele descărcate cu serverul, apoi va continua în dosarul original. Verificarea transferă din nou aceste intervale; setările de cerere salvate rămân în memorie.",+ "httpVerifying": "Pregătire sau verificare…",+ "httpOriginalFilesKept": "Fișierele existente au fost păstrate."},"rendererRecovery": {"title": "Interfața trebuie recuperată",diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex 4003e65b..4dbe355f 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -1045,6 +1045,11 @@},"task": {"add": {+ "extraHeaders": "Дополнительные заголовки",+ "headerName": "Имя заголовка",+ "headerValue": "Значение заголовка",+ "addHeader": "Добавить заголовок",+ "removeHeader": "Удалить заголовок","title": "Новая задача","links": "Ссылки","torrent": "Торрент",@@ -1140,6 +1145,7 @@"doc": "Документ"},"errors": {+ "headerNameRequired": "Введите имя заголовка или удалите этот заголовок.","urlsRequired": "Требуется хотя бы один URL","saveDirRequired": "Укажите папку сохранения","noFilesSelected": "Выберите хотя бы один файл",@@ -3190,12 +3196,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Для прежних файлов cookie введите нужный заголовок Cookie. Для имён пользователей и паролей HTTP введите соответствующий заголовок Authorization. Укажите учётные данные прокси в его URL.",+ "unsupportedOptions": "Неподдерживаемые параметры: {{options}}",+ "requestOptions": "Сохранённые настройки запроса: {{options}}",+ "requestSettingsDescription": "Прежние настройки запроса не скопированы. Введите их заново в расширенных настройках перед загрузкой в новую папку.",+ "reconfigureDownload": "Настроить заново и скачать…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Сохранённые настройки запроса будут проверены перед продолжением",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Неподдерживаемые параметры загрузки","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3238,14 +3251,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Загруженные данные отличаются от содержимого сервера.",+ "httpRangeUnsupported": "Сервер не поддерживает необходимые диапазоны байтов.",+ "httpValidatorRequired": "Сервер не предоставляет надёжный идентификатор версии ресурса.",+ "httpVerificationFailed": "Не удалось проверить загруженные данные.",+ "httpRequestUnsupported": "Движок или настройки запроса не поддерживают безопасное возобновление.",+ "httpVerificationCancelled": "Проверка отменена.",+ "httpRedirectUnsupported": "Ссылки с перенаправлением нельзя безопасно возобновить в исходном месте."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Откройте сведения о задаче, чтобы проверить и возобновить загрузку.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Проверить и продолжить","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3359,7 +3379,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix сравнит все загруженные диапазоны с сервером и продолжит в исходной папке. Проверка повторно передаёт эти диапазоны; сохранённые настройки запроса остаются в памяти.",+ "httpVerifying": "Подготовка или проверка…",+ "httpOriginalFilesKept": "Существующие файлы сохранены."},"rendererRecovery": {"title": "Интерфейс необходимо восстановить",diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex ef195989..40ff55d6 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -2711,6 +2711,11 @@},"task": {"add": {+ "extraHeaders": "ส่วนหัวเพิ่มเติม",+ "headerName": "ชื่อส่วนหัว",+ "headerValue": "ค่าส่วนหัว",+ "addHeader": "เพิ่มส่วนหัว",+ "removeHeader": "ลบส่วนหัว","adding": "กำลังเพิ่ม…","advanced": "ขั้นสูง","allProxy": "พร็อกซี",@@ -2741,6 +2746,7 @@"title": "มีทอร์เรนต์นี้อยู่แล้ว"},"errors": {+ "headerNameRequired": "ป้อนชื่อส่วนหัวหรือลบส่วนหัวนี้","missingSource": "ต้องมีไฟล์ทอร์เรนต์หรือลิงก์แมกเน็ต","noFilesSelected": "เลือกอย่างน้อยหนึ่งไฟล์","saveDirRequired": "ต้องระบุโฟลเดอร์บันทึก",@@ -3124,12 +3130,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "สำหรับไฟล์คุกกี้เดิม ให้ป้อนส่วนหัว Cookie ที่จำเป็น สำหรับชื่อผู้ใช้และรหัสผ่าน HTTP ให้ป้อนส่วนหัว Authorization ที่เทียบเท่ากัน ป้อนข้อมูลรับรองพร็อกซีใน URL ของพร็อกซี",+ "unsupportedOptions": "ตัวเลือกที่ไม่รองรับ: {{options}}",+ "requestOptions": "การตั้งค่าคำขอที่บันทึกไว้: {{options}}",+ "requestSettingsDescription": "ไม่ได้คัดลอกการตั้งค่าคำขอเดิม โปรดกรอกอีกครั้งในขั้นสูงก่อนดาวน์โหลดลงโฟลเดอร์ใหม่",+ "reconfigureDownload": "ตั้งค่าใหม่และดาวน์โหลด…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "จะตรวจสอบการตั้งค่าคำขอที่บันทึกไว้ก่อนดาวน์โหลดต่อ",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "ตัวเลือกการดาวน์โหลดที่ไม่รองรับ","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3172,14 +3185,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "ข้อมูลที่ดาวน์โหลดแล้วต่างจากเนื้อหาบนเซิร์ฟเวอร์",+ "httpRangeUnsupported": "เซิร์ฟเวอร์ไม่รองรับช่วงไบต์ที่จำเป็น",+ "httpValidatorRequired": "เซิร์ฟเวอร์ไม่มีตัวระบุเวอร์ชันทรัพยากรที่เชื่อถือได้",+ "httpVerificationFailed": "ไม่สามารถตรวจสอบข้อมูลที่ดาวน์โหลดแล้วได้",+ "httpRequestUnsupported": "เอนจินหรือการตั้งค่าคำขอไม่รองรับการดาวน์โหลดต่ออย่างปลอดภัย",+ "httpVerificationCancelled": "ยกเลิกการตรวจสอบแล้ว",+ "httpRedirectUnsupported": "ไม่สามารถดาวน์โหลดลิงก์ที่เปลี่ยนเส้นทางต่อในตำแหน่งเดิมได้อย่างปลอดภัย"},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "เปิดรายละเอียดงานเพื่อตรวจสอบและดาวน์โหลดต่อ","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "ตรวจสอบและดำเนินการต่อ","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3287,7 +3307,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix จะเปรียบเทียบข้อมูลทุกช่วงที่ดาวน์โหลดแล้วกับเซิร์ฟเวอร์ก่อนดาวน์โหลดต่อในโฟลเดอร์เดิม การตรวจสอบจะถ่ายโอนข้อมูลเหล่านั้นอีกครั้ง โดยใช้การตั้งค่าคำขอที่บันทึกไว้ในหน่วยความจำเท่านั้น",+ "httpVerifying": "กำลังเตรียมหรือตรวจสอบ…",+ "httpOriginalFilesKept": "เก็บไฟล์เดิมไว้แล้ว"},"rendererRecovery": {"title": "ต้องกู้คืนส่วนติดต่อ",diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex b2251683..7b5d95b1 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -1021,6 +1021,11 @@},"task": {"add": {+ "extraHeaders": "Ek üstbilgiler",+ "headerName": "Üstbilgi adı",+ "headerValue": "Üstbilgi değeri",+ "addHeader": "Üstbilgi ekle",+ "removeHeader": "Üstbilgiyi kaldır","title": "Yeni Görev","links": "Bağlantılar","torrent": "Torrent",@@ -1114,6 +1119,7 @@"doc": "Belge"},"errors": {+ "headerNameRequired": "Bir üstbilgi adı girin veya bu üstbilgiyi kaldırın.","urlsRequired": "En az bir URL gerekli","saveDirRequired": "Kayıt klasörü gerekli","noFilesSelected": "En az bir dosya seçin",@@ -3146,12 +3152,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Eski çerez dosyaları için gerekli Cookie üstbilgisini girin. HTTP kullanıcı adları ve parolaları için eşdeğer bir Authorization üstbilgisi girin. Proxy kimlik bilgilerini proxy URL’sine girin.",+ "unsupportedOptions": "Desteklenmeyen seçenekler: {{options}}",+ "requestOptions": "Kaydedilmiş istek ayarları: {{options}}",+ "requestSettingsDescription": "Eski istek ayarları kopyalanmadı. Yeni bir klasöre indirmeden önce Gelişmiş bölümünde yeniden girin.",+ "reconfigureDownload": "Yeniden yapılandır ve indir…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Devam etmeden önce kaydedilmiş istek ayarları kontrol edilecek",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Desteklenmeyen indirme seçenekleri","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3194,14 +3207,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "İndirilen veriler sunucu içeriğinden farklı.",+ "httpRangeUnsupported": "Sunucu gerekli bayt aralıklarını desteklemiyor.",+ "httpValidatorRequired": "Sunucu güvenilir bir kaynak sürümü tanımlayıcısı sağlamıyor.",+ "httpVerificationFailed": "İndirilen veriler doğrulanamadı.",+ "httpRequestUnsupported": "Motor veya istek ayarları güvenli devamı desteklemiyor.",+ "httpVerificationCancelled": "Doğrulama iptal edildi.",+ "httpRedirectUnsupported": "Yönlendirilen bağlantılara özgün konumda güvenle devam edilemez."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "İndirmeyi doğrulayıp devam ettirmek için görev ayrıntılarını açın.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Doğrula ve devam et","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3311,7 +3331,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix indirilen tüm aralıkları sunucuyla karşılaştırıp özgün klasörde devam eder. Doğrulama bu aralıkları yeniden aktarır; kayıtlı istek ayarları bellekte kalır.",+ "httpVerifying": "Hazırlanıyor veya doğrulanıyor…",+ "httpOriginalFilesKept": "Mevcut dosyalarınız korundu."},"rendererRecovery": {"title": "Arayüzün kurtarılması gerekiyor",diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex 61d8ead5..b4b1344f 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -2771,6 +2771,11 @@},"task": {"add": {+ "extraHeaders": "Додаткові заголовки",+ "headerName": "Назва заголовка",+ "headerValue": "Значення заголовка",+ "addHeader": "Додати заголовок",+ "removeHeader": "Видалити заголовок","adding": "Додавання…","advanced": "Додатково","allProxy": "Проксі",@@ -2801,6 +2806,7 @@"title": "Цей торрент уже існує"},"errors": {+ "headerNameRequired": "Введіть назву заголовка або видаліть цей заголовок.","missingSource": "Потрібен торрент-файл або magnet-посилання","noFilesSelected": "Виберіть принаймні один файл","saveDirRequired": "Потрібно вказати теку збереження",@@ -3190,12 +3196,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Для попередніх файлів cookie введіть потрібний заголовок Cookie. Для імен користувачів і паролів HTTP введіть відповідний заголовок Authorization. Вкажіть облікові дані проксі в його URL.",+ "unsupportedOptions": "Непідтримувані параметри: {{options}}",+ "requestOptions": "Збережені налаштування запиту: {{options}}",+ "requestSettingsDescription": "Старі налаштування запиту не скопійовано. Введіть їх знову в розширених налаштуваннях перед завантаженням у нову теку.",+ "reconfigureDownload": "Налаштувати знову та завантажити…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Збережені налаштування запиту буде перевірено перед відновленням",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Непідтримувані параметри завантаження","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3238,14 +3251,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Завантажені дані відрізняються від вмісту сервера.",+ "httpRangeUnsupported": "Сервер не підтримує потрібні діапазони байтів.",+ "httpValidatorRequired": "Сервер не надає надійний ідентифікатор версії ресурсу.",+ "httpVerificationFailed": "Не вдалося перевірити завантажені дані.",+ "httpRequestUnsupported": "Рушій або налаштування запиту не підтримують безпечне відновлення.",+ "httpVerificationCancelled": "Перевірку скасовано.",+ "httpRedirectUnsupported": "Посилання з перенаправленням не можна безпечно відновити у вихідному місці."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Відкрийте подробиці завдання, щоб перевірити й відновити завантаження.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Перевірити й продовжити","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3359,7 +3379,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix порівняє всі завантажені діапазони із сервером і продовжить у вихідній теці. Перевірка повторно передає ці діапазони; збережені налаштування запиту залишаються в пам’яті.",+ "httpVerifying": "Підготовка або перевірка…",+ "httpOriginalFilesKept": "Наявні файли збережено."},"rendererRecovery": {"title": "Інтерфейс потребує відновлення",diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex 38386669..8be9b097 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -1009,6 +1009,11 @@},"task": {"add": {+ "extraHeaders": "Tiêu đề bổ sung",+ "headerName": "Tên tiêu đề",+ "headerValue": "Giá trị tiêu đề",+ "addHeader": "Thêm tiêu đề",+ "removeHeader": "Xóa tiêu đề","title": "Tác vụ mới","links": "Liên kết","torrent": "Torrent",@@ -1101,6 +1106,7 @@"doc": "Tài liệu"},"errors": {+ "headerNameRequired": "Nhập tên tiêu đề hoặc xóa tiêu đề này.","urlsRequired": "Cần ít nhất một URL","saveDirRequired": "Cần chọn thư mục lưu","noFilesSelected": "Chọn ít nhất một tệp",@@ -3124,12 +3130,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "Với các tệp cookie cũ, hãy nhập tiêu đề Cookie cần thiết. Với tên người dùng và mật khẩu HTTP, hãy nhập tiêu đề Authorization tương đương. Nhập thông tin xác thực proxy trong URL proxy.",+ "unsupportedOptions": "Tùy chọn không được hỗ trợ: {{options}}",+ "requestOptions": "Cài đặt yêu cầu đã lưu: {{options}}",+ "requestSettingsDescription": "Các cài đặt yêu cầu cũ chưa được sao chép. Hãy nhập lại trong phần Nâng cao trước khi tải vào thư mục mới.",+ "reconfigureDownload": "Cấu hình lại và tải xuống…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "Các cài đặt yêu cầu đã lưu sẽ được kiểm tra trước khi tiếp tục",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "Tùy chọn tải xuống không được hỗ trợ","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3172,14 +3185,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "Dữ liệu đã tải khác với nội dung máy chủ.",+ "httpRangeUnsupported": "Máy chủ không hỗ trợ các phạm vi byte cần thiết.",+ "httpValidatorRequired": "Máy chủ không cung cấp mã định danh phiên bản tài nguyên đáng tin cậy.",+ "httpVerificationFailed": "Không thể xác minh dữ liệu đã tải.",+ "httpRequestUnsupported": "Bộ máy hoặc cài đặt yêu cầu không hỗ trợ tiếp tục an toàn.",+ "httpVerificationCancelled": "Đã hủy xác minh.",+ "httpRedirectUnsupported": "Không thể tiếp tục an toàn liên kết chuyển hướng tại vị trí gốc."},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "Mở chi tiết tác vụ để xác minh và tiếp tục tải.","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "Xác minh và tiếp tục","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3287,7 +3307,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix sẽ đối chiếu tất cả các vùng đã tải với máy chủ rồi tiếp tục trong thư mục gốc. Xác minh sẽ truyền lại các vùng này; cài đặt yêu cầu đã lưu chỉ được giữ trong bộ nhớ.",+ "httpVerifying": "Đang chuẩn bị hoặc xác minh…",+ "httpOriginalFilesKept": "Các tệp hiện có được giữ nguyên."},"rendererRecovery": {"title": "Giao diện cần được khôi phục",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex bc9a2a82..beae5744 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1009,6 +1009,11 @@},"task": {"add": {+ "extraHeaders": "额外请求头",+ "headerName": "请求头名称",+ "headerValue": "请求头值",+ "addHeader": "添加请求头",+ "removeHeader": "移除请求头","title": "新建任务","links": "链接","torrent": "种子",@@ -1101,6 +1106,7 @@"doc": "文档"},"errors": {+ "headerNameRequired": "请输入请求头名称,或移除此请求头。","urlsRequired": "至少需要一个 URL","saveDirRequired": "必须指定保存目录","noFilesSelected": "请至少选择一个文件",@@ -3124,12 +3130,19 @@"freshDescription": "选择新的保存位置后,Motrix 会创建单独的文件夹,并打开下载窗口供你确认。本次将从头下载,原文件会保留。","freshDestination": "选择新下载的保存位置","chooseDestination": "选择其他位置…",+ "requestSettingsHelp": "旧版 Cookie 文件中的信息,请填写为所需的 Cookie 请求头。旧版 HTTP 用户名和密码,请填写为等效的 Authorization 请求头。代理凭据请填写在代理 URL 中。",+ "unsupportedOptions": "不支持的选项:{{options}}",+ "requestOptions": "已保存的请求设置:{{options}}",+ "requestSettingsDescription": "旧版请求设置未复制。请在“高级”中重新填写后,下载到新文件夹。",+ "reconfigureDownload": "重新配置并下载…","reasons": {"fresh-download-required": "需要重新下载","verification-required": "需要检查已有文件","metadata-required": "需要原种子文件","selection-required": "需要重新选择文件",- "unsupported-options": "下载信息需要确认",+ "request-settings-required": "续传前会检查已保存的请求设置",+ "mirrors-unsupported": "此任务包含多个下载地址,请复制要使用的地址并新建下载。",+ "unsupported-options": "不支持的下载选项","invalid-record": "无法读取此任务","unsafe-path": "文件位置需要确认","already-imported": "已经导入",@@ -3172,14 +3185,21 @@"payloadMissing": "部分原文件缺失,包括之前未选中的文件。继续下载需要这些文件,请换一个文件夹重新下载。","payloadUnsafe": "原文件的链接或权限设置使其无法安全更新。请保留原文件,并换一个文件夹重新下载。","controlRequired": "找不到旧版保存的下载进度,请换一个文件夹重新下载。",- "activationUncertain": "暂时无法安全恢复此任务,原文件仍受保护。你可以换一个文件夹重新下载。"+ "activationUncertain": "暂时无法安全恢复此任务,原文件仍受保护。你可以换一个文件夹重新下载。",+ "httpContentChanged": "已下载的数据与服务器内容不一致。",+ "httpRangeUnsupported": "服务器不支持所需的字节范围请求。",+ "httpValidatorRequired": "服务器未提供可靠的资源版本标识。",+ "httpVerificationFailed": "无法校验已下载的数据。",+ "httpRequestUnsupported": "引擎或请求设置不支持安全续传。",+ "httpVerificationCancelled": "校验已取消。",+ "httpRedirectUnsupported": "跳转链接暂时无法安全原地续传。"},"resultIncompleteTitle": "迁移尚未完成","resultStoppedTitle": "迁移已停止",- "activationRequired": "请选择新的文件夹重新下载,原文件会保留。",+ "activationRequired": "请打开任务详情,校验后继续下载。","chooseTorrent": "选择种子文件…","torrentFile": "种子文件",- "verifyAndContinue": "检查并继续",+ "verifyAndContinue": "校验并继续","verifyDescription": "Motrix 会先检查原文件,再按旧任务的文件选择继续下载。下载期间可能上传数据,未选文件也可能写入部分内容;完成后不会自动做种。","authorizeOriginalDirectory": "选择原下载文件夹","verifyReady": "你可以检查已有文件后继续下载,也可以换一个文件夹重新下载。",@@ -3287,7 +3307,10 @@"remaining": "尚未迁移"}},- "importSelected": "迁移"+ "importSelected": "迁移",+ "httpResumeDescription": "Motrix 会将所有已下载的数据段与服务器内容比对,通过后在原目录继续下载。校验会重新传输这些数据段;已保存的请求设置仅在内存中使用。",+ "httpVerifying": "正在准备或校验…",+ "httpOriginalFilesKept": "原文件已保留。"},"rendererRecovery": {"title": "界面需要恢复",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 80727051..b2e280fb 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1009,6 +1009,11 @@},"task": {"add": {+ "extraHeaders": "額外請求標頭",+ "headerName": "標頭名稱",+ "headerValue": "標頭值",+ "addHeader": "新增標頭",+ "removeHeader": "移除標頭","title": "新增任務","links": "連結","torrent": "Torrent",@@ -1101,6 +1106,7 @@"doc": "文件"},"errors": {+ "headerNameRequired": "請輸入標頭名稱,或移除此標頭。","urlsRequired": "至少需要一個 URL","saveDirRequired": "必須指定儲存目錄","noFilesSelected": "至少選擇一個檔案",@@ -3124,12 +3130,19 @@"freshDescription": "Choose where to save the new download. Motrix will create a separate folder and open the download form for you to confirm. It will start from the beginning and leave your old files untouched.","freshDestination": "Choose where to save the new download","chooseDestination": "Choose another location…",+ "requestSettingsHelp": "舊版 Cookie 檔案中的資訊,請填寫為所需的 Cookie 請求標頭。舊版 HTTP 使用者名稱和密碼,請填寫為等效的 Authorization 請求標頭。代理伺服器憑證請填寫在代理伺服器 URL 中。",+ "unsupportedOptions": "不支援的選項:{{options}}",+ "requestOptions": "已儲存的請求設定:{{options}}",+ "requestSettingsDescription": "舊版請求設定未複製。請在「進階」中重新填寫後,下載到新資料夾。",+ "reconfigureDownload": "重新設定並下載…","reasons": {"fresh-download-required": "Needs a new download","verification-required": "Existing files need checking","metadata-required": "Original torrent file needed","selection-required": "Choose which files to download",- "unsupported-options": "Download details need checking",+ "request-settings-required": "續傳前會檢查已儲存的請求設定",+ "mirrors-unsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "unsupported-options": "不支援的下載選項","invalid-record": "Couldn’t read this task","unsafe-path": "File location needs checking","already-imported": "Already imported",@@ -3172,14 +3185,21 @@"payloadMissing": "Some original files are missing, including files previously left unselected. All are needed to resume this task. Download again in a new folder.","payloadUnsafe": "The original files can’t be updated safely because of file links or permissions. Keep them and download again in a new folder.","controlRequired": "The saved download progress is missing. Download again in a new folder.",- "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder."+ "activationUncertain": "Motrix couldn’t safely resume this task. The original files are protected. You can download again in a new folder.",+ "httpContentChanged": "已下載的資料與伺服器內容不一致。",+ "httpRangeUnsupported": "伺服器不支援所需的位元組範圍請求。",+ "httpValidatorRequired": "伺服器未提供可靠的資源版本識別碼。",+ "httpVerificationFailed": "無法驗證已下載的資料。",+ "httpRequestUnsupported": "引擎或請求設定不支援安全續傳。",+ "httpVerificationCancelled": "驗證已取消。",+ "httpRedirectUnsupported": "重新導向的連結暫時無法安全原地續傳。"},"resultIncompleteTitle": "Migration is incomplete","resultStoppedTitle": "Migration stopped",- "activationRequired": "Download again in a new folder to keep the original files.",+ "activationRequired": "請開啟任務詳細資料,驗證後繼續下載。","chooseTorrent": "Choose torrent…","torrentFile": "Torrent file",- "verifyAndContinue": "Verify and continue",+ "verifyAndContinue": "驗證並繼續","verifyDescription": "Motrix will verify the original files, then continue with your previous file selection. While downloading, it may upload data and write shared pieces to unselected files. It won’t seed automatically when finished.","authorizeOriginalDirectory": "Choose the original download folder","verifyReady": "Verify your existing files to continue this download, or start again in a new folder.",@@ -3287,7 +3307,10 @@"remaining": "Remaining"}},- "importSelected": "Migrate"+ "importSelected": "Migrate",+ "httpResumeDescription": "Motrix 會將所有已下載的資料區段與伺服器內容比對,通過後在原資料夾繼續下載。驗證會重新傳輸這些區段;已儲存的請求設定僅在記憶體中使用。",+ "httpVerifying": "正在準備或驗證…",+ "httpOriginalFilesKept": "原始檔案已保留。"},"rendererRecovery": {"title": "介面需要復原",diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex 430be938..7d7b2cab 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -18,6 +18,8 @@ export const Commands = {CancelPluginOperation: 'command:cancelPluginOperation',PickFile: 'command:pickFile',ActivateLegacyBt: 'command:activateLegacyBt',+ ActivateLegacyHttp: 'command:activateLegacyHttp',+ CancelLegacyHttpActivation: 'command:cancelLegacyHttpActivation',PickLegacyImportSource: 'command:pickLegacyImportSource',RevealLegacyImportSource: 'command:revealLegacyImportSource',PickLegacyTorrentMetadata: 'command:pickLegacyTorrentMetadata',diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.tsindex edd7ccc8..c98ada95 100644--- a/src/shared/protocol/queries.ts+++ b/src/shared/protocol/queries.ts@@ -2,6 +2,8 @@ export const Queries = {GetRendererSession: 'query:getRendererSession',GetLegacyImportNavigation: 'query:getLegacyImportNavigation',GetLegacyBtActivationAvailability: 'query:getLegacyBtActivationAvailability',+ GetLegacyHttpActivationAvailability:+ 'query:getLegacyHttpActivationAvailability',DiscoverLegacyImport: 'query:discoverLegacyImport',ScanLegacyImport: 'query:scanLegacyImport',GetLegacyImportRun: 'query:getLegacyImportRun',diff --git a/src/shared/schemas/add-task.test.ts b/src/shared/schemas/add-task.test.tsindex bf1de12b..2f48dec8 100644--- a/src/shared/schemas/add-task.test.ts+++ b/src/shared/schemas/add-task.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import {addTaskFormSchema,+ addTaskPrefillSchema,addTaskUrlParamsSchema,encodeUrlParams,formValuesToTaskCreateRequest,@@ -10,6 +11,30 @@ import {} from './add-task'describe('addTaskFormSchema', () => {+ it('carries migration option names through the draft without submitting them', () => {+ const draft = addTaskPrefillSchema.parse({+ tab: 'links',+ urls: 'https://a.com/f.zip',+ saveDir: '/downloads/new',+ legacyRequestOptions: ['header', 'all-proxy'],+ })+ expect(draft).toHaveProperty('legacyRequestOptions', [+ 'header',+ 'all-proxy',+ ])+ const request = formValuesToTaskCreateRequest(+ addTaskFormSchema.parse(draft)+ )+ expect(request).not.toHaveProperty('legacyRequestOptions')+ expect(request).toMatchObject({ headers: [], proxy: undefined })+ expect(+ addTaskPrefillSchema.safeParse({+ ...draft,+ legacyRequestOptions: ['header=Cookie: secret'],+ }).success+ ).toBe(false)+ })+it('accepts minimal links tab', () => {const result = addTaskFormSchema.safeParse({tab: 'links',diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.tsindex 36f8f19a..8fdba8dd 100644--- a/src/shared/schemas/add-task.ts+++ b/src/shared/schemas/add-task.ts@@ -2,6 +2,7 @@ import { analyzeDownloadInput } from '@shared/lib/download-source-input'import { MAX_TORRENT_BASE64_SIZE } from '@shared/lib/torrent-meta'import { z } from 'zod'import { MAX_MIRROR_URIS, type SourceFailure } from './download-source'+import { legacyOptionNamesSchema } from './legacy-import'import { infoHashToMagnetUri } from './magnet-input'const torrentFileSchema = z.object({@@ -21,7 +22,7 @@ const torrentMetaSchema = z.object({export { torrentMetaSchema }const httpHeaderSchema = z.object({- name: z.string().min(1),+ name: z.string().min(1, { message: 'task.add.errors.headerNameRequired' }),value: z.string(),})@@ -37,6 +38,8 @@ const linksTabSchema = z.object({cookie: z.string().optional(),authorization: z.string().optional(),allProxy: z.string().optional(),+ // Draft-only reminder; option values are entered explicitly in the new task.+ legacyRequestOptions: legacyOptionNamesSchema.optional(),})const torrentTabSchema = zdiff --git a/src/shared/schemas/legacy-http-activation.ts b/src/shared/schemas/legacy-http-activation.tsnew file mode 100644index 00000000..d21b7b00--- /dev/null+++ b/src/shared/schemas/legacy-http-activation.ts@@ -0,0 +1,65 @@+import { z } from 'zod'+import { directResourceValidatorSchema } from './direct-replay-recipe'+import {+ legacyCheckpointFileSchema,+ legacyCheckpointMetadataSchema,+} from './legacy-checkpoint'++/** Safe recovery identity only; HTTP credentials stay in the original profile. */+export const legacyHttpActivationSchema = z+ .object({+ version: z.literal(1),+ stage: z.enum([+ 'import-uncertain',+ 'checkpoint',+ 'create-uncertain',+ 'bound',+ 'resume-uncertain',+ 'active',+ ]),+ token: z.string().regex(/^[A-Za-z0-9_-]{16,128}$/),+ engineTaskId: z+ .string()+ .regex(/^[a-f0-9]{16}$/)+ .refine((value) => !/^0+$/.test(value)),+ targetPath: z.string().min(1).max(4096),+ saveDir: z.string().min(1).max(4096),+ rootIdentity: z.string().min(1),+ controlBackupPath: z.string().min(1),+ controlIdentity: z.string().min(1),+ controlDigest: z.string().regex(/^[a-f0-9]{64}$/),+ uriDigest: z.string().regex(/^[a-f0-9]{64}$/),+ expected: legacyCheckpointMetadataSchema.refine(+ (value) => value.type === 'http' && value.infoHash === null+ ),+ files: z.tuple([legacyCheckpointFileSchema]),+ completedBytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),+ retainedContentDigest: z+ .string()+ .regex(/^[a-f0-9]{64}$/)+ .optional(),+ resourceValidator: directResourceValidatorSchema.options[0],+ })+ .strict()+ .superRefine((value, ctx) => {+ if (+ value.files[0].path !== value.targetPath ||+ value.files[0].offset !== 0 ||+ value.files[0].length !== value.expected.totalBytes ||+ value.completedBytes > value.expected.totalBytes ||+ value.resourceValidator.contentLength !== value.expected.totalBytes ||+ (value.stage === 'resume-uncertain' && !value.retainedContentDigest)+ )+ ctx.addIssue({+ code: 'custom',+ message: 'HTTP checkpoint identity mismatch',+ })+ })+export type LegacyHttpActivation = z.infer<typeof legacyHttpActivationSchema>+export const legacyHttpAvailabilitySchema = z+ .object({+ available: z.boolean(),+ reason: z.string().nullable(),+ directory: z.string(),+ })+ .strict()diff --git a/src/shared/schemas/legacy-import.ts b/src/shared/schemas/legacy-import.tsindex f052c2fd..574de78e 100644--- a/src/shared/schemas/legacy-import.ts+++ b/src/shared/schemas/legacy-import.ts@@ -13,6 +13,8 @@ export const legacyReasonSchema = z.enum(['verification-required','metadata-required','selection-required',+ 'request-settings-required',+ 'mirrors-unsupported','unsupported-options','invalid-record','unsafe-path',@@ -26,6 +28,18 @@ export const legacyReasonSchema = z.enum([])export type LegacyReason = z.infer<typeof legacyReasonSchema>+// Names only: request credentials and option values must not enter previews,+// reports or the task database.+export const legacyOptionNamesSchema = z+ .array(+ z+ .string()+ .min(1)+ .max(64)+ .regex(/^[a-z0-9-]+$/)+ )+ .max(64)+export const legacyImportItemSchema = z.object({itemId: z.string().min(1).max(128),name: z.string().max(1024),@@ -34,6 +48,8 @@ export const legacyImportItemSchema = z.object({type: z.enum(['http', 'bt', 'magnet', 'unknown']),selectable: z.boolean(),reason: legacyReasonSchema,+ requestOptions: legacyOptionNamesSchema.optional(),+ unsupportedOptions: legacyOptionNamesSchema.optional(),})export type LegacyImportItem = z.infer<typeof legacyImportItemSchema>@@ -118,8 +134,13 @@ export const legacyTaskMetadataSchema = zsourceId: z.string(),itemKey: z.string(),activation: z.enum(['inactive', 'activating', 'active']),- storagePolicy: z.enum(['legacy-read-only', 'legacy-bt-in-place']),+ storagePolicy: z.enum([+ 'legacy-read-only',+ 'legacy-bt-in-place',+ 'legacy-http-in-place',+ ]),reason: legacyReasonSchema,+ requestOptions: legacyOptionNamesSchema.optional(),selectionKnown: z.boolean(),selectedFiles: z.array(z.number().int().nonnegative()).max(10000),origin: zdiff --git a/src/shared/types/task-actions.test.ts b/src/shared/types/task-actions.test.tsindex 670b39eb..184f4b49 100644--- a/src/shared/types/task-actions.test.ts+++ b/src/shared/types/task-actions.test.ts@@ -7,6 +7,7 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it } from 'vitest'import {@@ -23,6 +24,7 @@ import {canStopSeeding,getTaskRetryKind,isFinalizing,+ isLegacyImportInactive,} from './task-actions'function muxInstance(status: TaskStatus): TaskInstance {@@ -156,6 +158,44 @@ describe('canPause', () => {})describe('canResume', () => {+ it('allows an HTTP migration to resume only after its first activation', () => {+ const task = makeLegacyHttpTask()+ expect(isLegacyImportInactive(task)).toBe(false)+ expect(canResume(task)).toBe(true)+ expect(canRetry({ ...task, status: TaskStatus.Error })).toBe(false)+ expect(canRedownload({ ...task, status: TaskStatus.Completed })).toBe(false)+ })++ it.each([+ { stage: 'checkpoint' },+ { stage: 'create-uncertain' },+ { stage: 'bound' },+ { stage: 'resume-uncertain', retainedContentDigest: 'a'.repeat(64) },+ { version: 2 },+ { engineTaskId: 'abcdef1234567890' },+ { resourceValidator: { kind: 'last-modified', value: 'yesterday' } },+ ])('blocks HTTP migration with unconfirmed intent %j', (change) => {+ const task = makeLegacyHttpTask()+ Object.assign(+ task.instances[0].payload.legacyHttpActivation as object,+ change+ )+ expect(isLegacyImportInactive(task)).toBe(true)+ expect(canResume(task)).toBe(false)+ })++ it('requires the active HTTP storage marker even with a valid intent', () => {+ const task = makeLegacyHttpTask()+ Object.assign(task.instances[0].payload.legacyImport as object, {+ activation: 'activating',+ })+ expect(canResume(task)).toBe(false)+ delete task.instances[0].payload.legacyImport+ expect(isLegacyImportInactive(task)).toBe(true)+ expect(canResume(task)).toBe(false)+ expect(canRetry({ ...task, status: TaskStatus.Error })).toBe(false)+ })+it('returns true only for Paused', () => {expect(canResume(makeTask({ status: TaskStatus.Paused }))).toBe(true)expect(canResume(makeTask({ status: TaskStatus.Downloading }))).toBe(false)diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex 5632990e..6be1c54b 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -1,5 +1,6 @@import { isUriOnlyDirectReplay } from '@shared/schemas/direct-replay-recipe'import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'+import { legacyHttpActivationSchema } from '@shared/schemas/legacy-http-activation'import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'import {type DownloadTask,@@ -261,8 +262,10 @@ export function canAttemptRetry(t: DownloadTask): boolean {}export function hasLegacyImport(t: Pick<DownloadTask, 'instances'>): boolean {- return (t.instances ?? []).some((instance) =>- Object.hasOwn(instance.payload ?? {}, 'legacyImport')+ return (t.instances ?? []).some(+ (instance) =>+ Object.hasOwn(instance.payload ?? {}, 'legacyImport') ||+ Object.hasOwn(instance.payload ?? {}, 'legacyHttpActivation'))}@@ -271,10 +274,25 @@ export function isLegacyImportInactive(t: Pick<DownloadTask, 'instances'>): boolean {return (t.instances ?? []).some((instance) => {- if (!Object.hasOwn(instance.payload ?? {}, 'legacyImport')) return false+ if (!Object.hasOwn(instance.payload ?? {}, 'legacyImport'))+ return Object.hasOwn(instance.payload ?? {}, 'legacyHttpActivation')const marker = legacyTaskMetadataSchema.safeParse(instance.payload.legacyImport)+ if (+ marker.success &&+ marker.data.storagePolicy === 'legacy-http-in-place'+ ) {+ const activation = legacyHttpActivationSchema.safeParse(+ instance.payload.legacyHttpActivation+ )+ return (+ marker.data.activation !== 'active' ||+ !activation.success ||+ activation.data.stage !== 'active' ||+ instance.gid !== activation.data.engineTaskId+ )+ }const activation = legacyBtActivationSchema.safeParse(instance.payload.legacyBtActivation)diff --git a/src/test-utils/legacy-http-activation.ts b/src/test-utils/legacy-http-activation.tsnew file mode 100644index 00000000..4136ab1d--- /dev/null+++ b/src/test-utils/legacy-http-activation.ts@@ -0,0 +1,114 @@+import { createHash } from 'node:crypto'+import path from 'node:path'+import type { LegacyHttpActivation } from '@shared/schemas/legacy-http-activation'+import type { LegacyTaskMetadata } from '@shared/schemas/legacy-import'+import {+ type DownloadTask,+ TaskInstancePhase,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { makeDownloadTask } from './task'++/** A validated in-place HTTP migration with one immutable original source. */+export function makeLegacyHttpTask(+ overrides: Partial<DownloadTask> = {}+): DownloadTask {+ const id = overrides.id ?? 'legacy-http'+ const gid = overrides.engineTaskId ?? '1234567890abcdef'+ const targetPath = overrides.finalPath ?? '/original/file.bin'+ const uris = overrides.uris ?? ['https://example.com/file.bin']+ const status = overrides.status ?? TaskStatus.Paused+ const totalBytes = overrides.totalBytes ?? 1024+ const downloadedBytes = overrides.downloadedBytes ?? 512+ const intent: LegacyHttpActivation = {+ version: 1,+ stage: 'active',+ token: 'legacy-http-token',+ engineTaskId: gid,+ targetPath,+ saveDir: path.dirname(targetPath),+ rootIdentity: '1:2:0:0:0',+ controlBackupPath: '/metadata/control.backup',+ controlIdentity: '1:3:100:0:0',+ controlDigest: 'a'.repeat(64),+ uriDigest: createHash('sha256').update(uris[0]).digest('hex'),+ expected: {+ type: 'http',+ totalBytes,+ pieceBytes: 512,+ infoHash: null,+ },+ files: [+ {+ path: targetPath,+ offset: 0,+ length: totalBytes,+ identity: {+ device: '1',+ inode: '2',+ size: String(totalBytes),+ mtimeNs: '0',+ ctimeNs: '0',+ },+ },+ ],+ completedBytes: downloadedBytes,+ resourceValidator: {+ kind: 'strong-etag',+ value: '"original"',+ contentLength: totalBytes,+ capturedAt: 1,+ },+ }+ const marker: LegacyTaskMetadata = {+ version: 1,+ sourceId: 'source',+ itemKey: 'item',+ activation: 'active',+ storagePolicy: 'legacy-http-in-place',+ reason: 'verification-required',+ selectionKnown: true,+ selectedFiles: [0],+ }+ return makeDownloadTask({+ id,+ engineTaskId: gid,+ name: path.basename(targetPath),+ type: TaskType.Http,+ status,+ saveDir: path.dirname(targetPath),+ diskPath: targetPath,+ finalPath: targetPath,+ finalName: path.basename(targetPath),+ totalBytes,+ downloadedBytes,+ sizeWhenDone: totalBytes,+ progress: downloadedBytes / totalBytes,+ fileCount: 1,+ pieceLength: 512,+ uris,+ instances: [+ {+ instanceId: `primary:${id}`,+ motrixId: id,+ gid,+ phase: TaskInstancePhase.HttpDownload,+ status,+ progress: (downloadedBytes / totalBytes) * 100,+ totalBytes,+ downloadedBytes,+ uploadedBytes: 0,+ diskPath: targetPath,+ transitionPhase: TransitionPhase.Idle,+ uris: [...uris],+ uriHash: null,+ payload: { legacyImport: marker, legacyHttpActivation: intent },+ createdAt: 0,+ updatedAt: 0,+ },+ ],+ ...overrides,+ })+}diff --git a/src/test-utils/legacy-http-service.ts b/src/test-utils/legacy-http-service.tsnew file mode 100644index 00000000..6679900a--- /dev/null+++ b/src/test-utils/legacy-http-service.ts@@ -0,0 +1,224 @@+import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { gunzipSync } from 'node:zlib'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import {+ type LegacyHttpActivationDeps,+ LegacyHttpActivationService,+} from '@core/legacy-import/http-activation-service'+import { authorizeLegacySource } from '@core/legacy-import/source-scanner'+import type {+ MotrixDatabase,+ TaskWithInstances,+} from '@core/session/motrix-database'+import { TaskManager } from '@core/task/task-manager'+import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'+import {+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { vi } from 'vitest'++function secureWindowsFixture(root: string): void {+ if (process.platform !== 'win32') return+ const sid = execFileSync(+ 'powershell.exe',+ [+ '-NoProfile',+ '-Command',+ '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',+ ],+ { encoding: 'utf8' }+ ).trim()+ execFileSync('icacls.exe', [+ root,+ '/inheritance:r',+ '/grant:r',+ `*${sid}:(OI)(CI)F`,+ '*S-1-5-18:(OI)(CI)F',+ '*S-1-5-32-544:(OI)(CI)F',+ ])+ execFileSync('icacls.exe', [root, '/setowner', `*${sid}`, '/T'])+}++const hash = (bytes: Uint8Array) =>+ createHash('sha256').update(bytes).digest('hex')+export const LEGACY_HTTP_TOTAL = 4194304+export const LEGACY_HTTP_COMPLETED = 1638400++/** Real legacy HTTP payload/control bytes with an isolated persistence seam. */+export async function legacyHttpActivationFixture(options: {+ adapter: EngineAdapter+ uri?: string+ requestLines?: string+ system?: Record<string, unknown>+ verifier?: LegacyHttpActivationDeps['verifier']+}) {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-http-activation-'))+ )+ const profile = path.join(root, 'profile')+ const downloads = path.join(root, 'downloads')+ const backupRoot = path.join(root, 'backups')+ for (const dir of [profile, downloads, backupRoot])+ await mkdir(dir, { mode: 0o700 })+ const uri = options.uri ?? 'http://127.0.0.1:18080/partial.bin'+ const target = path.join(downloads, 'partial.bin')+ const fixtureRoot = path.resolve(+ 'tests/fixtures/legacy-v1/generated/downloads'+ )+ const payload = gunzipSync(+ await readFile(path.join(fixtureRoot, 'partial.bin.gz'))+ )+ const control = await readFile(path.join(fixtureRoot, 'partial.bin.aria2'))+ await writeFile(target, payload, { mode: 0o600 })+ await writeFile(`${target}.aria2`, control, { mode: 0o600 })+ const profiles: Record<string, Buffer> = {+ 'download.session': Buffer.from(+ `${uri}\n gid=0123456789abcdef\n dir=${downloads}\n out=partial.bin\n pause=true\n no-netrc=true\n${options.requestLines ?? ''}`+ ),+ 'system.json': Buffer.from(+ JSON.stringify({ dir: downloads, ...options.system })+ ),+ 'user.json': Buffer.from(JSON.stringify({ locale: 'en-US' })),+ }+ for (const [name, bytes] of Object.entries(profiles))+ await writeFile(path.join(profile, name), bytes)+ secureWindowsFixture(root)+ const source = await authorizeLegacySource(profile)+ const taskId = 'http-legacy-fixture'+ const row: TaskWithInstances = {+ task: {+ motrixId: taskId,+ name: 'partial.bin',+ kind: TaskKind.Direct,+ taskType: TaskType.Http,+ category: null,+ priority: 0,+ tags: null,+ createdAt: 1,+ updatedAt: 1,+ saveDir: downloads,+ finalPath: target,+ finalName: 'partial.bin',+ torrentMetaPath: null,+ infoHash: null,+ totalBytes: 0,+ downloadedBytes: 0,+ sizeWhenDone: 0,+ fileCount: 1,+ isPrivate: false,+ trackers: [],+ pieceLength: 0,+ aggStatus: TaskStatus.Paused,+ finishedAt: null,+ errorMessage: null,+ errorCode: null,+ errorDetailKey: null,+ errorDetailParams: null,+ diagnosisRevision: 0,+ uploadedBytesBaseline: 0,+ source: 'user',+ sourceMeta: null,+ },+ instances: [+ {+ instanceId: 'http-instance',+ motrixId: taskId,+ gid: null,+ phase: TaskInstancePhase.HttpDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: target,+ transitionPhase: TransitionPhase.Idle,+ uris: [uri],+ uriHash: null,+ createdAt: 1,+ updatedAt: 1,+ payload: {+ legacyImport: {+ version: 1,+ sourceId: 'source',+ itemKey: 'gid:0123456789abcdef',+ activation: 'inactive',+ storagePolicy: 'legacy-read-only',+ reason: 'verification-required',+ selectionKnown: false,+ selectedFiles: [],+ origin: {+ root: source.root,+ identity: source.identity,+ sessionDigest: hash(profiles['download.session']),+ torrentDigest: null,+ profileFiles: Object.entries(profiles).map(+ ([relativePath, bytes]) => ({+ relativePath,+ digest: hash(bytes),+ })+ ),+ },+ },+ },+ },+ ],+ }+ const rows = new Map([[taskId, row]])+ const db = {+ getTask: (id: string) => {+ const current = rows.get(id)+ return current ? structuredClone(current) : undefined+ },+ getAllTasks: () =>+ [...rows.values()].map((current) => structuredClone(current)),+ saveTaskWithInstances: (next: TaskWithInstances) =>+ rows.set(next.task.motrixId, structuredClone(next)),+ } as unknown as MotrixDatabase+ const taskManager = new TaskManager()+ taskManager.set(taskId, taskRowToDownloadTask(row.task, row.instances))+ const deps: LegacyHttpActivationDeps = {+ db,+ taskManager,+ adapter: options.adapter,+ backupRoot,+ isProcessRunning: vi.fn(() => false),+ publishTasks: vi.fn(),+ runTaskMutation: async (_ids, operation) => operation(),+ runExclusivePersistence: async (operation) => operation(),+ verifier: options.verifier,+ }+ const service = new LegacyHttpActivationService(deps)+ return {+ root,+ profile,+ downloads,+ target,+ taskId,+ payload,+ control,+ rows,+ db,+ taskManager,+ deps,+ service,+ dispose: async () => {+ await service.drain()+ await rm(root, { recursive: true, force: true })+ },+ }+}diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.tsindex b78465b1..dfc011bc 100644--- a/tests/check-third-party-notices.test.ts+++ b/tests/check-third-party-notices.test.ts@@ -460,9 +460,9 @@ describe('third-party graph dependency notices', () => {expect(notice).toContain('SFNS-Regular.ttf')expect(notice).toContain('https://developer.apple.com/fonts/')- expect(notice).toContain('1.37.0-motrix.19')+ expect(notice).toContain('1.37.0-motrix.20')expect(notice).toContain(- 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.19'+ 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.20')expect(notice).toContain('GPL-2.0-or-later')expect(notice).toContain('THIRD_PARTY_LICENSES/aria2-COPYING')diff --git a/tests/generate-third-party-notices.test.ts b/tests/generate-third-party-notices.test.tsindex 580788dd..d113d826 100644--- a/tests/generate-third-party-notices.test.ts+++ b/tests/generate-third-party-notices.test.ts@@ -171,7 +171,7 @@ describe('third-party notice generator', () => {expect(bundle.packageCount).toBeGreaterThan(100)expect(inventory).toContain('| @xyflow/react | 12.12.0 |')- expect(inventory).toContain('| aria2 | 1.37.0-motrix.19 |')+ expect(inventory).toContain('| aria2 | 1.37.0-motrix.20 |')expect(inventory).toContain('| motrix.filename-template | 1.1.1 |')expect(inventory).toContain('Apple San Francisco tray font')expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')@@ -282,7 +282,7 @@ describe('third-party notice generator', () => {expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')}const serverInventory = server.files['THIRD_PARTY_DEPENDENCIES.md']- expect(serverInventory).toContain('| aria2 | 1.37.0-motrix.19 |')+ expect(serverInventory).toContain('| aria2 | 1.37.0-motrix.20 |')expect(serverInventory).toContain('| motrix.filename-template | 1.1.1 |')expect(serverInventory).not.toContain('| Electron |')diff --git a/tests/scripts/electron-package-contract.test.ts b/tests/scripts/electron-package-contract.test.tsindex f255e81a..b9c0fbcd 100644--- a/tests/scripts/electron-package-contract.test.ts+++ b/tests/scripts/electron-package-contract.test.ts@@ -281,7 +281,7 @@ describe('Electron package contracts', () => {expect(contract).toEqual({schemaVersion: 1,- payloadBytes: 27 * 1024 * 1024,+ payloadBytes: 30 * 1024 * 1024,betterSqlite3Bytes: 4 * 1024 * 1024,unexpectedPackageNames: 0,foreignBetterSqlite3Prebuilds: 0,