A full-featured download manager.
feat(migration): add the v1 migration assistant (#2331)
Dr_rOote1ff6509d7ab
diff --git a/.gitattributes b/.gitattributesindex 03f72abb..f9ad9d87 100644--- a/.gitattributes+++ b/.gitattributes@@ -20,3 +20,8 @@ scripts/verify-electron-package.mjs text eol=lfscripts/sign-macos.mjs text eol=lfbuild/entitlements.safari.plist text eol=lfbuild/app.motrix.safari.bootstrap.plist text eol=lf++# Old-engine fixture bytes are intentional. aria2 appends a TAB to mirror+# URI lines; retain that serialized syntax and prevent checkout conversion.+tests/fixtures/legacy-v1/generated/** -text+tests/fixtures/legacy-v1/generated/profile/download.session whitespace=-blank-at-eoldiff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 9f38726f..2ff63560 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -38,6 +38,20 @@ and are not relicensed under Motrix’s MIT license.The round curled-tail squirrel silhouette follows a user-supplied referenceimage whose external author and license have not been verified.+## Glassmorphism migration import icon++The migration assistant uses a newly modeled purple glass folder and a+right-pointing arrow entering from the left, rendered in Blender with+glass/satin materials and studio lighting derived from the supplied+Glassmorphism collection's `File.blend`. The transparent lossless WebP assets are stored+in `src/renderer/features/legacy-import/icons/[email protected]` and+`[email protected]` at 128px and 256px. The supplied source has no verified+author or license declaration; inherited materials and lighting remain+`NOASSERTION` and are not relicensed under Motrix’s MIT license.++The folder-and-arrow silhouette follows a user-supplied reference image whose+external author and license have not been verified.+The previous Iconly Pro settings PNG assets have been removed from thisversion. Earlier versions containing those assets remain subject to theiroriginal UI8 license terms.diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.mdindex feb993ef..9ffc1513 100644--- a/THIRD_PARTY_NOTICES.zh-CN.md+++ b/THIRD_PARTY_NOTICES.zh-CN.md@@ -31,6 +31,17 @@ Dashboard 速度模式卡片使用新建的兔子、乌龟和松鼠几何模型圆卷尾松鼠的轮廓依据用户提供的参考图重建,该参考图的外部作者和许可尚未确认。+## 玻璃质感导入图标(Glassmorphism migration import icon)++迁移助手使用新建的紫色玻璃文件夹,以及从左侧进入、指向右侧的箭头,在 Blender 中沿用所提供+Glassmorphism 素材集 `File.blend` 的玻璃、缎面材质和摄影棚灯光渲染。+透明无损 WebP 资源以 128px 和 256px 保存于+`src/renderer/features/legacy-import/icons/[email protected]` 和+`[email protected]`。所提供的源文件没有可确认的作者或许可证声明,+继承的材质和灯光许可记录为 `NOASSERTION`,未重新授权为 Motrix 的 MIT 许可。++文件夹与箭头的轮廓依据用户提供的参考图重建,该参考图的外部作者和许可尚未确认。+本版本已移除旧版 Iconly Pro 设置图标 PNG。包含这些资源的历史版本仍遵循其原有的 UI8 许可条款。diff --git a/docs/production-builds.md b/docs/production-builds.mdindex d341b824..34ca6d21 100644--- a/docs/production-builds.md+++ b/docs/production-builds.md@@ -78,6 +78,11 @@ diagnostic names, and executable behavior survive compression. Platform packageverification and runtime smoke tests remain the authority for installed sizesand native runtime compatibility.+The migration assistant brings the complete main-process JavaScript output to+approximately 5.09 MiB, including its services and translations in all 26+languages. Its total budget is 5.25 MiB; the startup budget remains 2 MiB.+Budgets for the other five targets are unchanged.+## Desktop navigation comparisonBuild each revision with `pnpm build:electron` in a separate checkout with itsdiff --git a/docs/production-builds.zh-CN.md b/docs/production-builds.zh-CN.mdindex c89acb0a..d94b5fe7 100644--- a/docs/production-builds.zh-CN.md+++ b/docs/production-builds.zh-CN.md@@ -61,6 +61,10 @@ CI 检查初始及完整 JavaScript 体积预算,确认 26 种语言均被打服务端构建夹具还验证压缩后源码文档已移除,而许可证声明、诊断名称和执行行为仍然保留。各平台的包验证与运行冒烟测试继续负责检查安装体积及原生运行时兼容性。+迁移助手增加迁移服务和 26 种语言资源后,主进程完整 JavaScript 产物约为+5.09 MiB,总量预算为 5.25 MiB;启动体积预算仍为 2 MiB。+其他五类产物的预算保持不变。+## 桌面导航性能对比在两个各自安装依赖的独立检出目录中,对两个版本分别运行 `pnpm build:electron`,diff --git a/e2e/disclaimer.spec.ts b/e2e/disclaimer.spec.tsindex 544c0268..cccee35b 100644--- a/e2e/disclaimer.spec.ts+++ b/e2e/disclaimer.spec.ts@@ -152,9 +152,9 @@ test.describe('disclaimer startup gate', () => {await expect(main.getByRole('button', { name: 'Syncing...' })).toBeDisabled()- await expect(main.getByRole('status')).toHaveText(- 'Fetching tracker lists…'- )+ await expect(+ main.getByRole('status').filter({ hasText: 'Fetching tracker lists…' })+ ).toHaveText('Fetching tracker lists…')await expect(main.getByRole('tabpanel')).toContainText('Fetching tracker lists…')diff --git a/e2e/legacy-bt-activation.spec.ts b/e2e/legacy-bt-activation.spec.tsnew file mode 100644index 00000000..d629f205--- /dev/null+++ b/e2e/legacy-bt-activation.spec.ts@@ -0,0 +1,189 @@+import { cp, mkdir, readFile, writeFile } from 'node:fs/promises'+import path from 'node:path'+import type { Page } from '@playwright/test'+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'+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) {+ return page.evaluate(+ async ({ channel, input }) => {+ const api = (+ window as unknown as {+ motrix: {+ invoke: (channel: string, input?: unknown) => Promise<unknown>+ }+ }+ ).motrix+ return api.invoke(channel, input)+ },+ { channel, input }+ )+}++test('verifies imported BT files through the desktop UI and preserves them after removal', async ({+ userDataDir,+ rpcPort,+}, testInfo) => {+ // Opt in only when the staged development engine has both migration contracts.+ test.skip(+ process.env.MOTRIX_E2E_LEGACY_BT !== '1',+ 'Requires a staged legacy BT activation engine'+ )+ const root = path.join(userDataDir, 'generated-v1')+ await cp('tests/fixtures/legacy-v1/generated', root, { recursive: true })+ const source = path.join(root, 'profile')+ const downloads = path.join(root, 'downloads')+ for (const name of ['download.session', 'system.json']) {+ const filename = path.join(source, name)+ await writeFile(+ filename,+ (await readFile(filename, 'utf8'))+ .replaceAll('__FIXTURE_ROOT__', source)+ .replaceAll('__FIXTURE_DOWNLOADS__', downloads)+ .replaceAll('__FIXTURE_HTTP_PORT__', String(rpcPort))+ )+ }+ await mkdir(path.join(downloads, 'fixture-bundle'))+ const originalFiles = [+ ['first.bin', Buffer.alloc(16384, 1)],+ ['second.bin', Buffer.alloc(16384, 2)],+ ] as const+ for (const [name, bytes] of originalFiles)+ await writeFile(path.join(downloads, 'fixture-bundle', name), bytes, {+ mode: 0o600,+ })+ const torrentPath = path.join(+ downloads,+ 'a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent'+ )+ const torrentBefore = await readFile(torrentPath)+ const controlPath = path.join(downloads, 'fixture-bundle.aria2')+ const controlBefore = await readFile(controlPath)+ await writeFile(+ path.join(userDataDir, 'settings.json'),+ JSON.stringify({+ version: CURRENT_SETTINGS_VERSION,+ tracker: { autoSync: false },+ onboarding: { disclaimerAccepted: true },+ engine: { dhtEnabled: false, btEnableLpd: false },+ }),+ { flag: 'wx' }+ )+ let app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const invitation = await app.firstWindow()+ await invitation.waitForLoadState('domcontentloaded')+ await invitation.getByRole('button', { name: 'Choose downloads' }).click()+ // Deselect every selectable row, then authorize precisely the old torrent.+ for (const box of await invitation.getByRole('checkbox').all())+ if ((await box.isEnabled()) && (await box.isChecked()))+ await box.uncheck()+ await invitation.getByText('Skipped: 1', { exact: true }).click()+ await app.evaluate(({ dialog }, filename) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [filename],+ })+ }, torrentPath)+ await invitation.getByRole('button', { name: 'Choose torrent…' }).click()+ await expect(+ invitation.getByRole('checkbox', { name: 'fixture-bundle', exact: true })+ ).toBeChecked()+ await invitation+ .getByRole('button', { name: 'Import 1', exact: true })+ .click()+ await expect(+ invitation.getByText('Imported 1', { exact: true })+ ).toBeVisible()+ await invitation.getByRole('button', { name: 'View downloads' }).click()+ let main = invitation+ await main.waitForLoadState('domcontentloaded')+ await waitForEngineReady(main)+ const tasks = (await invoke(main, Queries.ListTasks)) as DownloadTask[]+ expect(tasks).toHaveLength(1)+ const taskId = tasks[0].id+ expect(tasks[0]).toMatchObject({ status: 'paused', engineTaskId: '' })+ await main.locator(`[data-task-id="${taskId}"]`).dblclick()+ const activate = main.getByRole('button', {+ name: 'Verify and continue',+ exact: true,+ })+ await expect(activate).toBeEnabled()+ await expect(activate).toBeVisible()+ await activate.scrollIntoViewIfNeeded()+ await main.screenshot({+ path: testInfo.outputPath('verify-and-continue.png'),+ })+ await app.evaluate(({ dialog }) => {+ dialog.showOpenDialog = async () => ({ canceled: true, filePaths: [] })+ })+ await activate.click()+ await expect(activate).toBeEnabled()+ expect(+ ((await invoke(main, Queries.ListTasks)) as DownloadTask[])[0]+ .engineTaskId+ ).toBe('')+ await app.evaluate(({ dialog }, directory) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [directory],+ })+ }, downloads)+ await activate.click()+ await expect+ .poll(+ async () =>+ ((await invoke(main, Queries.ListTasks)) as DownloadTask[])[0]+ ?.status,+ { timeout: 20000 }+ )+ .toBe('completed')+ const completed = (+ (await invoke(main, Queries.ListTasks)) as DownloadTask[]+ )[0]+ expect(completed.engineTaskId).toMatch(/^[a-f0-9]{16}$/)+ await main.screenshot({+ path: testInfo.outputPath('verified-completed.png'),+ })+ await app.close()+ app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ main = await app.firstWindow()+ await main.waitForLoadState('domcontentloaded')+ await waitForEngineReady(main)+ await expect+ .poll(() => invoke(main, Queries.ListTasks))+ .toMatchObject([+ {+ id: taskId,+ status: 'completed',+ engineTaskId: completed.engineTaskId,+ },+ ])+ await invoke(main, Commands.RemoveTask, { taskId, deleteWithFiles: true })+ expect(await invoke(main, Queries.ListTasks)).toEqual([])+ for (const [name, bytes] of originalFiles)+ expect(+ await readFile(path.join(downloads, 'fixture-bundle', name))+ ).toEqual(bytes)+ expect(await readFile(torrentPath)).toEqual(torrentBefore)+ expect(await readFile(controlPath)).toEqual(controlBefore)+ } finally {+ await app.close().catch(() => {})+ }+})diff --git a/e2e/legacy-import.spec.ts b/e2e/legacy-import.spec.tsnew file mode 100644index 00000000..28b80b72--- /dev/null+++ b/e2e/legacy-import.spec.ts@@ -0,0 +1,818 @@+import { cp, mkdir, readFile, writeFile } from 'node:fs/promises'+import path from 'node:path'+import type { ElectronApplication, Page } from '@playwright/test'+import { Commands } from '../src/shared/protocol/commands'+import { Queries } from '../src/shared/protocol/queries'+import {+ expect,+ launchMotrix,+ test,+ waitForEngineReady,+ waitForQueryHandlers,+} from './fixtures/electron-app'++/** Minimal synthetic source for the isolated consent and lifecycle cases. */+async function legacyProfile(userDataDir: string): Promise<string> {+ const root = path.join(userDataDir, 'legacy-v1')+ const dir = path.join(root, 'downloads')+ await mkdir(dir, { recursive: true })+ await writeFile(+ path.join(root, 'user.json'),+ JSON.stringify({ theme: 'auto', locale: 'en-US' })+ )+ await writeFile(path.join(root, 'system.json'), JSON.stringify({ dir }))+ await writeFile(+ path.join(root, 'download.session'),+ `https://example.invalid/archive.zip\n gid=1234567890abcdef\n dir=${dir}\n out=archive.zip\n pause=true\n`+ )+ await writeFile(path.join(dir, 'archive.zip'), 'original v1 bytes')+ return root+}++async function invoke(+ page: Page,+ channel: string,+ input?: unknown+): Promise<unknown> {+ return page.evaluate(+ async ({ channel, input }) => {+ const api = (+ window as unknown as {+ motrix: {+ invoke: (channel: string, input?: unknown) => Promise<unknown>+ }+ }+ ).motrix+ return input === undefined+ ? api.invoke(channel)+ : api.invoke(channel, input)+ },+ { channel, input }+ )+}++async function firstPage(app: ElectronApplication): Promise<Page> {+ const page = await app.firstWindow()+ await page.waitForLoadState('domcontentloaded')+ return page+}++const sourceTitle = 'Where would you like to migrate from?'++async function expandTaskGroups(page: Page) {+ for (const type of ['http', 'bt', 'magnet', 'unknown']) {+ const disclosure = page.locator(+ `[data-import-group="${type}"] button[aria-expanded="false"]`+ )+ if (await disclosure.count()) await disclosure.click()+ }+}++test.describe('v1 task import', () => {+ test('retains invalid source paths and recovers through the native folder picker', async ({+ userDataDir,+ rpcPort,+ }) => {+ const source = await legacyProfile(userDataDir)+ const systemPath = path.join(source, 'system.json')+ const originalSystem = await readFile(systemPath, 'utf8')+ await writeFile(systemPath, '{}')+ const rejected = path.join(userDataDir, 'not-a-profile')+ await mkdir(rejected)+ 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 expect(page.getByRole('alert')).toContainText(+ 'Unable to read downloads from this location'+ )+ await expect(page.getByRole('radio', { name: source })).toBeDisabled()+ await expect(+ page.getByRole('button', { name: 'Check again', exact: true })+ ).toHaveCount(0)+ const choose = page.getByRole('button', {+ name: 'Choose another location…',+ exact: true,+ })+ await app.evaluate(({ dialog }, dataPath) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [dataPath],+ })+ }, rejected)+ await choose.click()+ await expect(page.getByRole('radio', { name: rejected })).toBeDisabled()+ await expect(page.getByRole('radio', { name: source })).toBeDisabled()+ await app.evaluate(({ dialog }) => {+ dialog.showOpenDialog = async () => ({ canceled: true, filePaths: [] })+ })+ await choose.click()+ await expect(choose).toBeEnabled()+ await expect(page.getByRole('alert')).toBeVisible()+ await writeFile(systemPath, originalSystem)+ await app.evaluate(({ dialog }, dataPath) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [dataPath],+ })+ }, source)+ await choose.click()+ await expect(page.getByRole('radio', { name: source })).toBeEnabled()+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await expect(+ page.getByRole('heading', { name: 'Choose what to migrate' })+ ).toBeVisible()+ expect(await invoke(page, Queries.ListTasks)).toEqual([])+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('keeps group selection and disclosure independent across source navigation', async ({+ userDataDir,+ rpcPort,+ }) => {+ const source = await legacyProfile(userDataDir)+ const sessionPath = path.join(source, 'download.session')+ await writeFile(+ sessionPath,+ `${await readFile(sessionPath, 'utf8')}https://example.invalid/second.zip\n gid=2234567890abcdef\n dir=${path.join(source, 'downloads')}\n out=second.zip\n pause=true\n`+ )+ 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 })+ .dblclick()+ await expect(+ page.getByRole('heading', {+ name: 'Choose what to migrate',+ exact: true,+ })+ ).toBeVisible()+ expect(await invoke(page, Queries.ListTasks)).toEqual([])+ await expandTaskGroups(page)+ const group = page.locator('[data-import-group="http"]')+ const groupCheckbox = group.getByRole('checkbox').first()+ const disclosure = group.locator('button[aria-expanded]')+ const archive = page.getByRole('checkbox', {+ name: 'archive.zip',+ exact: true,+ })+ await archive.uncheck()+ await expect(groupCheckbox).toHaveAttribute('aria-checked', 'mixed')+ await disclosure.click()+ await expect(disclosure).toHaveAttribute('aria-expanded', 'false')+ await expect(+ page.getByRole('button', { name: /^Migrate$/ })+ ).toBeEnabled()+ await disclosure.press('Enter')+ await expect(archive).not.toBeChecked()+ await groupCheckbox.press('Space')+ await expect(archive).toBeChecked()+ await expect(+ page.getByRole('checkbox', { name: 'second.zip', exact: true })+ ).toBeChecked()+ await groupCheckbox.press('Space')+ await expect(+ page.getByRole('button', { name: /^Migrate$/ })+ ).toBeDisabled()+ await archive.check()+ await page+ .getByRole('button', { name: 'Back to source', exact: true })+ .click()+ await page+ .getByRole('button', { name: 'Continue', exact: true })+ .press('Enter')+ await expect(+ page.getByRole('heading', {+ name: 'Choose what to migrate',+ exact: true,+ })+ ).toBeFocused()+ await expandTaskGroups(page)+ await expect(archive).toBeChecked()+ await expect(+ page.getByRole('checkbox', { name: 'second.zip', exact: true })+ ).not.toBeChecked()+ await page.getByRole('button', { name: /^Migrate$/ }).click()+ await expect(+ page+ .getByLabel('Migration summary')+ .getByText('1 task', { exact: true })+ ).toBeVisible()+ expect(await invoke(page, Queries.ListTasks)).toEqual([+ expect.objectContaining({+ name: 'archive.zip',+ status: 'paused',+ engineTaskId: '',+ }),+ ])+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('authorizes an external v1-generated torrent and preserves task selection', async ({+ userDataDir,+ rpcPort,+ }, testInfo) => {+ const root = path.join(userDataDir, 'generated-v1')+ await cp('tests/fixtures/legacy-v1/generated', root, { recursive: true })+ const source = path.join(root, 'profile')+ const downloads = path.join(root, 'downloads')+ for (const name of ['download.session', 'system.json']) {+ const filename = path.join(source, name)+ const content = await readFile(filename, 'utf8')+ await writeFile(+ filename,+ content+ .replaceAll('__FIXTURE_ROOT__', source)+ .replaceAll('__FIXTURE_DOWNLOADS__', downloads)+ .replaceAll('__FIXTURE_HTTP_PORT__', String(rpcPort))+ )+ }+ const torrentPath = path.join(+ downloads,+ 'a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent'+ )+ const original = await readFile(torrentPath)+ const app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const page = await firstPage(app)+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).toBeVisible()+ await expect(+ page.getByRole('link', { name: 'Migration', exact: true })+ ).toBeVisible()+ await expect.poll(() => page.url()).toContain('w=main')+ await expect(+ page.getByRole('button', { name: 'Continue', exact: true })+ ).toBeEnabled()+ await page.screenshot({+ path: testInfo.outputPath('migration-discovery.png'),+ animations: 'disabled',+ })+ await expect(+ page.getByRole('radio', { name: source, exact: true })+ ).toBeChecked()+ await expect(+ page.getByRole('button', { name: 'Show in folder', exact: true })+ ).toBeVisible()+ const sourceViewport = await page.evaluate(() => ({+ width: window.innerWidth,+ height: window.innerHeight,+ }))+ await page.setViewportSize({ width: 800, height: 540 })+ await expect(+ page.getByRole('button', { name: 'Continue', exact: true })+ ).toBeInViewport()+ await expect(+ page.getByRole('radio', { name: source, exact: true })+ ).toBeInViewport()+ expect(+ await page.evaluate(+ () =>+ document.documentElement.scrollWidth <= innerWidth &&+ document.documentElement.scrollHeight <= innerHeight+ )+ ).toBe(true)+ await page.screenshot({+ path: testInfo.outputPath('migration-source-short.png'),+ })+ await page.setViewportSize(sourceViewport)+ await expect+ .poll(() =>+ page+ .locator('[data-slot="migration-import-illustration"]')+ .evaluate(+ (node) =>+ node instanceof HTMLImageElement &&+ node.complete &&+ node.naturalWidth > 0+ )+ )+ .toBe(true)+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await expect(+ page.getByRole('heading', { name: 'Choose what to migrate' })+ ).toBeVisible()+ await expect(+ page.locator('[data-slot="migration-import-illustration"]')+ ).toHaveCount(0)+ await page.screenshot({+ path: testInfo.outputPath('migration-selection.png'),+ })+ await expandTaskGroups(page)+ await page+ .getByRole('checkbox', { name: 'partial.bin', exact: true })+ .uncheck()+ await page+ .getByRole('button', { name: 'Back to source', exact: true })+ .click()+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).toBeVisible()+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await expandTaskGroups(page)+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ await page.getByRole('link', { name: 'Migration', exact: true }).click()+ await expect(+ page.getByRole('checkbox', { name: 'partial.bin', exact: true })+ ).not.toBeChecked()+ const choose = page.getByRole('button', { name: 'Choose torrent…' })+ await expect(choose).toBeVisible()+ await page.screenshot({+ path: testInfo.outputPath('external-torrent.png'),+ })+ await app.evaluate(({ dialog }) => {+ dialog.showOpenDialog = async () => ({ canceled: true, filePaths: [] })+ })+ await choose.click()+ await expect(choose).toBeEnabled()+ await expect(+ page.getByRole('button', { name: /^Migrate$/ })+ ).toBeEnabled()+ await app.evaluate(({ dialog }, torrentPath) => {+ dialog.showOpenDialog = async () => ({+ canceled: false,+ filePaths: [torrentPath],+ })+ }, torrentPath)+ await choose.click()+ await expect(+ page.getByRole('checkbox', { name: 'fixture-bundle', exact: true })+ ).toBeChecked()+ await expect(+ page.getByRole('checkbox', { name: 'partial.bin', exact: true })+ ).not.toBeChecked()+ await expect(+ page.getByRole('button', { name: /^Migrate$/ })+ ).toBeEnabled()+ await expect(+ page+ .locator('.migration-task-row')+ .getByTitle(downloads, { exact: true })+ ).toHaveCount(3)+ await expect(+ page.locator('.migration-task-row [data-slot="badge"]')+ ).toHaveCount(3)+ expect(+ await page.evaluate(() => ({+ vertical:+ document.documentElement.scrollHeight <= window.innerHeight + 1,+ horizontal:+ document.documentElement.scrollWidth <= window.innerWidth + 1,+ }))+ ).toEqual({ vertical: true, horizontal: true })+ await page.screenshot({+ path: testInfo.outputPath('authorized-torrent.png'),+ })+ await invoke(page, Commands.UpdateSettings, {+ app: { language: 'zh-CN' },+ })+ await expect(+ page.getByRole('heading', { name: '选择要迁移的内容', exact: true })+ ).toBeVisible()+ await expect(+ page.getByRole('checkbox', { name: 'partial.bin', exact: true })+ ).not.toBeChecked()+ await page.screenshot({+ path: testInfo.outputPath('migration-zh-CN.png'),+ })+ await invoke(page, Commands.UpdateSettings, {+ app: { language: 'en-US' },+ })+ await expect(+ page.getByRole('button', { name: /^Migrate$/ })+ ).toBeEnabled()+ const initialViewport = await page.evaluate(() => ({+ width: window.innerWidth,+ height: window.innerHeight,+ }))+ await page.setViewportSize({ width: 800, height: 540 })+ await expect(+ page.getByRole('button', { name: /^Migrate$/ })+ ).toBeInViewport()+ expect(+ await page.evaluate(() => ({+ vertical:+ document.documentElement.scrollHeight <= window.innerHeight + 1,+ horizontal:+ document.documentElement.scrollWidth <= window.innerWidth + 1,+ }))+ ).toEqual({ vertical: true, horizontal: true })+ await page.screenshot({+ path: testInfo.outputPath('migration-short.png'),+ })+ await page.setViewportSize(initialViewport)+ await page.getByRole('button', { name: /^Migrate$/ }).click()+ await expect(+ page+ .getByLabel('Migration summary')+ .getByText('2 tasks', { exact: true })+ ).toBeVisible()+ await page.screenshot({+ path: testInfo.outputPath('migration-result.png'),+ animations: 'disabled',+ })+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ await page.getByRole('link', { name: 'Migration', exact: true }).click()+ await expect(+ page+ .getByLabel('Migration summary')+ .getByText('2 tasks', { exact: true })+ ).toBeVisible()+ await page.getByRole('button', { name: 'View downloads' }).click()+ const main = page+ await main.waitForLoadState('domcontentloaded')+ await waitForQueryHandlers(main)+ const tasks = (await invoke(main, Queries.ListTasks)) as Array<{+ name: string+ status: string+ engineTaskId: string+ }>+ expect(tasks).toHaveLength(2)+ expect(+ tasks.every((task) => task.status === 'paused' && !task.engineTaskId)+ ).toBe(true)+ await main.getByRole('link', { name: 'Migration', exact: true }).click()+ await main.getByRole('button', { name: 'Continue', exact: true }).click()+ await expect(+ main.getByRole('button', { name: /^Migrate$/, exact: true })+ ).toBeEnabled()+ expect(await invoke(main, Queries.ListTasks)).toHaveLength(2)+ expect(await readFile(torrentPath)).toEqual(original)+ // Direct IPC updates bypass the local settings form refresh. Reload to+ // verify persisted dark appearance, as other appearance fixtures do.+ await invoke(page, Commands.UpdateSettings, {+ app: { theme: 'dark', language: 'zh-CN' },+ })+ await page.reload({ waitUntil: 'domcontentloaded' })+ await expect(page.locator('html')).toHaveClass(/dark/)+ await page.getByRole('button', { name: '继续', exact: true }).click()+ await expandTaskGroups(page)+ await expect(+ page.getByRole('heading', { name: '选择要迁移的内容', exact: true })+ ).toBeVisible()+ await page.screenshot({+ path: testInfo.outputPath('migration-dark.png'),+ animations: 'disabled',+ })+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('keeps motion optional and selection immediate across input methods', async ({+ userDataDir,+ rpcPort,+ }) => {+ const source = await legacyProfile(userDataDir)+ const app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const page = await firstPage(app)+ await page.emulateMedia({ reducedMotion: 'no-preference' })+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).toBeVisible()+ const motion = page.locator('.migration-motion')+ await page.emulateMedia({ reducedMotion: 'reduce' })+ await expect(motion).toHaveAttribute('data-motion', 'off')+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await expandTaskGroups(page)+ const checkbox = page.getByRole('checkbox', {+ name: 'archive.zip',+ exact: true,+ })+ await checkbox.uncheck()+ await expect(+ page.getByRole('button', { name: /^Migrate$/, exact: true })+ ).toBeDisabled()+ const runningAnimations = () =>+ motion.evaluate(+ (element) =>+ element+ .getAnimations({ subtree: true })+ .filter((animation) => animation.playState === 'running').length+ )+ expect(await runningAnimations()).toBe(0)+ await page.emulateMedia({ reducedMotion: 'no-preference' })+ await checkbox.press('Space')+ await expect(checkbox).toBeChecked()+ await expect(+ page.getByRole('button', { name: /^Migrate$/, exact: true })+ ).toBeEnabled()+ expect(await runningAnimations()).toBe(0)+ await checkbox.uncheck()+ await checkbox.check()+ await expect(motion).toHaveAttribute('data-motion', 'on')+ // Wait for route commit before inspecting the retained, hidden page.+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ await expect(motion).toBeHidden()+ await expect(motion).toHaveAttribute('data-motion', 'off')+ expect(await runningAnimations()).toBe(0)+ await page.getByRole('link', { name: 'Migration', exact: true }).click()+ await expect(checkbox).toBeChecked()+ await invoke(page, Commands.UpdateSettings, {+ app: { reduceMotion: true },+ })+ await expect(motion).toHaveAttribute('data-motion', 'off')+ await checkbox.uncheck()+ await checkbox.check()+ expect(await runningAnimations()).toBe(0)+ await page.getByRole('button', { name: /^Migrate$/, exact: true }).click()+ await expect(+ page+ .getByLabel('Migration summary')+ .getByText('1 task', { exact: true })+ ).toBeVisible()+ expect(await runningAnimations()).toBe(0)+ const tasks = (await invoke(page, Queries.ListTasks)) as Array<{+ status: string+ }>+ expect(tasks).toHaveLength(1)+ expect(tasks[0].status).toBe('paused')+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('opens migration in main only after consent and imports paused records without blocking the engine', async ({+ userDataDir,+ rpcPort,+ }) => {+ const source = await legacyProfile(userDataDir)+ let app = await launchMotrix({+ userDataDir,+ rpcPort,+ disclaimerAccepted: false,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const disclaimer = await firstPage(app)+ await expect(disclaimer.getByTestId('disclaimer-panel')).toBeVisible()+ await expect(+ invoke(disclaimer, Queries.DiscoverLegacyImport)+ ).rejects.toThrow(/consentRequired/)+ const opened = app.waitForEvent('window')+ await disclaimer.getByTestId('disclaimer-agree').click()+ const page = await opened+ await page.waitForLoadState('domcontentloaded')+ await expect.poll(() => page.url()).toContain('w=main')+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).toBeVisible()+ await expect(+ page.getByRole('link', { name: 'Migration', exact: true })+ ).toBeVisible()+ await waitForEngineReady(page)+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).not.toBeVisible()+ await page.getByRole('link', { name: 'Migration', exact: true }).click()+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).toBeVisible()+ expect(+ app.windows().filter((window) => window.url().includes('w=onboarding'))+ ).toHaveLength(0)+ await page.getByRole('button', { name: 'Continue', exact: true }).click()+ await expandTaskGroups(page)+ await page.getByRole('button', { name: /^Migrate$/ }).click()+ await expect(+ page+ .getByLabel('Migration summary')+ .getByText('1 task', { exact: true })+ ).toBeVisible()+ await page.getByRole('button', { name: 'View downloads' }).click()+ const main = page+ await main.waitForLoadState('domcontentloaded')+ await waitForQueryHandlers(main)+ const tasks = (await invoke(main, Queries.ListTasks)) as Array<{+ id: string+ status: string+ engineTaskId: string+ downloadedBytes: number+ }>+ expect(tasks).toHaveLength(1)+ expect(tasks[0]).toMatchObject({+ status: 'paused',+ engineTaskId: '',+ downloadedBytes: 0,+ })+ await expect(+ invoke(+ main,+ Commands.ResumeTask,+ (tasks[0] as unknown as { id: string }).id+ )+ ).rejects.toThrow()+ expect(+ await readFile(path.join(source, 'downloads', 'archive.zip'), 'utf8')+ ).toBe('original v1 bytes')+ await app.close()+ app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ const restarted = await app.firstWindow()+ await restarted.waitForLoadState('domcontentloaded')+ await waitForQueryHandlers(restarted)+ await expect.poll(() => restarted.url()).toContain('w=main')+ expect(await invoke(restarted, Queries.ListTasks)).toEqual([+ expect.objectContaining({+ id: tasks[0].id,+ status: 'paused',+ engineTaskId: '',+ downloadedBytes: 0,+ }),+ ])+ // Even an older renderer asking for file deletion must preserve v1 bytes.+ await invoke(restarted, Commands.RemoveTask, {+ taskId: tasks[0].id,+ deleteWithFiles: true,+ })+ expect(await invoke(restarted, Queries.ListTasks)).toEqual([])+ expect(+ await readFile(path.join(source, 'downloads', 'archive.zip'), 'utf8')+ ).toBe('original v1 bytes')+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('hides migration without a detected v1 profile and keeps manual import available', async ({+ userDataDir,+ rpcPort,+ }) => {+ const app = await launchMotrix({ userDataDir, rpcPort })+ try {+ const main = await firstPage(app)+ await waitForEngineReady(main)+ await expect(+ main.getByRole('link', { name: 'Migration', exact: true })+ ).toHaveCount(0)+ await main.getByRole('link', { name: 'Settings', exact: true }).click()+ await main.getByText('Advanced', { exact: true }).first().click()+ await main+ .getByRole('button', { name: 'Open migration', exact: true })+ .click()+ await expect(+ main.getByRole('button', {+ name: 'Choose another location…',+ exact: true,+ })+ ).toBeVisible()+ expect(+ app.windows().filter((window) => window.url().includes('w=onboarding'))+ ).toHaveLength(0)+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('retains a migration entry for a detected empty v1 profile', async ({+ userDataDir,+ rpcPort,+ }) => {+ const source = await legacyProfile(userDataDir)+ await writeFile(path.join(source, 'download.session'), '')+ const app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const main = await firstPage(app)+ await waitForEngineReady(main)+ const entry = main.getByRole('link', { name: 'Migration', exact: true })+ await expect(entry).toBeVisible()+ await entry.click()+ await expect(+ main.getByRole('heading', {+ name: sourceTitle,+ exact: true,+ })+ ).toBeVisible()+ expect(await invoke(main, Queries.ListTasks)).toEqual([])+ } finally {+ await app.close().catch(() => {})+ }+ })++ test('skip returns to Dashboard from every entry and preserves dismissal and the Advanced draft', async ({+ userDataDir,+ rpcPort,+ }) => {+ const source = await legacyProfile(userDataDir)+ let app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ try {+ const page = await firstPage(app)+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).toBeVisible()+ await page.getByRole('button', { name: 'Not now', exact: true }).click()+ await expect(+ page.getByRole('heading', { name: sourceTitle })+ ).not.toBeVisible()+ await expect(+ page.getByRole('link', { name: 'Migration', exact: true })+ ).toBeVisible()+ await expect(+ page.getByRole('heading', { name: 'Dashboard', exact: true })+ ).toBeVisible()+ await app.close()+ app = await launchMotrix({+ userDataDir,+ rpcPort,+ extraEnv: { MOTRIX_LEGACY_PROFILE: source },+ })+ const main = await app.firstWindow()+ await main.waitForLoadState('domcontentloaded')+ await expect.poll(() => main.url()).toContain('w=main')+ await waitForQueryHandlers(main)+ await expect(+ main.getByRole('link', { name: 'Migration', exact: true })+ ).toBeVisible()+ await expect(+ main.getByRole('heading', { name: sourceTitle })+ ).not.toBeVisible()+ await main.getByRole('link', { name: 'Migration', exact: true }).click()+ await main.getByRole('button', { name: 'Continue', exact: true }).click()+ await expect(+ main.getByRole('button', { name: 'Migrate', exact: true })+ ).toBeEnabled()+ const selection = main.locator('[data-slot="migration-task-selection"]')+ await expect+ .poll(() =>+ selection.evaluate(+ (element) => element.getBoundingClientRect().height+ )+ )+ .toBeGreaterThanOrEqual(120)+ await expect+ .poll(() =>+ selection+ .locator(':scope > div')+ .evaluate((element) => element.scrollHeight - element.clientHeight)+ )+ .toBe(0)+ await main.getByRole('button', { name: 'Not now', exact: true }).click()+ await expect(+ main.getByRole('heading', { name: 'Dashboard', exact: true })+ ).toBeVisible()+ await main.getByRole('link', { name: 'Settings', exact: true }).click()+ await main.getByText('Advanced', { exact: true }).first().click()+ const port = main.getByRole('spinbutton').first()+ await port.fill('17000')+ await main+ .getByRole('button', { name: 'Open migration', exact: true })+ .click()+ await expect(+ main.getByRole('heading', {+ name: 'Choose what to migrate',+ exact: true,+ })+ ).toBeVisible()+ await main.getByRole('button', { name: 'Not now', exact: true }).click()+ await expect(+ main.getByRole('heading', { name: 'Dashboard', exact: true })+ ).toBeVisible()+ // Returning through history reopens the retained card; opening Settings+ // from the sidebar intentionally closes it first.+ await main.goBack()+ await expect(+ main.getByRole('button', { name: 'Not now', exact: true })+ ).toBeVisible()+ await main.goBack()+ await expect(port).toHaveValue('17000')+ expect(await invoke(main, Queries.ListTasks)).toEqual([])+ } finally {+ await app.close().catch(() => {})+ }+ })+})diff --git a/screenshots/motrix-migration-result-cn-light.png b/screenshots/motrix-migration-result-cn-light.pngnew file mode 100644index 00000000..ec3192e5Binary files /dev/null and b/screenshots/motrix-migration-result-cn-light.png differdiff --git a/scripts/third-party-notices.config.json b/scripts/third-party-notices.config.jsonindex 87074d46..a3442484 100644--- a/scripts/third-party-notices.config.json+++ b/scripts/third-party-notices.config.json@@ -211,6 +211,17 @@"src/renderer/routes/dashboard/icons/[email protected]"]},+ {+ "id": "glassmorphism-migration-import-icon",+ "name": "Glassmorphism migration import icon",+ "scope": "renderer migration assistant",+ "licenseDeclared": "NOASSERTION",+ "noticeMarker": "Glassmorphism migration import icon",+ "paths": [+ "src/renderer/features/legacy-import/icons/[email protected]",+ "src/renderer/features/legacy-import/icons/[email protected]"+ ]+ },{"id": "apple-sfns-tray-font","name": "Apple San Francisco tray font",diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex a0b0e910..0784f720 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto'import { access, mkdir } from 'node:fs/promises'import path from 'node:path'import { setTimeout as delay } from 'node:timers/promises'@@ -9,6 +10,10 @@ import {} from '@core/proxy/aria2-proxy-routing'import { admitDownloadSources } from '@core/task/source-admission'import { AppError, ErrorCode } from '@shared/errors'+import type {+ LegacyCheckpointImport,+ LegacyCheckpointReconcile,+} from '@shared/schemas/legacy-checkpoint'import type {EngineCapability,EngineFeatureReport,@@ -33,8 +38,10 @@ import type {DirectResourceMetadataProfile,DownloadCookie,EngineAdapter,+ LegacyBtBindingProof,} from '../engine-adapter'import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine-adapter'+import { Aria2LegacyCheckpoint } from './aria2-legacy-checkpoint'import type { Aria2RpcClient } from './aria2-rpc-client'import { recommend } from './aria2-tuning'import { isConnectionLimitRangeError, isNotFoundError } from './error-utils'@@ -745,7 +752,56 @@ export class Aria2Adapter implements EngineAdapter {return translateGlobalStat(raw)}+ async supportsLegacyBtActivation(): Promise<boolean> {+ const report = await this.rpc.getVersion()+ return (+ report.enabledFeatures.includes('LegacyTorrentMetadataV1') &&+ (await this.supportsLegacyCheckpointImport())+ )+ }++ async verifyLegacyBtBinding(input: LegacyBtBindingProof): Promise<boolean> {+ const task = await this.getTaskStatus(input.engineTaskId)+ if (+ !task ||+ task.engineTaskId !== input.engineTaskId ||+ task.infoHash?.toLowerCase() !== input.infoHash+ )+ return false+ const [files, options, trackers] = await Promise.all([+ this.getTaskFiles(input.engineTaskId),+ this.getEngineTaskOptions(input.engineTaskId),+ this.getTaskBtTracker(input.engineTaskId),+ ])+ const selected = new Set(input.selectedFiles)+ return (+ files.length === input.files.length &&+ files.every(+ (file, index) =>+ file.index === index &&+ file.path === input.files[index].path &&+ file.size === input.files[index].length &&+ file.selected === selected.has(index)+ ) &&+ options !== null &&+ options.dir === input.saveDir &&+ options['bt-seed-unverified'] === 'false' &&+ options['bt-hash-check-seed'] === 'false' &&+ Number(options['seed-time']) === 0 &&+ Number(options['seed-ratio']) === 0 &&+ options['bt-remove-unselected-file'] === 'false' &&+ options['allow-overwrite'] === 'false' &&+ options['auto-file-renaming'] === 'false' &&+ options['remove-control-file'] === 'false' &&+ options['check-integrity'] === 'true' &&+ trackers.join(',') === input.trackers.join(',')+ )+ }+async addTorrent(params: AddTorrentParams): Promise<string> {+ const legacyMetadata = params.legacyCheckpointActivation+ ? Buffer.from(params.metadata)+ : nullconst extraGid = params.extraEngineOptions?.gidif (extraGid !== undefined && typeof extraGid !== 'string') {throw new TypeError(@@ -824,13 +880,51 @@ export class Aria2Adapter implements EngineAdapter {opts[k] = v}}- await this.applyBtTrackerPolicy(- opts,- requestedGid,- params.metadata,- params.isPrivate- )- if (params.isPrivate) {+ if (params.legacyCheckpointActivation) {+ if (+ !params.pause ||+ !requestedGid ||+ !params.selectedFiles?.length ||+ params.outputRoot ||+ params.outputFilePaths+ )+ throw new TypeError('Invalid legacy torrent activation')+ const allowed = new Set(['bt-tracker'])+ if (+ Object.keys(params.extraEngineOptions ?? {}).some(+ (key) => !allowed.has(key)+ )+ )+ throw new TypeError('Unexpected legacy torrent options')+ // Pin after extras so neither ambient settings nor global tracker policy can override consent.+ Object.assign(opts, {+ dir: params.saveDir,+ pause: 'true',+ 'select-file': params.selectedFiles.join(','),+ 'allow-overwrite': 'false',+ 'auto-file-renaming': 'false',+ 'remove-control-file': 'false',+ 'check-integrity': 'true',+ 'bt-seed-unverified': 'false',+ 'bt-hash-check-seed': 'false',+ 'seed-time': '0',+ 'seed-ratio': '0.0',+ 'bt-remove-unselected-file': 'false',+ 'file-allocation': 'none',+ 'rpc-save-upload-metadata': 'false',+ 'bt-save-metadata': 'false',+ 'bt-exclude-tracker': '',+ 'enable-peer-exchange': 'false',+ 'bt-enable-lpd': 'false',+ })+ } else+ await this.applyBtTrackerPolicy(+ opts,+ requestedGid,+ params.metadata,+ params.isPrivate+ )+ if (params.isPrivate && !params.legacyCheckpointActivation) {// Apply after extra options: private torrents keep their own trackers.// A configured policy can restore explicitly owned private-task edits.// Without that provenance, no supplemental option is trusted.@@ -846,8 +940,60 @@ export class Aria2Adapter implements EngineAdapter {// Web Seed cannot abort peers or other Web Seeds before their first byte.opts['max-file-not-found'] = '0'if (params.outputRoot) await mkdir(params.saveDir, { recursive: true })- const b64 = Buffer.from(params.metadata).toString('base64')- const actualGid = await this.rpc.addTorrent(b64, [], opts)+ const b64 = (legacyMetadata ?? Buffer.from(params.metadata)).toString(+ 'base64'+ )+ let actualGid: string+ if (params.legacyCheckpointActivation) {+ const context = params.legacyCheckpointActivation+ const reference = params.durableMetadata+ if (+ !reference ||+ !legacyMetadata ||+ !/^[a-f0-9]{64}$/.test(reference.digest) ||+ createHash('sha256').update(legacyMetadata).digest('hex') !==+ reference.digest ||+ !/^[A-Za-z0-9_-]{16,128}$/.test(context.token) ||+ ![reference.path, context.targetPath, params.saveDir].every(+ (value) =>+ path.isAbsolute(value) &&+ path.normalize(value) === value &&+ Buffer.byteLength(value) <= 4096 &&+ [...value].every(+ (char) => char.charCodeAt(0) > 31 && char.charCodeAt(0) !== 127+ )+ )+ )+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'Invalid durable torrent reference'+ )+ if (!(await this.supportsLegacyBtActivation()))+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.checkpointUnavailable'+ )+ const input = {+ token: context.token,+ targetPath: context.targetPath,+ metadataFile: reference.path,+ metadataDigest: reference.digest,+ metadata: b64,+ options: opts,+ }+ if (Buffer.byteLength(JSON.stringify(input)) > 2 * 1024 * 1024 - 4096)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.tooLarge'+ )+ actualGid = await this.rpc.addLegacyTorrentV1(input)+ } else {+ if (params.durableMetadata)+ throw new TypeError(+ 'Durable torrent reference requires legacy activation'+ )+ actualGid = await this.rpc.addTorrent(b64, [], opts)+ }if (requestedGid !== undefined &&actualGid.toLowerCase() !== requestedGid.toLowerCase()@@ -898,6 +1044,22 @@ export class Aria2Adapter implements EngineAdapter {}}+ supportsLegacyCheckpointImport(): Promise<boolean> {+ return new Aria2LegacyCheckpoint(this.rpc).supported()+ }++ inspectLegacyCheckpoint(bytes: Uint8Array) {+ return new Aria2LegacyCheckpoint(this.rpc).inspect(bytes)+ }++ importLegacyCheckpoint(input: LegacyCheckpointImport) {+ return new Aria2LegacyCheckpoint(this.rpc).import(input)+ }++ reconcileLegacyCheckpoint(input: LegacyCheckpointReconcile) {+ return new Aria2LegacyCheckpoint(this.rpc).reconcile(input)+ }+async removeDownloadResult(engineTaskId: string): Promise<void> {// forceRemove acknowledges a halt request before aria2 creates its stopped// result. Retry only that precise transition race; successful cleanups adddiff --git a/src/core/engine/aria2/aria2-legacy-bt-policy.test.ts b/src/core/engine/aria2/aria2-legacy-bt-policy.test.tsnew file mode 100644index 00000000..efad8683--- /dev/null+++ b/src/core/engine/aria2/aria2-legacy-bt-policy.test.ts@@ -0,0 +1,169 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import { readFile } from 'node:fs/promises'+import path from 'node:path'+import type { AddTorrentParams } from '@core/engine/engine-adapter'+import { describe, expect, it, vi } from 'vitest'+import { Aria2Adapter } from './aria2-adapter'+import type { Aria2RpcClient } from './aria2-rpc-client'++const gid = '1234567890abcdef'+const saveDir = '/confirmed/legacy/downloads'+const tracker = 'http://127.0.0.1:45123/announce'++async function fixture() {+ const addTorrent = vi.fn().mockResolvedValue(gid)+ const ordinaryAddTorrent = vi.fn()+ const getVersion = vi.fn(async () => ({+ version: '1.37.0',+ enabledFeatures: [+ 'SQLite3-Persistence',+ 'LegacyCheckpointImportV1',+ 'LegacyTorrentMetadataV1',+ ],+ }))+ const rpc = {+ addLegacyTorrentV1: addTorrent,+ addTorrent: ordinaryAddTorrent,+ getVersion,+ onBtDownloadComplete: vi.fn(),+ onDownloadComplete: vi.fn(),+ onDownloadError: vi.fn(),+ } as unknown as Aria2RpcClient+ const adapter = new Aria2Adapter(rpc)+ const policy = vi.fn().mockResolvedValue({+ trackers: ['https://unrelated.example/announce'],+ isPrivate: false,+ })+ adapter.configureBtTrackerPolicy(policy)+ const params: AddTorrentParams = {+ metadata: await readFile(+ path.resolve(+ 'tests/fixtures/legacy-v1/generated/downloads/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent'+ )+ ),+ legacyCheckpointActivation: {+ token: 'legacy_policy_test_token',+ targetPath: `${saveDir}/fixture-bundle`,+ },+ gid,+ saveDir,+ pause: true,+ selectedFiles: [1],+ isPrivate: true,+ extraEngineOptions: { 'bt-tracker': tracker },+ }+ params.durableMetadata = {+ path: '/authorized/backup/source.torrent',+ digest: createHash('sha256').update(params.metadata).digest('hex'),+ }+ return { adapter, addTorrent, ordinaryAddTorrent, getVersion, policy, params }+}++describe('legacy BT activation dispatch safety', () => {+ it('keeps explicit selection and original trackers instead of global policy', async () => {+ const f = await fixture()+ await f.adapter.addTorrent(f.params)+ expect(f.policy).not.toHaveBeenCalled()+ expect(f.ordinaryAddTorrent).not.toHaveBeenCalled()+ expect(f.addTorrent).toHaveBeenCalledOnce()+ expect(f.addTorrent.mock.calls[0]?.[0].options).toMatchObject({+ gid,+ dir: saveDir,+ pause: 'true',+ 'select-file': '1',+ 'bt-tracker': tracker,+ 'check-integrity': 'true',+ 'bt-seed-unverified': 'false',+ 'bt-hash-check-seed': 'false',+ 'seed-time': '0',+ 'bt-remove-unselected-file': 'false',+ })+ })++ it('cannot let extra options unpause, redirect or destructively restart old files', async () => {+ const f = await fixture()+ f.params.extraEngineOptions = {+ ...f.params.extraEngineOptions,+ pause: 'false',+ dir: '/unconfirmed/destination',+ 'select-file': '2',+ 'index-out': ['1=/unconfirmed/overwrite.bin'],+ out: 'replacement.bin',+ 'piece-length': '1M',+ 'check-integrity': 'false',+ 'bt-seed-unverified': 'true',+ 'bt-hash-check-seed': 'true',+ 'seed-time': '999',+ 'bt-remove-unselected-file': 'true',+ 'remove-control-file': 'true',+ 'allow-overwrite': 'true',+ 'auto-file-renaming': 'true',+ }+ // Rejecting unsafe options or pinning them are both safe. Dispatching+ // them is not: paused admission must precede application ownership.+ try {+ await f.adapter.addTorrent(f.params)+ } catch {+ expect(f.addTorrent).not.toHaveBeenCalled()+ return+ }+ const options = f.addTorrent.mock.calls[0]?.[0].options+ expect(options).toMatchObject({+ gid,+ dir: saveDir,+ pause: 'true',+ 'select-file': '1',+ 'check-integrity': 'true',+ 'bt-seed-unverified': 'false',+ 'bt-hash-check-seed': 'false',+ 'seed-time': '0',+ 'bt-remove-unselected-file': 'false',+ 'remove-control-file': 'false',+ 'allow-overwrite': 'false',+ 'auto-file-renaming': 'false',+ })+ expect(options).not.toHaveProperty('index-out')+ expect(options).not.toHaveProperty('out')+ expect(options).not.toHaveProperty('piece-length')+ })++ it('rejects an older engine without silently falling back to ordinary addTorrent', async () => {+ const f = await fixture()+ f.getVersion.mockResolvedValue({+ version: '1.37.0',+ enabledFeatures: ['SQLite3-Persistence', 'LegacyCheckpointImportV1'],+ })+ await expect(f.adapter.addTorrent(f.params)).rejects.toThrow(+ 'checkpointUnavailable'+ )+ expect(f.addTorrent).not.toHaveBeenCalled()+ expect(f.ordinaryAddTorrent).not.toHaveBeenCalled()+ })++ it.each<Partial<AddTorrentParams>>([+ { pause: false },+ { gid: undefined },+ { selectedFiles: [] },+ { durableMetadata: undefined },+ {+ durableMetadata: {+ path: '/authorized/backup/source.torrent',+ digest: '0'.repeat(64),+ },+ },+ { durableMetadata: { path: '../source.torrent', digest: '0'.repeat(64) } },+ { outputRoot: '/another/root' },+ { outputFilePaths: [{ fileIndex: 0, relativePath: 'another.bin' }] },+ ])(+ 'rejects incomplete or remapped activation before dispatch: %j',+ async (override) => {+ const f = await fixture()+ await expect(+ f.adapter.addTorrent({ ...f.params, ...override })+ ).rejects.toThrow()+ expect(f.addTorrent).not.toHaveBeenCalled()+ expect(f.policy).not.toHaveBeenCalled()+ }+ )+})diff --git a/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.ts b/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.tsnew file mode 100644index 00000000..e7002baf--- /dev/null+++ b/src/core/engine/aria2/aria2-legacy-checkpoint.integration.test.ts@@ -0,0 +1,289 @@+// @vitest-environment node+// Opt in with MOTRIX_LEGACY_CHECKPOINT_ENGINE pointing to an engine that+// implements LegacyCheckpointImportV1. The ordinary bundled engine may not.+import { createHash } from 'node:crypto'+import {+ mkdtemp,+ readFile,+ realpath,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises'+import { createServer, type Server } from 'node:http'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { gunzipSync } from 'node:zlib'+import type { LegacyCheckpointImport } from '@shared/schemas/legacy-checkpoint'+import {+ type Aria2Handle,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++const binaryPath = process.env.MOTRIX_LEGACY_CHECKPOINT_ENGINE+const fixtures = path.resolve('tests/fixtures/legacy-v1/generated/downloads')+const totalBytes = 4194304+const completedBytes = 1638400+const payloadDigest =+ 'a117210941a0b00dcb2d8577e680d84b6fa0eaf760d2afc654c953b9859d54fa'+const gid = '2222222222222222'+const token = 'real_v1_checkpoint_import_0001'++async function until<T>(read: () => Promise<T | false>): Promise<T> {+ const deadline = Date.now() + 20000+ while (Date.now() < deadline) {+ const value = await read()+ if (value !== false) return value+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+ throw new Error('Legacy checkpoint integration timed out')+}++describe.skipIf(!binaryPath)(+ 'real v1 checkpoint through the app adapter',+ () => {+ let root: string+ let handle: Aria2Handle | undefined+ let wired: Awaited<ReturnType<typeof connectAdapter>> | undefined+ let server: Server | undefined+ let targetPath: string+ let input: LegacyCheckpointImport+ const ranges: string[] = []++ async function stopEngine(): Promise<void> {+ wired?.disconnect()+ wired = undefined+ await handle?.kill()+ handle = undefined+ }++ async function startEngine() {+ handle = await spawnAria2ForTest({+ baseDir: root,+ binaryPath,+ extraArgs: [+ '--enable-sqlite3-persistence=true',+ `--sqlite3-db-path=${path.join(root, 'engine.db')}`,+ '--force-save=true',+ '--continue=false',+ '--split=1',+ '--max-connection-per-server=1',+ '--file-allocation=none',+ '--max-tries=1',+ ],+ })+ wired = await connectAdapter(handle)+ expect(await wired.adapter.supportsLegacyCheckpointImport()).toBe(true)+ return wired+ }++ beforeEach(async () => {+ root = await realpath(+ await mkdtemp(path.join(tmpdir(), 'motrix-v1-native-'))+ )+ ranges.length = 0+ targetPath = path.join(root, 'partial.bin')+ const partial = gunzipSync(+ await readFile(path.join(fixtures, 'partial.bin.gz'))+ )+ expect(partial.byteLength).toBe(completedBytes)+ await writeFile(targetPath, partial)+ const { adapter } = await startEngine()+ const controlFile = await readFile(+ path.join(fixtures, 'partial.bin.aria2')+ )+ const inspection = await adapter.inspectLegacyCheckpoint(controlFile)+ const identity = await stat(targetPath, { bigint: true })+ input = {+ token,+ engineTaskId: gid,+ targetPath,+ controlFile,+ sourceDigest: inspection.sourceDigest,+ expected: {+ type: inspection.type,+ totalBytes: inspection.totalBytes,+ pieceBytes: inspection.pieceBytes,+ infoHash: inspection.infoHash,+ },+ files: [+ {+ path: targetPath,+ offset: 0,+ length: totalBytes,+ identity: {+ device: String(identity.dev),+ inode: String(identity.ino),+ size: String(identity.size),+ mtimeNs: String(identity.mtimeNs),+ ctimeNs: String(identity.ctimeNs),+ },+ },+ ],+ }+ }, 15000)++ afterEach(async () => {+ await stopEngine()+ if (server) {+ server.closeAllConnections()+ await new Promise<void>((resolve) => server?.close(() => resolve()))+ server = undefined+ }+ if (root) await rm(root, { recursive: true, force: true })+ })++ it('inspects actual saved HTTP blocks and BT logical length', async () => {+ const { adapter } = wired!+ await expect(+ adapter.inspectLegacyCheckpoint(input.controlFile)+ ).resolves.toMatchObject({+ type: 'http',+ totalBytes,+ pieceBytes: 1048576,+ completedBytes,+ ranges: [{ offset: 0, length: completedBytes }],+ })+ await expect(+ adapter.inspectLegacyCheckpoint(+ await readFile(path.join(fixtures, 'fixture-bundle.aria2'))+ )+ ).resolves.toMatchObject({+ type: 'bt',+ totalBytes: 32768,+ pieceBytes: 16384,+ infoHash: '45c7c651e500cc0ceaa544d6fbafcb21b8cd52f8',+ completedBytes: 0,+ ranges: [],+ })+ expect(await wired!.rpc.tellActive()).toEqual([])+ })++ it('persists a silent import across restart, resumes missing bytes and consumes its receipt', async () => {+ const payload = Buffer.alloc(totalBytes)+ for (let i = 0; i < payload.length; i++) payload[i] = i % 251+ server = createServer((req, res) => {+ ranges.push(req.headers.range ?? 'none')+ const match = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range ?? '')+ const start = match ? Number(match[1]) : 0+ const end = match?.[2] ? Number(match[2]) : totalBytes - 1+ res.writeHead(match ? 206 : 200, {+ 'Accept-Ranges': 'bytes',+ ETag: '"motrix-v1-generated-fixture"',+ 'Content-Length': end - start + 1,+ ...(match+ ? { 'Content-Range': `bytes ${start}-${end}/${totalBytes}` }+ : {}),+ })+ res.end(+ req.method === 'HEAD' ? undefined : 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('No HTTP port')+ const original = await readFile(targetPath)+ const receipt = await wired!.adapter.importLegacyCheckpoint(input)+ expect(receipt.status).toBe('created')+ await expect(+ wired!.adapter.importLegacyCheckpoint(input)+ ).resolves.toEqual(receipt)+ await expect(wired!.rpc.tellActive()).resolves.toEqual([])+ await expect(wired!.rpc.tellWaiting(0, 10)).resolves.toEqual([])+ expect(ranges).toEqual([])+ expect(await readFile(targetPath)).toEqual(original)+ await wired!.rpc.saveSession()+ await stopEngine()+ const { adapter, rpc } = await startEngine()+ await expect(+ adapter.reconcileLegacyCheckpoint({ token, targetPath })+ ).resolves.toEqual(receipt)+ await expect(adapter.getCheckpointStatus(targetPath)).resolves.toBe(+ 'present'+ )+ await adapter.createDownload({+ uris: [`http://127.0.0.1:${address.port}/partial.bin`],+ saveDir: root,+ filename: 'partial.bin',+ gid,+ pause: true,+ resumePolicy: 'checkpoint',+ extraEngineOptions: {+ 'piece-length': String(input.expected.pieceBytes),+ },+ })+ expect((await rpc.tellStatus(gid, ['status'])).status).toBe('paused')+ expect(ranges).toEqual([])+ await rpc.unpause(gid)+ await until(async () => {+ const status = await rpc.tellStatus(gid, ['status', 'errorMessage'])+ if (status.status === 'error') throw new Error(status.errorMessage)+ return status.status === 'complete'+ })+ // aria2 first learns the remote length, then requests the saved suffix.+ // Import and paused task creation above must remain completely offline.+ expect(+ ranges.filter((range) => range === 'none').length+ ).toBeLessThanOrEqual(1)+ expect(ranges.filter((range) => range !== 'none')).toEqual([+ `bytes=${completedBytes}-${totalBytes - 1}`,+ ])+ expect(+ createHash('sha256')+ .update(await readFile(targetPath))+ .digest('hex')+ ).toBe(payloadDigest)+ const consumed = { ...receipt, status: 'consumed' }+ await expect(+ adapter.reconcileLegacyCheckpoint({ token, targetPath })+ ).resolves.toEqual(consumed)+ // Original file identities are now stale. A retry returns the durable+ // receipt and must not recreate the imported checkpoint.+ await expect(adapter.importLegacyCheckpoint(input)).resolves.toEqual(+ consumed+ )+ const source = gunzipSync(+ await readFile(path.join(fixtures, 'partial.bin.gz'))+ )+ expect(source).toEqual(original)+ }, 45000)++ it('rejects changed file identities without creating a receipt or checkpoint', async () => {+ const { adapter } = wired!+ await writeFile(targetPath, Buffer.alloc(completedBytes, 17))+ await expect(adapter.importLegacyCheckpoint(input)).rejects.toThrow()+ await expect(+ adapter.reconcileLegacyCheckpoint({ token, targetPath })+ ).resolves.toEqual({+ token,+ targetPath,+ status: 'absent',+ })+ await expect(adapter.getCheckpointStatus(targetPath)).resolves.toBe(+ 'absent'+ )+ expect(await readFile(targetPath)).toEqual(+ Buffer.alloc(completedBytes, 17)+ )+ })++ it('rejects a token replay with a different reserved task ID', async () => {+ const { adapter } = wired!+ const receipt = await adapter.importLegacyCheckpoint(input)+ await expect(+ adapter.importLegacyCheckpoint({+ ...input,+ engineTaskId: '3333333333333333',+ })+ ).rejects.toThrow()+ await expect(+ adapter.reconcileLegacyCheckpoint({ token, targetPath })+ ).resolves.toEqual(receipt)+ })+ }+)diff --git a/src/core/engine/aria2/aria2-legacy-checkpoint.test.ts b/src/core/engine/aria2/aria2-legacy-checkpoint.test.tsnew file mode 100644index 00000000..aa4e07af--- /dev/null+++ b/src/core/engine/aria2/aria2-legacy-checkpoint.test.ts@@ -0,0 +1,314 @@+import { createHash } from 'node:crypto'+import { ErrorCode } from '@shared/errors'+import {+ type LegacyCheckpointImport,+ MAX_LEGACY_CHECKPOINT_BYTES,+} from '@shared/schemas/legacy-checkpoint'+import { describe, expect, it, vi } from 'vitest'+import { Aria2Adapter } from './aria2-adapter'+import {+ Aria2LegacyCheckpoint,+ FEATURE_LEGACY_CHECKPOINT_IMPORT_V1,+} from './aria2-legacy-checkpoint'+import { Aria2RpcClient } from './aria2-rpc-client'+import type { JsonRpcProtocol } from './json-rpc-protocol'+import type { WebSocketTransport } from './web-socket-transport'++const bytes = new Uint8Array([0, 1, 0, 0])+const sourceDigest = createHash('sha256').update(bytes).digest('hex')+const token = 'legacy-checkpoint-test-token'+const gid = '1234567890abcdef'+const targetPath = '/downloads/archive.zip'+const inspection = {+ version: '1',+ format: 'aria2-v1',+ kind: 'http',+ totalLength: '100',+ pieceLength: '16',+ infoHash: '',+ uploadLength: '0',+ completedLength: '30',+ controlDigest: sourceDigest,+ ranges: [+ { offset: '0', length: '16' },+ { offset: '32', length: '14' },+ ],+}+const saved = {+ version: '1',+ status: 'created',+ token,+ gid,+ targetPath,+ controlDigest: sourceDigest,+}+function request(): LegacyCheckpointImport {+ return {+ token,+ engineTaskId: gid,+ targetPath,+ controlFile: bytes.slice(),+ sourceDigest,+ expected: { type: 'http', totalBytes: 100, pieceBytes: 16, infoHash: null },+ files: [+ {+ path: targetPath,+ offset: 0,+ length: 100,+ identity: {+ device: '1',+ inode: '2',+ size: '100',+ mtimeNs: '1000000000000000000',+ ctimeNs: '1000000000000000001',+ },+ },+ ],+ }+}+function setup() {+ const rpc = {+ getVersion: vi.fn().mockResolvedValue({+ version: '1.37.0-motrix.17',+ enabledFeatures: [+ 'SQLite3-Persistence',+ FEATURE_LEGACY_CHECKPOINT_IMPORT_V1,+ ],+ }),+ inspectLegacyCheckpointV1: vi.fn().mockResolvedValue(inspection),+ importLegacyCheckpointV1: vi.fn().mockResolvedValue(saved),+ reconcileLegacyCheckpointV1: vi.fn().mockResolvedValue(saved),+ }+ return {+ rpc,+ adapter: new Aria2LegacyCheckpoint(rpc as unknown as Aria2RpcClient),+ }+}++describe('legacy checkpoint engine boundary', () => {+ it('uses the live capability and never calls a legacy method on an older engine', async () => {+ const { rpc, adapter } = setup()+ rpc.getVersion.mockResolvedValue({+ enabledFeatures: ['SQLite3-Persistence'],+ })+ expect(await adapter.supported()).toBe(false)+ for (const operation of [+ () => adapter.inspect(bytes),+ () => adapter.import(request()),+ () => adapter.reconcile({ token, targetPath }),+ ])+ await expect(operation()).rejects.toMatchObject({+ code: ErrorCode.EngineFeatureUnavailable,+ })+ expect(rpc.inspectLegacyCheckpointV1).not.toHaveBeenCalled()+ expect(rpc.importLegacyCheckpointV1).not.toHaveBeenCalled()+ expect(rpc.reconcileLegacyCheckpointV1).not.toHaveBeenCalled()+ rpc.getVersion.mockResolvedValue({+ enabledFeatures: [FEATURE_LEGACY_CHECKPOINT_IMPORT_V1],+ })+ expect(await adapter.supported()).toBe(false)+ })++ it('does not cache a previously available runtime capability', async () => {+ const { rpc, adapter } = setup()+ expect(await adapter.supported()).toBe(true)+ rpc.getVersion.mockResolvedValue({ enabledFeatures: [] })+ await expect(adapter.import(request())).rejects.toMatchObject({+ code: ErrorCode.EngineFeatureUnavailable,+ })+ expect(rpc.importLegacyCheckpointV1).not.toHaveBeenCalled()+ })++ it('projects verified native ranges, not file length, as recorded progress', async () => {+ const { adapter } = setup()+ expect(await adapter.inspect(bytes)).toEqual({+ type: 'http',+ totalBytes: 100,+ pieceBytes: 16,+ infoHash: null,+ uploadedBytes: 0,+ sourceDigest,+ completedBytes: 30,+ ranges: [+ { offset: 0, length: 16 },+ { offset: 32, length: 14 },+ ],+ })+ })++ it.each([+ { controlDigest: 'f'.repeat(64) },+ { totalLength: '9007199254740993' },+ { completedLength: '31' },+ { pieceLength: '0' },+ { totalLength: '-1' },+ { infoHash: 'a'.repeat(40) },+ { kind: 'bittorrent' },+ {+ ranges: [+ { offset: '0', length: '20' },+ { offset: '19', length: '10' },+ ],+ },+ { ranges: [{ offset: '80', length: '30' }] },+ { version: '2' },+ ])(+ 'rejects malformed or inconsistent native output: %j',+ async (override) => {+ const { rpc, adapter } = setup()+ rpc.inspectLegacyCheckpointV1.mockResolvedValue({+ ...inspection,+ ...override,+ })+ await expect(adapter.inspect(bytes)).rejects.toMatchObject({+ code: ErrorCode.EngineProtocolError,+ })+ }+ )++ it('copies the control snapshot before asynchronous capability probing', async () => {+ const { rpc, adapter } = setup()+ const mutable = bytes.slice()+ const result = adapter.inspect(mutable)+ mutable.fill(255)+ await result+ expect(rpc.inspectLegacyCheckpointV1).toHaveBeenCalledWith({+ controlFile: Buffer.from(bytes).toString('base64'),+ })+ })++ it('rejects oversized snapshots before capability probing or dispatch', async () => {+ const { rpc, adapter } = setup()+ await expect(+ adapter.inspect(new Uint8Array(MAX_LEGACY_CHECKPOINT_BYTES + 1))+ ).rejects.toMatchObject({ code: ErrorCode.InvalidSelection })+ expect(rpc.getVersion).not.toHaveBeenCalled()+ })++ it('retains file identities as exact decimal strings and checks the receipt', async () => {+ const { rpc, adapter } = setup()+ expect(await adapter.import(request())).toEqual({+ status: 'created',+ token,+ engineTaskId: gid,+ targetPath,+ sourceDigest,+ })+ expect(rpc.importLegacyCheckpointV1).toHaveBeenCalledWith(+ expect.objectContaining({+ gid,+ token,+ controlDigest: sourceDigest,+ expected: {+ kind: 'http',+ totalLength: '100',+ pieceLength: '16',+ infoHash: '',+ },+ files: [{ ...request().files[0], offset: '0', length: '100' }],+ })+ )+ })++ it.each([+ { token: 'a-different-import-token' },+ { gid: 'fedcba0987654321' },+ { targetPath: '/downloads/other.zip' },+ { controlDigest: 'f'.repeat(64) },+ ])('rejects a receipt from another transaction: %j', async (override) => {+ const { rpc, adapter } = setup()+ rpc.importLegacyCheckpointV1.mockResolvedValue({ ...saved, ...override })+ await expect(adapter.import(request())).rejects.toMatchObject({+ code: ErrorCode.EngineProtocolError,+ })+ })++ it('does not retry or create a replacement identity after an unknown RPC outcome', async () => {+ const { rpc, adapter } = setup()+ rpc.importLegacyCheckpointV1.mockRejectedValue(new Error('response lost'))+ await expect(adapter.import(request())).rejects.toThrow('response lost')+ expect(rpc.importLegacyCheckpointV1).toHaveBeenCalledTimes(1)+ expect(rpc.reconcileLegacyCheckpointV1).not.toHaveBeenCalled()+ rpc.reconcileLegacyCheckpointV1.mockResolvedValue(saved)+ expect(await adapter.reconcile({ token, targetPath })).toMatchObject({+ status: 'created',+ token,+ engineTaskId: gid,+ })+ })++ it('distinguishes absent receipts from consumed checkpoints', async () => {+ const { rpc, adapter } = setup()+ rpc.reconcileLegacyCheckpointV1.mockResolvedValue({+ version: '1',+ status: 'absent',+ token,+ targetPath,+ })+ expect(await adapter.reconcile({ token, targetPath })).toEqual({+ status: 'absent',+ token,+ targetPath,+ })+ rpc.reconcileLegacyCheckpointV1.mockResolvedValue({+ ...saved,+ status: 'consumed',+ })+ expect(await adapter.reconcile({ token, targetPath })).toMatchObject({+ status: 'consumed',+ engineTaskId: gid,+ })+ expect(rpc.importLegacyCheckpointV1).not.toHaveBeenCalled()+ })++ it('rejects stale digest, overlapping mapping and noncanonical target paths before import', async () => {+ const { rpc, adapter } = setup()+ const digestChanged = request()+ digestChanged.controlFile[0] = 255+ const badMapping = request()+ badMapping.files[0].offset = 1+ const badPath = request()+ badPath.targetPath = '/downloads/../archive.zip'+ badPath.files[0].path = badPath.targetPath+ for (const input of [digestChanged, badMapping, badPath])+ await expect(adapter.import(input)).rejects.toMatchObject({+ code: ErrorCode.InvalidSelection,+ })+ expect(rpc.importLegacyCheckpointV1).not.toHaveBeenCalled()+ })++ it('routes all methods through the real authenticated client and public engine adapter', async () => {+ const call = vi.fn(async (method: string) => {+ if (method === 'aria2.getVersion')+ return {+ enabledFeatures: [+ 'SQLite3-Persistence',+ FEATURE_LEGACY_CHECKPOINT_IMPORT_V1,+ ],+ }+ if (method === 'aria2.inspectLegacyCheckpointV1') return inspection+ return saved+ })+ const rpc = new Aria2RpcClient(+ {} as WebSocketTransport,+ { call, onNotification: vi.fn() } as unknown as JsonRpcProtocol,+ 'fixture-secret'+ )+ const adapter = new Aria2Adapter(rpc)+ expect(await adapter.supportsLegacyCheckpointImport()).toBe(true)+ await adapter.inspectLegacyCheckpoint(bytes)+ await adapter.importLegacyCheckpoint(request())+ await adapter.reconcileLegacyCheckpoint({ token, targetPath })+ for (const [method, params] of call.mock.calls as unknown as Array<+ [string, unknown[]]+ >) {+ expect(params[0]).toBe('token:fixture-secret')+ expect([+ 'aria2.getVersion',+ 'aria2.inspectLegacyCheckpointV1',+ 'aria2.importLegacyCheckpointV1',+ 'aria2.reconcileLegacyCheckpointV1',+ ]).toContain(method)+ }+ })+})diff --git a/src/core/engine/aria2/aria2-legacy-checkpoint.ts b/src/core/engine/aria2/aria2-legacy-checkpoint.tsnew file mode 100644index 00000000..7c809c73--- /dev/null+++ b/src/core/engine/aria2/aria2-legacy-checkpoint.ts@@ -0,0 +1,292 @@+import { createHash } from 'node:crypto'+import path from 'node:path'+import { AppError, ErrorCode } from '@shared/errors'+import {+ type LegacyCheckpointImport,+ type LegacyCheckpointInspection,+ type LegacyCheckpointReceipt,+ type LegacyCheckpointReconcile,+ type LegacyCheckpointReconciliation,+ legacyCheckpointImportSchema,+ legacyCheckpointInspectionSchema,+ legacyCheckpointReceiptSchema,+ legacyCheckpointReconcileSchema,+ MAX_LEGACY_CHECKPOINT_BYTES,+ MAX_LEGACY_CHECKPOINT_RANGES,+} from '@shared/schemas/legacy-checkpoint'+import { FEATURE_SQLITE3_PERSISTENCE } from '@shared/types/engine'+import { z } from 'zod'+import type { Aria2RpcClient } from './aria2-rpc-client'++export const FEATURE_LEGACY_CHECKPOINT_IMPORT_V1 = 'LegacyCheckpointImportV1'+const MAX_REQUEST_BYTES = 2 * 1024 * 1024 - 4096+const decimal = z+ .string()+ .regex(/^(0|[1-9][0-9]{0,18})$/)+ .transform(Number)+ .refine(Number.isSafeInteger)+const digest = z.string().regex(/^[0-9a-f]{64}$/)+const wireInspection = z+ .object({+ version: z.literal('1'),+ format: z.literal('aria2-v1'),+ kind: z.enum(['http', 'bittorrent']),+ totalLength: decimal,+ pieceLength: decimal,+ infoHash: z.union([z.literal(''), z.string().regex(/^[0-9a-f]{40}$/)]),+ uploadLength: decimal,+ completedLength: decimal,+ controlDigest: digest,+ ranges: z+ .array(z.object({ offset: decimal, length: decimal }).strict())+ .max(MAX_LEGACY_CHECKPOINT_RANGES),+ })+ .strict()+const wireReceipt = z+ .object({+ version: z.literal('1'),+ status: z.enum(['created', 'consumed']),+ token: z.string(),+ gid: z.string(),+ targetPath: z.string(),+ controlDigest: digest,+ })+ .strict()+const wireAbsent = z+ .object({+ version: z.literal('1'),+ status: z.literal('absent'),+ token: z.string(),+ targetPath: z.string(),+ })+ .strict()++export interface Aria2LegacyCheckpointImport {+ token: string+ gid: string+ controlFile: string+ controlDigest: string+ targetPath: string+ expected: {+ kind: 'http' | 'bittorrent'+ totalLength: string+ pieceLength: string+ infoHash: string+ }+ files: Array<{+ path: string+ offset: string+ length: string+ identity: LegacyCheckpointImport['files'][number]['identity']+ }>+}++type CheckpointRpc = Pick<+ Aria2RpcClient,+ | 'getVersion'+ | 'inspectLegacyCheckpointV1'+ | 'importLegacyCheckpointV1'+ | 'reconcileLegacyCheckpointV1'+>++function parse<T>(+ schema: z.ZodType<T>,+ input: unknown,+ code = ErrorCode.EngineProtocolError+): T {+ const value = schema.safeParse(input)+ if (!value.success)+ throw new AppError(code, 'Invalid legacy checkpoint contract')+ return value.data+}++function checkPath(value: string): void {+ if (+ !path.isAbsolute(value) ||+ path.normalize(value) !== value ||+ Buffer.byteLength(value) > 4096+ )+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'Invalid legacy checkpoint path'+ )+}++function controlSnapshot(bytes: Uint8Array): {+ controlFile: string+ sourceDigest: string+} {+ if (+ !(bytes instanceof Uint8Array) ||+ !bytes.byteLength ||+ bytes.byteLength > MAX_LEGACY_CHECKPOINT_BYTES+ )+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'Invalid legacy checkpoint size'+ )+ // Copy before any await so caller mutation cannot change the admitted snapshot.+ const copy = Buffer.from(bytes)+ return {+ controlFile: copy.toString('base64'),+ sourceDigest: createHash('sha256').update(copy).digest('hex'),+ }+}++function receipt(+ value: unknown,+ expected: LegacyCheckpointReconcile+): LegacyCheckpointReceipt {+ const wire = parse(wireReceipt, value)+ const result = parse(legacyCheckpointReceiptSchema, {+ status: wire.status,+ token: wire.token,+ engineTaskId: wire.gid,+ targetPath: wire.targetPath,+ sourceDigest: wire.controlDigest,+ })+ if (+ result.token !== expected.token ||+ result.targetPath !== expected.targetPath+ )+ throw new AppError(+ ErrorCode.EngineProtocolError,+ 'Legacy checkpoint receipt identity mismatch'+ )+ return result+}++/** Native bytes stay opaque outside the concrete engine boundary. No method starts a task. */+export class Aria2LegacyCheckpoint {+ constructor(private readonly rpc: CheckpointRpc) {}++ async supported(): Promise<boolean> {+ // Pre-spawn --version reports only compile-time features. This operation+ // requires the live process's SQLite mode and platform safety support.+ const report = parse(+ z.object({ enabledFeatures: z.array(z.string()) }),+ await this.rpc.getVersion()+ )+ return (+ report.enabledFeatures.includes(FEATURE_SQLITE3_PERSISTENCE) &&+ report.enabledFeatures.includes(FEATURE_LEGACY_CHECKPOINT_IMPORT_V1)+ )+ }++ private async requireSupport(): Promise<void> {+ if (!(await this.supported()))+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'Legacy checkpoint import is unavailable'+ )+ }++ async inspect(bytes: Uint8Array): Promise<LegacyCheckpointInspection> {+ const snapshot = controlSnapshot(bytes)+ await this.requireSupport()+ const wire = parse(+ wireInspection,+ await this.rpc.inspectLegacyCheckpointV1({+ controlFile: snapshot.controlFile,+ })+ )+ if (wire.controlDigest !== snapshot.sourceDigest)+ throw new AppError(+ ErrorCode.EngineProtocolError,+ 'Legacy checkpoint digest mismatch'+ )+ return parse(legacyCheckpointInspectionSchema, {+ type: wire.kind === 'bittorrent' ? 'bt' : 'http',+ totalBytes: wire.totalLength,+ pieceBytes: wire.pieceLength,+ infoHash: wire.infoHash || null,+ sourceDigest: wire.controlDigest,+ completedBytes: wire.completedLength,+ uploadedBytes: wire.uploadLength,+ ranges: wire.ranges,+ })+ }++ async import(+ input: LegacyCheckpointImport+ ): Promise<LegacyCheckpointReceipt> {+ const request = parse(+ legacyCheckpointImportSchema,+ input,+ ErrorCode.InvalidSelection+ )+ const snapshot = controlSnapshot(request.controlFile)+ if (snapshot.sourceDigest !== request.sourceDigest)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'Legacy checkpoint source changed'+ )+ checkPath(request.targetPath)+ for (const file of request.files) checkPath(file.path)+ const wire: Aria2LegacyCheckpointImport = {+ token: request.token,+ gid: request.engineTaskId,+ controlFile: snapshot.controlFile,+ controlDigest: snapshot.sourceDigest,+ targetPath: request.targetPath,+ expected: {+ kind: request.expected.type === 'bt' ? 'bittorrent' : 'http',+ totalLength: String(request.expected.totalBytes),+ pieceLength: String(request.expected.pieceBytes),+ infoHash: request.expected.infoHash ?? '',+ },+ files: request.files.map((file) => ({+ ...file,+ offset: String(file.offset),+ length: String(file.length),+ })),+ }+ if (Buffer.byteLength(JSON.stringify(wire)) > MAX_REQUEST_BYTES)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'Legacy checkpoint request exceeds the app limit'+ )+ await this.requireSupport()+ // Never retry this mutation here: a lost response requires durable token+ // reconciliation by the caller before any subsequent activation.+ const result = receipt(+ await this.rpc.importLegacyCheckpointV1(wire),+ request+ )+ if (+ result.engineTaskId !== request.engineTaskId ||+ result.sourceDigest !== request.sourceDigest+ )+ throw new AppError(+ ErrorCode.EngineProtocolError,+ 'Legacy checkpoint receipt does not match the request'+ )+ return result+ }++ async reconcile(+ input: LegacyCheckpointReconcile+ ): Promise<LegacyCheckpointReconciliation> {+ const request = parse(+ legacyCheckpointReconcileSchema,+ input,+ ErrorCode.InvalidSelection+ )+ checkPath(request.targetPath)+ await this.requireSupport()+ const result = await this.rpc.reconcileLegacyCheckpointV1(request)+ const absent = wireAbsent.safeParse(result)+ if (absent.success) {+ if (+ absent.data.token !== request.token ||+ absent.data.targetPath !== request.targetPath+ )+ throw new AppError(+ ErrorCode.EngineProtocolError,+ 'Legacy checkpoint reconciliation identity mismatch'+ )+ return { ...request, status: 'absent' }+ }+ return receipt(result, request)+ }+}diff --git a/src/core/engine/aria2/aria2-process-inspector.test.ts b/src/core/engine/aria2/aria2-process-inspector.test.tsindex c7ad92d9..b2134439 100644--- a/src/core/engine/aria2/aria2-process-inspector.test.ts+++ b/src/core/engine/aria2/aria2-process-inspector.test.ts@@ -1,11 +1,17 @@import { describe, expect, it } from 'vitest'import {+ Aria2ProcessInspector,parseLsofPid,parseNetstatPid,parseSsPid,} from './aria2-process-inspector'describe('Aria2ProcessInspector parsers', () => {+ it('rejects unsafe PID input before platform inspection', async () => {+ const inspector = new Aria2ProcessInspector('win32')+ for (const pid of [0, -1, 1.5, Number.NaN, Number.MAX_SAFE_INTEGER + 1])+ await expect(inspector.inspectPid(pid)).resolves.toBeNull()+ })it('reads the first listener pid from lsof field output', () => {expect(parseLsofPid('p4201\np4201\n')).toBe(4201)expect(parseLsofPid('')).toBeNull()diff --git a/src/core/engine/aria2/aria2-process-inspector.ts b/src/core/engine/aria2/aria2-process-inspector.tsindex 77f33b9f..7ec68be6 100644--- a/src/core/engine/aria2/aria2-process-inspector.ts+++ b/src/core/engine/aria2/aria2-process-inspector.ts@@ -55,6 +55,11 @@ export class Aria2ProcessInspector {async inspectListeningPort(port: number): Promise<InspectedProcess | null> {const pid = await this.findListeningPid(port)if (pid === null) return null+ return this.inspectPid(pid)+ }++ async inspectPid(pid: number): Promise<InspectedProcess | null> {+ if (!Number.isSafeInteger(pid) || pid <= 0) return nullif (this.platform === 'win32') {return this.inspectWindowsProcess(pid)diff --git a/src/core/engine/aria2/aria2-rpc-client.ts b/src/core/engine/aria2/aria2-rpc-client.tsindex 3b6c5ee7..488a8e59 100644--- a/src/core/engine/aria2/aria2-rpc-client.ts+++ b/src/core/engine/aria2/aria2-rpc-client.ts@@ -1,5 +1,6 @@import type { EngineConnectionSnapshot } from '@shared/schemas/engine-connection'import type { DownloadCookie } from '../engine-adapter'+import type { Aria2LegacyCheckpointImport } from './aria2-legacy-checkpoint'import { Aria2PauseState } from './aria2-pause-state'import type { JsonRpcProtocol } from './json-rpc-protocol'import type {@@ -393,6 +394,34 @@ export class Aria2RpcClient {])}+ inspectLegacyCheckpointV1(input: { controlFile: string }): Promise<unknown> {+ return this.call('aria2.inspectLegacyCheckpointV1', [input])+ }++ addLegacyTorrentV1(input: {+ token: string+ targetPath: string+ metadataFile: string+ metadataDigest: string+ metadata: string+ options: Record<string, string | string[]>+ }): Promise<string> {+ return this.call<string>('aria2.addLegacyTorrentV1', [input])+ }++ importLegacyCheckpointV1(+ input: Aria2LegacyCheckpointImport+ ): Promise<unknown> {+ return this.call('aria2.importLegacyCheckpointV1', [input])+ }++ reconcileLegacyCheckpointV1(input: {+ token: string+ targetPath: string+ }): Promise<unknown> {+ return this.call('aria2.reconcileLegacyCheckpointV1', [input])+ }+exportSession(filePath: string): Promise<'OK'> {return this.call<'OK'>('aria2.exportSession', [filePath])}diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.tsindex 9191ec28..e8af04b2 100644--- a/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts+++ b/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts@@ -319,6 +319,7 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())()expect(args).toContain('--input-file=')handle = await spawnAria2ForTest({+ secret: settings.rpcSecret,baseDir: root,port,extraArgs: ['--no-conf=false', ...args],diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.test.tsindex 9b7177c2..e32a3aad 100644--- a/src/core/engine/aria2/aria2-session-identity-recovery.test.ts+++ b/src/core/engine/aria2/aria2-session-identity-recovery.test.ts@@ -20,7 +20,7 @@ const CHILD = '2222222222222222'const OTHER = '3333333333333333'const folders: string[] = []-async function setup(state = 'paused', schemaVersion: 2 | 3 = 2) {+async function setup(state = 'paused', schemaVersion: 2 | 3 | 4 | 5 = 2) {const root = await mkdtemp(path.join(tmpdir(), 'motrix-identity-'))folders.push(root)const file = path.join(root, 'aria2.db')@@ -40,7 +40,7 @@ async function setup(state = 'paused', schemaVersion: 2 | 3 = 2) {// Schema v3 (aria2_motrix 1.37.0-motrix.15) addresses checkpoints by output// path and no longer cascades them from task.const progressTable =- schemaVersion === 3+ schemaVersion >= 3? 'CREATE TABLE task_progress(gid TEXT NOT NULL, bitfield BLOB, out_path TEXT UNIQUE);': 'CREATE TABLE task_progress(gid TEXT PRIMARY KEY REFERENCES task(gid) ON DELETE CASCADE, bitfield BLOB);'db.exec(`@@ -50,6 +50,14 @@ async function setup(state = 'paused', schemaVersion: 2 | 3 = 2) {CREATE TABLE task_cookie_context(gid TEXT PRIMARY KEY REFERENCES task(gid) ON DELETE CASCADE, secret TEXT);CREATE TABLE download_history(id INTEGER PRIMARY KEY, gid TEXT, status TEXT, followed_by TEXT);`)+ if (schemaVersion >= 4)+ db.exec(+ 'CREATE TABLE legacy_checkpoint_import(token TEXT PRIMARY KEY, gid TEXT, consumed INTEGER)'+ )+ if (schemaVersion === 5)+ db.exec(+ 'CREATE TABLE legacy_torrent_metadata(token TEXT PRIMARY KEY, gid TEXT, metadata_digest TEXT)'+ )const insert = db.prepare('INSERT INTO task VALUES (?, ?, ?, ?, NULL, 0, ?)')insert.run(PARENT, 'waiting', entry(PARENT), Buffer.from('parent-digest'), 0)insert.run(@@ -294,29 +302,82 @@ describe('aria2 persisted task identity recovery', () => {}})- it('repairs a schema-v3 database and retires the ancestor checkpoint explicitly', async () => {- // v3 dropped the task→task_progress CASCADE, so retiring the metadata- // ancestor must delete its checkpoint itself or it would outlive the task.- const h = await setup('paused', 3)- try {- h.db- .prepare('INSERT INTO task_progress (gid, bitfield) VALUES (?, ?)')- .run(PARENT, Buffer.from([0xff]))- const result = await recoverAria2SessionIdentity(h.file)- expect(result?.repairedGids).toEqual([CHILD])- expect(result?.retiredMetadataGids).toEqual([PARENT])- expect(- h.db.prepare('SELECT gid, bitfield FROM task_progress').all()- ).toEqual([{ gid: CHILD, bitfield: Buffer.from([0xaa, 0xc0]) }])- } finally {- h.db.close()+ it.each([3, 4, 5] as const)(+ 'repairs schema v%s and preserves unrelated migration claims',+ async (schemaVersion) => {+ // v3 dropped the task→task_progress CASCADE, so retiring the metadata+ // ancestor must delete its checkpoint itself or it would outlive the task.+ const h = await setup('paused', schemaVersion)+ try {+ h.db+ .prepare('INSERT INTO task_progress (gid, bitfield) VALUES (?, ?)')+ .run(PARENT, Buffer.from([0xff]))+ if (schemaVersion >= 4)+ h.db+ .prepare('INSERT INTO legacy_checkpoint_import VALUES (?, ?, 1)')+ .run('unchanged-token', OTHER)+ if (schemaVersion === 5)+ h.db+ .prepare('INSERT INTO legacy_torrent_metadata VALUES (?, ?, ?)')+ .run('unchanged-token', OTHER, 'unchanged-digest')+ const result = await recoverAria2SessionIdentity(h.file)+ expect(result?.repairedGids).toEqual([CHILD])+ expect(result?.retiredMetadataGids).toEqual([PARENT])+ if (schemaVersion >= 4)+ expect(+ h.db.prepare('SELECT * FROM legacy_checkpoint_import').all()+ ).toEqual([{ token: 'unchanged-token', gid: OTHER, consumed: 1 }])+ if (schemaVersion === 5)+ expect(+ h.db.prepare('SELECT * FROM legacy_torrent_metadata').all()+ ).toEqual([+ {+ token: 'unchanged-token',+ gid: OTHER,+ metadata_digest: 'unchanged-digest',+ },+ ])+ expect(+ h.db.prepare('SELECT gid, bitfield FROM task_progress').all()+ ).toEqual([{ gid: CHILD, bitfield: Buffer.from([0xaa, 0xc0]) }])+ } finally {+ h.db.close()+ }}- })+ )++ it.each([PARENT, CHILD])(+ 'refuses repair involving a migration-owned GID %s',+ async (gid) => {+ const h = await setup('paused', 5)+ try {+ h.db+ .prepare('INSERT INTO legacy_checkpoint_import VALUES (?, ?, 1)')+ .run('owned-token', gid)+ const before = h.rows()+ const progress = h.db.prepare('SELECT * FROM task_progress').all()+ await expect(recoverAria2SessionIdentity(h.file)).rejects.toThrow(+ 'legacy checkpoint identity is immutable'+ )+ expect(h.rows()).toEqual(before)+ expect(h.db.prepare('SELECT * FROM task_progress').all()).toEqual(+ progress+ )+ expect(+ (await readdir(h.root)).filter((name) =>+ name.includes('identity-recovery-')+ )+ ).toHaveLength(0)+ } finally {+ h.db.close()+ }+ }+ )it('leaves an unfamiliar future schema unchanged', async () => {const h = await setup()try {- h.db.pragma('user_version = 4')+ h.db.pragma('user_version = 6')const before = h.rows()expect(await recoverAria2SessionIdentity(h.file)).toBeNull()expect(h.rows()).toEqual(before)diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.ts b/src/core/engine/aria2/aria2-session-identity-recovery.tsindex 5d225c1f..bc935f73 100644--- a/src/core/engine/aria2/aria2-session-identity-recovery.ts+++ b/src/core/engine/aria2/aria2-session-identity-recovery.ts@@ -60,7 +60,7 @@ export interface SessionIdentityRecovery {}/**- * Repair the fork's metadata-ancestor GID serialization (schema v1–v3) before spawn.+ * Repair the fork's metadata-ancestor GID serialization (schema v1–v5) before spawn.* The actual row key remains the owner of progress, cookies and app identity.* A verified local torrent replaces the magnet so aria2 recreates that exact* payload task directly. No engine schema, setting or download data changes.@@ -78,8 +78,7 @@ export async function recoverAria2SessionIdentity(const db = new Database(databasePath, { fileMustExist: true, timeout: 0 })try {const schemaVersion = db.pragma('user_version', { simple: true })- if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3)- return null+ if (![1, 2, 3, 4, 5].includes(Number(schemaVersion))) return nullconst dataVersion = db.pragma('data_version', { simple: true })const rows = z.array(rowSchema)@@ -89,6 +88,23 @@ export async function recoverAria2SessionIdentity(return entry && row.gid !== entry.gid ? [{ row, entry }] : []})if (candidates.length === 0) return null+ const legacyGids = new Set(+ Number(schemaVersion) >= 4+ ? (+ db+ .prepare(+ Number(schemaVersion) === 5+ ? 'SELECT gid FROM legacy_checkpoint_import UNION SELECT gid FROM legacy_torrent_metadata'+ : 'SELECT gid FROM legacy_checkpoint_import'+ )+ .all() as Array<{ gid: string }>+ ).map((row) => row.gid)+ : []+ )+ for (const { row, entry } of candidates) {+ if (legacyGids.has(row.gid) || legacyGids.has(entry.gid))+ throw failure(row.gid, 'legacy checkpoint identity is immutable')+ }if (!canRepair())throw new Error('aria2 session recovery requires a stopped engine')@@ -213,11 +229,11 @@ export async function recoverAria2SessionIdentity(throw failure(row.gid, 'task changed during recovery')}const remove = db.prepare('DELETE FROM task WHERE gid = ?')- // Schema v3 no longer cascades task → task_progress (checkpoints are+ // Schema v3 and later do not cascade task → task_progress (checkpoints are// addressed by output path), so a retired ancestor's checkpoint is// dropped explicitly, exactly as v1/v2 did through the cascade.const removeProgress =- schemaVersion === 3+ Number(schemaVersion) >= 3? db.prepare('DELETE FROM task_progress WHERE gid = ?'): nullfor (const gid of retiredMetadataGids) {diff --git a/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts b/src/core/engine/aria2/completed-task-startup-guard.integration.test.tsindex fb8bc72d..516de60c 100644--- a/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts+++ b/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts@@ -70,6 +70,7 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())({ timeout: 10000 })const run = await wired.rpc.addUri([`${base}/slow-running.bin`])+ const held = await wired.rpc.addUri([`${base}/slow-held.bin`])const paused = await wired.rpc.addUri([`${base}/slow-paused.bin`], {pause: 'true',})@@ -78,16 +79,22 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(expect((await wired.rpc.tellStatus(run)).status).toBe('active'),{ timeout: 10000 })+ await vi.waitFor(+ () => expect(counts.get('/slow-held.bin')).toBeGreaterThan(0),+ { timeout: 10000 }+ )await wired.rpc.saveSession()wired.disconnect()await handle.kill()await unlink(path.join(root, 'done.bin'))const requestsBefore = counts.get('/done.bin')+ const heldRequestsBefore = counts.get('/slow-held.bin')const restartArgs = sqlite? args: [...args, `--input-file=${session}`]const guard = new CompletedTaskStartupGuard({completedGids: () => new Set([done]),+ heldGids: () => new Set([held]),get rpc() {return wired.rpc},@@ -108,6 +115,8 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())({ timeout: 10000 })expect((await wired.rpc.tellStatus(paused)).status).toBe('paused')+ expect((await wired.rpc.tellStatus(held)).status).toBe('paused')+ expect(counts.get('/slow-held.bin')).toBe(heldRequestsBefore)expect(counts.get('/done.bin')).toBe(requestsBefore)await expect(access(path.join(root, 'done.bin'))@@ -179,6 +188,8 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(/not found/i)expect(counts.get('/fresh.bin')).toBe(1)+ expect((await wired.rpc.tellStatus(held)).status).toBe('paused')+ expect(counts.get('/slow-held.bin')).toBe(heldRequestsBefore)await expect(access(path.join(root, 'fresh.bin'))).rejects.toMatchObject({ code: 'ENOENT' })diff --git a/src/core/engine/aria2/completed-task-startup-guard.test.ts b/src/core/engine/aria2/completed-task-startup-guard.test.tsindex 72953ea3..7b1ac339 100644--- a/src/core/engine/aria2/completed-task-startup-guard.test.ts+++ b/src/core/engine/aria2/completed-task-startup-guard.test.ts@@ -104,6 +104,70 @@ describe('CompletedTaskStartupGuard', () => {expect(await h.guard.prepare(h.args)).toBeNull()})+ it.each([false, true])(+ 'holds pending ownership without purging it or changing other run intent (sqlite=%s)',+ async (sqlite) => {+ const h = await setup(sqlite)+ const guard = new CompletedTaskStartupGuard({+ completedGids: () => new Set(),+ heldGids: () => new Set([RUN]),+ rpc: h.rpc,+ removeResult: h.removeResult,+ })+ const prepared = await guard.prepare(h.args)+ expect(prepared?.args).toContain('--pause=true')+ expect(JSON.parse(await readFile(h.journal, 'utf8')).resume).toEqual([+ DONE,+ ])+ await prepared?.reconcile(() => false)+ expect(h.rpc.unpause).toHaveBeenCalledExactlyOnceWith(DONE)+ expect(h.rpc.forceRemove).not.toHaveBeenCalled()+ expect(h.removeResult).not.toHaveBeenCalled()+ }+ )++ it('removes a newly held GID from an interrupted journal even if its hold later resolves', async () => {+ const h = await setup()+ await h.guard.prepare(h.args)+ await writeFile(+ h.source,+ entry(DONE, true) + entry(RUN, true) + entry(PAUSED, true)+ )+ const held = new Set([RUN])+ const guard = new CompletedTaskStartupGuard({+ completedGids: () => new Set([DONE]),+ heldGids: () => held,+ rpc: h.rpc,+ removeResult: h.removeResult,+ })+ const prepared = await guard.prepare(h.args)+ expect(JSON.parse(await readFile(h.journal, 'utf8')).resume).toEqual([DONE])+ held.clear()+ await prepared?.reconcile(() => false)+ expect(h.rpc.unpause).not.toHaveBeenCalled()+ expect(h.removeResult).toHaveBeenCalledExactlyOnceWith(DONE)+ })++ it('rechecks a new hold after awaiting status and never purges overlapping held/completed GIDs', async () => {+ const h = await setup()+ const held = new Set([DONE])+ const guard = new CompletedTaskStartupGuard({+ completedGids: () => new Set([DONE]),+ heldGids: () => held,+ rpc: h.rpc,+ removeResult: h.removeResult,+ })+ const prepared = await guard.prepare(h.args)+ h.rpc.tellStatus.mockImplementation(async (gid) => {+ if (gid === RUN) held.add(RUN)+ return { status: 'paused' } as never+ })+ await prepared?.reconcile(() => false)+ expect(h.rpc.unpause).not.toHaveBeenCalled()+ expect(h.rpc.forceRemove).not.toHaveBeenCalled()+ expect(h.removeResult).not.toHaveBeenCalled()+ })+it('preserves original run intent after a crash in a paused startup', async () => {const h = await setup()await h.guard.prepare(h.args)diff --git a/src/core/engine/aria2/completed-task-startup-guard.ts b/src/core/engine/aria2/completed-task-startup-guard.tsindex 8c7ded65..ca67de1b 100644--- a/src/core/engine/aria2/completed-task-startup-guard.ts+++ b/src/core/engine/aria2/completed-task-startup-guard.ts@@ -142,7 +142,7 @@ async function readRunIntent(}/**- * A targeted startup barrier for durable completed GIDs. Other downloads keep+ * A targeted startup barrier for completed and explicitly held GIDs. Other downloads keep* the engine's original run intent, including engine-only and paused tasks.* A small durable journal preserves that intent if a paused boot is interrupted.*/@@ -150,6 +150,8 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {constructor(private readonly deps: {completedGids: () => ReadonlySet<string>+ /** Pending ownership reconciliation: pause at boot, never purge or auto-resume. */+ heldGids?: () => ReadonlySet<string>rpc: Pick<Aria2RpcClient,'tellStatus' | 'forceRemove' | 'unpause' | 'changeGlobalOption'@@ -183,17 +185,25 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {if (!missing(error)) throw error}const completed = this.deps.completedGids()- if (!previous && completed.size === 0) return null+ const held = new Set(this.deps.heldGids?.())+ if (!previous && completed.size === 0 && held.size === 0) return nullconst intent = await readRunIntent(source,sqlite,- (gids) => previous !== null || gids.some((gid) => completed.has(gid))+ (gids) =>+ previous !== null ||+ gids.some((gid) => completed.has(gid) || held.has(gid)))- const targets = [...intent.keys()].filter((gid) => completed.has(gid))- if (!previous && targets.length === 0) return null- const resume = previous- ? previous.resume.filter((gid) => intent.has(gid))- : [...intent].filter(([, run]) => run).map(([gid]) => gid)+ const targets = [...intent.keys()].filter(+ (gid) => completed.has(gid) && !held.has(gid)+ )+ const hasHeldTask = [...intent.keys()].some((gid) => held.has(gid))+ if (!previous && targets.length === 0 && !hasHeldTask) return null+ const resume = (+ previous+ ? previous.resume.filter((gid) => intent.has(gid))+ : [...intent].filter(([, run]) => run).map(([gid]) => gid)+ ).filter((gid) => !held.has(gid))await writeFileAtomic(journalPath,JSON.stringify({ version: 1, source, resume }),@@ -208,6 +218,7 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {reconcile: async (isStopping) => {for (const gid of targets) {if (isStopping()) return+ if (this.deps.heldGids?.().has(gid)) continuelet state: string | undefinedtry {state = (await this.deps.rpc.tellStatus(gid)).status@@ -215,13 +226,15 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {if (!isNotFoundError(error)) throw error}if (state && !['complete', 'error', 'removed'].includes(state)) {+ if (this.deps.heldGids?.().has(gid)) continuetry {await this.deps.rpc.forceRemove(gid)} catch (error) {if (!isNotFoundError(error)) throw error}}- await this.deps.removeResult(gid)+ if (!this.deps.heldGids?.().has(gid))+ await this.deps.removeResult(gid)}// Do not release any remaining task if even one required purge failed.if (isStopping()) return@@ -229,9 +242,12 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {const completedNow = this.deps.completedGids()for (const gid of resume) {if (isStopping()) return- if (completedNow.has(gid)) continue+ if (completedNow.has(gid) || this.deps.heldGids?.().has(gid)) continuetry {- if ((await this.deps.rpc.tellStatus(gid)).status === 'paused')+ if (+ (await this.deps.rpc.tellStatus(gid)).status === 'paused' &&+ !this.deps.heldGids?.().has(gid)+ )await this.deps.rpc.unpause(gid)} catch (error) {if (!isNotFoundError(error)) throw errordiff --git a/src/core/engine/aria2/feature-report.test.ts b/src/core/engine/aria2/feature-report.test.tsindex 5dad6b3d..e4aa738d 100644--- a/src/core/engine/aria2/feature-report.test.ts+++ b/src/core/engine/aria2/feature-report.test.ts@@ -65,6 +65,33 @@ describe('isMotrixFork', () => {})describe('hasDurableRemoveSemantics', () => {+ it.each(['1.37.0-motrix.16-dev', '1.37.0-motrix.16-dev.legacy-import'])(+ 'recognizes explicitly labelled development builds: %s',+ (version) => {+ expect(+ isMotrixFork(buildFeatureReport(version, ['SQLite3-Persistence']))+ ).toBe(true)+ expect(isMotrixFork(buildFeatureReport(version, []))).toBe(false)+ expect(hasDurableRemoveSemantics(version)).toBe(true)+ }+ )++ it('keeps capability and removal thresholds for development builds', () => {+ expect(hasDurableRemoveSemantics('1.37.0-motrix.2-dev')).toBe(false)+ expect(hasDurableRemoveSemantics('1.36.0-motrix.16-dev')).toBe(false)+ for (const version of [+ '1.37.0-dev',+ '1.37.0-motrix.16-unknown',+ '1.37.0-motrix.16-dev.',+ '1.37.0-motrix.16-dev/other',+ ]) {+ expect(+ isMotrixFork(buildFeatureReport(version, ['SQLite3-Persistence']))+ ).toBe(false)+ expect(hasDurableRemoveSemantics(version)).toBe(false)+ }+ })+it('trusts motrix fork 1.37.0-motrix.3 and later', () => {expect(hasDurableRemoveSemantics('1.37.0-motrix.3')).toBe(true)expect(hasDurableRemoveSemantics('1.37.0-motrix.4')).toBe(true)diff --git a/src/core/engine/aria2/feature-report.ts b/src/core/engine/aria2/feature-report.tsindex 29be5dc7..e1fae4bd 100644--- a/src/core/engine/aria2/feature-report.ts+++ b/src/core/engine/aria2/feature-report.ts@@ -5,6 +5,9 @@ import {// aria2 gained --bt-seed-unverified and --bt-save-metadata in 1.37.0.const BT_FEATURES_MIN_VERSION = '1.37.0'+// The engine release workflow also builds explicitly labelled -dev candidates.+const MOTRIX_VERSION =+ /^(\d+\.\d+\.\d+)-motrix\.(\d+)(?:-dev(?:\.[a-z0-9-]+)*)?$/i/** Official aria2's per-task connection ceiling. */export const STANDARD_ARIA2_CONNECTION_LIMIT = 16@@ -17,10 +20,7 @@ export const STANDARD_ARIA2_CONNECTION_LIMIT = 16export function isMotrixFork(report: Pick<EngineFeatureReport, 'version' | 'hasSqlitePersistence'>): boolean {- return (- /^\d+\.\d+\.\d+-motrix\.\d+$/i.test(report.version) &&- report.hasSqlitePersistence- )+ return MOTRIX_VERSION.test(report.version) && report.hasSqlitePersistence}/**@@ -77,7 +77,7 @@ export function semverGte(a: string, b: string): boolean {* without it there is no durable row a not-found could be hiding.*/export function hasDurableRemoveSemantics(version: string): boolean {- const match = /^(\d+\.\d+\.\d+)-motrix\.(\d+)$/.exec(version)+ const match = MOTRIX_VERSION.exec(version)if (!match) return falseconst [, base, patch] = matchif (!semverGte(base, '1.37.0')) return falsediff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex 3cc4dc97..dcc7d4e1 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -1,4 +1,11 @@import type { EnginePerformanceProfile } from '@shared/constants/engine-performance-profiles'+import type {+ LegacyCheckpointImport,+ LegacyCheckpointInspection,+ LegacyCheckpointReceipt,+ LegacyCheckpointReconcile,+ LegacyCheckpointReconciliation,+} from '@shared/schemas/legacy-checkpoint'import type {EngineCapability,EngineFeatureReport,@@ -43,6 +50,10 @@ export type DirectResourceMetadataProfile =typeof DIRECT_RESOURCE_METADATA_PROFILEexport interface AddTorrentParams {+ /** Internal migration path: keeps original trackers and pins verification/no-seeding options. */+ legacyCheckpointActivation?: { token: string; targetPath: string }+ /** Read-only durable metadata source for an authorized legacy BT task. */+ durableMetadata?: { path: string; digest: string }metadata: Uint8ArraysaveDir: string/** Optional caller-reserved aria2 GID. aria2 accepts exactly 16@@ -150,7 +161,18 @@ export type BtTrackerPolicy = (input: {isPrivate?: boolean}) => Promise<{ trackers: string[]; isPrivate: boolean }>+export interface LegacyBtBindingProof {+ engineTaskId: string+ saveDir: string+ infoHash: string+ files: Array<{ path: string; length: number }>+ selectedFiles: number[]+ trackers: string[]+ isPrivate: boolean+}export interface EngineAdapter {+ /** Prove exact native BT ownership, selection and safe restoration options. */+ verifyLegacyBtBinding?(input: LegacyBtBindingProof): Promise<boolean>configureBtTrackerPolicy?(policy: BtTrackerPolicy): voidsetTaskBtTracker(engineTaskId: string, trackers: string[]): Promise<void>connect(): Promise<void>@@ -273,6 +295,23 @@ export interface EngineAdapter {*/getCheckpointStatus?(outputPath: string): Promise<'present' | 'absent' | null>+ /** Live capability check; compiled-in support alone does not authorize import. */+ supportsLegacyCheckpointImport?(): 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. */+ inspectLegacyCheckpoint?(+ bytes: Uint8Array+ ): Promise<LegacyCheckpointInspection>+ /** Persist a native checkpoint and idempotent receipt without starting a task. */+ importLegacyCheckpoint?(+ input: LegacyCheckpointImport+ ): Promise<LegacyCheckpointReceipt>+ /** Reconcile an uncertain import, sealing invalid receipts so they cannot revive. */+ reconcileLegacyCheckpoint?(+ input: LegacyCheckpointReconcile+ ): Promise<LegacyCheckpointReconciliation>+/*** Batch variant of {@link removeDownloadResult}, executed in bounded* chunks. Entries are attempted in array order and each outcome isdiff --git a/src/core/legacy-import/bt-activation-adversarial.test.ts b/src/core/legacy-import/bt-activation-adversarial.test.tsnew file mode 100644index 00000000..acd689d4--- /dev/null+++ b/src/core/legacy-import/bt-activation-adversarial.test.ts@@ -0,0 +1,386 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import {+ cp,+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import type {+ AddTorrentParams,+ EngineAdapter,+} from '@core/engine/engine-adapter'+import { MotrixDatabase } from '@core/session/motrix-database'+import {+ type FinalizeTaskDeps,+ finalizeTask,+} from '@core/task/actions/finalize-task'+import { TaskManager } from '@core/task/task-manager'+import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'+import type {+ LegacyCheckpointImport,+ LegacyCheckpointReconciliation,+} from '@shared/schemas/legacy-checkpoint'+import { type DownloadTask, TaskStatus } from '@shared/types/task'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LegacyBtActivationService } from './bt-activation-service'+import { LegacyImportService } from './import-service'++const cleanups: Array<() => Promise<void>> = []+const infoHash = '45c7c651e500cc0ceaa544d6fbafcb21b8cd52f8'+const digest = (bytes: Uint8Array) =>+ createHash('sha256').update(bytes).digest('hex')++async function fixture() {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'legacy-bt-review-'))+ )+ const generated = path.resolve('tests/fixtures/legacy-v1/generated')+ await cp(generated, root, { recursive: true })+ const profile = path.join(root, 'profile')+ const downloads = path.join(profile, 'downloads')+ await cp(path.join(root, 'downloads'), downloads, { recursive: true })+ for (const name of ['download.session', 'system.json']) {+ const filename = path.join(profile, name)+ await writeFile(+ filename,+ (await readFile(filename, 'utf8'))+ .replaceAll('__FIXTURE_ROOT__', profile)+ .replaceAll('__FIXTURE_DOWNLOADS__', downloads)+ .replaceAll('__FIXTURE_HTTP_PORT__', '18080')+ )+ }+ await mkdir(path.join(downloads, 'fixture-bundle'))+ await writeFile(+ path.join(downloads, 'fixture-bundle', 'first.bin'),+ Buffer.alloc(16384, 1),+ { mode: 0o600 }+ )+ await writeFile(+ path.join(downloads, 'fixture-bundle', 'second.bin'),+ Buffer.alloc(16384, 2),+ { mode: 0o600 }+ )+ const db = new MotrixDatabase(path.join(root, 'motrix.db'))+ db.init()+ const taskManager = new TaskManager()+ const isProcessRunning = vi.fn(async () => false)+ const backupRoot = path.join(root, 'backups')+ const importer = new LegacyImportService({+ db,+ taskManager,+ backupRoot,+ isProcessRunning,+ publishTasks: vi.fn(),+ })+ const source = await importer.addSource(profile)+ const preview = await importer.scan(source.sourceHandle)+ const item = preview.items.find(+ (candidate) => candidate.type === 'bt' && candidate.selectable+ )+ expect(item).toBeDefined()+ const run = await importer.commit({+ previewId: preview.previewId,+ itemIds: [item!.itemId],+ })+ await expect.poll(() => importer.getRun(run.runId).stage).toBe('completed')+ const taskId = importer+ .getRun(run.runId)+ .items.find((entry) => entry.outcome === 'imported')!.taskId!+ let imported: LegacyCheckpointImport | null = null+ let engine: DownloadTask | null = null+ const receipt = () => ({+ status: 'created' as const,+ token: imported!.token,+ engineTaskId: imported!.engineTaskId,+ targetPath: imported!.targetPath,+ sourceDigest: imported!.sourceDigest,+ })+ const mocks = {+ supportsLegacyCheckpointImport: vi.fn(async () => true),+ supportsLegacyBtActivation: vi.fn(async () => true),+ inspectLegacyCheckpoint: vi.fn(async (bytes: Uint8Array) => ({+ type: 'bt' as const,+ totalBytes: 32768,+ pieceBytes: 16384,+ infoHash,+ sourceDigest: digest(bytes),+ completedBytes: 0,+ uploadedBytes: 0,+ ranges: [],+ })),+ reconcileLegacyCheckpoint: vi.fn(+ async (input: {+ token: string+ targetPath: string+ }): Promise<LegacyCheckpointReconciliation> =>+ imported ? receipt() : { ...input, status: 'absent' as const }+ ),+ importLegacyCheckpoint: vi.fn(async (input: LegacyCheckpointImport) => {+ imported = input+ return receipt()+ }),+ getTaskStatus: vi.fn(async () => engine),+ verifyLegacyBtBinding: vi.fn(async () => true),+ listActiveAndWaiting: vi.fn(async () => []),+ listStopped: vi.fn(async () => []),+ addTorrent: vi.fn(async (input: AddTorrentParams) => {+ const pair = db.getTask(taskId)!+ engine = {+ ...taskRowToDownloadTask(pair.task, pair.instances),+ engineTaskId: input.gid!,+ status: TaskStatus.Paused,+ }+ return input.gid!+ }),+ pauseTask: vi.fn(async () => {+ if (engine) engine.status = TaskStatus.Paused+ }),+ resumeTask: vi.fn(async () => {+ if (engine) engine.status = TaskStatus.Downloading+ }),+ }+ const deps = {+ db,+ taskManager,+ backupRoot,+ isProcessRunning,+ adapter: mocks as unknown as EngineAdapter,+ publishTasks: vi.fn(),+ runTaskMutation: async <T>(+ _ids: readonly string[],+ operation: () => Promise<T>+ ) => operation(),+ runExclusivePersistence: async <T>(operation: () => T | Promise<T>) =>+ operation(),+ }+ const services: LegacyBtActivationService[] = []+ const service = () => {+ const value = new LegacyBtActivationService(deps)+ services.push(value)+ return value+ }+ cleanups.push(async () => {+ for (const value of services) await value.drain()+ await importer.drain()+ db.close()+ await rm(root, { recursive: true, force: true })+ })+ return {+ root,+ profile,+ downloads,+ db,+ taskManager,+ taskId,+ mocks,+ service,+ pick: vi.fn(async () => downloads),+ setEngine: (value: DownloadTask) => {+ engine = value+ },+ getEngine: () => engine!,+ receipt,+ isProcessRunning,+ }+}++afterEach(async () => {+ for (const cleanup of cleanups.splice(0)) await cleanup()+})++describe('legacy BT activation adversarial recovery', () => {+ it('reconciles a lost checkpoint response without replaying the mutation', async () => {+ const f = await fixture()+ const implementation =+ f.mocks.importLegacyCheckpoint.getMockImplementation()!+ f.mocks.importLegacyCheckpoint.mockImplementationOnce(async (input) => {+ await implementation(input)+ throw new Error('lost checkpoint response')+ })+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow(+ 'lost checkpoint response'+ )+ expect(f.mocks.addTorrent).not.toHaveBeenCalled()+ await f.service().activate(f.taskId, f.pick)+ expect(f.mocks.importLegacyCheckpoint).toHaveBeenCalledOnce()+ expect(f.mocks.addTorrent).toHaveBeenCalledOnce()+ expect(f.mocks.resumeTask).toHaveBeenCalledOnce()+ expect(f.pick).toHaveBeenCalledOnce()+ expect(f.db.getAllTasks()).toHaveLength(1)+ })++ it('recovers a lost paused-create response without unpausing or creating twice', async () => {+ const f = await fixture()+ const implementation = f.mocks.addTorrent.getMockImplementation()!+ f.mocks.addTorrent.mockImplementationOnce(async (input) => {+ await implementation(input)+ throw new Error('lost create response')+ })+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow(+ 'lost create response'+ )+ const gid = f.getEngine().engineTaskId+ const recovered = f.service()+ await recovered.recover()+ expect(f.mocks.resumeTask).not.toHaveBeenCalled()+ expect(f.db.getTask(f.taskId)?.instances[0]?.gid).toBe(gid)+ await recovered.activate(f.taskId, f.pick)+ expect(f.mocks.addTorrent).toHaveBeenCalledOnce()+ expect(f.mocks.resumeTask).toHaveBeenCalledExactlyOnceWith(gid)+ expect(f.db.getAllTasks()).toHaveLength(1)+ })++ it('does not pause or adopt a different torrent occupying an uncertain GID', async () => {+ const f = await fixture()+ const implementation = f.mocks.addTorrent.getMockImplementation()!+ f.mocks.addTorrent.mockImplementationOnce(async (input) => {+ await implementation(input)+ throw new Error('lost create response')+ })+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow()+ f.setEngine({+ ...f.getEngine(),+ status: TaskStatus.Downloading,+ infoHash: 'f'.repeat(40),+ })+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow()+ expect(f.mocks.pauseTask).not.toHaveBeenCalled()+ expect(f.mocks.resumeTask).not.toHaveBeenCalled()+ expect(f.db.getTask(f.taskId)?.instances[0]?.gid).toBeNull()+ })++ it('rechecks the old process before binding a previously created task', async () => {+ const f = await fixture()+ const implementation = f.mocks.addTorrent.getMockImplementation()!+ f.mocks.addTorrent.mockImplementationOnce(async (input) => {+ await implementation(input)+ throw new Error('lost create response')+ })+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow()+ await writeFile(path.join(f.profile, 'engine.pid'), '54321')+ f.isProcessRunning.mockResolvedValue(true)+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow(+ /running/+ )+ expect(f.mocks.resumeTask).not.toHaveBeenCalled()+ expect(f.db.getTask(f.taskId)?.instances[0]?.gid).toBeNull()+ })++ it('does not pause matching torrent content without a complete ownership proof', async () => {+ const f = await fixture()+ const implementation = f.mocks.addTorrent.getMockImplementation()!+ f.mocks.addTorrent.mockImplementationOnce(async (input) => {+ await implementation(input)+ throw new Error('lost create response')+ })+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow()+ f.setEngine({ ...f.getEngine(), status: TaskStatus.Downloading })+ f.mocks.verifyLegacyBtBinding.mockResolvedValue(false)+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow()+ expect(f.mocks.pauseTask).not.toHaveBeenCalled()+ expect(f.mocks.resumeTask).not.toHaveBeenCalled()+ expect(f.db.getTask(f.taskId)?.instances[0]?.gid).toBeNull()+ })++ it('cancels an outstanding directory picker on shutdown without creating intent', async () => {+ const f = await fixture()+ const service = f.service()+ let answer: (value: string) => void = () => {}+ const picked = new Promise<string>((resolve) => {+ answer = resolve+ })+ const choose = vi.fn(() => picked)+ const operation = service.activate(f.taskId, choose)+ await expect.poll(() => choose.mock.calls.length).toBe(1)+ await service.drain()+ await expect(operation).resolves.toBe(false)+ answer(f.downloads)+ await Promise.resolve()+ expect(f.mocks.importLegacyCheckpoint).not.toHaveBeenCalled()+ expect(f.mocks.addTorrent).not.toHaveBeenCalled()+ expect(f.mocks.resumeTask).not.toHaveBeenCalled()+ expect(f.db.getTask(f.taskId)?.instances[0]?.payload).not.toHaveProperty(+ 'legacyBtActivation'+ )+ })++ it('never recreates consumed progress when its reserved task is absent', async () => {+ const f = await fixture()+ f.mocks.addTorrent.mockRejectedValueOnce(+ new Error('unknown create outcome')+ )+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow()+ f.mocks.reconcileLegacyCheckpoint.mockImplementation(async () => ({+ ...f.receipt(),+ status: 'consumed',+ }))+ await expect(f.service().activate(f.taskId, f.pick)).rejects.toThrow(+ /activationUncertain/+ )+ expect(f.mocks.addTorrent).toHaveBeenCalledOnce()+ expect(f.mocks.importLegacyCheckpoint).toHaveBeenCalledOnce()+ expect(f.mocks.resumeTask).not.toHaveBeenCalled()+ })++ it.each([+ {+ name: 'integrity verification is still running',+ status: TaskStatus.Downloading,+ bytes: 16384,+ mismatchedGid: false,+ },+ {+ name: 'the completed report has zero bytes',+ status: TaskStatus.Completed,+ bytes: 0,+ mismatchedGid: false,+ },+ {+ name: 'the public GID differs from the durable binding',+ status: TaskStatus.Completed,+ bytes: 16384,+ mismatchedGid: true,+ },+ ])(+ 'does not finalize when $name',+ async ({ status, bytes, mismatchedGid }) => {+ const f = await fixture()+ await f.service().activate(f.taskId, f.pick)+ f.setEngine({+ ...f.getEngine(),+ status,+ downloadedBytes: bytes,+ totalBytes: bytes,+ progress: 1,+ ...(mismatchedGid ? { engineTaskId: 'fedcba0987654321' } : {}),+ })+ if (mismatchedGid)+ f.taskManager.getById(f.taskId)!.engineTaskId = 'fedcba0987654321'+ const persisted = vi.fn(async () => {})+ const publishTaskUpdateNow = vi.fn()+ const deps = {+ taskManager: {+ getById: f.taskManager.getById.bind(f.taskManager),+ set: f.taskManager.set.bind(f.taskManager),+ persist: persisted,+ },+ adapter: f.mocks,+ publishTaskUpdateNow,+ eventBus: { emit: vi.fn() },+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },+ } as unknown as FinalizeTaskDeps+ await finalizeTask(f.taskId, deps)+ expect(persisted).not.toHaveBeenCalled()+ expect(publishTaskUpdateNow).not.toHaveBeenCalled()+ expect(f.taskManager.getById(f.taskId)?.status).not.toBe(+ TaskStatus.Completed+ )+ }+ )+})diff --git a/src/core/legacy-import/bt-activation-service.test.ts b/src/core/legacy-import/bt-activation-service.test.tsnew file mode 100644index 00000000..557628d1--- /dev/null+++ b/src/core/legacy-import/bt-activation-service.test.ts@@ -0,0 +1,257 @@+// @vitest-environment node+import { readFile, rm, writeFile } from 'node:fs/promises'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'+import type { LegacyCheckpointReceipt } from '@shared/schemas/legacy-checkpoint'+import type { DownloadTask } from '@shared/types/task'+import { TaskStatus } from '@shared/types/task'+import { isLegacyImportInactive } from '@shared/types/task-actions'+import { legacyBtActivationFixture } from '@test-utils/legacy-bt-activation-fixture'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LegacyBtActivationService } from './bt-activation-service'++const cleanup: Array<() => Promise<void>> = []+afterEach(async () => {+ await Promise.all(cleanup.splice(0).map((fn) => fn()))+})+async function fixture() {+ let receipt: LegacyCheckpointReceipt | null = null+ let engine: DownloadTask | null = null+ let loseImport = false+ let loseAdd = false+ let binding = true+ let f: Awaited<ReturnType<typeof legacyBtActivationFixture>>+ const adapter = {+ supportsLegacyBtActivation: vi.fn(async () => true),+ inspectLegacyCheckpoint: vi.fn(async () => ({+ type: 'bt',+ totalBytes: 32768,+ pieceBytes: 16384,+ infoHash: '45c7c651e500cc0ceaa544d6fbafcb21b8cd52f8',+ completedBytes: 0,+ uploadedBytes: 0,+ ranges: [],+ sourceDigest:+ '9eca779c68d5814eea38b1f4b2c7d73e528a88993f8ade862ca8db90adc5b7eb',+ })),+ reconcileLegacyCheckpoint: vi.fn(+ async (input) => receipt ?? { ...input, status: 'absent' }+ ),+ importLegacyCheckpoint: vi.fn(async (input) => {+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ ).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+ }),+ getTaskStatus: vi.fn(async () => engine),+ listActiveAndWaiting: vi.fn(async () =>+ engine ? [{ gid: engine.engineTaskId, infoHash: engine.infoHash }] : []+ ),+ listStopped: vi.fn(async () => []),+ addTorrent: vi.fn(async (params) => {+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ ).toMatchObject({ stage: 'create-uncertain', engineTaskId: params.gid })+ expect(params).toMatchObject({+ saveDir: f.downloads,+ pause: true,+ selectedFiles: [1],+ checkIntegrity: true,+ btSeedUnverified: false,+ legacyCheckpointActivation: expect.objectContaining({+ targetPath: path.join(f.downloads, 'fixture-bundle'),+ }),+ })+ expect(params.outputRoot).toBeUndefined()+ expect(f.taskManager.isEngineTaskIdRetired(params.gid)).toBe(true)+ engine = {+ ...f.taskManager.getById(f.taskId),+ engineTaskId: params.gid,+ status: TaskStatus.Paused,+ } as DownloadTask+ if (loseAdd) {+ loseAdd = false+ throw new Error('Lost add response')+ }+ return params.gid+ }),+ verifyLegacyBtBinding: vi.fn(async () => binding),+ pauseTask: vi.fn(async () => {+ if (engine) engine.status = TaskStatus.Paused+ }),+ resumeTask: vi.fn(async () => {+ const pair = f.db.getTask(f.taskId)+ expect(pair?.instances[0].payload.legacyImport).toMatchObject({+ activation: 'active',+ storagePolicy: 'legacy-bt-in-place',+ })+ expect(pair?.instances[0].payload.legacyBtActivation).toMatchObject({+ stage: 'bound',+ })+ if (engine) engine.status = TaskStatus.Downloading+ }),+ } as unknown as EngineAdapter+ f = await legacyBtActivationFixture(adapter)+ cleanup.push(f.dispose)+ return {+ ...f,+ adapter,+ loseImport: () => {+ loseImport = true+ },+ loseAdd: () => {+ loseAdd = true+ },+ badProof: () => {+ binding = false+ },+ consume: () => {+ if (receipt) receipt.status = 'consumed'+ engine = null+ },+ disappear: () => {+ engine = null+ },+ recover: async () => {+ const s = new LegacyBtActivationService(f.deps)+ await s.recover()+ return s+ },+ }+}++describe('durable BT legacy activation', () => {+ it('binds exact original layout/selection before unpause and backs up actual control bytes', async () => {+ const f = await fixture()+ const original = await readFile(+ path.join(f.downloads, 'fixture-bundle/first.bin')+ )+ expect(await f.service.activate(f.taskId, async () => f.downloads)).toBe(+ true+ )+ const pair = f.db.getTask(f.taskId)+ const intent = legacyBtActivationSchema.parse(+ pair?.instances[0].payload.legacyBtActivation+ )+ expect(intent.stage).toBe('active')+ expect(intent.files).toHaveLength(2)+ expect(intent.selectedFiles).toEqual([0])+ expect(await readFile(intent.controlBackupPath)).toEqual(+ await readFile(path.join(f.downloads, 'fixture-bundle.aria2'))+ )+ expect(+ await readFile(path.join(f.downloads, 'fixture-bundle/first.bin'))+ ).toEqual(original)+ expect(isLegacyImportInactive(f.taskManager.getById(f.taskId)!)).toBe(false)+ expect(f.adapter.addTorrent).toHaveBeenCalledTimes(1)+ })+ it('reconciles a lost checkpoint import response without duplicating the mutation', async () => {+ const f = await fixture()+ f.loseImport()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost import response')+ await f.recover()+ expect(f.adapter.importLegacyCheckpoint).toHaveBeenCalledTimes(1)+ expect(f.adapter.addTorrent).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ ).toMatchObject({ stage: 'bound' })+ })+ it('reconciles a lost add response with the reserved GID and keeps restart paused', async () => {+ const f = await fixture()+ f.loseAdd()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Lost add response')+ await f.recover()+ expect(f.adapter.addTorrent).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(isLegacyImportInactive(f.taskManager.getById(f.taskId)!)).toBe(false)+ })+ it('never recreates consumed or unknown absent engine state', async () => {+ const f = await fixture()+ f.loseAdd()+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow()+ f.consume()+ await f.recover()+ expect(f.adapter.addTorrent).toHaveBeenCalledTimes(1)+ expect(f.adapter.resumeTask).not.toHaveBeenCalled()+ expect(isLegacyImportInactive(f.taskManager.getById(f.taskId)!)).toBe(true)+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('activationUncertain')+ })+ it('keeps a failed binding protected and never unpauses it', async () => {+ const f = await fixture()+ f.badProof()+ 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)!)).toBe(true)+ })+ it('refuses unsupported engine, relocation, missing unselected file, and cancel without side effects', 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(path.join(f.downloads, 'fixture-bundle/second.bin'))+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('payloadMissing')+ vi.mocked(f.adapter.supportsLegacyBtActivation!).mockResolvedValue(false)+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('checkpointUnavailable')+ expect(f.adapter.importLegacyCheckpoint).not.toHaveBeenCalled()+ expect(f.adapter.addTorrent).not.toHaveBeenCalled()+ })+ it('rejects a source save during directory picker and concurrent double clicks', async () => {+ const f = await fixture()+ let release: (path: string) => void = () => {}+ const pending = f.service.activate(+ f.taskId,+ () =>+ new Promise((resolve) => {+ release = resolve+ })+ )+ await vi.waitFor(() =>+ expect(f.adapter.supportsLegacyBtActivation).toHaveBeenCalled()+ )+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('busy')+ await writeFile(path.join(f.profile, 'download.session'), '# changed\n')+ release(f.downloads)+ await expect(pending).rejects.toThrow('changedSource')+ expect(f.adapter.addTorrent).not.toHaveBeenCalled()+ })+ it('releases a pending picker on shutdown', async () => {+ const f = await fixture()+ const pending = f.service.activate(f.taskId, () => new Promise(() => {}))+ await vi.waitFor(() =>+ expect(f.adapter.supportsLegacyBtActivation).toHaveBeenCalled()+ )+ await f.service.drain()+ expect(await pending).toBe(false)+ expect(f.adapter.addTorrent).not.toHaveBeenCalled()+ })+})diff --git a/src/core/legacy-import/bt-activation-service.ts b/src/core/legacy-import/bt-activation-service.tsnew file mode 100644index 00000000..6a038a30--- /dev/null+++ b/src/core/legacy-import/bt-activation-service.ts@@ -0,0 +1,637 @@+import { createHash, randomUUID } from 'node:crypto'+import { 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 { parseBtFileLayout } from '@core/task/bt-storage-layout'+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 {+ type LegacyBtActivation,+ legacyBtActivationSchema,+} from '@shared/schemas/legacy-bt-activation'+import type { LegacyCheckpointFile } from '@shared/schemas/legacy-checkpoint'+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'+import { TaskStatus, TaskType } from '@shared/types/task'+import parseTorrent from 'parse-torrent'+import { authorizeLegacySource, readLegacyFile } from './source-scanner'++export interface LegacyBtActivationDeps {+ 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>+}+const sha256 = (bytes: Uint8Array) =>+ createHash('sha256').update(bytes).digest('hex')+const failure = (key: string) =>+ new AppError(ErrorCode.InvalidSelection, `legacyImport.errors.${key}`)++/** Explicit in-place BT authorization. Unknown mutations retain their durable identity. */+export class LegacyBtActivationService {+ private admission: Promise<unknown> | null = null+ private stopping = false+ private cancelPicker: (() => void) | null = null+ constructor(private readonly deps: LegacyBtActivationDeps) {}++ 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.Bt ||+ !pair.task.torrentMetaPath+ )+ reason = 'metadataRequired'+ else if (!marker.data.selectionKnown || !marker.data.selectedFiles.length)+ reason = 'selectionRequired'+ else if (!marker.data.origin?.torrentDigest)+ reason = 'activationSourceMissing'+ else if (!(await this.deps.adapter.supportsLegacyBtActivation?.()))+ reason = 'checkpointUnavailable'+ 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'))+ const operation = this.deps.runTaskMutation([taskId], async () => {+ const pair = this.requireTask(taskId)+ const previous = pair.instances[0].payload.legacyBtActivation+ if (previous !== undefined) {+ await this.reconcile(pair, true)+ return true+ }+ const available = await this.availability(taskId)+ if (!available.available)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ available.reason ?? 'legacyImport.errors.failed'+ )+ if (this.stopping) 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) return false+ // Resolve the current row after the picker; no stale task grants survive removal/change.+ if (JSON.stringify(this.requireTask(taskId)) !== JSON.stringify(pair))+ throw failure('changedSource')+ const intent = await this.prepare(pair, picked)+ this.deps.taskManager.reserveEngineTaskId(intent.engineTaskId)+ await this.persist(pair, intent, false)+ await this.reconcile(this.requireTask(taskId), true)+ return true+ })+ this.admission = operation+ void operation+ .finally(() => {+ this.admission = null+ this.cancelPicker = null+ })+ .catch(() => {})+ return operation+ }++ /** Runs before ordinary restore. Recovery may bind an exact paused GID, but never unpauses. */+ async recover(): Promise<void> {+ for (const pair of this.deps.db.getAllTasks()) {+ if (+ !Object.hasOwn(pair.instances[0]?.payload ?? {}, 'legacyBtActivation')+ )+ continue+ if (pair.task.aggStatus === TaskStatus.Completed) continue+ try {+ await this.deps.runTaskMutation([pair.task.motrixId], () =>+ this.reconcile(pair, false)+ )+ } catch {+ // A failed proof must remove ordinary resume/adoption authorization.+ const intent = legacyBtActivationSchema.safeParse(+ pair.instances[0].payload.legacyBtActivation+ )+ if (intent.success) await this.persist(pair, intent.data, false)+ }+ }+ }++ async drain(): Promise<void> {+ this.stopping = true+ this.cancelPicker?.()+ await this.admission?.catch(() => {})+ }++ private requireTask(taskId: string): TaskWithInstances {+ const pair = this.deps.db.getTask(taskId)+ const marker = legacyTaskMetadataSchema.safeParse(+ pair?.instances[0]?.payload.legacyImport+ )+ if (+ !pair ||+ !marker.success ||+ pair.instances.length !== 1 ||+ pair.task.taskType !== TaskType.Bt ||+ !pair.task.torrentMetaPath+ )+ throw failure('activationSourceMissing')+ return pair+ }++ private async metadata(pair: TaskWithInstances): Promise<Buffer> {+ const marker = legacyTaskMetadataSchema.parse(+ pair.instances[0].payload.legacyImport+ )+ const file = await this.backupFile(pair.task.torrentMetaPath ?? '')+ if (file.digest !== marker.origin?.torrentDigest)+ throw failure('changedSource')+ return file.bytes+ }++ 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 sourceStillClosed(pair: TaskWithInstances): Promise<void> {+ 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')+ for (const file of origin.profileFiles) {+ if (+ !['download.session', 'system.json', 'user.json'].includes(+ file.relativePath+ )+ )+ throw failure('changedSource')+ if (+ (await readLegacyFile(source, file.relativePath))?.digest !==+ file.digest+ )+ 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')+ }+ }++ private async prepare(+ pair: TaskWithInstances,+ picked: string+ ): Promise<LegacyBtActivation> {+ await this.sourceStillClosed(pair)+ const marker = legacyTaskMetadataSchema.parse(+ pair.instances[0].payload.legacyImport+ )+ const metadata = await this.metadata(pair)+ const layout = await parseBtFileLayout(metadata)+ const torrent = await parseTorrent(metadata)+ if (+ layout.infoHash !== pair.task.infoHash ||+ layout.torrentRootName !== pair.task.finalName ||+ layout.isPrivate !== pair.task.isPrivate+ )+ throw failure('changedSource')+ if (+ !marker.selectionKnown ||+ !marker.selectedFiles.length ||+ new Set(marker.selectedFiles).size !== marker.selectedFiles.length ||+ marker.selectedFiles.some((index) => index >= layout.files.length)+ )+ throw failure('selectionRequired')+ const saveDir = await realpath(picked)+ // The picker authorizes precisely the original parent; relocation/remapping is unsupported.+ if (+ saveDir !== pair.task.saveDir ||+ path.join(saveDir, layout.torrentRootName) !== pair.task.finalPath+ )+ throw failure('originalDirectoryRequired')+ const root = await this.safeStat(saveDir, true)+ await this.noConflicts(pair)+ let offset = 0+ const inodes = new Set<string>()+ const files: LegacyCheckpointFile[] = []+ for (const [index, file] of (torrent.files ?? []).entries()) {+ const filename = path.join(saveDir, file.path)+ if (+ !filename.startsWith(`${saveDir}${path.sep}`) ||+ (layout.multiFile &&+ !filename.startsWith(`${pair.task.finalPath}${path.sep}`))+ )+ throw failure('unsafePath')+ const stat = await this.safeStat(filename, false).catch((error) => {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')+ throw failure('payloadMissing')+ throw error+ })+ const identity = `${stat.dev}:${stat.ino}`+ if (inodes.has(identity)) throw failure('unsafePath')+ inodes.add(identity)+ if (+ !Number.isSafeInteger(file.length) ||+ file.length < 0 ||+ !layout.files[index]+ )+ throw failure('changedSource')+ files.push({+ path: filename,+ offset,+ length: file.length,+ identity: {+ device: String(stat.dev),+ inode: String(stat.ino),+ size: String(stat.size),+ mtimeNs: String(stat.mtimeNs),+ ctimeNs: String(stat.ctimeNs),+ },+ })+ offset += file.length+ }+ const control = await readLegacyFile(+ await authorizeLegacySource(saveDir),+ `${layout.torrentRootName}.aria2`,+ true+ )+ if (!control) throw failure('controlRequired')+ const inspection = await this.deps.adapter.inspectLegacyCheckpoint?.(+ new Uint8Array(control.bytes)+ )+ if (!inspection) throw failure('checkpointUnavailable')+ if (+ inspection.type !== 'bt' ||+ inspection.infoHash !== layout.infoHash ||+ inspection.totalBytes !== offset ||+ inspection.pieceBytes !== torrent.pieceLength+ )+ throw failure('changedSource')+ const controlBackupPath = await this.saveControl(control.bytes)+ await this.sourceStillClosed(pair)+ const controlAgain = await readLegacyFile(+ await authorizeLegacySource(saveDir),+ `${layout.torrentRootName}.aria2`+ )+ if (+ controlAgain?.digest !== control.digest ||+ controlAgain.identity !== control.identity+ )+ throw failure('changedSource')+ return legacyBtActivationSchema.parse({+ version: 1,+ stage: 'import-uncertain',+ token: `bt_${randomUUID().replaceAll('-', '_')}`,+ engineTaskId: newEngineTaskId(undefined, 'legacy BT activation'),+ targetPath: pair.task.finalPath,+ saveDir,+ rootIdentity: `${root.dev}:${root.ino}`,+ controlBackupPath,+ controlDigest: inspection.sourceDigest,+ torrentDigest: sha256(metadata),+ expected: {+ type: 'bt',+ totalBytes: inspection.totalBytes,+ pieceBytes: inspection.pieceBytes,+ infoHash: layout.infoHash,+ },+ files,+ selectedFiles: marker.selectedFiles,+ trackers: pair.task.trackers.flat(),+ isPrivate: layout.isPrivate,+ })+ }++ 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 ||+ (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)+ for (const other of this.deps.db.getAllTasks()) {+ if (other.task.motrixId === pair.task.motrixId) continue+ const claimed = [+ other.task.finalPath,+ ...other.instances.map((instance) => instance.diskPath),+ ].filter(Boolean)+ if (+ other.task.infoHash === pair.task.infoHash ||+ claimed.some((value) => {+ const identity = outputPathIdentity(value)+ return (+ target === identity ||+ target.startsWith(`${identity}${path.sep}`) ||+ identity.startsWith(`${target}${path.sep}`)+ )+ })+ )+ throw failure('pathConflict')+ }+ const owned = legacyBtActivationSchema.safeParse(+ pair.instances[0].payload.legacyBtActivation+ )+ const rows = [+ ...(await this.deps.adapter.listActiveAndWaiting()),+ ...(await this.deps.adapter.listStopped()),+ ]+ if (+ rows.some(+ (row) =>+ row.infoHash?.toLowerCase() === pair.task.infoHash &&+ row.gid !== (owned.success ? owned.data.engineTaskId : null)+ )+ )+ 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,+ 0o600+ )+ try {+ await file.writeFile(bytes)+ await file.sync()+ } finally {+ await file.close()+ }+ for (const name of [directory, source.root]) {+ const handle = await open(name, constants.O_RDONLY | constants.O_NOFOLLOW)+ try {+ await handle.sync()+ } finally {+ await handle.close()+ }+ }+ return filename+ }++ private async persist(+ pair: TaskWithInstances,+ intent: LegacyBtActivation,+ bound: boolean+ ): Promise<TaskWithInstances> {+ const next = structuredClone(pair)+ const marker = legacyTaskMetadataSchema.parse(+ next.instances[0].payload.legacyImport+ )+ next.instances[0].payload = {+ ...next.instances[0].payload,+ legacyBtActivation: intent,+ legacyImport: {+ ...marker,+ activation: bound ? 'active' : 'activating',+ storagePolicy: 'legacy-bt-in-place',+ },+ }+ if (bound) {+ next.instances[0].gid = intent.engineTaskId+ next.instances[0].diskPath = intent.targetPath+ next.task.saveDir = intent.saveDir+ }+ next.task.updatedAt = next.instances[0].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+ ): Promise<void> {+ const intent = legacyBtActivationSchema.parse(+ pair.instances[0].payload.legacyBtActivation+ )+ if (!(await this.deps.adapter.supportsLegacyBtActivation?.()))+ throw failure('checkpointUnavailable')+ if (+ pair.task.finalPath !== intent.targetPath ||+ pair.task.saveDir !== intent.saveDir ||+ pair.task.infoHash !== intent.expected.infoHash ||+ pair.task.isPrivate !== intent.isPrivate+ )+ throw failure('changedSource')+ const metadata = await this.metadata(pair)+ if (sha256(metadata) !== intent.torrentDigest)+ 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) {+ // Never trust consumed alone: the durable add phase and full live identity must agree.+ if (+ !['create-uncertain', 'bound', 'active'].includes(intent.stage) ||+ receipt.status === 'absent'+ )+ throw failure('activationUncertain')+ if (+ !engine ||+ engine.infoHash?.toLowerCase() !== intent.expected.infoHash ||+ engine.engineTaskId !== intent.engineTaskId+ )+ throw failure('activationUncertain')+ if (+ !(await this.deps.adapter.verifyLegacyBtBinding?.({+ engineTaskId: intent.engineTaskId,+ saveDir: intent.saveDir,+ infoHash: intent.expected.infoHash ?? '',+ files: intent.files,+ selectedFiles: intent.selectedFiles,+ trackers: intent.trackers,+ isPrivate: intent.isPrivate,+ }))+ )+ throw failure('activationUncertain')+ if (+ intent.stage === 'create-uncertain' &&+ engine.status !== TaskStatus.Paused+ ) {+ await this.deps.adapter.pauseTask(intent.engineTaskId)+ engine = await this.deps.adapter.getTaskStatus(intent.engineTaskId)+ }+ if (!engine) throw failure('activationUncertain')+ if (+ intent.stage !== 'active' ||+ (resume && engine.status === TaskStatus.Paused)+ ) {+ await this.sourceStillClosed(pair)+ await this.noConflicts(pair)+ }+ if (intent.stage !== 'active') {+ intent.stage = 'bound'+ pair = await this.persist(pair, intent, true)+ }+ if (resume && engine.status === TaskStatus.Paused && !this.stopping) {+ // Binding is durable before this side effect. Ordinary resume can now safely address only this GID.+ await this.deps.adapter.resumeTask(intent.engineTaskId)+ intent.stage = 'active'+ await this.persist(pair, intent, true)+ }+ return+ }+ if (+ receipt.status === 'consumed' ||+ ['create-uncertain', 'bound', 'active'].includes(intent.stage)+ )+ throw failure('activationUncertain')+ if (this.stopping) return+ await this.sourceStillClosed(pair)+ await this.noConflicts(pair)+ const root = await this.safeStat(intent.saveDir, true)+ if (`${root.dev}:${root.ino}` !== intent.rootIdentity)+ throw failure('changedSource')+ for (const file of intent.files) {+ const stat = await this.safeStat(file.path, false)+ const identity = file.identity+ if (+ String(stat.dev) !== identity.device ||+ String(stat.ino) !== identity.inode ||+ String(stat.size) !== identity.size ||+ String(stat.mtimeNs) !== identity.mtimeNs ||+ String(stat.ctimeNs) !== identity.ctimeNs+ )+ throw failure('changedSource')+ }+ if (receipt.status === 'absent') {+ if (intent.stage !== 'import-uncertain')+ throw failure('activationUncertain')+ const control = await this.backupFile(intent.controlBackupPath)+ if (control.digest !== intent.controlDigest)+ throw failure('changedSource')+ 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)+ if (this.stopping) return+ await this.sourceStillClosed(pair)+ // Save before dispatch: an unknown response cannot lead to a blind second add.+ intent.stage = 'create-uncertain'+ pair = await this.persist(pair, intent, false)+ 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.addTorrent({+ metadata,+ saveDir: intent.saveDir,+ gid: intent.engineTaskId,+ selectedFiles: intent.selectedFiles.map((index) => index + 1),+ pause: true,+ checkIntegrity: true,+ btSeedUnverified: false,+ isPrivate: intent.isPrivate,+ legacyCheckpointActivation: {+ token: intent.token,+ targetPath: intent.targetPath,+ },+ durableMetadata: {+ path: pair.task.torrentMetaPath ?? '',+ digest: intent.torrentDigest,+ },+ extraEngineOptions: { 'bt-tracker': intent.trackers.join(',') },+ })+ if (gid !== intent.engineTaskId) throw failure('activationUncertain')+ await this.reconcile(pair, resume)+ }+}diff --git a/src/core/legacy-import/bt-activation.integration.test.ts b/src/core/legacy-import/bt-activation.integration.test.tsnew file mode 100644index 00000000..d08b3051--- /dev/null+++ b/src/core/legacy-import/bt-activation.integration.test.ts@@ -0,0 +1,339 @@+// @vitest-environment node+import { readFile, writeFile } from 'node:fs/promises'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { EventBus } from '@core/events/event-bus'+import { getLogger } from '@core/logger'+import { SessionManager } from '@core/session/session-manager'+import { finalizeTask } from '@core/task/actions/finalize-task'+import { pauseTask } from '@core/task/actions/pause-task'+import { removeTask } from '@core/task/actions/remove-task'+import { resumeTask } from '@core/task/actions/resume-task'+import { mergeEngineTask } from '@core/task/merge-engine-task'+import { TorrentMetaStoreImpl } from '@core/task/torrent-meta-store'+import type { MagnetTracker } from '@core/torrent/magnet-tracker'+import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'+import { TaskStatus } from '@shared/types/task'+import {+ type Aria2Handle,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { legacyBtActivationFixture } from '@test-utils/legacy-bt-activation-fixture'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LegacyBtActivationService } from './bt-activation-service'++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() {+ // The importer is offline; the adapter is installed before any activation call.+ const f = await legacyBtActivationFixture({} as EngineAdapter)+ cleanup.push(f.dispose)+ let handle: Aria2Handle | undefined+ let wired: Awaited<ReturnType<typeof connectAdapter>> | undefined+ const start = async () => {+ handle = await spawnAria2ForTest({+ baseDir: f.root,+ binaryPath,+ extraArgs: [+ '--enable-sqlite3-persistence=true',+ '--force-save=true',+ `--sqlite3-db-path=${path.join(f.root, 'engine.db')}`,+ '--enable-dht=false',+ '--enable-dht6=false',+ '--enable-peer-exchange=false',+ '--bt-enable-lpd=false',+ '--seed-time=20',+ '--seed-ratio=20',+ '--bt-seed-unverified=true',+ '--bt-remove-unselected-file=true',+ '--file-allocation=none',+ ],+ })+ wired = await connectAdapter(handle)+ f.deps.adapter = wired.adapter+ return wired+ }+ const stop = async () => {+ wired?.disconnect()+ wired = undefined+ await handle?.kill()+ handle = undefined+ }+ cleanup.push(stop)+ return { ...f, start, stop }+}+async function completed(adapter: EngineAdapter, gid: string) {+ const deadline = Date.now() + 20000+ 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('BT verification timed out')+}++function actionsFor(+ f: Awaited<ReturnType<typeof nativeFixture>>,+ wired: Awaited<ReturnType<typeof connectAdapter>>+) {+ const session = new SessionManager(+ f.taskManager,+ wired.rpc,+ f.db,+ wired.adapter+ )+ cleanup.push(() => session.stopAndDrain())+ const deps = {+ taskManager: f.taskManager,+ adapter: wired.adapter,+ eventBus: new EventBus(),+ log: getLogger('legacy-bt-native-test'),+ publishTaskUpdate: vi.fn(),+ publishTaskUpdateNow: vi.fn(),+ persistTask: session.persistTask.bind(session),+ persistTaskWithOccurrence: session.persistTaskWithOccurrence.bind(session),+ occurrenceDispatcher: { dispatch: vi.fn(async () => {}) },+ runTaskMutation: f.deps.runTaskMutation,+ }+ const cleanupFiles = vi.fn(async () => {+ throw new Error('Legacy payload cleanup must not run')+ })+ const finalizeDeps = {+ ...deps,+ taskManager: Object.assign(f.taskManager, { persist: deps.persistTask }),+ fs: { renameAtomic: cleanupFiles, removePathRecursive: cleanupFiles },+ torrentMetaStore: new TorrentMetaStoreImpl(+ path.join(f.root, 'unused-metadata')+ ),+ settings: { get: () => ({ bt: { seedTime: 20, seedRatio: 20 } }) },+ activityRecorder: {+ recordSubmitted: vi.fn(),+ recordDownloadCompleted: vi.fn(),+ },+ }+ const removeDeps = {+ ...deps,+ db: f.db,+ taskPersistence: session,+ fileCleanupService: { cleanup: cleanupFiles },+ torrentMetaStore: finalizeDeps.torrentMetaStore,+ magnetTracker: {+ cancel: vi.fn(),+ markPendingUserDelete: vi.fn(),+ } as unknown as MagnetTracker,+ }+ return { deps, finalizeDeps, removeDeps, cleanupFiles, session }+}++describe.skipIf(!binaryPath)(+ 'real native application BT legacy activation',+ () => {+ it('verifies real v1 pieces with exact original selection, consumes once, and never auto-seeds', async () => {+ const f = await nativeFixture()+ const wired = await f.start()+ const { adapter, rpc } = wired+ const before = await readFile(+ path.join(f.downloads, 'fixture-bundle/second.bin')+ )+ await f.service.activate(f.taskId, async () => f.downloads)+ const intent = legacyBtActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ )+ const task = await completed(adapter, intent.engineTaskId)+ expect(task.status).toBe(TaskStatus.Completed)+ expect(task.downloadedBytes).toBeGreaterThan(0)+ expect(await rpc.tellActive()).toEqual([])+ expect(await adapter.getTaskFiles(intent.engineTaskId)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ index: 0, selected: true }),+ expect.objectContaining({ index: 1, selected: false }),+ ])+ )+ expect(+ await readFile(path.join(f.downloads, 'fixture-bundle/second.bin'))+ ).toEqual(before)+ expect(+ await adapter.reconcileLegacyCheckpoint({+ token: intent.token,+ targetPath: intent.targetPath,+ })+ ).toMatchObject({ status: 'consumed' })+ const rows = [+ ...(await adapter.listActiveAndWaiting()),+ ...(await adapter.listStopped()),+ ]+ expect(+ new Set(+ rows+ .filter((row) => row.infoHash === intent.expected.infoHash)+ .map((row) => row.gid)+ )+ ).toEqual(new Set([intent.engineTaskId]))+ const actions = actionsFor(f, wired)+ await finalizeTask(f.taskId, actions.finalizeDeps)+ expect(f.db.getTask(f.taskId)?.task.aggStatus).toBe(TaskStatus.Completed)+ expect(f.db.listUndispatchedOccurrences()).toEqual([+ expect.objectContaining({+ taskId: f.taskId,+ toStatus: TaskStatus.Completed,+ }),+ ])+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyImport+ ).toMatchObject({+ activation: 'active',+ storagePolicy: 'legacy-bt-in-place',+ })+ await f.stop()+ f.taskManager.clear()+ const restarted = await f.start()+ const recovery = new LegacyBtActivationService(f.deps)+ await recovery.recover()+ const replay = await restarted.adapter.getTaskStatus(intent.engineTaskId)+ expect(replay?.status).toBe(TaskStatus.Paused)+ const restored = actionsFor(f, restarted)+ await restored.session.restore()+ const history = f.taskManager.getById(f.taskId)+ expect(history?.status).toBe(TaskStatus.Completed)+ expect(f.db.getTask(f.taskId)?.task.aggStatus).toBe(TaskStatus.Completed)+ if (!history || !replay)+ throw new Error('Missing completed replay fixture')+ expect(mergeEngineTask(history, replay)).toBe(history)+ expect(+ await restarted.adapter.getTaskStatus(intent.engineTaskId)+ ).toMatchObject({ status: TaskStatus.Paused })+ await removeTask(f.taskId, { deleteWithFiles: true }, restored.removeDeps)+ await recovery.drain()+ expect(f.db.getTask(f.taskId)).toBeNull()+ expect(+ await readFile(path.join(f.downloads, 'fixture-bundle/first.bin'))+ ).toEqual(Buffer.alloc(16384, 1))+ expect(+ await readFile(path.join(f.downloads, 'fixture-bundle/second.bin'))+ ).toEqual(before)+ expect(actions.cleanupFiles).not.toHaveBeenCalled()+ expect(restored.cleanupFiles).not.toHaveBeenCalled()+ }, 30000)+ it('recovers a real lost paused add response after engine restart without recreating or unpausing', async () => {+ const f = await nativeFixture()+ const { adapter } = await f.start()+ const add = adapter.addTorrent.bind(adapter)+ adapter.addTorrent = async (input) => {+ await add(input)+ throw new Error('Simulated lost response')+ }+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Simulated lost response')+ const intent = legacyBtActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ )+ await f.stop()+ f.taskManager.clear()+ const resumed = await f.start()+ const service = new LegacyBtActivationService(f.deps)+ const proof = await resumed.adapter.verifyLegacyBtBinding({+ engineTaskId: intent.engineTaskId,+ saveDir: intent.saveDir,+ infoHash: intent.expected.infoHash ?? '',+ files: intent.files,+ selectedFiles: intent.selectedFiles,+ trackers: intent.trackers,+ isPrivate: intent.isPrivate,+ })+ expect(proof).toBe(true)+ await service.recover()+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ ).toMatchObject({ stage: 'bound' })+ expect(+ (await resumed.adapter.getTaskStatus(intent.engineTaskId))?.status+ ).toBe(TaskStatus.Paused)+ expect(+ (await resumed.adapter.listActiveAndWaiting()).filter(+ (row) => row.infoHash === intent.expected.infoHash+ )+ ).toHaveLength(1)+ await service.drain()+ }, 30000)+ it('reconciles a lost checkpoint response after restart without importing twice or starting work', async () => {+ const f = await nativeFixture()+ const { adapter } = await f.start()+ const importCheckpoint = adapter.importLegacyCheckpoint.bind(adapter)+ adapter.importLegacyCheckpoint = async (input) => {+ await importCheckpoint(input)+ throw new Error('Simulated lost checkpoint response')+ }+ await expect(+ f.service.activate(f.taskId, async () => f.downloads)+ ).rejects.toThrow('Simulated lost checkpoint response')+ const intent = legacyBtActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ )+ expect(intent.stage).toBe('import-uncertain')+ expect(await adapter.getTaskStatus(intent.engineTaskId)).toBeNull()+ await f.stop()+ f.taskManager.clear()+ const resumed = await f.start()+ const repeatedImport = vi.spyOn(resumed.adapter, 'importLegacyCheckpoint')+ const service = new LegacyBtActivationService(f.deps)+ await service.recover()+ expect(repeatedImport).not.toHaveBeenCalled()+ expect(+ (await resumed.adapter.getTaskStatus(intent.engineTaskId))?.status+ ).toBe(TaskStatus.Paused)+ expect(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ ).toMatchObject({ stage: 'bound', engineTaskId: intent.engineTaskId })+ expect(+ (await resumed.adapter.listActiveAndWaiting()).filter(+ (row) => row.infoHash === intent.expected.infoHash+ )+ ).toHaveLength(1)+ await service.drain()+ }, 30000)+ it('allows bound pause/resume and keeps every original payload on delete-with-files', async () => {+ const f = await nativeFixture()+ const incomplete = Buffer.alloc(16384, 0)+ await writeFile(+ path.join(f.downloads, 'fixture-bundle/first.bin'),+ incomplete+ )+ const wired = await f.start()+ await f.service.activate(f.taskId, async () => f.downloads)+ const intent = legacyBtActivationSchema.parse(+ f.db.getTask(f.taskId)?.instances[0].payload.legacyBtActivation+ )+ const actions = actionsFor(f, wired)+ await pauseTask(f.taskId, actions.deps)+ expect(+ (await wired.adapter.getTaskStatus(intent.engineTaskId))?.status+ ).toBe(TaskStatus.Paused)+ await resumeTask(f.taskId, actions.deps)+ expect(+ (await wired.adapter.getTaskStatus(intent.engineTaskId))?.status+ ).not.toBe(TaskStatus.Paused)+ await removeTask(f.taskId, { deleteWithFiles: true }, actions.removeDeps)+ expect(await wired.adapter.getTaskStatus(intent.engineTaskId)).toBeNull()+ expect(f.db.getTask(f.taskId)).toBeNull()+ expect(f.taskManager.isEngineTaskIdRetired(intent.engineTaskId)).toBe(+ true+ )+ expect(+ await readFile(path.join(f.downloads, 'fixture-bundle/first.bin'))+ ).toEqual(incomplete)+ expect(+ await readFile(path.join(f.downloads, 'fixture-bundle/second.bin'))+ ).toEqual(Buffer.alloc(16384, 2))+ expect(actions.cleanupFiles).not.toHaveBeenCalled()+ }, 30000)+ }+)diff --git a/src/core/legacy-import/import-service-adversarial.test.ts b/src/core/legacy-import/import-service-adversarial.test.tsnew file mode 100644index 00000000..378e6291--- /dev/null+++ b/src/core/legacy-import/import-service-adversarial.test.ts@@ -0,0 +1,432 @@+// @vitest-environment node+import {+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ realpath,+ rm,+ stat,+ symlink,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { MotrixDatabase } from '@core/session/motrix-database'+import { TaskManager } from '@core/task/task-manager'+import { TaskStatus } from '@shared/types/task'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ LegacyImportService,+ type LegacyImportServiceDeps,+} from './import-service'++const cleanups: Array<() => Promise<void>> = []++async function fixture(+ count = 1,+ overrides: Partial<LegacyImportServiceDeps> = {}+) {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'legacy-import-service-'))+ )+ const sourceRoot = path.join(root, 'legacy')+ await mkdir(sourceRoot)+ const downloads = path.join(root, 'downloads')+ await mkdir(downloads)+ await writeFile(path.join(downloads, 'file-0.zip'), 'original payload')+ await writeFile(+ path.join(sourceRoot, 'user.json'),+ JSON.stringify({ theme: 'auto' })+ )+ await writeFile(+ path.join(sourceRoot, 'system.json'),+ JSON.stringify({ dir: downloads })+ )+ const sessionPath = path.join(sourceRoot, 'download.session')+ await writeFile(+ sessionPath,+ Array.from(+ { length: count },+ (_, i) =>+ `https://example.test/file-${i}.zip\t\n gid=${(i + 1).toString(16).padStart(16, '0')}\n out=file-${i}.zip\n`+ ).join('')+ )+ const db = new MotrixDatabase(path.join(root, 'motrix.db'))+ db.init()+ const taskManager = new TaskManager()+ const deps: LegacyImportServiceDeps = {+ db,+ taskManager,+ backupRoot: path.join(root, 'backups'),+ isProcessRunning: () => false,+ publishTasks: vi.fn(),+ ...overrides,+ }+ const service = new LegacyImportService(deps)+ cleanups.push(async () => {+ await service.drain()+ db.close()+ await rm(root, { recursive: true, force: true })+ })+ const source = await service.addSource(sourceRoot)+ const preview = await service.scan(source.sourceHandle)+ const request = {+ previewId: preview.previewId,+ itemIds: preview.items+ .filter((item) => item.selectable)+ .map((item) => item.itemId),+ }+ return {+ root,+ sourceRoot,+ downloads,+ sessionPath,+ db,+ taskManager,+ service,+ source,+ preview,+ request,+ deps,+ }+}++async function completed(service: LegacyImportService, runId: string) {+ await expect+ .poll(() => service.getRun(runId).stage)+ .toMatch(/^(completed|failed|cancelled)$/)+ return service.getRun(runId)+}++afterEach(async () => {+ for (const cleanup of cleanups.splice(0)) await cleanup()+ vi.restoreAllMocks()+})++describe('legacy import service adversarial acceptance', () => {+ it('returns the authorized data path for discovered and reused sources', async () => {+ const f = await fixture()+ expect(f.source.dataPath).toBe(f.sourceRoot)+ expect(f.service.getSourcePath(f.source.sourceHandle)).toBe(f.sourceRoot)+ expect(() => f.service.getSourcePath('unknown')).toThrow(+ 'sourceNotAuthorized'+ )+ expect(await f.service.addSource(f.sourceRoot)).toEqual(f.source)+ expect(await f.service.discover([f.sourceRoot])).toEqual([f.source])+ })++ it('discovers and reauthorizes a large malformed session without parsing tasks or checking a PID', async () => {+ const running = vi.fn(() => false)+ const f = await fixture(1, { isProcessRunning: running })+ await writeFile(f.sessionPath, Buffer.alloc(4 * 1024 * 1024))+ await writeFile(path.join(f.sourceRoot, 'engine.pid'), '123')+ running.mockClear()+ expect(await f.service.discover([f.sourceRoot])).toEqual([f.source])+ expect(await f.service.addSource(f.sourceRoot)).toEqual(f.source)+ expect(running).not.toHaveBeenCalled()+ await expect(f.service.scan(f.source.sourceHandle)).rejects.toThrow(+ 'legacyImport.invalidSource'+ )+ expect(running).toHaveBeenCalledWith(123)+ })++ it('does not discover or authorize a missing or symlinked profile file', async () => {+ const f = await fixture()+ const user = path.join(f.sourceRoot, 'user.json')+ await rm(user)+ expect(await f.service.discover([f.sourceRoot])).toEqual([])+ await expect(f.service.addSource(f.sourceRoot)).rejects.toThrow(+ 'legacyImport.invalidSource'+ )+ const outside = path.join(f.root, 'outside-user.json')+ await writeFile(outside, '{"theme":"auto"}')+ await symlink(outside, user)+ expect(await f.service.discover([f.sourceRoot])).toEqual([])+ await expect(f.service.addSource(f.sourceRoot)).rejects.toThrow(+ 'legacyImport.unsafeSource'+ )+ })++ it('shows the original save directories in previews and persisted reports', async () => {+ const f = await fixture(2)+ const other = path.join(f.root, 'other-downloads')+ await writeFile(+ f.sessionPath,+ [+ 'https://example.test/file-0.zip\n out=file-0.zip\n',+ `https://example.test/file-1.zip\n out=file-1.zip\n dir=${other}\n`,+ 'https://example.test/invalid.zip\n out=invalid.zip\n dir=relative-folder\n',+ `${path.join(f.root, 'outside.torrent')}\n`,+ ].join('')+ )+ const preview = await f.service.scan(f.source.sourceHandle)+ expect(preview.items.map((item) => item.saveDir)).toEqual([+ f.downloads,+ other,+ null,+ f.downloads,+ ])+ const run = await f.service.commit({+ previewId: preview.previewId,+ itemIds: preview.items+ .filter((item) => item.selectable)+ .map((item) => item.itemId),+ })+ const report = await completed(f.service, run.runId)+ expect(report.imported).toBe(2)+ expect(report.items.map((item) => item.saveDir)).toEqual([+ f.downloads,+ other,+ null,+ f.downloads,+ ])+ expect(+ f.db+ .getAllTasks()+ .map(({ task }) => task.saveDir)+ .sort()+ ).toEqual([f.downloads, other].sort())+ // Displaying a directory does not probe or create it.+ await expect(stat(other)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('retains committed batches and retries only the failed batch', async () => {+ const f = await fixture(101)+ const save = f.db.saveLegacyImportBatch.bind(f.db)+ let calls = 0+ vi.spyOn(f.db, 'saveLegacyImportBatch').mockImplementation((...args) => {+ if (++calls === 2) throw new Error('injected second batch failure')+ return save(...args)+ })+ const run = await f.service.commit(f.request)+ const first = await completed(f.service, run.runId)+ expect(first.imported).toBe(100)+ expect(+ first.items.filter((item) => item.outcome === 'failed')+ ).toHaveLength(1)+ const retry = await f.service.retry(run.runId)+ const second = await completed(f.service, retry.runId)+ expect(second.imported).toBe(1)+ expect(f.db.getAllTasks()).toHaveLength(101)+ expect(+ new Set(f.db.getAllTasks().map(({ task }) => task.finalPath)).size+ ).toBe(101)+ })++ it('keeps cancellation at a batch boundary and preserves committed items', async () => {+ const f = await fixture(101)+ let runId = ''+ f.deps.publishTasks = () => {+ f.service.cancel(runId)+ }+ const run = await f.service.commit(f.request)+ runId = run.runId+ const report = await completed(f.service, runId)+ expect(report).toMatchObject({+ stage: 'cancelled',+ imported: 100,+ processed: 100,+ })+ expect(f.db.getAllTasks()).toHaveLength(100)+ expect(+ report.items.filter((item) => item.outcome === 'unprocessed')+ ).toHaveLength(1)+ })++ it('does not revive a deleted GID-less entry when v1 rewrites its pause option', async () => {+ const f = await fixture()+ await writeFile(+ f.sessionPath,+ 'https://example.test/file-0.zip\n out=file-0.zip\n pause=true\n'+ )+ const preview = await f.service.scan(f.source.sourceHandle)+ const run = await f.service.commit({+ previewId: preview.previewId,+ itemIds: preview.items.map((item) => item.itemId),+ })+ const report = await completed(f.service, run.runId)+ const id = report.items[0].taskId+ expect(id).toBeTruthy()+ f.db.deleteTask(id as string)+ await writeFile(+ f.sessionPath,+ 'https://example.test/file-0.zip\n out=file-0.zip\n pause=false\n'+ )+ const updated = await f.service.scan(f.source.sourceHandle)+ expect(updated.items[0]).toMatchObject({+ selectable: false,+ reason: 'deleted-import',+ })+ })++ it('rechecks source changes after waiting for the persistence lane', async () => {+ const f = await fixture()+ f.service.setPersistenceLane(async (operation) => {+ await writeFile(+ f.sessionPath,+ 'https://example.test/changed.zip\n out=changed.zip\n'+ )+ return operation()+ })+ const run = await f.service.commit(f.request)+ await completed(f.service, run.runId)+ expect(f.db.getAllTasks()).toHaveLength(0)+ })++ it('commits paused records and private backups without altering payload or source files', async () => {+ const f = await fixture()+ const before = await readFile(f.sessionPath)+ const run = await f.service.commit(f.request)+ 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.engineTaskId).toBe('')+ expect(task.downloadedBytes).toBe(0)+ expect(task.instances.every((instance) => !instance.gid)).toBe(true)+ expect(await readFile(f.sessionPath)).toEqual(before)+ expect(await readFile(path.join(f.downloads, 'file-0.zip'), 'utf8')).toBe(+ 'original payload'+ )+ const backup = path.join(f.deps.backupRoot, run.runId)+ expect(await readFile(path.join(backup, 'download.session'))).toEqual(+ before+ )+ if (process.platform !== 'win32') {+ expect((await stat(backup)).mode & 0o777).toBe(0o700)+ expect(+ (await stat(path.join(backup, 'download.session'))).mode & 0o777+ ).toBe(0o600)+ }+ })++ it('rejects a stale preview before committing records', async () => {+ const f = await fixture()+ await writeFile(+ f.sessionPath,+ 'https://example.test/changed.zip\n out=changed.zip\n'+ )+ await expect(f.service.commit(f.request)).rejects.toThrow()+ expect(f.db.getAllTasks()).toHaveLength(0)+ })++ it('rejects a now-running old engine even if preview observed it stopped', async () => {+ let running = false+ const f = await fixture(1, { isProcessRunning: () => running })+ await writeFile(path.join(f.sourceRoot, 'engine.pid'), '12345')+ const preview = await f.service.scan(f.source.sourceHandle)+ running = true+ await expect(+ f.service.commit({+ previewId: preview.previewId,+ itemIds: preview.items.map((item) => item.itemId),+ })+ ).rejects.toThrow()+ expect(f.db.getAllTasks()).toHaveLength(0)+ })++ it('admits only one of two concurrent commits and persists one record', async () => {+ const f = await fixture()+ const results = await Promise.allSettled([+ f.service.commit(f.request),+ f.service.commit(f.request),+ ])+ const accepted = results.filter((result) => result.status === 'fulfilled')+ expect(accepted).toHaveLength(1)+ if (accepted[0].status === 'fulfilled')+ await completed(f.service, accepted[0].value.runId)+ expect(f.db.getAllTasks()).toHaveLength(1)+ })++ it('keeps the deletion tombstone across importer restarts', async () => {+ const f = await fixture()+ const run = await f.service.commit(f.request)+ const report = await completed(f.service, run.runId)+ const id = report.items[0].taskId+ expect(id).toBeTruthy()+ f.db.deleteTask(id as string)+ const restarted = new LegacyImportService(f.deps)+ const source = await restarted.addSource(f.sourceRoot)+ const preview = await restarted.scan(source.sourceHandle)+ expect(preview.items[0]).toMatchObject({+ selectable: false,+ reason: 'deleted-import',+ })+ })++ it('refuses a backup root symlink and commits no task', async () => {+ const f = await fixture()+ const outside = path.join(f.root, 'outside')+ await mkdir(outside)+ await symlink(outside, f.deps.backupRoot)+ await expect(f.service.commit(f.request)).rejects.toThrow()+ expect(f.db.getAllTasks()).toHaveLength(0)+ expect(await readdir(outside)).toEqual([])+ })++ it('rolls back task graphs and ledger when the import transaction fails', async () => {+ const f = await fixture()+ f.db.database.exec(+ "CREATE TRIGGER reject_import BEFORE INSERT ON legacy_import_ledger BEGIN SELECT RAISE(ABORT, 'injected failure'); END"+ )+ const run = await f.service.commit(f.request)+ const report = await completed(f.service, run.runId)+ expect(report.imported).toBe(0)+ expect(report.items[0].outcome).toBe('failed')+ expect(f.db.getAllTasks()).toHaveLength(0)+ expect(+ f.db.database.prepare('SELECT * FROM legacy_import_ledger').all()+ ).toHaveLength(0)+ })++ it('does not relabel a durable success as failure when UI publication throws', async () => {+ const f = await fixture(1, {+ publishTasks: () => {+ throw new Error('observer failed')+ },+ })+ const run = await f.service.commit(f.request)+ const report = await completed(f.service, run.runId)+ expect(f.db.getAllTasks()).toHaveLength(1)+ expect(report).toMatchObject({ imported: 1, processed: 1 })+ expect(report.items[0].outcome).toBe('imported')+ })++ it('stops further batches if the source changes after the first batch', async () => {+ let f: Awaited<ReturnType<typeof fixture>>+ let batches = 0+ f = await fixture(101, {+ runExclusivePersistence: async (operation) => {+ const result = await operation()+ if (++batches === 1)+ await writeFile(+ f.sessionPath,+ 'https://example.test/changed.zip\n out=changed.zip\n'+ )+ return result+ },+ })+ const run = await f.service.commit(f.request)+ await completed(f.service, run.runId)+ expect(f.db.getAllTasks()).toHaveLength(100)+ })++ it('drains an admitted import before shutdown without committing after drain returns', async () => {+ const f = await fixture()+ let admissionSettled = false+ const committing = f.service+ .commit(f.request)+ .catch(() => null)+ .finally(() => {+ admissionSettled = true+ })+ await f.service.drain()+ expect(admissionSettled).toBe(true)+ const atShutdown = f.db.getAllTasks().length+ const report = await committing+ if (report) await completed(f.service, report.runId)+ expect(f.db.getAllTasks()).toHaveLength(atShutdown)+ expect(atShutdown).toBe(0)+ })+})diff --git a/src/core/legacy-import/import-service.ts b/src/core/legacy-import/import-service.tsnew file mode 100644index 00000000..53edc559--- /dev/null+++ b/src/core/legacy-import/import-service.ts@@ -0,0 +1,878 @@+import { randomUUID } from 'node:crypto'+import { constants } from 'node:fs'+import { chmod, lstat, mkdir, open, realpath } from 'node:fs/promises'+import path from 'node:path'+import type {+ MotrixDatabase,+ TaskWithInstancesAndFiles,+} from '@core/session/motrix-database'+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 {+ type LegacyImportPreview,+ type LegacyImportReport,+ type LegacyImportSource,+ legacyCommitRequestSchema,+ legacyImportReportSchema,+ legacyMetadataRequestSchema,+} from '@shared/schemas/legacy-import'+import {+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import {+ authorizeLegacySource,+ authorizeLegacyTorrent,+ isLegacyTorrentGrantValid,+ type LegacyCandidate,+ type LegacySnapshot,+ type LegacySource,+ type LegacyTorrentGrant,+ probeLegacySource,+ scanLegacySource,+} from './source-scanner'++export interface LegacyImportServiceDeps {+ db: MotrixDatabase+ taskManager: TaskManager+ backupRoot: string+ isProcessRunning: (pid: number) => boolean | Promise<boolean>+ publishTasks: () => void+ runExclusivePersistence?: <T>(operation: () => T | Promise<T>) => Promise<T>+ now?: () => number+}+interface PreviewState {+ dto: LegacyImportPreview+ snapshot: LegacySnapshot+ committedRunId?: string+}+const PREVIEW_TTL = 15 * 60 * 1000+const BATCH_SIZE = 100++export class LegacyImportService {+ private sources = new Map<string, LegacySource>()+ private previews = new Map<string, PreviewState>()+ private cancelled = new Set<string>()+ private activeRun: string | null = null+ private runningJobs = new Map<string, Promise<void>>()+ private admissions = new Set<Promise<LegacyImportReport>>()+ private metadataAdmissions = new Set<Promise<LegacyImportPreview | null>>()+ private metadataGrants = new Map<string, Map<string, LegacyTorrentGrant>>()+ private stopMetadataPicker: (() => void) | null = null+ private draining = false+ private clock: () => number++ constructor(private readonly deps: LegacyImportServiceDeps) {+ this.clock = deps.now ?? Date.now+ for (const row of deps.db.database+ .prepare(+ "SELECT run_id, report FROM legacy_import_runs WHERE json_extract(report, '$.stage') IN ('backing-up', 'committing')"+ )+ .all() as Array<{ run_id: string; report: string }>) {+ const report = legacyImportReportSchema.parse(JSON.parse(row.report))+ if (report.stage === 'committing' || report.stage === 'backing-up') {+ report.stage = 'failed'+ for (const item of report.items) {+ if (item.outcome === 'unprocessed') {+ item.outcome = 'failed'+ item.reason = 'stopped'+ }+ }+ this.saveReport(report)+ }+ }+ }++ setPersistenceLane(+ lane: LegacyImportServiceDeps['runExclusivePersistence']+ ): void {+ this.deps.runExclusivePersistence = lane+ }++ invitationDismissed(): boolean {+ return (+ (+ this.deps.db.database+ .prepare('SELECT dismissed FROM legacy_import_invitation WHERE id=1')+ .get() as { dismissed: number }+ ).dismissed === 1+ )+ }++ dismissInvitation(): void {+ this.deps.db.database+ .prepare('UPDATE legacy_import_invitation SET dismissed=1 WHERE id=1')+ .run()+ }++ async addSource(root: string): Promise<LegacyImportSource> {+ const source = await authorizeLegacySource(root)+ await probeLegacySource(source)+ for (const [handle, existing] of this.sources) {+ if (+ existing.root === source.root &&+ existing.identity === source.identity+ )+ return {+ sourceHandle: handle,+ name: path.basename(source.root),+ dataPath: source.root,+ }+ }+ if (this.sources.size >= 16) throw this.error('tooManySources')+ const sourceHandle = randomUUID()+ this.sources.set(sourceHandle, source)+ return {+ sourceHandle,+ name: path.basename(source.root),+ dataPath: source.root,+ }+ }++ async discover(roots: readonly string[]): Promise<LegacyImportSource[]> {+ const result: LegacyImportSource[] = []+ for (const root of roots) {+ try {+ const dto = await this.addSource(root)+ if (!result.some((entry) => entry.sourceHandle === dto.sourceHandle))+ result.push(dto)+ } catch {+ /* Unrecognized or unavailable defaults do not trigger an invitation. */+ }+ }+ return result+ }++ getSourcePath(sourceHandle: string): string {+ const source = this.sources.get(sourceHandle)+ if (!source) throw this.error('sourceNotAuthorized')+ return source.root+ }++ async scan(+ sourceHandle: string,+ expectedDigest?: string+ ): Promise<LegacyImportPreview> {+ if (this.draining) throw this.error('busy')+ const source = this.sources.get(sourceHandle)+ if (!source) throw this.error('sourceNotAuthorized')+ let snapshot: LegacySnapshot+ try {+ snapshot = await this.scanSource(source)+ } catch (error) {+ const grants = this.metadataGrants.get(sourceHandle)+ if (+ expectedDigest ||+ !grants?.size ||+ !(error instanceof Error) ||+ !/changedSource/.test(error.message)+ )+ throw error+ const valid = new Map<string, LegacyTorrentGrant>()+ for (const [digest, grant] of grants)+ if (await isLegacyTorrentGrantValid(grant)) valid.set(digest, grant)+ if (valid.size === grants.size) throw error+ snapshot = await scanLegacySource(+ source,+ this.deps.isProcessRunning,+ valid+ )+ if (this.draining) throw this.error('busy')+ this.metadataGrants.set(sourceHandle, valid)+ for (const [id, state] of this.previews)+ if (state.dto.sourceHandle === sourceHandle) this.previews.delete(id)+ }+ if (this.draining) throw this.error('busy')+ if (expectedDigest && snapshot.digest !== expectedDigest)+ throw this.error('changedSource')+ const grants = this.metadataGrants.get(sourceHandle)+ if (grants) {+ const currentEntries = new Set(+ snapshot.candidates.map((candidate) => candidate.entry.digest)+ )+ for (const digest of grants.keys())+ if (!currentEntries.has(digest)) grants.delete(digest)+ }+ const claims = this.claimedPaths()+ const pendingPaths: string[] = []+ for (const candidate of snapshot.candidates) {+ const ledger = this.deps.db.database+ .prepare(+ 'SELECT state, entry_digest FROM legacy_import_ledger WHERE source_id=? AND item_key=?'+ )+ .get(snapshot.sourceId, candidate.entry.itemKey) as+ | { state: string; entry_digest: string }+ | undefined+ if (ledger) {+ candidate.item.selectable = false+ candidate.item.reason =+ ledger.state === 'user-deleted'+ ? 'deleted-import'+ : ledger.entry_digest !== candidate.entry.digest+ ? 'changed-source'+ : 'already-imported'+ } else if (candidate.item.selectable && candidate.outputPath) {+ if (this.overlaps(candidate.outputPath, [...claims, ...pendingPaths])) {+ candidate.item.selectable = false+ candidate.item.reason = 'path-conflict'+ } else pendingPaths.push(candidate.outputPath)+ }+ }+ for (const [id, value] of this.previews)+ if (value.dto.expiresAt < this.clock()) this.previews.delete(id)+ while (this.previews.size >= 4) {+ const oldest = this.previews.keys().next().value+ if (!oldest) break+ this.previews.delete(oldest)+ }+ const dto: LegacyImportPreview = {+ previewId: randomUUID(),+ sourceHandle,+ sourceName: path.basename(source.root),+ items: snapshot.candidates.map((candidate) => candidate.item),+ running: snapshot.running,+ checkpointImportAvailable: false,+ expiresAt: this.clock() + PREVIEW_TTL,+ }+ this.previews.set(dto.previewId, { dto, snapshot })+ return dto+ }++ authorizeMetadata(+ input: unknown,+ chooseFile: () => Promise<string | null>+ ): Promise<LegacyImportPreview | null> {+ if (this.draining || this.activeRun || this.metadataAdmissions.size)+ return Promise.reject(this.error('busy'))+ const admission = this.authorizeMetadataAdmission(input, chooseFile)+ this.metadataAdmissions.add(admission)+ void admission+ .finally(() => this.metadataAdmissions.delete(admission))+ .catch(() => {})+ return admission+ }++ private async authorizeMetadataAdmission(+ input: unknown,+ chooseFile: () => Promise<string | null>+ ): Promise<LegacyImportPreview | null> {+ const { previewId, itemId } = legacyMetadataRequestSchema.parse(input)+ const preview = this.previews.get(previewId)+ const current = () => {+ if (+ !preview ||+ this.previews.get(previewId) !== preview ||+ preview.dto.expiresAt < this.clock()+ )+ throw this.error('expiredPreview')+ if (this.draining || this.activeRun || preview.committedRunId)+ throw this.error('busy')+ const candidate = preview.snapshot.candidates.find(+ (entry) => entry.item.itemId === itemId+ )+ if (+ candidate?.item.type !== 'bt' ||+ candidate.item.selectable ||+ candidate.item.reason !== 'metadata-required' ||+ !candidate.torrentReferencePath+ )+ throw this.error('invalidSelection')+ return candidate+ }+ const candidate = current()+ if (!preview) throw this.error('expiredPreview')+ const unchanged = async () => {+ current()+ const snapshot = await this.scanSource(preview.snapshot.source)+ current()+ if (snapshot.digest !== preview.snapshot.digest)+ throw this.error('changedSource')+ if (snapshot.running) throw this.error('running')+ }+ await unchanged()+ let selected: string | null+ try {+ selected = await Promise.race([+ chooseFile(),+ new Promise<null>((resolve) => {+ this.stopMetadataPicker = () => resolve(null)+ }),+ ])+ } finally {+ this.stopMetadataPicker = null+ }+ if (!selected) return null+ await unchanged()+ const grant = await authorizeLegacyTorrent(+ selected,+ candidate.torrentReferencePath ?? ''+ )+ const previous =+ this.metadataGrants.get(preview.dto.sourceHandle) ??+ new Map<string, LegacyTorrentGrant>()+ const trialGrants = new Map(previous)+ trialGrants.set(candidate.entry.digest, grant)+ const trial = await scanLegacySource(+ preview.snapshot.source,+ this.deps.isProcessRunning,+ trialGrants+ )+ const resolved = trial.candidates.find(+ (entry) => entry.entry.digest === candidate.entry.digest+ )+ if (!resolved?.torrent || !resolved.torrentRelativePath)+ throw this.error('metadataMismatch')+ await unchanged()+ // Admission owns the single metadata mutation lane. No previous grant or+ // preview changes until every chosen-file/source check has succeeded.+ this.metadataGrants.set(preview.dto.sourceHandle, trialGrants)+ try {+ const refreshed = await this.scan(preview.dto.sourceHandle, trial.digest)+ for (const [id, state] of this.previews)+ if (+ id !== refreshed.previewId &&+ state.dto.sourceHandle === preview.dto.sourceHandle+ )+ this.previews.delete(id)+ return refreshed+ } catch (error) {+ this.metadataGrants.set(preview.dto.sourceHandle, previous)+ throw error+ }+ }++ private scanSource(source: LegacySource): Promise<LegacySnapshot> {+ const handle = [...this.sources].find(+ ([, existing]) =>+ existing.root === source.root && existing.identity === source.identity+ )?.[0]+ return scanLegacySource(+ source,+ this.deps.isProcessRunning,+ handle ? this.metadataGrants.get(handle) : undefined+ )+ }++ commit(input: unknown): Promise<LegacyImportReport> {+ if (this.draining) return Promise.reject(this.error('busy'))+ const admission = this.commitAdmission(input)+ this.admissions.add(admission)+ void admission+ .finally(() => this.admissions.delete(admission))+ .catch(() => {})+ return admission+ }++ private async commitAdmission(input: unknown): Promise<LegacyImportReport> {+ const request = legacyCommitRequestSchema.parse(input)+ const preview = this.previews.get(request.previewId)+ if (!preview || preview.dto.expiresAt < this.clock())+ throw this.error('expiredPreview')+ if (preview.committedRunId) return this.getRun(preview.committedRunId)+ if (this.activeRun || this.metadataAdmissions.size) throw this.error('busy')+ const ids = new Set(request.itemIds)+ if (+ ids.size !== request.itemIds.length ||+ request.itemIds.some(+ (id) =>+ !preview.dto.items.some(+ (item) => item.itemId === id && item.selectable+ )+ )+ )+ throw this.error('invalidSelection')+ // Lock before the first await: two simultaneous commits cannot pass admission.+ const runId = randomUUID()+ this.activeRun = runId+ try {+ const refreshed = await this.scanSource(preview.snapshot.source)+ if (refreshed.digest !== preview.snapshot.digest)+ throw this.error('changedSource')+ if (refreshed.running) throw this.error('running')+ const selected = preview.snapshot.candidates.filter((candidate) =>+ ids.has(candidate.item.itemId)+ )+ this.assertNoConflicts(selected, preview.snapshot.sourceId)+ const report: LegacyImportReport = {+ runId,+ stage: 'backing-up',+ processed: 0,+ total: selected.length,+ imported: 0,+ backupCreated: false,+ items: preview.dto.items.map((item) => ({+ ...item,+ outcome: ids.has(item.itemId) ? 'unprocessed' : 'skipped',+ taskId: null,+ reason:+ item.selectable && !ids.has(item.itemId)+ ? 'not-selected'+ : item.reason,+ })),+ }+ this.deps.db.database+ .prepare(+ 'INSERT INTO legacy_import_runs (run_id,source_id,snapshot_digest,report,created_at) VALUES (?,?,?,?,?)'+ )+ .run(+ runId,+ preview.snapshot.sourceId,+ preview.snapshot.digest,+ JSON.stringify(report),+ this.clock()+ )+ const backup = await this.backup(preview.snapshot, runId)+ // The source and liveness guard must still hold after the potentially slow backup.+ const afterBackup = await this.scanSource(preview.snapshot.source)+ if (afterBackup.digest !== preview.snapshot.digest)+ throw this.error('changedSource')+ if (afterBackup.running) throw this.error('running')+ report.backupCreated = true+ report.stage = 'committing'+ this.deps.db.database+ .prepare(+ 'UPDATE legacy_import_runs SET backup_path=?,report=? WHERE run_id=?'+ )+ .run(backup, JSON.stringify(report), runId)+ preview.committedRunId = runId+ const job = this.runBatches(+ preview.snapshot,+ selected,+ backup,+ report+ ).finally(() => {+ this.activeRun = null+ this.runningJobs.delete(runId)+ this.cancelled.delete(runId)+ })+ this.runningJobs.set(runId, job)+ void job.catch(() => {})+ return this.getRun(runId)+ } catch (error) {+ const row = this.deps.db.database+ .prepare('SELECT report FROM legacy_import_runs WHERE run_id=?')+ .get(runId) as { report: string } | undefined+ if (row) {+ const report = legacyImportReportSchema.parse(JSON.parse(row.report))+ report.stage = 'failed'+ this.saveReport(report)+ }+ this.activeRun = null+ throw error+ }+ }++ getRun(runId: string): LegacyImportReport {+ const row = this.deps.db.database+ .prepare('SELECT report FROM legacy_import_runs WHERE run_id=?')+ .get(runId) as { report: string } | undefined+ if (!row) throw this.error('unknownRun')+ return legacyImportReportSchema.parse(JSON.parse(row.report))+ }++ cancel(runId: string): LegacyImportReport {+ if (this.activeRun === runId) this.cancelled.add(runId)+ return this.getRun(runId)+ }++ async drain(): Promise<void> {+ this.draining = true+ this.stopMetadataPicker?.()+ if (this.activeRun) this.cancelled.add(this.activeRun)+ // Backup and admission can still hold the database before a batch job exists.+ // Shutdown must wait for both phases before its caller closes the database.+ await Promise.allSettled(this.admissions)+ await Promise.allSettled(this.metadataAdmissions)+ await Promise.allSettled(this.runningJobs.values())+ }++ async retry(runId: string): Promise<LegacyImportReport> {+ const report = this.getRun(runId)+ const state = [...this.previews.values()].find(+ (preview) => preview.committedRunId === runId+ )+ if (!state) throw this.error('rescanRequired')+ const failed = report.items+ .filter(+ (item) => item.outcome === 'failed' || item.outcome === 'unprocessed'+ )+ .map((item) => item.itemId)+ if (!failed.length) return report+ const refreshed = await this.scan(state.dto.sourceHandle)+ return this.commit({ previewId: refreshed.previewId, itemIds: failed })+ }++ private async runBatches(+ snapshot: LegacySnapshot,+ selected: LegacyCandidate[],+ backup: string,+ report: LegacyImportReport+ ): Promise<void> {+ try {+ for (let offset = 0; offset < selected.length; offset += BATCH_SIZE) {+ // Yield at every boundary so a stop request can run before the next commit.+ await new Promise<void>((resolve) => setImmediate(resolve))+ if (this.cancelled.has(report.runId)) break+ const batch = selected.slice(offset, offset + BATCH_SIZE)+ let committed = false+ let preflightPassed = false+ const commit = async () => {+ const refreshed = await this.scanSource(snapshot.source)+ if (refreshed.digest !== snapshot.digest)+ throw this.error('changedSource')+ if (refreshed.running) throw this.error('running')+ if (this.cancelled.has(report.runId)) return+ preflightPassed = true+ this.assertNoConflicts(batch, snapshot.sourceId)+ const now = this.clock()+ const graphs = batch.map((candidate) =>+ this.graph(candidate, snapshot, backup, now)+ )+ const next: LegacyImportReport = structuredClone(report)+ for (let index = 0; index < batch.length; index++) {+ const item = next.items.find(+ (entry) => entry.itemId === batch[index].item.itemId+ )+ if (!item) throw this.error('invalidSelection')+ item.outcome = 'imported'+ item.taskId = graphs[index].task.motrixId+ }+ next.processed += batch.length+ next.imported += batch.length+ this.deps.db.saveLegacyImportBatch(graphs, () => {+ const ledger = this.deps.db.database.prepare(+ 'INSERT INTO legacy_import_ledger (source_id,item_key,entry_digest,task_id,state) VALUES (?,?,?,?,?)'+ )+ const items = this.deps.db.database.prepare(+ 'INSERT INTO legacy_import_items VALUES (?,?,?,?)'+ )+ for (let index = 0; index < batch.length; index++) {+ ledger.run(+ snapshot.sourceId,+ batch[index].entry.itemKey,+ batch[index].entry.digest,+ graphs[index].task.motrixId,+ 'imported'+ )+ items.run(+ report.runId,+ batch[index].entry.itemKey,+ 'imported',+ graphs[index].task.motrixId+ )+ }+ this.saveReport(next)+ })+ Object.assign(report, next)+ committed = true+ for (const graph of graphs)+ this.deps.taskManager.add(+ taskRowToDownloadTask(graph.task, graph.instances)+ )+ this.deps.publishTasks()+ }+ try {+ if (this.deps.runExclusivePersistence)+ await this.deps.runExclusivePersistence(commit)+ else await commit()+ } catch (error) {+ // A downstream observer or persistence-lane wrapper can fail after+ // SQLite committed. Its exception cannot undo durable import results.+ if (committed) continue+ // A stale source invalidates every remaining batch, not just this one.+ if (!preflightPassed) throw error+ for (const candidate of batch) {+ const item = report.items.find(+ (entry) => entry.itemId === candidate.item.itemId+ )+ if (item) {+ item.outcome = 'failed'+ item.reason = 'commit-failed'+ }+ }+ report.processed += batch.length+ this.saveReport(report)+ }+ }+ const stopped = this.cancelled.has(report.runId)+ report.stage = stopped ? 'cancelled' : 'completed'+ if (stopped)+ for (const item of report.items)+ if (item.outcome === 'unprocessed') item.reason = 'stopped'+ this.saveReport(report)+ } catch (error) {+ report.stage = 'failed'+ const changed =+ error instanceof Error && /changedSource|\.running$/.test(error.message)+ for (const item of report.items) {+ if (item.outcome !== 'unprocessed') continue+ item.outcome = 'failed'+ item.reason = changed ? 'changed-source' : 'commit-failed'+ report.processed+++ }+ this.saveReport(report)+ }+ }++ private graph(+ candidate: LegacyCandidate,+ snapshot: LegacySnapshot,+ backup: string,+ now: number+ ): TaskWithInstancesAndFiles {+ const id = randomUUID()+ const finalPath = candidate.outputPath+ if (!finalPath) throw this.error('unsafePath')+ const type =+ candidate.item.type === 'bt'+ ? TaskType.Bt+ : candidate.item.type === 'magnet'+ ? TaskType.Magnet+ : TaskType.Http+ const torrentMetaPath = candidate.torrentRelativePath+ ? path.join(backup, candidate.torrentRelativePath)+ : null+ const sessionDigest = snapshot.files.find(+ (file) => file.relativePath === 'download.session'+ )?.digest+ if (!sessionDigest) throw this.error('changedSource')+ const payload = {+ legacyImport: {+ version: 1,+ sourceId: snapshot.sourceId,+ origin: {+ root: snapshot.source.root,+ identity: snapshot.source.identity,+ sessionDigest,+ torrentDigest:+ snapshot.files.find(+ (file) => file.relativePath === candidate.torrentRelativePath+ )?.digest ?? null,+ profileFiles: snapshot.files+ .filter((file) =>+ ['download.session', 'user.json', 'system.json'].includes(+ file.relativePath+ )+ )+ .map(({ relativePath, digest }) => ({ relativePath, digest })),+ },+ itemKey: candidate.entry.itemKey,+ activation: 'inactive',+ storagePolicy: 'legacy-read-only',+ reason: candidate.item.reason,+ selectionKnown: candidate.selectionKnown,+ selectedFiles: candidate.selectedFiles,+ },+ }+ return {+ task: {+ motrixId: id,+ name: candidate.item.name,+ kind: type === TaskType.Http ? TaskKind.Direct : TaskKind.Bt,+ taskType: type,+ category: null,+ priority: 0,+ tags: null,+ createdAt: now,+ updatedAt: now,+ saveDir: path.dirname(finalPath),+ finalPath,+ finalName: candidate.item.name,+ torrentMetaPath,+ infoHash: candidate.torrent?.infoHash ?? null,+ totalBytes: candidate.torrent?.totalSize ?? 0,+ downloadedBytes: 0,+ sizeWhenDone: 0,+ fileCount: candidate.torrent?.files.length ?? 1,+ isPrivate: candidate.torrent?.isPrivate ?? false,+ trackers: candidate.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: randomUUID(),+ motrixId: id,+ gid: null,+ phase:+ type === TaskType.Http+ ? TaskInstancePhase.HttpDownload+ : TaskInstancePhase.BtDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: candidate.torrent?.totalSize ?? 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: finalPath,+ transitionPhase: TransitionPhase.Idle,+ uris: type === TaskType.Bt ? [] : candidate.entry.uris,+ uriHash: null,+ payload,+ createdAt: now,+ updatedAt: now,+ },+ ],+ files:+ candidate.torrent?.files.map((file) => ({+ fileIndex: file.index,+ path: file.path,+ size: file.size,+ selected: candidate.selectedFiles.includes(file.index),+ })) ?? [],+ }+ }++ private saveReport(report: LegacyImportReport): void {+ this.deps.db.database+ .prepare('UPDATE legacy_import_runs SET report=? WHERE run_id=?')+ .run(JSON.stringify(report), report.runId)+ }++ private claimedPaths(): string[] {+ return this.deps.db+ .getAllTasks()+ .flatMap(({ task, instances }) => [+ task.finalPath,+ ...instances.map((instance) => instance.diskPath),+ ])+ .filter(Boolean)+ }++ private overlaps(value: string, others: string[]): boolean {+ const identity = outputPathIdentity(value)+ return others.some((other) => {+ const candidate = outputPathIdentity(other)+ return (+ identity === candidate ||+ identity.startsWith(`${candidate}${path.sep}`) ||+ candidate.startsWith(`${identity}${path.sep}`)+ )+ })+ }++ private assertNoConflicts(+ candidates: LegacyCandidate[],+ sourceId: string+ ): void {+ const claims = this.claimedPaths()+ for (const candidate of candidates) {+ if (+ !candidate.outputPath ||+ this.overlaps(candidate.outputPath, claims) ||+ this.deps.db.database+ .prepare(+ 'SELECT 1 FROM legacy_import_ledger WHERE source_id=? AND item_key=?'+ )+ .get(sourceId, candidate.entry.itemKey)+ )+ throw this.error('pathConflict')+ claims.push(candidate.outputPath)+ }+ }++ private async backup(+ snapshot: LegacySnapshot,+ runId: string+ ): Promise<string> {+ await mkdir(this.deps.backupRoot, { recursive: true, mode: 0o700 })+ const root = await lstat(this.deps.backupRoot)+ if (+ !root.isDirectory() ||+ root.isSymbolicLink() ||+ (await realpath(this.deps.backupRoot)) !==+ path.resolve(this.deps.backupRoot)+ )+ throw this.error('unsafeBackup')+ if (process.platform !== 'win32') await chmod(this.deps.backupRoot, 0o700)+ const target = path.join(this.deps.backupRoot, runId)+ await mkdir(target, { mode: 0o700 })+ const directories = new Set([target])+ const write = async (relativePath: string, bytes: Uint8Array) => {+ const filename = path.join(target, relativePath)+ await mkdir(path.dirname(filename), { recursive: true, mode: 0o700 })+ if (+ !(await realpath(path.dirname(filename))).startsWith(+ `${target}${path.sep}`+ ) &&+ path.dirname(filename) !== target+ )+ throw this.error('unsafeBackup')+ for (+ let directory = path.dirname(filename);+ directory !== target;+ directory = path.dirname(directory)+ )+ directories.add(directory)+ const handle = await open(+ filename,+ constants.O_WRONLY |+ constants.O_CREAT |+ constants.O_EXCL |+ (constants.O_NOFOLLOW ?? 0),+ 0o600+ )+ try {+ await handle.writeFile(bytes)+ await handle.sync()+ } finally {+ await handle.close()+ }+ }+ for (const file of snapshot.files)+ await write(file.relativePath, file.bytes)+ await write(+ 'manifest.json',+ Buffer.from(+ JSON.stringify({+ version: 1,+ sourceId: snapshot.sourceId,+ snapshotDigest: snapshot.digest,+ files: snapshot.files.map(({ relativePath, digest }) => ({+ relativePath,+ digest,+ })),+ })+ )+ )+ // Node cannot open directory handles for fsync on Windows; each file has+ // already been flushed. POSIX also flushes nested directory entries and+ // the parent that owns this run before any database reference is committed.+ if (process.platform !== 'win32') {+ for (const directory of [...directories]+ .sort((a, b) => b.length - a.length)+ .concat(this.deps.backupRoot)) {+ const handle = await open(+ directory,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)+ )+ try {+ await handle.sync()+ } finally {+ await handle.close()+ }+ }+ }+ return target+ }++ private error(reason: string): AppError {+ return new AppError(+ ErrorCode.IpcInvalidPayload,+ `legacyImport.errors.${reason}`+ )+ }+}diff --git a/src/core/legacy-import/legacy-task-policy.ts b/src/core/legacy-import/legacy-task-policy.tsnew file mode 100644index 00000000..13271d38--- /dev/null+++ b/src/core/legacy-import/legacy-task-policy.ts@@ -0,0 +1,54 @@+import { AppError, ErrorCode } from '@shared/errors'+import type { DownloadTask } from '@shared/types/task'++export {+ hasLegacyImport,+ isLegacyImportInactive as isInactiveLegacyTask,+} from '@shared/types/task-actions'++import { isLegacyImportInactive as isInactiveLegacyTask } from '@shared/types/task-actions'++export function assertLegacyTaskNotActivated(+ task: Pick<DownloadTask, 'instances'>+): void {+ if (isInactiveLegacyTask(task)) {+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.activationRequired'+ )+ }+}++export function assertLegacyTaskNotRecreated(+ task: Pick<DownloadTask, 'instances'>+): void {+ if (+ (task.instances ?? []).some((instance) =>+ Object.hasOwn(instance.payload ?? {}, 'legacyImport')+ )+ )+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.activationRequired'+ )+}++/** Pending or corrupt migration records quarantine every known reserved/bound GID. */+export function getLegacyQuarantinedGids(+ task: Pick<DownloadTask, 'instances'>+): Set<string> {+ const result = new Set<string>()+ if (!isInactiveLegacyTask(task)) return result+ for (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)+ }+ return result+}diff --git a/src/core/legacy-import/metadata-authorization.test.ts b/src/core/legacy-import/metadata-authorization.test.tsnew file mode 100644index 00000000..8eebeda6--- /dev/null+++ b/src/core/legacy-import/metadata-authorization.test.ts@@ -0,0 +1,308 @@+// @vitest-environment node+import {+ cp,+ link,+ mkdtemp,+ readFile,+ realpath,+ rename,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { MotrixDatabase } from '@core/session/motrix-database'+import { TaskManager } from '@core/task/task-manager'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { LegacyImportService } from './import-service'+import {+ authorizeLegacySource,+ authorizeLegacyTorrent,+ scanLegacySource,+} from './source-scanner'++const fixtures = fileURLToPath(+ new URL('../../../tests/fixtures/legacy-v1/generated/', import.meta.url)+)+const cleanup: Array<() => Promise<void>> = []+async function fixture() {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-metadata-grant-'))+ )+ await cp(fixtures, root, { recursive: true })+ const profile = path.join(root, 'profile')+ const downloads = path.join(root, 'downloads')+ for (const name of ['download.session', 'system.json']) {+ const file = path.join(profile, name)+ await writeFile(+ file,+ (await readFile(file, 'utf8'))+ .replaceAll('__FIXTURE_ROOT__', profile)+ .replaceAll('__FIXTURE_DOWNLOADS__', downloads)+ .replaceAll('__FIXTURE_HTTP_PORT__', '18080')+ )+ }+ const provenance = JSON.parse(+ await readFile(path.join(root, 'provenance.json'), 'utf8')+ )+ const metadata = path.join(downloads, provenance.bt.metadataFilename)+ const db = new MotrixDatabase(path.join(root, 'motrix.db'))+ db.init()+ const tasks = new TaskManager()+ let now = Date.now()+ const service = new LegacyImportService({+ db,+ taskManager: tasks,+ backupRoot: path.join(root, 'backups'),+ isProcessRunning: () => false,+ publishTasks: vi.fn(),+ now: () => now,+ })+ cleanup.push(async () => {+ await service.drain()+ db.close()+ await rm(root, { recursive: true, force: true })+ })+ const source = await service.addSource(profile)+ const preview = await service.scan(source.sourceHandle)+ const item = preview.items.find((entry) => entry.type === 'bt')+ if (!item) throw new Error('Missing generated BT fixture')+ const request = { previewId: preview.previewId, itemId: item.itemId }+ return {+ root,+ profile,+ downloads,+ metadata,+ provenance,+ db,+ tasks,+ service,+ source,+ preview,+ request,+ expire: () => {+ now += 16 * 60 * 1000+ },+ }+}+afterEach(async () => {+ await Promise.all(cleanup.splice(0).map((operation) => operation()))+})++describe('exact legacy torrent metadata authorization', () => {+ it('imports explicitly chosen external metadata through a safe backup alias and invalidates the old preview', async () => {+ const f = await fixture()+ const original = await readFile(f.metadata)+ const next = await f.service.authorizeMetadata(+ f.request,+ async () => f.metadata+ )+ const item = next?.items.find((entry) => entry.itemId === f.request.itemId)+ expect(item).toMatchObject({+ type: 'bt',+ name: 'fixture-bundle',+ selectable: true,+ })+ await expect(+ f.service.commit({+ previewId: f.preview.previewId,+ itemIds: [+ f.preview.items.find((entry) => entry.type === 'http')?.itemId,+ ],+ })+ ).rejects.toThrow('expiredPreview')+ const run = await f.service.commit({+ previewId: next?.previewId,+ itemIds: [f.request.itemId],+ })+ await vi.waitFor(() =>+ expect(f.service.getRun(run.runId).stage).toBe('completed')+ )+ expect(f.service.getRun(run.runId).imported).toBe(1)+ const task = f.db.getAllTasks()[0]+ expect(task.task.torrentMetaPath).toMatch(+ /authorized-torrents[/\\][a-f\d]{64}\.torrent$/+ )+ expect(await readFile(task.task.torrentMetaPath ?? '')).toEqual(original)+ expect(await readFile(f.metadata)).toEqual(original)+ expect(task.task.isPrivate).toBe(true)+ expect(task.task.trackers[0][0]).toContain('127.0.0.1')+ })++ it('cancel leaves the current preview and all selections usable', async () => {+ const f = await fixture()+ await expect(+ f.service.authorizeMetadata(f.request, async () => null)+ ).resolves.toBeNull()+ const http = f.preview.items.find((entry) => entry.type === 'http')+ const run = await f.service.commit({+ previewId: f.preview.previewId,+ itemIds: [http?.itemId],+ })+ await vi.waitFor(() =>+ expect(f.service.getRun(run.runId).stage).toBe('completed')+ )+ expect(f.service.getRun(run.runId).imported).toBe(1)+ })++ it('rejects incorrect bytes for a SHA1-named v1 reference without invalidating the preview', async () => {+ const f = await fixture()+ const wrong = path.join(f.downloads, 'wrong.torrent')+ const bytes = Buffer.from(await readFile(f.metadata))+ bytes[bytes.indexOf(Buffer.from('127.0.0.1'))] = '2'.charCodeAt(0)+ await writeFile(wrong, bytes)+ await expect(+ f.service.authorizeMetadata(f.request, async () => wrong)+ ).rejects.toThrow('metadataMismatch')+ const next = await f.service.authorizeMetadata(+ f.request,+ async () => f.metadata+ )+ expect(+ next?.items.find((entry) => entry.itemId === f.request.itemId)?.selectable+ ).toBe(true)+ })++ it('rejects a source saved while the native picker was open', async () => {+ const f = await fixture()+ await expect(+ f.service.authorizeMetadata(f.request, async () => {+ const session = path.join(f.profile, 'download.session')+ await writeFile(+ session,+ (await readFile(session, 'utf8')).replace('pause=true', 'pause=false')+ )+ return f.metadata+ })+ ).rejects.toThrow('changedSource')+ const scan = await f.service.scan(f.source.sourceHandle)+ expect(scan.items.find((entry) => entry.type === 'bt')?.selectable).toBe(+ false+ )+ })++ it('checks preview expiry before and after choosing a file', async () => {+ const f = await fixture()+ await expect(+ f.service.authorizeMetadata(f.request, async () => {+ f.expire()+ return f.metadata+ })+ ).rejects.toThrow('expiredPreview')+ const choose = vi.fn(async () => f.metadata)+ await expect(+ f.service.authorizeMetadata(f.request, choose)+ ).rejects.toThrow('expiredPreview')+ expect(choose).not.toHaveBeenCalled()+ })++ it('rejects a replaced authorized inode even when replacement bytes are identical', async () => {+ const f = await fixture()+ const next = await f.service.authorizeMetadata(+ f.request,+ async () => f.metadata+ )+ const bytes = await readFile(f.metadata)+ await rename(f.metadata, `${f.metadata}.original`)+ await writeFile(f.metadata, bytes)+ await expect(+ f.service.commit({+ previewId: next?.previewId,+ itemIds: [f.request.itemId],+ })+ ).rejects.toThrow('changedSource')+ expect(f.db.getAllTasks()).toEqual([])+ const rescanned = await f.service.scan(f.source.sourceHandle)+ expect(+ rescanned.items.find((entry) => entry.itemId === f.request.itemId)+ ).toMatchObject({ selectable: false, reason: 'metadata-required' })+ const recovered = await f.service.authorizeMetadata(+ { ...f.request, previewId: rescanned.previewId },+ async () => f.metadata+ )+ expect(+ recovered?.items.find((entry) => entry.itemId === f.request.itemId)+ ?.selectable+ ).toBe(true)+ })++ it('authorizes one chosen file without granting adjacent referenced torrent files', async () => {+ const f = await fixture()+ const source = await authorizeLegacySource(f.profile)+ const first = await scanLegacySource(source, () => false)+ const bt = first.candidates.find((entry) => entry.item.type === 'bt')+ if (!bt?.torrentReferencePath) throw new Error('Missing reference')+ const grant = await authorizeLegacyTorrent(+ f.metadata,+ bt.torrentReferencePath+ )+ const sibling = path.join(f.downloads, 'ungranted.torrent')+ await writeFile(sibling, await readFile(f.metadata))+ const session = path.join(f.profile, 'download.session')+ await writeFile(+ session,+ (await readFile(session, 'utf8')) ++ `\n${sibling}\n gid=2222333344445555\n dir=${f.downloads}\n select-file=1\n`+ )+ const scan = await scanLegacySource(+ source,+ () => false,+ new Map([[bt.entry.digest, grant]])+ )+ expect(+ scan.candidates.find((entry) => entry.entry.gid === '2222333344445555')+ ?.item+ ).toMatchObject({ selectable: false, reason: 'metadata-required' })+ expect(+ scan.files.filter((file) =>+ file.relativePath.startsWith('authorized-torrents/')+ )+ ).toHaveLength(1)+ })++ it('rejects symbolic and hard linked picker targets', async () => {+ const f = await fixture()+ const alias = path.join(f.downloads, 'alias.torrent')+ await symlink(f.metadata, alias)+ await expect(+ f.service.authorizeMetadata(f.request, async () => alias)+ ).rejects.toThrow('unsafeSource')+ await rm(alias)+ await link(f.metadata, alias)+ await expect(+ f.service.authorizeMetadata(f.request, async () => alias)+ ).rejects.toThrow('unsafeSource')+ })++ it('releases a pending picker on drain without mutating grants after shutdown', async () => {+ const f = await fixture()+ let entered = false+ const admission = f.service.authorizeMetadata(f.request, async () => {+ entered = true+ return new Promise<string>(() => {})+ })+ await vi.waitFor(() => expect(entered).toBe(true))+ await f.service.drain()+ await expect(admission).resolves.toBeNull()+ expect(f.db.getAllTasks()).toEqual([])+ })++ it('rejects concurrent metadata admissions before opening a second picker', async () => {+ const f = await fixture()+ let entered = false+ const first = f.service.authorizeMetadata(f.request, async () => {+ entered = true+ return new Promise<string>(() => {})+ })+ await vi.waitFor(() => expect(entered).toBe(true))+ const choose = vi.fn(async () => f.metadata)+ await expect(+ f.service.authorizeMetadata(f.request, choose)+ ).rejects.toThrow('busy')+ expect(choose).not.toHaveBeenCalled()+ await f.service.drain()+ await expect(first).resolves.toBeNull()+ })+})diff --git a/src/core/legacy-import/parser-adversarial.test.ts b/src/core/legacy-import/parser-adversarial.test.tsnew file mode 100644index 00000000..9df87225--- /dev/null+++ b/src/core/legacy-import/parser-adversarial.test.ts@@ -0,0 +1,88 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest'+import { parseLegacySession, validateLegacyBencode } from './session-parser'++const encode = (value: string) => new TextEncoder().encode(value)++describe('legacy session adversarial parsing', () => {+ it('recognizes a saved session with BOM, trailing TAB, CRLF, comments and blank option lines', () => {+ const entries = parseLegacySession(+ encode(+ '\uFEFFhttps://example.test/a\thttps://mirror.test/a\t\r\n gid=0123456789abcdef\r\n# saved options\r\n\r\n out=a.zip\r\n'+ )+ )+ expect(entries).toHaveLength(1)+ expect(entries[0].uris).toEqual([+ 'https://example.test/a',+ 'https://mirror.test/a',+ ])+ expect(entries[0].options.out).toBe('a.zip')+ expect(entries[0].reason).toBeNull()+ })++ it('uses the final singleton option without discarding valid saved records', () => {+ const [entry] = parseLegacySession(+ encode('https://example.test/a\n out=first.zip\n out=last.zip\n')+ )+ expect(entry.options.out).toBe('last.zip')+ expect(entry.reason).toBeNull()+ })++ it.each(['false', '0', '1', ''])(+ 'does not enable ambient netrc credentials through no-netrc=%s',+ (value) => {+ const [entry] = parseLegacySession(+ encode(`https://example.test/a\n no-netrc=${value}\n`)+ )+ expect(entry.reason).toBe('unsupported-options')+ }+ )++ it('preserves cumulative tracker pairs while applying singleton last-value semantics', () => {+ const [entry] = parseLegacySession(+ encode(+ 'metadata.torrent\n bt-tracker=https://first.test/announce\n out=first\n bt-tracker=https://second.test/announce\n out=last\n'+ )+ )+ expect(entry.options.out).toBe('last')+ expect(entry.optionPairs.filter(([key]) => key === 'bt-tracker')).toEqual([+ ['bt-tracker', 'https://first.test/announce'],+ ['bt-tracker', 'https://second.test/announce'],+ ])+ expect(entry.reason).toBeNull()+ })++ 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()+ }+ )++ it('rejects malformed UTF-8 instead of merging replacement characters into an identity', () => {+ expect(() =>+ parseLegacySession(new Uint8Array([0x68, 0xff, 0x0a]))+ ).toThrow()+ })++ it.each([+ 'l'.repeat(40) + 'e'.repeat(40),+ '99999999:a',+ 'i9007199254740992e',+ 'd1:ale',+ ])(+ 'rejects malicious or truncated bencode before torrent decoding: %s',+ (input) => {+ expect(() => validateLegacyBencode(encode(input))).toThrow()+ }+ )+})diff --git a/src/core/legacy-import/session-parser.ts b/src/core/legacy-import/session-parser.tsnew file mode 100644index 00000000..fd14521f--- /dev/null+++ b/src/core/legacy-import/session-parser.ts@@ -0,0 +1,188 @@+import { createHash } from 'node:crypto'+import path from 'node:path'+import type { LegacyReason } from '@shared/schemas/legacy-import'++export const MAX_LEGACY_BYTES = 8 * 1024 * 1024+export const MAX_LEGACY_ITEMS = 10000+const MAX_LINE = 16384+const OPTIONS = new Set([+ 'gid',+ 'dir',+ 'out',+ 'select-file',+ 'pause',+ 'continue',+ 'max-connection-per-server',+ 'split',+ 'min-split-size',+ 'max-download-limit',+ 'max-upload-limit',+ 'bt-seed-unverified',+ 'seed-time',+ 'seed-ratio',+ 'bt-save-metadata',+ 'bt-metadata-only',+ 'check-integrity',+ 'allow-overwrite',+ 'auto-file-renaming',+ 'file-allocation',+ // Only explicit true is accepted: 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.+ 'pause-metadata',+ 'user-agent',+ 'follow-torrent',+ 'follow-metalink',+ 'enable-peer-exchange',+ 'bt-enable-lpd',+ 'bt-force-encryption',+ 'bt-load-saved-metadata',+ 'bt-tracker',+])++export interface LegacySessionEntry {+ itemKey: string+ digest: string+ gid: string | null+ uris: string[]+ options: Record<string, string>+ optionPairs: Array<readonly [string, string]>+ reason: LegacyReason | null+}++export function digestBytes(bytes: Uint8Array | string): string {+ return createHash('sha256').update(bytes).digest('hex')+}++/** aria2 text sessions: each URI line is followed by indented key=value options. */+export function parseLegacySession(bytes: Uint8Array): LegacySessionEntry[] {+ if (bytes.byteLength > MAX_LEGACY_BYTES)+ throw new Error('legacyImport.tooLarge')+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)+ if (text.includes('\0')) throw new Error('legacyImport.invalidSource')+ const entries: LegacySessionEntry[] = []+ let lines: string[] = []+ const flush = () => {+ if (!lines.length) return+ if (entries.length >= MAX_LEGACY_ITEMS)+ throw new Error('legacyImport.tooLarge')+ const raw = lines.join('\n')+ const uris = lines[0].trim().split(/\t+/).filter(Boolean)+ const options: Record<string, string> = Object.create(null)+ const optionPairs: Array<readonly [string, string]> = []+ let reason: LegacyReason | null =+ lines.some((line) => line.length > MAX_LINE) || uris.length > 16+ ? 'invalid-record'+ : null+ for (const line of lines.slice(1)) {+ const match = /^\s+([a-z0-9-]+)=(.*)$/.exec(line)+ if (!match) {+ 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 gid =+ options.gid && /^[a-f\d]{16}$/i.test(options.gid)+ ? options.gid.toLowerCase()+ : null+ 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 })+ lines = []+ }+ for (const line of text.split(/\r?\n/)) {+ if (!line.trim() || line.startsWith('#')) continue+ if (!/^\s/.test(line)) flush()+ if (!lines.length && /^\s/.test(line)) {+ lines = ['invalid:', line]+ } else lines.push(line)+ }+ flush()+ const counts = new Map<string, number>()+ for (const entry of entries)+ counts.set(entry.itemKey, (counts.get(entry.itemKey) ?? 0) + 1)+ for (const entry of entries)+ if ((counts.get(entry.itemKey) ?? 0) > 1) entry.reason = 'invalid-record'+ return entries+}++export function safeLegacyComponent(value: string): boolean {+ return (+ value.length > 0 &&+ value.length <= 255 &&+ value !== '.' &&+ value !== '..' &&+ !Array.from(value).some((character) => character.charCodeAt(0) < 32) &&+ !/[<>:"/\\|?*]/.test(value) &&+ !/[. ]$/.test(value) &&+ !/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(value)+ )+}++export function safeLegacyDirectory(dir: string): string | null {+ if (!path.isAbsolute(dir) || dir.includes('\0') || dir.length > 4096)+ return null+ const root = path.resolve(dir)+ return root === path.parse(root).root ? null : root+}++export function safeLegacyOutput(dir: string, name: string): string | null {+ const root = safeLegacyDirectory(dir)+ return root && safeLegacyComponent(name) ? path.join(root, name) : null+}++/** Validate bencode complexity before allowing a third-party decoder to recurse. */+export function validateLegacyBencode(bytes: Uint8Array): void {+ if (bytes.length > MAX_LEGACY_BYTES) throw new Error('legacyImport.tooLarge')+ let cursor = 0+ let nodes = 0+ const visit = (depth: number) => {+ if (depth > 32 || ++nodes > 100000)+ throw new Error('legacyImport.invalidSource')+ const char = bytes[cursor++]+ if (char === 100 || char === 108) {+ while (bytes[cursor] !== 101) {+ if (cursor >= bytes.length)+ throw new Error('legacyImport.invalidSource')+ visit(depth + 1)+ }+ cursor+++ } else if (char === 105) {+ const start = cursor+ while (bytes[cursor] !== 101 && cursor < bytes.length) cursor+++ const number = new TextDecoder().decode(bytes.slice(start, cursor))+ if (+ number.length > 20 ||+ !/^-?\d+$/.test(number) ||+ !Number.isSafeInteger(Number(number)) ||+ cursor >= bytes.length+ )+ throw new Error('legacyImport.invalidSource')+ cursor+++ } else if (char >= 48 && char <= 57) {+ let length = char - 48+ let digits = 1+ while (bytes[cursor] !== 58) {+ const next = bytes[cursor++]+ if (++digits > 8 || next < 48 || next > 57)+ throw new Error('legacyImport.invalidSource')+ length = length * 10 + next - 48+ }+ cursor+++ if (length > bytes.length - cursor)+ throw new Error('legacyImport.invalidSource')+ cursor += length+ } else throw new Error('legacyImport.invalidSource')+ }+ visit(0)+ if (cursor !== bytes.length) throw new Error('legacyImport.invalidSource')+}diff --git a/src/core/legacy-import/source-scanner-adversarial.test.ts b/src/core/legacy-import/source-scanner-adversarial.test.tsnew file mode 100644index 00000000..7ccb688a--- /dev/null+++ b/src/core/legacy-import/source-scanner-adversarial.test.ts@@ -0,0 +1,147 @@+// @vitest-environment node+import {+ link,+ mkdir,+ mkdtemp,+ rename,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import {+ authorizeLegacySource,+ readLegacyFile,+ scanLegacySource,+} from './source-scanner'++const roots: string[] = []++async function fixture(+ session = 'https://example.test/file.zip\t\n gid=0123456789abcdef\n out=file.zip\n'+) {+ const root = await mkdtemp(+ path.join(os.tmpdir(), 'legacy-import-adversarial-')+ )+ roots.push(root)+ const sourceRoot = path.join(root, 'legacy')+ await mkdir(sourceRoot)+ await writeFile(+ path.join(sourceRoot, 'user.json'),+ JSON.stringify({ theme: 'auto' })+ )+ await writeFile(+ path.join(sourceRoot, 'system.json'),+ JSON.stringify({ dir: path.join(root, 'downloads') })+ )+ await writeFile(path.join(sourceRoot, 'download.session'), session)+ return { root, sourceRoot, source: await authorizeLegacySource(sourceRoot) }+}++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))+ )+})++describe('legacy source adversarial boundaries', () => {+ it('rejects a session replaced with a symlink outside the selected directory', async () => {+ const { root, sourceRoot, source } = await fixture()+ const outside = path.join(root, 'private.session')+ await writeFile(outside, 'https://example.test/private.zip\n')+ await rm(path.join(sourceRoot, 'download.session'))+ await symlink(outside, path.join(sourceRoot, 'download.session'))+ await expect(scanLegacySource(source, () => false)).rejects.toThrow()+ })++ it('rejects a hard-linked session even when its name stays inside the grant', async () => {+ const { root, sourceRoot, source } = await fixture()+ await link(+ path.join(sourceRoot, 'download.session'),+ path.join(root, 'alias.session')+ )+ await expect(scanLegacySource(source, () => false)).rejects.toThrow()+ })++ it('invalidates a source handle when a different directory replaces its path', async () => {+ const { root, sourceRoot, source } = await fixture()+ await rename(sourceRoot, path.join(root, 'original'))+ await mkdir(sourceRoot)+ await writeFile(+ path.join(sourceRoot, 'download.session'),+ 'https://example.test/replacement.zip\n'+ )+ await expect(readLegacyFile(source, 'download.session')).rejects.toThrow()+ })++ it.each([+ '../outside.session',+ 'nested/../../outside.session',+ '/tmp/outside.session',+ 'nested\\..\\outside.session',+ ])('rejects metadata path traversal: %s', async (relative) => {+ const { source } = await fixture()+ await expect(readLegacyFile(source, relative)).rejects.toThrow()+ })++ it('does not follow a symlink in an intermediate metadata directory', async () => {+ const { root, sourceRoot, source } = await fixture()+ const outside = path.join(root, 'outside')+ await mkdir(outside)+ await writeFile(path.join(outside, 'meta.torrent'), 'private')+ await symlink(outside, path.join(sourceRoot, 'metadata'))+ await expect(+ readLegacyFile(source, 'metadata/meta.torrent')+ ).rejects.toThrow()+ })++ it('blocks a task whose old request depended on a header without exposing that value', async () => {+ const { source } = await fixture(+ 'https://example.test/file.zip\n header=Authorization: Bearer private-token\n out=file.zip\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')+ })++ it('blocks inherited request credentials instead of treating the task as URI-only', async () => {+ const { root, sourceRoot, source } = await fixture()+ await writeFile(+ path.join(sourceRoot, 'system.json'),+ JSON.stringify({+ dir: path.join(root, 'downloads'),+ 'http-user': 'private-user',+ 'http-passwd': 'private-pass',+ })+ )+ 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')+ })++ 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'+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates).toHaveLength(2)+ expect(scan.candidates.every(({ item }) => !item.selectable)).toBe(true)+ })++ it('keeps the same URL in two output directories as distinct import candidates', async () => {+ const { root, sourceRoot, source } = await fixture()+ await writeFile(+ path.join(sourceRoot, 'download.session'),+ `https://example.test/file.zip\n dir=${root}/first\n out=file.zip\nhttps://example.test/file.zip\n dir=${root}/second\n out=file.zip\n`+ )+ const scan = await scanLegacySource(source, () => false)+ expect(scan.candidates.every(({ item }) => item.selectable)).toBe(true)+ expect(new Set(scan.candidates.map(({ item }) => item.itemId)).size).toBe(2)+ })+})diff --git a/src/core/legacy-import/source-scanner-probe.test.ts b/src/core/legacy-import/source-scanner-probe.test.tsnew file mode 100644index 00000000..cd1152c8--- /dev/null+++ b/src/core/legacy-import/source-scanner-probe.test.ts@@ -0,0 +1,164 @@+// @vitest-environment node+import {+ link,+ lstat,+ mkdir,+ mkdtemp,+ open,+ readdir,+ readFile,+ realpath,+ rename,+ rm,+ symlink,+ truncate,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { MAX_LEGACY_BYTES } from './session-parser'+import {+ authorizeLegacySource,+ probeLegacySource,+ scanLegacySource,+} from './source-scanner'++vi.mock('node:fs/promises', async (original) => {+ const actual = await original<typeof import('node:fs/promises')>()+ return {+ ...actual,+ lstat: vi.fn(actual.lstat),+ open: vi.fn(actual.open),+ readdir: vi.fn(actual.readdir),+ readFile: vi.fn(actual.readFile),+ }+})++const roots: string[] = []+const metadata = ['user.json', 'system.json', 'download.session'] as const++async function fixture(session: string | Buffer = '') {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'legacy-source-probe-'))+ )+ roots.push(root)+ const profile = path.join(root, 'profile')+ await mkdir(profile)+ await writeFile(path.join(profile, 'user.json'), '{"theme":"auto"}')+ await writeFile(+ path.join(profile, 'system.json'),+ JSON.stringify({ dir: path.join(root, 'downloads') })+ )+ await writeFile(path.join(profile, 'download.session'), session)+ return { root, profile, source: await authorizeLegacySource(profile) }+}++beforeEach(() => vi.clearAllMocks())+afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))+ )+})++describe('lightweight legacy source probe', () => {+ it('stats only the root and three fixed files without task, PID or content IO', async () => {+ const f = await fixture(+ 'https://example.test/a.zip\n out=a.zip\n/file/outside.torrent\n'+ )+ await writeFile(path.join(f.profile, 'engine.pid'), '123')+ await mkdir(path.join(f.profile, 'nested'))+ await writeFile(path.join(f.profile, 'nested', 'download.torrent'), 'bad')+ vi.clearAllMocks()+ await expect(probeLegacySource(f.source)).resolves.toBeUndefined()+ expect(vi.mocked(lstat).mock.calls.map(([filename]) => filename)).toEqual([+ f.profile,+ ...metadata.map((name) => path.join(f.profile, name)),+ f.profile,+ ])+ expect(open).not.toHaveBeenCalled()+ expect(readFile).not.toHaveBeenCalled()+ expect(readdir).not.toHaveBeenCalled()+ })++ it('recognizes an empty session and leaves full scanning able to return no tasks', async () => {+ const f = await fixture()+ await expect(probeLegacySource(f.source)).resolves.toBeUndefined()+ const running = vi.fn(() => false)+ expect((await scanLegacySource(f.source, running)).candidates).toEqual([])+ expect(running).not.toHaveBeenCalled()+ })++ it.each([Buffer.from('\0bad session'), Buffer.alloc(4 * 1024 * 1024)])(+ 'defers malformed session parsing, including large files within the safety limit',+ async (session) => {+ const f = await fixture(session)+ await writeFile(path.join(f.profile, 'engine.pid'), '123')+ const running = vi.fn(() => false)+ vi.clearAllMocks()+ await expect(probeLegacySource(f.source)).resolves.toBeUndefined()+ expect(open).not.toHaveBeenCalled()+ expect(running).not.toHaveBeenCalled()+ await expect(scanLegacySource(f.source, running)).rejects.toThrow(+ 'legacyImport.invalidSource'+ )+ expect(running).toHaveBeenCalledWith(123)+ }+ )++ it('defers configuration parsing while full scan still rejects invalid configuration', async () => {+ const f = await fixture()+ await writeFile(path.join(f.profile, 'system.json'), '{}')+ vi.clearAllMocks()+ await expect(probeLegacySource(f.source)).resolves.toBeUndefined()+ expect(open).not.toHaveBeenCalled()+ await expect(scanLegacySource(f.source, () => false)).rejects.toThrow(+ 'legacyImport.invalidSource'+ )+ })++ it.each(metadata)('rejects a missing required file: %s', async (name) => {+ const f = await fixture()+ await rm(path.join(f.profile, name))+ await expect(probeLegacySource(f.source)).rejects.toThrow(+ 'legacyImport.invalidSource'+ )+ })++ it.each(metadata)('rejects a symlinked required file: %s', async (name) => {+ const f = await fixture()+ const outside = path.join(f.root, 'outside')+ await writeFile(outside, '{}')+ await rm(path.join(f.profile, name))+ await symlink(outside, path.join(f.profile, name))+ await expect(probeLegacySource(f.source)).rejects.toThrow(+ 'legacyImport.unsafeSource'+ )+ })++ it('rejects hard-linked and oversized metadata without opening it', async () => {+ const f = await fixture()+ const filename = path.join(f.profile, 'download.session')+ const alias = path.join(f.root, 'alias')+ await link(filename, alias)+ await expect(probeLegacySource(f.source)).rejects.toThrow(+ 'legacyImport.unsafeSource'+ )+ await rm(alias)+ await truncate(filename, MAX_LEGACY_BYTES + 1)+ vi.clearAllMocks()+ await expect(probeLegacySource(f.source)).rejects.toThrow(+ 'legacyImport.unsafeSource'+ )+ expect(open).not.toHaveBeenCalled()+ })++ it('rejects a replacement directory behind an existing grant', async () => {+ const f = await fixture()+ await rename(f.profile, path.join(f.root, 'original'))+ await mkdir(f.profile)+ await expect(probeLegacySource(f.source)).rejects.toThrow(+ 'legacyImport.changedSource'+ )+ })+})diff --git a/src/core/legacy-import/source-scanner.ts b/src/core/legacy-import/source-scanner.tsnew file mode 100644index 00000000..a4f0441e--- /dev/null+++ b/src/core/legacy-import/source-scanner.ts@@ -0,0 +1,521 @@+import { createHash } from 'node:crypto'+import { constants } from 'node:fs'+import { lstat, open, realpath } from 'node:fs/promises'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { analyzeDownloadSource } from '@shared/lib/download-source'+import { projectTorrentMeta } from '@shared/lib/torrent-meta'+import type { LegacyImportItem } from '@shared/schemas/legacy-import'+import type { TorrentMeta } from '@shared/types/torrent'+import parseTorrent from 'parse-torrent'+import { parseBtFileLayout } from '../task/bt-storage-layout'+import {+ digestBytes,+ type LegacySessionEntry,+ MAX_LEGACY_BYTES,+ parseLegacySession,+ safeLegacyComponent,+ safeLegacyDirectory,+ safeLegacyOutput,+ validateLegacyBencode,+} from './session-parser'++export interface LegacySource {+ root: string+ identity: string+}+export interface LegacySnapshotFile {+ relativePath: string+ bytes: Buffer+ digest: string+ identity?: string+}+/** An exact user-selected file; it never authorizes other files in its parent. */+export interface LegacyTorrentGrant {+ source: LegacySource+ relativePath: string+ identity: string+ digest: string+ referencePath: string+}+export interface LegacyCandidate {+ item: LegacyImportItem+ entry: LegacySessionEntry+ outputPath: string | null+ torrent: TorrentMeta | null+ torrentRelativePath: string | null+ torrentReferencePath?: string+ selectedFiles: number[]+ selectionKnown: boolean+ trackers: string[][]+}+export interface LegacySnapshot {+ source: LegacySource+ sourceId: string+ digest: string+ files: LegacySnapshotFile[]+ candidates: LegacyCandidate[]+ running: boolean+}++export async function authorizeLegacySource(+ selectedRoot: string+): Promise<LegacySource> {+ const root = await realpath(selectedRoot)+ const stat = await lstat(root)+ if (!stat.isDirectory()) throw new Error('legacyImport.invalidSource')+ return { root, identity: `${stat.dev}:${stat.ino}` }+}++/** Recognize a profile with fixed metadata stats; content validation belongs to scan. */+export async function probeLegacySource(source: LegacySource): Promise<void> {+ const checkRoot = async () => {+ const root = await lstat(source.root)+ if (+ !root.isDirectory() ||+ root.isSymbolicLink() ||+ `${root.dev}:${root.ino}` !== source.identity+ )+ throw new Error('legacyImport.changedSource')+ }+ try {+ await checkRoot()+ for (const name of ['user.json', 'system.json', 'download.session']) {+ const file = await lstat(path.join(source.root, name))+ if (+ !file.isFile() ||+ file.isSymbolicLink() ||+ file.nlink !== 1 ||+ file.size > MAX_LEGACY_BYTES+ )+ throw new Error('legacyImport.unsafeSource')+ }+ // The metadata checks do not grant a replacement directory at this path.+ await checkRoot()+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')+ throw new Error('legacyImport.invalidSource')+ throw error+ }+}++/** Fixed metadata reads only; payloads and control files outside this grant are never opened. */+export async function readLegacyFile(+ source: LegacySource,+ relativePath: string,+ optional = false+): Promise<LegacySnapshotFile | null> {+ const parts = relativePath.split(/[\\/]/)+ if (+ path.isAbsolute(relativePath) ||+ parts.some((part) => !part || part === '.' || part === '..')+ )+ throw new Error('legacyImport.unsafeSource')+ const root = await lstat(source.root)+ if (+ !root.isDirectory() ||+ root.isSymbolicLink() ||+ `${root.dev}:${root.ino}` !== source.identity+ )+ throw new Error('legacyImport.changedSource')+ let candidatePath = source.root+ try {+ for (const part of parts.slice(0, -1)) {+ candidatePath = path.join(candidatePath, part)+ const stat = await lstat(candidatePath)+ if (!stat.isDirectory() || stat.isSymbolicLink())+ throw new Error('legacyImport.unsafeSource')+ }+ const filename = path.join(source.root, ...parts)+ const before = await lstat(filename)+ if (+ !before.isFile() ||+ before.isSymbolicLink() ||+ before.nlink !== 1 ||+ before.size > MAX_LEGACY_BYTES+ )+ throw new Error('legacyImport.unsafeSource')+ const handle = await open(+ filename,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)+ )+ try {+ const opened = await handle.stat()+ if (+ opened.dev !== before.dev ||+ opened.ino !== before.ino ||+ opened.nlink !== 1 ||+ !opened.isFile() ||+ opened.size > MAX_LEGACY_BYTES+ )+ throw new Error('legacyImport.changedSource')+ const bytes = Buffer.alloc(opened.size + 1)+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0)+ const after = await handle.stat()+ if (+ bytesRead !== opened.size ||+ after.size !== opened.size ||+ after.mtimeMs !== opened.mtimeMs ||+ after.ctimeMs !== opened.ctimeMs+ )+ throw new Error('legacyImport.changedSource')+ const content = bytes.subarray(0, bytesRead)+ return {+ relativePath,+ bytes: content,+ digest: digestBytes(content),+ identity: `${opened.dev}:${opened.ino}`,+ }+ } finally {+ await handle.close()+ }+ } catch (error) {+ if (optional && (error as NodeJS.ErrnoException).code === 'ENOENT')+ return null+ throw error+ }+}++export async function authorizeLegacyTorrent(+ selectedFile: string,+ referencePath: string+): Promise<LegacyTorrentGrant> {+ const selected = path.resolve(selectedFile)+ const before = await lstat(selected)+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1)+ throw new Error('legacyImport.unsafeSource')+ const canonical = await realpath(selected)+ const source = await authorizeLegacySource(path.dirname(canonical))+ const relativePath = path.basename(canonical)+ const file = await readLegacyFile(source, relativePath)+ if (!file || file.identity !== `${before.dev}:${before.ino}`)+ throw new Error('legacyImport.changedSource')+ try {+ validateLegacyBencode(file.bytes)+ const parsed = await parseTorrent(new Uint8Array(file.bytes))+ const torrent = projectTorrentMeta(parsed)+ await parseBtFileLayout(file.bytes)+ if (+ !torrent.files.length ||+ torrent.files.length > 10000 ||+ !safeLegacyComponent(torrent.name)+ )+ throw new Error('invalid')+ } catch {+ throw new Error('legacyImport.metadataMismatch')+ }+ const expected = /^([a-f\d]{40})\.torrent$/i.exec(+ path.basename(referencePath)+ )+ if (expected) {+ if (+ createHash('sha1').update(file.bytes).digest('hex') !==+ expected[1].toLowerCase()+ )+ throw new Error('legacyImport.metadataMismatch')+ } else if (canonical !== path.resolve(referencePath)) {+ // A human filename has no durable content identifier. Only the exact+ // referenced file can be explicitly authorized; arbitrary replacements+ // cannot be proved to describe the old task.+ throw new Error('legacyImport.metadataMismatch')+ }+ return {+ source,+ relativePath,+ identity: file.identity,+ digest: file.digest,+ referencePath,+ }+}++export async function isLegacyTorrentGrantValid(+ grant: LegacyTorrentGrant+): Promise<boolean> {+ try {+ const file = await readLegacyFile(grant.source, grant.relativePath)+ return file?.identity === grant.identity && file.digest === grant.digest+ } catch {+ return false+ }+}++async function readGrantedTorrent(+ grant: LegacyTorrentGrant,+ entryDigest: string,+ referencePath: string+): Promise<LegacySnapshotFile> {+ if (grant.referencePath !== referencePath)+ throw new Error('legacyImport.changedSource')+ const file = await readLegacyFile(grant.source, grant.relativePath)+ if (!file || file.identity !== grant.identity || file.digest !== grant.digest)+ throw new Error('legacyImport.changedSource')+ return { ...file, relativePath: `authorized-torrents/${entryDigest}.torrent` }+}++function parseObject(file: LegacySnapshotFile): Record<string, unknown> {+ const value: unknown = JSON.parse(file.bytes.toString('utf8'))+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new Error('legacyImport.invalidSource')+ return value as Record<string, unknown>+}++function selection(+ value: string | undefined,+ count: number+): { files: number[]; known: boolean } {+ if (!value) return { files: [], known: false }+ const result = new Set<number>()+ for (const range of value.split(',')) {+ const match = /^(\d+)(?:-(\d+))?$/.exec(range)+ if (!match) throw new Error('legacyImport.invalidSource')+ const start = Number(match[1])+ const end = Number(match[2] ?? match[1])+ if (start < 1 || end < start || end > count || end - start > 10000)+ throw new Error('legacyImport.invalidSource')+ for (let index = start; index <= end; index++) result.add(index - 1)+ }+ return { files: [...result].sort((a, b) => a - b), known: true }+}++export async function scanLegacySource(+ source: LegacySource,+ isProcessRunning: (pid: number) => boolean | Promise<boolean>,+ torrentGrants: ReadonlyMap<string, LegacyTorrentGrant> = new Map()+): Promise<LegacySnapshot> {+ const files: LegacySnapshotFile[] = []+ const required = async (name: string) => {+ const file = await readLegacyFile(source, name)+ if (!file) throw new Error('legacyImport.invalidSource')+ files.push(file)+ return file+ }+ const user = parseObject(await required('user.json'))+ const system = parseObject(await required('system.json'))+ if (+ typeof system.dir !== 'string' ||+ !('theme' in user || 'locale' in user || 'auto-resume-all' in user)+ )+ throw new Error('legacyImport.invalidSource')+ const session = await required('download.session')+ const pidFile = await readLegacyFile(source, 'engine.pid', true)+ if (pidFile) files.push(pidFile)+ const pid = pidFile ? Number(pidFile.bytes.toString('utf8').trim()) : null+ const running =+ pid !== null &&+ Number.isSafeInteger(pid) &&+ pid > 0 &&+ (await isProcessRunning(pid))+ const candidates: LegacyCandidate[] = []+ 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 item: LegacyImportItem = {+ itemId: entry.itemKey,+ name: entry.options.out || '—',+ saveDir: safeLegacyDirectory(entry.options.dir ?? (system.dir as string)),+ type: 'unknown',+ selectable: true,+ reason: 'fresh-download-required',+ }+ const candidate: LegacyCandidate = {+ item,+ entry,+ outputPath: null,+ torrent: null,+ torrentRelativePath: null,+ selectedFiles: [],+ selectionKnown: false,+ trackers: [],+ }+ candidates.push(candidate)+ try {+ if (entry.reason) {+ item.selectable = false+ item.reason = entry.reason+ continue+ }+ const first = entry.uris[0]+ if (!first) throw new Error('invalid')+ const dir = entry.options.dir ?? (system.dir as string)+ if (first.startsWith('magnet:?')) {+ const analysis = analyzeDownloadSource(first)+ if (+ entry.uris.length !== 1 ||+ analysis.status !== 'accepted' ||+ analysis.protocol !== 'magnet'+ )+ throw new Error('invalid')+ item.type = 'magnet'+ const url = new URL(first)+ item.name = entry.options.out || url.searchParams.get('dn') || 'Magnet'+ candidate.outputPath = safeLegacyOutput(dir, item.name)+ item.reason = 'metadata-required'+ } else if (/^https?:\/\//i.test(first)) {+ if (+ entry.uris.some((uri) => {+ const analysis = analyzeDownloadSource(uri)+ return (+ analysis.status !== 'accepted' ||+ !['http', 'https'].includes(analysis.protocol) ||+ Boolean(new URL(uri).username || new URL(uri).password)+ )+ })+ )+ 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 ||+ decodeURIComponent(+ new URL(first).pathname.split('/').at(-1) || 'download'+ )+ candidate.outputPath = safeLegacyOutput(dir, item.name)+ item.reason = 'fresh-download-required'+ } else {+ const filename = first.startsWith('file:')+ ? fileURLToPath(first)+ : first+ const resolved = path.isAbsolute(filename)+ ? path.resolve(filename)+ : path.resolve(source.root, filename)+ candidate.torrentReferencePath = resolved+ let relative = path.relative(source.root, resolved)+ if (entry.uris.length !== 1 || !relative.endsWith('.torrent'))+ throw new Error('unsafe')+ const outsideGrant =+ !relative || relative.startsWith('..') || path.isAbsolute(relative)+ const explicitGrant = torrentGrants.get(entry.digest)+ if (outsideGrant && !explicitGrant) {+ // The session often references RPC-saved metadata in the user's+ // separate downloads directory. That path does not grant access.+ item.type = 'bt'+ item.name = entry.options.out || path.basename(filename)+ item.selectable = false+ item.reason = 'metadata-required'+ continue+ }+ let file = torrentByPath.get(relative)+ if (!file) {+ file = explicitGrant+ ? await readGrantedTorrent(explicitGrant, entry.digest, resolved)+ : ((await readLegacyFile(source, relative)) ?? undefined)+ if (!file) throw new Error('invalid')+ relative = file.relativePath+ snapshotBytes += file.bytes.length+ if (snapshotBytes > 64 * 1024 * 1024)+ throw new Error('legacyImport.tooLarge')+ files.push(file)+ torrentByPath.set(relative, file)+ }+ validateLegacyBencode(file.bytes)+ const parsed = await parseTorrent(new Uint8Array(file.bytes))+ const torrent = projectTorrentMeta(parsed)+ await parseBtFileLayout(file.bytes)+ if (+ torrent.files.length < 1 ||+ torrent.files.length > 10000 ||+ !safeLegacyComponent(torrent.name) ||+ !Number.isSafeInteger(torrent.totalSize)+ )+ throw new Error('unsafe')+ const selected = selection(+ entry.options['select-file'],+ torrent.files.length+ )+ candidate.torrent = torrent+ candidate.torrentRelativePath = relative+ candidate.selectedFiles = selected.files+ candidate.selectionKnown = selected.known+ const additionalTrackers = entry.optionPairs+ .filter(([key]) => key === 'bt-tracker')+ .flatMap(([, value]) => value.split(',').filter(Boolean))+ candidate.trackers = [+ ...new Set([...(parsed.announce ?? []), ...additionalTrackers]),+ ].map((tracker) => [tracker])+ item.type = 'bt'+ item.name = entry.options.out || torrent.name+ candidate.outputPath = safeLegacyOutput(dir, item.name)+ item.reason = selected.known+ ? 'verification-required'+ : 'selection-required'+ }+ if (!candidate.outputPath) {+ item.reason = 'unsafe-path'+ item.selectable = false+ }+ if (!entry.gid && candidate.outputPath) {+ // Pause, limits, selection and other mutable session options are not+ // task identity. Keep deletion tombstones stable across ordinary saves.+ const content =+ candidate.torrent?.infoHash ??+ (item.type === 'magnet'+ ? new URL(first).searchParams+ .getAll('xt')+ .map((value) => value.toLowerCase())+ .sort()+ : [...entry.uris].sort())+ entry.itemKey = `entry:${digestBytes(JSON.stringify([item.type, candidate.outputPath, content]))}`+ if (!torrentGrants.has(entry.digest)) item.itemId = entry.itemKey+ }+ } catch (error) {+ if (error instanceof Error && error.message === 'legacyImport.tooLarge')+ throw error+ if (torrentGrants.has(entry.digest))+ throw new Error('legacyImport.changedSource')+ item.reason = 'invalid-record'+ item.selectable = false+ }+ }+ const groups = new Map<string, LegacyCandidate[]>()+ for (const candidate of candidates) {+ const group = groups.get(candidate.entry.itemKey) ?? []+ group.push(candidate)+ groups.set(candidate.entry.itemKey, group)+ }+ for (const group of groups.values()) {+ if (group.length < 2) continue+ group.forEach((candidate, index) => {+ candidate.item.selectable = false+ candidate.item.reason = 'invalid-record'+ candidate.item.itemId = `${candidate.entry.itemKey}:duplicate:${index}`+ })+ }+ const sourceId = digestBytes(`${source.root}\0${source.identity}`)+ const digest = digestBytes(+ files+ .map(+ (file) => `${file.relativePath}\0${file.digest}\0${file.identity ?? ''}`+ )+ .sort()+ .join('\n')+ )+ return { source, sourceId, digest, files, candidates, running }+}diff --git a/src/core/legacy-import/v1-generated-fixtures.test.ts b/src/core/legacy-import/v1-generated-fixtures.test.tsnew file mode 100644index 00000000..471ee0a5--- /dev/null+++ b/src/core/legacy-import/v1-generated-fixtures.test.ts@@ -0,0 +1,174 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import {+ cp,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { gunzipSync } from 'node:zlib'+import { afterEach, describe, expect, it } from 'vitest'+import { parseLegacySession } from './session-parser'+import { authorizeLegacySource, scanLegacySource } from './source-scanner'++const fixtureRoot = fileURLToPath(+ new URL('../../../tests/fixtures/legacy-v1/generated/', import.meta.url)+)+const roots: string[] = []+const hash = (value: Uint8Array) =>+ createHash('sha256').update(value).digest('hex')++async function stagedFixture(withinGrant = false) {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-v1-fixture-test-'))+ )+ roots.push(root)+ await cp(fixtureRoot, root, { recursive: true })+ const profile = path.join(root, 'profile')+ const downloads = withinGrant+ ? path.join(profile, 'downloads')+ : path.join(root, 'downloads')+ if (withinGrant)+ await cp(path.join(root, 'downloads'), downloads, { recursive: true })+ for (const name of ['download.session', 'system.json']) {+ const file = path.join(profile, name)+ const text = await readFile(file, 'utf8')+ await writeFile(+ file,+ text+ .replaceAll('__FIXTURE_ROOT__', profile)+ .replaceAll('__FIXTURE_DOWNLOADS__', downloads)+ .replaceAll('__FIXTURE_HTTP_PORT__', '18080')+ )+ }+ return {+ root,+ profile,+ downloads,+ source: await authorizeLegacySource(profile),+ }+}++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))+ )+})++describe('Motrix v1.8.19 bundled-engine generated fixtures', () => {+ it('pins binary provenance and verifies unchanged control/torrent bytes', async () => {+ const provenance = JSON.parse(+ await readFile(path.join(fixtureRoot, 'provenance.json'), 'utf8')+ )+ expect(provenance).toMatchObject({+ tag: 'v1.8.19',+ commit: 'a0a1fe90f7e9f6d305ed2b512f62c8d36c2fb95a',+ binarySha256:+ '1527c4d071c16c1266880e93750e385cdd4e9d2a950d7f56cb5a21125e3bd311',+ binaryGitObject: 'f4a274061acbbc22c6eb1ab487ffdc0e80ad1b71',+ version: 'aria2 version 1.36.0',+ })+ for (const file of provenance.files) {+ const bytes = await readFile(path.join(fixtureRoot, file.path))+ expect(bytes.length).toBe(file.bytes)+ expect(hash(bytes)).toBe(file.sha256)+ if (file.path.endsWith('.aria2')) expect(bytes.readUInt16BE(0)).toBe(1)+ }+ const partial = gunzipSync(+ await readFile(path.join(fixtureRoot, provenance.http.savedPayloadGzip))+ )+ expect(partial.length).toBe(provenance.http.savedPayloadBytes)+ expect(hash(partial)).toBe(provenance.http.savedPayloadSha256)+ expect(+ Number(provenance.http.completedLengthAtPauseRequest)+ ).toBeGreaterThan(1024 * 1024)+ expect(partial.length).toBeLessThan(Number(provenance.http.totalLength))+ })++ it('accepts actual v1 serialization with documented isolation overrides, pauses and trailing mirror TAB', async () => {+ const { profile } = await stagedFixture()+ const entries = parseLegacySession(+ await readFile(path.join(profile, 'download.session'))+ )+ expect(entries).toHaveLength(3)+ expect(entries.every((entry) => entry.reason === null)).toBe(true)+ const http = entries.find((entry) => entry.gid === '0123456789abcdef')+ expect(http?.uris).toEqual([+ 'http://127.0.0.1:18080/partial.bin',+ 'http://127.0.0.1:18080/mirror.bin',+ ])+ expect(http?.options).toMatchObject({+ pause: 'true',+ 'no-netrc': 'true',+ 'follow-torrent': 'true',+ 'follow-metalink': 'true',+ 'bt-load-saved-metadata': 'true',+ })+ expect(http?.optionPairs.some(([key]) => key === 'user-agent')).toBe(true)+ })++ it('recognizes external saved torrent metadata without reading outside the profile grant', async () => {+ const { source, downloads } = await stagedFixture()+ const scan = await scanLegacySource(source, async () => false)+ const bt = scan.candidates.find(+ (candidate) => candidate.entry.gid === 'fedcba9876543210'+ )+ expect(bt?.item).toMatchObject({+ type: 'bt',+ selectable: false,+ reason: 'metadata-required',+ })+ expect(bt?.torrent).toBeNull()+ expect(bt?.torrentRelativePath).toBeNull()+ expect(scan.files.map((file) => file.relativePath).sort()).toEqual([+ 'download.session',+ 'system.json',+ 'user.json',+ ])+ // Even removed metadata does not make a scan dereference the external path.+ await rm(downloads, { recursive: true })+ const rescan = await scanLegacySource(source, () => false)+ expect(+ rescan.candidates.find((candidate) => candidate.item.type === 'bt')?.item+ .reason+ ).toBe('metadata-required')+ expect(+ scan.candidates.find((candidate) => candidate.item.type === 'http')?.item+ .selectable+ ).toBe(true)+ })++ it('parses retained private torrent bytes and one-based selection when metadata is explicitly staged inside the grant', async () => {+ // This is a labeled grant variant, not the original generated directory layout.+ const { source } = await stagedFixture(true)+ const scan = await scanLegacySource(source, () => false)+ const bt = scan.candidates.find(+ (candidate) => candidate.entry.gid === 'fedcba9876543210'+ )+ expect(bt?.item).toMatchObject({+ name: 'fixture-bundle',+ type: 'bt',+ selectable: true,+ reason: 'verification-required',+ })+ expect(bt?.torrent?.files).toHaveLength(2)+ expect(bt?.selectedFiles).toEqual([0])+ expect(bt?.selectionKnown).toBe(true)+ expect(bt?.trackers[0]?.[0]).toMatch(+ /^http:\/\/127\.0\.0\.1:\d+\/announce$/+ )+ expect(bt?.torrentRelativePath).toMatch(/^downloads\/[a-f\d]{40}\.torrent$/)+ const provenance = JSON.parse(+ await readFile(path.join(fixtureRoot, 'provenance.json'), 'utf8')+ )+ expect(bt?.torrent?.infoHash).toBe(provenance.bt.infoHash)+ expect(path.basename(bt?.torrentRelativePath ?? '', '.torrent')).not.toBe(+ provenance.bt.infoHash+ )+ })+})diff --git a/src/core/session/migrations/index.ts b/src/core/session/migrations/index.tsindex b8b26b54..76510607 100644--- a/src/core/session/migrations/index.ts+++ b/src/core/session/migrations/index.ts@@ -11,6 +11,7 @@ import { V4_SCHEMA_OBJECTS, v4 } from './v4'import { V5_TASK_SCHEMA_OBJECTS, v5 } from './v5'import { V6_SCHEMA_OBJECTS, v6 } from './v6'import { V7_SCHEMA_OBJECTS, v7 } from './v7'+import { V8_SCHEMA_OBJECTS, v8 } from './v8'interface Migration {version: number@@ -27,7 +28,7 @@ interface Migration {// persists the user-selected save directory independently of engine paths and// repairs stale instance statuses beneath terminal tasks. v6 adds independent// seeding-time counters without inventing pre-upgrade history.-const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6, v7]+const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6, v7, v8]const HIGHEST_KNOWN_VERSION = MIGRATIONS.reduce((max, m) => (m.version > max ? m.version : max),@@ -213,7 +214,10 @@ function hasExactCanonicalTaskSchema(return false}- const expectedNames = new Set(objects.map((object) => object.name))+ const expectedNames = new Set([+ ...objects.map((object) => object.name),+ 'legacy_import_delete_tombstone',+ ])const explicitIndexesAndTriggers = db.prepare(`SELECT name@@ -285,6 +289,9 @@ function validateCanonicalTaskAndActivitySchema(db: Database.Database): void {}function validateCanonicalSchema(db: Database.Database): void {+ if (!hasExactSchemaObjects(db, V8_SCHEMA_OBJECTS)) {+ throw new StaleSchemaError('task_tracker_schema_missing', db.name)+ }if (!hasExactSchemaObjects(db, V7_SCHEMA_OBJECTS) ||!hasNoExplicitIndexesOrTriggers(db, ['task_tracker_state'])diff --git a/src/core/session/migrations/v1.test.ts b/src/core/session/migrations/v1.test.tsindex b0abf3dd..ccd4deca 100644--- a/src/core/session/migrations/v1.test.ts+++ b/src/core/session/migrations/v1.test.ts@@ -468,7 +468,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {version INTEGER PRIMARY KEY,applied_at INTEGER NOT NULL);- INSERT INTO schema_version (version, applied_at) VALUES (8, 0);+ INSERT INTO schema_version (version, applied_at) VALUES (9, 0);CREATE TABLE task_metadata (motrix_id TEXT PRIMARY KEY);`)@@ -524,7 +524,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {const rows = db.prepare('SELECT version FROM schema_version ORDER BY version').all() as Array<{ version: number }>- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7])+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8])db.close()})@@ -543,7 +543,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {// Inspector Activity persistence, and v4 adds durable Hook delivery and// finalize journals. V5 repairs terminal instances and v6 tracks seeding time.// All apply on a fresh DB.- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7])+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8])const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'")diff --git a/src/core/session/migrations/v3.test.ts b/src/core/session/migrations/v3.test.tsindex 8dd90278..ef344006 100644--- a/src/core/session/migrations/v3.test.ts+++ b/src/core/session/migrations/v3.test.ts@@ -110,7 +110,7 @@ describe('migration v3 compatibility', () => {const db = openMemory()migrate(db)- expect(readVersion(db)).toBe(7)+ expect(readVersion(db)).toBe(8)const names = db.prepare(`SELECT name FROM sqlite_master@@ -166,7 +166,7 @@ describe('migration v3 compatibility', () => {const reopened = new Database(dbPath)reopened.pragma('foreign_keys = ON')- expect(readVersion(reopened)).toBe(7)+ expect(readVersion(reopened)).toBe(8)expect(reopened.prepare("SELECT motrix_id FROM tasks WHERE motrix_id = 'survivor'")@@ -207,7 +207,7 @@ describe('migration v3 compatibility', () => {})()expect(() => migrate(db)).not.toThrow()- expect(readVersion(db)).toBe(7)+ expect(readVersion(db)).toBe(8)db.close()})diff --git a/src/core/session/migrations/v4.test.ts b/src/core/session/migrations/v4.test.tsindex 1e6036bb..20797f85 100644--- a/src/core/session/migrations/v4.test.ts+++ b/src/core/session/migrations/v4.test.ts@@ -40,7 +40,7 @@ describe('migration v4', () => {const db = openMemory()migrate(db)- expect(readVersion(db)).toBe(7)+ expect(readVersion(db)).toBe(8)const rows = db.prepare(`SELECT name FROM sqlite_master@@ -68,7 +68,7 @@ describe('migration v4', () => {migrate(db)- expect(readVersion(db)).toBe(7)+ expect(readVersion(db)).toBe(8)expect(db.prepare("SELECT name FROM tasks WHERE motrix_id = 'survivor'").get()).toEqual({ name: 'fixture' })diff --git a/src/core/session/migrations/v5.test.ts b/src/core/session/migrations/v5.test.tsindex 4971c22a..0f532255 100644--- a/src/core/session/migrations/v5.test.ts+++ b/src/core/session/migrations/v5.test.ts@@ -111,7 +111,7 @@ describe('task recovery migration v5', () => {expect(db.prepare('SELECT total_changes() AS count').get()).toEqual(changes)expect(db.prepare('SELECT version FROM schema_version ORDER BY version').all()- ).toEqual([1, 2, 3, 4, 5, 6, 7].map((version) => ({ version })))+ ).toEqual([1, 2, 3, 4, 5, 6, 7, 8].map((version) => ({ version })))db.close()})})diff --git a/src/core/session/migrations/v8.ts b/src/core/session/migrations/v8.tsnew file mode 100644index 00000000..6a917e31--- /dev/null+++ b/src/core/session/migrations/v8.ts@@ -0,0 +1,59 @@+import type Database from 'better-sqlite3'+import type { SchemaObjectDefinition } from './v1'++export const V8_SCHEMA_OBJECTS: readonly SchemaObjectDefinition[] = [+ {+ name: 'legacy_import_runs',+ sql: `CREATE TABLE legacy_import_runs (+ run_id TEXT PRIMARY KEY NOT NULL,+ source_id TEXT NOT NULL,+ snapshot_digest TEXT NOT NULL,+ backup_path TEXT,+ report TEXT NOT NULL CHECK (json_valid(report)),+ created_at INTEGER NOT NULL+ )`,+ },+ {+ name: 'legacy_import_items',+ sql: `CREATE TABLE legacy_import_items (+ run_id TEXT NOT NULL,+ item_key TEXT NOT NULL,+ outcome TEXT NOT NULL CHECK (outcome IN ('imported', 'skipped', 'failed', 'unprocessed')),+ task_id TEXT,+ PRIMARY KEY (run_id, item_key),+ FOREIGN KEY (run_id) REFERENCES legacy_import_runs(run_id) ON DELETE CASCADE+ ) WITHOUT ROWID`,+ },+ {+ name: 'legacy_import_ledger',+ sql: `CREATE TABLE legacy_import_ledger (+ source_id TEXT NOT NULL,+ item_key TEXT NOT NULL,+ entry_digest TEXT NOT NULL,+ task_id TEXT NOT NULL,+ state TEXT NOT NULL CHECK (state IN ('imported', 'user-deleted')),+ PRIMARY KEY (source_id, item_key)+ ) WITHOUT ROWID`,+ },+ {+ name: 'legacy_import_invitation',+ sql: `CREATE TABLE legacy_import_invitation (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ dismissed INTEGER NOT NULL CHECK (dismissed IN (0, 1))+ )`,+ },+ {+ name: 'legacy_import_delete_tombstone',+ sql: `CREATE TRIGGER legacy_import_delete_tombstone BEFORE DELETE ON tasks BEGIN+ UPDATE legacy_import_ledger SET state = 'user-deleted' WHERE task_id = OLD.motrix_id;+ END`,+ },+]++export const v8 = {+ version: 8,+ up(db: Database.Database): void {+ for (const object of V8_SCHEMA_OBJECTS) db.exec(object.sql)+ db.prepare('INSERT INTO legacy_import_invitation VALUES (1, 0)').run()+ },+}diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.tsindex 09c79ef3..34ca85da 100644--- a/src/core/session/motrix-database.ts+++ b/src/core/session/motrix-database.ts@@ -612,6 +612,23 @@ export class MotrixDatabase {this.lastPersistedSig.set(payload.task.motrixId, signature)}+ /** Publish paused import graphs and their durable ledger in one transaction. */+ saveLegacyImportBatch(+ graphs: TaskWithInstancesAndFiles[],+ writeLedger: () => void+ ): void {+ this.db.transaction(() => {+ for (const graph of graphs) {+ this.writeRow(graph)+ this.writeTaskFiles(graph.task.motrixId, graph.files)+ }+ writeLedger()+ })()+ for (const graph of graphs) {+ this.lastPersistedSig.set(graph.task.motrixId, this.rowSignature(graph))+ }+ }+saveTasksBatch(payloads: TaskWithInstances[]): void {const tx = this.db.transaction((rows: TaskWithInstances[]) => {for (const row of rows) {diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 3d235d28..3c1cd95b 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -4499,3 +4499,33 @@ it('restores an existing paused direct BT download with internal engine metadatafs.rmSync(root, { recursive: true, force: true })}})++it('quarantines a durable pending migration GID during restore and later authoritative polls', async () => {+ const manager = new TaskManager()+ const db = createMockDb()+ const gid = '1122334455667788'+ 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 },+ },+ })+ 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()+})diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 5f940d7a..f6450c4a 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -1,5 +1,9 @@import fs from 'node:fs'import path from 'node:path'+import {+ hasLegacyImport,+ isInactiveLegacyTask,+} from '@core/legacy-import/legacy-task-policy'import { newEngineTaskId, newTaskId } from '@core/lib/ids'import { getLogger } from '@core/logger'import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'@@ -14,6 +18,7 @@ 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,@@ -655,10 +660,30 @@ export class SessionManager {Array<{ motrixId: string; instance: TaskInstanceRow }>>()const tasksByInfoHash = new Map<string, TaskWithInstances[]>()+ const migrationGids = new Set<string>()for (const pair of persisted) {byMotrixId.set(pair.task.motrixId, pair)- if (pair.task.infoHash) {+ 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)+ }+ }+ if (isInactiveLegacyTask(pair)) continue+ if (pair.task.infoHash && !hasLegacyImport(pair)) {const infoHash = pair.task.infoHash.toLowerCase()const candidates = tasksByInfoHash.get(infoHash) ?? []candidates.push(pair)@@ -671,7 +696,7 @@ export class SessionManager {instance: inst,})}- if (inst.uriHash) {+ if (inst.uriHash && !hasLegacyImport(pair)) {const candidates = instancesByUriHash.get(inst.uriHash) ?? []candidates.push({motrixId: pair.task.motrixId,@@ -730,6 +755,7 @@ export class SessionManager {// Pass 1 — drive from aria2 rows.for (const aria2 of aria2Tasks) {+ if (migrationGids.has(aria2.gid)) continue// Media segments are ephemeral children of a coordinator task. Older// versions left them in aria2's durable store, so hide AND evict them;// skipping adoption alone made the restarted downloads invisible.@@ -813,6 +839,20 @@ export class SessionManager {consumedMotrixIds.add(parent.task.motrixId)continue}+ if (+ hasLegacyImport(parent) &&+ [TaskStatus.Completed, TaskStatus.Error].includes(+ parent.task.aggStatus+ )+ ) {+ // Native migration records restart paused. Durable terminal history+ // cannot be reopened by that replay. Retain the engine row for explicit+ // deletion, which verifies the full migration binding before cleanup.+ const task = taskRowToDownloadTask(parent.task, parent.instances)+ this.taskManager.set(task.id, task)+ consumedMotrixIds.add(parent.task.motrixId)+ continue+ }if (parent.task.aggStatus === TaskStatus.Error) {// Error is durable history and motrix.db owns it. An engine row// still carrying this GID is the engine's session store@@ -896,10 +936,29 @@ export class SessionManager {// • Anything else: aria2 truly lost the task; re-add (BT via// adapter.addTorrent with checkIntegrity, HTTP via createDownload).for (const pair of persisted) {+ if (isInactiveLegacyTask(pair)) {+ this.taskManager.set(+ pair.task.motrixId,+ taskRowToDownloadTask(pair.task, pair.instances)+ )+ continue+ }if (consumedMotrixIds.has(pair.task.motrixId)) continueif (pair.instances.some((i) => i.gid && aria2GidSet.has(i.gid))) continueconst primary = pair.instances[0]+ if (hasLegacyImport(pair)) {+ // A migrated task can be recovered only by its durable token/GID service.+ // Preserve its identity and originals when the engine loses its bound row.+ const task = taskRowToDownloadTask(pair.task, pair.instances)+ task.status = [TaskStatus.Completed, TaskStatus.Error].includes(+ pair.task.aggStatus+ )+ ? pair.task.aggStatus+ : TaskStatus.Paused+ this.taskManager.set(task.id, task)+ continue+ }const isHiddenMagnetTombstone = pair.instances.some(isMagnetCleanupTombstoneHidden)diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex 64b6879d..d0affce1 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -1,10 +1,16 @@import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import {+ hasLegacyImport,+ isInactiveLegacyTask,+} from '@core/legacy-import/legacy-task-policy'import { newEngineTaskId } from '@core/lib/ids'import type { HookAuditLog } from '@core/plugin/hooks/audit-log'import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'import { AppError, DownloadErrorCode, ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'+import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'import type {BeforeFinalizeContextDTO,PluginHookTask,@@ -94,6 +100,7 @@ export interface FinalizeTaskDeps {publishTaskUpdate: () => voidpublishTaskUpdateNow: () => voidadapter: {+ verifyLegacyBtBinding?: EngineAdapter['verifyLegacyBtBinding']removeDownloadResult(engineTaskId: string): Promise<void>forceRemoveTask(engineTaskId: string): Promise<void>getUploadLength(engineTaskId: string): Promise<number>@@ -190,6 +197,49 @@ async function finalizeTaskSerialized(const publishedTask = getTaskOrWarn(deps, taskId, 'finalizeTask')if (!publishedTask) returnconst task = structuredClone(publishedTask)+ if (hasLegacyImport(task)) {+ if (isInactiveLegacyTask(task)) return+ // An authorized in-place task never renames, deletes unselected files, or+ // creates a seeding replacement. Keep its original GID and provenance.+ const live = await deps.adapter.getTaskStatus(task.engineTaskId)+ if (+ !live ||+ live.status !== TaskStatus.Completed ||+ live.engineTaskId !== task.engineTaskId ||+ live.infoHash !== task.infoHash ||+ live.totalBytes <= 0 ||+ 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+ const previous = task.status+ Object.assign(task, applyTerminalTransition(task, TaskStatus.Completed))+ task.downloadedBytes = live.downloadedBytes+ task.totalBytes = live.totalBytes+ task.progress = 1+ for (const instance of task.instances)+ instance.status = TaskStatus.Completed+ await persistTaskTransition(task, previous, deps)+ deps.publishTaskUpdateNow()+ return+ }const alreadyOutputReady =getBtDirectStorageLayout(task)?.finalized !== false &&diff --git a/src/core/task/actions/pause-task.ts b/src/core/task/actions/pause-task.tsindex 8da8f54f..2d49dce7 100644--- a/src/core/task/actions/pause-task.ts+++ b/src/core/task/actions/pause-task.ts@@ -1,3 +1,4 @@+import { assertLegacyTaskNotActivated } from '@core/legacy-import/legacy-task-policy'import { TaskStatus } from '@shared/types/task'import {commitTaskUpdate,@@ -22,6 +23,7 @@ export async function pauseTask(): Promise<void> {const task = getTaskOrWarn(deps, taskId, 'pauseTask')if (!task) return+ assertLegacyTaskNotActivated(task)deps.onPauseRequested?.(taskId)const optimistic = {...task,diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 2baa5688..41d4525b 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -1,4 +1,5 @@import path from 'node:path'+import { assertLegacyTaskNotRecreated } from '@core/legacy-import/legacy-task-policy'import { newEngineTaskId } from '@core/lib/ids'import type { AppliedDownloadProxyPolicyReader } from '@core/proxy/applied-download-proxy-policy'import { admitDownloadSources } from '@core/task/source-admission'@@ -482,6 +483,7 @@ export async function reAddTask(deps: ReAddTaskDeps): Promise<void> {const task = deps.taskManager.getById(taskId)+ if (task) assertLegacyTaskNotRecreated(task)if (task &&(task.transitionPhase === TransitionPhase.Renaming ||diff --git a/src/core/task/actions/remove-task.ts b/src/core/task/actions/remove-task.tsindex 58187548..a59d46b1 100644--- a/src/core/task/actions/remove-task.ts+++ b/src/core/task/actions/remove-task.ts@@ -1,6 +1,8 @@import path from 'node:path'+import { 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'import {type DownloadTask,TaskInstancePhase,@@ -118,6 +120,74 @@ 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+ // 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 =+ typeof candidate?.engineTaskId === 'string' &&+ /^[a-f0-9]{16}$/.test(candidate.engineTaskId)+ ? candidate.engineTaskId+ : task.engineTaskId+ 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,+ }))+ )+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.activationUncertain'+ )+ if (!isStoppedTaskStatus(engine.status)) {+ try {+ await deps.adapter.forceRemoveTask(gid)+ } catch (error) {+ // Verification can finish between tellStatus and forceRemove. A+ // stopped row is purged directly; a live/unknown owner is retained.+ 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,+ })))+ )+ throw error+ }+ }+ await deps.adapter.removeDownloadResult(gid)+ }+ }+ await deleteParentBarrier(() => {+ deps.db.deleteTask(taskId)+ deps.taskManager.remove(taskId)+ })+ deps.publishTaskUpdate()+ return+ }+// Plan B Task 4: magnet metadata pending removal — delegate cleanup// to MagnetTracker which knows about the metadata temp dir and the// bounded-retry / quarantine state machine. Only delete the DB rowdiff --git a/src/core/task/actions/resume-task.ts b/src/core/task/actions/resume-task.tsindex d7a2d13c..bf2637c8 100644--- a/src/core/task/actions/resume-task.ts+++ b/src/core/task/actions/resume-task.ts@@ -1,3 +1,4 @@+import { assertLegacyTaskNotActivated } from '@core/legacy-import/legacy-task-policy'import { TaskStatus } from '@shared/types/task'import {commitTaskUpdate,@@ -24,6 +25,7 @@ export async function resumeTask(): Promise<void> {const task = getTaskOrWarn(deps, taskId, 'resumeTask')if (!task) return+ assertLegacyTaskNotActivated(task)deps.onResumeRequested?.(taskId)const optimistic = {...task,diff --git a/src/core/task/merge-engine-task.test.ts b/src/core/task/merge-engine-task.test.tsindex 819ed370..834d5845 100644--- a/src/core/task/merge-engine-task.test.ts+++ b/src/core/task/merge-engine-task.test.ts@@ -35,6 +35,25 @@ function instance(status: TaskStatus, index = 0): TaskInstance {}describe('mergeEngineTask', () => {+ it.each([TaskStatus.Completed, TaskStatus.Error])(+ 'preserves imported %s history against a late paused replay',+ (status) => {+ const primary = instance(status)+ primary.payload = { legacyImport: { version: 99 } }+ const existing = baseTask({+ status,+ progress: 1,+ finishedAt: 100,+ instances: [primary],+ })+ const late = baseTask({+ status: TaskStatus.Paused,+ progress: 0,+ finishedAt: null,+ })+ expect(mergeEngineTask(existing, late)).toBe(existing)+ }+ )it.each([['gid1', 25, 125],['gid1', 30, 130],diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex d589901d..6580ff57 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -1,3 +1,4 @@+import { hasLegacyImport } from '@core/legacy-import/legacy-task-policy'import type { DownloadTask } from '@shared/types/task'import { TaskStatus, TransitionPhase } from '@shared/types/task'import { shareRatio } from '@shared/utils/share-ratio'@@ -23,7 +24,9 @@ export function mergeEngineTask(// direct history. Explicit re-add changes ownership/state before merging.if (existing.engineTaskId === engineTask.engineTaskId &&- isCompletedDirectOutput(existing)+ (isCompletedDirectOutput(existing) ||+ (hasLegacyImport(existing) &&+ [TaskStatus.Completed, TaskStatus.Error].includes(existing.status)))) {return existing}@@ -87,7 +90,18 @@ export function mergeEngineTask(infoHash: protected_.infoHash ?? existing.infoHash,uris: protected_.uris.length > 0 ? protected_.uris : existing.uris,bt: bt- ? { ...bt, ratio: shareRatio(uploadedBytes, protected_.totalBytes) }+ ? {+ ...bt,+ ...(hasLegacyImport(existing)+ ? {+ isPrivate: existing.bt?.isPrivate ?? false,+ selectedFiles: existing.bt?.selectedFiles ?? [],+ announceList: existing.bt?.announceList ?? [],+ trackers: existing.bt?.trackers ?? [],+ }+ : {}),+ ratio: shareRatio(uploadedBytes, protected_.totalBytes),+ }: undefined,updatedAt: now,}diff --git a/src/core/task/set-selected-files.ts b/src/core/task/set-selected-files.tsindex 5ab8ee89..c1320b0d 100644--- a/src/core/task/set-selected-files.ts+++ b/src/core/task/set-selected-files.ts@@ -1,5 +1,6 @@import type { EngineAdapter } from '@core/engine/engine-adapter'import type { EventBus } from '@core/events/event-bus'+import { hasLegacyImport } from '@core/legacy-import/legacy-task-policy'import { getLogger } from '@core/logger'import type { MotrixDatabase } from '@core/session/motrix-database'import type { TaskManager } from '@core/task/task-manager'@@ -37,6 +38,11 @@ export function createSetSelectedFilesHandler(deps: Deps) {throw new AppError(ErrorCode.TaskNotFound, `Task ${taskId} not found`)}+ if (hasLegacyImport(task))+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.activationRequired'+ )await deps.engine.changeOption(task.engineTaskId, {'select-file': formatRange(indices),})diff --git a/src/core/task/should-skip-engine-completion-finalize.ts b/src/core/task/should-skip-engine-completion-finalize.tsindex a53eb362..a0e76be5 100644--- a/src/core/task/should-skip-engine-completion-finalize.ts+++ b/src/core/task/should-skip-engine-completion-finalize.ts@@ -1,3 +1,7 @@+import {+ hasLegacyImport,+ isInactiveLegacyTask,+} from '@core/legacy-import/legacy-task-policy'import type { DownloadTask } from '@shared/types/task'import { TaskStatus, TransitionPhase } from '@shared/types/task'import { getBtDirectStorageLayout } from './bt-storage-layout'@@ -16,6 +20,8 @@ import { getBtDirectStorageLayout } from './bt-storage-layout'export function shouldSkipEngineCompletionFinalize(task: DownloadTask): boolean {+ if (hasLegacyImport(task))+ return isInactiveLegacyTask(task) || task.status === TaskStatus.Completedreturn ((task.diskPath === task.finalPath &&getBtDirectStorageLayout(task)?.finalized !== false) ||diff --git a/src/core/task/task-manager.test.ts b/src/core/task/task-manager.test.tsindex 9f501f52..30eb08bf 100644--- a/src/core/task/task-manager.test.ts+++ b/src/core/task/task-manager.test.ts@@ -371,3 +371,113 @@ describe('TaskManager — multi-instance engineIndex (Plan A Task 9)', () => {expect(tm.isEngineTaskIdRetired(cleanedUpGid)).toBe(true)})})++it('quarantines durable migration GIDs after ordinary set consumes a transient reservation', () => {+ const manager = new TaskManager()+ const task = makeTask()+ const gid = '1122334455667788'+ task.engineTaskId = gid+ task.instances = [+ {+ instanceId: 'legacy-i',+ motrixId: task.id,+ gid,+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/old',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: 0,+ updatedAt: 0,+ },+ ]+ task.instances[0].payload = {+ legacyImport: { version: 99 },+ legacyBtActivation: { engineTaskId: gid },+ }+ manager.reserveEngineTaskId(gid)+ manager.set(task.id, task)+ expect(manager.isEngineTaskIdRetired(gid)).toBe(true)+ manager.clear()+ manager.set(task.id, task)+ expect(manager.isEngineTaskIdRetired(gid)).toBe(true)+ task.instances[0].payload = {}+ manager.set(task.id, task)+ expect(manager.isEngineTaskIdRetired(gid)).toBe(false)+ expect(manager.getByEngineTaskId(gid)?.id).toBe(task.id)+})++it('keeps deleted payload-only migration GIDs retired and refuses duplicate reservations', () => {+ const manager = new TaskManager()+ const gid = '1122334455667788'+ const task = makeTask({ engineTaskId: '' })+ task.instances = [+ {+ instanceId: 'pending',+ motrixId: task.id,+ gid: null,+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/old',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {+ legacyImport: { version: 99 },+ legacyBtActivation: { engineTaskId: gid },+ },+ createdAt: 0,+ updatedAt: 0,+ },+ ]+ manager.set(task.id, task)+ expect(() => manager.reserveEngineTaskId(gid)).toThrow('not available')+ manager.remove(task.id)+ expect(manager.isEngineTaskIdRetired(gid)).toBe(true)+ expect(() => manager.reserveEngineTaskId(gid)).toThrow('not available')+})+it('preserves the quarantine when either duplicated durable owner is removed', () => {+ const manager = new TaskManager()+ const gid = '1122334455667788'+ for (const id of ['owner-a', 'owner-b']) {+ const task = makeTask({ id, engineTaskId: '' })+ task.instances = [+ {+ instanceId: id,+ motrixId: id,+ gid: null,+ phase: TaskInstancePhase.BtDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/old',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {+ legacyImport: { version: 99 },+ legacyBtActivation: { engineTaskId: gid },+ },+ createdAt: 0,+ updatedAt: 0,+ },+ ]+ manager.set(id, task)+ }+ manager.remove('owner-b')+ expect(manager.getById('owner-a')).toBeDefined()+ expect(manager.isEngineTaskIdRetired(gid)).toBe(true)+ expect(() => manager.reserveEngineTaskId(gid)).toThrow('not available')+})diff --git a/src/core/task/task-manager.ts b/src/core/task/task-manager.tsindex 3d8402e0..9d8c84d0 100644--- a/src/core/task/task-manager.ts+++ b/src/core/task/task-manager.ts@@ -1,3 +1,4 @@+import { getLegacyQuarantinedGids } from '@core/legacy-import/legacy-task-policy'import type { DownloadTask } from '@shared/types/task'import { normalizeTerminalRuntimeMetrics } from './normalize-terminal-runtime-metrics'import { collectTaskGids } from './task-instance'@@ -5,6 +6,8 @@ import { collectTaskGids } from './task-instance'const MAX_RETIRED_ENGINE_GIDS = 4_096export class TaskManager {+ private legacyGidOwners = new Map<string, Set<string>>()+ private indexedLegacyGids = new Map<string, Set<string>>()private tasks = new Map<string, DownloadTask>()// Secondary index: every instance gid (and the legacy engineTaskId for// back-compat) maps to the parent task's motrixId. Multi-instance tasks@@ -40,6 +43,12 @@ export class TaskManager {// set(), so the "existing" object may already contain the new gid and can// no longer tell us which old keys it contributed.private deindex(id: string): void {+ for (const gid of this.indexedLegacyGids.get(id) ?? []) {+ const owners = this.legacyGidOwners.get(gid)+ owners?.delete(id)+ if (owners?.size === 0) this.legacyGidOwners.delete(gid)+ }+ this.indexedLegacyGids.delete(id)const gids = this.indexedGids.get(id)if (!gids) returnfor (const gid of gids) {@@ -111,10 +120,20 @@ export class TaskManager {// bypasses the usual action commit helpers (restore/adoption/recovery).normalizeTerminalRuntimeMetrics(task)- const previousGids = new Set(this.indexedGids.get(id) ?? [])+ const previousGids = new Set([+ ...(this.indexedGids.get(id) ?? []),+ ...(this.indexedLegacyGids.get(id) ?? []),+ ])if (this.tasks.has(id)) this.deindex(id)this.tasks.set(id, task)+ const legacyGids = getLegacyQuarantinedGids(task)+ for (const gid of legacyGids) {+ const owners = this.legacyGidOwners.get(gid) ?? new Set<string>()+ owners.add(id)+ this.legacyGidOwners.set(gid, owners)+ }+ if (legacyGids.size) this.indexedLegacyGids.set(id, legacyGids)const gids = collectTaskGids(task)for (const gid of previousGids) {@@ -143,7 +162,10 @@ export class TaskManager {}remove(id: string): boolean {- const gids = new Set(this.indexedGids.get(id) ?? [])+ const gids = new Set([+ ...(this.indexedGids.get(id) ?? []),+ ...(this.indexedLegacyGids.get(id) ?? []),+ ])if (this.tasks.has(id)) this.deindex(id)for (const gid of gids) this.retireEngineGid(gid)return this.tasks.delete(id)@@ -151,6 +173,8 @@ export class TaskManager {clear(): void {this.tasks.clear()+ this.legacyGidOwners.clear()+ this.indexedLegacyGids.clear()this.engineIndex.clear()this.indexedGids.clear()this.reservedEngineGids.clear()@@ -165,6 +189,7 @@ export class TaskManager {isEngineTaskIdRetired(engineTaskId: string): boolean {return (+ this.legacyGidOwners.has(engineTaskId) ||this.reservedEngineGids.has(engineTaskId) ||this.retiredEngineGids.has(engineTaskId))@@ -180,6 +205,7 @@ export class TaskManager {if (engineTaskId.length === 0 ||this.engineIndex.has(engineTaskId) ||+ this.legacyGidOwners.has(engineTaskId) ||this.reservedEngineGids.has(engineTaskId) ||this.retiredEngineGids.has(engineTaskId)) {diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.tsindex d5f7be03..e61f0ce8 100644--- a/src/core/task/task-recovery-service.ts+++ b/src/core/task/task-recovery-service.ts@@ -1,5 +1,6 @@import { access, rename, rm } from 'node:fs/promises'import type { EngineAdapter } from '@core/engine/engine-adapter'+import { hasLegacyImport } from '@core/legacy-import/legacy-task-policy'import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { MotrixDatabase } from '@core/session/motrix-database'import { DownloadErrorCode, ErrorCode } from '@shared/errors'@@ -204,6 +205,7 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {// them would sit on the awaited startup path.const inFlightPublished = publishedTasks.filter((t) =>+ !hasLegacyImport(t) &&(taskId === undefined || t.id === taskId) &&(t.transitionPhase !== TransitionPhase.Idle ||t.status === TaskStatus.Finalizing ||diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.tsindex abd89ed4..91372116 100644--- a/src/core/task/task-row-to-download-task.ts+++ b/src/core/task/task-row-to-download-task.ts@@ -1,4 +1,5 @@import type { TaskInstanceRow, TaskRow } from '@core/session/motrix-database'+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'import {type DownloadTask,makeDefaultBtExtension,@@ -44,6 +45,11 @@ export function taskRowToDownloadTask(}): undefined+ const legacy = legacyTaskMetadataSchema.safeParse(+ primary?.payload.legacyImport+ )+ if (bt && legacy.success) bt.selectedFiles = legacy.data.selectedFiles+return restoreMediaProgress({id: task.motrixId,engineTaskId: primary?.gid ?? '',diff --git a/src/core/tracker/task-tracker-service.test.ts b/src/core/tracker/task-tracker-service.test.tsindex 941cac0e..8b983d3e 100644--- a/src/core/tracker/task-tracker-service.test.ts+++ b/src/core/tracker/task-tracker-service.test.ts@@ -1,7 +1,12 @@import type { EngineAdapter } from '@core/engine/engine-adapter'import { TaskManager } from '@core/task/task-manager'import type { TaskTrackerState } from '@shared/schemas/task-tracker'-import { makeDefaultBtExtension, TaskStatus } from '@shared/types/task'+import {+ makeDefaultBtExtension,+ TaskInstancePhase,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import parseTorrent from 'parse-torrent'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -95,6 +100,67 @@ beforeEach(() => {})describe('task tracker ownership and journal', () => {+ it.each([TaskStatus.Paused, TaskStatus.Downloading])(+ 'keeps imported %s tasks outside tracker edit, sync, creation, and pending recovery',+ async (status) => {+ const f = fixture()+ f.task.status = status+ f.task.instances = [+ {+ instanceId: 'legacy',+ motrixId: f.task.id,+ gid: f.task.engineTaskId,+ phase: TaskInstancePhase.BtDownload,+ status,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/legacy',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ createdAt: 0,+ updatedAt: 0,+ payload: { legacyImport: { version: 99, activation: 'active' } },+ },+ ]+ const state = f.state()!+ f.setState({+ ...state,+ pending: {+ before: [a, b],+ after: [c],+ next: state,+ resumeRequired: true,+ },+ })+ f.tasks.set(f.task.id, f.task)+ await expect(f.plan()).rejects.toThrow('legacyImport.trackersReadOnly')+ await expect(+ f.service.apply(f.task.id, f.task.engineTaskId, 'old')+ ).rejects.toThrow('legacyImport.trackersReadOnly')+ await expect(+ f.service.edit(f.task.id, f.task.engineTaskId, [c])+ ).rejects.toThrow('legacyImport.trackersReadOnly')+ await expect(+ f.service.prepareCreation({+ engineGid: f.task.engineTaskId,+ manual: [c],+ isPrivate: false,+ })+ ).rejects.toThrow('legacyImport.trackersReadOnly')+ f.service.noteTaskControl(f.task.id, false)+ await f.service.recover()+ expect(f.adapter.getTaskStatus).not.toHaveBeenCalled()+ expect(f.adapter.getTaskBtTracker).not.toHaveBeenCalled()+ expect(f.adapter.setTaskBtTracker).not.toHaveBeenCalled()+ expect(f.actions.pauseTask).not.toHaveBeenCalled()+ expect(f.actions.resumeTask).not.toHaveBeenCalled()+ expect(f.repository.save).not.toHaveBeenCalled()+ expect(f.state()?.pending?.resumeRequired).toBe(true)+ }+ )it('previews only managed removal, preserves manual and native overlap, then resumes', async () => {const f = fixture([a, b, native])const plan = await f.plan()diff --git a/src/core/tracker/task-tracker-service.ts b/src/core/tracker/task-tracker-service.tsindex c7726eef..31019059 100644--- a/src/core/tracker/task-tracker-service.ts+++ b/src/core/tracker/task-tracker-service.ts@@ -4,7 +4,9 @@ import type {BtTrackerPolicy,EngineAdapter,} from '@core/engine/engine-adapter'+import { hasLegacyImport } from '@core/legacy-import/legacy-task-policy'import type { TaskManager } from '@core/task/task-manager'+import { AppError, ErrorCode } from '@shared/errors'import type {TaskTrackerOwnership,TaskTrackerPlan,@@ -55,6 +57,16 @@ export class TaskTrackerService {return task}+ private writable(taskId: string, gid: string): DownloadTask {+ const task = this.current(taskId, gid)+ if (hasLegacyImport(task))+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.trackersReadOnly'+ )+ return task+ }+private run<T>(taskId: string, operation: () => Promise<T>): Promise<T> {if (this.stopped)return Promise.reject(new Error('Tracker service stopped'))@@ -79,6 +91,8 @@ export class TaskTrackerService {}noteTaskControl(taskId: string, paused: boolean): void {+ const task = this.deps.tasks.getById(taskId)+ if (task && hasLegacyImport(task)) returnif (this.operations.has(taskId)) this.controlIntents.set(taskId, paused)const state = this.deps.repository.get(taskId)if (state?.pending)@@ -113,6 +127,7 @@ export class TaskTrackerService {: undefinedif (!task || task.engineTaskId !== engineGid)return { trackers: manual, isPrivate: privacy === true }+ this.writable(task.id, engineGid)const saved = this.deps.repository.get(task.id)const retainedManual =privacy === true@@ -247,6 +262,7 @@ export class TaskTrackerService {plan(taskId: string, gid: string): Promise<TaskTrackerPlan> {return this.run(taskId, async () => {+ this.writable(taskId, gid)await this.recoverTask(taskId)return (await this.build(taskId, gid)).plan})@@ -254,6 +270,7 @@ export class TaskTrackerService {apply(taskId: string, gid: string, fingerprint: string): Promise<void> {return this.run(taskId, async () => {+ this.writable(taskId, gid)await this.recoverTask(taskId)const { plan, state, next, effective, after } = await this.build(taskId,@@ -267,6 +284,7 @@ export class TaskTrackerService {edit(taskId: string, gid: string, urls: string[]): Promise<void> {return this.run(taskId, async () => {+ this.writable(taskId, gid)await this.recoverTask(taskId)const { effective, state } = await this.read(taskId, gid)const requested = unique(urls)@@ -305,9 +323,9 @@ export class TaskTrackerService {before: string[],after: string[]): Promise<void> {- this.current(taskId, gid)+ this.writable(taskId, gid)const task = await this.deps.adapter.getTaskStatus(gid)- this.current(taskId, gid)+ this.writable(taskId, gid)if (!task || terminal(task))throw new Error('Tracker engine task unavailable')if (same(before, after)) {@@ -329,7 +347,7 @@ export class TaskTrackerService {let phase: 'pause' | 'write' = 'pause'try {if (active(task)) await this.deps.actions.pauseTask(taskId)- this.current(taskId, gid)+ this.writable(taskId, gid)if (this.current(taskId, gid).bt?.isPrivate === true &&next.isPrivate === false@@ -337,7 +355,7 @@ export class TaskTrackerService {throw new Error('Torrent privacy changed')phase = 'write'await this.deps.adapter.setTaskBtTracker(gid, after)- this.current(taskId, gid)+ this.writable(taskId, gid)} catch (error) {this.recordFailure(taskId, phase)throw error@@ -374,7 +392,13 @@ export class TaskTrackerService {const pending = state?.pendingif (!state || !pending) returnconst task = this.deps.tasks.getById(taskId)- if (!task || task.engineTaskId !== state.engineGid || terminal(task)) return+ if (+ !task ||+ hasLegacyImport(task) ||+ task.engineTaskId !== state.engineGid ||+ terminal(task)+ )+ returnconst engineTask = await this.deps.adapter.getTaskStatus(state.engineGid)if (!engineTask)throw new Error('Tracker engine task unavailable; recovery pending')@@ -399,7 +423,7 @@ export class TaskTrackerService {latest?.pending?.resumeRequired &&this.controlIntents.get(taskId) !== true) {- const current = this.current(taskId, state.engineGid)+ const current = this.writable(taskId, state.engineGid)if (current.status === TaskStatus.Paused ||engineTask.status === TaskStatus.Paused@@ -429,7 +453,10 @@ export class TaskTrackerService {.getAll().filter((task) =>- task.bt && !terminal(task) && !this.deps.repository.get(task.id)+ task.bt &&+ !hasLegacyImport(task) &&+ !terminal(task) &&+ !this.deps.repository.get(task.id)).map((task) => task.id),])@@ -446,7 +473,7 @@ export class TaskTrackerService {await this.recoverTask(id)if (this.deps.repository.get(id)) returnconst task = this.deps.tasks.getById(id)- if (!task || terminal(task)) return+ if (!task || hasLegacyImport(task) || terminal(task)) returnif (!(await this.deps.adapter.getTaskStatus(task.engineTaskId)))returnconst { state } = await this.read(id, task.engineTaskId)diff --git a/src/main/index.ts b/src/main/index.tsindex e6b8fce7..460e7d24 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -36,6 +36,12 @@ import {TaskInspectorActivityStore,taskInspectorActivityEnvironment,} from '@core/inspector-activity'+import { LegacyBtActivationService } from '@core/legacy-import/bt-activation-service'+import { LegacyImportService } from '@core/legacy-import/import-service'+import {+ getLegacyQuarantinedGids,+ hasLegacyImport,+} from '@core/legacy-import/legacy-task-policy'import { newTaskId } from '@core/lib/ids'import { getLogger } from '@core/logger'import { registerEngineCompatibilitySubscriber } from '@core/notifications/engine-compatibility-subscriber'@@ -124,6 +130,7 @@ import { TaskTrackerRepository } from '@core/tracker/task-tracker-repository'import type { NatManager } from '@motrix/nat'import { APP_ID } from '@shared/constants'import { DEFAULT_LOCALE, type SupportedLocale } from '@shared/constants/locales'+import { LEGACY_MIGRATION_INVITATION_ROUTE } from '@shared/lib/legacy-import-navigation'import {ALL_DOWNLOADS_ROUTE,resolveTaskRoute,@@ -175,6 +182,12 @@ import { setupEventForwarding } from './ipc/events'import { registerNotificationIpc } from './ipc/notifications'import { registerQueryHandlers } from './ipc/queries'import { setupLauncher } from './launcher'+import {+ defaultLegacyRoots,+ legacyPidRunning,+ registerLegacyImportIpc,+} from './legacy-import/desktop-import'+import { LegacyImportNavigation } from './legacy-import/navigation-state'import { applyMainLocale, i18n } from './lib/i18n'import { setupLogger } from './logger'import { MainProcessWorkCoordinator } from './main-process-work-coordinator'@@ -516,6 +529,8 @@ let bridgeManager: BridgeManager | null = nulllet magnetTracker: MagnetTracker | null = nulllet segmentClient: Aria2SegmentClient | null = nulllet disposeIpcIngress: (() => void) | null = null+let legacyImportService: LegacyImportService | null = null+let legacyBtActivationService: LegacyBtActivationService | null = nulllet pendingDisclaimerGate: DisclaimerGate | null = nullconst mainProcessWork = new MainProcessWorkCoordinator()const pollingNotificationUnsubscribers: Array<() => void> = []@@ -568,6 +583,7 @@ function performCleanup(): Promise<void> {// synchronously. Cancellation-capable teardown must begin before awaiting// the drain: startup can be blocked on the engine/plugin/session that only// those teardown operations can release.+ void legacyBtActivationService?.drain()const acceptedWorkDrain = mainProcessWork.stopAndDrain()postDeliveryAbortController?.abort()await ingressClose@@ -641,6 +657,10 @@ function performCleanup(): Promise<void> {log.warn('transfer statistics final checkpoint failed')}})+ await safely('legacy-bt-activation', () =>+ legacyBtActivationService?.drain()+ )+ await safely('legacy-import', () => legacyImportService?.drain())await safely('database', () => {if (motrixDb?.database.open) motrixDb.close()})@@ -1349,6 +1369,7 @@ async function startEngineAndRestore(try {await appliedDownloadProxyPolicy.runWithSnapshot(async (_snapshot, lease) => {+ await legacyBtActivationService?.recover()await sessionManager.restore(lease.assertCurrent, (snapshot) =>completedEngineTaskCleanup.observe(snapshot))@@ -1519,7 +1540,11 @@ async function startEngineAndRestore(if (!task) return// BT tasks emit `onDownloadComplete` again after seeding finishes;// route only HTTP/FTP here. BT finalize runs via onBtDownloadComplete.- if (task.type !== TaskType.Http && task.type !== TaskType.Ftp) {+ if (+ task.type !== TaskType.Http &&+ task.type !== TaskType.Ftp &&+ !hasLegacyImport(task)+ ) {return}if (shouldSkipEngineCompletionFinalize(task)) return@@ -1752,6 +1777,113 @@ async function initializeMainProcess(): Promise<void> {pluginHost?.notifySecurityWake()})+ const legacyBackupRoot = path.join(+ platform.userDataDir,+ 'legacy-import-backups'+ )+ const getLegacyImportService = () => {+ if (!gate.isAccepted())+ throw new Error('legacyImport.errors.consentRequired')+ if (!legacyImportService) {+ motrixDb.init()+ legacyImportService = new LegacyImportService({+ db: motrixDb,+ taskManager,+ backupRoot: legacyBackupRoot,+ isProcessRunning: legacyPidRunning,+ publishTasks: publishTaskUpdateNow,+ })+ }+ return legacyImportService+ }+ const legacyNavigation = new LegacyImportNavigation({+ hasConsent: () => gate.isAccepted() && mainProcessWork.isAccepting(),+ getService: getLegacyImportService,+ roots: defaultLegacyRoots,+ changed: () => {+ const mainWindow = windowManager?.get('main')+ if (mainWindow)+ dispatchWhenReady(+ mainWindow,+ Events.LegacyImportNavigationChanged,+ undefined+ )+ },+ })+ const navigateToMigration = () => {+ const mainWindow = windowManager?.get('main')+ if (mainWindow)+ dispatchWhenReady(+ mainWindow,+ Events.NavigateTo,+ LEGACY_MIGRATION_INVITATION_ROUTE+ )+ }+ const finishLegacyChoice = () => {+ legacyNavigation.finishInvitation()+ }+ const getLegacyBtActivationService = () => {+ if (!legacyBtActivationService) {+ getLegacyImportService()+ legacyBtActivationService = new LegacyBtActivationService({+ 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 legacyBtActivationService+ }+ const disposeLegacyImportIpc = registerLegacyImportIpc({+ getActivationService: getLegacyBtActivationService,+ getService: getLegacyImportService,+ hasConsent: () => gate.isAccepted() && mainProcessWork.isAccepting(),+ getTask: (taskId) => taskManager.getById(taskId),+ backupRoot: legacyBackupRoot,+ finishInvitation: finishLegacyChoice,+ getNavigationState: () => legacyNavigation.getState(),+ onSourceDetected: () => legacyNavigation.sourceDetected(),+ waitForTasksReady: () => mainProcessWork.waitForStartup(),+ runAcceptedMutation: (operation) => mainProcessWork.run(operation),+ })+ const beginLegacyInvitation = (): void => {+ runShellAsyncWork('legacy-import-discovery', async () => {+ const state = await legacyNavigation.detect()+ if (+ !state.invitationPending ||+ !gate.isAccepted() ||+ !mainProcessWork.isAccepting()+ )+ return+ windowManager?.open('main', { show: true })+ navigateToMigration()+ })+ }+ const disposeDisclaimerIpc = registerDisclaimerIpc({+ gate,+ onAccepted: beginLegacyInvitation,+ getResolvedLanguage: () => resolvedApplicationLocale,+ applyLocale: (language) => enqueueLocaleUpdate(language, true),+ settings: settingsManager,+ windowManager,+ canContinue: () => mainProcessWork.isAccepting(),+ quitApp: () => requestForcedQuit('disclaimer-declined'),+ })+ disposeIpcIngress = () => {+ disposeDisclaimerIpc()+ disposeLegacyImportIpc()+ }+if (gate.isAccepted()) {const runMode = settingsManager.getApp().runModeconst backgroundPolicy = resolveDesktopBackgroundPolicy({@@ -1765,42 +1897,25 @@ async function initializeMainProcess(): Promise<void> {runMode,releaseWhenHidden: backgroundPolicy.releaseMainWindowWhenHidden,})- if (mainWindowPlan.create) {+ if (mainWindowPlan.create)windowManager.open('main', { show: mainWindowPlan.show })- }launcher.markWindowReady()+ beginLegacyInvitation()} else {- const disposeDisclaimerIpc = registerDisclaimerIpc({- gate,- getResolvedLanguage: () => resolvedApplicationLocale,- applyLocale: (language) => enqueueLocaleUpdate(language, true),- settings: settingsManager,- windowManager,- canContinue: () => mainProcessWork.isAccepting(),- quitApp: () => requestForcedQuit('disclaimer-declined'),- })- disposeIpcIngress = disposeDisclaimerIpc-const onboardingWindow = windowManager.open('onboarding')onboardingWindow.once('closed', () => {- if (!gate.isAccepted()) {- requestForcedQuit('disclaimer-window-closed')- }+ if (!gate.isAccepted()) requestForcedQuit('onboarding-window-closed')})// A second launch must also be able to restore a minimized onboarding// window while download ingress is still waiting for legal acceptance.launcher.markWindowReady()- const decision = await gate.waitForDecision()- disposeDisclaimerIpc()- if (disposeIpcIngress === disposeDisclaimerIpc) {- disposeIpcIngress = null- }- if (pendingDisclaimerGate === gate) {- pendingDisclaimerGate = null- }- if (decision !== 'accepted' || !mainProcessWork.isAccepting()) return}+ const decision = await gate.waitForDecision()+ if (decision !== 'accepted' || !mainProcessWork.isAccepting()) return+ if (!mainProcessWork.isAccepting()) return+ disposeDisclaimerIpc()+ if (pendingDisclaimerGate === gate) pendingDisclaimerGate = nullif (!mainProcessWork.isAccepting()) returnsyncAutoLaunch(settingsManager.getApp().launchAtStartup)@@ -1862,7 +1977,13 @@ async function initializeMainProcess(): Promise<void> {})- motrixDb.init()+ if (!legacyImportService) motrixDb.init()+ getLegacyBtActivationService()+ legacyImportService?.setPersistenceLane((operation) =>+ sessionManager+ ? sessionManager.runExclusivePersistence(operation)+ : Promise.resolve().then(operation)+ )await mediaMetaStore.pruneOrphans(motrixDb.getAllTasks().map(({ task }) => task.motrixId)).catch((err) => log.warn({ err }, 'Media metadata recovery failed'))@@ -2092,6 +2213,12 @@ async function initializeMainProcess(): Promise<void> {supervisor.setStartupGuard(new CompletedTaskStartupGuard({completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),+ heldGids: () =>+ new Set(+ motrixDb+ .getAllTasks()+ .flatMap((pair) => [...getLegacyQuarantinedGids(pair)])+ ),rpc: rpcClient,removeResult: (gid) => adapter.removeDownloadResult(gid),})@@ -2878,6 +3005,7 @@ async function initializeMainProcess(): Promise<void> {logError: (err) => log.warn({ err }, 'completion shutdown failed'),})disposeIpcIngress = () => {+ disposeLegacyImportIpc()disposeCompletionShutdown()disposeCommandHandlers()disposeQueryHandlers()diff --git a/src/main/ipc/disclaimer.test.ts b/src/main/ipc/disclaimer.test.tsindex 3d312376..fa9a2137 100644--- a/src/main/ipc/disclaimer.test.ts+++ b/src/main/ipc/disclaimer.test.ts@@ -57,6 +57,7 @@ describe('disclaimer IPC', () => {await expect(handlers[Queries.GetDisclaimerState]?.()).resolves.toEqual({language: 'en-US',resolvedLanguage: 'en-US',+ disclaimerAccepted: false,})})@@ -87,6 +88,7 @@ describe('disclaimer IPC', () => {await expect(handlers[Queries.GetDisclaimerState]?.()).resolves.toEqual({language: 'system',resolvedLanguage: 'en-US',+ disclaimerAccepted: false,})deps.applyLocale.mockRejectedValueOnce(new Error('locale application failed')@@ -110,6 +112,35 @@ describe('disclaimer IPC', () => {)})+ it('opens main before starting background legacy detection, without awaiting it', async () => {+ let release!: () => void+ const pending = new Promise<void>((resolve) => {+ release = resolve+ })+ const deps = { ...createDeps(), onAccepted: vi.fn(() => pending) }+ const handlers = buildDisclaimerHandlers(deps)+ await expect(handlers[Commands.AcceptDisclaimer]?.()).resolves.toEqual({+ ok: true,+ })+ expect(deps.onAccepted).toHaveBeenCalledOnce()+ expect(deps.gate.accept.mock.invocationCallOrder[0]).toBeLessThan(+ deps.onAccepted.mock.invocationCallOrder[0] ?? 0+ )+ expect(deps.windowManager.open).toHaveBeenCalledWith('main', { show: true })+ expect(deps.windowManager.close).toHaveBeenCalledWith('onboarding')+ expect(deps.windowManager.open.mock.invocationCallOrder[0]).toBeLessThan(+ deps.onAccepted.mock.invocationCallOrder[0] ?? 0+ )+ release()+ })++ it('never detects sources when the agreement is declined', async () => {+ const deps = { ...createDeps(), onAccepted: vi.fn(async () => true) }+ await buildDisclaimerHandlers(deps)[Commands.DeclineDisclaimer]?.()+ expect(deps.onAccepted).not.toHaveBeenCalled()+ expect(deps.quitApp).toHaveBeenCalledOnce()+ })+it('does not open main when shutdown starts during acceptance', async () => {const deps = createDeps()deps.canContinue.mockReturnValue(false)diff --git a/src/main/ipc/disclaimer.ts b/src/main/ipc/disclaimer.tsindex c9af860e..7ee42281 100644--- a/src/main/ipc/disclaimer.ts+++ b/src/main/ipc/disclaimer.ts@@ -12,7 +12,9 @@ import type { WindowManager } from '../window/window-manager'import { registerTrustedIpcHandler } from './trusted-ipc'export interface DisclaimerIpcDeps {- gate: Pick<DisclaimerGate, 'accept'>+ gate: Pick<DisclaimerGate, 'accept'> &+ Partial<Pick<DisclaimerGate, 'isAccepted'>>+ onAccepted?: () => voidgetResolvedLanguage: () => SupportedLocaleapplyLocale: (language: LanguagePreference) => Promise<void>settings: {@@ -35,6 +37,7 @@ export function buildDisclaimerHandlers([Queries.GetDisclaimerState]: async () => ({language: deps.settings.get().app.language,resolvedLanguage: deps.getResolvedLanguage(),+ disclaimerAccepted: deps.gate.isAccepted?.() ?? false,}),[Commands.SetDisclaimerLanguage]: async (input: unknown) => {const language = languagePreferenceSchema.parse(input)@@ -47,6 +50,7 @@ export function buildDisclaimerHandlers(if (!deps.canContinue()) return { ok: true }deps.windowManager.close('onboarding')deps.windowManager.open('main', { show: true })+ deps.onAccepted?.()return { ok: true }},[Commands.DeclineDisclaimer]: async () => {diff --git a/src/main/legacy-import/desktop-import.test.ts b/src/main/legacy-import/desktop-import.test.tsnew file mode 100644index 00000000..f53b2752--- /dev/null+++ b/src/main/legacy-import/desktop-import.test.ts@@ -0,0 +1,476 @@+// @vitest-environment node+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { Aria2ProcessInspector } from '@core/engine/aria2/aria2-process-inspector'+import type { LegacyImportService } from '@core/legacy-import/import-service'+import { TorrentParser } from '@core/torrent/torrent-parser'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ makeDownloadTask,+ TaskInstancePhase,+ TaskKind,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { afterEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ handlers: new Map<string, (...args: unknown[]) => Promise<unknown>>(),+ pick: vi.fn(),+ save: vi.fn(),+ reveal: vi.fn(),+ owner: {},+}))+vi.mock('electron', () => ({+ app: { isPackaged: false },+ BrowserWindow: { fromWebContents: () => mocks.owner },+ dialog: { showOpenDialog: mocks.pick, showSaveDialog: mocks.save },+ shell: { showItemInFolder: mocks.reveal },+ ipcMain: {+ removeHandler: (channel: string) => mocks.handlers.delete(channel),+ },+}))+vi.mock('../ipc/trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ handler: (...args: unknown[]) => Promise<unknown>+ ) => mocks.handlers.set(channel, handler),+}))++import {+ defaultLegacyRoots,+ legacyPidRunning,+ registerLegacyImportIpc,+} from './desktop-import'++const roots: string[] = []+afterEach(async () => {+ mocks.handlers.clear()+ vi.clearAllMocks()+ vi.restoreAllMocks()+ vi.unstubAllEnvs()+ for (const root of roots.splice(0))+ await rm(root, { recursive: true, force: true })+})+async function fixture() {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-desktop-import-'))+ )+ roots.push(root)+ const oldPath = path.join(root, 'old.zip')+ await writeFile(oldPath, 'original bytes')+ const task = makeDownloadTask({+ id: 'imported',+ name: 'old.zip',+ type: TaskType.Http,+ kind: TaskKind.Direct,+ saveDir: root,+ createdAt: 1,+ updatedAt: 1,+ filename: 'old.zip',+ finalName: 'old.zip',+ finalPath: oldPath,+ diskPath: oldPath,+ source: 'user',+ sourceMeta: null,+ status: TaskStatus.Paused,+ uris: ['https://example.invalid/old.zip'],+ instances: [+ {+ instanceId: 'instance',+ motrixId: 'imported',+ gid: null,+ phase: TaskInstancePhase.HttpDownload,+ status: TaskStatus.Paused,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: oldPath,+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {+ legacyImport: {+ version: 1,+ sourceId: 'source',+ itemKey: 'key',+ activation: 'inactive',+ storagePolicy: 'legacy-read-only',+ reason: 'fresh-download-required',+ selectionKnown: false,+ selectedFiles: [],+ },+ },+ createdAt: 1,+ updatedAt: 1,+ },+ ],+ })+ const service = {} as LegacyImportService+ mocks.pick.mockResolvedValue({ canceled: false, filePaths: [root] })+ const getService = vi.fn(() => service)+ registerLegacyImportIpc({+ getService,+ hasConsent: () => true,+ getTask: () => task,+ backupRoot: path.join(root, 'backups'),+ finishInvitation: vi.fn(),+ })+ const event = { sender: {} }+ return { root, oldPath, task, getService, event }+}++describe('desktop legacy import', () => {+ it.each([+ 'invalidSource',+ 'unsafeSource',+ 'changedSource',+ 'tooManySources',+ 'failed',+ ])(+ 'returns only the native selected path and a safe error code for %s',+ async (code) => {+ const { root, event, getService } = await fixture()+ const addSource = vi+ .fn()+ .mockRejectedValue(+ new Error(+ code === 'failed'+ ? 'private diagnostics'+ : `legacyImport.errors.${code}`+ )+ )+ getService.mockReturnValue({+ addSource,+ } as unknown as LegacyImportService)+ await expect(+ mocks.handlers.get(Commands.PickLegacyImportSource)?.(event)+ ).resolves.toEqual({+ dataPath: root,+ errorCode: code,+ })+ expect(addSource).toHaveBeenCalledWith(root)+ }+ )++ it('preserves authorized source results and does not authorize a cancelled selection', async () => {+ const { root, event, getService } = await fixture()+ const source = {+ sourceHandle: '11111111-1111-4111-8111-111111111111',+ name: 'Motrix',+ dataPath: root,+ }+ const addSource = vi.fn().mockResolvedValue(source)+ getService.mockReturnValue({ addSource } as unknown as LegacyImportService)+ await expect(+ mocks.handlers.get(Commands.PickLegacyImportSource)?.(event)+ ).resolves.toEqual(source)+ mocks.pick.mockResolvedValue({ canceled: true, filePaths: [] })+ await expect(+ mocks.handlers.get(Commands.PickLegacyImportSource)?.(event)+ ).resolves.toBeNull()+ expect(addSource).toHaveBeenCalledOnce()+ })++ it('waits for task restore before commit/retry and rechecks admission after shutdown', async () => {+ let release!: () => void+ const readiness = new Promise<void>((resolve) => {+ release = resolve+ })+ let consent = true+ const commit = vi.fn(async () => ({ ok: true }))+ const retry = vi.fn(async () => ({ ok: true }))+ registerLegacyImportIpc({+ getService: () => ({ commit, retry }) as unknown as LegacyImportService,+ hasConsent: () => consent,+ getTask: () => undefined,+ backupRoot: '/unused',+ finishInvitation: vi.fn(),+ waitForTasksReady: () => readiness,+ })+ const first = mocks.handlers.get(Commands.CommitLegacyImport)?.(+ { sender: {} },+ {}+ )+ const second = mocks.handlers.get(Commands.RetryLegacyImport)?.(+ { sender: {} },+ { runId: '33333333-3333-4333-8333-333333333333' }+ )+ await Promise.resolve()+ expect(commit).not.toHaveBeenCalled()+ expect(retry).not.toHaveBeenCalled()+ consent = false+ release()+ await expect(first).rejects.toThrow('consentRequired')+ await expect(second).rejects.toThrow('consentRequired')+ expect(commit).not.toHaveBeenCalled()+ expect(retry).not.toHaveBeenCalled()+ })+ it('rejects before waiting for startup when there is no consent', async () => {+ const wait = vi.fn(() => new Promise<void>(() => {}))+ const getService = vi.fn()+ registerLegacyImportIpc({+ getService,+ hasConsent: () => false,+ getTask: () => undefined,+ backupRoot: '/unused',+ finishInvitation: vi.fn(),+ waitForTasksReady: wait,+ })+ for (const channel of [+ Commands.CommitLegacyImport,+ Commands.RetryLegacyImport,+ Commands.ActivateLegacyBt,+ Queries.GetLegacyBtActivationAvailability,+ Queries.GetLegacyImportNavigation,+ ])+ await expect(+ mocks.handlers.get(channel)?.({ sender: {} }, {})+ ).rejects.toThrow('consentRequired')+ expect(wait).not.toHaveBeenCalled()+ expect(getService).not.toHaveBeenCalled()+ })+ it('keeps navigation/scan available before task readiness and admits commit only afterwards', async () => {+ let release!: () => void+ const readiness = new Promise<void>((resolve) => {+ release = resolve+ })+ const scan = vi.fn(async () => ({ items: [] }))+ const commit = vi.fn(async () => ({ ok: true }))+ const detected = vi.fn()+ registerLegacyImportIpc({+ getService: () => ({ scan, commit }) as unknown as LegacyImportService,+ hasConsent: () => true,+ getTask: () => undefined,+ backupRoot: '/unused',+ finishInvitation: vi.fn(),+ waitForTasksReady: () => readiness,+ onSourceDetected: detected,+ getNavigationState: () => ({ detected: true, invitationPending: false }),+ })+ await expect(+ mocks.handlers.get(Queries.GetLegacyImportNavigation)?.({ sender: {} })+ ).resolves.toEqual({ detected: true, invitationPending: false })+ await mocks.handlers.get(Queries.ScanLegacyImport)?.(+ { sender: {} },+ { sourceHandle: '11111111-1111-4111-8111-111111111111' }+ )+ expect(detected).toHaveBeenCalledOnce()+ const pending = mocks.handlers.get(Commands.CommitLegacyImport)?.(+ { sender: {} },+ {}+ )+ await Promise.resolve()+ expect(commit).not.toHaveBeenCalled()+ release()+ await pending+ expect(commit).toHaveBeenCalledOnce()+ })+ it('creates a separate fresh directory and a single-source draft without reading or modifying old bytes', async () => {+ const { root, oldPath, task, event } = await fixture()+ const result = (await mocks.handlers.get(+ Commands.PrepareLegacyFreshDownload+ )?.(event, { taskId: task.id })) as { saveDir: string; urls: string }+ expect(result.urls).toBe(task.uris[0])+ expect(path.dirname(result.saveDir)).toBe(root)+ expect(path.basename(result.saveDir)).toMatch(/^Motrix-new-/)+ expect(result.saveDir).not.toBe(task.saveDir)+ expect(task.status).toBe(TaskStatus.Paused)+ 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')+ await expect(+ mocks.handlers.get(Commands.PrepareLegacyFreshDownload)?.(event, {+ taskId: task.id,+ })+ ).rejects.toThrow('mirrorsUnsupported')+ expect(mocks.pick).not.toHaveBeenCalled()+ })++ it('rejects changed malformed or credentialed task sources before choosing a destination', async () => {+ const { task, event } = await fixture()+ task.uris = ['https://secret:[email protected]/file.zip']+ await expect(+ mocks.handlers.get(Commands.PrepareLegacyFreshDownload)?.(event, {+ taskId: task.id,+ })+ ).rejects.toThrow('unsafeSource')+ expect(mocks.pick).not.toHaveBeenCalled()+ })++ it('shares an in-flight preparation so concurrent requests create one directory', async () => {+ const { task, event } = await fixture()+ const handler = mocks.handlers.get(Commands.PrepareLegacyFreshDownload)+ const [first, second] = await Promise.all([+ handler?.(event, { taskId: task.id }),+ handler?.(event, { taskId: task.id }),+ ])+ expect(first).toEqual(second)+ expect(mocks.pick).toHaveBeenCalledOnce()+ })++ it('retains torrent bytes and leaves unknown historical file selection empty in the fresh draft', async () => {+ const { root, task, event } = await fixture()+ const bytes = await readFile(+ new URL('../../core/torrent/__fixtures__/test.torrent', import.meta.url)+ )+ const backup = path.join(root, 'backups', 'run')+ await mkdir(backup, { recursive: true })+ task.torrentMetaPath = path.join(backup, 'retained.torrent')+ await writeFile(task.torrentMetaPath, bytes)+ const meta = await new TorrentParser().parse(bytes.toString('base64'))+ task.type = TaskType.Bt+ task.infoHash = meta.infoHash+ const result = await mocks.handlers.get(+ Commands.PrepareLegacyFreshDownload+ )?.(event, { taskId: task.id })+ expect(result).toMatchObject({+ tab: 'torrent',+ source: 'file',+ base64: bytes.toString('base64'),+ torrentMeta: meta,+ selectedFiles: [],+ })+ expect(await readFile(task.torrentMetaPath)).toEqual(bytes)+ })++ it('does not block a live unrelated process after a recorded PID is reused', async () => {+ vi.spyOn(Aria2ProcessInspector.prototype, 'inspectPid').mockResolvedValue({+ pid: process.pid,+ name: 'node',+ executablePath: process.execPath,+ commandLine: 'node test',+ })+ await expect(legacyPidRunning(process.pid)).resolves.toBe(false)+ vi.spyOn(Aria2ProcessInspector.prototype, 'inspectPid').mockResolvedValue({+ pid: process.pid,+ name: 'unknown',+ executablePath: null,+ commandLine: null,+ })+ await expect(legacyPidRunning(process.pid)).resolves.toBe(true)+ })++ it('refusal blocks all legacy reads and native dialogs', async () => {+ const getService = vi.fn()+ registerLegacyImportIpc({+ getService,+ hasConsent: () => false,+ getTask: () => undefined,+ backupRoot: '',+ finishInvitation: vi.fn(),+ })+ await expect(+ mocks.handlers.get(Commands.PickLegacyImportSource)?.({ sender: {} })+ ).rejects.toThrow('consentRequired')+ expect(getService).not.toHaveBeenCalled()+ expect(mocks.pick).not.toHaveBeenCalled()+ await expect(+ mocks.handlers.get(Commands.RevealLegacyImportSource)?.(+ {},+ { sourceHandle: '11111111-1111-4111-8111-111111111111' }+ )+ ).rejects.toThrow('consentRequired')+ expect(mocks.reveal).not.toHaveBeenCalled()+ })++ it('reveals only the authorized source path resolved by the service', async () => {+ const sourceHandle = '11111111-1111-4111-8111-111111111111'+ const getSourcePath = vi.fn(() => '/authorized/Motrix')+ registerLegacyImportIpc({+ getService: () => ({ getSourcePath }) as unknown as LegacyImportService,+ hasConsent: () => true,+ getTask: () => undefined,+ backupRoot: '',+ finishInvitation: vi.fn(),+ })+ const reveal = mocks.handlers.get(Commands.RevealLegacyImportSource)+ await expect(+ reveal?.({}, { sourceHandle, path: '/untrusted' })+ ).rejects.toThrow()+ expect(mocks.reveal).not.toHaveBeenCalled()+ await reveal?.({}, { sourceHandle })+ expect(getSourcePath).toHaveBeenCalledWith(sourceHandle)+ expect(mocks.reveal).toHaveBeenCalledExactlyOnceWith('/authorized/Motrix')+ getSourcePath.mockImplementationOnce(() => {+ throw new Error('sourceNotAuthorized')+ })+ await expect(reveal?.({}, { sourceHandle })).rejects.toThrow(+ 'sourceNotAuthorized'+ )+ expect(mocks.reveal).toHaveBeenCalledTimes(1)+ })++ it('isolates unpackaged tests from real profile paths', () => {+ vi.stubEnv('NODE_ENV', 'test')+ vi.stubEnv('MOTRIX_LEGACY_PROFILE', '')+ expect(defaultLegacyRoots()).toEqual([])+ vi.stubEnv('MOTRIX_LEGACY_PROFILE', '/fixture/motrix')+ expect(defaultLegacyRoots()).toEqual(['/fixture/motrix'])+ vi.stubEnv('MOTRIX_LEGACY_PROFILE', 'relative/path')+ expect(defaultLegacyRoots()).toEqual([])+ })++ it('passes only a preview item to the service and authorizes one native-selected torrent path privately', async () => {+ const f = await fixture()+ const request = {+ previewId: '11111111-1111-4111-8111-111111111111',+ itemId: 'gid:0123456789abcdef',+ }+ let selected: string | null = null+ const authorizeMetadata = vi.fn(+ async (_input, chooseFile: () => Promise<string | null>) => {+ selected = await chooseFile()+ return { previewId: 'refreshed-preview' }+ }+ )+ f.getService.mockReturnValue({+ authorizeMetadata,+ } as unknown as LegacyImportService)+ const chosen = path.join(f.root, 'original.torrent')+ mocks.pick.mockResolvedValue({ canceled: false, filePaths: [chosen] })+ const result = await mocks.handlers.get(+ Commands.PickLegacyTorrentMetadata+ )?.(f.event, request)+ expect(authorizeMetadata).toHaveBeenCalledWith(+ request,+ expect.any(Function)+ )+ expect(selected).toBe(chosen)+ expect(result).toEqual({ previewId: 'refreshed-preview' })+ expect(mocks.pick).toHaveBeenCalledWith(+ mocks.owner,+ expect.objectContaining({+ properties: ['openFile'],+ filters: [{ name: expect.any(String), extensions: ['torrent'] }],+ })+ )+ })++ it('rejects renderer-supplied metadata paths before invoking a native picker or service', async () => {+ const f = await fixture()+ await expect(+ mocks.handlers.get(Commands.PickLegacyTorrentMetadata)?.(f.event, {+ previewId: '11111111-1111-4111-8111-111111111111',+ itemId: 'gid:0123456789abcdef',+ filePath: '/untrusted/file.torrent',+ })+ ).rejects.toThrow()+ expect(f.getService).not.toHaveBeenCalled()+ expect(mocks.pick).not.toHaveBeenCalled()+ })+})diff --git a/src/main/legacy-import/desktop-import.ts b/src/main/legacy-import/desktop-import.tsnew file mode 100644index 00000000..0db26958--- /dev/null+++ b/src/main/legacy-import/desktop-import.ts@@ -0,0 +1,381 @@+import { lstat, mkdir, mkdtemp, realpath } from 'node:fs/promises'+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 { LegacyImportService } from '@core/legacy-import/import-service'+import { isInactiveLegacyTask } from '@core/legacy-import/legacy-task-policy'+import {+ authorizeLegacySource,+ readLegacyFile,+} from '@core/legacy-import/source-scanner'+import { TorrentParser } from '@core/torrent/torrent-parser'+import { AppError, ErrorCode } from '@shared/errors'+import { analyzeDownloadSource } from '@shared/lib/download-source'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ type LegacyImportNavigationState,+ legacyMetadataRequestSchema,+ legacyRunRequestSchema,+ legacyScanRequestSchema,+ legacyTaskMetadataSchema,+ legacyTaskRequestSchema,+} from '@shared/schemas/legacy-import'+import type { AddTaskPrefill } from '@shared/schemas/show-add-task-window'+import type { DownloadTask } from '@shared/types/task'+import { TaskType } from '@shared/types/task'+import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'+import writeFileAtomic from 'write-file-atomic'+import { registerTrustedIpcHandler } from '../ipc/trusted-ipc'+import { i18n } from '../lib/i18n'++export function defaultLegacyRoots(): string[] {+ // Hermetic end-to-end launches never inspect the developer's real profiles.+ if (!app.isPackaged && process.env.NODE_ENV === 'test') {+ const fixture = process.env.MOTRIX_LEGACY_PROFILE+ return fixture && path.isAbsolute(fixture) ? [fixture] : []+ }+ if (process.platform === 'darwin')+ return [path.join(os.homedir(), 'Library', 'Application Support', 'Motrix')]+ if (process.platform === 'win32')+ return [+ path.join(+ process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming'),+ 'Motrix'+ ),+ ]+ return [+ path.join(+ process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), '.config'),+ 'Motrix'+ ),+ path.join(os.homedir(), '.config', 'motrix'),+ ]+}++export async function legacyPidRunning(pid: number): Promise<boolean> {+ if (!Number.isSafeInteger(pid) || pid <= 0) return false+ try {+ process.kill(pid, 0)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EPERM') return false+ }+ const processInfo = await new Aria2ProcessInspector().inspectPid(pid)+ if (!processInfo) return true+ const identities = [+ processInfo.name,+ processInfo.executablePath ?? '',+ ].filter((value) => value && value !== 'unknown')+ // An inaccessible identity remains a reason to close/recheck v1. A reused+ // PID with a known unrelated executable must not block import.+ return (+ identities.length === 0 ||+ identities.some((value) => /(^|[/\\])aria2c(?:\.exe)?$/i.test(value))+ )+}++interface DesktopImportDeps {+ getService: () => LegacyImportService+ getActivationService?: () => LegacyBtActivationService+ hasConsent: () => boolean+ getTask: (taskId: string) => DownloadTask | undefined+ backupRoot: string+ finishInvitation: () => void+ getNavigationState?: () => LegacyImportNavigationState+ onSourceDetected?: () => void+ waitForTasksReady?: () => Promise<void>+ runAcceptedMutation?: <T>(operation: () => Promise<T>) => Promise<T>+}++export function registerLegacyImportIpc(deps: DesktopImportDeps): () => void {+ const prepared = new Map<string, Promise<AddTaskPrefill | null>>()+ const service = () => {+ if (!deps.hasConsent())+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.consentRequired'+ )+ return deps.getService()+ }+ const readyService = async () => {+ service()+ await deps.waitForTasksReady?.()+ return service()+ }+ const handlers: Record<+ string,+ (event: Electron.IpcMainInvokeEvent, input?: unknown) => Promise<unknown>+ > = {+ [Queries.GetLegacyImportNavigation]: async () => {+ service()+ return (+ deps.getNavigationState?.() ?? {+ detected: false,+ invitationPending: false,+ }+ )+ },+ [Queries.GetLegacyBtActivationAvailability]: async (_event, input) => {+ await readyService()+ if (!deps.getActivationService)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.checkpointUnavailable'+ )+ return deps+ .getActivationService()+ .availability(legacyTaskRequestSchema.parse(input).taskId)+ },+ [Commands.ActivateLegacyBt]: async (event, input) => {+ await readyService()+ const { taskId } = legacyTaskRequestSchema.parse(input)+ const owner = BrowserWindow.fromWebContents(event.sender)+ if (!owner || !deps.getActivationService)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.checkpointUnavailable'+ )+ return deps.getActivationService().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]+ })+ },+ [Queries.DiscoverLegacyImport]: async () =>+ service().discover(defaultLegacyRoots()),+ [Commands.RevealLegacyImportSource]: async (_event, input) => {+ const current = service()+ const { sourceHandle } = legacyScanRequestSchema.parse(input)+ shell.showItemInFolder(current.getSourcePath(sourceHandle))+ },+ [Queries.ScanLegacyImport]: async (_event, input) => {+ const preview = await service().scan(+ legacyScanRequestSchema.parse(input).sourceHandle+ )+ deps.onSourceDetected?.()+ return preview+ },+ [Queries.GetLegacyImportRun]: async (_event, input) =>+ service().getRun(legacyRunRequestSchema.parse(input).runId),+ [Commands.CommitLegacyImport]: async (_event, input) => {+ return (await readyService()).commit(input)+ },+ [Commands.CancelLegacyImport]: async (_event, input) =>+ service().cancel(legacyRunRequestSchema.parse(input).runId),+ [Commands.RetryLegacyImport]: async (_event, input) => {+ return (await readyService()).retry(+ legacyRunRequestSchema.parse(input).runId+ )+ },+ [Commands.DismissLegacyImportInvitation]: async () => {+ service().dismissInvitation()+ deps.finishInvitation()+ return { ok: true }+ },+ [Commands.FinishLegacyImportInvitation]: async () => {+ service().dismissInvitation()+ deps.finishInvitation()+ return { ok: true }+ },+ [Commands.PickLegacyImportSource]: async (event) => {+ service()+ const owner = BrowserWindow.fromWebContents(event.sender)+ if (!owner)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.sourceNotAuthorized'+ )+ const result = await dialog.showOpenDialog(owner, {+ title: i18n.t('legacyImport.pickSource'),+ properties: ['openDirectory'],+ })+ if (result.canceled || !result.filePaths[0]) return null+ const current = service()+ const dataPath = result.filePaths[0]+ try {+ return await current.addSource(dataPath)+ } catch (cause) {+ const message = cause instanceof Error ? cause.message : String(cause)+ const errorCode =+ message.match(+ /legacyImport\.(?:errors\.)?(invalidSource|unsafeSource|changedSource|tooManySources)\b/+ )?.[1] ?? 'failed'+ // A rejected native selection is display-only and carries no source grant.+ return { dataPath, errorCode }+ }+ },+ [Commands.PickLegacyTorrentMetadata]: async (event, input) => {+ const request = legacyMetadataRequestSchema.parse(input)+ const owner = BrowserWindow.fromWebContents(event.sender)+ if (!owner)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.sourceNotAuthorized'+ )+ return service().authorizeMetadata(request, async () => {+ const result = await dialog.showOpenDialog(owner, {+ title: i18n.t('legacyImport.chooseTorrent'),+ properties: ['openFile'],+ filters: [+ {+ name: i18n.t('legacyImport.torrentFile'),+ extensions: ['torrent'],+ },+ ],+ })+ if (result.canceled || result.filePaths.length !== 1) return null+ return result.filePaths[0]+ })+ },+ [Commands.ExportLegacyImportReport]: async (event, input) => {+ const report = service().getRun(legacyRunRequestSchema.parse(input).runId)+ const owner = BrowserWindow.fromWebContents(event.sender)+ if (!owner) return false+ const result = await dialog.showSaveDialog(owner, {+ title: i18n.t('legacyImport.exportReport'),+ defaultPath: `motrix-import-${report.runId}.json`,+ filters: [{ name: 'JSON', extensions: ['json'] }],+ })+ if (result.canceled || !result.filePath) return false+ await writeFileAtomic(result.filePath, JSON.stringify(report, null, 2), {+ mode: 0o600,+ fsync: true,+ })+ return true+ },+ [Commands.PrepareLegacyFreshDownload]: async (event, input) => {+ service()+ const { taskId } = legacyTaskRequestSchema.parse(input)+ if (prepared.has(taskId)) return prepared.get(taskId)+ const operation = prepareFreshDownload(event, taskId, deps)+ prepared.set(taskId, operation)+ try {+ return await operation+ } finally {+ prepared.delete(taskId)+ }+ },+ }+ const taskMutations = new Set<string>([+ Commands.CommitLegacyImport,+ Commands.RetryLegacyImport,+ Commands.ActivateLegacyBt,+ ])+ for (const [channel, handler] of Object.entries(handlers))+ registerTrustedIpcHandler(channel, (event, input) =>+ taskMutations.has(channel) && deps.runAcceptedMutation+ ? deps.runAcceptedMutation(() => handler(event, input))+ : handler(event, input)+ )+ return () => {+ for (const channel of Object.keys(handlers)) ipcMain.removeHandler(channel)+ }+}++async function prepareFreshDownload(+ event: Electron.IpcMainInvokeEvent,+ taskId: string,+ deps: DesktopImportDeps+): Promise<AddTaskPrefill | null> {+ const task = deps.getTask(taskId)+ if (!task || !isInactiveLegacyTask(task))+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.unknownTask'+ )+ const marker = legacyTaskMetadataSchema.parse(+ task.instances[0]?.payload.legacyImport+ )+ let prefill: AddTaskPrefill+ if (task.type === TaskType.Bt) {+ const metaPath = task.torrentMetaPath+ if (!metaPath)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.metadataRequired'+ )+ const backupRoot = await realpath(deps.backupRoot)+ const relative = path.relative(backupRoot, metaPath)+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative))+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.unsafeSource'+ )+ const file = await readLegacyFile(+ await authorizeLegacySource(backupRoot),+ relative+ )+ if (!file)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.metadataRequired'+ )+ const base64 = file.bytes.toString('base64')+ const torrentMeta = await new TorrentParser().parse(base64)+ if (torrentMeta.infoHash !== task.infoHash)+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.changedSource'+ )+ prefill = {+ tab: 'torrent',+ source: 'file',+ base64,+ torrentMeta,+ selectedFiles: marker.selectionKnown ? marker.selectedFiles : [],+ }+ } else if (task.type === TaskType.Magnet) {+ const source =+ task.uris.length === 1 ? analyzeDownloadSource(task.uris[0]) : null+ if (source?.status !== 'accepted' || source.protocol !== 'magnet')+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.unsafeSource'+ )+ prefill = { tab: 'links', urls: task.uris.join('\n') }+ } else {+ if (task.uris.length !== 1)+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ 'legacyImport.errors.mirrorsUnsupported'+ )+ const source = analyzeDownloadSource(task.uris[0])+ if (+ source.status !== 'accepted' ||+ !['http', 'https'].includes(source.protocol)+ )+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.unsafeSource'+ )+ prefill = { tab: 'links', urls: task.uris[0], filename: task.finalName }+ }+ const owner = BrowserWindow.fromWebContents(event.sender)+ if (!owner) return null+ const result = await dialog.showOpenDialog(owner, {+ title: i18n.t('legacyImport.freshDestination'),+ properties: ['openDirectory', 'createDirectory'],+ })+ if (result.canceled || !result.filePaths[0]) return null+ if (deps.getTask(taskId) !== task || !isInactiveLegacyTask(task))+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.unknownTask'+ )+ const root = await realpath(result.filePaths[0])+ const stat = await lstat(root)+ if (!stat.isDirectory())+ throw new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.unsafePath'+ )+ await mkdir(root, { recursive: true })+ const freshDir = await mkdtemp(path.join(root, 'Motrix-new-'))+ return { ...prefill, saveDir: freshDir }+}diff --git a/src/main/legacy-import/navigation-state.test.ts b/src/main/legacy-import/navigation-state.test.tsnew file mode 100644index 00000000..771c5694--- /dev/null+++ b/src/main/legacy-import/navigation-state.test.ts@@ -0,0 +1,85 @@+import type { LegacyImportSource } from '@shared/schemas/legacy-import'+import { describe, expect, it, vi } from 'vitest'+import { LegacyImportNavigation } from './navigation-state'++function fixture(sources: LegacyImportSource[] = []) {+ const service = {+ discover: vi.fn(async () => sources),+ invitationDismissed: vi.fn(() => false),+ }+ const deps = {+ hasConsent: vi.fn(() => true),+ getService: () => service,+ roots: vi.fn(() => ['/old']),+ changed: vi.fn(),+ }+ return { navigation: new LegacyImportNavigation(deps), deps, service }+}+describe('legacy main navigation state', () => {+ it('never reads old roots before consent', async () => {+ const f = fixture()+ f.deps.hasConsent.mockReturnValue(false)+ await expect(f.navigation.detect()).rejects.toThrow('consentRequired')+ expect(f.deps.roots).not.toHaveBeenCalled()+ expect(f.service.discover).not.toHaveBeenCalled()+ })+ it('keeps an empty detected v1 source visible after skip or completed invitation', async () => {+ const f = fixture([+ { sourceHandle: 'old', name: 'Motrix', dataPath: '/old' },+ ])+ expect(await f.navigation.detect()).toEqual({+ detected: true,+ invitationPending: true,+ })+ f.navigation.finishInvitation()+ expect(f.navigation.getState()).toEqual({+ detected: true,+ invitationPending: false,+ })+ const next = fixture([+ { sourceHandle: 'old', name: 'Motrix', dataPath: '/old' },+ ])+ next.service.invitationDismissed.mockReturnValue(true)+ expect(await next.navigation.detect()).toEqual({+ detected: true,+ invitationPending: false,+ })+ })+ it('does not pretend a failed detection found v1 and permits a later retry', async () => {+ const f = fixture()+ f.service.discover.mockRejectedValueOnce(new Error('unavailable'))+ await expect(f.navigation.detect()).rejects.toThrow('unavailable')+ expect(f.navigation.getState().detected).toBe(false)+ expect(await f.navigation.detect()).toEqual({+ detected: false,+ invitationPending: false,+ })+ })+ it('does not lose a manually validated source to an older empty default discovery', async () => {+ const f = fixture()+ let done!: (sources: []) => void+ f.service.discover.mockReturnValueOnce(+ new Promise((resolve) => {+ done = resolve+ })+ )+ const pending = f.navigation.detect()+ f.navigation.sourceDetected()+ done([])+ expect(await pending).toEqual({ detected: true, invitationPending: false })+ })+ it('does not publish a discovery result during shutdown', async () => {+ const f = fixture()+ let done!: (sources: LegacyImportSource[]) => void+ f.service.discover.mockReturnValueOnce(+ new Promise((resolve) => {+ done = resolve+ })+ )+ const pending = f.navigation.detect()+ f.deps.hasConsent.mockReturnValue(false)+ done([{ sourceHandle: 'old', name: 'Motrix', dataPath: '/old' }])+ expect(await pending).toEqual({ detected: false, invitationPending: false })+ expect(f.deps.changed).not.toHaveBeenCalled()+ })+})diff --git a/src/main/legacy-import/navigation-state.ts b/src/main/legacy-import/navigation-state.tsnew file mode 100644index 00000000..25059892--- /dev/null+++ b/src/main/legacy-import/navigation-state.ts@@ -0,0 +1,63 @@+import type { LegacyImportService } from '@core/legacy-import/import-service'+import { AppError, ErrorCode } from '@shared/errors'+import type { LegacyImportNavigationState } from '@shared/schemas/legacy-import'++/** Detection controls navigation only; it never blocks engine/task startup. */+export class LegacyImportNavigation {+ private state: LegacyImportNavigationState = {+ detected: false,+ invitationPending: false,+ }+ private discovery: Promise<LegacyImportNavigationState> | null = null+ constructor(+ private readonly deps: {+ hasConsent: () => boolean+ getService: () => Pick<+ LegacyImportService,+ 'discover' | 'invitationDismissed'+ >+ roots: () => string[]+ changed: () => void+ }+ ) {}++ getState(): LegacyImportNavigationState {+ return { ...this.state }+ }++ detect(): Promise<LegacyImportNavigationState> {+ if (!this.deps.hasConsent())+ return Promise.reject(+ new AppError(+ ErrorCode.InvalidSelection,+ 'legacyImport.errors.consentRequired'+ )+ )+ if (this.discovery) return this.discovery+ this.discovery = (async () => {+ const service = this.deps.getService()+ const sources = await service.discover(this.deps.roots())+ if (!this.deps.hasConsent()) return this.getState()+ this.state = {+ detected: this.state.detected || sources.length > 0,+ invitationPending: sources.length > 0 && !service.invitationDismissed(),+ }+ this.deps.changed()+ return this.getState()+ })().catch((error) => {+ this.discovery = null+ throw error+ })+ return this.discovery+ }++ sourceDetected(): void {+ this.state = { ...this.state, detected: true }+ this.deps.changed()+ }++ finishInvitation(): void {+ this.state = { ...this.state, invitationPending: false }+ this.deps.changed()+ }+}diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsxindex d98fdc26..9a4810ee 100644--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx@@ -22,11 +22,11 @@ import {} from '@shared/constants/add-task'import { Events } from '@shared/protocol/events'import {+ addTaskModeToFormDefaults,magnetFileSelectionPayloadSchema,magnetFileSelectionSettledPayloadSchema,protocolTorrentFilePayloadSchema,setAddTaskModeEventPayloadSchema,- urlParamsToFormDefaults,} from '@shared/schemas/add-task'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -141,7 +141,7 @@ export function AddTaskDialogHost() {const onSetMode = (...args: unknown[]) => {const p = setAddTaskModeEventPayloadSchema.safeParse(args[0])if (!p.success) return- openWith(urlParamsToFormDefaults(p.data))+ openWith(addTaskModeToFormDefaults(p.data))}transport.on(Events.MagnetFileSelection, onMagnet)diff --git a/src/renderer/components/add-task/use-external-hydration.test.ts b/src/renderer/components/add-task/use-external-hydration.test.tsindex 8a66e805..d497d149 100644--- a/src/renderer/components/add-task/use-external-hydration.test.ts+++ b/src/renderer/components/add-task/use-external-hydration.test.ts@@ -264,6 +264,66 @@ describe('useExternalHydration', () => {).toBe('/override')})+ it('preserves a typed HTTP fresh-download draft including its exclusive directory', () => {+ const { result } = renderHook(() =>+ useForm<AddTaskFormValues>({+ defaultValues: { tab: 'links', urls: '', saveDir: '/old' },+ })+ )+ renderHook(() => useExternalHydration(result.current, true))+ const draft = {+ tab: 'links',+ urls: 'https://example.invalid/a.zip',+ filename: 'a.zip',+ saveDir: '/new/exclusive',+ }+ act(() => fire(Events.SetAddTaskMode, draft))+ expect(result.current.getValues()).toEqual(draft)+ })++ it('preserves retained torrent metadata and an explicitly empty selection', () => {+ const { result } = renderHook(() =>+ useForm<AddTaskFormValues>({+ defaultValues: { tab: 'links', urls: '', saveDir: '/old' },+ })+ )+ renderHook(() => useExternalHydration(result.current, true))+ const draft = {+ tab: 'torrent',+ source: 'file',+ base64: 'dG9ycmVudA==',+ saveDir: '/new/exclusive',+ torrentMeta: {+ name: 't',+ infoHash: 'a'.repeat(40),+ totalSize: 1,+ files: [{ index: 0, path: 'a.mp4', size: 1, extension: '.mp4' }],+ },+ selectedFiles: [],+ }+ act(() => fire(Events.SetAddTaskMode, draft))+ expect(result.current.getValues()).toEqual(draft)+ act(() => fire(Events.SetAddTaskMode, { ...draft, selectedFiles: [0] }))+ expect(result.current.getValues('selectedFiles')).toEqual([0])+ })++ it('rejects invalid typed drafts without falling back to a URL-mode reset', () => {+ const { result } = renderHook(() =>+ useForm<AddTaskFormValues>({+ defaultValues: {+ tab: 'links',+ urls: 'https://old.example/a',+ saveDir: '/old',+ },+ })+ )+ renderHook(() => useExternalHydration(result.current, true))+ act(() =>+ fire(Events.SetAddTaskMode, { tab: 'torrent', selectedFiles: [-1] })+ )+ expect(result.current.getValues('urls')).toBe('https://old.example/a')+ })+it('ignores invalid payloads silently', () => {const { result } = renderHook(() =>useForm({ defaultValues: { tab: 'links', urls: '', saveDir: '/d' } })diff --git a/src/renderer/components/add-task/use-external-hydration.ts b/src/renderer/components/add-task/use-external-hydration.tsindex 8504a873..4a2da1ec 100644--- a/src/renderer/components/add-task/use-external-hydration.ts+++ b/src/renderer/components/add-task/use-external-hydration.ts@@ -2,12 +2,12 @@ import { transport } from '@renderer/lib/transport'import { Events } from '@shared/protocol/events'import {type AddTaskFormValues,+ addTaskModeToFormDefaults,magnetFileSelectionPayloadSchema,magnetFileSelectionSettledPayloadSchema,protocolTorrentFilePayloadSchema,setAddTaskModeEventPayloadSchema,torrentQueueSizeChangedPayloadSchema,- urlParamsToFormDefaults,} from '@shared/schemas/add-task'import { useEffect } from 'react'import type { UseFormReturn } from 'react-hook-form'@@ -94,7 +94,7 @@ export function useExternalHydration(const parsed = setAddTaskModeEventPayloadSchema.safeParse(args[0])if (!parsed.success) returnonTorrentQueueChanged?.(null)- const defaults = urlParamsToFormDefaults(parsed.data)+ const defaults = addTaskModeToFormDefaults(parsed.data)const refreshDefaultSaveDir =defaults.saveDir === undefined && !form.getFieldState('saveDir').isDirty// A mode switch without an explicit saveDir must not wipe whateverdiff --git a/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx b/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsxindex 983d73c2..f11cc9a4 100644--- a/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx+++ b/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx@@ -2,10 +2,13 @@ import '@testing-library/jest-dom/vitest'import '@renderer/lib/i18n'import { SidebarProvider } from '@renderer/components/ui/sidebar'import { TooltipProvider } from '@renderer/components/ui/tooltip'-import { render, screen } from '@testing-library/react'+import { transport } from '@renderer/lib/transport'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'+import { act, render, screen } from '@testing-library/react'import type { ReactElement } from 'react'import { MemoryRouter } from 'react-router'-import { beforeAll, describe, expect, it, vi } from 'vitest'+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import { AppSidebar } from './app-sidebar'// The footer's NotificationsNavItem (Task 17R) calls useNotifications(),@@ -19,6 +22,17 @@ vi.mock('@renderer/lib/transport', () => ({},}))+beforeEach(() => {+ vi.mocked(transport.on).mockClear()+ vi.mocked(transport.invoke)+ .mockReset()+ .mockImplementation(async (channel) => {+ if (channel === Queries.GetLegacyImportNavigation)+ return { detected: false, invitationPending: false }+ return []+ })+})+// jsdom 29 + Node 25 do not provide a working window.localStorage.// SidebarProvider reads/writes SIDEBAR_STATE_KEY, so stub it here.// matchMedia is also missing in jsdom and used by the mobile hook.@@ -66,6 +80,58 @@ function wrap(ui: ReactElement, initialEntries: string[] = ['/']) {}describe('AppSidebar', () => {+ it('keeps migration hidden when no v1 source was detected', async () => {+ render(wrap(<AppSidebar />))+ await act(async () => Promise.resolve())+ expect(screen.queryByText('Migration')).not.toBeInTheDocument()+ })++ it('keeps detected migration available after an invitation was dismissed', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyImportNavigation+ ? { detected: true, invitationPending: false }+ : []+ )+ render(wrap(<AppSidebar />, ['/migration']))+ const link = (await screen.findByText('Migration')).closest('a')+ expect(link).toHaveAttribute('href', '/migration')+ expect(link).toHaveAttribute('aria-current', 'page')+ expect(link?.querySelector('svg')).toHaveAttribute('data-icon', 'migration')+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Queries.DiscoverLegacyImport+ )+ })++ it('refreshes navigation after desktop detection without reading profile paths', async () => {+ render(wrap(<AppSidebar />))+ await act(async () => Promise.resolve())+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyImportNavigation+ ? { detected: true, invitationPending: true }+ : []+ )+ const handler = vi+ .mocked(transport.on)+ .mock.calls.find(+ ([event]) => event === Events.LegacyImportNavigationChanged+ )?.[1]+ expect(handler).toBeTypeOf('function')+ await act(async () => handler?.())+ expect(await screen.findByText('Migration')).toBeInTheDocument()+ expect(transport.invoke).not.toHaveBeenCalledWith(Queries.ScanLegacyImport)+ })++ it('does not display a migration entry after a failed navigation snapshot', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetLegacyImportNavigation)+ throw new Error('Discovery unavailable')+ return []+ })+ render(wrap(<AppSidebar />))+ await act(async () => Promise.resolve())+ expect(screen.queryByText('Migration')).not.toBeInTheDocument()+ })+it('renders four nav items with localized labels', () => {render(wrap(<AppSidebar />))expect(screen.getByText('Dashboard')).toBeInTheDocument()diff --git a/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx b/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsxindex 29c7c7a9..5d8a7c93 100644--- a/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx+++ b/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx@@ -2,6 +2,7 @@ import type { MotrixIcon } from '@renderer/components/icons'import {DashboardIcon,DownloadLibraryIcon,+ MigrationIcon,PluginIcon,SettingsIcon,TrackerIcon,@@ -20,6 +21,8 @@ import {SidebarMenuItem,SidebarSeparator,} from '@renderer/components/ui/sidebar'+import { useLegacyImportNavigation } from '@renderer/features/legacy-import/use-legacy-import-navigation'+import { LEGACY_MIGRATION_ROUTE } from '@shared/lib/legacy-import-navigation'import { useTranslation } from 'react-i18next'import { NavLink } from 'react-router'@@ -44,6 +47,17 @@ const FOOTER_NAV_ITEMS: readonly NavItem[] = [export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {const { t } = useTranslation()const direction = useDirection()+ const { detected } = useLegacyImportNavigation()+ const items = detected+ ? [+ ...NAV_ITEMS,+ {+ to: LEGACY_MIGRATION_ROUTE,+ icon: MigrationIcon,+ labelKey: 'legacyImport.navigation',+ },+ ]+ : NAV_ITEMSreturn (<Sidebar@@ -60,7 +74,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {<SidebarGroup><SidebarGroupContent><SidebarMenu>- {NAV_ITEMS.map((item) => {+ {items.map((item) => {const Icon = item.iconreturn (<SidebarMenuItem key={item.to}>diff --git a/src/renderer/components/icons/index.ts b/src/renderer/components/icons/index.tsindex d11fddee..61f4264c 100644--- a/src/renderer/components/icons/index.ts+++ b/src/renderer/components/icons/index.ts@@ -56,6 +56,7 @@ export { LockedIcon } from './locked'export { MagnetIcon } from './magnet'export { MarkAllReadIcon } from './mark-all-read'export { MetalinkIcon } from './metalink'+export { MigrationIcon } from './migration'export { MoreIcon } from './more'export { NotificationsIcon } from './notifications'export { OpenFileIcon } from './open-file'diff --git a/src/renderer/components/icons/migration.tsx b/src/renderer/components/icons/migration.tsxnew file mode 100644index 00000000..62ab8371--- /dev/null+++ b/src/renderer/components/icons/migration.tsx@@ -0,0 +1,7 @@+import { FolderInput } from 'lucide-react'+import { createIcon } from './create-icon'+export const MigrationIcon = /* @__PURE__ */ createIcon(+ 'migration',+ FolderInput,+ 'lucide'+)diff --git a/src/renderer/components/ui/checkbox.tsx b/src/renderer/components/ui/checkbox.tsxindex 95d8d6b6..bb9201ca 100644--- a/src/renderer/components/ui/checkbox.tsx+++ b/src/renderer/components/ui/checkbox.tsx@@ -1,11 +1,16 @@import { Checkbox as CheckboxPrimitive } from '@base-ui/react/checkbox'-import { CheckIcon } from '@renderer/components/icons'+import { CheckIcon, SubtractIcon } from '@renderer/components/icons'import { cn } from '@renderer/lib/utils'-function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {+function Checkbox({+ className,+ indeterminate,+ ...props+}: CheckboxPrimitive.Root.Props) {return (<CheckboxPrimitive.Rootdata-slot="checkbox"+ indeterminate={indeterminate}className={cn('peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-checked:bg-primary',className@@ -16,7 +21,11 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {data-slot="checkbox-indicator"className="grid place-content-center text-current transition-none">- <CheckIcon className="size-3.5" />+ {indeterminate ? (+ <SubtractIcon className="size-3.5" />+ ) : (+ <CheckIcon className="size-3.5" />+ )}</CheckboxPrimitive.Indicator></CheckboxPrimitive.Root>)diff --git a/src/renderer/components/ui/radio-group.tsx b/src/renderer/components/ui/radio-group.tsxnew file mode 100644index 00000000..67b63697--- /dev/null+++ b/src/renderer/components/ui/radio-group.tsx@@ -0,0 +1,38 @@+import { Radio as RadioPrimitive } from '@base-ui/react/radio'+import { RadioGroup as RadioGroupPrimitive } from '@base-ui/react/radio-group'+import { cn } from '@renderer/lib/utils'++function RadioGroup<Value>({+ className,+ ...props+}: RadioGroupPrimitive.Props<Value>) {+ return (+ <RadioGroupPrimitive+ data-slot="radio-group"+ className={cn('grid gap-3', className)}+ {...props}+ />+ )+}++function RadioGroupItem<Value>({+ className,+ ...props+}: RadioPrimitive.Root.Props<Value>) {+ return (+ <RadioPrimitive.Root+ data-slot="radio-group-item"+ className={cn(+ 'peer flex size-4 shrink-0 items-center justify-center rounded-full border border-input text-primary shadow-xs outline-none transition-shadow focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-checked:border-primary aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:bg-input/30 dark:aria-invalid:ring-destructive/40',+ className+ )}+ {...props}+ >+ <RadioPrimitive.Indicator data-slot="radio-group-indicator">+ <span className="block size-2 rounded-full bg-current" />+ </RadioPrimitive.Indicator>+ </RadioPrimitive.Root>+ )+}++export { RadioGroup, RadioGroupItem }diff --git a/src/renderer/features/legacy-import/icons/[email protected] b/src/renderer/features/legacy-import/icons/[email protected]new file mode 100644index 00000000..948a415cBinary files /dev/null and b/src/renderer/features/legacy-import/icons/[email protected] differdiff --git a/src/renderer/features/legacy-import/icons/[email protected] b/src/renderer/features/legacy-import/icons/[email protected]new file mode 100644index 00000000..628090adBinary files /dev/null and b/src/renderer/features/legacy-import/icons/[email protected] differdiff --git a/src/renderer/features/legacy-import/import-illustration.tsx b/src/renderer/features/legacy-import/import-illustration.tsxnew file mode 100644index 00000000..0f61cef3--- /dev/null+++ b/src/renderer/features/legacy-import/import-illustration.tsx@@ -0,0 +1,20 @@+const illustration1x = new URL('./icons/[email protected]', import.meta.url)+ .href+const illustration2x = new URL('./icons/[email protected]', import.meta.url)+ .href++/** The adjacent stage heading conveys the meaning of this decorative artwork. */+export function ImportIllustration() {+ return (+ <img+ data-slot="migration-import-illustration"+ src={illustration1x}+ srcSet={`${illustration1x} 1x, ${illustration2x} 2x`}+ width={128}+ height={128}+ alt=""+ className="size-full object-contain brightness-90 contrast-[1.12] saturate-[1.2] drop-shadow-[0_1px_1px_rgb(15_23_42/0.12)] dark:filter-none"+ draggable={false}+ />+ )+}diff --git a/src/renderer/features/legacy-import/import-motion.css b/src/renderer/features/legacy-import/import-motion.cssnew file mode 100644index 00000000..070d61c9--- /dev/null+++ b/src/renderer/features/legacy-import/import-motion.css@@ -0,0 +1,145 @@+/* Migration feedback is immediate; motion only follows an actual state change. */+.migration-motion {+ --migration-ease: cubic-bezier(0.23, 1, 0.32, 1);+ --migration-duration: 0ms;+}++.migration-motion[data-motion="on"] {+ --migration-duration: 180ms;+}++.migration-motion .migration-primary {+ background: var(--foreground);+ color: var(--background);+}++.migration-motion .migration-primary:hover:not(:disabled) {+ background: color-mix(in oklab, var(--foreground) 85%, var(--background));+}++.migration-task-row {+ transition: background-color var(--migration-duration) ease;+}++.migration-task-row[data-selected="true"] {+ background: color-mix(in oklab, var(--foreground) 2%, var(--background));+}++.migration-motion .migration-progress-fill {+ background: var(--foreground);+ transform: scaleX(var(--migration-progress));+ transform-origin: left;+ transition: transform var(--migration-duration) linear;+}++.migration-progress-fill:dir(rtl) {+ transform-origin: right;+}++@media (min-height: 760px) {+ .migration-page-column:is([data-stage="discovery"], [data-stage="selection"])+ > div {+ justify-content: center;+ }++ .migration-page-column[data-stage="discovery"] .migration-source-options {+ flex: 0 1 auto;+ }+}++@media (max-height: 760px) {+ .migration-stage-heading-illustrated {+ padding-block: 12px;+ }++ .migration-stage-illustration {+ margin-bottom: 12px;+ }+}++@media (max-height: 650px) {+ .migration-source-options {+ padding-top: 12px;+ }++ .migration-page-column[data-stage="discovery"] > div {+ overflow-y: auto;+ }++ .migration-page-column[data-stage="discovery"] .migration-source-options {+ flex: 0 0 auto;+ overflow: visible;+ }++ .migration-stage-heading {+ padding-block: 12px;+ }++ .migration-stage-heading > p {+ margin-top: 8px;+ }++ .migration-selection-note {+ padding-block: 10px;+ }++ .migration-stage-illustration {+ margin-bottom: 8px;+ }+}++@media (hover: hover) and (pointer: fine) {+ .migration-motion [data-slot="button"] {+ transition:+ transform var(--migration-duration) var(--migration-ease),+ background-color var(--migration-duration) ease,+ color var(--migration-duration) ease;+ }++ .migration-motion[data-motion="on"]+ [data-slot="button"]:active:not(:disabled) {+ transform: scale(0.98);+ }+}++.migration-motion[data-motion="off"] *,+.migration-motion[data-motion="off"] *::before,+.migration-motion[data-motion="off"] *::after {+ animation: none;+ transition-duration: 0ms;+}++/* Run stages share a quiet, centered column; expanded details own the scroll. */+.migration-page-column:is([data-stage="progress"], [data-stage="result"])+> div {+ justify-content: center;+}++.migration-run-step:not(:last-child)::after {+ position: absolute;+ top: 28px;+ bottom: -24px;+ inset-inline-start: 11.5px;+ width: 1px;+ background: var(--border);+ content: "";+}++@media (max-height: 650px) {+ .migration-run-content {+ padding-block: 12px;+ }+ .migration-run-content .migration-stage-heading {+ padding-top: 0;+ padding-bottom: 20px;+ }+}++@media (max-height: 650px) {+ .migration-run-content dl > div {+ padding-block: 10px;+ }+ .migration-run-content .migration-result-details {+ margin-top: 12px;+ }+}diff --git a/src/renderer/features/legacy-import/import-motion.test.tsx b/src/renderer/features/legacy-import/import-motion.test.tsxnew file mode 100644index 00000000..02eb96d9--- /dev/null+++ b/src/renderer/features/legacy-import/import-motion.test.tsx@@ -0,0 +1,143 @@+import '@testing-library/jest-dom/vitest'+import { setAppReduceMotion } from '@renderer/lib/reduced-motion'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ ImportCount,+ ImportMotionScope,+ ImportStageContent,+} from './import-motion'++const originalAnimate = Element.prototype.animate+const animations: Array<{+ cancel: ReturnType<typeof vi.fn>+ playState: string+}> = []+const animate = vi.fn(() => {+ const animation = { cancel: vi.fn(), playState: 'running' }+ animations.push(animation)+ return animation+})++function Counter({+ value,+ active = true,+}: {+ value: number+ active?: boolean+}) {+ return (+ <ImportMotionScope active={active}>+ <button type="button">Select</button>+ <output aria-label="Selected">+ <ImportCount value={value} />+ </output>+ </ImportMotionScope>+ )+}++beforeEach(() => {+ setAppReduceMotion(false)+ animations.length = 0+ animate.mockClear()+ vi.stubGlobal(+ 'matchMedia',+ vi.fn(() => ({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }))+ )+ Object.defineProperty(Element.prototype, 'animate', {+ configurable: true,+ writable: true,+ value: animate,+ })+})++afterEach(() => {+ cleanup()+ setAppReduceMotion(false)+ if (originalAnimate) Element.prototype.animate = originalAnimate+ else Reflect.deleteProperty(Element.prototype, 'animate')+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++describe('migration motion', () => {+ it('shows actual counts immediately and replaces an interrupted response', () => {+ const view = render(<Counter value={6} />)+ expect(animate).not.toHaveBeenCalled()+ view.rerender(<Counter value={5} />)+ expect(screen.getByRole('status')).toHaveTextContent('5')+ view.rerender(<Counter value={2} />)+ expect(screen.getByRole('status')).toHaveTextContent('2')+ expect(animations[0].cancel).toHaveBeenCalledOnce()+ expect(animate).toHaveBeenCalledTimes(2)+ view.unmount()+ expect(animations[1].cancel).toHaveBeenCalledOnce()+ })++ it('cancels running feedback on app reduction and does not replay stale counts', () => {+ const view = render(<Counter value={6} />)+ view.rerender(<Counter value={5} />)+ act(() => setAppReduceMotion(true))+ expect(animations[0].cancel).toHaveBeenCalledOnce()+ view.rerender(<Counter value={4} />)+ act(() => setAppReduceMotion(false))+ expect(screen.getByRole('status')).toHaveTextContent('4')+ expect(animate).toHaveBeenCalledTimes(1)+ view.rerender(<Counter value={3} />)+ expect(animate).toHaveBeenCalledTimes(2)+ })++ it('keeps keyboard changes immediate and resumes feedback with pointer input', () => {+ const view = render(<Counter value={6} />)+ fireEvent.keyDown(screen.getByRole('button'), { key: ' ' })+ view.rerender(<Counter value={0} />)+ expect(screen.getByRole('status')).toHaveTextContent('0')+ expect(animate).not.toHaveBeenCalled()+ fireEvent.pointerDown(screen.getByRole('button'))+ expect(animate).not.toHaveBeenCalled()+ view.rerender(<Counter value={6} />)+ expect(animate).toHaveBeenCalledTimes(1)+ })++ it('stops feedback while the retained page is inactive or the document is hidden', () => {+ const view = render(<Counter value={6} />)+ view.rerender(<Counter value={5} />)+ view.rerender(<Counter value={5} active={false} />)+ expect(animations[0].cancel).toHaveBeenCalledOnce()+ view.rerender(<Counter value={2} active={false} />)+ view.rerender(<Counter value={2} />)+ expect(animate).toHaveBeenCalledTimes(1)+ view.rerender(<Counter value={1} />)+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)+ fireEvent(document, new Event('visibilitychange'))+ expect(animations[1].cancel).toHaveBeenCalledOnce()+ view.rerender(<Counter value={0} />)+ expect(screen.getByRole('status')).toHaveTextContent('0')+ expect(animate).toHaveBeenCalledTimes(2)+ })++ it('honors system reduction and renders stage actions without an animation delay', () => {+ vi.mocked(window.matchMedia).mockReturnValue({+ matches: true,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ } as unknown as MediaQueryList)+ const click = vi.fn()+ render(+ <ImportMotionScope active>+ <ImportStageContent>+ <button type="button" onClick={click}>+ Import+ </button>+ </ImportStageContent>+ </ImportMotionScope>+ )+ fireEvent.click(screen.getByRole('button'))+ expect(click).toHaveBeenCalledOnce()+ expect(animate).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/features/legacy-import/import-motion.tsx b/src/renderer/features/legacy-import/import-motion.tsxnew file mode 100644index 00000000..fbb11e4a--- /dev/null+++ b/src/renderer/features/legacy-import/import-motion.tsx@@ -0,0 +1,135 @@+import { useReducedMotion } from '@renderer/lib/reduced-motion'+import {+ createContext,+ type ReactNode,+ useContext,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from 'react'+import './import-motion.css'++const MotionContext = createContext(false)+const feedback = {+ count: { transform: 'translateY(5px)', opacity: 0.5, duration: 180 },+ stage: { transform: 'translateY(6px)', opacity: 0, duration: 220 },+ task: {+ transform: 'translateY(-6px) scale(.94)',+ opacity: 0.4,+ duration: 240,+ },+ success: { transform: 'scale(.9)', opacity: 0.3, duration: 280 },+} as const++export function ImportMotionScope({+ active,+ children,+}: {+ active: boolean+ children: ReactNode+}) {+ const reducedMotion = useReducedMotion()+ const [keyboard, setKeyboard] = useState(false)+ const [visible, setVisible] = useState(!document.hidden)+ useEffect(() => {+ const onVisibility = () => setVisible(!document.hidden)+ document.addEventListener('visibilitychange', onVisibility)+ return () => document.removeEventListener('visibilitychange', onVisibility)+ }, [])+ const enabled = active && visible && !reducedMotion && !keyboard+ return (+ <MotionContext value={enabled}>+ <div+ className="migration-motion h-full min-h-0 bg-background text-foreground"+ data-motion={enabled ? 'on' : 'off'}+ onKeyDownCapture={() => setKeyboard(true)}+ onPointerDownCapture={() => setKeyboard(false)}+ >+ {children}+ </div>+ </MotionContext>+ )+}++/** Values render immediately. Only the presentation responds to a real change. */+function useImportFeedback<T extends HTMLElement = HTMLSpanElement>(+ value: number | string,+ kind: keyof typeof feedback,+ enter = false+) {+ const enabled = useContext(MotionContext)+ const ref = useRef<T>(null)+ const previous = useRef<number | string>(value)+ const mounted = useRef(false)+ const animation = useRef<Animation | null>(null)+ useLayoutEffect(() => {+ const changed = previous.current !== value || (!mounted.current && enter)+ previous.current = value+ mounted.current = true+ const element = ref.current+ if (!enabled) {+ animation.current?.cancel()+ animation.current = null+ return+ }+ if (!changed || !element?.animate) return+ const preset = feedback[kind]+ // Re-target a rapid change from its visible position, without queuing effects.+ const current =+ animation.current?.playState === 'running'+ ? getComputedStyle(element)+ : null+ const from = {+ transform: current?.transform ?? preset.transform,+ opacity: current?.opacity ?? preset.opacity,+ }+ animation.current?.cancel()+ const next = element.animate([from, { transform: 'none', opacity: 1 }], {+ duration: preset.duration,+ easing: 'cubic-bezier(0.23, 1, 0.32, 1)',+ })+ animation.current = next+ next.onfinish = () => {+ if (animation.current === next) animation.current = null+ }+ }, [value, kind, enter, enabled])+ useLayoutEffect(() => () => animation.current?.cancel(), [])+ return ref+}++export function ImportCount({ value }: { value: number }) {+ const ref = useImportFeedback(value, 'count')+ return (+ <span ref={ref} className="inline-block tabular-nums">+ {value}+ </span>+ )+}++export function ImportStageContent({ children }: { children: ReactNode }) {+ const ref = useImportFeedback<HTMLDivElement>('stage', 'stage', true)+ return (+ <div ref={ref} className="flex min-h-0 flex-1 flex-col">+ {children}+ </div>+ )+}++export function ImportResultMark({+ success,+ children,+}: {+ success: boolean+ children: ReactNode+}) {+ const ref = useImportFeedback('result', 'success', success)+ return (+ <span+ ref={ref}+ className="mb-4 flex size-12 items-center justify-center rounded-2xl border border-border/50 bg-muted shadow-xs"+ >+ {children}+ </span>+ )+}diff --git a/src/renderer/features/legacy-import/import-page-layout.tsx b/src/renderer/features/legacy-import/import-page-layout.tsxnew file mode 100644index 00000000..7ec3799b--- /dev/null+++ b/src/renderer/features/legacy-import/import-page-layout.tsx@@ -0,0 +1,96 @@+import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'+import { cn } from '@renderer/lib/utils'+import { type ReactNode, useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { ImportMotionScope, ImportStageContent } from './import-motion'++export type ImportStage = 'discovery' | 'selection' | 'progress' | 'result'++export function ImportPageLayout({+ active,+ stage,+ footer,+ children,+}: {+ active: boolean+ stage: ImportStage+ footer: ReactNode+ children: ReactNode+}) {+ const { t } = useTranslation()+ return (+ <ImportMotionScope active={active}>+ <PanelShell+ title={t('legacyImport.page.assistantTitle')}+ contentClassName="overflow-hidden"+ footer={<div className="w-full py-1">{footer}</div>}+ >+ <div className="@container/import flex min-h-0 flex-1 flex-col px-6">+ <div+ data-stage={stage}+ className="migration-page-column mx-auto flex min-h-0 w-full max-w-120 flex-1 flex-col @[56rem]/import:max-w-140"+ >+ <ImportStageContent key={stage}>{children}</ImportStageContent>+ </div>+ </div>+ </PanelShell>+ </ImportMotionScope>+ )+}++export function ImportStageHeading({+ title,+ description,+ source,+ illustration,+ className,+}: {+ title: string+ description: string+ source?: string+ illustration?: ReactNode+ className?: string+}) {+ const heading = useRef<HTMLHeadingElement>(null)+ useEffect(() => {+ // A new stage starts at its heading, not the newly repurposed primary button.+ if (heading.current?.getClientRects().length)+ heading.current.focus({ preventScroll: true })+ }, [])+ return (+ <div+ className={cn(+ 'migration-stage-heading mx-auto w-full max-w-160 shrink-0 py-5 text-start',+ illustration && 'migration-stage-heading-illustrated',+ className+ )}+ >+ {illustration && (+ <div+ className="migration-stage-illustration mb-5 -ml-5 size-32"+ aria-hidden+ >+ {illustration}+ </div>+ )}+ <h2+ ref={heading}+ tabIndex={-1}+ className="text-balance text-lg font-semibold leading-tight tracking-tight outline-none"+ >+ {title}+ </h2>+ <p className="mt-1.5 text-pretty text-sm leading-relaxed text-muted-foreground">+ {description}+ </p>+ {source && (+ <p+ className="mt-2 truncate text-xs text-muted-foreground"+ title={source}+ >+ {source}+ </p>+ )}+ </div>+ )+}diff --git a/src/renderer/features/legacy-import/import-result-details.test.tsx b/src/renderer/features/legacy-import/import-result-details.test.tsxnew file mode 100644index 00000000..732a6166--- /dev/null+++ b/src/renderer/features/legacy-import/import-result-details.test.tsx@@ -0,0 +1,123 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import type { LegacyImportReport } from '@shared/schemas/legacy-import'+import { fireEvent, render, screen } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { ImportResultDetails } from './import-result-details'++const report: LegacyImportReport = {+ runId: '33333333-3333-4333-8333-333333333333',+ stage: 'completed',+ processed: 1,+ total: 1,+ imported: 1,+ backupCreated: true,+ items: [+ {+ itemId: 'one',+ name: 'one.zip',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ outcome: 'imported',+ taskId: 'new',+ },+ ],+}++beforeEach(() => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+})++describe('migration report details', () => {+ it('mounts the report only on disclosure and exports the unchanged run', () => {+ const exportReport = vi.fn()+ render(+ <ImportResultDetails+ report={report}+ busy={false}+ exportReport={exportReport}+ />+ )+ const disclosure = screen.getByRole('button', { name: 'View details' })+ expect(disclosure).toHaveAttribute('aria-expanded', 'false')+ expect(screen.queryByText('one.zip')).not.toBeInTheDocument()+ fireEvent.click(disclosure)+ expect(screen.getByTitle('one.zip')).toBeVisible()+ fireEvent.click(screen.getByRole('button', { name: 'Save report…' }))+ expect(exportReport).toHaveBeenCalledOnce()+ fireEvent.click(disclosure)+ expect(screen.queryByTitle('one.zip')).not.toBeInTheDocument()+ expect(report.items[0].outcome).toBe('imported')+ })++ it('prioritizes unfinished tasks and excludes tasks the user did not select', () => {+ const source = {+ ...report,+ items: [+ report.items[0],+ {+ ...report.items[0],+ itemId: 'failed',+ name: 'failed.zip',+ outcome: 'failed' as const,+ reason: 'commit-failed' as const,+ },+ {+ ...report.items[0],+ itemId: 'unselected',+ name: 'unselected.zip',+ outcome: 'skipped' as const,+ reason: 'not-selected' as const,+ },+ ],+ }+ render(+ <ImportResultDetails+ report={source}+ busy={false}+ exportReport={() => {}}+ />+ )+ fireEvent.click(screen.getByRole('button', { name: 'View details' }))+ const rows = document.querySelectorAll('[data-import-result]')+ expect(rows).toHaveLength(2)+ expect(rows[0]).toHaveAttribute('data-import-result', 'failed')+ expect(screen.queryByTitle('unselected.zip')).not.toBeInTheDocument()+ expect(source.items).toHaveLength(3)+ expect(source.items[0].itemId).toBe('one')+ })++ it('virtualizes large reports instead of building every hidden row', () => {+ const large = {+ ...report,+ items: Array.from({ length: 5000 }, (_, index) => ({+ ...report.items[0],+ itemId: `item-${index}`,+ name: `download-${index}.zip`,+ })),+ }+ render(+ <ImportResultDetails+ report={large}+ busy={false}+ exportReport={() => {}}+ />+ )+ expect(document.querySelectorAll('[data-import-result]')).toHaveLength(0)+ fireEvent.click(screen.getByRole('button', { name: 'View details' }))+ expect(screen.getByTestId('virtual-list-container')).toBeInTheDocument()+ expect(+ document.querySelectorAll('[data-import-result]').length+ ).toBeLessThan(100)+ expect(screen.getByRole('button', { name: 'Save report…' })).toBeEnabled()+ })+})diff --git a/src/renderer/features/legacy-import/import-result-details.tsx b/src/renderer/features/legacy-import/import-result-details.tsxnew file mode 100644index 00000000..b841a353--- /dev/null+++ b/src/renderer/features/legacy-import/import-result-details.tsx@@ -0,0 +1,116 @@+import { VirtualList } from '@renderer/components/desktop-kit/virtual-list/virtual-list'+import { ChevronDownIcon, ChevronRightIcon } from '@renderer/components/icons'+import { Button } from '@renderer/components/ui/button'+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from '@renderer/components/ui/collapsible'+import type { LegacyImportReport } from '@shared/schemas/legacy-import'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { ImportTaskInfo } from './import-task-info'++export function ImportResultDetails({+ report,+ busy,+ exportReport,+}: {+ report: LegacyImportReport+ busy: boolean+ exportReport: () => void+}) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [focusedId, setFocusedId] = useState<string | null>(null)+ // Unselected tasks are outside this run. Put unfinished work first without+ // changing the source report, which is exported in full.+ const items = useMemo(+ () =>+ report.items+ .filter((item) => item.reason !== 'not-selected')+ .sort(+ (a, b) =>+ Number(b.outcome === 'failed' || b.outcome === 'unprocessed') -+ Number(a.outcome === 'failed' || a.outcome === 'unprocessed')+ ),+ [report.items]+ )+ const row = (item: LegacyImportReport['items'][number]) => (+ <div+ data-import-result={item.itemId}+ className={`flex h-16 items-center justify-between gap-3 border-border/70 px-4 py-1 ${item.itemId === items[0]?.itemId ? '' : 'border-t'}`}+ key={item.itemId}+ >+ <ImportTaskInfo item={item} showReason={item.outcome !== 'imported'} />+ <span+ className={+ item.outcome === 'failed'+ ? 'shrink-0 text-xs text-destructive'+ : 'shrink-0 text-xs text-muted-foreground'+ }+ >+ {t(`legacyImport.page.outcomes.${item.outcome}`)}+ </span>+ </div>+ )+ return (+ <Collapsible+ open={open}+ onOpenChange={setOpen}+ className={`migration-result-details mt-5 flex min-h-0 flex-col overflow-hidden text-xs ${open ? 'flex-1' : 'shrink-0'}`}+ >+ <CollapsibleTrigger+ render={<Button variant="ghost" size="sm" />}+ className="w-fit shrink-0 justify-start gap-1.5 px-0 has-[>svg]:px-0 text-xs text-muted-foreground hover:bg-transparent hover:text-foreground"+ >+ {t('legacyImport.details')}+ {open ? (+ <ChevronDownIcon aria-hidden="true" />+ ) : (+ <ChevronRightIcon aria-hidden="true" className="rtl:rotate-180" />+ )}+ </CollapsibleTrigger>+ <CollapsibleContent className="mt-3 flex max-h-80 min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/70">+ {open && (+ <>+ {items.length > 100 ? (+ <VirtualList+ items={items}+ getId={(item) => item.itemId}+ rowHeight={64}+ className="min-h-0 flex-1"+ keepMountedIndex={items.findIndex(+ (item) => item.itemId === focusedId+ )}+ containerProps={{+ onFocusCapture: (event) => {+ const item = (+ event.target as HTMLElement+ ).closest<HTMLElement>('[data-import-result]')+ if (item) setFocusedId(item.dataset.importResult ?? null)+ },+ }}+ renderRow={({ item }) => row(item)}+ />+ ) : (+ <div className="min-h-0 flex-1 overflow-auto">+ {items.map(row)}+ </div>+ )}+ <div className="shrink-0 border-t border-border/70 px-4 py-3">+ <Button+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={exportReport}+ >+ {t('legacyImport.exportReport')}+ </Button>+ </div>+ </>+ )}+ </CollapsibleContent>+ </Collapsible>+ )+}diff --git a/src/renderer/features/legacy-import/import-run-content.test.tsx b/src/renderer/features/legacy-import/import-run-content.test.tsxnew file mode 100644index 00000000..c75d7a97--- /dev/null+++ b/src/renderer/features/legacy-import/import-run-content.test.tsx@@ -0,0 +1,112 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import type { LegacyImportReport } from '@shared/schemas/legacy-import'+import { render, screen, within } from '@testing-library/react'+import { describe, expect, it } from 'vitest'+import { ImportRunProgress, ImportRunResult } from './import-run-content'++const report: LegacyImportReport = {+ runId: '33333333-3333-4333-8333-333333333333',+ stage: 'committing',+ processed: 1,+ total: 3,+ imported: 1,+ backupCreated: true,+ items: ['imported', 'failed', 'unprocessed', 'skipped'].map(+ (outcome, index) => ({+ itemId: String(index),+ name: `${index}.zip`,+ type: 'http',+ selectable: true,+ reason: outcome === 'skipped' ? 'not-selected' : 'commit-failed',+ outcome: outcome as LegacyImportReport['items'][number]['outcome'],+ taskId: index === 0 ? 'new' : null,+ })+ ),+}++describe('migration run feedback', () => {+ it('does not invent a percentage while preparing the backup', () => {+ render(<ImportRunProgress report={null} />)+ expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow')+ expect(screen.getByText('Waiting for the backup')).toBeVisible()+ expect(screen.queryByText('Backup saved')).not.toBeInTheDocument()+ })++ it('keeps the empty fill initialized while backup changes to a determinate run', () => {+ const view = render(<ImportRunProgress report={null} />)+ const progress = screen.getByRole('progressbar')+ const fill = progress.querySelector('.migration-progress-fill')+ expect(fill).toBeInTheDocument()+ expect(progress.style.getPropertyValue('--migration-progress')).toBe('0')+ expect(fill).toHaveClass('animate-none')+ view.rerender(+ <ImportRunProgress report={{ ...report, processed: 0, imported: 0 }} />+ )+ expect(progress.querySelector('.migration-progress-fill')).toBe(fill)+ expect(progress.style.getPropertyValue('--migration-progress')).toBe('0')+ expect(progress).toHaveAttribute('aria-valuenow', '0')+ view.rerender(<ImportRunProgress report={report} />)+ expect(progress.style.getPropertyValue('--migration-progress')).toBe(+ String(1 / 3)+ )+ })++ it('uses actual processed work, rather than imported work, for progress', () => {+ render(<ImportRunProgress report={{ ...report, processed: 2 }} />)+ expect(screen.getByRole('progressbar')).toHaveAttribute(+ 'aria-valuenow',+ String((2 / 3) * 100)+ )+ expect(screen.getByText('2 / 3 processed')).toBeVisible()+ expect(screen.getByText('Backup saved')).toBeVisible()+ expect(screen.getByText('Add downloads').closest('li')).toHaveAttribute(+ 'aria-current',+ 'step'+ )+ })++ it('summarizes unfinished work without counting unselected tasks', () => {+ render(+ <ImportRunResult+ report={{ ...report, stage: 'completed' }}+ busy={false}+ exportReport={() => {}}+ />+ )+ expect(+ screen.getByRole('heading', { name: 'Migration is incomplete' })+ ).toBeVisible()+ const summary = screen.getByLabelText('Migration summary')+ expect(within(summary).getByText('1 task')).toBeVisible()+ expect(within(summary).getByText('2 tasks')).toBeVisible()+ expect(within(summary).queryByText('Skipped')).not.toBeInTheDocument()+ expect(+ screen.getByText(+ 'Imported tasks are paused. You can retry the remaining tasks or view your downloads.'+ )+ ).toBeVisible()+ })++ it('does not describe paused downloads when nothing was imported', () => {+ render(+ <ImportRunResult+ report={{ ...report, stage: 'cancelled', imported: 0 }}+ busy={false}+ exportReport={() => {}}+ />+ )+ expect(+ screen.getByRole('heading', { name: 'Migration stopped' })+ ).toBeVisible()+ expect(+ screen.getByText(+ 'No tasks were added. You can try again when you’re ready.'+ )+ ).toBeVisible()+ expect(+ screen.queryByText(/Imported tasks are paused/)+ ).not.toBeInTheDocument()+ })+})diff --git a/src/renderer/features/legacy-import/import-run-content.tsx b/src/renderer/features/legacy-import/import-run-content.tsxnew file mode 100644index 00000000..da23bd33--- /dev/null+++ b/src/renderer/features/legacy-import/import-run-content.tsx@@ -0,0 +1,211 @@+import { CheckIcon } from '@renderer/components/icons'+import { Progress } from '@renderer/components/ui/progress'+import { Spinner } from '@renderer/components/ui/spinner'+import type { LegacyImportReport } from '@shared/schemas/legacy-import'+import type { CSSProperties, ReactNode } from 'react'+import { useTranslation } from 'react-i18next'+import { ImportStageHeading } from './import-page-layout'+import { ImportResultDetails } from './import-result-details'++function RunStep({+ title,+ description,+ state,+ children,+}: {+ title: string+ description: string+ state: 'active' | 'done' | 'waiting'+ children?: ReactNode+}) {+ return (+ <li+ className="migration-run-step relative flex gap-3"+ aria-current={state === 'active' ? 'step' : undefined}+ >+ <span+ aria-hidden="true"+ className="relative z-1 flex size-6 shrink-0 items-center justify-center bg-background"+ >+ {state === 'done' ? (+ <CheckIcon className="size-4" />+ ) : state === 'active' ? (+ <Spinner aria-hidden="true" className="size-4" />+ ) : (+ <span className="size-2 rounded-full bg-muted-foreground/30" />+ )}+ </span>+ <div className="min-w-0 flex-1 pt-0.5">+ <p+ className={`text-sm leading-5 ${state === 'waiting' ? 'text-muted-foreground' : 'font-medium'}`}+ >+ {title}+ </p>+ <p className="mt-1 text-xs leading-5 tabular-nums text-muted-foreground">+ {description}+ </p>+ {children}+ </div>+ </li>+ )+}++export function ImportRunProgress({+ report,+ notice,+}: {+ report: LegacyImportReport | null+ notice?: ReactNode+}) {+ const { t } = useTranslation()+ const committing = report?.stage === 'committing'+ const fraction =+ committing && report.total > 0+ ? Math.min(1, Math.max(0, report.processed / report.total))+ : 0+ return (+ <div className="migration-run-content flex min-h-0 flex-col py-6">+ <ImportStageHeading+ title={t('legacyImport.page.progressTitle')}+ description={t('legacyImport.preserveFiles')}+ className="pt-0 pb-8"+ />+ {notice}+ <span className="sr-only" role="status">+ {t(committing ? 'legacyImport.committing' : 'legacyImport.backingUp')}+ </span>+ <ol className="space-y-7" aria-label={t('legacyImport.page.stepsLabel')}>+ <RunStep+ title={t('legacyImport.page.run.backup')}+ description={t(+ report?.backupCreated+ ? 'legacyImport.page.run.backupDone'+ : 'legacyImport.page.run.backupActive'+ )}+ state={report?.backupCreated ? 'done' : 'active'}+ />+ <RunStep+ title={t('legacyImport.page.run.add')}+ description={+ committing+ ? t('legacyImport.processed', {+ done: report.processed,+ total: report.total,+ })+ : t('legacyImport.page.run.waiting')+ }+ state={committing ? 'active' : 'waiting'}+ >+ <Progress+ value={committing ? fraction * 100 : undefined}+ className="mt-4 h-1"+ aria-label={t('legacyImport.progress')}+ aria-valuetext={+ committing+ ? t('legacyImport.processed', {+ done: report.processed,+ total: report.total,+ })+ : t('legacyImport.backingUp')+ }+ // Keep scaleX(0) from the first paint. Adding the transform only+ // after backup would animate from the default full-width scale.+ indicatorClassName="migration-progress-fill w-full! animate-none"+ style={{ '--migration-progress': fraction } as CSSProperties}+ />+ </RunStep>+ </ol>+ </div>+ )+}++export function ImportRunResult({+ report,+ busy,+ notice,+ exportReport,+}: {+ report: LegacyImportReport+ busy: boolean+ notice?: ReactNode+ exportReport: () => void+}) {+ const { t } = useTranslation()+ const remaining = report.items.filter(+ (item) => item.outcome === 'failed' || item.outcome === 'unprocessed'+ ).length+ const skipped = report.items.filter(+ (item) => item.outcome === 'skipped' && item.reason !== 'not-selected'+ ).length+ const titleKey =+ report.stage === 'cancelled'+ ? 'legacyImport.resultStoppedTitle'+ : report.stage === 'failed' || remaining > 0+ ? 'legacyImport.resultIncompleteTitle'+ : report.imported === 0+ ? 'legacyImport.page.resultEmptyTitle'+ : 'legacyImport.resultTitle'+ const descriptionKey =+ report.imported > 0+ ? remaining > 0+ ? 'legacyImport.page.run.partialDescription'+ : 'legacyImport.page.run.completeDescription'+ : report.stage === 'cancelled'+ ? 'legacyImport.page.run.stoppedEmptyDescription'+ : report.stage === 'failed' || remaining > 0+ ? 'legacyImport.page.run.failedEmptyDescription'+ : 'legacyImport.page.resultEmptyDescription'+ return (+ <div className="migration-run-content flex min-h-0 flex-col py-6">+ <ImportStageHeading+ title={t(titleKey)}+ description={t(descriptionKey)}+ className="pt-0 pb-8"+ />+ {notice}+ <dl+ aria-label={t('legacyImport.page.resultSummary')}+ className="shrink-0 divide-y divide-border/70 border-y border-border/70 text-sm"+ >+ <div className="flex items-center justify-between gap-4 py-4">+ <dt>{t('legacyImport.page.run.imported')}</dt>+ <dd className="flex items-center gap-2 tabular-nums">+ {report.imported > 0 && (+ <CheckIcon+ aria-hidden="true"+ className="size-3.5 text-muted-foreground"+ />+ )}+ <span>+ {t('legacyImport.page.groupCount', { count: report.imported })}+ </span>+ </dd>+ </div>+ {remaining > 0 && (+ <div className="flex items-center justify-between gap-4 py-4">+ <dt>{t('legacyImport.page.run.remaining')}</dt>+ <dd className="tabular-nums">+ {t('legacyImport.page.groupCount', { count: remaining })}+ </dd>+ </div>+ )}+ {skipped > 0 && (+ <div className="flex items-center justify-between gap-4 py-4">+ <dt>{t('legacyImport.page.skippedSummary')}</dt>+ <dd className="tabular-nums">+ {t('legacyImport.page.groupCount', { count: skipped })}+ </dd>+ </div>+ )}+ </dl>+ <p className="mt-4 shrink-0 text-xs leading-5 text-muted-foreground">+ {t('legacyImport.preserveFiles')}+ </p>+ <ImportResultDetails+ report={report}+ busy={busy}+ exportReport={exportReport}+ />+ </div>+ )+}diff --git a/src/renderer/features/legacy-import/import-source-feedback.tsx b/src/renderer/features/legacy-import/import-source-feedback.tsxnew file mode 100644index 00000000..538eb3e9--- /dev/null+++ b/src/renderer/features/legacy-import/import-source-feedback.tsx@@ -0,0 +1,50 @@+import { Button } from '@renderer/components/ui/button'+import { useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'++export function ImportSourceFeedback({+ id,+ title,+ description,+ busy,+ onRetry,+}: {+ id: string+ title: string+ description: string+ busy: boolean+ onRetry?: () => void+}) {+ const { t } = useTranslation()+ const notice = useRef<HTMLDivElement>(null)+ useEffect(() => {+ if (notice.current?.getClientRects().length) {+ notice.current.focus({ preventScroll: true })+ notice.current.scrollIntoView({ block: 'nearest', behavior: 'instant' })+ }+ }, [])+ return (+ <div+ ref={notice}+ id={id}+ role="alert"+ tabIndex={-1}+ className="mt-2 space-y-1 ps-7 text-xs leading-relaxed outline-none"+ >+ <p className="font-medium text-foreground">{title}</p>+ <p className="text-muted-foreground">{description}</p>+ {onRetry && (+ <Button+ type="button"+ variant="link"+ size="sm"+ disabled={busy}+ onClick={onRetry}+ className="h-auto px-0 py-1 text-xs"+ >+ {t('legacyImport.page.sourceFeedback.retry')}+ </Button>+ )}+ </div>+ )+}diff --git a/src/renderer/features/legacy-import/import-task-info.tsx b/src/renderer/features/legacy-import/import-task-info.tsxnew file mode 100644index 00000000..102ff3fa--- /dev/null+++ b/src/renderer/features/legacy-import/import-task-info.tsx@@ -0,0 +1,44 @@+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'+import { Badge } from '@renderer/components/ui/badge'+import type { LegacyImportItem } from '@shared/schemas/legacy-import'+import { useTranslation } from 'react-i18next'++/** The path describes the original save directory, not a new destination. */+export function ImportTaskInfo({+ item,+ showReason = true,+}: {+ item: LegacyImportItem+ showReason?: boolean+}) {+ const { t } = useTranslation()+ const reason = 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">+ <MiddleEllipsis+ text={item.name}+ className="min-w-0 font-sans! text-[13px] font-medium"+ />+ <Badge variant="secondary" className="border-border">+ {t(`legacyImport.page.types.${item.type}`)}+ </Badge>+ </div>+ <p className="flex min-w-0 text-xs leading-4 text-foreground/70">+ {item.saveDir ? (+ <MiddleEllipsis text={item.saveDir} className="font-sans!" />+ ) : (+ t('legacyImport.page.pathUnavailable')+ )}+ </p>+ {showReason && item.reason !== 'metadata-required' && (+ <p+ title={reason}+ className="truncate text-xs leading-4 text-foreground/70"+ >+ {reason}+ </p>+ )}+ </div>+ )+}diff --git a/src/renderer/features/legacy-import/import-task-selection.test.tsx b/src/renderer/features/legacy-import/import-task-selection.test.tsxnew file mode 100644index 00000000..af192611--- /dev/null+++ b/src/renderer/features/legacy-import/import-task-selection.test.tsx@@ -0,0 +1,167 @@+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import type { LegacyImportItem } from '@shared/schemas/legacy-import'+import { fireEvent, render, screen, within } from '@testing-library/react'+import { useState } from 'react'+import { describe, expect, it } from 'vitest'+import {+ ImportTaskSelection,+ initialExpandedGroups,+} from './import-task-selection'++const items: LegacyImportItem[] = [+ {+ itemId: 'a',+ name: 'first.zip',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ },+ {+ itemId: 'b',+ name: 'second.zip',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ },+ {+ itemId: 'skipped',+ name: 'previous.zip',+ type: 'http',+ selectable: false,+ reason: 'already-imported',+ },+ {+ itemId: 'torrent',+ name: 'linux.iso',+ type: 'bt',+ selectable: true,+ reason: 'verification-required',+ },+]++function Harness({ tasks = items }: { tasks?: LegacyImportItem[] }) {+ const [selected, setSelected] = useState(+ new Set(tasks.filter((item) => item.selectable).map((item) => item.itemId))+ )+ const [expanded, setExpanded] = useState(initialExpandedGroups(tasks))+ const [query, setQuery] = useState('')+ return (+ <>+ <output aria-label="Selected">{selected.size}</output>+ <ImportTaskSelection+ items={tasks}+ selected={selected}+ setSelected={setSelected}+ expanded={expanded}+ setExpanded={setExpanded}+ query={query}+ setQuery={setQuery}+ busy={false}+ running={false}+ chooseTorrent={() => {}}+ />+ </>+ )+}++describe('migration content groups', () => {+ it('keeps selection and disclosure independent, counts skipped tasks, and exposes a mixed group', () => {+ render(<Harness />)+ const group = screen.getByRole('checkbox', { name: 'Select Direct links' })+ const disclosure = screen.getByRole('button', { name: 'Direct links' })+ expect(group).toBeChecked()+ expect(disclosure).toHaveAttribute('aria-expanded', 'false')+ expect(+ within(+ disclosure.closest('[data-import-group]') as HTMLElement+ ).getByText('3 tasks')+ ).toBeVisible()+ fireEvent.click(disclosure)+ expect(group).toBeChecked()+ const skipped = screen.getByRole('checkbox', { name: 'previous.zip' })+ expect(skipped).toHaveAttribute('aria-disabled', 'true')+ expect(skipped).not.toBeChecked()+ fireEvent.click(screen.getByRole('checkbox', { name: 'first.zip' }))+ expect(group).toHaveAttribute('aria-checked', 'mixed')+ expect(group.querySelector('[data-icon="subtract"]')).toBeInTheDocument()+ expect(screen.getByRole('status')).toHaveTextContent('2')+ fireEvent.click(disclosure)+ expect(group).toHaveAttribute('aria-checked', 'mixed')+ fireEvent.click(group)+ expect(group).toBeChecked()+ expect(screen.getByRole('status')).toHaveTextContent('3')+ expect(+ screen.getByRole('checkbox', { name: 'Select Torrent downloads' })+ ).toBeChecked()+ })++ it('changes the whole eligible group while search filters only its visible rows', () => {+ const tasks: LegacyImportItem[] = Array.from(+ { length: 21 },+ (_, index) => ({+ itemId: `task-${index}`,+ name: index === 0 ? 'match.zip' : `hidden-${index}.zip`,+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ })+ )+ tasks.push({+ itemId: 'skipped',+ name: 'skipped.zip',+ type: 'http',+ selectable: false,+ reason: 'already-imported',+ })+ render(<Harness tasks={tasks} />)+ fireEvent.change(+ screen.getByRole('textbox', { name: 'Search downloads' }),+ { target: { value: 'match' } }+ )+ expect(+ screen.queryByRole('checkbox', { name: 'hidden-1.zip' })+ ).not.toBeInTheDocument()+ fireEvent.click(+ screen.getByRole('checkbox', { name: 'Select Direct links' })+ )+ expect(screen.getByRole('status')).toHaveTextContent('0')+ fireEvent.click(screen.getByRole('checkbox', { name: 'match.zip' }))+ expect(+ screen.getByRole('checkbox', { name: 'Select Direct links' })+ ).toHaveAttribute('aria-checked', 'mixed')+ fireEvent.click(+ screen.getByRole('checkbox', { name: 'Select Direct links' })+ )+ expect(screen.getByRole('status')).toHaveTextContent('21')+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '' } })+ expect(screen.getByRole('checkbox', { name: 'hidden-1.zip' })).toBeChecked()+ expect(+ screen.getByRole('checkbox', { name: 'skipped.zip' })+ ).not.toBeChecked()+ })++ it('does not allow a fully skipped group to enter the selection', () => {+ render(+ <Harness+ tasks={[+ {+ itemId: 'invalid',+ name: 'unreadable',+ type: 'unknown',+ selectable: false,+ reason: 'invalid-record',+ },+ ]}+ />+ )+ expect(+ screen.getByRole('checkbox', { name: 'Select Other downloads' })+ ).toHaveAttribute('aria-disabled', 'true')+ expect(+ screen.getByRole('checkbox', { name: 'unreadable' })+ ).toHaveAttribute('aria-disabled', 'true')+ expect(screen.getByRole('status')).toHaveTextContent('0')+ expect(screen.getByText('Couldn’t read this task')).toBeVisible()+ })+})diff --git a/src/renderer/features/legacy-import/import-task-selection.tsx b/src/renderer/features/legacy-import/import-task-selection.tsxnew file mode 100644index 00000000..f5804217--- /dev/null+++ b/src/renderer/features/legacy-import/import-task-selection.tsx@@ -0,0 +1,255 @@+import { VirtualList } from '@renderer/components/desktop-kit/virtual-list/virtual-list'+import { ChevronDownIcon, ChevronRightIcon } from '@renderer/components/icons'+import { Button } from '@renderer/components/ui/button'+import { Checkbox } from '@renderer/components/ui/checkbox'+import { Input } from '@renderer/components/ui/input'+import type { LegacyImportItem } from '@shared/schemas/legacy-import'+import {+ type Dispatch,+ type SetStateAction,+ useId,+ useMemo,+ useState,+} from 'react'+import { useTranslation } from 'react-i18next'+import { ImportTaskInfo } from './import-task-info'++export const importTaskTypes = ['http', 'bt', 'magnet', 'unknown'] as const+type TaskType = LegacyImportItem['type']+type SelectionRow =+ | { kind: 'group'; type: TaskType; items: LegacyImportItem[] }+ | { kind: 'task'; item: LegacyImportItem }++export function initialExpandedGroups(items: LegacyImportItem[]) {+ const types = new Set(items.map((item) => item.type))+ return new Set(+ items+ .filter((item) => types.size === 1 || item.reason === 'metadata-required')+ .map((item) => item.type)+ )+}++/** A group always selects its full eligible contents, even while searching. */+export function toggleImportGroup(+ selected: ReadonlySet<string>,+ items: LegacyImportItem[],+ checked: boolean+) {+ const next = new Set(selected)+ for (const item of items) {+ if (!item.selectable) continue+ if (checked) next.add(item.itemId)+ else next.delete(item.itemId)+ }+ return next+}++export function ImportTaskSelection({+ items,+ selected,+ setSelected,+ expanded,+ setExpanded,+ query,+ setQuery,+ busy,+ running,+ chooseTorrent,+}: {+ items: LegacyImportItem[]+ selected: ReadonlySet<string>+ setSelected: Dispatch<SetStateAction<Set<string>>>+ expanded: ReadonlySet<TaskType>+ setExpanded: Dispatch<SetStateAction<Set<TaskType>>>+ query: string+ setQuery: (query: string) => void+ busy: boolean+ running: boolean+ chooseTorrent: (item: LegacyImportItem) => void+}) {+ const { t } = useTranslation()+ const id = useId()+ const [focusedId, setFocusedId] = useState<string | null>(null)+ const search = query.trim().toLocaleLowerCase()+ const rows = useMemo(() => {+ const next: SelectionRow[] = []+ for (const type of importTaskTypes) {+ const group = items.filter((item) => item.type === type)+ const visible = group.filter((item) =>+ `${item.name} ${item.saveDir ?? ''}`+ .toLocaleLowerCase()+ .includes(search)+ )+ if (!group.length || (search && !visible.length)) continue+ next.push({ kind: 'group', type, items: group })+ if (search || expanded.has(type))+ next.push(+ ...visible.map((item): SelectionRow => ({ kind: 'task', item }))+ )+ }+ return next+ }, [items, expanded, search])+ const renderRow = (row: SelectionRow) => {+ if (row.kind === 'task') {+ const { item } = row+ return (+ <div+ key={item.itemId}+ data-import-task={item.itemId}+ data-import-row={item.itemId}+ data-selected={selected.has(item.itemId)}+ className="migration-task-row flex h-14 items-center gap-2 py-0.5 pe-3 ps-11"+ >+ <Checkbox+ aria-label={item.name}+ disabled={busy || !item.selectable}+ checked={item.selectable && selected.has(item.itemId)}+ onCheckedChange={(checked) =>+ setSelected((current) =>+ toggleImportGroup(current, [item], checked)+ )+ }+ />+ <ImportTaskInfo item={item} />+ {item.type === 'bt' && item.reason === 'metadata-required' && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="max-w-32 whitespace-normal text-xs"+ disabled={busy || running}+ onClick={() => chooseTorrent(item)}+ >+ {t('legacyImport.chooseTorrent')}+ </Button>+ )}+ </div>+ )+ }+ const eligible = row.items.filter((item) => item.selectable)+ const count = eligible.filter((item) => selected.has(item.itemId)).length+ const isOpen = Boolean(search) || expanded.has(row.type)+ const title = t(`legacyImport.page.groups.${row.type}`)+ const groupId = `${id}-${row.type}`+ return (+ <div+ key={row.type}+ data-import-group={row.type}+ data-import-row={`group:${row.type}`}+ className="flex h-14 items-center gap-2 px-3"+ >+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="shrink-0"+ aria-label={title}+ aria-expanded={isOpen}+ disabled={Boolean(search)}+ onClick={() =>+ setExpanded((current) => {+ const next = new Set(current)+ if (next.has(row.type)) next.delete(row.type)+ else next.add(row.type)+ return next+ })+ }+ >+ {isOpen ? (+ <ChevronDownIcon aria-hidden="true" className="size-4" />+ ) : (+ <ChevronRightIcon+ aria-hidden="true"+ className="size-4 rtl:rotate-180"+ />+ )}+ </Button>+ <Checkbox+ id={groupId}+ aria-labelledby={`${groupId}-label`}+ disabled={busy || eligible.length === 0}+ checked={eligible.length > 0 && count === eligible.length}+ indeterminate={count > 0 && count < eligible.length}+ onCheckedChange={(checked) =>+ setSelected((current) =>+ toggleImportGroup(current, row.items, checked)+ )+ }+ />+ <span id={`${groupId}-label`} className="sr-only">+ {t('legacyImport.page.selectGroup', { name: title })}+ </span>+ <label htmlFor={groupId} className="min-w-0 flex-1 cursor-pointer">+ <span className="block text-[13px] font-medium">{title}</span>+ </label>+ <span className="shrink-0 text-xs tabular-nums text-foreground/80">+ {t('legacyImport.page.groupCount', { count: row.items.length })}+ </span>+ </div>+ )+ }+ return (+ <>+ {items.length > 20 && (+ <div className="mx-auto mb-3 w-full max-w-160 shrink-0">+ <Input+ aria-label={t('legacyImport.search')}+ placeholder={t('legacyImport.search')}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ </div>+ )}+ <div+ data-slot="migration-task-selection"+ className="mx-auto flex min-h-30 w-full max-w-160 flex-1 flex-col overflow-hidden rounded-md border border-border"+ // Include both borders so a fitting list does not scroll by two pixels.+ style={{ maxHeight: Math.max(120, rows.length * 56 + 2) }}+ >+ {items.length > 100 ? (+ <VirtualList+ items={rows}+ getId={(row) =>+ row.kind === 'group' ? `group:${row.type}` : row.item.itemId+ }+ rowHeight={56}+ keepMountedIndex={rows.findIndex(+ (row) =>+ (row.kind === 'group'+ ? `group:${row.type}`+ : row.item.itemId) === focusedId+ )}+ containerProps={{+ onFocusCapture: (event) => {+ const row = (event.target as HTMLElement).closest<HTMLElement>(+ '[data-import-row]'+ )+ if (row) setFocusedId(row.dataset.importRow ?? null)+ },+ }}+ className="min-h-0 flex-1"+ renderRow={({ item }) => renderRow(item)}+ renderEmpty={() => <EmptySelection searching={Boolean(search)} />}+ />+ ) : (+ <div className="min-h-0 flex-1 overflow-auto">+ {rows.length ? (+ rows.map(renderRow)+ ) : (+ <EmptySelection searching={Boolean(search)} />+ )}+ </div>+ )}+ </div>+ </>+ )+}++function EmptySelection({ searching }: { searching: boolean }) {+ const { t } = useTranslation()+ return (+ <p className="px-6 py-10 text-center text-sm leading-relaxed text-muted-foreground">+ {t(searching ? 'legacyImport.page.searchEmpty' : 'legacyImport.empty')}+ </p>+ )+}diff --git a/src/renderer/features/legacy-import/legacy-fresh-download.test.tsx b/src/renderer/features/legacy-import/legacy-fresh-download.test.tsxnew file mode 100644index 00000000..fbeb5954--- /dev/null+++ b/src/renderer/features/legacy-import/legacy-fresh-download.test.tsx@@ -0,0 +1,99 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+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 { makeDownloadTask } from '@test-utils/task'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { LegacyFreshDownload } from './legacy-fresh-download'++vi.mock('@renderer/lib/transport', () => ({+ transport: { invoke: vi.fn(), platform: 'darwin' },+}))+vi.mock('@renderer/lib/open-add-task-dialog', () => ({+ openAddTaskDialog: vi.fn(),+}))+const task = makeDownloadTask({+ id: 'legacy-bt',+ type: TaskType.Bt,+ status: TaskStatus.Paused,+ saveDir: '/original/downloads',+})+describe('legacy BT activation entry', () => {+ beforeEach(() => {+ vi.mocked(transport.invoke).mockReset()+ })+ it('shows the original directory and only sends opaque task identity on explicit activation', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyBtActivationAvailability+ ? { available: true, reason: null, directory: task.saveDir }+ : false+ )+ render(<LegacyFreshDownload task={task} />)+ const button = await screen.findByRole('button', {+ name: 'Verify and continue',+ })+ await waitFor(() => expect(button).toBeEnabled())+ expect(screen.getByText(task.saveDir)).toBeVisible()+ expect(+ screen.queryByText('This version imports task records only.', {+ exact: false,+ })+ ).not.toBeInTheDocument()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.ActivateLegacyBt,+ expect.anything()+ )+ fireEvent.click(button)+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(Commands.ActivateLegacyBt, {+ taskId: task.id,+ })+ )+ expect(+ screen.getByRole('button', { name: 'Download again…' })+ ).toBeEnabled()+ })+ it('disables an unsupported engine and keeps the fresh download entry', async () => {+ vi.mocked(transport.invoke).mockResolvedValue({+ available: false,+ reason: 'legacyImport.errors.checkpointUnavailable',+ directory: task.saveDir,+ })+ render(<LegacyFreshDownload task={task} />)+ await screen.findByText(+ 'This version can’t resume the old files. You can download again in a new folder.'+ )+ expect(+ screen.getByRole('button', { name: 'Verify and continue' })+ ).toBeDisabled()+ expect(+ screen.getByRole('button', { name: 'Download again…' })+ ).toBeEnabled()+ })+ it('guards activation double clicks and recovers after picker cancellation', async () => {+ let complete: (value: boolean) => void = () => {}+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetLegacyBtActivationAvailability+ ? { available: true, reason: null, directory: task.saveDir }+ : new Promise((resolve) => {+ complete = resolve+ })+ )+ render(<LegacyFreshDownload task={task} />)+ const button = screen.getByRole('button', { name: 'Verify and continue' })+ await waitFor(() => expect(button).toBeEnabled())+ fireEvent.click(button)+ fireEvent.click(button)+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([channel]) => channel === Commands.ActivateLegacyBt)+ ).toHaveLength(1)+ complete(false)+ await waitFor(() => expect(button).toBeEnabled())+ })+})diff --git a/src/renderer/features/legacy-import/legacy-fresh-download.tsx b/src/renderer/features/legacy-import/legacy-fresh-download.tsxnew file mode 100644index 00000000..7860e3d3--- /dev/null+++ b/src/renderer/features/legacy-import/legacy-fresh-download.tsx@@ -0,0 +1,158 @@+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@renderer/components/ui/alert-dialog'+import { Button } from '@renderer/components/ui/button'+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 { legacyBtAvailabilitySchema } from '@shared/schemas/legacy-bt-activation'+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'++export function LegacyFreshDownload({ task }: { task: DownloadTask }) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [busy, setBusy] = useState(false)+ const inFlight = useRef(false)+ const [availability, setAvailability] = useState<ReturnType<+ typeof legacyBtAvailabilitySchema.parse+ > | null>(null)+ useEffect(() => {+ let current = true+ setAvailability(null)+ void transport+ .invoke(Queries.GetLegacyBtActivationAvailability, { taskId: task.id })+ .then((value) => {+ if (current) setAvailability(legacyBtAvailabilitySchema.parse(value))+ })+ .catch(() => {+ if (current)+ setAvailability({+ available: false,+ reason: 'legacyImport.errors.checkpointUnavailable',+ directory: task.saveDir,+ })+ })+ return () => {+ current = false+ }+ }, [task.id, task.saveDir])+ const activate = async () => {+ if (inFlight.current) return+ inFlight.current = true+ setBusy(true)+ try {+ await transport.invoke(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'),+ type: 'error',+ })+ } finally {+ inFlight.current = false+ setBusy(false)+ }+ }+ const prepare = async () => {+ if (inFlight.current) return+ inFlight.current = true+ setBusy(true)+ try {+ const prefill = (await transport.invoke(+ Commands.PrepareLegacyFreshDownload,+ { taskId: task.id }+ )) as AddTaskPrefill | null+ if (!prefill) return+ await openAddTaskDialog(prefill)+ setOpen(false)+ } catch (cause) {+ const message = cause instanceof Error ? cause.message : String(cause)+ const key = message.match(/legacyImport\.errors\.[a-zA-Z]+/)?.[0]+ toast.add({+ title: key ? t(key) : t('legacyImport.errors.failed'),+ type: 'error',+ })+ } finally {+ inFlight.current = false+ setBusy(false)+ }+ }+ 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')}+ </p>+ {task.type === 'bt' && (+ <div className="space-y-2">+ <p className="text-xs leading-5 text-muted-foreground">+ {t('legacyImport.verifyDescription')}+ </p>+ <p className="break-all text-xs">+ {availability?.directory ?? task.saveDir}+ </p>+ <Button+ size="sm"+ disabled={busy || !availability?.available}+ onClick={() => void activate()}+ >+ {t('legacyImport.verifyAndContinue')}+ </Button>+ </div>+ )}+ <Button+ size="sm"+ variant="outline"+ onClick={() => setOpen(true)}+ disabled={busy}+ >+ {t('legacyImport.freshDownload')}+ </Button>+ </div>+ <AlertDialog+ open={open}+ onOpenChange={(next) => {+ if (!busy) setOpen(next)+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t('legacyImport.freshDownload')}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t('legacyImport.freshDescription')}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={() => setOpen(false)}+ >+ {t('common.cancel')}+ </Button>+ <Button size="sm" disabled={busy} onClick={() => void prepare()}>+ {t('legacyImport.chooseDestination')}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}diff --git a/src/renderer/features/legacy-import/legacy-import-dialog-adversarial.test.tsx b/src/renderer/features/legacy-import/legacy-import-dialog-adversarial.test.tsxnew file mode 100644index 00000000..3b0e01b8--- /dev/null+++ b/src/renderer/features/legacy-import/legacy-import-dialog-adversarial.test.tsx@@ -0,0 +1,172 @@+import '@test-utils/dom-animations'+import '@testing-library/jest-dom/vitest'+import { i18n } from '@renderer/lib/i18n'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { LegacyImportDialog } from './legacy-import-dialog'++vi.mock('@renderer/lib/transport', () => ({+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'darwin' },+}))++const source = {+ sourceHandle: '11111111-1111-4111-8111-111111111111',+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+}+const item = {+ itemId: 'record',+ name: 'archive.zip',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+}+const preview = {+ previewId: '22222222-2222-4222-8222-222222222222',+ sourceHandle: source.sourceHandle,+ sourceName: source.name,+ items: [item],+ running: false,+ checkpointImportAvailable: false,+ expiresAt: Date.now() + 100000,+}+const run = {+ runId: '33333333-3333-4333-8333-333333333333',+ stage: 'committing',+ processed: 0,+ total: 1,+ imported: 0,+ backupCreated: true,+ items: [{ ...item, outcome: 'unprocessed', taskId: null }],+}++beforeEach(async () => {+ await i18n.changeLanguage('en-US')+ vi.mocked(transport.invoke)+ .mockReset()+ .mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport) return preview+ if (+ channel === Commands.CommitLegacyImport ||+ channel === Queries.GetLegacyImportRun+ )+ return run+ return { ok: true }+ })+})++afterEach(async () => {+ cleanup()+ await i18n.changeLanguage('en-US')+})++describe('legacy import UI adversarial state', () => {+ it('defers full scanning until Continue and prevents duplicate scans while waiting', async () => {+ let resolveScan!: (value: unknown) => void+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport)+ return new Promise((resolve) => {+ resolveScan = resolve+ })+ return { ok: true }+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ const button = await screen.findByRole('button', { name: 'Continue' })+ await waitFor(() => expect(button).toBeEnabled())+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Queries.ScanLegacyImport,+ expect.anything()+ )+ fireEvent.click(button)+ fireEvent.click(button)+ expect(button).toBeDisabled()+ expect(+ screen.getByRole('radio', { name: source.dataPath })+ ).toHaveAttribute('aria-disabled', 'true')+ expect(+ screen.getByRole('button', { name: 'Choose another location…' })+ ).toBeDisabled()+ expect(+ screen.queryByRole('heading', { name: 'Choose what to migrate' })+ ).not.toBeInTheDocument()+ await act(async () => resolveScan(preview))+ expect(+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ ).toBeVisible()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([channel]) => channel === Queries.ScanLegacyImport)+ ).toHaveLength(1)+ })++ it('preserves the active run when the user changes language', async () => {+ render(<LegacyImportDialog open onClose={vi.fn()} />)+ const continueButton = await screen.findByRole('button', {+ name: 'Continue',+ })+ await waitFor(() => expect(continueButton).toBeEnabled())+ fireEvent.click(continueButton)+ expect(+ await screen.findByRole('checkbox', { name: 'Select Direct links' })+ ).toBeChecked()+ fireEvent.click(await screen.findByRole('button', { name: 'Migrate' }))+ await screen.findByRole('progressbar')+ await act(async () => {+ await i18n.changeLanguage('zh-CN')+ })+ expect(screen.getByRole('progressbar')).toBeInTheDocument()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(+ ([channel]) => channel === Queries.DiscoverLegacyImport+ )+ ).toHaveLength(1)+ })++ it('starts a fresh scan after reopening while the previous scan is unresolved', async () => {+ let resolveFirst: (value: unknown) => void = () => {}+ let discoveryCalls = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) {+ if (++discoveryCalls === 1)+ return new Promise((resolve) => {+ resolveFirst = resolve+ })+ return [source]+ }+ if (channel === Queries.ScanLegacyImport) return preview+ return { ok: true }+ })+ const close = vi.fn()+ const view = render(<LegacyImportDialog open onClose={close} />)+ await waitFor(() => expect(discoveryCalls).toBe(1))+ view.rerender(<LegacyImportDialog open={false} onClose={close} />)+ view.rerender(<LegacyImportDialog open onClose={close} />)+ await act(async () => {+ resolveFirst([])+ })+ const continueButton = await screen.findByRole('button', {+ name: 'Continue',+ })+ await waitFor(() => expect(continueButton).toBeEnabled())+ fireEvent.click(continueButton)+ expect(+ await screen.findByRole('checkbox', { name: 'archive.zip' })+ ).toBeChecked()+ expect(discoveryCalls).toBe(2)+ })+})diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsxnew file mode 100644index 00000000..2521f021--- /dev/null+++ b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx@@ -0,0 +1,574 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { LegacyImportDialog } from './legacy-import-dialog'++vi.mock('@renderer/lib/transport', () => ({+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'darwin' },+}))+const sourceHandle = '11111111-1111-4111-8111-111111111111'+const previewId = '22222222-2222-4222-8222-222222222222'+const runId = '33333333-3333-4333-8333-333333333333'+const items = [+ {+ itemId: 'gid:1111111111111111',+ name: 'archive.zip',+ saveDir: '/Users/example/Downloads/Project files',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ },+]+const preview = {+ previewId,+ sourceHandle,+ sourceName: 'Motrix',+ items,+ running: false,+ checkpointImportAvailable: false,+ expiresAt: Date.now() + 100000,+}+const report = {+ runId,+ stage: 'completed',+ processed: 1,+ total: 1,+ imported: 1,+ backupCreated: true,+ items: items.map((item) => ({+ ...item,+ outcome: 'imported',+ taskId: 'new-task',+ })),+}++async function continueFromSource() {+ const button = await screen.findByRole('button', {+ name: 'Continue',+ })+ await waitFor(() => expect(button).toBeEnabled())+ fireEvent.click(button)+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ for (const group of document.querySelectorAll<HTMLButtonElement>(+ '[data-import-group] button[aria-expanded="false"]'+ ))+ fireEvent.click(group)+}++class MockResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}++describe('legacy import dialog', () => {+ beforeEach(() => {+ vi.stubGlobal('ResizeObserver', MockResizeObserver)+ vi.mocked(transport.invoke)+ .mockReset()+ .mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport) return preview+ if (+ channel === Commands.CommitLegacyImport ||+ channel === Queries.GetLegacyImportRun+ )+ return report+ return { ok: true }+ })+ })++ 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(+ await screen.findByRole('heading', {+ name: 'Where would you like to migrate from?',+ })+ ).toBeVisible()+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ expect(+ screen.queryByRole('checkbox', { name: 'archive.zip' })+ ).not.toBeInTheDocument()+ expect(+ screen.getByRole('radio', {+ name: '/Users/example/Library/Application Support/Motrix',+ })+ ).toBeVisible()+ expect(screen.queryByText('Downloads found: 1')).not.toBeInTheDocument()+ expect(+ screen.queryByText('Downloads from the previous version')+ ).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Show in folder' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.RevealLegacyImportSource,+ { sourceHandle }+ )+ )+ expect(screen.getByRole('radio', { name: /Motrix/ })).toBeChecked()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Queries.ScanLegacyImport,+ expect.anything()+ )+ await continueFromSource()+ fireEvent.click(screen.getByRole('checkbox', { name: 'archive.zip' }))+ fireEvent.click(screen.getByRole('button', { name: 'Back to source' }))+ fireEvent.click(screen.getByRole('radio', { name: /Motrix/ }))+ await continueFromSource()+ expect(+ screen.getByRole('checkbox', { name: 'archive.zip' })+ ).not.toBeChecked()+ expect(screen.getByRole('button', { name: 'Migrate' })).toBeDisabled()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([channel]) => channel === Queries.ScanLegacyImport)+ ).toHaveLength(1)+ })++ it('invalidates the old preview on source change and reauthorizes an unreadable source before scanning it again', async () => {+ const other = {+ sourceHandle: '55555555-5555-4555-8555-555555555555',+ name: 'Backup',+ dataPath: '/Volumes/Backup/Motrix',+ }+ let backupScans = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel, payload) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ other,+ ]+ if (channel === Queries.ScanLegacyImport) {+ if (+ (payload as { sourceHandle: string }).sourceHandle ===+ other.sourceHandle+ ) {+ if (++backupScans === 1)+ throw new Error('legacyImport.errors.invalidSource')+ return {+ ...preview,+ sourceHandle: other.sourceHandle,+ sourceName: other.name,+ items: [{ ...items[0], itemId: 'backup-task', name: 'backup.zip' }],+ }+ }+ return preview+ }+ if (channel === Commands.PickLegacyImportSource) return other+ return undefined+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ fireEvent.click(screen.getByRole('checkbox', { name: 'archive.zip' }))+ fireEvent.click(screen.getByRole('button', { name: 'Back to source' }))+ fireEvent.click(screen.getByRole('radio', { name: /Backup/ }))+ expect(backupScans).toBe(0)+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ await screen.findByRole('alert')+ expect(+ screen.queryByRole('button', { name: 'Continue' })+ ).not.toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'Choose another location…' })+ ).toBeEnabled()+ expect(+ screen.queryByRole('button', { name: /Migrate/ })+ ).not.toBeInTheDocument()+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ await continueFromSource()+ expect(screen.getByRole('checkbox', { name: 'backup.zip' })).toBeChecked()+ expect(+ screen.queryByRole('checkbox', { name: 'archive.zip' })+ ).not.toBeInTheDocument()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ expect.anything()+ )+ })++ it('shows folder fallback when discovery has no source and uses the authorized picked source', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return []+ if (channel === Commands.PickLegacyImportSource)+ return {+ sourceHandle,+ name: 'Picked folder',+ dataPath: '/Volumes/Backup/Motrix',+ }+ if (channel === Queries.ScanLegacyImport)+ return { ...preview, sourceName: 'Picked folder' }+ return undefined+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await screen.findByText(+ 'No downloads from the previous version of Motrix were found. Choose another location to look for them.'+ )+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ await screen.findByRole('radio', { name: '/Volumes/Backup/Motrix' })+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Queries.ScanLegacyImport,+ expect.anything()+ )+ await continueFromSource()+ expect(screen.getByRole('checkbox', { name: 'archive.zip' })).toBeChecked()+ expect(transport.invoke).toHaveBeenCalledWith(Queries.ScanLegacyImport, {+ sourceHandle,+ })+ })++ it('shows an empty source path and keeps migration disabled', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport) return { ...preview, items: [] }+ return undefined+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ expect(screen.getByRole('button', { name: 'Migrate' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Back to source' })).toBeEnabled()+ })++ it('imports selection directly, preserves the paused-state explanation and exposes details on demand', async () => {+ render(<LegacyImportDialog open onClose={vi.fn()} />)+ await continueFromSource()+ const action = await screen.findByRole('button', { name: 'Migrate' })+ expect(+ screen.queryByRole('textbox', { name: 'Search downloads' })+ ).not.toBeInTheDocument()+ expect(+ screen.getByText(+ 'Selected 1 task. After migration, tasks will stay paused and downloaded files will remain in place.'+ )+ ).toBeVisible()+ fireEvent.click(action)+ await screen.findByRole('heading', { name: 'Migration complete' })+ expect(transport.invoke).toHaveBeenCalledWith(Commands.CommitLegacyImport, {+ previewId,+ itemIds: [items[0].itemId],+ })+ expect(+ screen.getByRole('button', { name: 'View details' })+ ).toHaveAttribute('aria-expanded', 'false')+ })++ it('keeps the original download path and task type visible through import', async () => {+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ await screen.findByRole('checkbox', { name: 'archive.zip' })+ expect(screen.getByTitle(items[0].saveDir)).toBeVisible()+ expect(+ screen.getByText('Link', { selector: '[data-slot="badge"]' })+ ).toBeVisible()+ fireEvent.click(screen.getByRole('button', { name: 'Migrate' }))+ await screen.findByRole('heading', { name: 'Migration complete' })+ fireEvent.click(screen.getByText('View details'))+ expect(screen.getByTitle(items[0].saveDir)).toBeVisible()+ expect(transport.invoke).toHaveBeenCalledWith(Commands.CommitLegacyImport, {+ previewId,+ itemIds: [items[0].itemId],+ })+ })++ it('disables empty selection and running-source commits', async () => {+ render(<LegacyImportDialog open onClose={vi.fn()} />)+ await continueFromSource()+ const checkbox = await screen.findByRole('checkbox', {+ name: 'archive.zip',+ })+ fireEvent.click(checkbox)+ expect(screen.getByRole('button', { name: 'Migrate' })).toBeDisabled()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ expect.anything()+ )+ })++ it.each([+ {+ stage: 'completed',+ outcome: 'skipped',+ reason: 'already-imported',+ title: 'No new downloads',+ description: 'Open the details to see why each task was skipped.',+ status: 'Skipped',+ canRetry: false,+ },+ {+ stage: 'cancelled',+ outcome: 'unprocessed',+ reason: 'stopped',+ title: 'Migration stopped',+ description: 'No tasks were added. You can try again when you’re ready.',+ status: 'Not imported',+ canRetry: true,+ },+ {+ stage: 'failed',+ outcome: 'failed',+ reason: 'commit-failed',+ title: 'Migration is incomplete',+ description: 'No tasks were added. Review the details, then try again.',+ status: 'Failed',+ canRetry: true,+ },+ ])(+ 'explains $stage / $outcome without claiming migration completed',+ async (result) => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport) return preview+ if (channel === Commands.CommitLegacyImport)+ return {+ ...report,+ stage: result.stage,+ imported: 0,+ items: [+ {+ ...items[0],+ reason: result.reason,+ outcome: result.outcome,+ taskId: null,+ },+ ],+ }+ return { ok: true }+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ fireEvent.click(await screen.findByRole('button', { name: 'Migrate' }))+ expect(+ await screen.findByRole('heading', { name: result.title })+ ).toBeVisible()+ expect(+ screen.queryByRole('heading', { name: 'Migration complete' })+ ).not.toBeInTheDocument()+ expect(screen.getByText(result.description)).toBeVisible()+ expect(+ Boolean(screen.queryByRole('button', { name: 'Migrate remaining' }))+ ).toBe(result.canRetry)+ fireEvent.click(screen.getByText('View details'))+ expect(+ screen.getByText(result.status, { selector: 'span' })+ ).toBeVisible()+ }+ )++ it('keeps a failed preflight on selection with its selected item', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport) return preview+ if (channel === Commands.CommitLegacyImport)+ throw new Error('legacyImport.errors.changedSource')+ return undefined+ })+ render(<LegacyImportDialog open onClose={vi.fn()} />)+ await continueFromSource()+ fireEvent.click(await screen.findByRole('button', { name: 'Migrate' }))+ await screen.findByRole('alert')+ expect(screen.getByRole('checkbox', { name: 'archive.zip' })).toBeChecked()+ expect(screen.getByRole('button', { name: 'Migrate' })).toBeEnabled()+ })++ it('skipping an invitation persists dismissal without a commit', async () => {+ const close = vi.fn()+ render(<LegacyImportDialog open invitation onClose={close} />)+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ fireEvent.click(screen.getByRole('button', { name: 'Not now' }))+ await waitFor(() => expect(close).toHaveBeenCalledOnce())+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.DismissLegacyImportInvitation+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ expect.anything()+ )+ })++ it('keeps a torrent awaiting metadata reachable from its source', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport)+ return {+ ...preview,+ items: [+ {+ itemId: 'gid:2222222222222222',+ name: 'saved.torrent',+ type: 'bt',+ selectable: false,+ reason: 'metadata-required',+ },+ ],+ }+ return undefined+ })+ render(<LegacyImportDialog open invitation onClose={vi.fn()} />)+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ expect(+ await screen.findByRole('button', { name: 'Migrate' })+ ).toBeDisabled()+ expect(+ screen.getByRole('button', { name: 'Choose torrent…' })+ ).toBeEnabled()+ })++ it('authorizes a skipped torrent in place, preserves deselected downloads and selects the repaired item', async () => {+ const bt = {+ itemId: 'gid:2222222222222222',+ name: 'saved.torrent',+ type: 'bt',+ selectable: false,+ reason: 'metadata-required',+ }+ const refreshedId = '44444444-4444-4444-8444-444444444444'+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport)+ return { ...preview, items: [...items, bt] }+ if (channel === Commands.PickLegacyTorrentMetadata)+ return {+ ...preview,+ previewId: refreshedId,+ items: [+ ...items,+ {+ ...bt,+ name: 'fixture-bundle',+ selectable: true,+ reason: 'verification-required',+ },+ ],+ }+ if (channel === Commands.CommitLegacyImport) return report+ return undefined+ })+ render(<LegacyImportDialog open onClose={vi.fn()} />)+ await continueFromSource()+ fireEvent.click(+ await screen.findByRole('checkbox', { name: 'archive.zip' })+ )+ fireEvent.click(screen.getByRole('button', { name: 'Choose torrent…' }))+ const repaired = await screen.findByRole('checkbox', {+ name: 'fixture-bundle',+ })+ expect(repaired).toBeChecked()+ expect(+ screen.getByRole('checkbox', { name: 'archive.zip' })+ ).not.toBeChecked()+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.PickLegacyTorrentMetadata,+ { previewId, itemId: bt.itemId }+ )+ fireEvent.click(screen.getByRole('button', { name: 'Migrate' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ { previewId: refreshedId, itemIds: [bt.itemId] }+ )+ )+ })++ it('retains the current selection and preview when torrent selection is cancelled', async () => {+ const bt = {+ itemId: 'gid:2222222222222222',+ name: 'saved.torrent',+ type: 'bt',+ selectable: false,+ reason: 'metadata-required',+ }+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport)+ return { ...preview, items: [...items, bt] }+ if (channel === Commands.PickLegacyTorrentMetadata) return null+ if (channel === Commands.CommitLegacyImport) return report+ return undefined+ })+ render(<LegacyImportDialog open onClose={vi.fn()} />)+ await continueFromSource()+ await screen.findByRole('checkbox', { name: 'archive.zip' })+ fireEvent.click(screen.getByRole('button', { name: 'Choose torrent…' }))+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Migrate' })).toBeEnabled()+ )+ expect(screen.getByRole('checkbox', { name: 'archive.zip' })).toBeChecked()+ fireEvent.click(screen.getByRole('button', { name: 'Migrate' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ { previewId, itemIds: [items[0].itemId] }+ )+ )+ })+})diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.tsxnew file mode 100644index 00000000..ced51cf0--- /dev/null+++ b/src/renderer/features/legacy-import/legacy-import-dialog.tsx@@ -0,0 +1,963 @@+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'+import { RevealFolderIcon, WarningIcon } from '@renderer/components/icons'+import { Alert, AlertDescription } from '@renderer/components/ui/alert'+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@renderer/components/ui/alert-dialog'+import { Button } from '@renderer/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '@renderer/components/ui/dialog'+import { Label } from '@renderer/components/ui/label'+import { RadioGroup, RadioGroupItem } from '@renderer/components/ui/radio-group'+import { Spinner } from '@renderer/components/ui/spinner'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ type LegacyImportItem,+ type LegacyImportPreview,+ type LegacyImportReport,+ type LegacyImportSource,+ legacyImportPreviewSchema,+ legacyImportReportSchema,+ legacyImportSourceSchema,+ legacyImportSourceSelectionSchema,+} from '@shared/schemas/legacy-import'+import {+ Component,+ type ReactNode,+ useCallback,+ useEffect,+ useId,+ useRef,+ useState,+} from 'react'+import { useTranslation } from 'react-i18next'+import { ImportIllustration } from './import-illustration'+import { ImportMotionScope } from './import-motion'+import {+ ImportPageLayout,+ type ImportStage,+ ImportStageHeading,+} from './import-page-layout'+import { ImportRunProgress, ImportRunResult } from './import-run-content'+import { ImportSourceFeedback } from './import-source-feedback'+import {+ ImportTaskSelection,+ initialExpandedGroups,+} from './import-task-selection'++interface Props {+ open: boolean+ invitation?: boolean+ onClose: () => void+ onViewTasks?: () => void+ presentation?: 'dialog' | 'page'+ active?: boolean+}+type SourceAction =+ | { type: 'discover' }+ | { type: 'pick'; dataPath?: string }+ | { type: 'scan' | 'reveal'; sourceHandle: string }+interface ImportFailure {+ key: string+ sourceAction?: SourceAction+}+const sourceNeedsSelection = (key: string) =>+ [+ 'invalidSource',+ 'unsafeSource',+ 'sourceNotAuthorized',+ 'changedSource',+ 'rescanRequired',+ ].some((code) => key === `legacyImport.errors.${code}`)+const terminal = (report: LegacyImportReport) =>+ ['completed', 'cancelled', 'failed'].includes(report.stage)++class ImportErrorBoundary extends Component<+ { children: ReactNode; fallback: ReactNode },+ { failed: boolean }+> {+ state = { failed: false }+ static getDerivedStateFromError() {+ return { failed: true }+ }+ render() {+ return this.state.failed ? this.props.fallback : this.props.children+ }+}++export function LegacyImportDialog(props: Props) {+ const { t } = useTranslation()+ return (+ <ImportErrorBoundary+ fallback={<p role="alert">{t('legacyImport.errors.failed')}</p>}+ >+ <LegacyImportDialogContent {...props} />+ </ImportErrorBoundary>+ )+}++function LegacyImportDialogContent({+ open,+ invitation = false,+ onClose,+ onViewTasks,+ presentation = 'dialog',+ active = true,+}: Props) {+ const { t } = useTranslation()+ const page = presentation === 'page'+ const sourceGroupId = useId()+ const [stage, setStage] = useState<ImportStage>('discovery')+ const [preview, setPreview] = useState<LegacyImportPreview | null>(null)+ const previewRef = useRef<LegacyImportPreview | null>(null)+ const [sources, setSources] = useState<LegacyImportSource[]>([])+ const [rejectedPaths, setRejectedPaths] = useState<string[]>([])+ const [sourceHandle, setSourceHandle] = useState<string | null>(null)+ const sourceHandleRef = useRef<string | null>(null)+ const sourceFeedbackEpoch = useRef(0)+ const [sourceActivity, setSourceActivity] = useState<+ 'discover' | 'scan' | null+ >(null)+ const [selected, setSelected] = useState<Set<string>>(new Set())+ const [expanded, setExpanded] = useState<Set<LegacyImportItem['type']>>(+ new Set()+ )+ const [report, setReport] = useState<LegacyImportReport | null>(null)+ const [busy, setBusy] = useState(false)+ const busyRef = useRef(false)+ const [error, setError] = useState<ImportFailure | null>(null)+ const [unavailableSource, setUnavailableSource] =+ useState<ImportFailure | null>(null)+ const [query, setQuery] = useState('')+ const [confirmStop, setConfirmStop] = useState(false)+ const epoch = useRef(0)+ const runId = report?.runId+ const finished = report ? terminal(report) : false+ const failure = useCallback(+ (cause: unknown, sourceAction?: SourceAction) => {+ const message = cause instanceof Error ? cause.message : String(cause)+ const found = message.match(/legacyImport\.(?:errors\.)?[a-zA-Z]+/)?.[0]+ const key = found?.includes('.errors.')+ ? found+ : found+ ? `legacyImport.errors.${found.split('.').at(-1)}`+ : undefined+ const next = {+ key: key && t(key) !== key ? key : 'legacyImport.errors.failed',+ sourceAction,+ }+ if (sourceAction?.type === 'scan' && sourceNeedsSelection(next.key)) {+ setUnavailableSource(next)+ const source = sources.find(+ (entry) => entry.sourceHandle === sourceAction.sourceHandle+ )+ if (source)+ setRejectedPaths((current) =>+ current.includes(source.dataPath)+ ? current+ : [...current, source.dataPath]+ )+ }+ setError(next)+ },+ [t, sources]+ )+ const failureRef = useRef(failure)+ useEffect(() => {+ failureRef.current = failure+ }, [failure])++ const perform = useCallback(+ async (+ operation: () => Promise<void>,+ options?: { sourceAction?: SourceAction; preserveError?: boolean }+ ) => {+ if (busyRef.current) return+ ++sourceFeedbackEpoch.current+ const generation = epoch.current+ busyRef.current = true+ setBusy(true)+ const action = options?.sourceAction?.type+ setSourceActivity(+ action === 'discover' || action === 'scan' ? action : null+ )+ if (!options?.preserveError) setError(null)+ try {+ await operation()+ } catch (cause) {+ if (generation === epoch.current)+ failureRef.current(cause, options?.sourceAction)+ } finally {+ if (generation === epoch.current) {+ busyRef.current = false+ setBusy(false)+ setSourceActivity(null)+ }+ }+ },+ []+ )++ const selectSource = useCallback(+ (source: LegacyImportSource, refresh = false) => {+ if (source.sourceHandle === sourceHandleRef.current && !refresh) return+ ++sourceFeedbackEpoch.current+ sourceHandleRef.current = source.sourceHandle+ setSourceHandle(source.sourceHandle)+ previewRef.current = null+ setPreview(null)+ setSelected(new Set())+ setExpanded(new Set())+ setQuery('')+ setError(null)+ setUnavailableSource(null)+ },+ []+ )++ const scan = useCallback(+ async (source: LegacyImportSource, refresh = false) => {+ const generation = epoch.current+ const sameSource = source.sourceHandle === sourceHandleRef.current+ const preserveSelection = sameSource && previewRef.current !== null+ if (sameSource && previewRef.current && !refresh) return+ selectSource(source)+ const next = legacyImportPreviewSchema.parse(+ await transport.invoke(Queries.ScanLegacyImport, {+ sourceHandle: source.sourceHandle,+ })+ )+ if (generation !== epoch.current) return+ previewRef.current = next+ setPreview(next)+ setSelected(+ (current) =>+ new Set(+ next.items+ .filter(+ (item) =>+ item.selectable &&+ (!preserveSelection || current.has(item.itemId))+ )+ .map((item) => item.itemId)+ )+ )+ if (!preserveSelection) setExpanded(initialExpandedGroups(next.items))+ setError(null)+ },+ [selectSource]+ )++ const discover = useCallback(async () => {+ const generation = epoch.current+ const result = await transport.invoke(Queries.DiscoverLegacyImport)+ if (generation !== epoch.current) return+ const found = (result as unknown[]).map((source) =>+ legacyImportSourceSchema.parse(source)+ )+ setSources(found)+ if (found[0]) selectSource(found[0])+ }, [selectSource])++ useEffect(() => {+ if (!open) return+ ++epoch.current+ setStage('discovery')+ previewRef.current = null+ sourceHandleRef.current = null+ setPreview(null)+ setSourceHandle(null)+ setSources([])+ setRejectedPaths([])+ setUnavailableSource(null)+ setReport(null)+ setSelected(new Set())+ setExpanded(new Set())+ setQuery('')+ setConfirmStop(false)+ void perform(discover, { sourceAction: { type: 'discover' } })+ return () => {+ epoch.current+++ busyRef.current = false+ }+ }, [open, perform, discover])++ const receiveReport = useCallback((next: LegacyImportReport) => {+ setReport((current) => {+ if (+ current?.runId === next.runId &&+ ((terminal(current) && !terminal(next)) ||+ current.processed > next.processed)+ )+ return current+ return next+ })+ if (terminal(next)) setStage('result')+ }, [])++ useEffect(() => {+ if (!open || !runId || finished) return+ let disposed = false+ let timer: ReturnType<typeof setTimeout> | null = null+ const poll = async () => {+ try {+ const next = legacyImportReportSchema.parse(+ await transport.invoke(Queries.GetLegacyImportRun, { runId })+ )+ if (disposed) return+ receiveReport(next)+ if (terminal(next)) return+ setError(null)+ } catch (cause) {+ if (!disposed) failure(cause)+ }+ if (!disposed) timer = setTimeout(() => void poll(), 250)+ }+ timer = setTimeout(() => void poll(), 250)+ return () => {+ disposed = true+ if (timer) clearTimeout(timer)+ }+ }, [open, runId, finished, failure, receiveReport])++ const pickSource = () =>+ void perform(+ async () => {+ const generation = epoch.current+ const result = await transport.invoke(Commands.PickLegacyImportSource)+ if (!result || generation !== epoch.current) return+ const source = legacyImportSourceSelectionSchema.parse(result)+ if ('errorCode' in source) {+ setRejectedPaths((current) =>+ current.includes(source.dataPath)+ ? current+ : [...current, source.dataPath]+ )+ const existing = sources.find(+ (entry) => entry.dataPath === source.dataPath+ )+ failureRef.current(+ new Error(`legacyImport.errors.${source.errorCode}`),+ existing+ ? { type: 'scan', sourceHandle: existing.sourceHandle }+ : { type: 'pick', dataPath: source.dataPath }+ )+ return+ }+ setRejectedPaths((current) =>+ current.filter((entry) => entry !== source.dataPath)+ )+ setSources((current) => [+ ...current.filter(+ (entry) =>+ entry.dataPath !== source.dataPath &&+ entry.sourceHandle !== source.sourceHandle+ ),+ source,+ ])+ selectSource(source, true)+ },+ { sourceAction: { type: 'pick' }, preserveError: true }+ )+ const continueToSelection = () =>+ void perform(+ async () => {+ const source = sources.find(+ (entry) => entry.sourceHandle === sourceHandleRef.current+ )+ if (!source) return+ const generation = epoch.current+ await scan(source)+ if (+ generation === epoch.current &&+ previewRef.current?.sourceHandle === source.sourceHandle+ )+ setStage('selection')+ },+ {+ sourceAction: sourceHandle ? { type: 'scan', sourceHandle } : undefined,+ }+ )+ const revealSource = async (handle: string) => {+ const generation = epoch.current+ const feedbackGeneration = ++sourceFeedbackEpoch.current+ try {+ await transport.invoke(Commands.RevealLegacyImportSource, {+ sourceHandle: handle,+ })+ if (+ generation === epoch.current &&+ feedbackGeneration === sourceFeedbackEpoch.current+ )+ setError((current) =>+ current?.sourceAction?.type === 'reveal' &&+ current.sourceAction.sourceHandle === handle+ ? null+ : current+ )+ } catch (cause) {+ if (+ generation === epoch.current &&+ feedbackGeneration === sourceFeedbackEpoch.current+ )+ failureRef.current(cause, { type: 'reveal', sourceHandle: handle })+ }+ }+ const recheck = () =>+ void perform(async () => {+ const source = sources.find(+ (entry) => entry.sourceHandle === sourceHandle+ )+ if (source) await scan(source, true)+ else await discover()+ })+ const chooseTorrent = (item: LegacyImportItem) =>+ void perform(async () => {+ if (!preview) return+ const generation = epoch.current+ const result = await transport.invoke(+ Commands.PickLegacyTorrentMetadata,+ { previewId: preview.previewId, itemId: item.itemId }+ )+ if (!result || generation !== epoch.current) return+ const next = legacyImportPreviewSchema.parse(result)+ previewRef.current = next+ setPreview(next)+ setSelected(+ (current) =>+ new Set(+ next.items+ .filter(+ (entry) =>+ entry.selectable &&+ (current.has(entry.itemId) || entry.itemId === item.itemId)+ )+ .map((entry) => entry.itemId)+ )+ )+ })+ const leave = () =>+ void perform(async () => {+ const generation = epoch.current+ if (invitation)+ await transport.invoke(Commands.DismissLegacyImportInvitation)+ if (generation === epoch.current) onClose()+ })+ const viewTasks = () =>+ void perform(async () => {+ const generation = epoch.current+ await transport.invoke(Commands.FinishLegacyImportInvitation)+ if (generation === epoch.current) (onViewTasks ?? onClose)()+ })+ const startImport = () =>+ void perform(async () => {+ if (!preview || !selected.size || preview.running) return+ const generation = epoch.current+ setStage('progress')+ try {+ const next = legacyImportReportSchema.parse(+ await transport.invoke(Commands.CommitLegacyImport, {+ previewId: preview.previewId,+ itemIds: [...selected],+ })+ )+ if (generation !== epoch.current) return+ receiveReport(next)+ } catch (cause) {+ if (generation !== epoch.current) return+ setStage('selection')+ throw cause+ }+ })+ const retry = () =>+ void perform(async () => {+ if (!report) return+ const generation = epoch.current+ const next = legacyImportReportSchema.parse(+ await transport.invoke(Commands.RetryLegacyImport, {+ runId: report.runId,+ })+ )+ if (generation !== epoch.current) return+ setReport(next)+ setStage(terminal(next) ? 'result' : 'progress')+ })+ const onBack = () => {+ if (busyRef.current || stage === 'progress') return+ if (stage === 'selection') setStage('discovery')+ else if (stage === 'result') viewTasks()+ else leave()+ }+ const primaryClass = 'migration-primary'+ const sourceError =+ stage === 'discovery'+ ? error?.sourceAction+ ? error+ : !error+ ? unavailableSource+ : null+ : null+ const scanFailed = sourceError?.sourceAction?.type === 'scan'+ const chooseSourceInstead =+ unavailableSource?.sourceAction?.type === 'scan' &&+ unavailableSource.sourceAction.sourceHandle === sourceHandle+ const footer = (+ <div className="flex w-full items-center justify-between gap-3">+ {(stage === 'discovery' || stage === 'selection') && (+ <>+ <Button size="sm" variant="ghost" disabled={busy} onClick={leave}>+ {t('legacyImport.skip')}+ </Button>+ {stage === 'discovery' ? (+ <Button+ size="sm"+ className={primaryClass}+ disabled={busy || !sourceHandle}+ onClick={chooseSourceInstead ? pickSource : continueToSelection}+ >+ {t(+ chooseSourceInstead+ ? 'legacyImport.chooseDestination'+ : scanFailed+ ? 'legacyImport.page.sourceFeedback.retry'+ : 'legacyImport.page.continue'+ )}+ </Button>+ ) : (+ <div className="flex items-center gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={onBack}+ >+ {t('legacyImport.page.backToSource')}+ </Button>+ <Button+ size="sm"+ className={primaryClass}+ disabled={busy || !selected.size || preview?.running}+ onClick={(event) => {+ // A double-click on Continue must not commit the next stage.+ if (event.detail < 2) startImport()+ }}+ >+ {t('legacyImport.importSelected')}+ </Button>+ </div>+ )}+ </>+ )}+ {stage === 'progress' && (+ <>+ <span className="text-xs text-muted-foreground">+ {t('legacyImport.page.footerNote')}+ </span>+ <Button+ size="sm"+ variant="outline"+ disabled={!report || busy}+ onClick={() => setConfirmStop(true)}+ >+ {t('legacyImport.stop')}+ </Button>+ </>+ )}+ {stage === 'result' && (+ <div className="ms-auto flex items-center gap-2">+ {report?.items.some(+ (item) =>+ item.outcome === 'failed' || item.outcome === 'unprocessed'+ ) ? (+ <Button size="sm" variant="outline" disabled={busy} onClick={retry}>+ {t('legacyImport.retry')}+ </Button>+ ) : (+ <span />+ )}+ <Button+ size="sm"+ className={primaryClass}+ disabled={busy}+ onClick={viewTasks}+ >+ {t('legacyImport.viewTasks')}+ </Button>+ </div>+ )}+ </div>+ )+ const errorNotice = error && (+ <Alert+ variant="destructive"+ className="mx-auto mb-3 w-full max-w-160 shrink-0"+ >+ <AlertDescription className="flex flex-wrap items-center justify-between gap-3 text-xs">+ <p className="min-w-0 flex-1">{t(error.key)}</p>+ {(stage === 'discovery' || stage === 'selection') && (+ <Button variant="outline" size="sm" disabled={busy} onClick={recheck}>+ {t('legacyImport.recheck')}+ </Button>+ )}+ </AlertDescription>+ </Alert>+ )+ const sourceFeedback = (handle?: string, dataPath?: string) => {+ const action = sourceError?.sourceAction+ if (+ !sourceError ||+ !action ||+ ('sourceHandle' in action ? action.sourceHandle : undefined) !== handle ||+ (action.type === 'pick' ? action.dataPath : undefined) !== dataPath+ )+ return null+ const chooseFolder = sourceNeedsSelection(sourceError.key)+ const kind =+ action.type === 'scan'+ ? chooseFolder+ ? 'unreadable'+ : 'read'+ : action.type+ const retryAction =+ action.type === 'discover'+ ? () => void perform(discover, { sourceAction: action })+ : action.type === 'reveal'+ ? () => void revealSource(action.sourceHandle)+ : undefined+ return (+ <ImportSourceFeedback+ id={`${sourceGroupId}-error`}+ title={t(`legacyImport.page.sourceFeedback.${kind}Title`)}+ description={+ chooseFolder+ ? t('legacyImport.page.sourceFeedback.chooseFolder')+ : sourceError.key === 'legacyImport.errors.failed'+ ? t(`legacyImport.page.sourceFeedback.${kind}Description`)+ : t(sourceError.key)+ }+ busy={busy}+ onRetry={retryAction}+ />+ )+ }+ const content = (+ <>+ {stage === 'discovery' && (+ <>+ <ImportStageHeading+ title={t('legacyImport.page.welcomeTitle')}+ description={t('legacyImport.page.sourceIntroduction')}+ illustration={<ImportIllustration />}+ />+ {!sourceError && errorNotice}+ <div className="migration-source-options mx-auto min-h-0 w-full max-w-160 flex-1 overflow-auto pt-8 pb-4">+ <h3 id={sourceGroupId} className="mb-5 text-sm font-medium">+ {t('legacyImport.page.sourceTitle')}+ </h3>+ {(sources.length > 0 || rejectedPaths.length > 0) && (+ <RadioGroup+ value={sourceHandle}+ disabled={busy}+ onValueChange={(value) => {+ const source = sources.find(+ (entry) => entry.sourceHandle === value+ )+ if (source) selectSource(source)+ }}+ aria-labelledby={sourceGroupId}+ className="gap-4"+ >+ {sources.map((source) => (+ <div key={source.sourceHandle} className="min-w-0">+ <div className="flex min-w-0 items-center gap-1.5">+ <Label+ className="group flex min-w-0 items-center gap-3 py-2 font-normal leading-normal data-[disabled=true]:opacity-50"+ data-disabled={+ busy || rejectedPaths.includes(source.dataPath)+ }+ >+ <RadioGroupItem+ value={source.sourceHandle}+ disabled={rejectedPaths.includes(source.dataPath)}+ aria-labelledby={`${sourceGroupId}-${source.sourceHandle}-path`}+ aria-describedby={+ sourceError?.sourceAction &&+ 'sourceHandle' in sourceError.sourceAction &&+ sourceError.sourceAction.sourceHandle ===+ source.sourceHandle+ ? `${sourceGroupId}-error`+ : undefined+ }+ className="border-foreground/35 text-foreground shadow-none data-checked:border-foreground"+ />+ <span+ id={`${sourceGroupId}-${source.sourceHandle}-path`}+ className="min-w-0"+ >+ <MiddleEllipsis+ text={source.dataPath}+ className="font-sans text-sm"+ />+ </span>+ </Label>+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ disabled={busy}+ aria-label={t('legacyImport.page.revealSource')}+ aria-describedby={`${sourceGroupId}-${source.sourceHandle}-path`}+ title={t('legacyImport.page.revealSource')}+ className="text-muted-foreground hover:text-foreground"+ onClick={() => void revealSource(source.sourceHandle)}+ >+ <RevealFolderIcon+ aria-hidden="true"+ className="size-3.5"+ />+ </Button>+ </div>+ {sourceFeedback(source.sourceHandle)}+ </div>+ ))}+ {rejectedPaths+ .filter(+ (dataPath) =>+ !sources.some((source) => source.dataPath === dataPath)+ )+ .map((dataPath, index) => (+ <div key={dataPath} className="min-w-0">+ <div className="flex min-w-0 items-center gap-1.5">+ <Label className="flex min-w-0 items-center gap-3 py-2 font-normal leading-normal opacity-50">+ <RadioGroupItem+ value={`rejected:${dataPath}`}+ disabled+ aria-labelledby={`${sourceGroupId}-rejected-${index}-path`}+ aria-describedby={+ sourceError?.sourceAction?.type === 'pick' &&+ sourceError.sourceAction.dataPath === dataPath+ ? `${sourceGroupId}-error`+ : undefined+ }+ className="border-foreground/35 text-foreground shadow-none"+ />+ <span+ id={`${sourceGroupId}-rejected-${index}-path`}+ className="min-w-0"+ >+ <MiddleEllipsis+ text={dataPath}+ className="font-sans text-sm"+ />+ </span>+ </Label>+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ disabled+ aria-label={t('legacyImport.page.revealSource')}+ className="text-muted-foreground"+ >+ <RevealFolderIcon+ aria-hidden="true"+ className="size-3.5"+ />+ </Button>+ </div>+ {sourceFeedback(undefined, dataPath)}+ </div>+ ))}+ </RadioGroup>+ )}+ {sourceFeedback()}+ {sourceActivity ? (+ <p+ role="status"+ className="flex items-center gap-2 py-3 text-xs text-muted-foreground"+ >+ <Spinner aria-hidden="true" className="size-3.5" />+ {t(+ sourceActivity === 'scan'+ ? 'legacyImport.page.sourceFeedback.reading'+ : 'legacyImport.loading'+ )}+ </p>+ ) : (+ !sources.length &&+ !sourceError && (+ <p className="max-w-md text-sm leading-relaxed text-muted-foreground">+ {t('legacyImport.page.noSourceDescription')}+ </p>+ )+ )}+ {!chooseSourceInstead && (+ <div className="mt-5 flex">+ <Button+ type="button"+ variant="link"+ size="sm"+ disabled={busy}+ onClick={pickSource}+ className="h-auto px-0 py-1 text-xs font-normal text-muted-foreground underline-offset-4 hover:text-foreground"+ >+ {t('legacyImport.chooseDestination')}+ </Button>+ </div>+ )}+ </div>+ </>+ )}+ {stage === 'selection' && (+ <>+ <ImportStageHeading+ title={t('legacyImport.page.selectionTitle')}+ description={t('legacyImport.page.introduction')}+ className="pt-4 pb-5"+ />+ {errorNotice}+ {preview?.running && (+ <Alert className="mx-auto mb-3 w-full max-w-160 shrink-0">+ <WarningIcon aria-hidden="true" />+ <AlertDescription className="flex flex-wrap items-center justify-between gap-3 text-xs">+ <span className="min-w-0 flex-1">+ {t('legacyImport.running')}+ </span>+ <Button+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={recheck}+ >+ {t('legacyImport.recheck')}+ </Button>+ </AlertDescription>+ </Alert>+ )}+ <ImportTaskSelection+ items={preview?.items ?? []}+ selected={selected}+ setSelected={setSelected}+ expanded={expanded}+ setExpanded={setExpanded}+ query={query}+ setQuery={setQuery}+ busy={busy}+ running={preview?.running ?? false}+ chooseTorrent={chooseTorrent}+ />+ <p className="migration-selection-note mx-auto w-full max-w-160 shrink-0 py-3 text-xs leading-relaxed text-muted-foreground">+ {t('legacyImport.page.selectedNote', { count: selected.size })}+ </p>+ </>+ )}+ {stage === 'progress' && (+ <ImportRunProgress report={report} notice={errorNotice} />+ )}+ {stage === 'result' && report && (+ <ImportRunResult+ report={report}+ busy={busy}+ notice={errorNotice}+ exportReport={() =>+ void perform(async () => {+ await transport.invoke(Commands.ExportLegacyImportReport, {+ runId: report.runId,+ })+ })+ }+ />+ )}+ </>+ )+ return (+ <>+ {page ? (+ <ImportPageLayout active={active} stage={stage} footer={footer}>+ {content}+ </ImportPageLayout>+ ) : (+ <Dialog+ open={open}+ onOpenChange={(next, details) => {+ if (!next) {+ if (stage === 'progress' || busy) details.cancel()+ else leave()+ }+ }}+ >+ <DialogContent+ className="flex h-[min(680px,85vh)] flex-col gap-0 p-0 sm:max-w-[720px]"+ initialFocus={false}+ >+ <DialogHeader className="sr-only">+ <DialogTitle>{t('legacyImport.page.assistantTitle')}</DialogTitle>+ <DialogDescription>+ {t('legacyImport.pausedDescription')}+ </DialogDescription>+ </DialogHeader>+ <ImportMotionScope active={active}>+ <div className="flex h-full min-h-0 flex-col px-6">+ {content}+ <div className="shrink-0 py-4">{footer}</div>+ </div>+ </ImportMotionScope>+ </DialogContent>+ </Dialog>+ )}+ <AlertDialog open={confirmStop && active} onOpenChange={setConfirmStop}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t('legacyImport.stopTitle')}</AlertDialogTitle>+ <AlertDialogDescription>+ {t('legacyImport.stopDescription')}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={() => setConfirmStop(false)}+ >+ {t('common.cancel')}+ </Button>+ <Button+ size="sm"+ className={primaryClass}+ disabled={busy}+ onClick={() =>+ void perform(async () => {+ if (!report) return+ const generation = epoch.current+ const next = legacyImportReportSchema.parse(+ await transport.invoke(Commands.CancelLegacyImport, {+ runId: report.runId,+ })+ )+ if (generation !== epoch.current) return+ receiveReport(next)+ setConfirmStop(false)+ })+ }+ >+ {t('legacyImport.stop')}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}diff --git a/src/renderer/features/legacy-import/legacy-import-source-recovery.test.tsx b/src/renderer/features/legacy-import/legacy-import-source-recovery.test.tsxnew file mode 100644index 00000000..27541761--- /dev/null+++ b/src/renderer/features/legacy-import/legacy-import-source-recovery.test.tsx@@ -0,0 +1,294 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { LegacyImportDialog } from './legacy-import-dialog'++vi.mock('@renderer/lib/transport', () => ({+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'darwin' },+}))+const source = {+ sourceHandle: '11111111-1111-4111-8111-111111111111',+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+}+const preview = {+ previewId: '22222222-2222-4222-8222-222222222222',+ sourceHandle: source.sourceHandle,+ sourceName: source.name,+ items: [],+ running: false,+ checkpointImportAvailable: false,+ expiresAt: Date.now() + 100000,+}+const calls = (channel: string) =>+ vi.mocked(transport.invoke).mock.calls.filter(([name]) => name === channel)+ .length+async function continueFromSource() {+ const button = await screen.findByRole('button', { name: 'Continue' })+ await waitFor(() => expect(button).toBeEnabled())+ fireEvent.click(button)+}++beforeEach(() => vi.mocked(transport.invoke).mockReset())++describe('migration source recovery', () => {+ it('does not announce a scan while the native folder picker is open', async () => {+ let closePicker!: (result: null) => void+ let finishScan!: (result: typeof preview) => void+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Commands.PickLegacyImportSource)+ return new Promise((resolve) => {+ closePicker = resolve+ })+ if (channel === Queries.ScanLegacyImport)+ return new Promise((resolve) => {+ finishScan = resolve+ })+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await screen.findByRole('radio', { name: source.dataPath })+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ expect(calls(Commands.PickLegacyImportSource)).toBe(1)+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ expect(calls(Queries.ScanLegacyImport)).toBe(0)+ await act(async () => closePicker(null))+ await continueFromSource()+ expect(screen.getByRole('status')).toHaveTextContent('Reading downloads…')+ await act(async () => finishScan(preview))+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ })++ it.each([+ 'invalidSource',+ 'unsafeSource',+ 'changedSource',+ 'sourceNotAuthorized',+ ])(+ 'offers folder selection for %s and preserves recovery when the picker is cancelled or fails',+ async (code) => {+ let scans = 0+ let picks = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport) {+ if (++scans === 1) throw new Error(`legacyImport.errors.${code}`)+ return preview+ }+ if (channel === Commands.PickLegacyImportSource) {+ if (++picks === 1) return null+ if (picks === 2) throw new Error('legacyImport.invalidSource')+ return source+ }+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ const notice = await screen.findByRole('alert')+ expect(notice).toHaveTextContent(+ 'Unable to read downloads from this location'+ )+ expect(+ screen.getByRole('radio', { name: source.dataPath })+ ).toHaveAttribute('aria-describedby', notice.id)+ expect(+ screen.getByRole('radio', { name: source.dataPath })+ ).toHaveAttribute('aria-disabled', 'true')+ expect(+ screen.queryByRole('button', { name: 'Check again' })+ ).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Continue' })+ ).not.toBeInTheDocument()+ const choose = screen.getByRole('button', {+ name: 'Choose another location…',+ })+ fireEvent.click(choose)+ await waitFor(() => expect(choose).toBeEnabled())+ expect(screen.getByRole('alert')).toHaveTextContent(+ 'Unable to read downloads from this location'+ )+ fireEvent.click(choose)+ await screen.findByText('Unable to use the selected folder')+ expect(+ screen.queryByRole('button', { name: 'Continue' })+ ).not.toBeInTheDocument()+ expect(scans).toBe(1)+ fireEvent.click(choose)+ await continueFromSource()+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ expect(scans).toBe(2)+ expect(calls(Commands.CommitLegacyImport)).toBe(0)+ }+ )++ it('retains a rejected native path as a disabled row until that folder is successfully selected again', async () => {+ const dataPath = '/Volumes/Backup/Motrix'+ const repaired = {+ ...source,+ dataPath,+ sourceHandle: '33333333-3333-4333-8333-333333333333',+ }+ let picks = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Commands.PickLegacyImportSource) {+ if (++picks === 1) return { dataPath, errorCode: 'invalidSource' }+ if (picks === 2) return null+ return repaired+ }+ if (channel === Queries.ScanLegacyImport)+ return { ...preview, sourceHandle: repaired.sourceHandle }+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await screen.findByRole('radio', { name: source.dataPath })+ const choose = await screen.findByRole('button', {+ name: 'Choose another location…',+ })+ await waitFor(() => expect(choose).toBeEnabled())+ fireEvent.click(choose)+ const rejected = await screen.findByRole('radio', { name: dataPath })+ expect(rejected).toHaveAttribute('aria-disabled', 'true')+ expect(screen.getByRole('radio', { name: source.dataPath })).toBeChecked()+ expect(+ screen.getAllByRole('button', { name: 'Show in folder' })[1]+ ).toBeDisabled()+ expect(calls(Queries.ScanLegacyImport)).toBe(0)+ expect(calls(Commands.RevealLegacyImportSource)).toBe(0)+ fireEvent.click(choose)+ await waitFor(() => expect(choose).toBeEnabled())+ expect(rejected).toHaveAttribute('aria-disabled', 'true')+ expect(screen.getByRole('alert')).toBeVisible()+ fireEvent.click(choose)+ await waitFor(() =>+ expect(screen.getByRole('radio', { name: dataPath })).not.toHaveAttribute(+ 'aria-disabled',+ 'true'+ )+ )+ expect(screen.getAllByRole('radio', { name: dataPath })).toHaveLength(1)+ expect(screen.getByRole('radio', { name: dataPath })).toBeChecked()+ await continueFromSource()+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ expect(calls(Queries.ScanLegacyImport)).toBe(1)+ })++ it('retries a temporary scan failure and advances directly after success', async () => {+ let scans = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport) {+ if (++scans === 1) throw new Error('temporary read failure')+ return preview+ }+ if (channel === Commands.PickLegacyImportSource) return null+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ await screen.findByText(+ 'Check that this location is accessible, then try again.'+ )+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ const retry = screen.getByRole('button', { name: 'Try again' })+ await waitFor(() => expect(retry).toBeEnabled())+ expect(screen.getByRole('alert')).toBeVisible()+ fireEvent.click(retry)+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ expect(scans).toBe(2)+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ })++ it('keeps the existing source usable after an unrelated folder selection fails', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport) return preview+ if (channel === Commands.PickLegacyImportSource)+ throw new Error('legacyImport.invalidSource')+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ fireEvent.click(+ await screen.findByRole('button', { name: 'Back to source' })+ )+ fireEvent.click(+ screen.getByRole('button', { name: 'Choose another location…' })+ )+ await screen.findByText('Unable to use the selected folder')+ expect(screen.getByRole('radio', { name: source.dataPath })).toBeChecked()+ await continueFromSource()+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ expect(calls(Queries.ScanLegacyImport)).toBe(1)+ })++ it('retries discovery without parsing tasks', async () => {+ let attempts = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) {+ if (++attempts === 1) throw new Error('unavailable')+ return [source]+ }+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await screen.findByText('Unable to look for previous downloads')+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }))+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ expect(attempts).toBe(2)+ expect(calls(Queries.ScanLegacyImport)).toBe(0)+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ })++ it('ignores a late reveal failure after continuing to task selection', async () => {+ let rejectReveal!: (error: Error) => void+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport) return preview+ if (channel === Commands.RevealLegacyImportSource)+ return new Promise((_resolve, reject) => {+ rejectReveal = reject+ })+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ fireEvent.click(+ await screen.findByRole('button', { name: 'Show in folder' })+ )+ await continueFromSource()+ await screen.findByRole('heading', { name: 'Choose what to migrate' })+ await act(async () => rejectReveal(new Error('unavailable')))+ await waitFor(() =>+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ )+ })++ it('retries reveal without scanning or forgetting that the selected source needs reauthorization', async () => {+ let reveals = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport) return [source]+ if (channel === Queries.ScanLegacyImport)+ throw new Error('legacyImport.invalidSource')+ if (channel === Commands.RevealLegacyImportSource && ++reveals === 1)+ throw new Error('unavailable')+ })+ render(<LegacyImportDialog open presentation="page" onClose={vi.fn()} />)+ await continueFromSource()+ await screen.findByRole('alert')+ fireEvent.click(screen.getByRole('button', { name: 'Show in folder' }))+ await screen.findByText('Unable to show this folder')+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }))+ await screen.findByText('Unable to read downloads from this location')+ expect(+ screen.getByRole('button', { name: 'Choose another location…' })+ ).toBeEnabled()+ expect(calls(Queries.ScanLegacyImport)).toBe(1)+ expect(reveals).toBe(2)+ })+})diff --git a/src/renderer/features/legacy-import/use-legacy-import-navigation.ts b/src/renderer/features/legacy-import/use-legacy-import-navigation.tsnew file mode 100644index 00000000..439c25f9--- /dev/null+++ b/src/renderer/features/legacy-import/use-legacy-import-navigation.ts@@ -0,0 +1,20 @@+import { useTransportMirror } from '@renderer/hooks/use-transport-mirror'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'+import { legacyImportNavigationSchema } from '@shared/schemas/legacy-import'+import { useState } from 'react'++export function useLegacyImportNavigation() {+ const [detected, setDetected] = useState(false)+ useTransportMirror({+ events: [Events.LegacyImportNavigationChanged],+ load: async (stale, read) => {+ if (__MOTRIX_TARGET__ !== 'electron') return+ const state = legacyImportNavigationSchema.parse(+ await read(Queries.GetLegacyImportNavigation)+ )+ if (!stale()) setDetected(state.detected)+ },+ })+ return { detected }+}diff --git a/src/renderer/layouts/app-layout.test.tsx b/src/renderer/layouts/app-layout.test.tsxindex 4b87bee0..ffe64900 100644--- a/src/renderer/layouts/app-layout.test.tsx+++ b/src/renderer/layouts/app-layout.test.tsx@@ -1,10 +1,13 @@+import '@test-utils/dom-animations'import '@testing-library/jest-dom/vitest'import '@renderer/lib/i18n'import { useDownloadsSelection } from '@renderer/routes/downloads/store'import { useDownloadsView } from '@renderer/routes/downloads/view-preferences'+import { SettingsPage } from '@renderer/routes/settings/settings-page'import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'import { makeDownloadTask } from '@test-utils/task'-import { act, fireEvent, render, screen } from '@testing-library/react'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { createMemoryRouter, RouterProvider } from 'react-router'import { beforeEach, describe, expect, it, vi } from 'vitest'import { AppLayout } from './app-layout'@@ -17,7 +20,10 @@ function setWindowWidth(width: number) {})}-function renderAppLayout(routeHandle?: Record<string, unknown>) {+function renderAppLayout(+ routeHandle?: Record<string, unknown>,+ initialEntry = '/'+) {// AppLayout uses useMatches() which only works under a data router.const router = createMemoryRouter([@@ -28,10 +34,16 @@ function renderAppLayout(routeHandle?: Record<string, unknown>) {{ index: true, element: <div>INDEX_PAGE</div>, handle: routeHandle },{ path: 'downloads/:filter', element: <div>DOWNLOADS_PAGE</div> },{ path: 'plugins/:id', element: <div>PLUGIN_PAGE</div> },+ { path: 'migration', element: null },+ {+ path: 'settings',+ element: <SettingsPage />,+ children: [{ path: ':cardId', element: null }],+ },],},],- { initialEntries: ['/'] }+ { initialEntries: [initialEntry] })render(<RouterProvider router={router} />)return router@@ -239,4 +251,49 @@ describe('AppLayout', () => {// Outlet renderedexpect(screen.getByText('INDEX_PAGE')).toBeInTheDocument()})++ it('mounts the initial non-settings outlet only once and does not scan while migration is hidden', async () => {+ renderAppLayout()+ expect(screen.getAllByText('INDEX_PAGE')).toHaveLength(1)+ await act(async () => Promise.resolve())+ expect(window.motrix.invoke).not.toHaveBeenCalledWith(+ Queries.DiscoverLegacyImport+ )+ })++ it('retains an Advanced draft across migration dismissal to Dashboard', async () => {+ vi.mocked(window.motrix.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetSettings)+ return {+ engine: {+ rpcPort: 16800,+ rpcSecret: 'test-secret',+ sqlite3Persistence: true,+ sqlite3DbPath: '',+ sqlite3HistoryLimit: -1,+ },+ }+ if (channel === Queries.GetLegacyImportNavigation)+ return { detected: false, invitationPending: false }+ if (channel === Queries.DiscoverLegacyImport) return []+ return {}+ })+ const router = renderAppLayout(undefined, '/settings/advanced')+ const port = await screen.findByDisplayValue('16800')+ fireEvent.change(port, { target: { value: '17000' } })+ fireEvent.click(screen.getByRole('button', { name: 'Open migration' }))+ await waitFor(() =>+ expect(router.state.location.pathname).toBe('/migration')+ )+ expect(router.state.location.search).toBe('?from=settings')+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ fireEvent.click(await screen.findByRole('button', { name: 'Not now' }))+ await waitFor(() => expect(router.state.location.pathname).toBe('/'))+ expect(screen.queryByRole('dialog')).toBeNull()+ await act(async () => {+ await router.navigate('/settings/advanced')+ })+ expect(await screen.findByDisplayValue('17000')).toBeVisible()+ expect(screen.getByRole('dialog')).toBeVisible()+ })})diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsxindex 3b243e6f..53f4e280 100644--- a/src/renderer/layouts/app-layout.tsx+++ b/src/renderer/layouts/app-layout.tsx@@ -26,10 +26,13 @@ import type { RouteHandle } from '@renderer/router-types'import { RemoveTasksDialogHost } from '@renderer/routes/downloads/inspector/remove-tasks-dialog-host'import { useDownloadsSelection } from '@renderer/routes/downloads/store'import { useDownloadsView } from '@renderer/routes/downloads/view-preferences'+import { MigrationPage } from '@renderer/routes/migration/migration-page'import { usePairRequestPrompts } from '@renderer/routes/settings/cards/integration/use-pair-request-prompts'+import { LEGACY_MIGRATION_ROUTE } from '@shared/lib/legacy-import-navigation'import { isDownloadsListRoute } from '@shared/lib/task-navigation'import { Events } from '@shared/protocol/events'-import { Outlet, useMatches, useNavigate } from 'react-router'+import { type ReactNode, useRef } from 'react'+import { useLocation, useMatches, useNavigate, useOutlet } from 'react-router'const platformServices =__MOTRIX_TARGET__ === 'electron' ? electronServices : webServices@@ -47,6 +50,12 @@ export function AppLayout() {useNotificationToasts()const navigate = useNavigate()+ const location = useLocation()+ const outlet = useOutlet()+ const migrationActive = location.pathname === LEGACY_MIGRATION_ROUTE+ const settingsActive = /^\/settings(?:\/|$)/.test(location.pathname)+ const retainedSettings = useRef<ReactNode>(null)+ if (settingsActive) retainedSettings.current = outletconst matches = useMatches()const transparentInset = matches.some((m) => (m.handle as RouteHandle | undefined)?.transparentInset@@ -109,7 +118,18 @@ export function AppLayout() {)}><div className="min-h-0 flex-1 overflow-hidden">- <Outlet />+ <div hidden={!migrationActive} className="h-full min-h-0">+ <MigrationPage active={migrationActive} />+ </div>+ <div hidden={!settingsActive} className="h-full min-h-0">+ {retainedSettings.current}+ </div>+ <div+ hidden={migrationActive || settingsActive}+ className="h-full min-h-0"+ >+ {!settingsActive && outlet}+ </div></div><WebConnectionNotice /></SidebarInset>diff --git a/src/renderer/router.tsx b/src/renderer/router.tsxindex a2252334..cb6ef5ce 100644--- a/src/renderer/router.tsx+++ b/src/renderer/router.tsx@@ -36,6 +36,8 @@ const routes = [},{ path: 'plugins/:id', element: <PluginDetailPage /> },{ path: 'notifications', element: <NotificationsPage /> },+ // MigrationPage is retained by AppLayout across navigation.+ { path: 'migration', element: null },{path: 'settings',element: <SettingsPage />,diff --git a/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx b/src/renderer/routes/downloads/inspector/trackers-tab.test.tsxindex c93ab4ae..36345268 100644--- a/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx@@ -4,7 +4,12 @@ import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'import type { BtExtension, DownloadTask } from '@shared/types/task'-import { TaskStatus, TaskType } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -132,6 +137,51 @@ describe('TrackersTab — read mode', () => {).not.toBeNull()})+ it('keeps imported tracker rows readable without edit, sync, or delete controls', async () => {+ const task = makeBtTask()+ task.instances = [+ {+ instanceId: 'legacy',+ motrixId: task.id,+ gid: task.engineTaskId,+ phase: TaskInstancePhase.BtDownload,+ status: task.status,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/legacy',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ createdAt: 0,+ updatedAt: 0,+ payload: { legacyImport: { version: 99 } },+ },+ ]+ render(<TrackersTab task={task} />)+ expect(await screen.findByText('http://effective-only')).toBeInTheDocument()+ expect(+ screen.getByText(+ 'This download keeps its original trackers. They can’t be changed here.'+ )+ ).toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Edit' })+ ).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Sync' })+ ).not.toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: 'Delete tracker' })+ ).not.toBeInTheDocument()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.some(([channel]) => channel === Queries.GetTaskTrackerPlan)+ ).toBe(false)+ })+it('header summary shows "{N} trackers · {M} not in global"', async () => {render(<TrackersTab task={makeBtTask()} />)// 4 rows, 1 global URL not in effective (global2)diff --git a/src/renderer/routes/downloads/inspector/trackers-tab.tsx b/src/renderer/routes/downloads/inspector/trackers-tab.tsxindex 52e8744a..784669cb 100644--- a/src/renderer/routes/downloads/inspector/trackers-tab.tsx+++ b/src/renderer/routes/downloads/inspector/trackers-tab.tsx@@ -19,6 +19,7 @@ import {} from '@shared/schemas/task-tracker'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'+import { hasLegacyImport } from '@shared/types/task-actions'import { type KeyboardEvent, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { TaskTrackerDialog } from './task-tracker-dialog'@@ -59,11 +60,13 @@ export function TrackersTab({ task }: TrackersTabProps) {)const announceSet = useMemo(() => new Set(announceFlat), [announceFlat])const isPrivate = task.bt?.isPrivate === true+ const isLegacy = hasLegacyImport(task)// Tasks that aria2 no longer holds (Completed-and-evicted, Error,// Removed) cannot accept SetTaskBtTracker / SyncTaskBtTracker —// aria2.changeOption raises "GID not found". Hide Edit/Sync and the// drift indicator entirely so we don't offer actions that 100% fail.const isEditable =+ !isLegacy &&task.status !== TaskStatus.Completed &&task.status !== TaskStatus.Error &&task.status !== TaskStatus.Removed@@ -82,10 +85,10 @@ export function TrackersTab({ task }: TrackersTabProps) {// While the announce baseline is loading or failed, an "effective// only" classification is unreliable — a private torrent's native// trackers must never be presented as removable extras.- out.push({ url, deletable: detailReady })+ out.push({ url, deletable: detailReady && isEditable })}return out- }, [announceFlat, announceSet, effective, detailReady])+ }, [announceFlat, announceSet, effective, detailReady, isEditable])const planRequest = JSON.stringify({taskId: task.id,@@ -207,6 +210,7 @@ export function TrackersTab({ task }: TrackersTabProps) {)const startEdit = () => {+ if (!isEditable) returnsetDraft(editableEffective.join('\n'))setMode('edit')}@@ -219,6 +223,7 @@ export function TrackersTab({ task }: TrackersTabProps) {a.every((x) => b.includes(x))const save = async () => {+ if (!isEditable) returnconst { valid, dropped } = parseTrackerInput(draft)if (dropped > 0) {toast.add({@@ -258,7 +263,7 @@ export function TrackersTab({ task }: TrackersTabProps) {}const sync = async () => {- if (isPrivate) return // defensive — button is also disabled+ if (!isEditable || isPrivate) return // defensive — button is also disabledconst taskKey = taskKeyRef.currentsetIsSyncing(true)try {@@ -285,7 +290,7 @@ export function TrackersTab({ task }: TrackersTabProps) {}const applyPlan = async () => {- if (!syncPlan || isSyncing) return+ if (!isEditable || !syncPlan || isSyncing) returnconst taskKey = taskKeyRef.currentsetIsSyncing(true)try {@@ -323,6 +328,7 @@ export function TrackersTab({ task }: TrackersTabProps) {}const handleDelete = async (url: string) => {+ if (!isEditable) returnconst taskKey = taskKeyRef.currentconst next = effective.filter((u) => u !== url)try {@@ -362,6 +368,11 @@ export function TrackersTab({ task }: TrackersTabProps) {</span></Alert>)}+ {isLegacy && (+ <p className="shrink-0 text-xs text-muted-foreground">+ {t('legacyImport.trackersReadOnly')}+ </p>+ )}<div className="flex shrink-0 items-center justify-between gap-2 text-xs text-muted-foreground"><span>diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex dca518e1..8ac1087d 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -24,12 +24,16 @@ import {TabsList,TabsTrigger,} from '@renderer/components/ui/tabs'+import { LegacyFreshDownload } from '@renderer/features/legacy-import/legacy-fresh-download'import { createTaskInspectorActivitySnapshotCache } from '@renderer/hooks/use-task-inspector-activity'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import { TaskType } from '@shared/types/task'-import { canInspectPieces } from '@shared/types/task-actions'+import {+ canInspectPieces,+ isLegacyImportInactive,+} from '@shared/types/task-actions'import { useCallback, useLayoutEffect, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { ActivityTab } from './inspector/activity-tab'@@ -224,6 +228,12 @@ export function TaskInspectorDrawer({</TabsTrigger></TabsList><TabsContent value="overview" className="min-h-0">+ {__MOTRIX_TARGET__ === 'electron' &&+ isLegacyImportInactive(single) && (+ <div className="mb-4">+ <LegacyFreshDownload task={single} />+ </div>+ )}<OverviewTabtask={single}snapshotCache={activitySnapshotCache}diff --git a/src/renderer/routes/migration/migration-page-boundary.test.tsx b/src/renderer/routes/migration/migration-page-boundary.test.tsxnew file mode 100644index 00000000..9f2210f5--- /dev/null+++ b/src/renderer/routes/migration/migration-page-boundary.test.tsx@@ -0,0 +1,49 @@+import '@testing-library/jest-dom/vitest'+import '@renderer/lib/i18n'+import { fireEvent, render, screen } from '@testing-library/react'+import { MemoryRouter, useLocation } from 'react-router'+import { describe, expect, it, vi } from 'vitest'+import { MigrationPage } from './migration-page'++vi.mock('@renderer/features/legacy-import/legacy-import-dialog', () => ({+ LegacyImportDialog: () => {+ throw new Error('Unexpected rendering failure')+ },+}))++function Host() {+ const location = useLocation()+ const active = location.pathname === '/migration'+ return (+ <>+ <p>Other navigation remains available</p>+ <div hidden={!active}>+ <MigrationPage active={active} />+ </div>+ {!active && <p>DOWNLOADS_PAGE</p>}+ </>+ )+}++describe('migration failure isolation', () => {+ it('keeps unrelated navigation usable without automatically starting another import', () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ render(+ <MemoryRouter initialEntries={['/migration']}>+ <Host />+ </MemoryRouter>+ )+ expect(screen.getByRole('alert')).toHaveTextContent(+ 'Migration couldn’t open.'+ )+ expect(+ screen.getByText('Other navigation remains available')+ ).toBeVisible()+ fireEvent.click(screen.getByRole('button', { name: 'View downloads' }))+ expect(screen.getByText('DOWNLOADS_PAGE')).toBeVisible()+ } finally {+ log.mockRestore()+ }+ })+})diff --git a/src/renderer/routes/migration/migration-page.test.tsx b/src/renderer/routes/migration/migration-page.test.tsxnew file mode 100644index 00000000..524e1371--- /dev/null+++ b/src/renderer/routes/migration/migration-page.test.tsx@@ -0,0 +1,256 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { MemoryRouter, useLocation, useNavigate } from 'react-router'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { MigrationPage } from './migration-page'++vi.mock('@renderer/lib/transport', () => ({+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'darwin' },+}))+const sourceHandle = '11111111-1111-4111-8111-111111111111'+const previewId = '22222222-2222-4222-8222-222222222222'+const runId = '33333333-3333-4333-8333-333333333333'+const items = [+ {+ itemId: 'one',+ name: 'one.zip',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ },+ {+ itemId: 'two',+ name: 'two.zip',+ type: 'http',+ selectable: true,+ reason: 'fresh-download-required',+ },+]+const preview = {+ previewId,+ sourceHandle,+ sourceName: 'Motrix',+ items,+ running: false,+ checkpointImportAvailable: false,+ expiresAt: Date.now() + 100000,+}+const finished = {+ runId,+ stage: 'completed',+ processed: 1,+ total: 1,+ imported: 1,+ backupCreated: true,+ items: [{ ...items[0], outcome: 'imported', taskId: 'new' }],+}+function Host() {+ const location = useLocation()+ const navigate = useNavigate()+ const active = location.pathname === '/migration'+ return (+ <>+ <button type="button" onClick={() => navigate('/downloads/all')}>+ Go downloads+ </button>+ <button type="button" onClick={() => navigate('/migration')}>+ Go migration+ </button>+ <p data-testid="route">{location.pathname}</p>+ <div hidden={!active} className="h-full">+ <MigrationPage active={active} />+ </div>+ </>+ )+}+beforeEach(() => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ vi.mocked(transport.invoke)+ .mockReset()+ .mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport) return preview+ if (+ channel === Commands.CommitLegacyImport ||+ channel === Queries.GetLegacyImportRun+ )+ return finished+ return { ok: true }+ })+})+describe('retained migration page', () => {+ it.each([+ ['/migration?invitation=1', 'source'],+ ['/migration?invitation=1', 'selection'],+ ['/migration', 'source'],+ ['/migration', 'selection'],+ ['/migration?from=settings', 'source'],+ ['/migration?from=settings', 'selection'],+ ])('returns to Dashboard when skipping %s from %s', async (entry, stage) => {+ render(+ <MemoryRouter initialEntries={[entry]}>+ <Host />+ </MemoryRouter>+ )+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ if (stage === 'selection') {+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ await screen.findByRole('checkbox', { name: 'one.zip' })+ }+ fireEvent.click(screen.getByRole('button', { name: 'Not now' }))+ await waitFor(() =>+ expect(screen.getByTestId('route').textContent).toBe('/')+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.CommitLegacyImport,+ expect.anything()+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.FinishLegacyImportInvitation+ )+ if (entry.includes('invitation=1'))+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.DismissLegacyImportInvitation+ )+ })++ it('retains invitation and individual choices across navigation, then persists explicit skip', async () => {+ render(+ <MemoryRouter initialEntries={['/migration?invitation=1']}>+ <Host />+ </MemoryRouter>+ )+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ fireEvent.click(await screen.findByRole('checkbox', { name: 'two.zip' }))+ fireEvent.click(screen.getByText('Go downloads'))+ fireEvent.click(screen.getByText('Go migration'))+ expect(screen.getByRole('checkbox', { name: 'two.zip' })).not.toBeChecked()+ expect(screen.getByRole('button', { name: 'Migrate' })).toBeEnabled()+ fireEvent.click(screen.getByRole('button', { name: 'Not now' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.DismissLegacyImportInvitation+ )+ )+ fireEvent.click(screen.getByText('Go migration'))+ expect(+ screen.queryByRole('button', { name: 'Continue' })+ ).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Back to source' })).toBeVisible()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([c]) => c === Queries.DiscoverLegacyImport)+ ).toHaveLength(1)+ })+ it('keeps one running import and its result while away; explicit finish starts a fresh deduplicated preview on return', async () => {+ let complete!: (value: typeof finished) => void+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport) return preview+ if (channel === Commands.CommitLegacyImport)+ return new Promise((resolve) => {+ complete = resolve+ })+ return { ok: true }+ })+ render(+ <MemoryRouter initialEntries={['/migration']}>+ <Host />+ </MemoryRouter>+ )+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ fireEvent.click(await screen.findByRole('checkbox', { name: 'two.zip' }))+ fireEvent.click(screen.getByRole('button', { name: 'Migrate' }))+ fireEvent.click(screen.getByText('Go downloads'))+ fireEvent.click(screen.getByText('Go migration'))+ expect(screen.getByRole('progressbar')).toBeVisible()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([c]) => c === Commands.CommitLegacyImport)+ ).toHaveLength(1)+ await act(async () => complete(finished))+ await screen.findByRole('heading', { name: 'Migration complete' })+ fireEvent.click(screen.getByText('Go downloads'))+ fireEvent.click(screen.getByText('Go migration'))+ expect(+ screen.getByRole('heading', { name: 'Migration complete' })+ ).toBeVisible()+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.DiscoverLegacyImport)+ return [+ {+ sourceHandle,+ name: 'Motrix',+ dataPath: '/Users/example/Library/Application Support/Motrix',+ },+ ]+ if (channel === Queries.ScanLegacyImport)+ return {+ ...preview,+ items: [+ { ...items[0], selectable: false, reason: 'already-imported' },+ items[1],+ ],+ }+ return { ok: true }+ })+ fireEvent.click(screen.getByRole('button', { name: 'View downloads' }))+ await waitFor(() =>+ expect(screen.getByTestId('route')).toHaveTextContent('/downloads/all')+ )+ fireEvent.click(screen.getByText('Go migration'))+ expect(+ await screen.findByRole('button', { name: 'Continue' })+ ).toBeVisible()+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled()+ )+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ expect(await screen.findByRole('button', { name: 'Migrate' })).toBeVisible()+ expect(+ screen.queryByRole('heading', { name: 'Migration complete' })+ ).not.toBeInTheDocument()+ expect(+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([c]) => c === Queries.DiscoverLegacyImport)+ ).toHaveLength(2)+ })+})diff --git a/src/renderer/routes/migration/migration-page.tsx b/src/renderer/routes/migration/migration-page.tsxnew file mode 100644index 00000000..228419a7--- /dev/null+++ b/src/renderer/routes/migration/migration-page.tsx@@ -0,0 +1,75 @@+import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'+import { Button } from '@renderer/components/ui/button'+import { LegacyImportDialog } from '@renderer/features/legacy-import/legacy-import-dialog'+import { ALL_DOWNLOADS_ROUTE } from '@shared/lib/task-navigation'+import { Component, type ReactNode, useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useLocation, useNavigate } from 'react-router'++class MigrationBoundary extends Component<+ { children: ReactNode; fallback: ReactNode },+ { failed: boolean }+> {+ state = { failed: false }+ static getDerivedStateFromError() {+ return { failed: true }+ }+ render() {+ return this.state.failed ? this.props.fallback : this.props.children+ }+}++/** The main shell retains this instance so navigation never drops an import run/draft. */+export function MigrationPage({ active }: { active: boolean }) {+ const { t } = useTranslation()+ const location = useLocation()+ const navigate = useNavigate()+ const [started, setStarted] = useState(active)+ const [invitation, setInvitation] = useState(+ active && new URLSearchParams(location.search).get('invitation') === '1'+ )+ useEffect(() => {+ if (active) {+ setStarted(true)+ if (new URLSearchParams(location.search).get('invitation') === '1')+ setInvitation(true)+ }+ }, [active, location.search])+ return (+ <MigrationBoundary+ fallback={+ <PanelShell title={t('legacyImport.page.assistantTitle')}>+ <div role="alert" className="space-y-4 p-6">+ <p className="text-sm text-muted-foreground">+ {t('legacyImport.errors.pageUnavailable')}+ </p>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => navigate(ALL_DOWNLOADS_ROUTE)}+ >+ {t('legacyImport.viewTasks')}+ </Button>+ </div>+ </PanelShell>+ }+ >+ <LegacyImportDialog+ open={started}+ active={active}+ presentation="page"+ invitation={invitation}+ onClose={() => {+ setInvitation(false)+ navigate('/')+ }}+ onViewTasks={() => {+ setInvitation(false)+ setStarted(false)+ navigate(ALL_DOWNLOADS_ROUTE)+ }}+ />+ </MigrationBoundary>+ )+}diff --git a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx b/src/renderer/routes/settings/cards/advanced-dialog.test.tsxindex f57b59fd..c9d0539c 100644--- a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx@@ -7,6 +7,9 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'+const navigate = vi.fn()+vi.mock('react-router', () => ({ useNavigate: () => navigate }))+vi.mock('@renderer/lib/transport', () => ({transport: {invoke: vi.fn(async () => undefined),@@ -37,6 +40,7 @@ const SETTINGS_FIXTURE = {describe('<AdvancedDialog>', () => {beforeEach(() => {+ navigate.mockClear()vi.stubGlobal('ResizeObserver', MockResizeObserver)vi.mocked(transport.invoke).mockReset()vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {diff --git a/src/renderer/routes/settings/cards/advanced-dialog.tsx b/src/renderer/routes/settings/cards/advanced-dialog.tsxindex aae6ebfe..422cb40e 100644--- a/src/renderer/routes/settings/cards/advanced-dialog.tsx+++ b/src/renderer/routes/settings/cards/advanced-dialog.tsx@@ -47,11 +47,13 @@ import { Separator } from '@renderer/components/ui/separator'import { Switch } from '@renderer/components/ui/switch'import { pickDirty } from '@renderer/lib/form-utils'import { saveSettings } from '@renderer/lib/settings-save'+import { LEGACY_MIGRATION_SETTINGS_ROUTE } from '@shared/lib/legacy-import-navigation'import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas'import type { EngineSettings } from '@shared/types/settings'import { generateRpcSecret } from '@shared/utils/rpc-secret'import { useEffect, useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useNavigate } from 'react-router'import type { SettingsCardDialogProps } from './card-types'import { advancedFormSchema } from './settings-form-schemas'@@ -82,6 +84,7 @@ export function AdvancedDialog({labelKey,}: SettingsCardDialogProps) {const { t } = useTranslation()+ const navigate = useNavigate()const [historyModeOverride, setHistoryModeOverride] =useState<HistoryRetentionMode | null>(null)const historyModeRef = useRef<HistoryRetentionMode | null>(null)@@ -494,6 +497,29 @@ export function AdvancedDialog({</fieldset></form></Form>+ {__MOTRIX_TARGET__ === 'electron' && (+ <>+ <Separator className="my-4" />+ <div className="flex items-center justify-between gap-4">+ <div className="space-y-1">+ <h3 className="text-sm font-medium">+ {t('legacyImport.settingsTitle')}+ </h3>+ <p className="text-xs text-muted-foreground">+ {t('legacyImport.settingsDescription')}+ </p>+ </div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => navigate(LEGACY_MIGRATION_SETTINGS_ROUTE)}+ >+ {t('legacyImport.settingsAction')}+ </Button>+ </div>+ </>+ )}</ScrollAreaContent></ScrollAreaViewport><ScrollBar />diff --git a/src/renderer/routes/settings/settings-page.tsx b/src/renderer/routes/settings/settings-page.tsxindex 1c80580c..6751aca4 100644--- a/src/renderer/routes/settings/settings-page.tsx+++ b/src/renderer/routes/settings/settings-page.tsx@@ -1,12 +1,14 @@import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'import { useTranslation } from 'react-i18next'-import { useNavigate, useParams } from 'react-router'+import { useLocation, useNavigate, useParams } from 'react-router'import { findCard, SETTINGS_CARDS } from './card-registry'import { SettingsCard } from './cards/settings-card'export function SettingsPage() {const { t } = useTranslation()const navigate = useNavigate()+ const location = useLocation()+ const visible = /^\/settings(?:\/|$)/.test(location.pathname)const { cardId } = useParams<{ cardId: string }>()const activeCard = findCard(cardId)const columnsPerRow = 3@@ -33,7 +35,7 @@ export function SettingsPage() {</div>{activeCard && (<activeCard.Dialog- open+ open={visible}onClose={closeDialog}labelKey={activeCard.labelKey}descKey={activeCard.descKey}diff --git a/src/renderer/windows/onboarding-window.test.tsx b/src/renderer/windows/onboarding-window.test.tsxindex dfe4bfb4..08feac54 100644--- a/src/renderer/windows/onboarding-window.test.tsx+++ b/src/renderer/windows/onboarding-window.test.tsx@@ -34,8 +34,9 @@ describe('OnboardingWindow', () => {)render(<OnboardingWindow />)- expect(transport.invoke).toHaveBeenCalledExactlyOnceWith(- Queries.GetDisclaimerState+ expect(transport.invoke).toHaveBeenCalledWith(Queries.GetDisclaimerState)+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Queries.DiscoverLegacyImport)expect(screen.getByTestId('disclaimer-panel')).toBeVisible()expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()diff --git a/src/server/index.ts b/src/server/index.tsindex 5f2d721c..9054336f 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -45,6 +45,10 @@ import {TaskInspectorActivityStore,taskInspectorActivityEnvironment,} from '@core/inspector-activity'+import {+ getLegacyQuarantinedGids,+ hasLegacyImport,+} from '@core/legacy-import/legacy-task-policy'import { newTaskId } from '@core/lib/ids'import { getLogger, initLogger } from '@core/logger'import { registerEngineCompatibilitySubscriber } from '@core/notifications/engine-compatibility-subscriber'@@ -745,6 +749,12 @@ async function main() {supervisor.setStartupGuard(new CompletedTaskStartupGuard({completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),+ heldGids: () =>+ new Set(+ db+ .getAllTasks()+ .flatMap((pair) => [...getLegacyQuarantinedGids(pair)])+ ),rpc: rpcClient,removeResult: (gid) => adapter.removeDownloadResult(gid),})@@ -1679,7 +1689,11 @@ async function main() {runShellAsyncWork('HTTP finalize', async () => {const task = taskManager.getByEngineTaskId(engineTaskId)if (!task) return- if (task.type !== TaskType.Http && task.type !== TaskType.Ftp) {+ if (+ task.type !== TaskType.Http &&+ task.type !== TaskType.Ftp &&+ !hasLegacyImport(task)+ ) {return}if (shouldSkipEngineCompletionFinalize(task)) returndiff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 48e058f3..216cd9e8 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -109,6 +109,7 @@ import type { ServerDownloadPathPolicy } from '../download-path-policy'import type { ServerPluginInstallService } from '../plugin/install-service'import type { createServerProxyApplier } from '../proxy/wiring'import type { ServerDirectoryService } from '../server-directory-service'+import { unsupportedLegacyImportCommands } from './legacy-import'export interface ServerCommandContext {supervisor: EngineSupervisor@@ -419,6 +420,7 @@ export function buildServerCommandHandlers(manualMediaMerge.get(value),[Commands.CancelMediaMerge]: async (value: unknown) =>manualMediaMerge.cancel(value),+ ...unsupportedLegacyImportCommands(),[Commands.InstallFfmpeg]: async (payload: unknown) => {z.undefined().parse(payload)return { ok: false, error: 'unsupported' }diff --git a/src/server/ipc/legacy-import.test.ts b/src/server/ipc/legacy-import.test.tsnew file mode 100644index 00000000..889445c2--- /dev/null+++ b/src/server/ipc/legacy-import.test.ts@@ -0,0 +1,26 @@+import { ErrorCode } from '@shared/errors'+import { Queries } from '@shared/protocol/queries'+import { describe, expect, it } from 'vitest'+import {+ unsupportedLegacyImportCommands,+ unsupportedLegacyImportQueries,+} from './legacy-import'++describe('server legacy import boundary', () => {+ it('explicitly rejects every desktop import channel before interpreting a supplied path', async () => {+ const handlers = {+ ...unsupportedLegacyImportCommands(),+ ...unsupportedLegacyImportQueries(),+ }+ expect(Object.keys(handlers)).toHaveLength(16)+ await expect(+ handlers[Queries.GetLegacyImportNavigation]?.()+ ).resolves.toEqual({ detected: false, invitationPending: false })+ for (const [channel, handler] of Object.entries(handlers)) {+ if (channel === Queries.GetLegacyImportNavigation) continue+ await expect(+ handler?.({ root: '/untrusted/path', sourceHandle: '../../etc/passwd' })+ ).rejects.toMatchObject({ code: ErrorCode.EngineNotSupported })+ }+ })+})diff --git a/src/server/ipc/legacy-import.ts b/src/server/ipc/legacy-import.tsnew file mode 100644index 00000000..aafd2701--- /dev/null+++ b/src/server/ipc/legacy-import.ts@@ -0,0 +1,44 @@+import { AppError, ErrorCode } from '@shared/errors'+import { Commands } from '@shared/protocol/commands'+import type {+ CommandHandlerMap,+ QueryHandlerMap,+} from '@shared/protocol/handler-types'+import { Queries } from '@shared/protocol/queries'++async function desktopOnly(): Promise<never> {+ throw new AppError(+ ErrorCode.EngineNotSupported,+ 'legacyImport.errors.desktopOnly'+ )+}++/** Server requests cannot select, read or write a local legacy profile. */+export function unsupportedLegacyImportCommands(): CommandHandlerMap {+ return {+ [Commands.ActivateLegacyBt]: desktopOnly,+ [Commands.PickLegacyImportSource]: desktopOnly,+ [Commands.RevealLegacyImportSource]: desktopOnly,+ [Commands.PickLegacyTorrentMetadata]: desktopOnly,+ [Commands.CommitLegacyImport]: desktopOnly,+ [Commands.CancelLegacyImport]: desktopOnly,+ [Commands.RetryLegacyImport]: desktopOnly,+ [Commands.DismissLegacyImportInvitation]: desktopOnly,+ [Commands.FinishLegacyImportInvitation]: desktopOnly,+ [Commands.PrepareLegacyFreshDownload]: desktopOnly,+ [Commands.ExportLegacyImportReport]: desktopOnly,+ }+}++export function unsupportedLegacyImportQueries(): QueryHandlerMap {+ return {+ [Queries.GetLegacyImportNavigation]: async () => ({+ detected: false,+ invitationPending: false,+ }),+ [Queries.GetLegacyBtActivationAvailability]: desktopOnly,+ [Queries.DiscoverLegacyImport]: desktopOnly,+ [Queries.ScanLegacyImport]: desktopOnly,+ [Queries.GetLegacyImportRun]: desktopOnly,+ }+}diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.tsindex d5a463f5..58cc7d07 100644--- a/src/server/ipc/queries.ts+++ b/src/server/ipc/queries.ts@@ -57,6 +57,7 @@ import type { GetTaskActivityParams } from '@shared/types/task-activity'import type { ServerDownloadPathPolicy } from '../download-path-policy'import { makeServerFfmpegDetect } from '../plugin/ffmpeg-detect-server'import type { ServerDirectoryService } from '../server-directory-service'+import { unsupportedLegacyImportQueries } from './legacy-import'const UNSUPPORTED_WEB_CLI_STATUS: CliToolStatus = {phase: CliToolPhase.ManualOnly,@@ -172,6 +173,7 @@ export function buildServerQueryHandlers(})return {+ ...unsupportedLegacyImportQueries(),[Queries.GetFfmpegInstallStatus]: async () => ({phase: 'idle',bytesReceived: 0,diff --git a/src/shared/lib/legacy-import-navigation.ts b/src/shared/lib/legacy-import-navigation.tsnew file mode 100644index 00000000..36973602--- /dev/null+++ b/src/shared/lib/legacy-import-navigation.ts@@ -0,0 +1,3 @@+export const LEGACY_MIGRATION_ROUTE = '/migration'+export const LEGACY_MIGRATION_INVITATION_ROUTE = '/migration?invitation=1'+export const LEGACY_MIGRATION_SETTINGS_ROUTE = '/migration?from=settings'diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 9fa8f5b0..29ff6b42 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -3105,5 +3105,224 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_zero": "{{count}} tasks",+ "selectedNote_zero": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_two": "{{count}} tasks",+ "selectedNote_two": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_few": "{{count}} tasks",+ "selectedNote_few": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 97a69899..f5cc5064 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex 3f654567..c52ea1b0 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -3039,5 +3039,218 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex 42e9b0e7..75bbccae 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex 2657a9a1..7f464bc7 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 8f8c0c9b..defb9472 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Link",+ "bt": "Torrent",+ "magnet": "Magnet",+ "unknown": "Other"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex f9a70e1a..c02340ec 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -3039,5 +3039,218 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex a8ff7888..a4436381 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex 73e3a006..0d7a4290 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -3039,5 +3039,218 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex 1e2f5168..f993e8aa 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex c0b88ee3..3f00626f 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex f69b6732..fecbb417 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -3039,5 +3039,218 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex a36d4975..39f97e4a 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex df27e0f0..f96bab88 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex 18521343..4d86c985 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 519ec00f..90be1413 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex 5ba5f2af..6a29281b 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -3061,5 +3061,220 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_few": "{{count}} tasks",+ "selectedNote_few": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex 330b25d0..2a644f64 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -3039,5 +3039,218 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex ad0fd0d5..1f2cac42 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -3039,5 +3039,218 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_few": "{{count}} tasks",+ "selectedNote_few": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex 91c3a01a..49834525 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -3061,5 +3061,220 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_few": "{{count}} tasks",+ "selectedNote_few": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex 8bd3ca91..9fb9f29a 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex db116f05..bdea8324 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -3017,5 +3017,216 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex d7aea017..75a6ea56 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -3061,5 +3061,220 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_one": "{{count}} task",+ "selectedNote_one": "Selected {{count}} task. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_few": "{{count}} tasks",+ "selectedNote_few": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_many": "{{count}} tasks",+ "selectedNote_many": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex a83857c7..52d5a5fe 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "Original files are kept","format": "Output format"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 61a02bd2..25c46c0c 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "无损合并,保留源文件","format": "输出格式"+ },+ "legacyImport": {+ "navigation": "迁移",+ "title": "迁移",+ "pausedDescription": "选择要导入的旧版任务,导入后不会自动下载。",+ "settingsTitle": "迁移",+ "settingsDescription": "导入 Motrix v1 的下载任务。",+ "settingsAction": "打开迁移",+ "pickSource": "选择 Motrix v1 的数据文件夹",+ "source": "来源",+ "changeSource": "更换文件夹…",+ "noSource": "选择存放 Motrix v1 数据的文件夹",+ "discovery": "找到 {{count}} 项下载任务",+ "preserveFiles": "已下载的文件保留在原来的位置。",+ "chooseTasks": "选择任务",+ "skip": "暂不迁移",+ "back": "返回",+ "loading": "正在查找旧版任务…",+ "empty": "此文件夹中没有可迁移的任务。",+ "continueBefore": "继续下载前:",+ "capabilityLimit": "此任务需要重新下载。请选择新的保存位置,以保留原文件。",+ "running": "Motrix v1 可能仍在运行,请退出旧版后重新检查。",+ "recheck": "重新检查",+ "search": "搜索下载任务",+ "selectAll": "全选",+ "skipped": "已跳过 {{count}} 项",+ "backupNote": "导入前会备份任务列表,已下载的文件保留在原处。",+ "backingUp": "正在备份任务列表…",+ "committing": "正在导入任务…",+ "progress": "迁移进度",+ "processed": "已处理 {{done}} / {{total}} 项",+ "stop": "停止迁移",+ "stopTitle": "停止迁移?",+ "stopDescription": "已导入的任务会保留,剩余任务可以稍后再导入。",+ "resultTitle": "迁移完成",+ "importedCount": "已导入 {{count}} 项任务",+ "resultDescription": "已导入的任务可在“下载”中查看。",+ "details": "查看明细",+ "exportReport": "保存报告…",+ "retry": "迁移剩余任务",+ "viewTasks": "查看下载",+ "freshDownload": "重新下载…",+ "freshDescription": "选择新的保存位置后,Motrix 会创建单独的文件夹,并打开下载窗口供你确认。本次将从头下载,原文件会保留。",+ "freshDestination": "选择新下载的保存位置",+ "chooseDestination": "选择其他位置…",+ "reasons": {+ "fresh-download-required": "需要重新下载",+ "verification-required": "需要检查已有文件",+ "metadata-required": "需要原种子文件",+ "selection-required": "需要重新选择文件",+ "unsupported-options": "下载信息需要确认",+ "invalid-record": "无法读取此任务",+ "unsafe-path": "文件位置需要确认",+ "already-imported": "已经导入",+ "deleted-import": "此前已移除",+ "path-conflict": "其他任务正在使用此位置",+ "changed-source": "旧版数据有变动",+ "not-selected": "未选择",+ "stopped": "停止时尚未导入",+ "commit-failed": "导入失败,可以重试"+ },+ "errors": {+ "pageUnavailable": "迁移页面无法打开,请重启 Motrix 后重试。已导入的任务会保留。",+ "failed": "操作未能完成,请重试。",+ "consentRequired": "请先同意使用协议,再打开迁移。",+ "invalidSource": "未找到旧版数据,请选择 Motrix v1 原来的数据文件夹。",+ "unsafeSource": "无法安全读取此文件夹,请选择 Motrix v1 原来的数据文件夹。",+ "unsafeBackup": "无法安全备份任务列表,已停止导入。",+ "tooLarge": "旧版任务数据过大,暂时无法导入。",+ "tooManySources": "打开的文件夹过多,请重启 Motrix 后再试。",+ "sourceNotAuthorized": "请在弹出的窗口中选择旧版数据文件夹。",+ "expiredPreview": "任务列表需要更新,请重新检查后再导入。",+ "changedSource": "旧版数据有变动,请重新检查后再导入。",+ "running": "Motrix v1 可能仍在运行,请退出旧版后重新检查。",+ "invalidSelection": "所选任务有变动,请重新检查列表。",+ "pathConflict": "其他任务正在使用此文件位置,请重新检查列表。",+ "busy": "正在导入任务,请等待完成。",+ "unknownRun": "无法读取本次导入结果。",+ "unknownTask": "此导入任务已经不可用。",+ "rescanRequired": "请重新选择数据文件夹,再导入剩余任务。",+ "metadataRequired": "请先选择此任务原来的种子文件。",+ "unsafePath": "请选择可以访问的文件夹。",+ "mirrorsUnsupported": "此任务包含多个下载地址,请复制要使用的地址并新建下载。",+ "stopping": "Motrix 正在退出,请重新打开后再导入。",+ "desktopOnly": "请在 Motrix 桌面应用中使用迁移。",+ "metadataMismatch": "这个种子与旧任务不一致。请选择原来的种子文件。",+ "checkpointUnavailable": "当前版本无法接着下载原文件,你可以换一个文件夹重新下载。",+ "activationSourceMissing": "旧版任务信息不完整,请换一个文件夹重新下载。",+ "selectionRequired": "无法确定之前选择了哪些文件,请重新下载并选择文件。",+ "originalDirectoryRequired": "请选择这里显示的原文件夹。文件移动后暂时无法继续下载。",+ "payloadMissing": "部分原文件缺失,包括之前未选中的文件。继续下载需要这些文件,请换一个文件夹重新下载。",+ "payloadUnsafe": "原文件的链接或权限设置使其无法安全更新。请保留原文件,并换一个文件夹重新下载。",+ "controlRequired": "找不到旧版保存的下载进度,请换一个文件夹重新下载。",+ "activationUncertain": "暂时无法安全恢复此任务,原文件仍受保护。你可以换一个文件夹重新下载。"+ },+ "resultIncompleteTitle": "迁移尚未完成",+ "resultStoppedTitle": "迁移已停止",+ "activationRequired": "请选择新的文件夹重新下载,原文件会保留。",+ "chooseTorrent": "选择种子文件…",+ "torrentFile": "种子文件",+ "verifyAndContinue": "检查并继续",+ "verifyDescription": "Motrix 会先检查原文件,再按旧任务的文件选择继续下载。下载期间可能上传数据,未选文件也可能写入部分内容;完成后不会自动做种。",+ "authorizeOriginalDirectory": "选择原下载文件夹",+ "verifyReady": "你可以检查已有文件后继续下载,也可以换一个文件夹重新下载。",+ "trackersReadOnly": "此任务沿用旧版的 Tracker,暂不支持修改。",+ "page": {+ "stepsLabel": "迁移步骤",+ "steps": {+ "select": "选择任务",+ "import": "导入任务",+ "result": "查看结果"+ },+ "foundSummary": "任务类型",+ "selectionSummary": "已选择",+ "resultSummary": "迁移结果",+ "countUnit": "项",+ "notImported": "尚未导入",+ "skippedSummary": "已跳过",+ "types": {+ "http": "链接",+ "bt": "种子",+ "magnet": "磁力",+ "unknown": "其他"+ },+ "pathUnavailable": "下载位置未知",+ "filesStayTitle": "文件保留在原处",+ "filesStayDescription": "迁移不会移动或删除已下载的文件。",+ "nextTitle": "仅迁移下载任务",+ "nextDescription": "应用设置保持不变。",+ "footerNote": "迁移后,任务将保持暂停。",+ "discoveryDescription": "选择要保留的任务。部分任务需要重新下载,或先检查已有文件。",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "选择要添加到 Motrix 的下载任务。",+ "selectionTitle": "选择要迁移的内容",+ "searchEmpty": "没有找到匹配的任务。",+ "resultEmptyTitle": "没有新增任务",+ "resultEmptyDescription": "展开明细,查看每项任务未导入的原因。",+ "resultIncompleteDescription": "已导入的任务会保留。查看明细后,可重试剩余任务。",+ "resultStoppedDescription": "已导入的任务会保留,你可以继续导入剩余任务。",+ "outcomes": {+ "imported": "已导入",+ "skipped": "已跳过",+ "failed": "导入失败",+ "unprocessed": "尚未导入"+ },+ "sourceDescription": "来源:{{name}}",+ "assistantTitle": "迁移助手",+ "backToSource": "返回来源",+ "continue": "继续",+ "revealSource": "在文件夹中显示",+ "welcomeTitle": "迁移下载任务",+ "sourceFeedback": {+ "retry": "重试",+ "unreadableTitle": "无法从此位置读取下载任务",+ "chooseFolder": "请选择旧版 Motrix 使用的数据文件夹。",+ "readTitle": "无法读取下载任务",+ "readDescription": "请确认此位置可以访问,然后重试。",+ "pickTitle": "无法使用所选文件夹",+ "pickDescription": "请重新选择文件夹,之前的选择仍然保留。",+ "revealTitle": "无法显示此文件夹",+ "revealDescription": "请确认此位置可以访问,然后重试。",+ "discoverTitle": "无法查找旧版下载任务",+ "discoverDescription": "请重试,或手动选择旧版 Motrix 的数据文件夹。",+ "reading": "正在读取下载任务…"+ },+ "sourceTitle": "从哪里迁移?",+ "sourceIntroduction": "将旧版 Motrix 的下载任务导入到这里。接下来,你可以选择要迁移的内容,已下载的文件会保留在原处。",+ "sourceKind": "旧版下载任务",+ "sourceHelp": "选择 Motrix v1 使用的数据文件夹。已下载的文件会保留在原处。",+ "noSourceDescription": "没有找到旧版 Motrix 的下载任务。你可以选择其他位置继续查找。",+ "progressTitle": "正在迁移下载任务",+ "progressDescription": "正在备份任务列表,并将任务添加到 Motrix。",+ "selectGroup": "选择{{name}}",+ "phases": {+ "discovery": "选择来源",+ "selection": "选择内容",+ "progress": "正在迁移",+ "result": "迁移结果"+ },+ "groups": {+ "http": "链接下载",+ "bt": "种子下载",+ "magnet": "磁力链接",+ "unknown": "其他任务"+ },+ "groupDescriptions": {+ "http": "需要重新下载",+ "bt": "继续前会检查已有文件",+ "magnet": "需要原种子文件",+ "unknown": "查看任务信息"+ },+ "groupCount_other": "{{count}} 项",+ "selectedNote_other": "已选择 {{count}} 项任务。迁移后任务保持暂停,已下载的文件保留在原处。",+ "run": {+ "backup": "备份任务列表",+ "backupActive": "正在保存旧版任务列表的备份…",+ "backupDone": "备份已保存",+ "add": "添加下载任务",+ "waiting": "等待备份完成",+ "completeDescription": "任务已添加到“下载”中,保持暂停,等待你继续。",+ "partialDescription": "已迁移的任务保持暂停。你可以重试剩余任务,或先查看下载。",+ "stoppedEmptyDescription": "尚未添加任何任务,你可以在准备好后重新迁移。",+ "failedEmptyDescription": "尚未添加任何任务。请查看明细后重试。",+ "imported": "已迁移",+ "remaining": "尚未迁移"+ }+ },+ "importSelected": "迁移"}}diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 8c3e2234..69876eaa 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -2995,5 +2995,214 @@},"preserveOriginals": "無損合併,保留原始檔案","format": "輸出格式"+ },+ "legacyImport": {+ "navigation": "Migration",+ "title": "Migration",+ "pausedDescription": "Choose which Motrix v1 downloads to import. They won’t start automatically.",+ "settingsTitle": "Migration",+ "settingsDescription": "Import your downloads from Motrix v1.",+ "settingsAction": "Open migration",+ "pickSource": "Choose the Motrix v1 data folder",+ "source": "From",+ "changeSource": "Change folder…",+ "noSource": "Choose the folder containing your Motrix v1 data",+ "discovery": "Downloads found: {{count}}",+ "preserveFiles": "Downloaded files stay in their original location.",+ "chooseTasks": "Choose downloads",+ "skip": "Not now",+ "back": "Back",+ "loading": "Looking for your old downloads…",+ "empty": "There are no tasks to migrate from this folder.",+ "continueBefore": "Before continuing:",+ "capabilityLimit": "This task needs to be downloaded again. Choose a new folder to keep the original files.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "recheck": "Check again",+ "search": "Search downloads",+ "selectAll": "Select all",+ "skipped": "Skipped: {{count}}",+ "backupNote": "Your task list is backed up before import. Downloaded files stay in place.",+ "backingUp": "Backing up your task list…",+ "committing": "Adding your downloads…",+ "progress": "Migration progress",+ "processed": "{{done}} / {{total}} processed",+ "stop": "Stop migration",+ "stopTitle": "Stop migration?",+ "stopDescription": "Downloads already imported will be kept. You can import the rest later.",+ "resultTitle": "Migration complete",+ "importedCount": "Imported {{count}}",+ "resultDescription": "Your imported tasks are now in Downloads.",+ "details": "View details",+ "exportReport": "Save report…",+ "retry": "Migrate remaining",+ "viewTasks": "View downloads",+ "freshDownload": "Download again…",+ "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…",+ "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",+ "invalid-record": "Couldn’t read this task",+ "unsafe-path": "File location needs checking",+ "already-imported": "Already imported",+ "deleted-import": "Previously removed",+ "path-conflict": "Another task uses this location",+ "changed-source": "Old task data has changed",+ "not-selected": "Not selected",+ "stopped": "Not imported before stopping",+ "commit-failed": "Import failed. You can try again."+ },+ "errors": {+ "pageUnavailable": "Migration couldn’t open. Restart Motrix and try again. Downloads already imported are kept.",+ "failed": "The operation couldn’t be completed. Please try again.",+ "consentRequired": "Accept the agreement before opening migration.",+ "invalidSource": "No Motrix v1 data was found here. Choose its original data folder.",+ "unsafeSource": "This data folder can’t be read safely. Choose the original Motrix v1 folder.",+ "unsafeBackup": "A safe backup couldn’t be created, so importing has stopped.",+ "tooLarge": "This task list is too large to import.",+ "tooManySources": "Too many folders have been opened. Restart Motrix and try again.",+ "sourceNotAuthorized": "Select the old data folder using the folder picker.",+ "expiredPreview": "This task list needs refreshing. Check again before importing.",+ "changedSource": "The old task data has changed. Check again before importing.",+ "running": "Motrix v1 may still be running. Quit it, then check again.",+ "invalidSelection": "The selected tasks have changed. Check the list again.",+ "pathConflict": "Another task uses this file location. Check the list again.",+ "busy": "An import is already running. Wait for it to finish.",+ "unknownRun": "The import result is unavailable.",+ "unknownTask": "This imported task is no longer available.",+ "rescanRequired": "Choose the data folder again to import the remaining tasks.",+ "metadataRequired": "Choose this task’s original torrent file first.",+ "unsafePath": "Choose a folder you can access.",+ "mirrorsUnsupported": "This task uses multiple download links. Copy the link you want to use and add a new download.",+ "stopping": "Motrix is closing. Reopen it to continue importing.",+ "desktopOnly": "Open migration in the Motrix desktop app.",+ "metadataMismatch": "This torrent does not match the old task. Choose its original torrent file.",+ "checkpointUnavailable": "This version can’t resume the old files. You can download again in a new folder.",+ "activationSourceMissing": "Some original task information is missing. Download again in a new folder.",+ "selectionRequired": "The previous file selection is unavailable. Choose the files again in a new download.",+ "originalDirectoryRequired": "Choose the original folder shown here. Files moved to another location can’t be resumed.",+ "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."+ },+ "resultIncompleteTitle": "Migration is incomplete",+ "resultStoppedTitle": "Migration stopped",+ "activationRequired": "Download again in a new folder to keep the original files.",+ "chooseTorrent": "Choose torrent…",+ "torrentFile": "Torrent file",+ "verifyAndContinue": "Verify and continue",+ "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.",+ "trackersReadOnly": "This download keeps its original trackers. They can’t be changed here.",+ "page": {+ "stepsLabel": "Migration steps",+ "steps": {+ "select": "Choose downloads",+ "import": "Import",+ "result": "Review"+ },+ "foundSummary": "Download types",+ "selectionSummary": "Selected",+ "resultSummary": "Migration summary",+ "countUnit": "total",+ "notImported": "Not imported",+ "skippedSummary": "Skipped",+ "types": {+ "http": "Direct links",+ "bt": "Torrents",+ "magnet": "Magnet links",+ "unknown": "Other tasks"+ },+ "pathUnavailable": "Download location unavailable",+ "filesStayTitle": "Your files stay where they are",+ "filesStayDescription": "Migration won’t move or delete downloaded files.",+ "nextTitle": "Only your downloads",+ "nextDescription": "Your app settings stay the same.",+ "footerNote": "Imported tasks will stay paused.",+ "discoveryDescription": "Choose what to add to your download list. Some tasks need a new download or a check of the existing files.",+ "previousVersion": "Motrix v1",+ "currentVersion": "Motrix",+ "introduction": "Choose the downloads you’d like to add to Motrix.",+ "selectionTitle": "Choose what to migrate",+ "searchEmpty": "No matching downloads.",+ "resultEmptyTitle": "No new downloads",+ "resultEmptyDescription": "Open the details to see why each task was skipped.",+ "resultIncompleteDescription": "Downloads already imported are kept. Review the details and try importing the rest again.",+ "resultStoppedDescription": "Downloads already imported are kept. You can import the rest when you’re ready.",+ "outcomes": {+ "imported": "Imported",+ "skipped": "Skipped",+ "failed": "Failed",+ "unprocessed": "Not imported"+ },+ "sourceDescription": "From {{name}}",+ "assistantTitle": "Migration Assistant",+ "backToSource": "Back to source",+ "continue": "Continue",+ "revealSource": "Show in folder",+ "welcomeTitle": "Migrate your downloads",+ "sourceFeedback": {+ "retry": "Try again",+ "unreadableTitle": "Unable to read downloads from this location",+ "chooseFolder": "Choose the data folder used by the previous version of Motrix.",+ "readTitle": "Unable to read downloads",+ "readDescription": "Check that this location is accessible, then try again.",+ "pickTitle": "Unable to use the selected folder",+ "pickDescription": "Try choosing the folder again. Your previous selection is still available.",+ "revealTitle": "Unable to show this folder",+ "revealDescription": "Check that this location is accessible, then try again.",+ "discoverTitle": "Unable to look for previous downloads",+ "discoverDescription": "Try again, or choose the previous Motrix data folder yourself.",+ "reading": "Reading downloads…"+ },+ "sourceTitle": "Where would you like to migrate from?",+ "sourceIntroduction": "Import your download tasks from the previous version of Motrix. You can choose what to migrate next. Your downloaded files will stay where they are.",+ "sourceKind": "Downloads from the previous version",+ "sourceHelp": "Choose the data folder used by Motrix v1. Your downloaded files stay where they are.",+ "noSourceDescription": "No downloads from the previous version of Motrix were found. Choose another location to look for them.",+ "progressTitle": "Migrating your downloads",+ "progressDescription": "Your task list is being backed up and added to Motrix.",+ "selectGroup": "Select {{name}}",+ "phases": {+ "discovery": "Choose source",+ "selection": "Choose content",+ "progress": "Migration",+ "result": "Result"+ },+ "groups": {+ "http": "Direct links",+ "bt": "Torrent downloads",+ "magnet": "Magnet links",+ "unknown": "Other downloads"+ },+ "groupDescriptions": {+ "http": "A new download is needed",+ "bt": "Existing files will be checked before continuing",+ "magnet": "The original torrent file is needed",+ "unknown": "Review the task details"+ },+ "groupCount_other": "{{count}} tasks",+ "selectedNote_other": "Selected {{count}} tasks. After migration, tasks will stay paused and downloaded files will remain in place.",+ "run": {+ "backup": "Back up task list",+ "backupActive": "Saving a copy of your previous task list…",+ "backupDone": "Backup saved",+ "add": "Add downloads",+ "waiting": "Waiting for the backup",+ "completeDescription": "Your tasks are now in Downloads, paused until you’re ready to continue.",+ "partialDescription": "Imported tasks are paused. You can retry the remaining tasks or view your downloads.",+ "stoppedEmptyDescription": "No tasks were added. You can try again when you’re ready.",+ "failedEmptyDescription": "No tasks were added. Review the details, then try again.",+ "imported": "Imported",+ "remaining": "Remaining"+ }+ },+ "importSelected": "Migrate"}}diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex c720bb5a..e556e977 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -5,6 +5,17 @@ export const Commands = {GetMediaMergeJob: 'command:getMediaMergeJob',CancelMediaMerge: 'command:cancelMediaMerge',PickFile: 'command:pickFile',+ ActivateLegacyBt: 'command:activateLegacyBt',+ PickLegacyImportSource: 'command:pickLegacyImportSource',+ RevealLegacyImportSource: 'command:revealLegacyImportSource',+ PickLegacyTorrentMetadata: 'command:pickLegacyTorrentMetadata',+ CommitLegacyImport: 'command:commitLegacyImport',+ CancelLegacyImport: 'command:cancelLegacyImport',+ RetryLegacyImport: 'command:retryLegacyImport',+ DismissLegacyImportInvitation: 'command:dismissLegacyImportInvitation',+ FinishLegacyImportInvitation: 'command:finishLegacyImportInvitation',+ PrepareLegacyFreshDownload: 'command:prepareLegacyFreshDownload',+ ExportLegacyImportReport: 'command:exportLegacyImportReport',SetCompletionShutdown: 'command:setCompletionShutdown',SaveDownloadsSettings: 'command:saveDownloadsSettings',PauseTask: 'command:pauseTask',diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.tsindex a26b5106..0b0ac173 100644--- a/src/shared/protocol/events.ts+++ b/src/shared/protocol/events.ts@@ -10,6 +10,7 @@ export interface WindowMaximizedChangedPayload {}export const Events = {+ LegacyImportNavigationChanged: 'event:legacyImportNavigationChanged',CompletionShutdownChanged: 'event:completionShutdownChanged',TaskUpdated: 'event:taskUpdated',TaskFilesUpdated: 'event:taskFilesUpdated',diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.tsindex 02d772ee..59a65809 100644--- a/src/shared/protocol/queries.ts+++ b/src/shared/protocol/queries.ts@@ -1,4 +1,9 @@export const Queries = {+ GetLegacyImportNavigation: 'query:getLegacyImportNavigation',+ GetLegacyBtActivationAvailability: 'query:getLegacyBtActivationAvailability',+ DiscoverLegacyImport: 'query:discoverLegacyImport',+ ScanLegacyImport: 'query:scanLegacyImport',+ GetLegacyImportRun: 'query:getLegacyImportRun',GetCompletionShutdown: 'query:getCompletionShutdown',GetDownloadsSettingsDraft: 'query:getDownloadsSettingsDraft',GetDisclaimerState: 'query:getDisclaimerState',diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.tsindex d391d611..36f8f19a 100644--- a/src/shared/schemas/add-task.ts+++ b/src/shared/schemas/add-task.ts@@ -209,9 +209,30 @@ export const addTaskUrlParamsSchema = z.object({})export type AddTaskUrlParams = z.infer<typeof addTaskUrlParamsSchema>-// ── Event payloads (reused from URL params + runtime validation) ─+// A draft can be incomplete (including an explicitly empty torrent selection).+// Submission still goes through addTaskFormSchema and taskCreateRequestSchema.+export const addTaskPrefillSchema = z.discriminatedUnion('tab', [+ linksTabSchema+ .partial()+ .extend({ tab: z.literal('links') })+ .strict(),+ z+ .object({+ ...torrentTabSchema.shape,+ base64: z.string().max(MAX_TORRENT_BASE64_SIZE).optional(),+ selectedFiles: z.array(z.number().int().nonnegative()).max(10000),+ })+ .partial()+ .extend({ tab: z.literal('torrent') })+ .strict(),+])++// ── Event payloads (URL opens and validated in-app form drafts) ─-export const setAddTaskModeEventPayloadSchema = addTaskUrlParamsSchema+export const setAddTaskModeEventPayloadSchema = z.union([+ addTaskPrefillSchema,+ addTaskUrlParamsSchema.strict(),+])export const magnetFileSelectionPayloadSchema = z.object({// Plan B Task 3: motrixId of the persisted magnet_metadata_resolution@@ -367,6 +388,14 @@ export function urlParamsToFormDefaults(}}+export function addTaskModeToFormDefaults(+ payload: z.infer<typeof setAddTaskModeEventPayloadSchema>+): Partial<AddTaskFormValues> {+ return 'tab' in payload+ ? payload+ : (urlParamsToFormDefaults(payload) as Partial<AddTaskFormValues>)+}+export function encodeUrlParams(p: AddTaskUrlParams): Record<string, string> {const out: Record<string, string> = {}for (const [k, v] of Object.entries(p)) {diff --git a/src/shared/schemas/legacy-bt-activation.ts b/src/shared/schemas/legacy-bt-activation.tsnew file mode 100644index 00000000..c95d95cc--- /dev/null+++ b/src/shared/schemas/legacy-bt-activation.ts@@ -0,0 +1,43 @@+import { z } from 'zod'+import {+ legacyCheckpointFileSchema,+ legacyCheckpointMetadataSchema,+} from './legacy-checkpoint'++/** Durable user authorization and recovery identity, never an engine add request. */+export const legacyBtActivationSchema = z+ .object({+ version: z.literal(1),+ stage: z.enum([+ 'import-uncertain',+ 'checkpoint',+ 'create-uncertain',+ 'bound',+ '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),+ controlDigest: z.string().regex(/^[a-f0-9]{64}$/),+ torrentDigest: z.string().regex(/^[a-f0-9]{64}$/),+ expected: legacyCheckpointMetadataSchema,+ files: z.array(legacyCheckpointFileSchema).min(1).max(10000),+ selectedFiles: z.array(z.number().int().nonnegative()).min(1).max(10000),+ trackers: z.array(z.string()).max(10000),+ isPrivate: z.boolean(),+ })+ .strict()+export type LegacyBtActivation = z.infer<typeof legacyBtActivationSchema>+export const legacyBtAvailabilitySchema = z+ .object({+ available: z.boolean(),+ reason: z.string().nullable(),+ directory: z.string(),+ })+ .strict()diff --git a/src/shared/schemas/legacy-checkpoint.ts b/src/shared/schemas/legacy-checkpoint.tsnew file mode 100644index 00000000..ddb7c0a3--- /dev/null+++ b/src/shared/schemas/legacy-checkpoint.ts@@ -0,0 +1,165 @@+import { z } from 'zod'++// App limits leave room for the JSON envelope on engines using a 2 MiB RPC limit.+// The native codec may support larger snapshots without the app admitting them.+export const MAX_LEGACY_CHECKPOINT_BYTES = 1024 * 1024+export const MAX_LEGACY_CHECKPOINT_RANGES = 100000+const byteCount = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)+const identityValue = z.string().regex(/^(0|[1-9][0-9]{0,19})$/)+const digest = z.string().regex(/^[0-9a-f]{64}$/)+const token = z+ .string()+ .min(16)+ .max(128)+ .regex(/^[A-Za-z0-9_-]+$/)+const engineTaskId = z+ .string()+ .regex(/^[0-9a-f]{16}$/)+ .refine((v) => !/^0+$/.test(v))+const filePath = z+ .string()+ .min(1)+ .max(4096)+ .refine((v) =>+ [...v].every(+ (char) => char.charCodeAt(0) > 31 && char.charCodeAt(0) !== 127+ )+ )++export const legacyCheckpointMetadataSchema = z+ .object({+ type: z.enum(['http', 'bt']),+ totalBytes: byteCount,+ pieceBytes: byteCount.min(1).max(2147483647),+ infoHash: z+ .string()+ .regex(/^[0-9a-f]{40}$/)+ .nullable(),+ })+ .strict()+ .superRefine((value, ctx) => {+ if ((value.type === 'bt') !== (value.infoHash !== null))+ ctx.addIssue({+ code: 'custom',+ message: 'Checkpoint content identity does not match its type',+ })+ })+export const legacyCheckpointInspectionSchema = legacyCheckpointMetadataSchema+ .safeExtend({+ sourceDigest: digest,+ completedBytes: byteCount,+ uploadedBytes: byteCount,+ ranges: z+ .array(z.object({ offset: byteCount, length: byteCount.min(1) }).strict())+ .max(MAX_LEGACY_CHECKPOINT_RANGES),+ })+ .superRefine((value, ctx) => {+ let end = 0+ let completed = 0+ for (const range of value.ranges) {+ if (+ range.offset < end ||+ range.length > value.totalBytes - range.offset+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'Checkpoint ranges overlap or exceed the payload',+ })+ return+ }+ end = range.offset + range.length+ completed += range.length+ }+ if (completed !== value.completedBytes)+ ctx.addIssue({+ code: 'custom',+ message: 'Checkpoint progress does not match its ranges',+ })+ })+export type LegacyCheckpointInspection = z.infer<+ typeof legacyCheckpointInspectionSchema+>++export const legacyCheckpointFileSchema = z+ .object({+ path: filePath,+ offset: byteCount,+ length: byteCount,+ identity: z+ .object({+ device: identityValue,+ inode: identityValue,+ size: identityValue,+ mtimeNs: identityValue,+ ctimeNs: identityValue,+ })+ .strict(),+ })+ .strict()+export type LegacyCheckpointFile = z.infer<typeof legacyCheckpointFileSchema>++export const legacyCheckpointImportSchema = z+ .object({+ token,+ engineTaskId,+ targetPath: filePath,+ controlFile: z+ .instanceof(Uint8Array)+ .refine(+ (v) => v.byteLength > 0 && v.byteLength <= MAX_LEGACY_CHECKPOINT_BYTES+ ),+ sourceDigest: digest,+ expected: legacyCheckpointMetadataSchema,+ files: z.array(legacyCheckpointFileSchema).min(1).max(10000),+ })+ .strict()+ .superRefine((value, ctx) => {+ let offset = 0+ const paths = new Set<string>()+ for (const file of value.files) {+ if (+ file.offset !== offset ||+ paths.has(file.path) ||+ file.length > value.expected.totalBytes - offset+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'Checkpoint file mapping is incomplete or overlaps',+ })+ return+ }+ paths.add(file.path)+ offset += file.length+ }+ if (+ offset !== value.expected.totalBytes ||+ (value.expected.type === 'http' &&+ (value.files.length !== 1 || value.files[0].path !== value.targetPath))+ )+ ctx.addIssue({+ code: 'custom',+ message: 'Checkpoint file mapping does not match its metadata',+ })+ })+export type LegacyCheckpointImport = z.infer<+ typeof legacyCheckpointImportSchema+>++export const legacyCheckpointReconcileSchema = z+ .object({ token, targetPath: filePath })+ .strict()+export type LegacyCheckpointReconcile = z.infer<+ typeof legacyCheckpointReconcileSchema+>+export const legacyCheckpointReceiptSchema =+ legacyCheckpointReconcileSchema.extend({+ status: z.enum(['created', 'consumed']),+ engineTaskId,+ sourceDigest: digest,+ })+export type LegacyCheckpointReceipt = z.infer<+ typeof legacyCheckpointReceiptSchema+>+export type LegacyCheckpointReconciliation =+ | LegacyCheckpointReceipt+ | (LegacyCheckpointReconcile & { status: 'absent' })diff --git a/src/shared/schemas/legacy-import.ts b/src/shared/schemas/legacy-import.tsnew file mode 100644index 00000000..f052c2fd--- /dev/null+++ b/src/shared/schemas/legacy-import.ts@@ -0,0 +1,149 @@+import { z } from 'zod'++export const legacyImportNavigationSchema = z.object({+ detected: z.boolean(),+ invitationPending: z.boolean(),+})+export type LegacyImportNavigationState = z.infer<+ typeof legacyImportNavigationSchema+>++export const legacyReasonSchema = z.enum([+ 'fresh-download-required',+ 'verification-required',+ 'metadata-required',+ 'selection-required',+ 'unsupported-options',+ 'invalid-record',+ 'unsafe-path',+ 'already-imported',+ 'deleted-import',+ 'path-conflict',+ 'changed-source',+ 'not-selected',+ 'stopped',+ 'commit-failed',+])+export type LegacyReason = z.infer<typeof legacyReasonSchema>++export const legacyImportItemSchema = z.object({+ itemId: z.string().min(1).max(128),+ name: z.string().max(1024),+ // Display-only original directory; optional for reports saved by older builds.+ saveDir: z.string().max(4096).nullable().optional(),+ type: z.enum(['http', 'bt', 'magnet', 'unknown']),+ selectable: z.boolean(),+ reason: legacyReasonSchema,+})+export type LegacyImportItem = z.infer<typeof legacyImportItemSchema>++export const legacyImportPreviewSchema = z.object({+ previewId: z.uuid(),+ sourceHandle: z.uuid(),+ sourceName: z.string(),+ items: z.array(legacyImportItemSchema).max(10000),+ running: z.boolean(),+ checkpointImportAvailable: z.boolean(),+ expiresAt: z.number(),+})+export type LegacyImportPreview = z.infer<typeof legacyImportPreviewSchema>++export const legacyImportSourceSchema = z.object({+ sourceHandle: z.uuid(),+ name: z.string(),+ dataPath: z.string().min(1),+})+export type LegacyImportSource = z.infer<typeof legacyImportSourceSchema>++export const legacyImportSourceSelectionSchema = z.union([+ legacyImportSourceSchema,+ z+ .object({+ dataPath: z.string().min(1),+ errorCode: z.enum([+ 'invalidSource',+ 'unsafeSource',+ 'changedSource',+ 'tooManySources',+ 'failed',+ ]),+ })+ .strict(),+])++export const legacyImportReportSchema = z.object({+ runId: z.uuid(),+ stage: z.enum([+ 'backing-up',+ 'committing',+ 'completed',+ 'cancelled',+ 'failed',+ ]),+ processed: z.number().int().nonnegative(),+ total: z.number().int().nonnegative(),+ imported: z.number().int().nonnegative(),+ backupCreated: z.boolean(),+ items: z+ .array(+ legacyImportItemSchema.extend({+ outcome: z.enum(['imported', 'skipped', 'failed', 'unprocessed']),+ taskId: z.string().nullable(),+ })+ )+ .max(10000),+})+export type LegacyImportReport = z.infer<typeof legacyImportReportSchema>++export const legacyScanRequestSchema = z+ .object({ sourceHandle: z.uuid() })+ .strict()+export const legacyMetadataRequestSchema = z+ .object({ previewId: z.uuid(), itemId: z.string().min(1).max(128) })+ .strict()+export const legacyCommitRequestSchema = z+ .object({+ previewId: z.uuid(),+ itemIds: z.array(z.string().min(1).max(128)).min(1).max(10000),+ })+ .strict()+export const legacyRunRequestSchema = z.object({ runId: z.uuid() }).strict()+export const legacyTaskRequestSchema = z+ .object({ taskId: z.string().min(1).max(128) })+ .strict()++export const legacyTaskMetadataSchema = z+ .object({+ version: z.literal(1),+ sourceId: z.string(),+ itemKey: z.string(),+ activation: z.enum(['inactive', 'activating', 'active']),+ storagePolicy: z.enum(['legacy-read-only', 'legacy-bt-in-place']),+ reason: legacyReasonSchema,+ selectionKnown: z.boolean(),+ selectedFiles: z.array(z.number().int().nonnegative()).max(10000),+ origin: z+ .object({+ root: z.string(),+ identity: z.string(),+ sessionDigest: z.string().regex(/^[a-f0-9]{64}$/),+ torrentDigest: z+ .string()+ .regex(/^[a-f0-9]{64}$/)+ .nullable(),+ profileFiles: z+ .array(+ z+ .object({+ relativePath: z.string(),+ digest: z.string().regex(/^[a-f0-9]{64}$/),+ })+ .strict()+ )+ .max(3),+ })+ .strict()+ .optional(),+ })+ .strict()+export type LegacyTaskMetadata = z.infer<typeof legacyTaskMetadataSchema>diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex 9948957b..18aa9c81 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -1,4 +1,6 @@import { isUriOnlyDirectReplay } from '@shared/schemas/direct-replay-recipe'+import { legacyBtActivationSchema } from '@shared/schemas/legacy-bt-activation'+import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'import {type DownloadTask,TaskInstancePhase,@@ -72,7 +74,7 @@ export function canPause(t: DownloadTask): boolean {}export function canResume(t: DownloadTask): boolean {- return t.status === TaskStatus.Paused+ return t.status === TaskStatus.Paused && !isLegacyImportInactive(t)}/** A completed task whose published output is a single file. */@@ -87,6 +89,7 @@ export function canOpenTaskFile(t: DownloadTask): boolean {/** Live multi-file downloads that accept a changed file selection. */export function canSelectTaskFiles(t: DownloadTask): boolean {return (+ !hasLegacyImport(t) &&Boolean(t.engineTaskId) &&t.fileCount > 1 &&(isTorrentLike(t) || t.type === TaskType.Metalink) &&@@ -112,6 +115,7 @@ export function canStopSeeding(t: DownloadTask): boolean {export function canReseed(t: DownloadTask): boolean {return (+ !hasLegacyImport(t) &&t.status === TaskStatus.Completed &&isTorrentLikeType(t.type) &&t.torrentMetaPath != null@@ -119,7 +123,10 @@ export function canReseed(t: DownloadTask): boolean {}export function canRetry(t: DownloadTask): boolean {- return t.status === TaskStatus.Error || t.status === TaskStatus.Removed+ return (+ !hasLegacyImport(t) &&+ (t.status === TaskStatus.Error || t.status === TaskStatus.Removed)+ )}export function canRemove(t: DownloadTask): boolean {@@ -243,3 +250,36 @@ export function getTaskRetryKind(t: DownloadTask): TaskRetryKind | null {export function canAttemptRetry(t: DownloadTask): boolean {return getTaskRetryKind(t) !== null}++export function hasLegacyImport(t: Pick<DownloadTask, 'instances'>): boolean {+ return (t.instances ?? []).some((instance) =>+ Object.hasOwn(instance.payload ?? {}, 'legacyImport')+ )+}++/** Unknown markers or an unconfirmed durable binding fail closed. */+export function isLegacyImportInactive(+ t: Pick<DownloadTask, 'instances'>+): boolean {+ return (t.instances ?? []).some((instance) => {+ if (!Object.hasOwn(instance.payload ?? {}, 'legacyImport')) return false+ const marker = legacyTaskMetadataSchema.safeParse(+ instance.payload.legacyImport+ )+ const activation = legacyBtActivationSchema.safeParse(+ instance.payload.legacyBtActivation+ )+ return (+ !marker.success ||+ marker.data.activation !== 'active' ||+ marker.data.storagePolicy !== 'legacy-bt-in-place' ||+ !activation.success ||+ !['bound', 'active'].includes(activation.data.stage) ||+ instance.gid !== activation.data.engineTaskId ||+ !marker.data.selectionKnown ||+ marker.data.origin?.torrentDigest !== activation.data.torrentDigest ||+ marker.data.selectedFiles.join(',') !==+ activation.data.selectedFiles.join(',')+ )+ })+}diff --git a/src/test-utils/aria2.test.ts b/src/test-utils/aria2.test.tsnew file mode 100644index 00000000..ed1cd8bd--- /dev/null+++ b/src/test-utils/aria2.test.ts@@ -0,0 +1,36 @@+// @vitest-environment node+import { createServer } from 'node:http'+import { describe, expect, it } from 'vitest'+import { waitForRpc } from './aria2'++describe('test engine readiness ownership', () => {+ it('does not accept a successful HTTP response containing an RPC authentication error', async () => {+ const server = createServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(+ JSON.stringify({+ jsonrpc: '2.0',+ id: 'probe',+ error: { code: 1, message: 'Unauthorized' },+ })+ )+ })+ 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 port')+ try {+ await expect(+ waitForRpc(address.port, 150, 'this-instance')+ ).rejects.toThrow('did not come up')+ } finally {+ server.closeAllConnections()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ })++ it('does not inspect a port after its own child has exited', async () => {+ await expect(+ waitForRpc(1, 5000, 'this-instance', () => new Error('child exited'))+ ).rejects.toThrow('child exited')+ })+})diff --git a/src/test-utils/aria2.ts b/src/test-utils/aria2.tsindex e0a86530..03d7b27a 100644--- a/src/test-utils/aria2.ts+++ b/src/test-utils/aria2.ts@@ -7,7 +7,9 @@// on platforms that do not ship the binary.import { type ChildProcess, spawn, spawnSync } from 'node:child_process'+import { randomBytes } from 'node:crypto'import { accessSync } from 'node:fs'+import { createServer } from 'node:net'import path from 'node:path'import { aria2BinaryName } from '@shared/platform/aria2'import { Aria2Adapter } from '../core/engine/aria2/aria2-adapter'@@ -94,8 +96,8 @@ export function canBindLoopbackTcp(): boolean {export async function spawnAria2ForTest(opts: SpawnAria2Options): Promise<Aria2Handle> {- const port = opts.port ?? 16800 + Math.floor(Math.random() * 2000)- const secret = opts.secret ?? 'test_secret'+ const port = opts.port ?? (await availablePort())+ const secret = opts.secret ?? randomBytes(24).toString('hex')const bin = opts.binaryPath ?? resolveBundledAria2()const proc = spawn(@@ -121,14 +123,28 @@ export async function spawnAria2ForTest({ stdio: ['ignore', 'pipe', 'pipe'] })- // Swallow stdout/stderr so test output stays clean. If a spawn fails we- // still see the exit code / signal from `proc` itself.- proc.stdout?.on('data', () => {})- proc.stderr?.on('data', () => {})+ // Keep bounded diagnostics for startup failures without noisy passing tests.+ let startupOutput = ''+ const collectOutput = (chunk: Buffer) => {+ startupOutput = (startupOutput + chunk.toString()).slice(-4096)+ }+ proc.stdout?.on('data', collectOutput)+ proc.stderr?.on('data', collectOutput)+ let spawnError: Error | undefined+ proc.once('error', (error) => {+ spawnError = error+ })+ const failure = () =>+ spawnError ??+ (proc.exitCode !== null || proc.signalCode !== null+ ? new Error(+ `Test aria2 exited before its authenticated RPC was ready (exit=${proc.exitCode}, signal=${proc.signalCode}): ${startupOutput.trim()}`+ )+ : undefined)if (opts.waitForHttpRpc !== false) {try {- await waitForRpc(port, 5000)+ await waitForRpc(port, 5000, secret, failure)} catch (err) {// Bail out cleanly if RPC never comes up.if (!proc.killed) proc.kill('SIGKILL')@@ -141,10 +157,10 @@ export async function spawnAria2ForTest(port,secret,kill: async () => {- if (proc.killed || proc.exitCode !== null) return+ if (proc.exitCode !== null || proc.signalCode !== null) returnawait new Promise<void>((resolve) => {const hardKill = setTimeout(() => {- if (!proc.killed && proc.exitCode === null) {+ if (proc.exitCode === null && proc.signalCode === null) {proc.kill('SIGKILL')}}, 1000)@@ -159,29 +175,67 @@ export async function spawnAria2ForTest(}}+async function availablePort(): Promise<number> {+ const server = createServer()+ server.unref()+ return new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const address = server.address()+ server.close((error) => {+ if (error) reject(error)+ else if (address && typeof address !== 'string') resolve(address.port)+ else reject(new Error('Unable to reserve a test aria2 port'))+ })+ })+ })+}+/*** Poll aria2's RPC endpoint until it responds or the timeout elapses.* Uses HTTP POST (simpler than WebSocket for readiness probing).*/export async function waitForRpc(port: number,- timeoutMs: number+ timeoutMs: number,+ secret?: string,+ processFailure?: () => Error | undefined): Promise<void> {const start = Date.now()let lastErr: unknown = nullwhile (Date.now() - start < timeoutMs) {+ const failure = processFailure?.()+ if (failure) throw failuretry {const res = await fetch(`http://127.0.0.1:${port}/jsonrpc`, {method: 'POST',+ signal: AbortSignal.timeout(+ Math.max(1, Math.min(500, timeoutMs - (Date.now() - start)))+ ),headers: { 'content-type': 'application/json' },body: JSON.stringify({jsonrpc: '2.0',id: 'probe',- method: 'system.listMethods',- params: [],+ method: secret ? 'aria2.getVersion' : 'system.listMethods',+ params: secret ? [`token:${secret}`] : [],}),})- if (res.ok) return+ if (res.ok) {+ const body = (await res.json()) as {+ result?: { version?: unknown }+ error?: unknown+ }+ if (+ !body.error &&+ (secret+ ? typeof body.result?.version === 'string'+ : Array.isArray(body.result))+ ) {+ const failure = processFailure?.()+ if (failure) throw failure+ return+ }+ }} catch (err) {lastErr = err}diff --git a/src/test-utils/legacy-bt-activation-fixture.ts b/src/test-utils/legacy-bt-activation-fixture.tsnew file mode 100644index 00000000..a4346b1d--- /dev/null+++ b/src/test-utils/legacy-bt-activation-fixture.ts@@ -0,0 +1,112 @@+import {+ cp,+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'+import { LegacyBtActivationService } from '@core/legacy-import/bt-activation-service'+import { LegacyImportService } from '@core/legacy-import/import-service'+import { MotrixDatabase } from '@core/session/motrix-database'+import { TaskManager } from '@core/task/task-manager'+import { vi } from 'vitest'++/** Actual v1 metadata/control snapshots; deterministic payloads recreated from the recorded recipe. */+export async function legacyBtActivationFixture(adapter: EngineAdapter) {+ const root = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-bt-activation-'))+ )+ await cp(path.resolve('tests/fixtures/legacy-v1/generated'), root, {+ recursive: true,+ })+ const profile = path.join(root, 'profile')+ const downloads = path.join(root, 'downloads')+ for (const name of ['download.session', 'system.json']) {+ const filename = path.join(profile, name)+ await writeFile(+ filename,+ (await readFile(filename, 'utf8'))+ .replaceAll('__FIXTURE_ROOT__', profile)+ .replaceAll('__FIXTURE_DOWNLOADS__', downloads)+ .replaceAll('__FIXTURE_HTTP_PORT__', '18080')+ )+ }+ await mkdir(path.join(downloads, 'fixture-bundle'))+ for (const [name, byte] of [+ ['first.bin', 1],+ ['second.bin', 2],+ ] as const)+ await writeFile(+ path.join(downloads, 'fixture-bundle', name),+ Buffer.alloc(16384, byte),+ { mode: 0o600 }+ )+ const db = new MotrixDatabase(path.join(root, 'motrix.db'))+ db.init()+ const taskManager = new TaskManager()+ const importer = new LegacyImportService({+ db,+ taskManager,+ backupRoot: path.join(root, 'backups'),+ isProcessRunning: () => false,+ publishTasks: vi.fn(),+ })+ const source = await importer.addSource(profile)+ const preview = await importer.scan(source.sourceHandle)+ const item = preview.items.find((entry) => entry.type === 'bt')+ if (!item) throw new Error('No BT fixture')+ const next = await importer.authorizeMetadata(+ { previewId: preview.previewId, itemId: item.itemId },+ async () =>+ path.join(downloads, 'a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent')+ )+ if (!next) throw new Error('No authorized preview')+ const run = await importer.commit({+ previewId: next.previewId,+ itemIds: [item.itemId],+ })+ await vi.waitFor(() => expectCompleted())+ function expectCompleted() {+ if (importer.getRun(run.runId).stage !== 'completed')+ throw new Error('Import pending')+ }+ const taskId = db.getAllTasks()[0].task.motrixId+ const publishTasks = vi.fn()+ const deps = {+ db,+ taskManager,+ adapter,+ backupRoot: path.join(root, 'backups'),+ isProcessRunning: vi.fn(() => false),+ publishTasks,+ runTaskMutation: async <T>(+ _ids: readonly string[],+ operation: () => Promise<T>+ ) => operation(),+ runExclusivePersistence: async <T>(operation: () => T | Promise<T>) =>+ operation(),+ }+ const service = new LegacyBtActivationService(deps)+ return {+ root,+ profile,+ downloads,+ taskId,+ db,+ taskManager,+ service,+ deps,+ importer,+ dispose: async () => {+ await service.drain()+ await importer.drain()+ db.close()+ await rm(root, { recursive: true, force: true })+ },+ }+}diff --git a/tests/fixtures/legacy-v1/README.md b/tests/fixtures/legacy-v1/README.mdnew file mode 100644index 00000000..c0998459--- /dev/null+++ b/tests/fixtures/legacy-v1/README.md@@ -0,0 +1,53 @@+# Motrix v1.8.19 fixtures++These fixtures were generated by the **actual bundled aria2 1.36.0 executable**+from the official Motrix `v1.8.19` Git tree. The generator extracts that binary+from Git and verifies its SHA-256 before executing it. It does not use the+current Motrix engine, an adjacent engine checkout, or a real user profile.+The binary itself is not checked in.++Run on macOS arm64 from the repository root:++```sh+node tests/fixtures/legacy-v1/generate.mjs+```++The local checkout must contain tag `v1.8.19`, commit+`a0a1fe90f7e9f6d305ed2b512f62c8d36c2fb95a`. The authoritative binary is+`extra/darwin/arm64/engine/aria2c`, Git object+`f4a274061acbbc22c6eb1ab487ffdc0e80ad1b71`, SHA-256+`1527c4d071c16c1266880e93750e385cdd4e9d2a950d7f56cb5a21125e3bd311`.+Source reference: [official Motrix v1.8.19 tree](https://github.com/agalwood/Motrix/tree/v1.8.19).++The generator creates a disposable profile and a separate downloads directory,+as normal installations do. Only loopback HTTP/RPC/tracker endpoints are used;+DHT, PEX and local peer discovery are disabled. The HTTP response is generated+test data, and the two-file private torrent describes generated test data.+No private tokens, trackers, credentials or user paths are included.++`download.session`, both `.aria2` files and the saved RPC `.torrent` are actual+old-engine output. The `.aria2` and `.torrent` bytes are unmodified.+`partial.bin.gz` contains the actual partial HTTP output, compressed+without changing its uncompressed bytes. Profile/download directory prefixes+and the HTTP port in text files use placeholders. The saved torrent contains+its original loopback tracker port. Ports, incomplete block boundaries and+torrent filenames can vary on regeneration; `provenance.json` records the+resulting digests and the source binary identity.++`user.json` and `system.json` are **source-derived defaults**, evaluated from+the tagged `ConfigManager.js` with disposable paths and an English locale.+They are not presented as output from running the complete old Electron app.+The engine is launched using these defaults and the tagged `aria2.conf`, with+the documented loopback/isolation overrides in the generator.++The saved RPC torrent filename is the SHA-1 of its complete metadata bytes,+which differs from its info hash. Its session reference is outside the profile+grant. Scanner tests deliberately verify that this real layout yields an+unselectable `metadata-required` row rather than reading arbitrary downloads+paths from `system.json`. A separately labeled test variant copies metadata+inside the grant to verify parsing and file selection. The external-directory+case still needs an explicit additional user grant before it can be imported.++These fixtures prove compatibility with this tagged binary's serialization;+they do not prove packaged cross-platform migration, historical HTTP validator+availability, or safe continuation from arbitrary legacy files.diff --git a/tests/fixtures/legacy-v1/README.zh-CN.md b/tests/fixtures/legacy-v1/README.zh-CN.mdnew file mode 100644index 00000000..04eb25b7--- /dev/null+++ b/tests/fixtures/legacy-v1/README.zh-CN.md@@ -0,0 +1,45 @@+# Motrix v1.8.19 测试样本++这些样本由官方 Motrix `v1.8.19` Git 树中实际随应用发布的+**aria2 1.36.0 可执行文件**生成。生成器从 Git 提取该文件,检查 SHA-256+后再运行,不使用当前 Motrix 引擎、相邻引擎工作区或真实用户配置。+可执行文件本身不提交到仓库。++在 macOS arm64 上,从仓库根目录运行:++```sh+node tests/fixtures/legacy-v1/generate.mjs+```++本地仓库须包含标签 `v1.8.19`,对应提交+`a0a1fe90f7e9f6d305ed2b512f62c8d36c2fb95a`。权威可执行文件路径为+`extra/darwin/arm64/engine/aria2c`,Git 对象为+`f4a274061acbbc22c6eb1ab487ffdc0e80ad1b71`,SHA-256 为+`1527c4d071c16c1266880e93750e385cdd4e9d2a950d7f56cb5a21125e3bd311`。+源码参考:[官方 Motrix v1.8.19 Git 树](https://github.com/agalwood/Motrix/tree/v1.8.19)。++生成器建立临时配置目录及独立的下载目录,与普通安装的目录关系一致。+HTTP、RPC 和 tracker 都只监听回环地址,并关闭 DHT、PEX 和局域网发现。+HTTP 内容及包含两个文件的私有种子都是生成的测试数据,不含私人令牌、+tracker、凭据或用户路径。++`download.session`、两份 `.aria2` 以及 RPC 保存的 `.torrent` 均为旧引擎+的真实输出。`.aria2` 和 `.torrent` 字节没有修改。`partial.bin.gz` 是实际+部分 HTTP 下载文件的 gzip 压缩版本,解压后的字节未作修改。文本中的配置、+下载目录前缀和 HTTP 端口使用占位符;种子保留生成时的回环 tracker 端口。+重新生成时端口、未完成块边界及种子文件名可能变化,`provenance.json`+记录每份结果的摘要及来源引擎身份。++`user.json` 和 `system.json` 是从标签中的 `ConfigManager.js` 求值获得的+默认配置,使用临时路径及英文区域设置。它们**不代表运行完整旧版 Electron+应用生成的配置**。引擎使用这些默认配置和标签中的 `aria2.conf` 启动,并+应用生成器中明确列出的回环网络隔离选项。++RPC 保存的种子文件名是整个元信息文件的 SHA-1,与种子的 info hash 不同。+会话引用的种子位于配置目录授权范围之外。扫描测试验证这种真实布局会产生+不可选择的 `metadata-required` 项,不会根据 `system.json` 读取任意下载+目录。另一个明确标注的测试变体把元信息放入授权范围,用于验证解析与文件+选择。原始外部目录布局需要用户额外授权所引用的种子文件后才能导入。++这些样本证明了对该标签引擎序列化格式的兼容性,不证明跨平台安装包迁移、+历史 HTTP 校验信息可用性,或任意旧文件的安全续传。diff --git a/tests/fixtures/legacy-v1/generate.mjs b/tests/fixtures/legacy-v1/generate.mjsnew file mode 100644index 00000000..6fb25d8b--- /dev/null+++ b/tests/fixtures/legacy-v1/generate.mjs@@ -0,0 +1,455 @@+import { execFileSync, spawn } from 'node:child_process'+import { createHash } from 'node:crypto'+import {+ chmod,+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ rm,+ writeFile,+} from 'node:fs/promises'+import { createServer } from 'node:http'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import vm from 'node:vm'+import { gzipSync } from 'node:zlib'++// Requires only Git, Node, and the executable bundled in the local v1.8.19 tag.+// No current engine binary or real Motrix profile participates in generation.+const tag = 'v1.8.19'+const commit = 'a0a1fe90f7e9f6d305ed2b512f62c8d36c2fb95a'+const directory = path.dirname(fileURLToPath(import.meta.url))+const repository = path.resolve(directory, '../../..')+const platform = process.platform+const architecture = process.arch+if (platform !== 'darwin' || architecture !== 'arm64') {+ throw new Error(+ 'This pinned fixture generator requires darwin/arm64; fixtures are platform-neutral after normalization'+ )+}+const binaryPath = 'extra/darwin/arm64/engine/aria2c'+const binarySha256 =+ '1527c4d071c16c1266880e93750e385cdd4e9d2a950d7f56cb5a21125e3bd311'+const git = (...args) =>+ execFileSync('git', args, { cwd: repository, maxBuffer: 16 * 1024 * 1024 })+const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')+if (git('rev-parse', tag).toString().trim() !== commit)+ throw new Error('Unexpected legacy tag commit')+const binary = git('show', `${tag}:${binaryPath}`)+if (sha256(binary) !== binarySha256)+ throw new Error('Unexpected legacy bundled binary digest')+const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-v1-generated-'))+const profile = path.join(root, 'profile')+// Motrix normally puts its profile and downloads in separate directories.+const downloads = path.join(root, 'downloads')+await mkdir(downloads, { recursive: true })+await mkdir(profile)+const executable = path.join(root, 'aria2c')+await writeFile(executable, binary)+await chmod(executable, 0o700)+const version = execFileSync(executable, ['--version'], {+ encoding: 'utf8',+}).split('\n')[0]+const configurationPath = 'src/main/core/ConfigManager.js'+const source = git('show', `${tag}:${configurationPath}`).toString()+const defaults = [...source.matchAll(/defaults: (\{[\s\S]*?\n {6}\})/g)]+if (defaults.length !== 2)+ throw new Error('Legacy ConfigManager defaults changed')+const constantsSource = git('show', `${tag}:src/shared/constants.js`).toString()+const uaSource = git('show', `${tag}:src/shared/ua.js`).toString()+const stringConstant = (name) => {+ const match = new RegExp(`export const ${name} = '([^']*)'`).exec(+ `${constantsSource}\n${uaSource}`+ )+ if (!match) throw new Error(`Missing legacy constant ${name}`)+ return match[1]+}+const context = {+ EMPTY_STRING: '',+ IP_VERSION: { V4: 4, V6: 6 },+ APP_THEME: { AUTO: 'auto' },+ APP_RUN_MODE: { STANDARD: 1 },+ CHROME_UA: stringConstant('CHROME_UA'),+ NGOSANG_TRACKERS_BEST_IP_URL_CDN: stringConstant(+ 'NGOSANG_TRACKERS_BEST_IP_URL_CDN'+ ),+ NGOSANG_TRACKERS_BEST_URL_CDN: stringConstant(+ 'NGOSANG_TRACKERS_BEST_URL_CDN'+ ),+ getDhtPath: (version) =>+ path.join(profile, version === 4 ? 'dht.dat' : 'dht6.dat'),+ getUserDownloadsPath: () => downloads,+ getMaxConnectionPerServer: () => 64,+ app: { getLocale: () => 'en-US' },+ is: { macOS: () => true, windows: () => false, linux: () => false },+}+const system = vm.runInNewContext(`(${defaults[0][1]})`, context, {+ timeout: 1000,+})+const user = vm.runInNewContext(`(${defaults[1][1]})`, context, {+ timeout: 1000,+})+const normalize = (text) =>+ text+ .replaceAll(profile, '__FIXTURE_ROOT__')+ .replaceAll(downloads, '__FIXTURE_DOWNLOADS__')+await writeFile(+ path.join(profile, 'system.json'),+ JSON.stringify(system, null, 2)+)+await writeFile(path.join(profile, 'user.json'), JSON.stringify(user, null, 2))+const conf = git('show', `${tag}:extra/darwin/arm64/engine/aria2.conf`)+await writeFile(path.join(root, 'aria2.conf'), conf)++const sleep = (milliseconds) =>+ new Promise((resolve) => setTimeout(resolve, milliseconds))+const payload = Buffer.alloc(4 * 1024 * 1024)+for (let index = 0; index < payload.length; index++)+ payload[index] = index % 251+const server = createServer((request, response) => {+ if (request.url === '/announce') {+ response.end('d8:intervali3600e5:peers0:e')+ return+ }+ const range = /^bytes=(\d+)-(\d*)$/.exec(request.headers.range ?? '')+ const start = range ? Number(range[1]) : 0+ const end = range?.[2]+ ? Math.min(Number(range[2]), payload.length - 1)+ : payload.length - 1+ response.writeHead(range ? 206 : 200, {+ 'Content-Length': end - start + 1,+ 'Accept-Ranges': 'bytes',+ ETag: '"fixture-v1-stable"',+ 'Last-Modified': 'Mon, 01 May 2023 00:00:00 GMT',+ ...(range+ ? { 'Content-Range': `bytes ${start}-${end}/${payload.length}` }+ : {}),+ })+ if (request.method === 'HEAD') {+ response.end()+ return+ }+ let cursor = start+ const timer = setInterval(() => {+ const next = Math.min(cursor + 65536, end + 1)+ response.write(payload.subarray(cursor, next))+ cursor = next+ if (cursor > end) {+ clearInterval(timer)+ response.end()+ }+ }, 20)+ response.on('close', () => clearInterval(timer))+})+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))+const httpPort = server.address().port+const reserve = createServer()+await new Promise((resolve) => reserve.listen(0, '127.0.0.1', resolve))+const rpcPort = reserve.address().port+await new Promise((resolve) => reserve.close(resolve))+let engine+let engineExit+let engineLog = ''+const rpc = async (method, ...params) => {+ const response = await fetch(`http://127.0.0.1:${rpcPort}/jsonrpc`, {+ method: 'POST',+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: method,+ method: `aria2.${method}`,+ params: ['token:fixture-only', ...params],+ }),+ signal: AbortSignal.timeout(2000),+ })+ const body = await response.json()+ if (body.error) throw new Error(JSON.stringify(body.error))+ return body.result+}+const waitFor = async (operation) => {+ const deadline = Date.now() + 15000+ while (Date.now() < deadline) {+ try {+ const value = await operation()+ if (value) return value+ } catch {}+ await sleep(50)+ }+ throw new Error(`Legacy engine fixture timed out\n${engineLog}`)+}+const bencode = (value) => {+ if (Buffer.isBuffer(value))+ return Buffer.concat([Buffer.from(`${value.length}:`), value])+ if (typeof value === 'string') return bencode(Buffer.from(value))+ if (typeof value === 'number') return Buffer.from(`i${value}e`)+ if (Array.isArray(value))+ return Buffer.concat([+ Buffer.from('l'),+ ...value.map(bencode),+ Buffer.from('e'),+ ])+ return Buffer.concat([+ Buffer.from('d'),+ ...Object.keys(value)+ .sort()+ .flatMap((key) => [bencode(key), bencode(value[key])]),+ Buffer.from('e'),+ ])+}+try {+ const argumentsList = [+ `--conf-path=${path.join(root, 'aria2.conf')}`,+ `--save-session=${path.join(profile, 'download.session')}`,+ ...Object.entries(system)+ .filter(([, value]) => value !== '')+ .map(([key, value]) => `--${key}=${value}`),+ `--rpc-listen-port=${rpcPort}`,+ '--rpc-listen-all=false',+ '--rpc-secret=fixture-only',+ '--enable-dht=false',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ '--enable-peer-exchange=false',+ '--no-netrc=true',+ '--save-session-interval=0',+ '--auto-save-interval=0',+ '--max-concurrent-downloads=2',+ ]+ engine = spawn(executable, argumentsList, {+ cwd: profile,+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ engineExit = new Promise((resolve, reject) => {+ engine.once('exit', resolve)+ engine.once('error', reject)+ })+ engine.stdout.on('data', (bytes) => {+ engineLog += bytes.toString()+ })+ engine.stderr.on('data', (bytes) => {+ engineLog += bytes.toString()+ })+ await waitFor(() => rpc('getVersion'))+ const uri = `http://127.0.0.1:${httpPort}/partial.bin`+ const httpGid = await rpc(+ 'addUri',+ [uri, `http://127.0.0.1:${httpPort}/mirror.bin`],+ {+ gid: '0123456789abcdef',+ dir: downloads,+ out: 'partial.bin',+ pause: 'false',+ split: '1',+ 'max-connection-per-server': '1',+ }+ )+ const httpStatus = await waitFor(async () => {+ const status = await rpc('tellStatus', httpGid)+ return Number(status.completedLength) >= 1500000 &&+ status.status === 'active'+ ? status+ : null+ })+ await rpc('forcePause', httpGid)+ const httpPaused = await waitFor(async () => {+ const status = await rpc('tellStatus', httpGid)+ return status.status === 'paused' ? status : null+ })+ const info = {+ name: 'fixture-bundle',+ private: 1,+ 'piece length': 16384,+ files: [+ { length: 16384, path: ['first.bin'] },+ { length: 16384, path: ['second.bin'] },+ ],+ pieces: Buffer.concat([+ createHash('sha1').update(Buffer.alloc(16384, 1)).digest(),+ createHash('sha1').update(Buffer.alloc(16384, 2)).digest(),+ ]),+ }+ const torrent = bencode({+ announce: `http://127.0.0.1:${httpPort}/announce`,+ info,+ })+ const infoHash = createHash('sha1').update(bencode(info)).digest('hex')+ const btGid = await rpc('addTorrent', torrent.toString('base64'), [], {+ gid: 'fedcba9876543210',+ dir: downloads,+ pause: 'false',+ 'select-file': '1',+ 'seed-time': '0',+ 'bt-tracker': '',+ 'bt-save-metadata': 'true',+ })+ await waitFor(+ async () => (await rpc('tellStatus', btGid)).status === 'active'+ )+ await sleep(250)+ await rpc('forcePause', btGid)+ const btPaused = await waitFor(async () => {+ const status = await rpc('tellStatus', btGid)+ return status.status === 'paused' ? status : null+ })+ await rpc(+ 'addUri',+ [+ 'magnet:?xt=urn:btih:1111111111111111111111111111111111111111&dn=fixture-magnet',+ ],+ {+ gid: '1111222233334444',+ dir: downloads,+ pause: 'true',+ }+ )+ await rpc('saveSession')+ await rpc('shutdown')+ await engineExit+ engine = null+ const output = path.join(directory, 'generated')+ await rm(output, { recursive: true, force: true })+ await mkdir(output, { recursive: true })+ const session = await readFile(path.join(profile, 'download.session'), 'utf8')+ await mkdir(path.join(output, 'profile'))+ await writeFile(+ path.join(output, 'profile', 'download.session'),+ normalize(session).replaceAll(String(httpPort), '__FIXTURE_HTTP_PORT__')+ )+ await writeFile(+ path.join(output, 'profile', 'system.json'),+ `${normalize(JSON.stringify(system, null, 2))}\n`+ )+ await writeFile(+ path.join(output, 'profile', 'user.json'),+ `${JSON.stringify(user, null, 2)}\n`+ )+ const files = []+ const visit = async (dir) => {+ for (const item of await readdir(dir, { withFileTypes: true })) {+ const filename = path.join(dir, item.name)+ if (item.isDirectory()) await visit(filename)+ else if (item.name.endsWith('.aria2') || item.name.endsWith('.torrent')) {+ const bytes = await readFile(filename)+ const relative = path.relative(root, filename)+ const target = path.join(output, relative)+ await mkdir(path.dirname(target), { recursive: true })+ await writeFile(target, bytes)+ files.push({+ path: relative,+ sha256: sha256(bytes),+ bytes: bytes.length,+ })+ }+ }+ }+ await visit(profile)+ await visit(downloads)+ if (!files.some((file) => file.path.endsWith('partial.bin.aria2')))+ throw new Error('Missing real partial HTTP control file')+ if (!files.some((file) => file.path.endsWith('fixture-bundle.aria2')))+ throw new Error('Missing real BT control file')+ const metadataDigest = createHash('sha1').update(torrent).digest('hex')+ if (!files.some((file) => file.path.endsWith(`${metadataDigest}.torrent`)))+ throw new Error('Missing engine-saved RPC torrent')+ const partial = await readFile(path.join(downloads, 'partial.bin'))+ await writeFile(+ path.join(output, 'downloads', 'partial.bin.gz'),+ gzipSync(partial)+ )+ await writeFile(+ path.join(output, 'provenance.json'),+ `${JSON.stringify(+ {+ tag,+ commit,+ binaryPath,+ binarySha256,+ binaryGitObject: git('rev-parse', `${tag}:${binaryPath}`)+ .toString()+ .trim(),+ version,+ sourceConfigSha256: sha256(source),+ generation:+ 'The tagged v1 bundled engine generated download.session, .aria2 control files and saved RPC .torrent files. Config JSON is source-derived ConfigManager defaults, not a full old Electron application run.',+ normalization:+ 'Only profile/download path prefixes and HTTP port in text files are replaced with fixture placeholders. Downloads are siblings of the profile, as in a normal installation. Control and torrent bytes are unmodified. Saved partial HTTP payload is gzip-compressed without altering its uncompressed bytes.',+ safety:+ 'Disposable profile, local range HTTP server and tracker only; DHT, PEX and LPD disabled. No real user profiles or external download endpoints.',+ http: {+ gid: httpGid,+ completedLengthAtPauseRequest: httpStatus.completedLength,+ totalLength: httpStatus.totalLength,+ payloadSha256: sha256(payload),+ payloadRecipe: '4194304 bytes; byte at zero-based index i is i % 251',+ checkpointStatus: {+ completedLength: httpPaused.completedLength,+ totalLength: httpPaused.totalLength,+ pieceLength: httpPaused.pieceLength,+ numPieces: httpPaused.numPieces,+ bitfield: httpPaused.bitfield,+ files: httpPaused.files.map(+ ({+ index,+ path: filename,+ length,+ completedLength,+ selected,+ }) => ({+ index,+ path: normalize(filename),+ length,+ completedLength,+ selected,+ })+ ),+ },+ savedPayloadBytes: partial.length,+ savedPayloadSha256: sha256(partial),+ savedPayloadGzip: 'downloads/partial.bin.gz',+ },+ bt: {+ gid: btGid,+ infoHash,+ metadataFilename: `${metadataDigest}.torrent`,+ selectedFiles: [1],+ private: true,+ checkpointStatus: {+ completedLength: btPaused.completedLength,+ totalLength: btPaused.totalLength,+ pieceLength: btPaused.pieceLength,+ numPieces: btPaused.numPieces,+ bitfield: btPaused.bitfield,+ files: btPaused.files.map(+ ({+ index,+ path: filename,+ length,+ completedLength,+ selected,+ }) => ({+ index,+ path: normalize(filename),+ length,+ completedLength,+ selected,+ })+ ),+ },+ },+ files,+ },+ null,+ 2+ )}\n`+ )+ console.log(JSON.stringify({ version, output, files }, null, 2))+} finally {+ if (engine) {+ engine.kill('SIGKILL')+ await engineExit+ }+ server.closeAllConnections()+ await new Promise((resolve) => server.close(resolve))+ await rm(root, { recursive: true, force: true })+}diff --git a/tests/fixtures/legacy-v1/generated/downloads/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent b/tests/fixtures/legacy-v1/generated/downloads/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrentnew file mode 100644index 00000000..e95242b8--- /dev/null+++ b/tests/fixtures/legacy-v1/generated/downloads/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent@@ -0,0 +1 @@+d8:announce31:http://127.0.0.1:60559/announce4:infod5:filesld6:lengthi16384e4:pathl9:first.bineed6:lengthi16384e4:pathl10:second.bineee4:name14:fixture-bundle12:piece lengthi16384e6:pieces40:��4�����s�a�a��o��N_~�R��F���[j����7:privatei1eee\ No newline at end of filediff --git a/tests/fixtures/legacy-v1/generated/downloads/fixture-bundle.aria2 b/tests/fixtures/legacy-v1/generated/downloads/fixture-bundle.aria2new file mode 100644index 00000000..9af43899Binary files /dev/null and b/tests/fixtures/legacy-v1/generated/downloads/fixture-bundle.aria2 differdiff --git a/tests/fixtures/legacy-v1/generated/downloads/partial.bin.aria2 b/tests/fixtures/legacy-v1/generated/downloads/partial.bin.aria2new file mode 100644index 00000000..03d6fb3bBinary files /dev/null and b/tests/fixtures/legacy-v1/generated/downloads/partial.bin.aria2 differdiff --git a/tests/fixtures/legacy-v1/generated/downloads/partial.bin.gz b/tests/fixtures/legacy-v1/generated/downloads/partial.bin.gznew file mode 100644index 00000000..d2a572beBinary files /dev/null and b/tests/fixtures/legacy-v1/generated/downloads/partial.bin.gz differdiff --git a/tests/fixtures/legacy-v1/generated/profile/download.session b/tests/fixtures/legacy-v1/generated/profile/download.sessionnew file mode 100644index 00000000..28ac9261--- /dev/null+++ b/tests/fixtures/legacy-v1/generated/profile/download.session@@ -0,0 +1,69 @@+__FIXTURE_DOWNLOADS__/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent+ gid=fedcba9876543210+ pause=true+ dir=__FIXTURE_DOWNLOADS__+ split=64+ max-download-limit=0+ allow-overwrite=false+ continue=true+ no-netrc=true+ auto-file-renaming=true+ max-connection-per-server=64+ pause-metadata=false+ user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36+ follow-torrent=true+ select-file=1+ seed-time=0+ seed-ratio=1+ enable-peer-exchange=false+ bt-save-metadata=true+ bt-enable-lpd=false+ bt-tracker=+ bt-force-encryption=false+ bt-load-saved-metadata=true+ follow-metalink=true+http://127.0.0.1:__FIXTURE_HTTP_PORT__/partial.bin http://127.0.0.1:__FIXTURE_HTTP_PORT__/mirror.bin+ gid=0123456789abcdef+ pause=true+ dir=__FIXTURE_DOWNLOADS__+ out=partial.bin+ split=1+ max-download-limit=0+ allow-overwrite=false+ continue=true+ no-netrc=true+ auto-file-renaming=true+ max-connection-per-server=1+ pause-metadata=false+ user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36+ follow-torrent=true+ seed-time=60+ seed-ratio=1+ enable-peer-exchange=false+ bt-save-metadata=true+ bt-enable-lpd=false+ bt-force-encryption=false+ bt-load-saved-metadata=true+ follow-metalink=true+magnet:?xt=urn:btih:1111111111111111111111111111111111111111&dn=fixture-magnet+ gid=1111222233334444+ pause=true+ dir=__FIXTURE_DOWNLOADS__+ split=64+ max-download-limit=0+ allow-overwrite=false+ continue=true+ no-netrc=true+ auto-file-renaming=true+ max-connection-per-server=64+ pause-metadata=false+ user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36+ follow-torrent=true+ seed-time=60+ seed-ratio=1+ enable-peer-exchange=false+ bt-save-metadata=true+ bt-enable-lpd=false+ bt-force-encryption=false+ bt-load-saved-metadata=true+ follow-metalink=truediff --git a/tests/fixtures/legacy-v1/generated/profile/system.json b/tests/fixtures/legacy-v1/generated/profile/system.jsonnew file mode 100644index 00000000..558e4115--- /dev/null+++ b/tests/fixtures/legacy-v1/generated/profile/system.json@@ -0,0 +1,33 @@+{+ "all-proxy": "",+ "allow-overwrite": false,+ "auto-file-renaming": true,+ "bt-exclude-tracker": "",+ "bt-force-encryption": false,+ "bt-load-saved-metadata": true,+ "bt-save-metadata": true,+ "bt-tracker": "",+ "continue": true,+ "dht-file-path": "__FIXTURE_ROOT__/dht.dat",+ "dht-file-path6": "__FIXTURE_ROOT__/dht6.dat",+ "dht-listen-port": 26701,+ "dir": "__FIXTURE_DOWNLOADS__",+ "enable-dht6": true,+ "follow-metalink": true,+ "follow-torrent": true,+ "listen-port": 21301,+ "max-concurrent-downloads": 5,+ "max-connection-per-server": 64,+ "max-download-limit": 0,+ "max-overall-download-limit": 0,+ "max-overall-upload-limit": 0,+ "no-proxy": "",+ "pause-metadata": false,+ "pause": true,+ "rpc-listen-port": 16800,+ "rpc-secret": "",+ "seed-ratio": 1,+ "seed-time": 60,+ "split": 64,+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"+}diff --git a/tests/fixtures/legacy-v1/generated/profile/user.json b/tests/fixtures/legacy-v1/generated/profile/user.jsonnew file mode 100644index 00000000..2d382a01--- /dev/null+++ b/tests/fixtures/legacy-v1/generated/profile/user.json@@ -0,0 +1,38 @@+{+ "all-proxy-backup": "",+ "auto-check-update": true,+ "auto-hide-window": false,+ "auto-sync-tracker": true,+ "enable-upnp": true,+ "engine-max-connection-per-server": 64,+ "favorite-directories": [],+ "hide-app-menu": false,+ "history-directories": [],+ "keep-seeding": false,+ "keep-window-state": false,+ "last-check-update-time": 0,+ "last-sync-tracker-time": 0,+ "locale": "en-US",+ "log-level": "warn",+ "new-task-show-downloading": true,+ "no-confirm-before-delete-task": false,+ "open-at-login": false,+ "protocols": {+ "magnet": true,+ "thunder": false+ },+ "resume-all-when-app-launched": false,+ "run-mode": 1,+ "show-progress-bar": true,+ "task-notification": true,+ "theme": "auto",+ "tracker-source": [+ "https://fastly.jsdelivr.net/gh/ngosang/trackerslist/trackers_best_ip.txt",+ "https://fastly.jsdelivr.net/gh/ngosang/trackerslist/trackers_best.txt"+ ],+ "tray-theme": "auto",+ "tray-speedometer": true,+ "update-channel": "latest",+ "use-proxy": false,+ "window-state": {}+}diff --git a/tests/fixtures/legacy-v1/generated/provenance.json b/tests/fixtures/legacy-v1/generated/provenance.jsonnew file mode 100644index 00000000..d6798581--- /dev/null+++ b/tests/fixtures/legacy-v1/generated/provenance.json@@ -0,0 +1,85 @@+{+ "tag": "v1.8.19",+ "commit": "a0a1fe90f7e9f6d305ed2b512f62c8d36c2fb95a",+ "binaryPath": "extra/darwin/arm64/engine/aria2c",+ "binarySha256": "1527c4d071c16c1266880e93750e385cdd4e9d2a950d7f56cb5a21125e3bd311",+ "binaryGitObject": "f4a274061acbbc22c6eb1ab487ffdc0e80ad1b71",+ "version": "aria2 version 1.36.0",+ "sourceConfigSha256": "73f99096443c733ac31ab506ae720be02bd97deb6187ac9812b97b9341803106",+ "generation": "The tagged v1 bundled engine generated download.session, .aria2 control files and saved RPC .torrent files. Config JSON is source-derived ConfigManager defaults, not a full old Electron application run.",+ "normalization": "Only profile/download path prefixes and HTTP port in text files are replaced with fixture placeholders. Downloads are siblings of the profile, as in a normal installation. Control and torrent bytes are unmodified. Saved partial HTTP payload is gzip-compressed without altering its uncompressed bytes.",+ "safety": "Disposable profile, local range HTTP server and tracker only; DHT, PEX and LPD disabled. No real user profiles or external download endpoints.",+ "http": {+ "gid": "0123456789abcdef",+ "completedLengthAtPauseRequest": "1638400",+ "totalLength": "4194304",+ "payloadSha256": "a117210941a0b00dcb2d8577e680d84b6fa0eaf760d2afc654c953b9859d54fa",+ "payloadRecipe": "4194304 bytes; byte at zero-based index i is i % 251",+ "checkpointStatus": {+ "completedLength": "1638400",+ "totalLength": "4194304",+ "pieceLength": "1048576",+ "numPieces": "4",+ "bitfield": "80",+ "files": [+ {+ "index": "1",+ "path": "__FIXTURE_DOWNLOADS__/partial.bin",+ "length": "4194304",+ "completedLength": "1048576",+ "selected": "true"+ }+ ]+ },+ "savedPayloadBytes": 1638400,+ "savedPayloadSha256": "2615f2219789224649954ea05e34824ca109727e10a9f1710a852357732a69f1",+ "savedPayloadGzip": "downloads/partial.bin.gz"+ },+ "bt": {+ "gid": "fedcba9876543210",+ "infoHash": "45c7c651e500cc0ceaa544d6fbafcb21b8cd52f8",+ "metadataFilename": "a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent",+ "selectedFiles": [1],+ "private": true,+ "checkpointStatus": {+ "completedLength": "0",+ "totalLength": "16384",+ "pieceLength": "16384",+ "numPieces": "2",+ "bitfield": "00",+ "files": [+ {+ "index": "1",+ "path": "__FIXTURE_DOWNLOADS__/fixture-bundle/first.bin",+ "length": "16384",+ "completedLength": "0",+ "selected": "true"+ },+ {+ "index": "2",+ "path": "__FIXTURE_DOWNLOADS__/fixture-bundle/second.bin",+ "length": "16384",+ "completedLength": "0",+ "selected": "false"+ }+ ]+ }+ },+ "files": [+ {+ "path": "downloads/a16dc78c94ce589ed4666ab32285f2d188edf26f.torrent",+ "sha256": "76dc89394c6ebc46b5f863e526e037e3f3da37f0ee3e5a7069d73017bc90f10b",+ "bytes": 245+ },+ {+ "path": "downloads/fixture-bundle.aria2",+ "sha256": "9eca779c68d5814eea38b1f4b2c7d73e528a88993f8ade862ca8db90adc5b7eb",+ "bytes": 59+ },+ {+ "path": "downloads/partial.bin.aria2",+ "sha256": "40a6f7572e913ad63f0b2e867f26367e30c0cad754389963cb2f2645088dc7c7",+ "bytes": 59+ }+ ]+}diff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.tsindex 3b3371ee..21b8f1c0 100644--- a/tests/scripts/production-build.test.ts+++ b/tests/scripts/production-build.test.ts@@ -5,7 +5,8 @@ import { beforeAll, describe, expect, it } from 'vitest'const MIB = 1024 * 1024const ROOT = path.resolve(import.meta.dirname, '../..')const TARGETS = [- { name: 'main', initial: 2 * MIB, total: 5 * MIB },+ // Migration services and 26 locale catalogs bring total main JS to ~5.09 MiB.+ { name: 'main', initial: 2 * MIB, total: 5.25 * MIB },{ name: 'preload', initial: 80 * 1024, total: 80 * 1024 },{ name: 'worker', initial: 48 * 1024, total: 48 * 1024 },{ name: 'renderer', initial: 2.75 * MIB, total: 8 * MIB },