Skip to content

A full-featured download manager.

fix(bt): keep large torrent creation responsive and recover failed adds (#2538)

Dr_rOotcee5f066a08c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7a6cfce6..bf55c9d3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -149,6 +149,12 @@ jobs:
--outputFile=output/ci/reports/shard-${{ matrix.shard }}.json
env:
MOTRIX_REQUIRE_ELECTRON_PROXY_TEST: '1'
+ - name: Verify large torrent creation and SQLite recovery with the pinned Linux engine
+ if: matrix.shard == 1
+ run: |
+ node scripts/fetch-engine.mjs
+ test -x extra/linux/x64/aria2c
+ pnpm exec vitest run src/core/task/bt-direct-storage.integration.test.ts -t 'adds a large nested file list'
- name: Upload test partition report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
@@ -193,6 +199,10 @@ jobs:
torrent-browser:
name: Torrent / Chromium, Firefox, WebKit
runs-on: ubuntu-24.04
+ # The system libraries and all three browser builds match the locked Playwright release.
+ container:
+ image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
+ options: --user pwuser
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -211,7 +221,7 @@ jobs:
MOTRIX_SKIP_ELECTRON_REBUILD: '1'
MOTRIX_SKIP_ENGINE_FETCH: '1'
- name: Install torrent conformance browsers
- run: pnpm exec playwright install --with-deps chromium firefox webkit
+ run: pnpm exec playwright install chromium firefox webkit
- name: Torrent conformance on HTTP without WebCrypto
run: pnpm test:browser:torrent
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml
index c8e2d338..c15feb73 100644
--- a/.github/workflows/flatpak.yml
+++ b/.github/workflows/flatpak.yml
@@ -305,7 +305,7 @@ jobs:
-path "*/native-messaging-hosts/*" \
\) -print -quit)"
output="$("$aria2c" --version)"
- printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.24"
+ printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.25"
printf "%s\n" "$output" | grep -qF "Async DNS"
printf "%s\n" "$output" | grep -qF "BitTorrent"
printf "%s\n" "$output" | grep -qF "HTTPS"
diff --git a/README.md b/README.md
index 4cd88fa3..7c004b30 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,7 @@ The same core powers two ways to run Motrix:
## Motrix 2.4.4
+Large multi-file torrents now use compact file selections and the updated aria2 engine.
Motrix now uses MDXP 0.10.0 and includes the SQLite ledger for paired download handoffs. Browser Extension 0.1.24 continues to use the existing submission flow.
Download [v2.4.4 from GitHub Releases](https://github.com/agalwood/Motrix/releases/tag/v2.4.4)
and read the [full release notes](./docs/release-notes/2.4.4.md).
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 4d91bbb3..301c3514 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -21,6 +21,7 @@ Motrix 是一款界面简洁、功能丰富的桌面下载管理器,可处理
## Motrix 2.4.4
+修复了添加多文件大种子时下载引擎卡住的问题。
Motrix 升级到 MDXP 0.10.0,并集成用于记录配对下载交接的 SQLite 账本。浏览器扩展 0.1.24 继续通过原有接口提交下载。
从 GitHub Releases 下载 [v2.4.4](https://github.com/agalwood/Motrix/releases/tag/v2.4.4),
并阅读[完整发布说明](./docs/release-notes/2.4.4.zh-CN.md)。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index c35e4ebe..438d3903 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -102,8 +102,8 @@ must obtain permission or replace the font before distributing the build.
Desktop builds bundle an `aria2c` executable pinned by
`scripts/engine.lock.json`:
-- **Version:** 1.37.0-motrix.24
-- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.24>
+- **Version:** 1.37.0-motrix.25
+- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.25>
- **License:** GNU General Public License v2.0 or later (`GPL-2.0-or-later`)
- **Full license text:** `THIRD_PARTY_LICENSES/aria2-COPYING`
- **OpenSSL exception / notice:**
diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.md
index 9e42cd86..a9e09eaa 100644
--- a/THIRD_PARTY_NOTICES.zh-CN.md
+++ b/THIRD_PARTY_NOTICES.zh-CN.md
@@ -87,8 +87,8 @@ Safari 图标是从 macOS 27.0(26A428)自带的 Safari 27.0 中 `Safari.app/
桌面版随应用打包 `aria2c` 可执行文件,版本由 `scripts/engine.lock.json` 固定:
-- **版本:** 1.37.0-motrix.24
-- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.24>
+- **版本:** 1.37.0-motrix.25
+- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.25>
- **许可证:** GNU General Public License v2.0 or later(`GPL-2.0-or-later`)
- **完整许可证文本:** `THIRD_PARTY_LICENSES/aria2-COPYING`
- **OpenSSL 例外条款 / 声明:**
diff --git a/docs/release-notes/2.4.4.md b/docs/release-notes/2.4.4.md
index c9285031..c8c8f0ce 100644
--- a/docs/release-notes/2.4.4.md
+++ b/docs/release-notes/2.4.4.md
@@ -4,6 +4,7 @@ English | [简体中文](https://github.com/agalwood/Motrix/blob/main/docs/relea
## Changes since 2.4.3
+- Fix engine stalls when adding torrents with many files (#2536). Bundled aria2 **1.37.0-motrix.25** appends output mappings in place and Motrix sends contiguous selections as ranges. The dialog shows submission failures. An uncertain creation retains the reserved task identity for reconciliation after restart.
- Update to **MDXP 0.10.0** and use its download handoff methods and payload schemas.
- Desktop can now negotiate durable direct-download handoffs with a paired extension. Set `MOTRIX_DOWNLOAD_HANDOFF=1` before launching Desktop to accept new operations. Turning it off preserves status and recovery for operations already prepared or committed.
- The desktop task manager records the task before dispatching the engine. A reconnect can retrieve the original task ID after a lost reply. Browser Extension **0.1.24** continues to use the existing submission flow.
diff --git a/docs/release-notes/2.4.4.zh-CN.md b/docs/release-notes/2.4.4.zh-CN.md
index 05c36ca7..41586798 100644
--- a/docs/release-notes/2.4.4.zh-CN.md
+++ b/docs/release-notes/2.4.4.zh-CN.md
@@ -4,6 +4,7 @@
## 相比 2.4.3 的变化
+- 修复大量文件的 BT 种子添加时引擎卡住的问题(#2536)。捆绑的 aria2 **1.37.0-motrix.25** 按顺序追加文件映射,Motrix 将连续选择压缩成区间。添加失败会在对话框显示原因;清理结果不确定时保留原任务标识,在重启后核对,避免残留零字节排队任务。
- 升级到 **MDXP 0.10.0**,使用 SDK 提供的下载交接方法和校验规则。
- 桌面端现可与已配对的扩展协商直链下载交接。启动桌面端前设置 `MOTRIX_DOWNLOAD_HANDOFF=1` 即可接受新的交接;关闭后仍可查询和恢复先前已准备或已提交的操作。
- 桌面任务管理器先持久化任务,再交给引擎。扩展丢失回执后可以重连并找回原任务 ID。浏览器扩展 **0.1.24** 继续通过原有接口提交下载。
diff --git a/flatpak/app.motrix.native.metainfo.xml b/flatpak/app.motrix.native.metainfo.xml
index 60cb2d6d..5c499650 100644
--- a/flatpak/app.motrix.native.metainfo.xml
+++ b/flatpak/app.motrix.native.metainfo.xml
@@ -70,7 +70,7 @@
<releases>
<release version="2.4.4" date="2026-11-20">
<description>
- <p>Updates MDXP to 0.10.0 and adds a SQLite ledger for paired download handoffs. Existing browser extensions retain their download submission flow.</p>
+ <p>Fixes stalls when adding torrents with many files. Updates MDXP to 0.10.0 and adds a SQLite ledger for paired download handoffs. Existing browser extensions retain their download submission flow.</p>
</description>
</release>
<release version="2.4.3" date="2026-11-17">
diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.yml
index 8d2b5bcb..16939c7c 100644
--- a/flatpak/app.motrix.native.yml
+++ b/flatpak/app.motrix.native.yml
@@ -101,7 +101,7 @@ modules:
set -e
output="$(src/aria2c --version)"
printf '%s\n' "$output"
- printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.24'
+ printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.25'
for feature in \
'Async DNS' \
'BitTorrent' \
@@ -123,8 +123,8 @@ modules:
sources:
- type: git
url: https://github.com/motrixapp/aria2.git
- tag: v1.37.0-motrix.24
- commit: 5f6f001d1fd7c9f8abd6b3bd15ece18cc3629a3b
+ tag: v1.37.0-motrix.25
+ commit: 83add2f972b6797b0a66ca0e3e3470e4618d84e1
x-checker-data:
type: git
tag-pattern: ^v([\d.]+-motrix\.\d+)$
@@ -136,9 +136,9 @@ modules:
commands:
- |
sed -i -E \
- 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.24]/' \
+ 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.25]/' \
configure.ac
- grep -qF 'AC_INIT([aria2],[1.37.0-motrix.24]' configure.ac
+ grep -qF 'AC_INIT([aria2],[1.37.0-motrix.25]' configure.ac
- type: script
dest-filename: autogen.sh
commands:
diff --git a/scripts/engine.lock.json b/scripts/engine.lock.json
index d0097c70..1aef82c2 100644
--- a/scripts/engine.lock.json
+++ b/scripts/engine.lock.json
@@ -1,56 +1,56 @@
{
"engine": "aria2",
"repo": "motrixapp/aria2",
- "tag": "v1.37.0-motrix.24",
- "version": "1.37.0-motrix.24",
+ "tag": "v1.37.0-motrix.25",
+ "version": "1.37.0-motrix.25",
"assets": {
"darwin-arm64": {
- "file": "aria2c-1.37.0-motrix.24-darwin-arm64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.25-darwin-arm64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "ea67b6d91f275358f61fd5880db777854b519e16cb3dc5acf163e20c2a8af018",
- "binarySha256": "b5beffed4f4b56dd9bf155ca48c6fbca1cc69598917982fad9b5ebba65738047"
+ "archiveSha256": "fb9e8cfc64cb38a7cc8f9a735d065620d16f6ed24dc09a1250b6c7d9261ca630",
+ "binarySha256": "4b72f07d733109c619615f6a15d7904f456da8205fe93ae7bfaab57ae860e910"
},
"darwin-x64": {
- "file": "aria2c-1.37.0-motrix.24-darwin-x64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.25-darwin-x64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "e31f15ede41c01f817f2b197ba08f2daa544d346ca2b54529c8563e74072bd58",
- "binarySha256": "d814bd512f8ce95e2e57549fe3d654fbe62c01ba15de52084b12923d3a8b2a49"
+ "archiveSha256": "7dc2e0041088b061c8690ef32e8c560224cff76de54aae820052872dc51b12a2",
+ "binarySha256": "03164972de91c3226d24f4e322d63b3ce9fef9754331cdc1e0138f5fb195bd0d"
},
"win32-arm64": {
- "file": "aria2c-1.37.0-motrix.24-win32-arm64.zip",
+ "file": "aria2c-1.37.0-motrix.25-win32-arm64.zip",
"bin": "aria2c.exe",
- "archiveSha256": "6cac43afc1e543f50951db49ef4bce9e73614d48ba2bd0aee8dc7d59ba54f29c",
- "binarySha256": "e883993c910efb8f096155676d950d8715561f15769c895fe8bdaedc0c0d3522"
+ "archiveSha256": "b650f9c5d51617a2a2447ab7a119bc7451394779e35d8b3fd7630552b9033418",
+ "binarySha256": "385062ead137fa50d114ef581c20405b22faf6bb707dea871ee4cd8785051b9c"
},
"win32-x64": {
- "file": "aria2c-1.37.0-motrix.24-win32-x64.zip",
+ "file": "aria2c-1.37.0-motrix.25-win32-x64.zip",
"bin": "aria2c.exe",
- "archiveSha256": "3305bc54c4b03da7d702848a189c8f40c85a23cce9c432e8ecf7c03d7b2dd11e",
- "binarySha256": "8138d93127fb5885a8100480a260d8383559b598e7e3e6ceedbc1d9f5959c849"
+ "archiveSha256": "8058bb40b518990f611c27276e6a646991b9a9a44964b04e02e329461af74a36",
+ "binarySha256": "cbdd159c948e1f652a78b8904669d1dc4a140ad5484fd3710f07d7d16919c5bc"
},
"win32-ia32": {
- "file": "aria2c-1.37.0-motrix.24-win32-ia32.zip",
+ "file": "aria2c-1.37.0-motrix.25-win32-ia32.zip",
"bin": "aria2c.exe",
- "archiveSha256": "fb38accf2ce30cb5345ab1f88f3c20d085f9e6e0fc58ea2c4d882f520818cfa5",
- "binarySha256": "1fcf977f284b3dff436f558b3ade7b8eb26dd9a65cc3dd4bbd55da04b4025811"
+ "archiveSha256": "c1ede373a2cdc2ab1190e3b6034fd42446730c5738223dfafe1aad57d77186cd",
+ "binarySha256": "81f69a61a995c62d764fd473800fbaf77b7ed29d7fe1763ce92e2e6cbe1b997c"
},
"linux-x64": {
- "file": "aria2c-1.37.0-motrix.24-linux-x64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.25-linux-x64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "f947ee872bfa294d958913503dc470140c247c97cc2e83b75d196e7a6bad155e",
- "binarySha256": "333a694fdaae0fba86e678e0c6893e909a556c2916ad6c5188bed09a99b1245f"
+ "archiveSha256": "881c5184341eda22c47d81330e9f48697f9c5389e5f2599324dae881cda50719",
+ "binarySha256": "3148270e05d62abc58bea04944ed940dbc8ba2c5aef9f3936a706b9d3b627201"
},
"linux-arm64": {
- "file": "aria2c-1.37.0-motrix.24-linux-arm64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.25-linux-arm64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "adb72cbbeb263eac67953923093e16d4c9251fef3a3648aa794b615b605279bb",
- "binarySha256": "1a7ba9f87a6b68842e3d71cfe917c0fcb729b13274c3572bd7baa74af1a33c24"
+ "archiveSha256": "1f9a8187305b848ad0b0ffa90358f2712fc64bdde6eabba76955a3c45ecea1ed",
+ "binarySha256": "0b25678b2337c23d0537fc916c57ae61dcc27f87a4f4e64a870d00949a286936"
},
"linux-arm": {
- "file": "aria2c-1.37.0-motrix.24-linux-armv7l.tar.gz",
+ "file": "aria2c-1.37.0-motrix.25-linux-armv7l.tar.gz",
"bin": "aria2c",
- "archiveSha256": "06cf8c47d508bbf90ad1f6249fec7526e4aeca14921245df275925bcc84925bc",
- "binarySha256": "d14cc259fa1a398928f6e119fa6dc9d54038cc4c7d532cbe981f8cdb3b9f4068"
+ "archiveSha256": "287bc571b46e3e767d3398834dea8e8d893c7e348d3e0c567a63e9d66873a611",
+ "binarySha256": "76d2bb7c3de7831554da393e031251e0c590a22b59b54deeb77e82e8726e905f"
}
}
}
diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjs
index ec23b0b6..f1ca90cd 100644
--- a/scripts/verify-flatpak-packaging.mjs
+++ b/scripts/verify-flatpak-packaging.mjs
@@ -18,8 +18,8 @@ export const FLATPAK_BUILDER_TOOLS_COMMIT =
// tag resolves to is pinned by hand (and cross-checked against the manifest).
export const ARIA2_SOURCE = Object.freeze({
url: 'https://github.com/motrixapp/aria2.git',
- // v1.37.0-motrix.24 — current Motrix aria2 fork release
- commit: '5f6f001d1fd7c9f8abd6b3bd15ece18cc3629a3b',
+ // v1.37.0-motrix.25 — current Motrix aria2 fork release
+ commit: '83add2f972b6797b0a66ca0e3e3470e4618d84e1',
})
const PNPM_SOURCE = Object.freeze({
diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.ts
index 6188862d..c4994e7b 100644
--- a/src/core/engine/aria2/aria2-adapter.ts
+++ b/src/core/engine/aria2/aria2-adapter.ts
@@ -11,6 +11,7 @@ import {
} from '@core/proxy/aria2-proxy-routing'
import { admitDownloadSources } from '@core/task/source-admission'
import { AppError, ErrorCode } from '@shared/errors'
+import { formatFileSelection } from '@shared/lib/file-selection-ranges'
import type {
LegacyCheckpointImport,
LegacyCheckpointReconcile,
@@ -903,7 +904,7 @@ export class Aria2Adapter implements EngineAdapter {
}
}
if (params.selectedFiles?.length) {
- opts['select-file'] = params.selectedFiles.join(',')
+ opts['select-file'] = formatFileSelection(params.selectedFiles, 1)
}
if (params.outputRoot !== undefined && !path.isAbsolute(params.outputRoot))
throw new TypeError('Torrent output root must be absolute')
@@ -989,7 +990,7 @@ export class Aria2Adapter implements EngineAdapter {
Object.assign(opts, {
dir: params.saveDir,
pause: 'true',
- 'select-file': params.selectedFiles.join(','),
+ 'select-file': formatFileSelection(params.selectedFiles, 1),
'allow-overwrite': 'false',
'auto-file-renaming': 'false',
'remove-control-file': 'false',
diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.ts
index 8e98c76d..424faeca 100644
--- a/src/core/session/session-manager.test.ts
+++ b/src/core/session/session-manager.test.ts
@@ -548,6 +548,57 @@ describe('SessionManager', () => {
expect(adapter.createDownload).not.toHaveBeenCalled()
})
+ describe('interrupted torrent creation cleanup', () => {
+ const gid = '123456789abcdef0'
+ const hash = 'a'.repeat(40)
+ function seed(markedGid = gid) {
+ seedAsPair(db, {
+ motrixId: 'failed-create',
+ gid,
+ kind: TaskKind.Bt,
+ infoHash: hash,
+ status: TaskStatus.Error,
+ payload: { unconfirmedTorrentCreateGid: markedGid },
+ })
+ }
+ it('removes the durable engine result even if its GID was evicted from memory', async () => {
+ seed()
+ vi.mocked(adapter.getTaskStatus).mockResolvedValue(null)
+ await session.restore()
+ expect(adapter.removeDownloadResult).toHaveBeenCalledWith(gid)
+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()
+ expect(db.getTask('failed-create')).toBeNull()
+ })
+ it('retains the failed owner on uncertain cleanup and does not resubmit', async () => {
+ seed()
+ vi.mocked(adapter.getTaskStatus).mockResolvedValue(null)
+ vi.mocked(adapter.removeDownloadResult).mockRejectedValue(
+ new Error('engine disconnected')
+ )
+ await session.restore()
+ expect(db.getTask('failed-create')?.task.aggStatus).toBe(TaskStatus.Error)
+ expect(taskManager.getById('failed-create')?.status).toBe(
+ TaskStatus.Error
+ )
+ expect(adapter.addTorrent).not.toHaveBeenCalled()
+ })
+ it('does not remove an engine task with another content identity', async () => {
+ seed()
+ vi.mocked(adapter.getTaskStatus).mockResolvedValue(
+ createTask({ infoHash: 'b'.repeat(40) })
+ )
+ await session.restore()
+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()
+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()
+ })
+ it('preserves a replacement instance after an explicit retry', async () => {
+ seed('different-reservation')
+ await session.restore()
+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()
+ expect(db.getTask('failed-create')).toBeTruthy()
+ })
+ })
+
describe('engine session quarantine', () => {
const failed = {
engineTaskId: '2222222222222222',
diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.ts
index 6e70f6b8..0444d458 100644
--- a/src/core/session/session-manager.ts
+++ b/src/core/session/session-manager.ts
@@ -802,9 +802,56 @@ export class SessionManager {
// reconstruct the parent task by reading all its sibling instances.
// Anything left over in motrix.db after Pass 1 is an orphan.
- const persisted = this.db.getAllTasks()
const handoffGids = new Set(pendingHandoffs.values())
const isolatedHandoffs = new Map<string, TaskWithInstances>()
+ const unconfirmed = new Map<string, TaskWithInstances>()
+ const persisted: TaskWithInstances[] = []
+ for (const pair of this.db.getAllTasks()) {
+ const owner = pair.instances[0]
+ if (
+ pair.task.kind === TaskKind.Bt &&
+ pair.task.aggStatus === TaskStatus.Error &&
+ pair.instances.length === 1 &&
+ owner?.gid &&
+ owner.payload.unconfirmedTorrentCreateGid === owner.gid
+ ) {
+ try {
+ // Compensation was interrupted. Only the caller-reserved GID is ours.
+ // Never infer absence from a timeout or delete any downloaded files.
+ const live = await this.adapter.getTaskStatus(owner.gid)
+ if (live !== null && (!live.infoHash || !pair.task.infoHash)) {
+ unconfirmed.set(owner.gid, pair)
+ continue
+ }
+ if (
+ !live ||
+ live.infoHash?.toLowerCase() === pair.task.infoHash?.toLowerCase()
+ ) {
+ if (
+ live &&
+ ![
+ TaskStatus.Error,
+ TaskStatus.Removed,
+ TaskStatus.Completed,
+ ].includes(live.status)
+ )
+ await this.adapter.forceRemoveTask(owner.gid)
+ // The SQLite-backed engine can retain a GID outside its in-memory window.
+ await this.adapter.removeDownloadResult(owner.gid)
+ }
+ this.db.deleteTask(pair.task.motrixId)
+ continue
+ } catch {
+ log.warn(
+ { taskId: pair.task.motrixId },
+ 'torrent creation cleanup still unconfirmed'
+ )
+ unconfirmed.set(owner.gid, pair)
+ continue
+ }
+ }
+ persisted.push(pair)
+ }
const byMotrixId = new Map<string, TaskWithInstances>()
const instanceByGid = new Map<
string,
@@ -884,6 +931,9 @@ export class SessionManager {
const aria2GidSet = new Set(aria2Tasks.map((t) => t.gid))
this.taskManager.clear()
+ for (const pair of unconfirmed.values()) {
+ this.taskManager.add(taskRowToDownloadTask(pair.task, pair.instances))
+ }
// The outbox owns activation. Generic orphan recovery must not issue a second GET.
for (const [id, pair] of isolatedHandoffs) {
const task = taskRowToDownloadTask(pair.task, pair.instances)
@@ -908,6 +958,7 @@ export class SessionManager {
// Pass 1 — drive from aria2 rows.
for (const aria2 of aria2Tasks) {
if (handoffGids.has(aria2.gid)) continue
+ if (unconfirmed.has(aria2.gid)) continue
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;
diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.ts
index f4b5dc89..6b6af8ba 100644
--- a/src/core/task/actions/re-add-task.ts
+++ b/src/core/task/actions/re-add-task.ts
@@ -373,6 +373,8 @@ function withReservedGid(
0,
task.instances.findIndex((instance) => instance.gid === task.engineTaskId)
)
+ const primaryPayload = { ...task.instances[primaryIndex]?.payload }
+ delete primaryPayload.unconfirmedTorrentCreateGid
return {
...task,
engineTaskId,
@@ -382,6 +384,7 @@ function withReservedGid(
? {
...instance,
gid: engineTaskId,
+ payload: primaryPayload,
uploadedBytes: 0,
...(status ? { status } : {}),
updatedAt: now,
diff --git a/src/core/task/bt-direct-storage.integration.test.ts b/src/core/task/bt-direct-storage.integration.test.ts
index a859184d..247f602f 100644
--- a/src/core/task/bt-direct-storage.integration.test.ts
+++ b/src/core/task/bt-direct-storage.integration.test.ts
@@ -12,6 +12,7 @@ import {
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import path from 'node:path'
+import { DEFAULT_TORRENT_RPC_BODY_LIMIT_BYTES } from '@shared/lib/torrent-meta'
import { TaskStatus } from '@shared/types/task'
import {
type Aria2Handle,
@@ -68,6 +69,74 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
if (root) await rm(root, { recursive: true, force: true })
})
+ it('adds a large nested file list and preserves its selected paths', async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'motrix-bt-library-'))
+ const count = 26_730
+ const length = 939_000
+ const pieceLength = 2 ** 19
+ const metadata = encode({
+ info: {
+ name: 'library',
+ 'piece length': pieceLength,
+ pieces: Buffer.alloc(Math.ceil((count * length) / pieceLength) * 20),
+ files: Array.from({ length: count }, (_, i) => ({
+ length,
+ path: [
+ 'collection',
+ String(i % 31),
+ `library-resource-item-${i}.bin`,
+ ],
+ })),
+ },
+ })
+ expect(metadata.length).toBeGreaterThan(2.8 * 1024 ** 2)
+ const output = path.join(root, 'Chosen folder')
+ const plan = createBtDirectStoragePlan(
+ output,
+ await parseBtFileLayout(metadata),
+ path.join(root, 'metadata.torrent')
+ )
+ const engineOptions = {
+ baseDir: root,
+ extraArgs: [
+ `--rpc-max-request-size=${DEFAULT_TORRENT_RPC_BODY_LIMIT_BYTES}`,
+ '--enable-sqlite3-persistence=true',
+ '--force-save=true',
+ `--sqlite3-db-path=${path.join(root, 'aria2.db')}`,
+ ],
+ }
+ handle = await spawnAria2ForTest(engineOptions)
+ let wired = await connectAdapter(handle)
+ disconnect = wired.disconnect
+ const gid = await wired.adapter.addTorrent({
+ ...plan,
+ metadata,
+ pause: true,
+ selectedFiles: Array.from({ length: count }, (_, i) => i + 1),
+ })
+ const files = await wired.adapter.getTaskFiles(gid)
+ expect(files).toHaveLength(count)
+ expect(files.every((f) => f.selected)).toBe(true)
+ expect(files.at(-1)?.path).toBe(
+ path.join(
+ output,
+ 'collection',
+ String((count - 1) % 31),
+ `library-resource-item-${count - 1}.bin`
+ )
+ )
+ expect(await wired.adapter.getGlobalStats()).toBeDefined()
+ disconnect()
+ await handle.kill()
+ handle = await spawnAria2ForTest(engineOptions)
+ wired = await connectAdapter(handle)
+ disconnect = wired.disconnect
+ const restored = await wired.adapter.getTaskFiles(gid)
+ expect(restored.length).toBe(count)
+ expect(restored.at(-1)?.path).toBe(files.at(-1)?.path)
+ expect(restored.every((file) => file.selected)).toBe(true)
+ }, 30_000)
+
it.each([false, true])(
'checks and seeds final files with multiFile=%s',
async (multiFile) => {
diff --git a/src/core/task/bt-storage-layout.ts b/src/core/task/bt-storage-layout.ts
index 1db22c6f..b7adf048 100644
--- a/src/core/task/bt-storage-layout.ts
+++ b/src/core/task/bt-storage-layout.ts
@@ -123,6 +123,7 @@ export interface BtOutputFilePath {
}
export interface ParsedBtFileLayout {
+ totalBytes?: number
/** Canonical lowercase hexadecimal BitTorrent content identity. */
infoHash: string
torrentRootName: string
@@ -144,7 +145,8 @@ export class UnsafeTorrentPathError extends Error {
* mapped into the selected output directory.
*/
export async function parseBtFileLayout(
- metadata: Uint8Array
+ metadata: Uint8Array,
+ selectedFiles?: readonly number[]
): Promise<ParsedBtFileLayout> {
const parsed = await parseTorrent(metadata)
if (
@@ -159,6 +161,15 @@ export async function parseBtFileLayout(
throw new UnsafeTorrentPathError('Torrent contains no files')
}
+ const selected = selectedFiles?.length ? new Set(selectedFiles) : null
+ if (
+ selected &&
+ [...selected].some(
+ (index) =>
+ !Number.isInteger(index) || index < 0 || index >= parsedFiles.length
+ )
+ )
+ throw new Error('Torrent file selection is outside the file list')
const multiFile = parsed.multiFile === true
const files = parsedFiles.map((file, fileIndex) => {
const components = file.pathComponents.map((component) =>
@@ -208,6 +219,11 @@ export async function parseBtFileLayout(
}
return {
+ totalBytes: parsedFiles.reduce(
+ (sum, file, index) =>
+ sum + (!selected || selected.has(index) ? file.length : 0),
+ 0
+ ),
infoHash: parsed.infoHash.toLowerCase(),
torrentRootName,
multiFile,
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index 6aa6d021..cfcfe9aa 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -32,6 +32,7 @@ import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'
import { verifyBtFiles } from './bt-file-verifier'
import { parseBtFileLayout } from './bt-storage-layout'
import { handleCreateTask } from './create-task-handler'
+import { mergeEngineTask } from './merge-engine-task'
const sampleTorrentBase64 = storageTorrent([
{ name: 'a', data: 'a' },
@@ -3102,6 +3103,42 @@ describe('handleCreateTask reserved-GID ownership', () => {
expect(deps.add).not.toHaveBeenCalled()
})
+ it('retains a failed torrent with known size and the reserved identity until cleanup can be confirmed', async () => {
+ const deps = makeDeps()
+ const error = new Error('addTorrent timed out')
+ deps.addTorrent.mockRejectedValue(error)
+ deps.forceRemove.mockRejectedValue(new Error('engine offline'))
+ deps.removeDownloadResult.mockRejectedValue(new Error('engine offline'))
+ const persistTask = vi.fn(async () => {})
+ await expect(
+ handleCreateTask(
+ {
+ type: 'bt',
+ payload: { kind: 'torrent-base64', base64: sampleTorrentBase64 },
+ selectedFiles: [0, 2],
+ saveDir: '/d',
+ },
+ { ...deps, persistTask, createEngineTaskId: () => reservedGid } as Deps
+ )
+ ).rejects.toBe(error)
+ const task = lastAddedTask(deps)
+ expect(task).toMatchObject({
+ status: TaskStatus.Error,
+ totalBytes: 2,
+ sizeWhenDone: 2,
+ fileCount: 3,
+ errorMessage: error.message,
+ engineTaskId: reservedGid,
+ })
+ expect(task.instances[0]?.payload.unconfirmedTorrentCreateGid).toBe(
+ reservedGid
+ )
+ expect(persistTask).toHaveBeenLastCalledWith(task)
+ expect(mergeEngineTask(task, { ...task, status: TaskStatus.Queued })).toBe(
+ task
+ )
+ })
+
it('publishes the durable candidate when post-dispatch cleanup is uncertain', async () => {
const deps = makeDeps()
const failure = new Error('transport lost after accept')
diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.ts
index 4f269d6a..89fbe31e 100644
--- a/src/core/task/create-task-handler.ts
+++ b/src/core/task/create-task-handler.ts
@@ -31,6 +31,7 @@ import {
import type { SettingsManager } from '@core/settings/settings-manager'
import { INCOMPLETE_SUFFIX } from '@shared/constants/incomplete'
import { AppError, ErrorCode } from '@shared/errors'
+import { formatFileSelection } from '@shared/lib/file-selection-ranges'
import type {
TaskCreateRequest,
TaskCreateSuccessResult,
@@ -452,7 +453,7 @@ async function handleCreateTaskUnderAdmission(
if (req.type === 'bt' && req.payload.kind === 'torrent-base64') {
torrentBytes = req.torrentBytes ?? decodeBase64ToBytes(req.payload.base64)
try {
- parsedBtLayout = await parseBtFileLayout(torrentBytes)
+ parsedBtLayout = await parseBtFileLayout(torrentBytes, req.selectedFiles)
torrentInfoName = parsedBtLayout.torrentRootName
isPrivateFromTorrent = parsedBtLayout.isPrivate
} catch (err) {
@@ -1071,7 +1072,7 @@ async function handleCreateTaskUnderAdmission(
: {}),
saveDir: btStoragePlan?.saveDir ?? diskPath,
// CREATE-PATH +1: req indices are 0-based; aria2 select-file is
- // 1-based, and addTorrent serializes selectedFiles with a raw join.
+ // 1-based. The adapter compacts consecutive indices into ranges.
selectedFiles: req.selectedFiles.map((i) => i + 1),
outputFilePaths: btStoragePlan?.outputFilePaths,
outputRoot: btStoragePlan?.outputRoot,
@@ -1088,12 +1089,13 @@ async function handleCreateTaskUnderAdmission(
params.gid = reservedGid
// Never log `params.metadata` itself: pino would expand the whole
// torrent byte array into a multi-megabyte JSON line.
- const { metadata, ...loggableParams } = params
+ const { metadata, selectedFiles, outputFilePaths } = params
log.info(
{
method: 'addTorrent',
metadataBytes: metadata.length,
- params: loggableParams,
+ selectedFileCount: selectedFiles?.length,
+ mappedFileCount: outputFilePaths?.length,
},
'dispatching to engine'
)
@@ -1105,9 +1107,10 @@ async function handleCreateTaskUnderAdmission(
// dir=diskPath, no out) through createDownload + extraEngineOptions.
const magnetEngineOpts: Record<string, string> = {}
if (req.selectedFiles.length > 0) {
- magnetEngineOpts['select-file'] = req.selectedFiles
- .map((i) => i + 1)
- .join(',')
+ magnetEngineOpts['select-file'] = formatFileSelection(
+ req.selectedFiles,
+ 0
+ )
}
if (req.dlLimit !== undefined) {
magnetEngineOpts['max-download-limit'] = String(req.dlLimit)
@@ -1159,7 +1162,7 @@ async function handleCreateTaskUnderAdmission(
phase,
status: TaskStatus.Queued,
progress: 0,
- totalBytes: 0,
+ totalBytes: parsedBtLayout?.totalBytes ?? 0,
downloadedBytes: 0,
uploadedBytes: 0,
diskPath,
@@ -1200,6 +1203,13 @@ async function handleCreateTaskUnderAdmission(
finalName,
torrentMetaPath,
infoHash: btInfoHash,
+ ...(parsedBtLayout
+ ? {
+ totalBytes: parsedBtLayout.totalBytes ?? 0,
+ sizeWhenDone: parsedBtLayout.totalBytes ?? 0,
+ fileCount: parsedBtLayout.files.length,
+ }
+ : {}),
// For BT/Magnet, seed bt.isPrivate at creation time so SessionManager.save()
// persists is_private to db. Other bt fields are filled in by the next poll
// cycle via translateBtExtension; mergeEngineTask preserves this metadata
@@ -1352,6 +1362,20 @@ async function handleCreateTaskUnderAdmission(
// The engine outcome or durable rollback is uncertain. Promote the silent
// candidate to an ordinary owner so every live GID has the same public
// task identity and recovery can reconcile it after restart.
+ if (parsedBtLayout) {
+ task.status = TaskStatus.Error
+ primaryInstance.status = TaskStatus.Error
+ primaryInstance.payload.unconfirmedTorrentCreateGid = gid
+ task.errorMessage = cause instanceof Error ? cause.message : null
+ try {
+ await deps.persistTask?.(task)
+ } catch (error) {
+ log.warn(
+ { err: error, taskId },
+ 'could not persist uncertain torrent creation'
+ )
+ }
+ }
deps.taskManager.add(task)
announceOwnedTask()
throw cause
diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.ts
index 58a251f3..76814edc 100644
--- a/src/core/task/merge-engine-task.ts
+++ b/src/core/task/merge-engine-task.ts
@@ -22,6 +22,16 @@ export function mergeEngineTask(
now = Date.now()
): DownloadTask {
if (existing.storageOperation) return existing
+ if (
+ existing.status === TaskStatus.Error &&
+ existing.engineTaskId === engineTask.engineTaskId &&
+ existing.instances.some(
+ (instance) =>
+ instance.gid === existing.engineTaskId &&
+ instance.payload.unconfirmedTorrentCreateGid === instance.gid
+ )
+ )
+ return existing
if (
existing.engineTaskId === engineTask.engineTaskId &&
existing.status === TaskStatus.Error &&
diff --git a/src/core/task/set-selected-files.ts b/src/core/task/set-selected-files.ts
index 976e548f..6fd97c34 100644
--- a/src/core/task/set-selected-files.ts
+++ b/src/core/task/set-selected-files.ts
@@ -5,6 +5,7 @@ import { getLogger } from '@core/logger'
import type { MotrixDatabase } from '@core/session/motrix-database'
import type { TaskManager } from '@core/task/task-manager'
import { AppError, ErrorCode } from '@shared/errors'
+import { formatFileSelection } from '@shared/lib/file-selection-ranges'
import { Events } from '@shared/protocol/events'
import { setSelectedFilesPayloadSchema } from '@shared/schemas/task-file-selection'
import type { DownloadTask } from '@shared/types/task'
@@ -74,31 +75,5 @@ export function createSetSelectedFilesHandler(deps: Deps) {
}
export function formatRange(indices: number[]): string {
- if (indices.length === 0) return ''
- const sorted = [...indices].sort((a, b) => a - b).map((index) => index + 1)
- const parts: string[] = []
- let start = sorted[0] as number
- let previous = start
- const flush = () => {
- const length = previous - start + 1
- if (length >= 3) {
- parts.push(`${start}-${previous}`)
- } else {
- for (let value = start; value <= previous; value++) {
- parts.push(`${value}`)
- }
- }
- }
- for (let index = 1; index < sorted.length; index++) {
- const current = sorted[index] as number
- if (current === previous + 1) {
- previous = current
- } else {
- flush()
- start = current
- previous = current
- }
- }
- flush()
- return parts.join(',')
+ return formatFileSelection(indices, 0)
}
diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsx
index bf0b4cb2..477fa918 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -954,6 +954,38 @@ describe('AddTaskForm', () => {
}
)
+ it('keeps a torrent creation timeout visible in the open dialog', async () => {
+ const user = userEvent.setup()
+ const onSubmitSuccess = vi.fn()
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === 'command:createTask')
+ throw new Error('aria2.addTorrent timed out')
+ return {}
+ })
+ renderForm({
+ onSubmitSuccess,
+ defaultValues: {
+ tab: 'torrent',
+ source: 'file',
+ base64: 'dG9ycmVudA==',
+ saveDir: '/custom',
+ selectedFiles: [0],
+ torrentMeta: {
+ name: 'library',
+ infoHash: 'a'.repeat(40),
+ totalSize: 1,
+ files: [
+ { index: 0, path: 'library.bin', size: 1, extension: '.bin' },
+ ],
+ },
+ },
+ })
+ await user.click(screen.getByRole('button', { name: /^download$|^add$/i }))
+ expect(await screen.findByText(/aria2\.addTorrent timed out/)).toBeVisible()
+ expect(onSubmitSuccess).not.toHaveBeenCalled()
+ })
+
it('closes an external queue when the shell reports no valid next torrent', async () => {
const onCancel = vi.fn()
const user = userEvent.setup()
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index ce07f420..27d1205b 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -541,6 +541,7 @@ export function AddTaskForm({
setSubmitting(true)
try {
form.clearErrors('urls')
+ form.clearErrors('root.torrentSubmission')
const requests = formValuesToTaskCreateRequests(values)
const lines = values.tab === 'links' ? parseUrlLines(values.urls) : []
const validLines = lines.filter((line) => line.valid)
@@ -641,7 +642,17 @@ export function AddTaskForm({
: null
)
}
- if (firstFailureReason)
+ if (failed > 0 && values.tab === 'torrent' && !blockedByConflict) {
+ form.setError('root.torrentSubmission', {
+ type: 'submission',
+ message: firstFailureReason
+ ? t('task.add.createFailedWithReason', {
+ reason: firstFailureReason,
+ })
+ : t('task.add.createFailed'),
+ })
+ }
+ if (firstFailureReason && values.tab === 'links')
form.setError('urls', {
type: 'submission',
message: unconfirmed
@@ -789,6 +800,12 @@ export function AddTaskForm({
)}
style={{ minWidth: '100%' }}
>
+ {form.watch('tab') === 'torrent' &&
+ form.formState.errors.root?.torrentSubmission?.message && (
+ <p role="alert" className="mb-2 text-sm text-destructive">
+ {form.formState.errors.root.torrentSubmission.message}
+ </p>
+ )}
<RendererSubmissionNotice className="mb-3 mt-1" />
{purpose === 'redownload' ? (
<LinksTabPanel advancedDefaultOpen />
diff --git a/src/shared/lib/file-selection-ranges.ts b/src/shared/lib/file-selection-ranges.ts
new file mode 100644
index 00000000..4e3d6bc5
--- /dev/null
+++ b/src/shared/lib/file-selection-ranges.ts
@@ -0,0 +1,36 @@
+export function formatFileSelection(
+ indices: readonly number[],
+ base: 0 | 1
+): string {
+ if (indices.length === 0) return ''
+ const sorted = Array.from(new Set(indices), (index) => {
+ const value = index + (1 - base)
+ if (!Number.isSafeInteger(value) || value < 1 || value > 0x7fffffff)
+ throw new RangeError('Invalid torrent file index')
+ return value
+ }).sort((a, b) => a - b)
+ const parts: string[] = []
+ let start = sorted[0] as number
+ let previous = start
+ const flush = () => {
+ const length = previous - start + 1
+ if (length >= 3) {
+ parts.push(`${start}-${previous}`)
+ } else {
+ parts.push(String(start))
+ if (start !== previous) parts.push(String(previous))
+ }
+ }
+ for (let index = 1; index < sorted.length; index++) {
+ const current = sorted[index] as number
+ if (current === previous + 1) {
+ previous = current
+ } else {
+ flush()
+ start = current
+ previous = current
+ }
+ }
+ flush()
+ return parts.join(',')
+}
diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.ts
index ea4cfe5c..ed3c430b 100644
--- a/tests/check-third-party-notices.test.ts
+++ b/tests/check-third-party-notices.test.ts
@@ -460,9 +460,9 @@ describe('third-party graph dependency notices', () => {
expect(notice).toContain('SFNS-Regular.ttf')
expect(notice).toContain('https://developer.apple.com/fonts/')
- expect(notice).toContain('1.37.0-motrix.24')
+ expect(notice).toContain('1.37.0-motrix.25')
expect(notice).toContain(
- 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.24'
+ 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.25'
)
expect(notice).toContain('GPL-2.0-or-later')
expect(notice).toContain('THIRD_PARTY_LICENSES/aria2-COPYING')
diff --git a/tests/generate-third-party-notices.test.ts b/tests/generate-third-party-notices.test.ts
index 5d691637..12f22f75 100644
--- a/tests/generate-third-party-notices.test.ts
+++ b/tests/generate-third-party-notices.test.ts
@@ -195,7 +195,7 @@ describe('third-party notice generator', () => {
expect(bundle.packageCount).toBeGreaterThan(100)
expect(inventory).toContain('| @xyflow/react | 13.0.1 |')
expect(inventory).toContain('| react-compiler-runtime | 1.0.0 |')
- expect(inventory).toContain('| aria2 | 1.37.0-motrix.24 |')
+ expect(inventory).toContain('| aria2 | 1.37.0-motrix.25 |')
expect(inventory).toContain('| motrix.filename-template | 1.1.1 |')
expect(inventory).toContain('Apple San Francisco tray font')
expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')
@@ -306,7 +306,7 @@ describe('third-party notice generator', () => {
expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')
}
const serverInventory = server.files['THIRD_PARTY_DEPENDENCIES.md']
- expect(serverInventory).toContain('| aria2 | 1.37.0-motrix.24 |')
+ expect(serverInventory).toContain('| aria2 | 1.37.0-motrix.25 |')
expect(serverInventory).toContain('| motrix.filename-template | 1.1.1 |')
expect(serverInventory).not.toContain('| Electron |')