A full-featured download manager.
fix: unblock task creation, resume retried downloads, explain long paths (#2194)
Dr_rOot5d5a1d191efa
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.ymlindex 8e127686..acdb54ce 100644--- a/.github/workflows/flatpak.yml+++ b/.github/workflows/flatpak.yml@@ -341,7 +341,7 @@ jobs:-path "*/native-messaging-hosts/*" \\) -print -quit)"output="$("$aria2c" --version)"- printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.14"+ printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.15"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/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 4e0b99c1..2d404c19 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -100,8 +100,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.14-- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.14>+- **Version:** 1.37.0-motrix.15+- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.15>- **License:** GNU General Public License v2.0 or later (`GPL-2.0-or-later`)- **Full license text:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL exception / notice:**diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.mdindex aac8fba8..1184843e 100644--- a/THIRD_PARTY_NOTICES.zh-CN.md+++ b/THIRD_PARTY_NOTICES.zh-CN.md@@ -88,8 +88,8 @@ src/renderer/routes/settings/icons/[email protected]桌面版随应用打包 `aria2c` 可执行文件,版本由 `scripts/engine.lock.json` 固定:-- **版本:** 1.37.0-motrix.14-- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.14>+- **版本:** 1.37.0-motrix.15+- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.15>- **许可证:** GNU General Public License v2.0 or later(`GPL-2.0-or-later`)- **完整许可证文本:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL 例外条款 / 声明:**diff --git a/docs/plugin-hook-runtime-plan.md b/docs/plugin-hook-runtime-plan.mdindex 824d3ec9..38e28692 100644--- a/docs/plugin-hook-runtime-plan.md+++ b/docs/plugin-hook-runtime-plan.md@@ -247,8 +247,6 @@ Tests must fetch/read the exact archives from `scripts/builtins.lock.json`, thenassert size, SHA-256, and signature before install. They must invoke the builtbundle through PluginHost/QuickJS:-- scraper-hook performs real loopback HEAD+GET and resolves a nested relative- archive URL;- url-resolver performs the Commons page/API flow through a real loopbacktransport that preserves the authorized URL/Host and returns an independentlyaccepted `upload.wikimedia.org` URL;diff --git a/docs/plugin-hook-runtime-plan.zh-CN.md b/docs/plugin-hook-runtime-plan.zh-CN.mdindex d90e2bf0..67a59a36 100644--- a/docs/plugin-hook-runtime-plan.zh-CN.md+++ b/docs/plugin-hook-runtime-plan.zh-CN.md@@ -224,7 +224,6 @@ no-op。测试从 `scripts/builtins.lock.json` 读取精确 archive,并在安装前断言 size、SHA-256、signature。构建 bundle 必须通过 PluginHost/QuickJS 真正调用:-- scraper-hook 走真实 loopback HEAD+GET,解析嵌套相对 archive URL;- url-resolver 通过保留授权 URL/Host 的真实 loopback transport 完成 Commonspage/API 流程,再返回独立接受的 `upload.wikimedia.org` URL;- filename-template 同步读取 `ctx.metadata.getAll()`、渲染嵌套值、经历 idlediff --git a/docs/plugin-hook-runtime.md b/docs/plugin-hook-runtime.mdindex 067bdb85..460db1e4 100644--- a/docs/plugin-hook-runtime.md+++ b/docs/plugin-hook-runtime.md@@ -867,7 +867,6 @@ rewritten fixture or source copy.| Plugin | Locked release | Required real Hook acceptance ||---|---:|---|-| `motrix.scraper-hook` | 1.0.0 | `beforeCreate` performs HEAD and GET through the real HTTP capability and rewrites a nested relative archive URL. || `motrix.url-resolver` | 1.0.0 | `beforeCreate` keeps its API requests and redirects inside Commons host permission, then rewrites to the returned `upload.wikimedia.org` URL after independent output-policy validation. || `motrix.filename-template` | 1.1.1 | `beforeFinalize` reads `ctx.metadata.getAll()`, renders nested metadata, and commits an automatic no-clobber rename. |diff --git a/docs/plugin-hook-runtime.zh-CN.md b/docs/plugin-hook-runtime.zh-CN.mdindex 7d3dd02a..b84acab4 100644--- a/docs/plugin-hook-runtime.zh-CN.md+++ b/docs/plugin-hook-runtime.zh-CN.md@@ -767,7 +767,6 @@ DTO、调度、提交、恢复和投递策略必须完全一致。| 插件 | 锁定发布版 | 必须通过的真实 Hook 验收 ||---|---:|---|-| `motrix.scraper-hook` | 1.0.0 | `beforeCreate` 通过真实 HTTP capability 执行 HEAD 与 GET,并把嵌套的相对 archive URL 改写为目标 URL。 || `motrix.url-resolver` | 1.0.0 | `beforeCreate` 的 API 请求与 redirect 始终位于 Commons host permission 内,再把独立 output policy 验证后的 `upload.wikimedia.org` URL 写回。 || `motrix.filename-template` | 1.1.1 | `beforeFinalize` 读取 `ctx.metadata.getAll()`,渲染嵌套 metadata,并提交自动 no-clobber rename。 |diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.ymlindex c44160cf..3b98a7d2 100644--- a/flatpak/app.motrix.native.yml+++ b/flatpak/app.motrix.native.yml@@ -101,7 +101,7 @@ modules:set -eoutput="$(src/aria2c --version)"printf '%s\n' "$output"- printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.14'+ printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.15'for feature in \'Async DNS' \'BitTorrent' \@@ -123,8 +123,8 @@ modules:sources:- type: giturl: https://github.com/motrixapp/aria2.git- tag: v1.37.0-motrix.14- commit: fb5aa179a3fa6649c59fcfe90b69c44165e32be3+ tag: v1.37.0-motrix.15+ commit: 8a54d2c76373f7e33607148e67e3ba3770748749x-checker-data:type: gittag-pattern: ^v([\d.]+-motrix\.\d+)$@@ -136,9 +136,9 @@ modules:commands:- |sed -i -E \- 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.14]/' \+ 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.15]/' \configure.ac- grep -qF 'AC_INIT([aria2],[1.37.0-motrix.14]' configure.ac+ grep -qF 'AC_INIT([aria2],[1.37.0-motrix.15]' configure.ac- type: scriptdest-filename: autogen.shcommands:diff --git a/scripts/builtins.lock.json b/scripts/builtins.lock.jsonindex 996fa570..adda3bcb 100644--- a/scripts/builtins.lock.json+++ b/scripts/builtins.lock.json@@ -8,13 +8,6 @@"sha256": "3b88e4b79ae3a019f1efec08ccd69bf6f83088887f7c13205f1d58ea22bfc4da","size": 5673},- "motrix.scraper-hook": {- "tag": "[email protected]",- "version": "1.0.0",- "file": "motrix.scraper-hook-1.0.0.moext",- "sha256": "2b6d1771fa0ccbd21e3a3da1284a589bd8f93d3a2ad6c6813fba6f21d2cfcb25",- "size": 2218- },"motrix.url-resolver": {"tag": "[email protected]","version": "1.0.0",diff --git a/scripts/engine.lock.json b/scripts/engine.lock.jsonindex 9489a7ec..abf8398d 100644--- a/scripts/engine.lock.json+++ b/scripts/engine.lock.json@@ -1,50 +1,50 @@{"engine": "aria2","repo": "motrixapp/aria2",- "tag": "v1.37.0-motrix.14",- "version": "1.37.0-motrix.14",+ "tag": "v1.37.0-motrix.15",+ "version": "1.37.0-motrix.15","assets": {"darwin-arm64": {- "file": "aria2c-1.37.0-motrix.14-darwin-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.15-darwin-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "30dccd659766c92531d810b742ceaf0be978cfe83ff631c0c3c701e26c888832",- "binarySha256": "bf71d3fd383ca115348e4cd0d093dac48198282c30590349fef23f832a49b4fc"+ "archiveSha256": "71529c8e4a9b1e92e9d720230e05313333d3c90bb0dd50ee1ddbd8fc92dfe787",+ "binarySha256": "7bdf7e0d261744356f995cf3e642bc71da18eebcdf57c8b1b5f2519ca3b7264d"},"darwin-x64": {- "file": "aria2c-1.37.0-motrix.14-darwin-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.15-darwin-x64.tar.gz","bin": "aria2c",- "archiveSha256": "56dc4d4dbc29c2a7400f5745eb902d2a0a4ded9139497ca65da4dd31565da408",- "binarySha256": "5c41e40931d2dca1fa13d06cb4ba38b82369b3c5accf2abf4ca506c22124f96d"+ "archiveSha256": "15cbedc4ac739ff0678166a3926d8cb6fd40a178e49a6eb2db04a44f585fbf25",+ "binarySha256": "22c26d5afdc7522158ade68207826a918c1ed55a79bfa23dfd8da5de87663c2f"},"win32-x64": {- "file": "aria2c-1.37.0-motrix.14-win32-x64.zip",+ "file": "aria2c-1.37.0-motrix.15-win32-x64.zip","bin": "aria2c.exe",- "archiveSha256": "36334f45437c3e3aa6733825b0d93976b4121f91aee83b2ecfe4bc210b8398df",- "binarySha256": "82e367164513a86eb5c52411fb77ad6cb2f6ca9766e6ddb8bd9526010f7fdf73"+ "archiveSha256": "e056fa31ce308b08b5071e3633cb81bba0fa6d5cae00186142f185ee41823ccb",+ "binarySha256": "5c565413d5b637aef7d0e427b1e048e29dd94657e66c7333c21dd8f47a03ba73"},"win32-ia32": {- "file": "aria2c-1.37.0-motrix.14-win32-ia32.zip",+ "file": "aria2c-1.37.0-motrix.15-win32-ia32.zip","bin": "aria2c.exe",- "archiveSha256": "bb3b7ee1e24c3c07e29ca674e7dee2cce03009f662d2815d1272ead827e0737b",- "binarySha256": "51ad76d9085380098b280e33bd1f7bf320e35d4704b15c301aa63a9835b7c3b2"+ "archiveSha256": "d1021de0120a81c1b484c7dc34e1e2672a83a0497656bbd880b101f16761635e",+ "binarySha256": "c8e1478579421bc573c0cbb23f79d58be5ba5e15f37c930973595ff8493b190c"},"linux-x64": {- "file": "aria2c-1.37.0-motrix.14-linux-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.15-linux-x64.tar.gz","bin": "aria2c",- "archiveSha256": "e4f5dd755de29e5789185afc415ca9190d82a3571f1cacc3072f0f9b840d33dc",- "binarySha256": "f694ef272993b66267ffd73e809f32cb14ad318ef5c64d3b835423db173c51e1"+ "archiveSha256": "8a4ea58485404d967a8e2fa30b58714b3e9200850833031f5a5afa0d32aa95c6",+ "binarySha256": "acd157ead3aef6d3e4bdd30fc4cbbc09cc00bcc27cd97682d797fb7d56de1ca4"},"linux-arm64": {- "file": "aria2c-1.37.0-motrix.14-linux-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.15-linux-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "df24bc9d155d5c09dd2fbb116c7e086e7cb846dae795f30f8a4671e626ad05ad",- "binarySha256": "686656d927bab1c96d21a320bfb26fc0427cb5bc46cfcc3b7e0cf787be071427"+ "archiveSha256": "1456b70189009a0853e1b3606611619ef2fb446134537ca0b7708935218d8e03",+ "binarySha256": "30c9fe4e9afdf21a625f5bb305246898599336028c0d965e75f36400b842005a"},"linux-arm": {- "file": "aria2c-1.37.0-motrix.14-linux-armv7l.tar.gz",+ "file": "aria2c-1.37.0-motrix.15-linux-armv7l.tar.gz","bin": "aria2c",- "archiveSha256": "b5a7c1b8c5f67244f3412504bb3475d3b36a6dda72b848169f0aa0ede2e1f627",- "binarySha256": "3e50f8c925d425cd0955fcc3fe2e92813e1f1b8f7e308e015bc868411a989ec6"+ "archiveSha256": "46ca68ab35be9a19169125a1aae01562f0c990e8de90e0a240f70a7a31647a66",+ "binarySha256": "1b20ca8abcbe4e55554794d2b88d3e034cc54595189ee3a06291fb12e877ab1b"}}}diff --git a/scripts/fetch-builtins.mjs b/scripts/fetch-builtins.mjsindex 101b132e..aec3c958 100644--- a/scripts/fetch-builtins.mjs+++ b/scripts/fetch-builtins.mjs@@ -476,6 +476,10 @@ if (invokedDirectly) {)process.exit(EXIT_FAILURE)}+ // Prune here too: retiring a builtin from the lockfile must take+ // effect in offline/CI packaging runs as well, or the retired plugin+ // keeps shipping from a stale seed dir.+ await pruneOutDir(lockIds)console.log('[fetch-builtins] skipped (seeds present)')process.exit(EXIT_OK)}diff --git a/scripts/third-party-notices.config.json b/scripts/third-party-notices.config.jsonindex 2b55418d..6c62cb55 100644--- a/scripts/third-party-notices.config.json+++ b/scripts/third-party-notices.config.json@@ -25,7 +25,7 @@"packageOverrides": {"@resvg/[email protected]": {"fallbackLicenseFiles": ["THIRD_PARTY_LICENSES/MPL-2.0"],- "attribution": "Copyright (c) 2021-present, yisibl (一丝)"+ "attribution": "Copyright (c) 2021-present, yisibl (\u4e00\u4e1d)"},"[email protected]": {"fallbackLicenseFiles": ["THIRD_PARTY_LICENSES/rust-common-LICENSE-MIT"],@@ -114,18 +114,6 @@"licenseDeclared": "NOASSERTION","noticeMarkers": ["motrix.filename-template"]},- {- "id": "builtin-scraper-hook",- "name": "motrix.scraper-hook",- "scope": "bundled first-party extension; standalone license pending upstream",- "distributions": ["desktop", "server"],- "metadataFile": "scripts/builtins.lock.json",- "metadataPath": ["plugins", "motrix.scraper-hook"],- "versionField": "version",- "sourceTemplate": "https://github.com/{repo}/tree/{tag}",- "licenseDeclared": "NOASSERTION",- "noticeMarkers": ["motrix.scraper-hook"]- },{"id": "builtin-url-resolver","name": "motrix.url-resolver",diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjsindex 9a50ffc3..70fab12a 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.14 — current Motrix aria2 fork release- commit: 'fb5aa179a3fa6649c59fcfe90b69c44165e32be3',+ // v1.37.0-motrix.15 — current Motrix aria2 fork release+ commit: '8a54d2c76373f7e33607148e67e3ba3770748749',})const PNPM_SOURCE = Object.freeze({@@ -53,8 +53,6 @@ const COMPANION_PAIR_FRAME_HEX =const BUILTIN_SIGNATURE_DIGESTS = Object.freeze({'motrix.filename-template-1.1.1.moext.sig':'5b6bfcc74e0d923ed37c4f2340bfdc4cdac30f64191a15ce5c46ddc86590bc6d',- 'motrix.scraper-hook-1.0.0.moext.sig':- '7403d5ec5f61819370bcf153fe955e0736109b844c1eb53f959e6ebd0790be78','motrix.url-resolver-1.0.0.moext.sig':'716af87eb2adbb4796ed6ac600c9b14840cb8354eb9ccebfe6122615ba88c17c',})diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 5c742f51..5eb27f73 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -44,6 +44,7 @@ function createMockRpc(): Aria2RpcClient {onDownloadError: vi.fn(),getOption: vi.fn(),getDownloadResultCount: vi.fn(),+ getCheckpointStatus: vi.fn(),searchDownloadResult: vi.fn(),exportSession: vi.fn(),requeueDownloadResult: vi.fn(),@@ -319,6 +320,52 @@ describe('Aria2Adapter', () => {})})+ describe('getCheckpointStatus', () => {+ // The engine answers from the checkpoint store it actually reads, so+ // recovery never has to guess between <file>.aria2 and aria2.db (#2187).+ it('maps the engine answer onto present / absent', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)+ vi.mocked(rpc.getCheckpointStatus).mockResolvedValueOnce({+ exists: 'true',+ store: 'sqlite3',+ })+ await expect(adapter.getCheckpointStatus('/d/a.motrix')).resolves.toBe(+ 'present'+ )+ expect(rpc.getCheckpointStatus).toHaveBeenCalledWith('/d/a.motrix')+ vi.mocked(rpc.getCheckpointStatus).mockResolvedValueOnce({+ exists: 'false',+ store: 'control-file',+ })+ await expect(adapter.getCheckpointStatus('/d/b.motrix')).resolves.toBe(+ 'absent'+ )+ })++ it('reports null when the engine predates the method', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)+ vi.mocked(rpc.getCheckpointStatus).mockRejectedValueOnce(+ new Error('No such method: aria2.getCheckpointStatus')+ )+ await expect(adapter.getCheckpointStatus('/d/a.motrix')).resolves.toBe(+ null+ )+ })++ it('propagates any other engine failure', async () => {+ const rpc = createMockRpc()+ const adapter = new Aria2Adapter(rpc)+ vi.mocked(rpc.getCheckpointStatus).mockRejectedValueOnce(+ new Error('Connection lost')+ )+ await expect(adapter.getCheckpointStatus('/d/a.motrix')).rejects.toThrow(+ 'Connection lost'+ )+ })+ })+describe('getCapabilities / getFeatureReport', () => {it('returns conservative defaults before connect()', () => {const rpc = createMockRpc()diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex bc739b63..e9a64fe1 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -831,6 +831,29 @@ export class Aria2Adapter implements EngineAdapter {)}+ async getCheckpointStatus(+ outputPath: string+ ): Promise<'present' | 'absent' | null> {+ try {+ const status = await this.rpc.getCheckpointStatus(outputPath)+ return status.exists === 'true' ? 'present' : 'absent'+ } catch (error) {+ // Official aria2 and fork builds before 1.37.0-motrix.15 lack the+ // method. The caller's control-file probe then matches what they can+ // resume: official aria2 only writes control files, and older fork+ // sqlite checkpoints are keyed by gid, which a retry never matches.+ if (+ error instanceof Error &&+ /(?:no such method|method not found).*getCheckpointStatus/i.test(+ error.message+ )+ ) {+ return null+ }+ throw error+ }+ }+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-rpc-client.ts b/src/core/engine/aria2/aria2-rpc-client.tsindex 06654b88..3b6c5ee7 100644--- a/src/core/engine/aria2/aria2-rpc-client.ts+++ b/src/core/engine/aria2/aria2-rpc-client.ts@@ -3,6 +3,7 @@ import type { DownloadCookie } from '../engine-adapter'import { Aria2PauseState } from './aria2-pause-state'import type { JsonRpcProtocol } from './json-rpc-protocol'import type {+ Aria2CheckpointStatus,Aria2HistoryCount,Aria2HistoryFilter,Aria2MethodCall,@@ -386,6 +387,12 @@ export class Aria2RpcClient {return this.call<Aria2RawStatus[]>('aria2.searchDownloadResult', params)}+ getCheckpointStatus(outputPath: string): Promise<Aria2CheckpointStatus> {+ return this.call<Aria2CheckpointStatus>('aria2.getCheckpointStatus', [+ outputPath,+ ])+ }+exportSession(filePath: string): Promise<'OK'> {return this.call<'OK'>('aria2.exportSession', [filePath])}diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.test.tsindex 4160b11e..9b7177c2 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') {+async function setup(state = 'paused', schemaVersion: 2 | 3 = 2) {const root = await mkdtemp(path.join(tmpdir(), 'motrix-identity-'))folders.push(root)const file = path.join(root, 'aria2.db')@@ -36,11 +36,17 @@ async function setup(state = 'paused') {const db = new Database(file)db.pragma('foreign_keys = ON')db.pragma('journal_mode = WAL')- db.pragma('user_version = 2')+ db.pragma(`user_version = ${schemaVersion}`)+ // 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+ ? '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(`CREATE TABLE task(gid TEXT PRIMARY KEY, state TEXT, serialized TEXT,digest BLOB, bt_local_path TEXT, updated_at INTEGER, queue_position INTEGER);- CREATE TABLE task_progress(gid TEXT PRIMARY KEY REFERENCES task(gid) ON DELETE CASCADE, bitfield BLOB);+ ${progressTable}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);`)@@ -60,7 +66,7 @@ async function setup(state = 'paused') {Buffer.from('other-digest'),2)- db.prepare('INSERT INTO task_progress VALUES (?, ?)').run(+ db.prepare('INSERT INTO task_progress (gid, bitfield) VALUES (?, ?)').run(CHILD,Buffer.from([0xaa, 0xc0]))@@ -288,10 +294,29 @@ 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('leaves an unfamiliar future schema unchanged', async () => {const h = await setup()try {- h.db.pragma('user_version = 3')+ h.db.pragma('user_version = 4')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 9ce362d0..5d225c1f 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 v1/v2 fork's metadata-ancestor GID serialization before spawn.+ * Repair the fork's metadata-ancestor GID serialization (schema v1–v3) 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,7 +78,8 @@ 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) return null+ if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3)+ return nullconst dataVersion = db.pragma('data_version', { simple: true })const rows = z.array(rowSchema)@@ -212,7 +213,17 @@ export async function recoverAria2SessionIdentity(throw failure(row.gid, 'task changed during recovery')}const remove = db.prepare('DELETE FROM task WHERE gid = ?')- for (const gid of retiredMetadataGids) remove.run(gid)+ // Schema v3 no longer cascades 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+ ? db.prepare('DELETE FROM task_progress WHERE gid = ?')+ : null+ for (const gid of retiredMetadataGids) {+ remove.run(gid)+ removeProgress?.run(gid)+ }}).immediate()return {backupPath,diff --git a/src/core/engine/aria2/translate.test.ts b/src/core/engine/aria2/translate.test.tsindex 463d16b0..cfd49740 100644--- a/src/core/engine/aria2/translate.test.ts+++ b/src/core/engine/aria2/translate.test.ts@@ -3,6 +3,7 @@ import { TaskStatus, TaskType, TransitionPhase } from '@shared/types/task'import { describe, expect, it } from 'vitest'import {bitfieldProgress,+ classifyTerminalError,decodeAria2PeerId,derivePathsFromRaw,translateErrorCode,@@ -365,3 +366,63 @@ describe('translatePeer', () => {expect(peer.peerChoking).toBe(false)})})++describe('classifyTerminalError', () => {+ const OVER_LIMIT = String.raw`F:\Game\Dead Cells (2018).motrix\Dead Cells (2018)\Bonuses\Dead Cells - Demake Soundtrack\FLAC Yoann Laulan - Dead Cells - Soundtrack Part 2 (Demake) FLAC\Yoann Laulan - Dead Cells - Soundtrack Part 2 (Demake) - 21 The Time Keeper Formerly Known As Assassin.flac`++ it('re-reads a file-open failure over MAX_PATH as a path-length error', () => {+ expect(+ classifyTerminalError(+ '16',+ `Failed to open the file ${OVER_LIMIT}, cause: The system cannot find the path specified.`,+ 'win32'+ )+ ).toEqual({+ errorCode: DownloadErrorCode.PathTooLong,+ errorDetailKey: 'task.error.detail.pathTooLong',+ errorDetailParams: { length: '262', limit: '259', path: OVER_LIMIT },+ })+ })++ it('leaves a genuine write failure alone when the path fits', () => {+ expect(+ classifyTerminalError(+ '16',+ 'Failed to open the file C:/d/a.bin, cause: Access is denied.',+ 'win32'+ )+ ).toEqual({+ errorCode: DownloadErrorCode.FileWriteError,+ errorDetailKey: null,+ errorDetailParams: null,+ })+ })++ it('does not reclassify on platforms without the MAX_PATH cap', () => {+ expect(+ classifyTerminalError(+ '16',+ `Failed to open the file ${OVER_LIMIT}, cause: nope`,+ 'darwin'+ ).errorCode+ ).toBe(DownloadErrorCode.FileWriteError)+ })++ it('does not reclassify an unrelated error code that mentions a long path', () => {+ expect(+ classifyTerminalError(+ '6',+ `Failed to open the file ${OVER_LIMIT}, cause: nope`,+ 'win32'+ ).errorCode+ ).toBe(DownloadErrorCode.NetworkError)+ })++ it('passes through when there is no error', () => {+ expect(classifyTerminalError('0', null, 'win32')).toEqual({+ errorCode: null,+ errorDetailKey: null,+ errorDetailParams: null,+ })+ })+})diff --git a/src/core/engine/aria2/translate.ts b/src/core/engine/aria2/translate.tsindex 8d8b6194..1c2a0fab 100644--- a/src/core/engine/aria2/translate.ts+++ b/src/core/engine/aria2/translate.ts@@ -3,6 +3,7 @@ import {applyTerminalTransition,terminalFieldsFromRow,} from '@core/task/apply-terminal-transition'+import { exceedsPathLimit, extractAria2FilePath } from '@core/task/path-length'import { toFinalPath } from '@core/task/paths'import { DownloadErrorCode } from '@shared/errors'import type { TaskPeer } from '@shared/types/peer'@@ -121,6 +122,54 @@ export function translateErrorCode(}}+/** aria2 exit codes whose cause can be an over-long destination path. */+const FILE_ACCESS_ERROR_CODES = new Set([13, 14, 15, 16, 17, 18])++export interface TerminalErrorClassification {+ errorCode: DownloadErrorCode | null+ errorDetailKey: string | null+ errorDetailParams: Record<string, string> | null+}++/**+ * Refine `translateErrorCode` with what the engine's message reveals.+ *+ * aria2 reports an over-long Windows destination as a plain file-open failure+ * carrying the OS text "The system cannot find the path specified"+ * (ERROR_PATH_NOT_FOUND), which the code-only mapping flattens into+ * `FileWriteError` — surfaced to the user as "check folder permissions and+ * disk space", advice that cannot resolve it. Measuring the path aria2 names+ * separates the two causes. See agalwood/Motrix#2183.+ */+export function classifyTerminalError(+ rawErrorCode: string | null | undefined,+ rawErrorMessage: string | null | undefined,+ platform: NodeJS.Platform | string = process.platform+): TerminalErrorClassification {+ const errorCode = translateErrorCode(rawErrorCode)+ const none = { errorDetailKey: null, errorDetailParams: null }+ if (errorCode === null) return { errorCode, ...none }++ const numeric = Number.parseInt(String(rawErrorCode).trim(), 10)+ if (!FILE_ACCESS_ERROR_CODES.has(numeric)) return { errorCode, ...none }++ const filePath = extractAria2FilePath(rawErrorMessage)+ if (filePath === null) return { errorCode, ...none }++ const overrun = exceedsPathLimit(filePath, platform)+ if (overrun === null) return { errorCode, ...none }++ return {+ errorCode: DownloadErrorCode.PathTooLong,+ errorDetailKey: 'task.error.detail.pathTooLong',+ errorDetailParams: {+ length: String(overrun.length),+ limit: String(overrun.limit),+ path: filePath,+ },+ }+}+// ─── Task Type Detection ──────────────────────────────────────export function detectTaskType(raw: Aria2RawStatus): TaskType {@@ -337,7 +386,7 @@ export function translateRawToTask(raw: Aria2RawStatus): DownloadTask {{finishedAt: raw.status === 'complete' ? now : null,errorMessage: raw.errorMessage ?? null,- errorCode: translateErrorCode(raw.errorCode),+ ...classifyTerminalError(raw.errorCode, raw.errorMessage),},now)diff --git a/src/core/engine/aria2/types.ts b/src/core/engine/aria2/types.tsindex 0623e56d..58460e45 100644--- a/src/core/engine/aria2/types.ts+++ b/src/core/engine/aria2/types.ts@@ -129,6 +129,12 @@ export type Aria2RequeueStrategy =| 'serialized-text'| 'synthesized-magnet'+/** `aria2.getCheckpointStatus` reply (aria2_motrix, checkpoint schema v3). */+export interface Aria2CheckpointStatus {+ exists: 'true' | 'false'+ store: 'sqlite3' | 'control-file'+}+export interface Aria2RequeueResult {gid: stringstrategy: Aria2RequeueStrategydiff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex 792805d1..af8bf0a8 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -255,6 +255,14 @@ export interface EngineAdapter {*/removeDownloadResult(engineTaskId: string): Promise<void>+ /**+ * Whether the engine holds a resumable checkpoint for the download written+ * to `outputPath`, answered from the store it actually reads (a control+ * file, or aria2.db under sqlite3 persistence). Null when the engine+ * cannot answer; callers then fall back to the `.aria2` control file.+ */+ getCheckpointStatus?(outputPath: string): Promise<'present' | 'absent' | null>+/*** Batch variant of {@link removeDownloadResult}, executed in bounded* chunks. Entries are attempted in array order and each outcome isdiff --git a/src/core/plugin/hooks/hook-orchestrator.test.ts b/src/core/plugin/hooks/hook-orchestrator.test.tsindex 1af67598..9620bb9c 100644--- a/src/core/plugin/hooks/hook-orchestrator.test.ts+++ b/src/core/plugin/hooks/hook-orchestrator.test.ts@@ -989,6 +989,37 @@ describe('HookOrchestrator', () => {expect(breaker.failure).not.toHaveBeenCalled()})+ it('defaults to a real breaker when the caller supplies none', async () => {+ // Regression: createPluginRuntime shipped without a breaker, so a+ // persistently failing plugin was never skipped and never disabled.+ // A missing breaker must fail safe, not fail open.+ const { host, extras } = makeMockHost([+ {+ id: 'plugin-flaky',+ role: 'enrich',+ hooks: ['beforeCreate'],+ handler: () => {+ throw new Error('boom')+ },+ },+ ])+ const orch = new HookOrchestrator({+ host,+ hookTimeoutMs: TIMEOUTS,+ ...ORCH_OPTS_BASE,+ })+ // Default threshold is 3 consecutive failures.+ for (const taskId of ['task-1', 'task-2', 'task-3']) {+ await orch.runBeforeCreateHttp(makeBeforeCreateDto(), taskId)+ }+ expect(extras.invocations).toHaveLength(3)+ expect(host.disable).toHaveBeenCalledWith('plugin-flaky', 'circuit_open')++ // Breaker is open now: the fourth chain skips the plugin entirely.+ await orch.runBeforeCreateHttp(makeBeforeCreateDto(), 'task-4')+ expect(extras.invocations).toHaveLength(3)+ })+it('calls host.disable with reason "circuit_open" when breaker trips', async () => {const { host } = makeMockHost([{diff --git a/src/core/plugin/hooks/hook-orchestrator.ts b/src/core/plugin/hooks/hook-orchestrator.tsindex c0265e35..7292f235 100644--- a/src/core/plugin/hooks/hook-orchestrator.ts+++ b/src/core/plugin/hooks/hook-orchestrator.ts@@ -31,6 +31,7 @@ import type {OnErrorContextDTO,} from '@shared/types/plugin-hooks'import type { CapabilityHost } from '../capabilities/interface'+import { CircuitBreaker as RealCircuitBreaker } from '../circuit/circuit-breaker'import type { ActivationDispatcher } from '../host/activation-dispatcher'import type { ActivePluginInfo, PluginHost } from '../host/plugin-host'import { newHookAbort } from './abort'@@ -76,7 +77,13 @@ export interface OrchestratorOptions {ffmpegStagingQuotaBytes?: number/** Optional NDJSON audit log; T15 wires the real instance. */auditLog?: HookAuditLog- /** Optional circuit breaker; T16 wires the real instance. */+ /**+ * Circuit breaker for per-(plugin, hook) failure accounting. Optional only+ * so callers can substitute a stub: when omitted the orchestrator builds a+ * real one. It must never be absent in effect — a `pre-resolve` plugin that+ * fails every chain would otherwise block task creation forever, with no+ * skip and no auto-disable (the #2189 failure mode).+ */breaker?: CircuitBreaker}@@ -141,7 +148,11 @@ function roleFromManifest(// ---------------------------------------------------------------------------export class HookOrchestrator {- constructor(private readonly opts: OrchestratorOptions) {}+ private readonly breaker: CircuitBreaker++ constructor(private readonly opts: OrchestratorOptions) {+ this.breaker = opts.breaker ?? new RealCircuitBreaker()+ }// -------------------------------------------------------------------------// beforeCreate (HTTP)@@ -178,7 +189,7 @@ export class HookOrchestrator {let working = cloneBeforeCreate(initial)for (const entry of chain) {- if (this.opts.breaker?.isOpen(entry.id, 'beforeCreate')) {+ if (this.breaker.isOpen(entry.id, 'beforeCreate')) {// Breaker open — skip this plugin entirely. Treated like fail-open:// resolve/post-process being skipped is a host policy decision, not a// plugin failure, so the chain continues regardless of band.@@ -217,10 +228,10 @@ export class HookOrchestrator {'http','https',]).map((source) => source.sourceUrl)- this.opts.breaker?.success(entry.id, 'beforeCreate')+ this.breaker.success(entry.id, 'beforeCreate')} catch (e) {if (e instanceof DownloadSourceError) throw e- this.opts.breaker?.failure(entry.id, 'beforeCreate')+ this.breaker.failure(entry.id, 'beforeCreate')await this.maybeDisable(entry.id, 'beforeCreate')const message = (e as Error).messageawait this.opts.auditLog?.log({@@ -311,7 +322,7 @@ export class HookOrchestrator {let working = cloneBeforeFinalize(initial)for (const entry of chain) {- if (this.opts.breaker?.isOpen(entry.id, 'beforeFinalize')) {+ if (this.breaker.isOpen(entry.id, 'beforeFinalize')) {await this.opts.auditLog?.log({type: 'chain.skip',hook: 'beforeFinalize',@@ -374,9 +385,9 @@ export class HookOrchestrator {targetFilePath: nextTarget,}}- this.opts.breaker?.success(entry.id, 'beforeFinalize')+ this.breaker.success(entry.id, 'beforeFinalize')} catch (e) {- this.opts.breaker?.failure(entry.id, 'beforeFinalize')+ this.breaker.failure(entry.id, 'beforeFinalize')await this.maybeDisable(entry.id, 'beforeFinalize')const message = (e as Error).messageawait this.opts.auditLog?.log({@@ -460,7 +471,7 @@ export class HookOrchestrator {const timeout = this.opts.hookTimeoutMs.parallelconst work = chain.map(async (entry) => {- if (this.opts.breaker?.isOpen(entry.id, hook)) {+ if (this.breaker.isOpen(entry.id, hook)) {await this.opts.auditLog?.log({type: 'chain.skip',hook,@@ -490,9 +501,9 @@ export class HookOrchestrator {taskId,},})- this.opts.breaker?.success(entry.id, hook)+ this.breaker.success(entry.id, hook)} catch (e) {- this.opts.breaker?.failure(entry.id, hook)+ this.breaker.failure(entry.id, hook)await this.maybeDisable(entry.id, hook)await this.opts.auditLog?.log({type: 'chain.plugin_error',@@ -608,7 +619,7 @@ export class HookOrchestrator {* up and break the running hook chain's fail-mode handling.*/private async maybeDisable(pluginId: string, hook: AnyHook): Promise<void> {- if (!this.opts.breaker?.isOpen(pluginId, hook)) return+ if (!this.breaker.isOpen(pluginId, hook)) returntry {await this.opts.host.disable(pluginId, 'circuit_open')} catch {diff --git a/src/core/plugin/host/capability-bridge.ts b/src/core/plugin/host/capability-bridge.tsindex 4c41396a..0993377f 100644--- a/src/core/plugin/host/capability-bridge.ts+++ b/src/core/plugin/host/capability-bridge.ts@@ -81,6 +81,46 @@ export interface CapabilityBridgeOptions {* method-level check is left to the capability host (spec §I30 is* capability-scope, not method-scope, in Phase 1A).*/+/**+ * How a hook invocation was cancelled. `HookAbortBudget` (see+ * `@core/plugin/hooks/abort`) aborts its signal with the literal reason+ * `'timeout'` when the chain deadline elapses; anything else — policy change,+ * admission close, caller cancellation — is a plain abort.+ */+type HookAbortKind = 'timeout' | 'aborted'++/**+ * Reason strings posted into the plugin VM's `onabort` event. Deliberately a+ * closed set: an arbitrary host-side `signal.reason` must never cross the+ * sandbox boundary.+ */+const HOOK_ABORT_REASON: Record<HookAbortKind, string> = {+ timeout: 'plugin hook timed out',+ aborted: 'plugin hook aborted',+}++/**+ * Margin between the caller's deadline and this bridge's defensive timer, so+ * the two never race for the same tick. See `callHook`.+ */+const HOOK_DEFENSIVE_TIMEOUT_GRACE_MS = 500++function abortKindOf(signal: AbortSignal): HookAbortKind {+ return signal.reason === 'timeout' ? 'timeout' : 'aborted'+}++function hookAbortError(+ kind: HookAbortKind,+ timeoutMs: number+): Error & { code?: string } {+ const e: Error & { code?: string } =+ kind === 'timeout'+ ? new Error(`plugin hook timed out after ${timeoutMs}ms`)+ : new Error(HOOK_ABORT_REASON.aborted)+ e.code = kind === 'timeout' ? 'plugin.hook.timeout' : 'plugin.hook.aborted'+ return e+}+const CAPABILITY_PERMISSIONS: Record<string, ReadonlyArray<string>> = {http: ['http'],notify: ['notify'],@@ -1521,7 +1561,7 @@ export class CapabilityBridge {}/** Cancel only the invocation captured by callHook's signal/deadline. */- private notifyAbort(scope: HookInvocationScopeV1): void {+ private notifyAbort(scope: HookInvocationScopeV1, kind: HookAbortKind): void {if (this.disposed ||!this.currentInvocationScope ||@@ -1533,7 +1573,7 @@ export class CapabilityBridge {type: 'event',event: 'abort',...scope,- reason: 'plugin hook aborted',+ reason: HOOK_ABORT_REASON[kind],})this.abortHttpCalls((entry) =>@@ -1855,12 +1895,13 @@ export class CapabilityBridge {** @param hook Hook name as registered by the plugin.* @param taskId Stable task id to send in `hookEnter`.- * @param signal AbortSignal from the host-owned HookAbortBudget; if it- * fires (timeout or external abort), this rejects with+ * @param signal AbortSignal from the host-owned HookAbortBudget. A+ * deadline overrun (reason `'timeout'`) rejects with+ * `plugin.hook.timeout`; any other abort rejects with* `plugin.hook.aborted`.* @param timeoutMs Defensive timeout in case the worker never replies- * (e.g. crash). Generally the AbortBudget's deadline is- * shorter; this is the upper bound.+ * (e.g. crash). Armed at `timeoutMs` plus a grace margin+ * so it never races the caller's own deadline.*/callHook(hook: HookName,@@ -1927,37 +1968,34 @@ export class CapabilityBridge {}return new Promise<HookEffectsV1>((resolve, reject) => {- const onAbort = () => {- if (this.pendingHook && sameHookScope(this.pendingHook.scope, scope)) {- this.notifyAbort(scope)- this.pendingHook.detach()- this.pendingHook = null- this.clearHookContext()- const e: Error & { code?: string } = new Error('plugin hook aborted')- e.code = 'plugin.hook.aborted'- reject(e)+ const settleAborted = (kind: HookAbortKind): void => {+ if (+ !this.pendingHook ||+ !sameHookScope(this.pendingHook.scope, scope)+ ) {+ return}+ this.notifyAbort(scope, kind)+ this.pendingHook.detach()+ this.pendingHook = null+ this.clearHookContext()+ reject(hookAbortError(kind, timeoutMs))}- const timer = setTimeout(() => {- if (this.pendingHook && sameHookScope(this.pendingHook.scope, scope)) {- this.notifyAbort(scope)- this.pendingHook.detach()- this.pendingHook = null- this.clearHookContext()- const e: Error & { code?: string } = new Error(- `plugin hook timed out after ${timeoutMs}ms`- )- e.code = 'plugin.hook.timeout'- reject(e)- }- }, timeoutMs)+ // The caller's budget and this defensive timer watch the same deadline.+ // Without the grace margin the two fire in the same tick and whichever+ // wins decides the message, so a plain deadline overrun could surface as+ // the uninformative 'plugin hook aborted'. The caller's signal is the+ // authority; this timer only covers callers that pass none.+ const onAbort = () => settleAborted(abortKindOf(signal))+ const timer = setTimeout(+ () => settleAborted('timeout'),+ timeoutMs + HOOK_DEFENSIVE_TIMEOUT_GRACE_MS+ )if (signal.aborted) {clearTimeout(timer)this.clearHookContext()- const e: Error & { code?: string } = new Error('plugin hook aborted')- e.code = 'plugin.hook.aborted'- reject(e)+ reject(hookAbortError(abortKindOf(signal), timeoutMs))return}diff --git a/src/core/plugin/host/e2e-builtins.test.ts b/src/core/plugin/host/e2e-builtins.test.tsindex abbe6c27..0e247b22 100644--- a/src/core/plugin/host/e2e-builtins.test.ts+++ b/src/core/plugin/host/e2e-builtins.test.ts@@ -123,19 +123,4 @@ describe('Built-in plugins via PluginHost', () => {await s.bridge.dispose()}})-- it('M2: motrix.scraper-hook registers beforeCreate hook', async () => {- const s = await load('motrix.scraper-hook')- try {- expect(- s.registrations.some(- (r) => r.kind === 'hook' && r.key === 'beforeCreate'- )- ).toBe(true)- // No public commands; the hook itself is exercised via the- // HookOrchestrator suite, not directly here.- } finally {- await s.bridge.dispose()- }- })})diff --git a/src/core/plugin/host/orchestrator.e2e.test.ts b/src/core/plugin/host/orchestrator.e2e.test.tsindex 2b48791c..bd820135 100644--- a/src/core/plugin/host/orchestrator.e2e.test.ts+++ b/src/core/plugin/host/orchestrator.e2e.test.ts@@ -326,23 +326,38 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {const response = Promise.withResolvers<void>()let requests = 0dispatcher- .get('https://example.test')- .intercept({ method: 'HEAD', path: '/archive.zip' })+ .get('https://commons.wikimedia.org')+ .intercept({+ method: 'GET',+ path: (value: string) => value.startsWith('/w/api.php'),+ }).reply(async () => {requests += 1requestStarted.resolve()await response.promisereturn {statusCode: 200,- data: '',+ data: JSON.stringify({+ query: {+ pages: {+ 1: {+ imageinfo: [+ {+ url: 'https://upload.wikimedia.org/wikipedia/commons/example.jpg',+ },+ ],+ },+ },+ },+ }),responseOptions: {- headers: { 'content-type': 'application/octet-stream' },+ headers: { 'content-type': 'application/json' },},}}).persist()const harness = await makeHarness({ dispatcher })- const pluginId = 'motrix.scraper-hook'+ const pluginId = 'motrix.url-resolver'enableOnly(harness, pluginId)await harness.host.activate(pluginId)const queuedEntry = Promise.withResolvers<void>()@@ -354,7 +369,7 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {return result})- const url = 'https://example.test/archive.zip'+ const url = 'https://commons.wikimedia.org/wiki/File:Example.jpg'vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })try {const active = harness.host.invokeHook(pluginId, 'beforeCreate', {@@ -404,7 +419,7 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {}}, 20_000)- it('keeps a repeated scraper request alive across the previous Hook deadline', async () => {+ it('keeps a repeated plugin request alive across the previous Hook deadline', async () => {const dispatcher = new MockAgent()dispatcher.disableNetConnect()cleanups.push(() => dispatcher.close())@@ -412,8 +427,11 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {const response = Promise.withResolvers<void>()let requests = 0dispatcher- .get('https://example.test')- .intercept({ method: 'HEAD', path: '/WeChatWin.exe' })+ .get('https://commons.wikimedia.org')+ .intercept({+ method: 'GET',+ path: (value: string) => value.startsWith('/w/api.php'),+ }).reply(async () => {requests += 1if (requests === 2) {@@ -422,18 +440,30 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {}return {statusCode: 200,- data: '',+ data: JSON.stringify({+ query: {+ pages: {+ 1: {+ imageinfo: [+ {+ url: 'https://upload.wikimedia.org/wikipedia/commons/example.jpg',+ },+ ],+ },+ },+ },+ }),responseOptions: {- headers: { 'content-type': 'application/octet-stream' },+ headers: { 'content-type': 'application/json' },},}}).persist()const harness = await makeHarness({ dispatcher })- enableOnly(harness, 'motrix.scraper-hook')- await harness.host.activate('motrix.scraper-hook')+ enableOnly(harness, 'motrix.url-resolver')+ await harness.host.activate('motrix.url-resolver')const invokeHook = vi.spyOn(harness.host, 'invokeHook')- const url = 'https://example.test/WeChatWin.exe'+ const url = 'https://commons.wikimedia.org/wiki/File:Example.jpg'const saveDir = String.raw`C:\Users\tester\Downloads`// The production 10-second budget runs on a controlled host clock;// worker execution and the HTTP response are synchronized by promises.@@ -456,7 +486,9 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {const result = await secondexpect(result.aborted).not.toBe(true)if (result.aborted) throw new Error(result.reason)- expect(result.final.uris).toEqual([url])+ expect(result.final.uris).toEqual([+ 'https://upload.wikimedia.org/wikipedia/commons/example.jpg',+ ])expect(result.final.saveDir).toBe(saveDir)expect(requests).toBe(2)expect(harness.logs.filter((entry) => entry.level === 'warn')).toEqual([])@@ -466,74 +498,6 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {}}, 20_000)- it('scraper-hook performs real HEAD+GET and resolves a nested relative archive', async () => {- const requests: Array<{ method: string; host: string; path: string }> = []- const loopback = await createOriginPreservingLoopback(- (request, response) => {- requests.push({- method: request.method ?? '',- host: request.headers.host ?? '',- path: request.url ?? '',- })- if (- request.headers.host !== 'example.test' ||- request.url !== '/catalog/deep/page.html'- ) {- response.writeHead(421).end()- return- }- response.setHeader('content-type', 'text/html; charset=utf-8')- if (request.method === 'HEAD') {- response.writeHead(200).end()- return- }- if (request.method === 'GET') {- response- .writeHead(200)- .end('<html><a href="../archives/release.zip">download</a></html>')- return- }- response.writeHead(405).end()- }- )- cleanups.push(() => loopback.close())-- const harness = await makeHarness({- dispatcher: loopback.dispatcher,- config: {- 'motrix.scraper-hook': { enabled: true, maxBodyBytes: 64 << 10 },- },- })- enableOnly(harness, 'motrix.scraper-hook')- const taskId = 'builtin-scraper-task'- const result = await harness.orchestrator.runBeforeCreateHttp(- beforeCreate(- taskId,- 'https://example.test/catalog/deep/page.html',- harness.root- ),- taskId- )-- if (result.aborted) throw new Error(result.reason)- expect(harness.logs.filter((entry) => entry.level === 'warn')).toEqual([])- expect(requests).toEqual([- {- method: 'HEAD',- host: 'example.test',- path: '/catalog/deep/page.html',- },- {- method: 'GET',- host: 'example.test',- path: '/catalog/deep/page.html',- },- ])- expect(result.final.uris).toEqual([- 'https://example.test/catalog/archives/release.zip',- ])- }, 30_000)-it('url-resolver keeps the Commons API transport authorized and emits the API-selected upload URL', async () => {const requests: Array<{ method: string; host: string; path: string }> = []const loopback = await createOriginPreservingLoopback(diff --git a/src/core/plugin/host/quick-js-worker.hooks.test.ts b/src/core/plugin/host/quick-js-worker.hooks.test.tsindex ac2823b5..f2f2efbe 100644--- a/src/core/plugin/host/quick-js-worker.hooks.test.ts+++ b/src/core/plugin/host/quick-js-worker.hooks.test.ts@@ -366,6 +366,47 @@ describe('QuickJS Worker Hook contract', () => {])}, 20_000)+ it('reports a deadline abort as a hook timeout, not a bare abort', async () => {+ const spawned = await spawn('test.hook-sdk-2-0')+ const staged = new StagedEffectStore()+ const controller = new AbortController()+ spawned.bridge.setHookContext({+ fsTaskHost: FS_TASK_HOST,+ taskId: TASK.id,+ phase: 'beforeCreate',+ staged,+ role: 'enrich',+ saveDir: TASK.saveDir,+ pluginStorageRoot: '/plugins/test.hook-sdk-2-0',+ })+ const result = spawned.bridge.callHook(+ 'beforeCreate',+ TASK.id,+ controller.signal,+ 5_000,+ beforeCreatePayload('abort'),+ {},+ scope('deadline')+ )+ await new Promise<void>((resolve) => setTimeout(resolve, 10))+ // HookAbortBudget's deadline timer aborts with the literal reason+ // 'timeout' (see @core/plugin/hooks/abort). The bridge must translate+ // that into the precise timeout code rather than a generic abort.+ controller.abort('timeout')+ await expect(result).rejects.toMatchObject({+ code: 'plugin.hook.timeout',+ message: 'plugin hook timed out after 5000ms',+ })+ await new Promise<void>((resolve) => setTimeout(resolve, 20))++ expect(+ await spawned.callPlugin('test.hook-sdk-2-0.read', undefined)+ ).toEqual([+ { hook: 'onabort', aborted: true, reason: 'plugin hook timed out' },+ { hook: 'abort-listener' },+ ])+ }, 20_000)+it('keeps a retained timer bound to its completed invocation', async () => {const spawned = await spawn('test.hook-sdk-2-0')spawned.bridge.setHookContext({diff --git a/src/core/plugin/manifest/builtin-config-l10n.test.ts b/src/core/plugin/manifest/builtin-config-l10n.test.tsindex 2b00e4fd..195cbc1b 100644--- a/src/core/plugin/manifest/builtin-config-l10n.test.ts+++ b/src/core/plugin/manifest/builtin-config-l10n.test.ts@@ -8,12 +8,8 @@ import { parseManifest } from './parse'// Each builtin ships a config schema whose field titles MUST localize through// the manifest %placeholder% mechanism. Without a resolvable title the renderer// (PluginSettingsForm) falls back to a non-existent app i18next key and shows a-// raw string like "plugin.motrix.scraper-hook.settings.enabled.title".-const BUILTINS = [- 'motrix.scraper-hook',- 'motrix.filename-template',- 'motrix.url-resolver',-] as const+// raw string like "plugin.motrix.url-resolver.settings.quality.title".+const BUILTINS = ['motrix.filename-template', 'motrix.url-resolver'] as constconst PLACEHOLDER_RE = /%[\w.-]+%/diff --git a/src/core/plugin/runtime/runtime-factory.ts b/src/core/plugin/runtime/runtime-factory.tsindex 28ff22cd..14a7c4f4 100644--- a/src/core/plugin/runtime/runtime-factory.ts+++ b/src/core/plugin/runtime/runtime-factory.ts@@ -1,6 +1,7 @@import path from 'node:path'import { getLogger } from '@core/logger'import type { CapabilityHost } from '@core/plugin/capabilities/interface'+import { CircuitBreaker } from '@core/plugin/circuit/circuit-breaker'import { ArtifactMutationLeaseCoordinator } from '@core/plugin/finalize/artifact-mutation-lease'import { NativeFinalizeFilesystemAdapter } from '@core/plugin/finalize/filesystem-adapter'import { NativeFinalizeArtifactOperations } from '@core/plugin/finalize/native-artifact-operations'@@ -79,13 +80,27 @@ export interface PluginRuntimeAssembly {export async function createPluginRuntime(options: PluginRuntimeFactoryOptions): Promise<PluginRuntimeAssembly> {+ const breakerLog = getLogger('plugin:circuit')const auditLog = new HookAuditLog(options.auditLogPath)const observability =options.observability ??createLoggingPostDeliveryObservability(getLogger('plugin:post-delivery'))+ // A misbehaving plugin must degrade, not brick the app: three consecutive+ // failures on the same (plugin, hook) evict it from later chains and+ // disable it. Without this a `pre-resolve` builtin that fails every+ // beforeCreate blocks every new task, permanently (issue #2189).+ const breaker = new CircuitBreaker({+ onOpen: (pluginId, hook, reason) => {+ breakerLog.warn(+ { pluginId, hook, reason },+ 'plugin circuit breaker opened; disabling plugin'+ )+ },+ })const orchestrator = new HookOrchestrator({host: options.host,activationDispatcher: options.activation,+ breaker,hookTimeoutMs: { series: 10_000, parallel: 30_000 },pluginsDir: options.pluginsDir,pluginStorageRootFor: (pluginId) =>diff --git a/src/core/session/checkpoint-resume.integration.test.ts b/src/core/session/checkpoint-resume.integration.test.tsnew file mode 100644index 00000000..1f8fbf40--- /dev/null+++ b/src/core/session/checkpoint-resume.integration.test.ts@@ -0,0 +1,197 @@+// Issue #2187 through the real engine: an HTTP download interrupted by a+// network drop errors, Motrix evicts it from the engine (removeDownloadResult,+// as shouldEvictFromEngine does), and the retry re-adds it under a NEW gid.+// With sqlite3 persistence there is no <file>.aria2 on disk, so the retry can+// only resume if the engine kept the checkpoint and can say so.++import { createHash, randomBytes } from 'node:crypto'+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { createServer, type Server } from 'node:http'+import { tmpdir } from 'node:os'+import path from 'node:path'+import {+ type Aria2Handle,+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import {+ createEngineCheckpointProbe,+ DirectRecoveryPlanner,+} from './direct-recovery-planner'++const SIZE = 8 * 1024 * 1024+const CHUNK = 64 * 1024++describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'retry after a network drop resumes from the engine checkpoint',+ () => {+ const payload = randomBytes(SIZE)+ const digest = createHash('sha256').update(payload).digest('hex')+ const ranges: string[] = []+ let root: string+ let server: Server | undefined+ let port = 0+ let handle: Aria2Handle+ let wired: Awaited<ReturnType<typeof connectAdapter>>++ // Throttled (~2 MiB/s) so the drop lands mid-download; honors Range.+ function listen(): Promise<void> {+ server = createServer((req, res) => {+ ranges.push(req.headers.range ?? 'none')+ const match = /bytes=(\d+)-/.exec(req.headers.range ?? '')+ const start = match ? Number(match[1]) : 0+ const headers = {+ 'Accept-Ranges': 'bytes',+ ETag: '"v1"',+ 'Content-Length': String(SIZE - start),+ }+ if (match) {+ res.writeHead(206, {+ ...headers,+ 'Content-Range': `bytes ${start}-${SIZE - 1}/${SIZE}`,+ })+ } else {+ res.writeHead(200, headers)+ }+ if (req.method === 'HEAD') return res.end()+ let pos = start+ const tick = setInterval(() => {+ if (pos >= SIZE) {+ clearInterval(tick)+ res.end()+ return+ }+ const chunk = payload.subarray(pos, Math.min(pos + CHUNK, SIZE))+ pos += chunk.length+ res.write(chunk)+ }, 30)+ res.on('close', () => clearInterval(tick))+ })+ return new Promise((resolve) =>+ server?.listen(port, '127.0.0.1', () => {+ const address = server?.address()+ if (address && typeof address !== 'string') port = address.port+ resolve()+ })+ )+ }++ async function drop(): Promise<void> {+ server?.closeAllConnections()+ await new Promise<void>((resolve) => server?.close(() => resolve()))+ server = undefined+ }++ async function until<T>(+ read: () => Promise<T | false>,+ label: string+ ): Promise<T> {+ const deadline = Date.now() + 30_000+ while (Date.now() < deadline) {+ const value = await read()+ if (value !== false) return value+ await new Promise((resolve) => setTimeout(resolve, 100))+ }+ throw new Error(`timed out waiting for ${label}`)+ }++ beforeAll(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'motrix-checkpoint-resume-'))+ await listen()+ handle = await spawnAria2ForTest({+ baseDir: root,+ extraArgs: [+ '--enable-sqlite3-persistence=true',+ `--sqlite3-db-path=${path.join(root, 'aria2.db')}`,+ '--force-save=true',+ '--continue=false',+ '--max-tries=1',+ '--retry-wait=0',+ '--connect-timeout=2',+ '--timeout=2',+ '--split=1',+ '--max-connection-per-server=1',+ '--file-allocation=none',+ ],+ })+ wired = await connectAdapter(handle)+ }, 30_000)++ afterAll(async () => {+ wired?.disconnect()+ await handle?.kill()+ if (server) await drop()+ if (root) await rm(root, { recursive: true, force: true })+ })++ it('keeps, reports and resumes the checkpoint under a new gid', async () => {+ const { adapter, rpc } = wired+ const uri = `http://127.0.0.1:${port}/file.bin`+ const filename = 'file.bin.motrix'+ const diskPath = path.join(root, filename)++ await adapter.createDownload({+ uris: [uri],+ saveDir: root,+ filename,+ gid: 'aaaaaaaaaaaaaaaa',+ })+ await until(async () => {+ const s = await rpc.tellStatus('aaaaaaaaaaaaaaaa', ['completedLength'])+ return Number(s.completedLength) > 2 * 1024 * 1024+ }, 'first 2 MiB')++ await drop()+ const saved = await until(async () => {+ const s = await rpc.tellStatus('aaaaaaaaaaaaaaaa', [+ 'status',+ 'completedLength',+ ])+ return s.status === 'error' && Number(s.completedLength)+ }, 'error after the drop')+ await adapter.removeDownloadResult('aaaaaaaaaaaaaaaa')++ // The engine still holds the checkpoint and says so; the planner+ // therefore offers a checkpoint resume instead of checkpoint-missing.+ await expect(adapter.getCheckpointStatus(diskPath)).resolves.toBe(+ 'present'+ )+ const plan = await new DirectRecoveryPlanner(undefined, undefined, () =>+ createEngineCheckpointProbe(adapter)+ ).plan({+ primary: { diskPath },+ finalPath: path.join(root, 'file.bin'),+ })+ expect(plan).toMatchObject({ kind: 'checkpoint' })++ await listen()+ const resumeFrom = ranges.length+ await adapter.createDownload({+ uris: [uri],+ saveDir: root,+ filename,+ gid: 'bbbbbbbbbbbbbbbb',+ resumePolicy: 'checkpoint',+ })+ await until(async () => {+ const s = await rpc.tellStatus('bbbbbbbbbbbbbbbb', ['status'])+ if (s.status === 'error') throw new Error('retry errored')+ return s.status === 'complete'+ }, 'retry to complete')++ const resumed = ranges+ .slice(resumeFrom)+ .map((range) => /bytes=(\d+)-/.exec(range)?.[1])+ .filter((start): start is string => start !== undefined)+ .map(Number)+ // Resumed from the saved progress, not restarted from byte 0.+ expect(Math.max(...resumed)).toBeGreaterThan(0)+ expect(Math.max(...resumed)).toBeLessThanOrEqual(saved)+ const file = await readFile(diskPath)+ expect(createHash('sha256').update(file).digest('hex')).toBe(digest)+ }, 60_000)+ }+)diff --git a/src/core/session/direct-recovery-planner.test.ts b/src/core/session/direct-recovery-planner.test.tsindex 04674e1e..a3ffba03 100644--- a/src/core/session/direct-recovery-planner.test.ts+++ b/src/core/session/direct-recovery-planner.test.ts@@ -1,6 +1,7 @@import path from 'node:path'-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import {+ createEngineCheckpointProbe,type DirectRecoveryFileStat,DirectRecoveryPlanner,} from './direct-recovery-planner'@@ -263,3 +264,100 @@ describe('DirectRecoveryPlanner', () => {})})})++describe('DirectRecoveryPlanner checkpoint probe', () => {+ const diskPath = '/downloads/linux.iso.motrix'+ const fileSystem = makeFileSystem({ [diskPath]: file(8192) })++ it('asks the injected probe instead of looking for a .aria2 file', async () => {+ // With sqlite3 persistence aria2 never writes <file>.aria2; the+ // checkpoint lives in aria2.db. Probing the disk alone made every+ // interrupted download look unresumable (issue #2187).+ const probed: string[] = []+ const planner = new DirectRecoveryPlanner(fileSystem, path.posix, () => {+ return async (target) => {+ probed.push(target)+ return 'present'+ }+ })+ await expect(+ planner.plan({ primary: { diskPath }, finalPath: '/downloads/linux.iso' })+ ).resolves.toMatchObject({+ kind: 'checkpoint',+ reason: 'checkpoint-present',+ })+ expect(probed).toEqual([diskPath])+ })++ it('still blocks a partial file whose checkpoint the probe cannot find', async () => {+ const planner = new DirectRecoveryPlanner(+ fileSystem,+ path.posix,+ () => async () => 'absent'+ )+ await expect(+ planner.plan({ primary: { diskPath }, finalPath: '/downloads/linux.iso' })+ ).resolves.toMatchObject({ kind: 'blocked', reason: 'checkpoint-missing' })+ })++ it('reports a checkpoint that is not a regular file as invalid', async () => {+ const planner = new DirectRecoveryPlanner(+ fileSystem,+ path.posix,+ () => async () => 'not-file'+ )+ await expect(+ planner.plan({ primary: { diskPath }, finalPath: '/downloads/linux.iso' })+ ).resolves.toMatchObject({+ kind: 'invalid',+ reason: 'checkpoint-path-not-file',+ })+ })++ it('treats a failing probe as a failed probe, not as a missing checkpoint', async () => {+ const planner = new DirectRecoveryPlanner(fileSystem, path.posix, () => {+ return async () => {+ throw new Error('database is locked')+ }+ })+ await expect(+ planner.plan({ primary: { diskPath }, finalPath: '/downloads/linux.iso' })+ ).resolves.toMatchObject({ kind: 'invalid', reason: 'file-probe-failed' })+ })+})++describe('createEngineCheckpointProbe', () => {+ const diskPath = '/downloads/linux.iso.motrix'++ it('asks the engine, which knows which checkpoint store it reads', async () => {+ const engine = {+ getCheckpointStatus: vi.fn(async () => 'present' as const),+ }+ const probe = createEngineCheckpointProbe(engine, makeFileSystem({}))+ await expect(probe(diskPath)).resolves.toBe('present')+ expect(engine.getCheckpointStatus).toHaveBeenCalledWith(diskPath)+ })++ it('does not second-guess an engine that says absent', async () => {+ // A stray .aria2 file is not what a sqlite3-persisting engine would read.+ const engine = { getCheckpointStatus: async () => 'absent' as const }+ const probe = createEngineCheckpointProbe(+ engine,+ makeFileSystem({ [`${diskPath}.aria2`]: file(16) })+ )+ await expect(probe(diskPath)).resolves.toBe('absent')+ })++ it('falls back to the control file when the engine cannot answer', async () => {+ const fileSystem = makeFileSystem({ [`${diskPath}.aria2`]: file(16) })+ await expect(+ createEngineCheckpointProbe(+ { getCheckpointStatus: async () => null },+ fileSystem+ )(diskPath)+ ).resolves.toBe('present')+ await expect(+ createEngineCheckpointProbe({}, fileSystem)(diskPath)+ ).resolves.toBe('present')+ })+})diff --git a/src/core/session/direct-recovery-planner.ts b/src/core/session/direct-recovery-planner.tsindex 17e5fa17..b609f30a 100644--- a/src/core/session/direct-recovery-planner.ts+++ b/src/core/session/direct-recovery-planner.ts@@ -1,5 +1,6 @@import fs from 'node:fs/promises'import path from 'node:path'+import type { EngineAdapter } from '@core/engine/engine-adapter'import { INCOMPLETE_SUFFIX } from '@shared/constants/incomplete'export type DirectRecoveryKind =@@ -56,6 +57,17 @@ export interface DirectRecoveryFileSystem {stat(filePath: string): Promise<DirectRecoveryFileStat | null>}+/**+ * Whether the engine holds a resumable checkpoint for an output file. Where+ * it lives depends on the engine's persistence mode: a `<file>.aria2` control+ * file, or a `task_progress` row in aria2.db under sqlite3 persistence. The+ * planner must ask the store the running engine actually reads.+ */+export type DirectCheckpointState = 'present' | 'absent' | 'not-file'+export type DirectCheckpointProbe = (+ diskPath: string+) => Promise<DirectCheckpointState>+export interface DirectRecoveryPath {isAbsolute(filePath: string): booleandirname(filePath: string): string@@ -81,6 +93,30 @@ const nodeFileSystem: DirectRecoveryFileSystem = {},}+/** Checkpoint probe for the classic `<file>.aria2` control file. */+export async function controlFileCheckpoint(+ fileSystem: DirectRecoveryFileSystem,+ diskPath: string+): Promise<DirectCheckpointState> {+ const stat = await fileSystem.stat(`${diskPath}.aria2`)+ if (!stat) return 'absent'+ return stat.isFile ? 'present' : 'not-file'+}++/**+ * Probe that asks the engine, which alone knows whether it keeps checkpoints+ * in control files or in aria2.db (issue #2187). Engines that cannot answer+ * fall back to the control file — the only store they can resume from.+ */+export function createEngineCheckpointProbe(+ engine: Pick<EngineAdapter, 'getCheckpointStatus'>,+ fileSystem: DirectRecoveryFileSystem = nodeFileSystem+): DirectCheckpointProbe {+ return async (diskPath) =>+ (await engine.getCheckpointStatus?.(diskPath)) ??+ controlFileCheckpoint(fileSystem, diskPath)+}+interface ResolvedOutput {diskPath: stringsaveDir: string@@ -92,7 +128,15 @@ interface ResolvedOutput {export class DirectRecoveryPlanner {constructor(private readonly fileSystem: DirectRecoveryFileSystem = nodeFileSystem,- private readonly pathApi: DirectRecoveryPath = path+ private readonly pathApi: DirectRecoveryPath = path,+ /**+ * Resolved per plan: the persistence mode is fixed only once the engine+ * has started, and can change across engine restarts. The default reads+ * the `.aria2` control file through `fileSystem`.+ */+ private readonly checkpointProbe: () => DirectCheckpointProbe = () =>+ (diskPath) =>+ controlFileCheckpoint(this.fileSystem, diskPath)) {}async plan(input: DirectRecoveryInput): Promise<DirectRecoveryPlan> {@@ -142,8 +186,8 @@ export class DirectRecoveryPlanner {return this.result(resolved, 'fresh', 'temp-file-empty', 0)}- const checkpointStat = await this.fileSystem.stat(resolved.checkpointPath)- if (checkpointStat && !checkpointStat.isFile) {+ const checkpoint = await this.checkpointProbe()(resolved.diskPath)+ if (checkpoint === 'not-file') {return this.result(resolved,'invalid',@@ -151,7 +195,7 @@ export class DirectRecoveryPlanner {tempStat.size)}- if (checkpointStat) {+ if (checkpoint === 'present') {return this.result(resolved,'checkpoint',diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 624575dd..936672c2 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -2524,6 +2524,44 @@ describe('SessionManager', () => {}})+ it('takes the checkpoint path when the engine reports one without any .aria2 file', async () => {+ // sqlite3 persistence keeps the checkpoint in aria2.db; the engine, not+ // the filesystem, says whether it exists (#2187). The task then leaves+ // the checkpoint-missing gate and reaches resource validation.+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-http-engine-checkpoint-')+ )+ const diskPath = path.join(tempDir, 'partial.bin.motrix')+ try {+ fs.writeFileSync(diskPath, Buffer.from('partial-bytes'))+ const getCheckpointStatus = vi.fn(async () => 'present' as const)+ ;(+ adapter as unknown as {+ getCheckpointStatus: typeof getCheckpointStatus+ }+ ).getCheckpointStatus = getCheckpointStatus+ seedAsPair(db, {+ motrixId: 'm-http-engine-checkpoint',+ gid: 'lost-http-engine-checkpoint',+ name: 'partial.bin',+ diskPath,+ finalPath: path.join(tempDir, 'partial.bin'),+ finalName: 'partial.bin',+ uris: ['https://example.com/partial.bin'],+ status: TaskStatus.Downloading,+ })++ await sessionManager.restore()++ expect(getCheckpointStatus).toHaveBeenCalledWith(diskPath)+ expect(+ taskManager.getById('m-http-engine-checkpoint')?.errorDetailKey+ ).not.toBe('task.recovery.startup.resumeCheckpointMissing')+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ })+it('does not replay a direct task whose request credentials were not persisted', async () => {seedAsPair(db, {motrixId: 'm-http-credentials',diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 54c97287..4d2bec55 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -30,11 +30,11 @@ import {import type { TaskOccurrence } from '@shared/types/task-occurrence'import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'import {+ classifyTerminalError,computeEta,derivePathsFromRaw,extractUris,translateBtExtension,- translateErrorCode,translateRawToTask,translateStatus,} from '../engine/aria2/translate'@@ -75,7 +75,10 @@ import { taskRowToDownloadTask } from '../task/task-row-to-download-task'import { restoreTaskSaveDirectory } from '../task/task-save-directory'import { isMagnetCleanupTombstoneHidden } from '../torrent/magnet-cleanup-quarantine'import { computeUriHash, deriveInfoHash } from './content-key'-import { DirectRecoveryPlanner } from './direct-recovery-planner'+import {+ createEngineCheckpointProbe,+ DirectRecoveryPlanner,+} from './direct-recovery-planner'import type {MotrixDatabase,TaskInstanceRow,@@ -269,10 +272,14 @@ export class SessionManager {* and non-media callers can omit it.*/private mediaTmpRoot?: string,+ // Checkpoints are probed through the engine, which alone knows whether it+ // keeps them in control files or in aria2.db (issue #2187).private directRecoveryPlanner: Pick<DirectRecoveryPlanner,'plan'- > = new DirectRecoveryPlanner(),+ > = new DirectRecoveryPlanner(undefined, undefined, () =>+ createEngineCheckpointProbe(adapter)+ ),private directResourceValidator: Pick<DirectResourceValidatorService,'verify'@@ -1275,7 +1282,7 @@ export class SessionManager {{finishedAt: aria2.status === 'complete' ? now : null,errorMessage: aria2.errorMessage ?? null,- errorCode: translateErrorCode(aria2.errorCode),+ ...classifyTerminalError(aria2.errorCode, aria2.errorMessage),},now)diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex 74210b45..075f00d2 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -443,6 +443,65 @@ describe('reAddTask (HTTP path)', () => {)})+ it('resumes from a checkpoint the engine reports without any .aria2 file', async () => {+ // sqlite3 persistence keeps the checkpoint in aria2.db, so there is no+ // <file>.aria2 on disk. The engine answers where it keeps it; the retry+ // after a network drop must resume, not fail checkpoint-missing (#2187).+ const tempDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-direct-readd-')+ )+ const diskPath = path.join(tempDir, 'file.zip.motrix')+ try {+ fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))+ const task = makeHttpTask({+ diskPath,+ finalPath: path.join(tempDir, 'file.zip'),+ })+ task.instances[0].diskPath = diskPath+ task.instances[0].payload = {+ directReplay: {+ version: 1,+ requestModifiers: [],+ replayability: 'uri-only',+ resourceValidator: {+ kind: 'strong-etag',+ value: '"release-v1"',+ contentLength: 4096,+ capturedAt: 7,+ },+ },+ }+ const deps = makeDeps(task)+ const getCheckpointStatus = vi.fn(async () => 'present' as const)+ deps.adapter.getCheckpointStatus = getCheckpointStatus++ await reAddTask('t2', {+ ...deps,+ directResourceValidator: {+ verify: vi.fn(async () => ({+ outcome: 'unchanged' as const,+ ifRange: '"release-v1"',+ })),+ },+ getDirectResourceProxyOptions: () => ({+ proxy: '',+ noProxy: '',+ userAgent: 'Motrix/Verified',+ }),+ })++ expect(getCheckpointStatus).toHaveBeenCalledWith(diskPath)+ expect(deps.adapter.createDownload).toHaveBeenCalledWith(+ expect.objectContaining({+ filename: 'file.zip.motrix',+ resumePolicy: 'checkpoint',+ })+ )+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true })+ }+ })+it('uses checkpoint resume for a non-empty HTTP partial with .aria2 state', async () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-direct-readd-')diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 3265a95c..2baa5688 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -22,7 +22,10 @@ import type {EngineAdapter,} from '../../engine/engine-adapter'import type { Logger } from '../../logger'-import { DirectRecoveryPlanner } from '../../session/direct-recovery-planner'+import {+ createEngineCheckpointProbe,+ DirectRecoveryPlanner,+} from '../../session/direct-recovery-planner'import { applyTerminalTransition } from '../apply-terminal-transition'import {buildBtDirectOutputPaths,@@ -199,7 +202,6 @@ async function reAddBt(})}-const directRecoveryPlanner = new DirectRecoveryPlanner()const directResourceValidator = new DirectResourceValidatorService()async function buildDirectReAddParams(@@ -227,7 +229,11 @@ async function buildDirectReAddParams(])const requestOptions = getProxyOptions()- const plan = await directRecoveryPlanner.plan({+ // Ask the engine: only it knows whether the checkpoint lives in a control+ // file or in aria2.db (issue #2187).+ const plan = await new DirectRecoveryPlanner(undefined, undefined, () =>+ createEngineCheckpointProbe(adapter)+ ).plan({primary,finalPath: task.finalPath,})diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 9bd91640..1b05e3ac 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -89,6 +89,7 @@ import {sanitizeRemoteFilename,} from './direct-resource-validator'import type { FinalNamePicker } from './final-name-picker'+import { findPathOverrun } from './path-length'import { toTempPath } from './paths'import {admitDownloadSources,@@ -538,6 +539,27 @@ async function handleCreateTaskUnderAdmission(? createBtDirectStoragePlan(finalPath, parsedBtLayout, torrentMetaPath): null+ // Fail before a single byte moves when a destination cannot be opened at+ // all. Windows caps a path at MAX_PATH and reports the overrun as+ // ERROR_PATH_NOT_FOUND mid-download, so without this the user pays for the+ // transfer first and then reads a misleading "cannot find the path" error+ // (agalwood/Motrix#2183). A .torrent declares its internal paths up front,+ // so the deep nesting that actually overruns is knowable here; a magnet's+ // is not, and falls back to the terminal-error classifier.+ const plannedPaths = [diskPath, finalPath]+ for (const file of parsedBtLayout?.files ?? []) {+ if (file.pathInsideRoot) {+ plannedPaths.push(path.join(finalPath, file.pathInsideRoot))+ }+ }+ const overrun = findPathOverrun(plannedPaths, process.platform)+ if (overrun) {+ throw new AppError(+ ErrorCode.TaskPathTooLong,+ `task path too long: ${overrun.length}/${overrun.limit}: ${overrun.path}`+ )+ }+// Create the engine's directory before admission so aria2 can persist its// torrent metadata. Multi-file BT uses its private metadata directory and// maps every payload into the final output root. Single-file BT uses thediff --git a/src/core/task/path-length.test.ts b/src/core/task/path-length.test.tsnew file mode 100644index 00000000..07bb4bd6--- /dev/null+++ b/src/core/task/path-length.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest'+import {+ exceedsPathLimit,+ extractAria2FilePath,+ findPathOverrun,+ WINDOWS_MAX_PATH,+} from './path-length'++// The exact destination from agalwood/Motrix#2183 (262 chars).+const ISSUE_2183 = String.raw`F:\Game\Dead Cells (2018).motrix\Dead Cells (2018)\Bonuses\Dead Cells - Demake Soundtrack\FLAC Yoann Laulan - Dead Cells - Soundtrack Part 2 (Demake) FLAC\Yoann Laulan - Dead Cells - Soundtrack Part 2 (Demake) - 21 The Time Keeper Formerly Known As Assassin.flac`++describe('exceedsPathLimit', () => {+ it('flags the #2183 destination on win32', () => {+ expect(ISSUE_2183).toHaveLength(262)+ expect(exceedsPathLimit(ISSUE_2183, 'win32')).toEqual({+ length: 262,+ limit: WINDOWS_MAX_PATH,+ })+ })++ it('accepts a path exactly at the limit', () => {+ const atLimit = `C:\\${'a'.repeat(WINDOWS_MAX_PATH - 3)}`+ expect(atLimit).toHaveLength(WINDOWS_MAX_PATH)+ expect(exceedsPathLimit(atLimit, 'win32')).toBeNull()+ })++ it('flags one character past the limit', () => {+ const overLimit = `C:\\${'a'.repeat(WINDOWS_MAX_PATH - 2)}`+ expect(exceedsPathLimit(overLimit, 'win32')?.length).toBe(+ WINDOWS_MAX_PATH + 1+ )+ })++ it('never flags on platforms without the MAX_PATH cap', () => {+ expect(exceedsPathLimit(ISSUE_2183, 'darwin')).toBeNull()+ expect(exceedsPathLimit(ISSUE_2183, 'linux')).toBeNull()+ })++ it('ignores a path already escaped with the long-path prefix', () => {+ expect(exceedsPathLimit(`\\\\?\\${ISSUE_2183}`, 'win32')).toBeNull()+ })++ it('measures UTF-16 code units, not code points', () => {+ // An astral emoji is two UTF-16 units to Windows, so a path that looks+ // short by code points can still overrun MAX_PATH.+ const emoji = '\u{1F600}'.repeat(130) // 130 code points, 260 units+ expect(exceedsPathLimit(`C:\\${emoji}`, 'win32')?.length).toBe(263)+ })+})++describe('extractAria2FilePath', () => {+ it('pulls the path out of the EX_FILE_OPEN message', () => {+ expect(+ extractAria2FilePath(+ 'Failed to open the file F:/Game/x/y.flac, cause: The system cannot find the path specified.'+ )+ ).toBe('F:/Game/x/y.flac')+ })++ it('keeps commas that belong to the filename', () => {+ expect(+ extractAria2FilePath(+ 'Failed to open the file C:/d/Hello, World (2018).mkv, cause: nope'+ )+ ).toBe('C:/d/Hello, World (2018).mkv')+ })++ it('returns null for an unrelated message', () => {+ expect(extractAria2FilePath('Timeout')).toBeNull()+ expect(extractAria2FilePath(null)).toBeNull()+ })+})++describe('findPathOverrun', () => {+ const dir = `C:\\Downloads\\${'d'.repeat(100)}`++ it('returns null when every candidate fits', () => {+ expect(findPathOverrun([`${dir}\\a.bin`], 'win32')).toBeNull()+ })++ it('reports the worst offender, not the first', () => {+ const slightly = `${dir}\\${'a'.repeat(160)}`+ const badly = `${dir}\\${'b'.repeat(400)}`+ expect(findPathOverrun([slightly, badly], 'win32')?.path).toBe(badly)+ })++ it('skips empty candidates', () => {+ expect(findPathOverrun(['', `${dir}\\a.bin`], 'win32')).toBeNull()+ })++ it('is inert off win32', () => {+ expect(findPathOverrun([`${dir}\\${'b'.repeat(400)}`], 'linux')).toBeNull()+ })+})diff --git a/src/core/task/path-length.ts b/src/core/task/path-length.tsnew file mode 100644index 00000000..e59ce829--- /dev/null+++ b/src/core/task/path-length.ts@@ -0,0 +1,81 @@+// Windows caps a path at MAX_PATH (260 including the terminating NUL, so 259+// usable characters) unless BOTH the machine's LongPathsEnabled policy is on+// AND the process declares `longPathAware` in its manifest. aria2c.exe carries+// that manifest (aria2_motrix/src/aria2c.manifest), but the policy is off by+// default on most installs, so an over-long destination still fails — and it+// fails with ERROR_PATH_NOT_FOUND, whose text ("The system cannot find the+// path specified") reads as a missing directory rather than an over-long path.+//+// Motrix already budgets the filename against NAME_MAX (255 bytes, see+// direct-resource-validator). That is a different, per-component limit; it+// says nothing about the assembled path. See agalwood/Motrix#2183.++/** Usable characters in a Windows path without the `\\?\` escape. */+export const WINDOWS_MAX_PATH = 259++/** Paths already escaped with this prefix bypass the MAX_PATH parser. */+const LONG_PATH_PREFIX = '\\\\?\\'++export interface PathLengthOverrun {+ /** Length in UTF-16 code units — the unit Windows itself counts. */+ length: number+ limit: number+}++/**+ * Report a destination that the platform cannot open, or null when it fits.+ * Only win32 has a whole-path cap low enough to hit in practice; POSIX+ * PATH_MAX (4096) is out of reach for any name a download produces.+ */+export function exceedsPathLimit(+ filePath: string,+ platform: NodeJS.Platform | string+): PathLengthOverrun | null {+ if (platform !== 'win32') return null+ if (filePath.startsWith(LONG_PATH_PREFIX)) return null+ // `.length` is already UTF-16 code units, which is what the Win32 wide-char+ // APIs count — an astral character costs two, exactly as it does there.+ const length = filePath.length+ if (length <= WINDOWS_MAX_PATH) return null+ return { length, limit: WINDOWS_MAX_PATH }+}++const FILE_OPEN_MESSAGE = /^Failed to open the file (.+), cause: /u++/**+ * Recover the destination from aria2's EX_FILE_OPEN message+ * (`Failed to open the file %s, cause: %s`). The greedy capture is deliberate:+ * a filename may contain ", " itself, while the trailing ", cause: " separator+ * appears once, last.+ */+export function extractAria2FilePath(+ errorMessage: string | null | undefined+): string | null {+ if (!errorMessage) return null+ return FILE_OPEN_MESSAGE.exec(errorMessage)?.[1] ?? null+}++export interface PathOverrun extends PathLengthOverrun {+ path: string+}++/**+ * Worst over-long path among the destinations a task will write, or null when+ * they all fit. Reporting the worst (not the first) keeps the error message+ * pointed at the path the user actually has to shorten.+ */+export function findPathOverrun(+ candidates: readonly string[],+ platform: NodeJS.Platform | string+): PathOverrun | null {+ let worst: PathOverrun | null = null+ for (const candidate of candidates) {+ if (!candidate) continue+ const overrun = exceedsPathLimit(candidate, platform)+ if (overrun === null) continue+ if (worst === null || overrun.length > worst.length) {+ worst = { ...overrun, path: candidate }+ }+ }+ return worst+}diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex 6dd603c9..8162fa1d 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -92,11 +92,13 @@ const nativeMessagingLog = getLogger('native-messaging')* `${manifest.id}.resolve` — the resolve-command marker.** Keying off this marker (not the `site-resolver` category alone) is the- * load-bearing distinction learned in A1: motrix.scraper-hook is also a- * `site-resolver` whose hostPermissions match all URLs, yet it has NO resolve- * command (it works via the `beforeCreate` hook, not the mux command seam).- * Deriving seam membership from the category alone would let it collapse- * routing to match-everything and send every download through a resolver VM.+ * load-bearing distinction learned in A1: a plugin can be a `site-resolver`+ * whose hostPermissions match all URLs and still have NO resolve command —+ * motrix.scraper-hook (since retired from the built-in set) was exactly that,+ * working through the `beforeCreate` hook rather than the mux command seam.+ * Deriving seam membership from the category alone would let such a plugin+ * collapse routing to match-everything and send every download through a+ * resolver VM.*/function contributesResolveCommand(manifest: PluginManifest): boolean {const commands = manifest.contributes?.commands ?? []diff --git a/src/main/bridge/make-resolve-to-mux.test.ts b/src/main/bridge/make-resolve-to-mux.test.tsindex 1418939f..5c389d35 100644--- a/src/main/bridge/make-resolve-to-mux.test.ts+++ b/src/main/bridge/make-resolve-to-mux.test.ts@@ -83,11 +83,12 @@ describe('makeResolveToMux — generalized multi-resolver routing', () => {)})- // Regression lock (carried from A1): motrix.scraper-hook is a builtin- // 'site-resolver' with hostPermissions ['*://*/*'] and NO resolve command.- // Routing keyed off the resolve-command marker (not the site-resolver- // category) must NEVER invoke it, so a broad co-installed site-resolver- // cannot collapse the seam to match-everything.+ // Regression lock (carried from A1): motrix.scraper-hook — a builtin at the+ // time, since retired from the shipped set — was a 'site-resolver' with+ // hostPermissions ['*://*/*'] and NO resolve command. Routing keyed off the+ // resolve-command marker (not the site-resolver category) must NEVER invoke+ // such a plugin, so a broad co-installed site-resolver cannot collapse the+ // seam to match-everything. The id stays as the historical fixture.it('never routes to a broad site-resolver that has no <id>.resolve command', async () => {const invokeCommand = vi.fn()const pluginHost = { activate: vi.fn(), invokeCommand } as anydiff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsxindex 4fcfa99e..9bf87593 100644--- a/src/renderer/components/add-task/add-task-form.tsx+++ b/src/renderer/components/add-task/add-task-form.tsx@@ -25,7 +25,10 @@ import { invalidateTaskList } from '@renderer/hooks/use-task-list'import type { ParsedTorrentFile } from '@renderer/lib/parse-torrent-file'import { transport } from '@renderer/lib/transport'import { cn } from '@renderer/lib/utils'-import { usePlatformServices } from '@renderer/platform/services'+import {+ type PlatformServices,+ usePlatformServices,+} from '@renderer/platform/services'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'import {@@ -58,6 +61,11 @@ import {readPendingCreates,rememberPendingCreate,} from './pending-create-inputs'+import {+ parsePathTooLong,+ parsePluginChainAbort,+ taskCreateFailureReason,+} from './task-create-failure'import { TorrentTabPanel } from './torrent-tab-panel'import { parseUrlLines } from './url-interpreters/multiline-url'import {@@ -89,13 +97,33 @@ interface LocalTorrentQueue {currentIndex: number}-function taskCreateFailureReason(error: unknown): string | null {- if (!(error instanceof Error)) return null- const reason = error.message- .replace(/^Error invoking remote method '[^']+':\s*/u, '')- .replace(/^(?:AppError|Error):\s*/u, '')- .trim()- return reason || null+/**+ * Notify the failure, preferring the plugin-attributed message when the chain+ * was aborted by a plugin: the raw text names an internal chain and gives the+ * user no way to act, while the plugin id plus "disable it in Settings" does.+ */+function notifyTaskCreateFailure(+ notify: PlatformServices['notify'],+ reason: string | null+): void {+ if (!reason) {+ notify('error', 'task.add.createFailed')+ return+ }+ const abort = parsePluginChainAbort(reason)+ if (abort) {+ notify('error', 'task.add.createFailedByPlugin', {+ pluginId: abort.pluginId,+ detail: abort.detail,+ })+ return+ }+ const tooLong = parsePathTooLong(reason)+ if (tooLong) {+ notify('error', 'task.add.createFailedPathTooLong', { ...tooLong })+ return+ }+ notify('error', 'task.add.createFailedWithReason', { reason })}export function AddTaskForm({@@ -584,13 +612,7 @@ export function AddTaskForm({failed,})} else if (failed > 0) {- if (firstFailureReason) {- platform.notify('error', 'task.add.createFailedWithReason', {- reason: firstFailureReason,- })- } else {- platform.notify('error', 'task.add.createFailed')- }+ notifyTaskCreateFailure(platform.notify, firstFailureReason)}if (successes.length > 0 && failed === 0) {await completeCurrentSubmission(@@ -658,12 +680,7 @@ export function AddTaskForm({await completeConflict(result.taskId)} catch (error) {console.error(error)- const reason = taskCreateFailureReason(error)- if (reason) {- platform.notify('error', 'task.add.createFailedWithReason', { reason })- } else {- platform.notify('error', 'task.add.createFailed')- }+ notifyTaskCreateFailure(platform.notify, taskCreateFailureReason(error))} finally {setSubmitting(false)}diff --git a/src/renderer/components/add-task/task-create-failure.test.ts b/src/renderer/components/add-task/task-create-failure.test.tsnew file mode 100644index 00000000..f2b9b06d--- /dev/null+++ b/src/renderer/components/add-task/task-create-failure.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest'+import {+ parsePathTooLong,+ parsePluginChainAbort,+ taskCreateFailureReason,+} from './task-create-failure'++describe('taskCreateFailureReason', () => {+ it('strips the Electron remote-method wrapper and the AppError prefix', () => {+ const error = new Error(+ "Error invoking remote method 'command:createTask': AppError: boom"+ )+ expect(taskCreateFailureReason(error)).toBe('boom')+ })++ it('returns null for a non-Error and for an empty message', () => {+ expect(taskCreateFailureReason('nope')).toBeNull()+ expect(taskCreateFailureReason(new Error(' '))).toBeNull()+ })+})++describe('parsePluginChainAbort', () => {+ it('splits the plugin id from the detail', () => {+ expect(+ parsePluginChainAbort(+ 'plugin chain aborted: motrix.scraper-hook: plugin hook timed out after 10000ms'+ )+ ).toEqual({+ pluginId: 'motrix.scraper-hook',+ detail: 'plugin hook timed out after 10000ms',+ })+ })++ it('keeps colons inside the detail intact', () => {+ expect(+ parsePluginChainAbort('plugin chain aborted: some.plugin: a: b: c')+ ).toEqual({ pluginId: 'some.plugin', detail: 'a: b: c' })+ })++ it('returns null when the chain aborted without a plugin attribution', () => {+ expect(parsePluginChainAbort('plugin chain aborted: no-colon-detail')).toBe(+ null+ )+ })++ it('returns null for unrelated failures', () => {+ expect(parsePluginChainAbort('disk is full')).toBeNull()+ })+})++describe('parsePathTooLong', () => {+ it('reads the length, the limit and the offending path', () => {+ expect(+ parsePathTooLong(+ 'task path too long: 262/259: F:\\Game\\Dead Cells (2018).motrix\\x.flac'+ )+ ).toEqual({+ length: '262',+ limit: '259',+ path: 'F:\\Game\\Dead Cells (2018).motrix\\x.flac',+ })+ })++ it('keeps colons inside a Windows drive path', () => {+ expect(+ parsePathTooLong('task path too long: 300/259: C:\\a\\b')?.path+ ).toBe('C:\\a\\b')+ })++ it('returns null for unrelated failures', () => {+ expect(parsePathTooLong('disk is full')).toBeNull()+ expect(parsePathTooLong('task path too long: nonsense')).toBeNull()+ })+})diff --git a/src/renderer/components/add-task/task-create-failure.ts b/src/renderer/components/add-task/task-create-failure.tsnew file mode 100644index 00000000..77a2d775--- /dev/null+++ b/src/renderer/components/add-task/task-create-failure.ts@@ -0,0 +1,60 @@+// Turns a raw CreateTask rejection into something a person can act on.+//+// The IPC layer hands the renderer the AppError message verbatim, wrapped in+// Electron's remote-method envelope. Most messages are already user-facing;+// a plugin-chain abort is not — it names an internal chain and a plugin id,+// and the only useful action (disable that plugin) is nowhere in the text.++/** Strip the IPC envelope and error-class prefix from a rejection. */+export function taskCreateFailureReason(error: unknown): string | null {+ if (!(error instanceof Error)) return null+ const reason = error.message+ .replace(/^Error invoking remote method '[^']+':\s*/u, '')+ .replace(/^(?:AppError|Error):\s*/u, '')+ .trim()+ return reason || null+}++export interface PluginChainAbort {+ pluginId: string+ detail: string+}++const CHAIN_ABORT_PREFIX = 'plugin chain aborted: '++/**+ * Recognize `plugin chain aborted: <pluginId>: <detail>` — the shape+ * HookOrchestrator produces for a fail-closed chain. Returns null when the+ * abort carries no plugin attribution (e.g. a chain-level abort), so the+ * caller falls back to the generic message rather than inventing a plugin id.+ */+export function parsePluginChainAbort(reason: string): PluginChainAbort | null {+ if (!reason.startsWith(CHAIN_ABORT_PREFIX)) return null+ const rest = reason.slice(CHAIN_ABORT_PREFIX.length)+ const separator = rest.indexOf(': ')+ if (separator <= 0) return null+ const pluginId = rest.slice(0, separator).trim()+ const detail = rest.slice(separator + 2).trim()+ if (!pluginId || !detail) return null+ return { pluginId, detail }+}++export interface PathTooLong {+ length: string+ limit: string+ path: string+}++const PATH_TOO_LONG = /^task path too long: (\d+)\/(\d+): (.+)$/su++/**+ * Recognize the pre-create guard from `create-task-handler` — the counterpart+ * of the `DL_PATH_TOO_LONG` terminal error, raised before the task exists.+ * Electron flattens AppError to its message across IPC, so the code travels+ * inside the text, the same way a plugin chain abort does.+ */+export function parsePathTooLong(reason: string): PathTooLong | null {+ const match = PATH_TOO_LONG.exec(reason)+ if (!match) return null+ return { length: match[1]!, limit: match[2]!, path: match[3]! }+}diff --git a/src/shared/errors.ts b/src/shared/errors.tsindex bb0acae7..4e5871d9 100644--- a/src/shared/errors.ts+++ b/src/shared/errors.ts@@ -10,6 +10,7 @@ export enum ErrorCode {TaskRevealFailed = 'TASK_REVEAL_FAILED',TaskOpenFailed = 'TASK_OPEN_FAILED',TaskNotRetryable = 'TASK_NOT_RETRYABLE',+ TaskPathTooLong = 'TASK_PATH_TOO_LONG',SessionRestoreFailed = 'SESSION_RESTORE_FAILED',SettingsInvalid = 'SETTINGS_INVALID',PluginTimeout = 'PLUGIN_TIMEOUT',@@ -84,6 +85,7 @@ export enum DownloadErrorCode {Timeout = 'DL_TIMEOUT',DiskFull = 'DL_DISK_FULL',FileWriteError = 'DL_FILE_WRITE_ERROR',+ PathTooLong = 'DL_PATH_TOO_LONG',ChecksumMismatch = 'DL_CHECKSUM_MISMATCH',TooManyRedirects = 'DL_TOO_MANY_REDIRECTS',ServerError = 'DL_SERVER_ERROR',diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 75007b85..6ea3d9e3 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -963,6 +963,8 @@"clearSelection": "Clear selection","createFailed": "Failed to create download task.","createFailedWithReason": "Failed to create download task: {{reason}}",+ "createFailedByPlugin": "Couldn’t create the task: the plugin “{{pluginId}}” stopped it ({{detail}}). Disable that plugin under Settings → Plugins, then try again.",+ "createFailedPathTooLong": "Couldn’t create the task: the destination path is {{length}} characters, over the Windows limit of {{limit}}. Choose a shorter save folder or file name.","parseFailed": "Failed to parse torrent file.","urlsCount_one": "{{count}} URL","urlsCount_other": "{{count}} URLs",@@ -1113,7 +1115,8 @@"renameDirFailed": "Failed to rename the directory: {{cause}}","pluginChainAborted": "Plugin chain aborted: {{cause}}","magnetCleanupQuarantined": "Magnet metadata cleanup is quarantined",- "muxFailed": "Failed to mux the downloaded media"+ "muxFailed": "Failed to mux the downloaded media",+ "pathTooLong": "The path is {{length}} characters; Windows allows {{limit}}"},"reason": {"unknown": "Download failed",@@ -1123,6 +1126,7 @@"timeout": "Download timed out","diskFull": "Disk is full","fileWriteError": "Could not write the file",+ "pathTooLong": "File path is too long for Windows","checksumMismatch": "File checksum did not match","tooManyRedirects": "Too many redirects","serverError": "Server returned an error",@@ -1136,6 +1140,7 @@"networkError": "Check your network connection, then retry","timeout": "Check your connection speed and stability, then retry","fileWriteError": "Check folder permissions and available disk space, then retry",+ "pathTooLong": "Shorten the save folder or the file name, or enable Windows long path support, then retry","checksumMismatch": "The downloaded file may be corrupted; re-download to verify it","tooManyRedirects": "The source link may be broken; try a different link","btMetadataFailed": "Check the magnet link or add more trackers, then retry"diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex f1bed64a..41fd0afa 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -951,6 +951,8 @@"clearSelection": "清除选择","createFailed": "创建下载任务失败。","createFailedWithReason": "创建下载任务失败:{{reason}}",+ "createFailedByPlugin": "创建任务失败:插件「{{pluginId}}」中断了任务创建({{detail}})。可在「设置 → 插件」中停用该插件后重试。",+ "createFailedPathTooLong": "创建任务失败:目标路径长 {{length}} 个字符,超出 Windows 上限 {{limit}}。请改用更短的保存目录或文件名。","parseFailed": "解析种子文件失败。","urlsCount_other": "{{count}} 个 URL","urlsWithInvalid": "{{valid}} 个有效,{{invalid}} 个无效",@@ -1099,7 +1101,8 @@"renameDirFailed": "重命名目录失败:{{cause}}","pluginChainAborted": "插件链已中止:{{cause}}","magnetCleanupQuarantined": "磁力链接元数据清理被隔离",- "muxFailed": "混流下载的媒体文件失败"+ "muxFailed": "混流下载的媒体文件失败",+ "pathTooLong": "路径长度 {{length}} 个字符,Windows 上限为 {{limit}} 个字符"},"reason": {"unknown": "下载失败",@@ -1109,6 +1112,7 @@"timeout": "下载超时","diskFull": "磁盘空间不足","fileWriteError": "无法写入文件",+ "pathTooLong": "文件路径超出 Windows 长度上限","checksumMismatch": "文件校验失败","tooManyRedirects": "重定向次数过多","serverError": "服务器返回错误",@@ -1122,6 +1126,7 @@"networkError": "检查网络连接后重试","timeout": "检查网络连接速度和稳定性后重试","fileWriteError": "检查文件夹权限和磁盘空间后重试",+ "pathTooLong": "缩短保存目录或文件名后重试;也可在 Windows 中启用长路径支持","checksumMismatch": "下载的文件可能已损坏,请重新下载以校验","tooManyRedirects": "该链接可能已失效,请尝试更换下载链接","btMetadataFailed": "检查磁力链接或添加更多 Tracker 后重试"diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 9ee945aa..6c0db05d 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -951,6 +951,8 @@"clearSelection": "清除選取項目","createFailed": "無法建立下載任務。","createFailedWithReason": "無法建立下載任務:{{reason}}",+ "createFailedByPlugin": "建立任務失敗:外掛「{{pluginId}}」中斷了任務建立({{detail}})。可在「設定 → 外掛」中停用該外掛後重試。",+ "createFailedPathTooLong": "建立任務失敗:目標路徑長 {{length}} 個字元,超出 Windows 上限 {{limit}}。請改用更短的儲存目錄或檔名。","parseFailed": "無法解析 Torrent 檔案。","urlsCount_other": "{{count}} 個 URL","urlsWithInvalid": "{{valid}} 個有效,{{invalid}} 個無效",@@ -1099,7 +1101,8 @@"renameDirFailed": "無法重新命名目錄:{{cause}}","pluginChainAborted": "外掛程式鏈已中止:{{cause}}","magnetCleanupQuarantined": "Magnet 中繼資料清理作業已隔離",- "muxFailed": "無法合併已下載的媒體"+ "muxFailed": "無法合併已下載的媒體",+ "pathTooLong": "路徑長度 {{length}} 個字元,Windows 上限為 {{limit}} 個字元"},"reason": {"unknown": "下載失敗",@@ -1109,6 +1112,7 @@"timeout": "下載逾時","diskFull": "磁碟空間已滿","fileWriteError": "無法寫入檔案",+ "pathTooLong": "檔案路徑超出 Windows 長度上限","checksumMismatch": "檔案總和檢查不符","tooManyRedirects": "重新導向次數過多","serverError": "伺服器傳回錯誤",@@ -1122,6 +1126,7 @@"networkError": "請檢查網路連線,然後重試","timeout": "請檢查連線速度與穩定性,然後重試","fileWriteError": "請檢查資料夾權限與可用磁碟空間,然後重試",+ "pathTooLong": "縮短儲存目錄或檔名後重試;也可在 Windows 中啟用長路徑支援","checksumMismatch": "下載的檔案可能損毀,請重新下載以驗證","tooManyRedirects": "來源連結可能失效,請嘗試其他連結","btMetadataFailed": "請檢查 Magnet 連結或新增更多 Tracker,然後重試"diff --git a/src/shared/task-error/descriptor.ts b/src/shared/task-error/descriptor.tsindex 0d20d644..a475665f 100644--- a/src/shared/task-error/descriptor.ts+++ b/src/shared/task-error/descriptor.ts@@ -51,6 +51,7 @@ const ERROR_REASON_LEAF: Readonly<Record<DownloadErrorCode, string>> = {DL_TIMEOUT: 'timeout',DL_DISK_FULL: 'diskFull',DL_FILE_WRITE_ERROR: 'fileWriteError',+ DL_PATH_TOO_LONG: 'pathTooLong',DL_CHECKSUM_MISMATCH: 'checksumMismatch',DL_TOO_MANY_REDIRECTS: 'tooManyRedirects',DL_SERVER_ERROR: 'serverError',diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.tsindex ddb8cae4..fd857c63 100644--- a/tests/check-third-party-notices.test.ts+++ b/tests/check-third-party-notices.test.ts@@ -470,9 +470,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.14')+ expect(notice).toContain('1.37.0-motrix.15')expect(notice).toContain(- 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.14'+ 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.15')expect(notice).toContain('GPL-2.0-or-later')expect(notice).toContain('THIRD_PARTY_LICENSES/aria2-COPYING')diff --git a/tests/generate-third-party-notices.test.ts b/tests/generate-third-party-notices.test.tsindex b34bf4a9..9fc9fb4f 100644--- a/tests/generate-third-party-notices.test.ts+++ b/tests/generate-third-party-notices.test.ts@@ -164,7 +164,7 @@ describe('third-party notice generator', () => {expect(bundle.packageCount).toBeGreaterThan(100)expect(inventory).toContain('| @xyflow/react | 12.11.6 |')- expect(inventory).toContain('| aria2 | 1.37.0-motrix.14 |')+ expect(inventory).toContain('| aria2 | 1.37.0-motrix.15 |')expect(inventory).toContain('| motrix.filename-template | 1.1.1 |')expect(inventory).toContain('Apple San Francisco tray font')expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')@@ -257,7 +257,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.14 |')+ expect(serverInventory).toContain('| aria2 | 1.37.0-motrix.15 |')expect(serverInventory).toContain('| motrix.filename-template | 1.1.1 |')expect(serverInventory).not.toContain('| Electron |')