Skip to content

A full-featured download manager.

fix(engine): handle official aria2 limits and task adoption races (#1923)

Dr_rOota4f2763fc9da
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml
index fe76e7f2..f7ca61c0 100644
--- a/.github/workflows/flatpak.yml
+++ b/.github/workflows/flatpak.yml
@@ -299,7 +299,7 @@ jobs:
-path "*/native-messaging-hosts/*" \
\) -print -quit)"
output="$("$aria2c" --version)"
- printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.6"
+ printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.10"
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.md
index e91ad52c..9d37f781 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -83,8 +83,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.6
-- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.6>
+- **Version:** 1.37.0-motrix.10
+- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.10>
- **License:** GNU General Public License v2.0 or later (`GPL-2.0-or-later`)
- **Full license text:** `THIRD_PARTY_LICENSES/aria2-COPYING`
- **OpenSSL exception / notice:**
diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.md
index 4a236b11..3b58c1ba 100644
--- a/THIRD_PARTY_NOTICES.zh-CN.md
+++ b/THIRD_PARTY_NOTICES.zh-CN.md
@@ -71,8 +71,8 @@ src/renderer/routes/settings/icons/[email protected]
桌面版随应用打包 `aria2c` 可执行文件,版本由 `scripts/engine.lock.json` 固定:
-- **版本:** 1.37.0-motrix.6
-- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.6>
+- **版本:** 1.37.0-motrix.10
+- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.10>
- **许可证:** GNU General Public License v2.0 or later(`GPL-2.0-or-later`)
- **完整许可证文本:** `THIRD_PARTY_LICENSES/aria2-COPYING`
- **OpenSSL 例外条款 / 声明:**
diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.yml
index 21c34e21..0c27b880 100644
--- a/flatpak/app.motrix.native.yml
+++ b/flatpak/app.motrix.native.yml
@@ -101,7 +101,7 @@ modules:
set -e
output="$(src/aria2c --version)"
printf '%s\n' "$output"
- printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.6'
+ printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.10'
for feature in \
'Async DNS' \
'BitTorrent' \
@@ -123,8 +123,8 @@ modules:
sources:
- type: git
url: https://github.com/motrixapp/aria2.git
- tag: v1.37.0-motrix.6
- commit: 7e3efdb0db9678efdc93cab6007125286d06bff1
+ tag: v1.37.0-motrix.10
+ commit: 9c48eda5343ee9060ce2136494bdbe3c0a892e8c
x-checker-data:
type: git
tag-pattern: ^v([\d.]+-motrix\.\d+)$
@@ -136,9 +136,9 @@ modules:
commands:
- |
sed -i -E \
- 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.6]/' \
+ 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.10]/' \
configure.ac
- grep -qF 'AC_INIT([aria2],[1.37.0-motrix.6]' configure.ac
+ grep -qF 'AC_INIT([aria2],[1.37.0-motrix.10]' configure.ac
- type: script
dest-filename: autogen.sh
commands:
diff --git a/scripts/engine.lock.json b/scripts/engine.lock.json
index 15e9b98c..3c49b4b8 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.6",
- "version": "1.37.0-motrix.6",
+ "tag": "v1.37.0-motrix.10",
+ "version": "1.37.0-motrix.10",
"assets": {
"darwin-arm64": {
- "file": "aria2c-1.37.0-motrix.6-darwin-arm64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.10-darwin-arm64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "8f47de3ea619cb635b4c7bf198569327f2c4546e5573261423b832e3cd7b9dcc",
- "binarySha256": "0b550e3f33c58131ef844c6de8c9893d7044c152a1615298acd323f64304e59c"
+ "archiveSha256": "c4848c92f926d53a445e847b93fb34f3c536ecf2d98861857eb72ff1ec5e935a",
+ "binarySha256": "9c1f5ee711ad8657eef53c8392398c5be961ee1c00afa9692bf282554381e21e"
},
"darwin-x64": {
- "file": "aria2c-1.37.0-motrix.6-darwin-x64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.10-darwin-x64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "637a5f0568aea2f4704fdc6f008e8a08931fdcf48a3b71c19df38f69daee1440",
- "binarySha256": "8ec726fd22dc794280ead836898f2336a3e6128271f4397aec545e9e3cdc6550"
+ "archiveSha256": "69ce3fa0895ed4687f188892e6f523d6a1d304cb4a6cb5d806bbb88cf411dc5a",
+ "binarySha256": "437c40c24b71d227a1e47828194ebbe4bc3b0e98fb424513e6fa4e9c22cb318b"
},
"win32-x64": {
- "file": "aria2c-1.37.0-motrix.6-win32-x64.zip",
+ "file": "aria2c-1.37.0-motrix.10-win32-x64.zip",
"bin": "aria2c.exe",
- "archiveSha256": "ef83499b161fd03db86ecbf96da29732f73b6679a541951880a65957f00a4015",
- "binarySha256": "effb57cd154d07443a271aff5700f4e37abec4b44ff46f380b68d9ddb792eebb"
+ "archiveSha256": "57fec29fac25e40d092aafa12e0d0e0f91766851647354befa024e33a076409d",
+ "binarySha256": "ae8fe4656ebd2f84a4027f67619e6335e2de766ae3e8e729e6b2527ed2455b9a"
},
"win32-ia32": {
- "file": "aria2c-1.37.0-motrix.6-win32-ia32.zip",
+ "file": "aria2c-1.37.0-motrix.10-win32-ia32.zip",
"bin": "aria2c.exe",
- "archiveSha256": "09d2ca8adac14b3345877e51e3b01a8de90f539493d1424425f2c2191f681ed9",
- "binarySha256": "003a8a2df16601b70732381a00f3ba9592d585fcf40fd06d782dced445ca4e4b"
+ "archiveSha256": "68dde2d1265e8c02fb99df0d60c54b0d9920726af485fd639cb2adfc3a6d6b0c",
+ "binarySha256": "04c1c12cb1bc960305b6882b223b85890b378915fdf09d63548a8f9c68617a6b"
},
"linux-x64": {
- "file": "aria2c-1.37.0-motrix.6-linux-x64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.10-linux-x64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "ad40cb968223b1fcd1218713d3a49f251c15d658a3365eac35bc8faef3588d62",
- "binarySha256": "0d6ff44de65427e46f16d7d94de19e56925523600269b75a74c56c890624d21f"
+ "archiveSha256": "7e9ed95e1f084d6b37dc720ceaec08d45c1493f8561190930404d905b6bd9bce",
+ "binarySha256": "f3068ee6db15c0448ab1a4509d2da193023dbc7f36abe08621e30732737e3d6b"
},
"linux-arm64": {
- "file": "aria2c-1.37.0-motrix.6-linux-arm64.tar.gz",
+ "file": "aria2c-1.37.0-motrix.10-linux-arm64.tar.gz",
"bin": "aria2c",
- "archiveSha256": "11b11f2f8c717ab8cccb08670677ba2ae12d6d4c98a33fcaaed407d818e7c06b",
- "binarySha256": "296425c961369db3e17dc0e58cdc04f486bf345dd734fbbaf94d980531f06147"
+ "archiveSha256": "a106dd9c65938f922ae2e63f0a1864aac3881f9191dd1cf995316d1eea96ade2",
+ "binarySha256": "6a05f94ae5d1765970bf4a142741d777f9f2f19108efae39c4f7477876a9def5"
},
"linux-arm": {
- "file": "aria2c-1.37.0-motrix.6-linux-armv7l.tar.gz",
+ "file": "aria2c-1.37.0-motrix.10-linux-armv7l.tar.gz",
"bin": "aria2c",
- "archiveSha256": "b5d4d90c09e6f5d774c19a23db731acc747ad9688d77104a7fd076fbba0277fa",
- "binarySha256": "d8872febda2f252e2111c951e273e7ca36af9ccbd2a5aa35a9c8003149582278"
+ "archiveSha256": "95d3c097bb8a38eb33314d172e1a3b95d86c182333d02484c1ffb4450e4573be",
+ "binarySha256": "3aae37cf4beec3beeff80b9c0a3a18ca5ce87e454fa59a551dad3de304ff5786"
}
}
}
diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjs
index e3257e38..4bf2a433 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.6 — portable Linux OpenSSL trust-store discovery
- commit: '7e3efdb0db9678efdc93cab6007125286d06bff1',
+ // v1.37.0-motrix.10 — current Motrix aria2 fork release
+ commit: '9c48eda5343ee9060ce2136494bdbe3c0a892e8c',
})
const PNPM_SOURCE = Object.freeze({
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.ts
index 8b8d5dcf..58cda43e 100644
--- a/src/core/engine/aria2/aria2-adapter.test.ts
+++ b/src/core/engine/aria2/aria2-adapter.test.ts
@@ -1,4 +1,5 @@
import { ErrorCode } from '@shared/errors'
+import type { EngineFeatureReport } from '@shared/types/engine'
import type { Mock } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import type { CreateDownloadParams } from '../engine-adapter'
@@ -43,6 +44,20 @@ function createMockRpc(): Aria2RpcClient {
} as unknown as Aria2RpcClient
}
+function featureReport(
+ overrides: Partial<EngineFeatureReport> = {}
+): EngineFeatureReport {
+ return {
+ version: '1.37.0-motrix.10',
+ features: ['SQLite3-Persistence'],
+ hasSqlitePersistence: true,
+ hasBtSeedUnverified: true,
+ hasBtSaveMetadata: true,
+ hasMoveStorage: false,
+ ...overrides,
+ }
+}
+
// ─── Fixtures ───────────────────────────────────────────────
const RAW_HTTP_ACTIVE: Aria2RawStatus = {
@@ -484,6 +499,120 @@ describe('Aria2Adapter', () => {
)
})
+ it('pre-caps connection options after the shell detects official aria2', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')
+ const adapter = new Aria2Adapter(rpc)
+ adapter.setFeatureReport(
+ featureReport({
+ version: '1.37.0',
+ features: [],
+ hasSqlitePersistence: false,
+ })
+ )
+
+ await adapter.createDownload({
+ uris: ['u'],
+ saveDir: '/d',
+ connections: 64,
+ })
+
+ expect(rpc.addUri).toHaveBeenCalledWith(
+ ['u'],
+ expect.objectContaining({
+ split: '16',
+ 'max-connection-per-server': '16',
+ })
+ )
+ })
+
+ it('preserves high connection options for the Motrix fork', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')
+ const adapter = new Aria2Adapter(rpc)
+ adapter.setFeatureReport(featureReport())
+
+ await adapter.createDownload({
+ uris: ['u'],
+ saveDir: '/d',
+ connections: 64,
+ })
+
+ expect(rpc.addUri).toHaveBeenCalledWith(
+ ['u'],
+ expect.objectContaining({
+ split: '64',
+ 'max-connection-per-server': '64',
+ })
+ )
+ })
+
+ it('retries errorCode=28 once at 16 and remembers the discovered limit', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri)
+ .mockRejectedValueOnce(
+ new Error(
+ 'errorCode=28: max-connection-per-server must be between 1 and 16'
+ )
+ )
+ .mockResolvedValueOnce('gid-first')
+ .mockResolvedValueOnce('gid-second')
+ const adapter = new Aria2Adapter(rpc)
+
+ await expect(
+ adapter.createDownload({
+ uris: ['first'],
+ saveDir: '/d',
+ connections: 64,
+ })
+ ).resolves.toBe('gid-first')
+ await adapter.createDownload({
+ uris: ['second'],
+ saveDir: '/d',
+ connections: 64,
+ })
+
+ expect(rpc.addUri).toHaveBeenNthCalledWith(
+ 1,
+ ['first'],
+ expect.objectContaining({
+ split: '64',
+ 'max-connection-per-server': '64',
+ })
+ )
+ expect(rpc.addUri).toHaveBeenNthCalledWith(
+ 2,
+ ['first'],
+ expect.objectContaining({
+ split: '16',
+ 'max-connection-per-server': '16',
+ })
+ )
+ expect(rpc.addUri).toHaveBeenNthCalledWith(
+ 3,
+ ['second'],
+ expect.objectContaining({
+ split: '16',
+ 'max-connection-per-server': '16',
+ })
+ )
+ })
+
+ it('does not retry unrelated addUri failures', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockRejectedValue(new Error('connection refused'))
+ const adapter = new Aria2Adapter(rpc)
+
+ await expect(
+ adapter.createDownload({
+ uris: ['u'],
+ saveDir: '/d',
+ connections: 64,
+ })
+ ).rejects.toThrow('connection refused')
+ expect(rpc.addUri).toHaveBeenCalledOnce()
+ })
+
it('auto profile applies per-file tuning without sending global disk-cache', async () => {
const rpc = createMockRpc()
vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')
diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.ts
index 8216cbdd..c8fe18f0 100644
--- a/src/core/engine/aria2/aria2-adapter.ts
+++ b/src/core/engine/aria2/aria2-adapter.ts
@@ -1,3 +1,4 @@
+import { getLogger } from '@core/logger'
import { AppError, ErrorCode } from '@shared/errors'
import type {
EngineCapability,
@@ -22,7 +23,7 @@ import type {
} from '../engine-adapter'
import type { Aria2RpcClient } from './aria2-rpc-client'
import { recommend } from './aria2-tuning'
-import { isNotFoundError } from './error-utils'
+import { isConnectionLimitRangeError, isNotFoundError } from './error-utils'
/**
* Per-multicall cap for removeDownloadResults. One unbounded batch must
@@ -35,7 +36,12 @@ import { isNotFoundError } from './error-utils'
*/
const REMOVE_RESULT_CHUNK_SIZE = 100
-import { buildFeatureReport, hasDurableRemoveSemantics } from './feature-report'
+import {
+ buildFeatureReport,
+ hasDurableRemoveSemantics,
+ isMotrixFork,
+ STANDARD_ARIA2_CONNECTION_LIMIT,
+} from './feature-report'
import {
translateGlobalStat,
translatePeer,
@@ -44,6 +50,7 @@ import {
} from './translate'
export class Aria2Adapter implements EngineAdapter {
+ private readonly log = getLogger('aria2-adapter')
private capability: EngineCapability = {
http: true,
ftp: true,
@@ -59,6 +66,7 @@ export class Aria2Adapter implements EngineAdapter {
hasBtSaveMetadata: false,
hasMoveStorage: false,
}
+ private connectionOptionLimit: number | null = null
private btCompleteHandlers: Array<(engineTaskId: string) => void> = []
private downloadCompleteHandlers: Array<(engineTaskId: string) => void> = []
@@ -159,6 +167,55 @@ export class Aria2Adapter implements EngineAdapter {
*/
setFeatureReport(report: EngineFeatureReport): void {
this.featureReport = report
+ this.connectionOptionLimit = isMotrixFork(report)
+ ? null
+ : STANDARD_ARIA2_CONNECTION_LIMIT
+ }
+
+ private capConnectionOptions(
+ options: Record<string, string | string[]>,
+ limit: number
+ ): Record<string, string | string[]> {
+ const compatible = { ...options }
+ for (const key of ['split', 'max-connection-per-server']) {
+ const value = compatible[key]
+ if (typeof value !== 'string') continue
+ const parsed = Number.parseInt(value, 10)
+ if (Number.isFinite(parsed) && parsed > limit) {
+ compatible[key] = String(limit)
+ }
+ }
+ return compatible
+ }
+
+ private async addUriWithConnectionFallback(
+ uris: string[],
+ options: Record<string, string | string[]>
+ ): Promise<string> {
+ const firstOptions =
+ this.connectionOptionLimit === null
+ ? options
+ : this.capConnectionOptions(options, this.connectionOptionLimit)
+
+ try {
+ return await this.rpc.addUri(uris, firstOptions)
+ } catch (error) {
+ const fallbackOptions = this.capConnectionOptions(
+ firstOptions,
+ STANDARD_ARIA2_CONNECTION_LIMIT
+ )
+ const changed = Object.keys(fallbackOptions).some(
+ (key) => fallbackOptions[key] !== firstOptions[key]
+ )
+ if (!changed || !isConnectionLimitRangeError(error)) throw error
+
+ this.connectionOptionLimit = STANDARD_ARIA2_CONNECTION_LIMIT
+ this.log.warn(
+ { err: error },
+ 'aria2 rejected connection options; retrying with compatibility limit'
+ )
+ return this.rpc.addUri(uris, fallbackOptions)
+ }
}
async createDownload(params: CreateDownloadParams): Promise<string> {
@@ -242,7 +299,10 @@ export class Aria2Adapter implements EngineAdapter {
options.gid = requestedGid
}
- const actualGid = await this.rpc.addUri(params.uris, options)
+ const actualGid = await this.addUriWithConnectionFallback(
+ params.uris,
+ options
+ )
if (
requestedGid !== undefined &&
actualGid.toLowerCase() !== requestedGid.toLowerCase()
diff --git a/src/core/engine/aria2/aria2-process-manager.test.ts b/src/core/engine/aria2/aria2-process-manager.test.ts
index c8ee94bd..27f05aa3 100644
--- a/src/core/engine/aria2/aria2-process-manager.test.ts
+++ b/src/core/engine/aria2/aria2-process-manager.test.ts
@@ -58,7 +58,7 @@ function createMockChildProcess() {
// ─── Standard aria2 --version output ─────────────────────────
-const ARIA2_VERSION_OUTPUT = `aria2 version 1.37.0
+const ARIA2_VERSION_OUTPUT = `aria2 version 1.37.0-motrix.10
Copyright (C) 2006, 2019 Tatsuhiro Tsujikawa
This program is free software; you can redistribute it and/or modify
@@ -112,7 +112,7 @@ describe('Aria2ProcessManager', () => {
['--version'],
expect.any(Function)
)
- expect(report.version).toBe('1.37.0')
+ expect(report.version).toBe('1.37.0-motrix.10')
expect(report.features).toContain('BitTorrent')
expect(report.features).toContain('SQLite3-Persistence')
expect(report.hasSqlitePersistence).toBe(true)
diff --git a/src/core/engine/aria2/error-utils.test.ts b/src/core/engine/aria2/error-utils.test.ts
new file mode 100644
index 00000000..b6fcee17
--- /dev/null
+++ b/src/core/engine/aria2/error-utils.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { isConnectionLimitRangeError } from './error-utils'
+
+describe('isConnectionLimitRangeError', () => {
+ it('recognizes official aria2 connection ceiling failures', () => {
+ expect(
+ isConnectionLimitRangeError(
+ new Error(
+ 'JSON-RPC errorCode=28: max-connection-per-server must be between 1 and 16'
+ )
+ )
+ ).toBe(true)
+ expect(
+ isConnectionLimitRangeError(
+ 'errorCode=28: The integer must be between 1 and 16.'
+ )
+ ).toBe(true)
+ })
+
+ it('does not classify unrelated option or transport failures', () => {
+ expect(
+ isConnectionLimitRangeError(
+ 'errorCode=28: max-tries must be between 1 and 16'
+ )
+ ).toBe(true)
+ expect(
+ isConnectionLimitRangeError(
+ 'max-connection-per-server must be between 1 and 32'
+ )
+ ).toBe(false)
+ expect(isConnectionLimitRangeError('connection refused')).toBe(false)
+ })
+})
diff --git a/src/core/engine/aria2/error-utils.ts b/src/core/engine/aria2/error-utils.ts
index 558e91f1..3493c205 100644
--- a/src/core/engine/aria2/error-utils.ts
+++ b/src/core/engine/aria2/error-utils.ts
@@ -8,3 +8,19 @@ export function isNotFoundError(err: unknown): boolean {
const msg = err instanceof Error ? err.message : String(err)
return /\bGID\b[^\r\n]*\b(?:is\s+)?not\s+found\b/i.test(msg)
}
+
+/**
+ * Official aria2 reports option validation failures as errorCode=28. Keep the
+ * classifier narrow so unrelated option errors are never retried silently.
+ */
+export function isConnectionLimitRangeError(err: unknown): boolean {
+ const message = err instanceof Error ? err.message : String(err)
+ const isExpectedRange = /must\s+be\s+between\s+1\s+and\s+16\b/i.test(message)
+ const identifiesConnectionOption =
+ /max-connection-per-server|(?:^|\W)split(?:\W|$)/i.test(message)
+ const identifiesAria2OptionError = /errorCode\s*=\s*28\b/i.test(message)
+ return (
+ isExpectedRange &&
+ (identifiesConnectionOption || identifiesAria2OptionError)
+ )
+}
diff --git a/src/core/engine/aria2/feature-report.test.ts b/src/core/engine/aria2/feature-report.test.ts
index 6bcb5b8b..5dad6b3d 100644
--- a/src/core/engine/aria2/feature-report.test.ts
+++ b/src/core/engine/aria2/feature-report.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
buildFeatureReport,
hasDurableRemoveSemantics,
+ isMotrixFork,
semverGte,
} from './feature-report'
@@ -49,6 +50,20 @@ describe('semverGte', () => {
})
})
+describe('isMotrixFork', () => {
+ it('requires both the Motrix version suffix and fork-only persistence feature', () => {
+ expect(
+ isMotrixFork(
+ buildFeatureReport('1.37.0-motrix.10', ['SQLite3-Persistence'])
+ )
+ ).toBe(true)
+ expect(
+ isMotrixFork(buildFeatureReport('1.37.0', ['SQLite3-Persistence']))
+ ).toBe(false)
+ expect(isMotrixFork(buildFeatureReport('1.37.0-motrix.10', []))).toBe(false)
+ })
+})
+
describe('hasDurableRemoveSemantics', () => {
it('trusts motrix fork 1.37.0-motrix.3 and later', () => {
expect(hasDurableRemoveSemantics('1.37.0-motrix.3')).toBe(true)
diff --git a/src/core/engine/aria2/feature-report.ts b/src/core/engine/aria2/feature-report.ts
index 984914af..29be5dc7 100644
--- a/src/core/engine/aria2/feature-report.ts
+++ b/src/core/engine/aria2/feature-report.ts
@@ -6,6 +6,23 @@ import {
// aria2 gained --bt-seed-unverified and --bt-save-metadata in 1.37.0.
const BT_FEATURES_MIN_VERSION = '1.37.0'
+/** Official aria2's per-task connection ceiling. */
+export const STANDARD_ARIA2_CONNECTION_LIMIT = 16
+
+/**
+ * Identify the Motrix fork from the pre-spawn `aria2c --version` report.
+ * Both markers are required: the version suffix establishes lineage and the
+ * feature token confirms the fork-only persistence capability is present.
+ */
+export function isMotrixFork(
+ report: Pick<EngineFeatureReport, 'version' | 'hasSqlitePersistence'>
+): boolean {
+ return (
+ /^\d+\.\d+\.\d+-motrix\.\d+$/i.test(report.version) &&
+ report.hasSqlitePersistence
+ )
+}
+
/**
* Single source for turning an aria2 (version, enabled-features) pair into an
* EngineFeatureReport. Both the process-probe path (Aria2ProcessManager,
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index c5e03452..360f049d 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -44,7 +44,7 @@ vi.mock('./port-check', () => ({
// ─── Mock factories ─────────────────────────────────────────
const FEATURE_REPORT: EngineFeatureReport = {
- version: '1.37.0',
+ version: '1.37.0-motrix.10',
features: ['Async DNS', 'BitTorrent', 'SQLite3-Persistence'],
hasSqlitePersistence: true,
hasBtSeedUnverified: false,
@@ -250,6 +250,99 @@ describe('EngineSupervisor', () => {
expect(adapter.setFeatureReport).toHaveBeenCalledWith(FEATURE_REPORT)
})
+ it('detects an official binary before spawn and starts with compatibility limits', async () => {
+ const officialReport: EngineFeatureReport = {
+ ...FEATURE_REPORT,
+ version: '1.37.0',
+ features: ['Async DNS', 'BitTorrent'],
+ hasSqlitePersistence: false,
+ }
+ vi.mocked(processManager.probe).mockResolvedValue(officialReport)
+ const configured = settings.getEngine()
+ vi.mocked(settings.getEngine).mockReturnValue({
+ ...configured,
+ performanceProfile: 'custom',
+ maxConnectionPerServer: 64,
+ split: 32,
+ })
+ const warning = vi.fn()
+ eventBus.on(Events.EngineCompatibilityWarning, warning)
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(warning).toHaveBeenCalledWith({
+ version: '1.37.0',
+ connectionLimit: 16,
+ })
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ maxConnectionPerServer: 16,
+ split: 16,
+ }),
+ false,
+ expect.anything(),
+ expect.anything()
+ )
+ expect(rpcClient.getVersion).not.toHaveBeenCalled()
+ expect(settings.update).toHaveBeenCalledWith({
+ engine: {
+ performanceProfile: 'custom',
+ maxConnectionPerServer: 16,
+ split: 16,
+ },
+ })
+ expect(
+ vi.mocked(processManager.probe).mock.invocationCallOrder[0]
+ ).toBeLessThan(
+ vi.mocked(processManager.spawn).mock.invocationCallOrder[0]
+ )
+ })
+
+ it('keeps starting with runtime limits if persisting compatibility settings fails', async () => {
+ vi.mocked(processManager.probe).mockResolvedValue({
+ ...FEATURE_REPORT,
+ version: '1.37.0',
+ features: ['Async DNS', 'BitTorrent'],
+ hasSqlitePersistence: false,
+ })
+ vi.mocked(settings.update).mockRejectedValue(new Error('disk full'))
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(supervisor.getState()).toBe(EngineState.Ready)
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ maxConnectionPerServer: 16,
+ split: 16,
+ }),
+ false,
+ expect.anything(),
+ expect.anything()
+ )
+ })
+
+ it('keeps Motrix fork connection settings above the official ceiling', async () => {
+ const configured = settings.getEngine()
+ vi.mocked(settings.getEngine).mockReturnValue({
+ ...configured,
+ performanceProfile: 'custom',
+ maxConnectionPerServer: 64,
+ split: 32,
+ })
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ maxConnectionPerServer: 64,
+ split: 32,
+ }),
+ true,
+ expect.anything(),
+ expect.anything()
+ )
+ })
+
it('does not overwrite persisted tuning settings during engine start', async () => {
await supervisor.start('/usr/bin/aria2c')
expect(settings.update).not.toHaveBeenCalled()
@@ -923,6 +1016,44 @@ describe('EngineSupervisor', () => {
'save-session-interval': '30',
})
})
+
+ it('caps hot connection changes for a detected official aria2 binary', async () => {
+ vi.mocked(processManager.probe).mockResolvedValue({
+ ...FEATURE_REPORT,
+ version: '1.37.0',
+ features: ['Async DNS', 'BitTorrent'],
+ hasSqlitePersistence: false,
+ })
+ await supervisor.start('/usr/bin/aria2c')
+ vi.mocked(rpcClient.changeGlobalOption).mockClear()
+ vi.mocked(settings.update).mockClear()
+ const settingsValue = settings.getEngine()
+
+ await supervisor.applyEngineSettings(
+ {
+ ...settingsValue,
+ maxConnectionPerServer: 8,
+ split: 8,
+ },
+ {
+ ...settingsValue,
+ maxConnectionPerServer: 64,
+ split: 32,
+ }
+ )
+
+ expect(rpcClient.changeGlobalOption).toHaveBeenCalledWith({
+ 'max-connection-per-server': '16',
+ split: '16',
+ })
+ expect(settings.update).toHaveBeenCalledWith({
+ engine: {
+ performanceProfile: 'custom',
+ maxConnectionPerServer: 16,
+ split: 16,
+ },
+ })
+ })
})
describe('applyProxyChange', () => {
diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.ts
index 4487b507..080e506b 100644
--- a/src/core/engine/engine-supervisor.ts
+++ b/src/core/engine/engine-supervisor.ts
@@ -4,6 +4,7 @@ import { ENGINE_RPC_PORT } from '@shared/constants'
import { AppError, ErrorCode } from '@shared/errors'
import { Events } from '@shared/protocol/events'
import {
+ type EngineCompatibilityWarningPayload,
type EngineDiagnosticReport,
type EngineFailureInfo,
type EngineFailurePayload,
@@ -27,6 +28,10 @@ import type { Aria2ProcessManager } from './aria2/aria2-process-manager'
import type { Aria2RpcClient } from './aria2/aria2-rpc-client'
import type { Aria2TrustStore } from './aria2/aria2-trust-store'
import { recommend } from './aria2/aria2-tuning'
+import {
+ isMotrixFork,
+ STANDARD_ARIA2_CONNECTION_LIMIT,
+} from './aria2/feature-report'
import { checkPort, findAvailablePort } from './port-check'
const log = getLogger('engine')
@@ -184,20 +189,74 @@ export class EngineSupervisor {
previous: EngineSettings,
next: EngineSettings
): Promise<void> {
+ const persistedNext = await this.persistCompatibilityLimits(next)
if (this.state !== EngineState.Ready) return
+ const compatiblePrevious = this.applyCompatibilityLimits(previous)
+ const compatibleNext = this.applyCompatibilityLimits(persistedNext)
const params: Record<string, string> = {}
for (const [key, option] of Object.entries(HOT_ENGINE_OPTIONS) as Array<
[keyof typeof HOT_ENGINE_OPTIONS, string]
>) {
- if (previous[key] !== next[key]) {
- params[option] = String(next[key])
+ if (compatiblePrevious[key] !== compatibleNext[key]) {
+ params[option] = String(compatibleNext[key])
}
}
if (Object.keys(params).length === 0) return
await this.rpcClient.changeGlobalOption(params)
}
+ private applyCompatibilityLimits(settings: EngineSettings): EngineSettings {
+ const report = this.featureReport
+ if (!report || isMotrixFork(report)) return settings
+
+ return {
+ ...settings,
+ maxConnectionPerServer: Math.min(
+ settings.maxConnectionPerServer,
+ STANDARD_ARIA2_CONNECTION_LIMIT
+ ),
+ split: Math.min(settings.split, STANDARD_ARIA2_CONNECTION_LIMIT),
+ }
+ }
+
+ private async persistCompatibilityLimits(
+ settings: EngineSettings
+ ): Promise<EngineSettings> {
+ const compatible = this.applyCompatibilityLimits(settings)
+ if (
+ compatible.maxConnectionPerServer === settings.maxConnectionPerServer &&
+ compatible.split === settings.split
+ ) {
+ return settings
+ }
+
+ const persisted: EngineSettings = {
+ ...compatible,
+ // Named profiles re-apply their fixed values during validation. Move
+ // the adjusted settings to custom so 16 remains the durable truth.
+ performanceProfile: 'custom',
+ }
+ try {
+ await this.settingsManager.update({
+ engine: {
+ performanceProfile: persisted.performanceProfile,
+ maxConnectionPerServer: persisted.maxConnectionPerServer,
+ split: persisted.split,
+ },
+ })
+ } catch (error) {
+ // A settings write failure must not revive the original startup crash.
+ // The in-memory compatibility values still let this engine run safely.
+ log.warn(
+ { err: error },
+ 'failed to persist aria2 compatibility limits; using runtime limits'
+ )
+ return compatible
+ }
+ return persisted
+ }
+
private async resolveRuntimeEngineSettings(
settings: EngineSettings
): Promise<EngineSettings> {
@@ -296,6 +355,13 @@ export class EngineSupervisor {
// and nothing calls adapter.connect() in production — inject the report
// we just probed so the gate reflects the real engine version.
this.adapter.setFeatureReport(featureReport)
+ if (!isMotrixFork(featureReport)) {
+ const payload: EngineCompatibilityWarningPayload = {
+ version: featureReport.version,
+ connectionLimit: STANDARD_ARIA2_CONNECTION_LIMIT,
+ }
+ this.eventBus.emit(Events.EngineCompatibilityWarning, payload)
+ }
// Step 2: Ensure config and build args
phase = 'config'
@@ -305,8 +371,10 @@ export class EngineSupervisor {
if (this.stopping) return
const configuredEngineSettings = this.settingsManager.getEngine()
- const engineSettings = await this.resolveRuntimeEngineSettings(
- configuredEngineSettings
+ const engineSettings = this.applyCompatibilityLimits(
+ await this.resolveRuntimeEngineSettings(
+ await this.persistCompatibilityLimits(configuredEngineSettings)
+ )
)
const proxy = this.settingsManager.getProxy()
// Provider is wired by the shell (Task 8) before start() in production;
diff --git a/src/core/notifications/engine-compatibility-subscriber.test.ts b/src/core/notifications/engine-compatibility-subscriber.test.ts
new file mode 100644
index 00000000..20e4c2ab
--- /dev/null
+++ b/src/core/notifications/engine-compatibility-subscriber.test.ts
@@ -0,0 +1,53 @@
+import { EventBus } from '@core/events/event-bus'
+import { Events } from '@shared/protocol/events'
+import { NotificationKinds } from '@shared/types/notification'
+import { describe, expect, it, vi } from 'vitest'
+import { registerEngineCompatibilitySubscriber } from './engine-compatibility-subscriber'
+
+describe('registerEngineCompatibilitySubscriber', () => {
+ it('maps the pre-spawn probe warning to a durable notification input', () => {
+ const eventBus = new EventBus()
+ const notify = vi.fn()
+ registerEngineCompatibilitySubscriber({
+ eventBus,
+ notificationCenter: { notify },
+ log: { warn: vi.fn() },
+ })
+
+ eventBus.emit(Events.EngineCompatibilityWarning, {
+ version: '1.37.0',
+ connectionLimit: 16,
+ })
+
+ expect(notify).toHaveBeenCalledWith({
+ sourceKey: 'engine-compatibility:1.37.0',
+ kind: NotificationKinds.EngineCompatibility,
+ severity: 'warning',
+ titleKey: 'notification.engineCompatibility.title',
+ bodyKey: 'notification.engineCompatibility.body',
+ bodyParams: { version: '1.37.0', limit: '16' },
+ })
+ })
+
+ it('isolates notification-store failures from engine startup', () => {
+ const eventBus = new EventBus()
+ const warn = vi.fn()
+ registerEngineCompatibilitySubscriber({
+ eventBus,
+ notificationCenter: {
+ notify: vi.fn(() => {
+ throw new Error('SQLITE_FULL')
+ }),
+ },
+ log: { warn },
+ })
+
+ expect(() =>
+ eventBus.emit(Events.EngineCompatibilityWarning, {
+ version: '1.37.0',
+ connectionLimit: 16,
+ })
+ ).not.toThrow()
+ expect(warn).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/core/notifications/engine-compatibility-subscriber.ts b/src/core/notifications/engine-compatibility-subscriber.ts
new file mode 100644
index 00000000..67ae5f8a
--- /dev/null
+++ b/src/core/notifications/engine-compatibility-subscriber.ts
@@ -0,0 +1,43 @@
+import type { EventBus } from '@core/events/event-bus'
+import type { Logger } from '@core/logger'
+import { Events } from '@shared/protocol/events'
+import type { EngineCompatibilityWarningPayload } from '@shared/types/engine'
+import { NotificationKinds } from '@shared/types/notification'
+import type { NotificationCenter } from './notification-center'
+
+export interface EngineCompatibilitySubscriberDeps {
+ eventBus: EventBus
+ notificationCenter: Pick<NotificationCenter, 'notify'>
+ log: Pick<Logger, 'warn'>
+}
+
+/**
+ * Persist the pre-spawn shell probe result as a warning. The version-scoped
+ * source key makes repeated starts with the same replacement binary
+ * idempotent while allowing a newly detected version to surface again.
+ */
+export function registerEngineCompatibilitySubscriber(
+ deps: EngineCompatibilitySubscriberDeps
+): void {
+ deps.eventBus.on(Events.EngineCompatibilityWarning, (...args: unknown[]) => {
+ const payload = args[0] as EngineCompatibilityWarningPayload
+ try {
+ deps.notificationCenter.notify({
+ sourceKey: `engine-compatibility:${payload.version}`,
+ kind: NotificationKinds.EngineCompatibility,
+ severity: 'warning',
+ titleKey: 'notification.engineCompatibility.title',
+ bodyKey: 'notification.engineCompatibility.body',
+ bodyParams: {
+ version: payload.version,
+ limit: String(payload.connectionLimit),
+ },
+ })
+ } catch (error) {
+ deps.log.warn(
+ { err: error, version: payload.version },
+ 'engineCompatibilitySubscriber: notify() threw'
+ )
+ }
+ })
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index b4eab6f3..582a86df 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -34,6 +34,7 @@ import {
} from '@core/inspector-activity'
import { newTaskId } from '@core/lib/ids'
import { getLogger } from '@core/logger'
+import { registerEngineCompatibilitySubscriber } from '@core/notifications/engine-compatibility-subscriber'
import { registerEngineFailureSubscriber } from '@core/notifications/engine-failure-subscriber'
import { NotificationCenter } from '@core/notifications/notification-center'
import { createNotificationOccurrenceConsumer } from '@core/notifications/occurrence-consumer'
@@ -817,21 +818,34 @@ async function handlePolledTasks(
}
} else {
const id = newTaskId()
- taskManager.set(id, { ...translated, id })
+ const discoveredTask: DownloadTask = { ...translated, id }
+ const persistParent = (): Promise<void> => persistTask(discoveredTask)
+ try {
+ if (taskInspectorActivityRuntime) {
+ await taskInspectorActivityRuntime.parentTaskCreated(
+ discoveredTask,
+ persistParent
+ )
+ } else {
+ await persistParent()
+ }
+ } catch (err) {
+ // Nothing has been published yet. Leave the engine row ownerless so
+ // the next poll retries the complete parent write with no Activity FK
+ // race and no in-memory task that would disappear after restart.
+ log.warn(
+ { err, gid: raw.gid, taskId: id },
+ 'engine task adoption failed'
+ )
+ continue
+ }
+ taskManager.set(id, discoveredTask)
log.info(
{ gid: raw.gid, taskId: id, name: translated.name },
'new task discovered from engine'
)
- // Persist identity right away so a subsequent crash within the
- // 15s auto-save window doesn't re-discover the same gid as a
- // *different* motrix task on next launch — that would orphan the
- // freshly minted id and confuse any downstream sidecar tables
- // that join on motrix_id. requestSave coalesces if multiple
- // orphans land in the same poll tick.
- void sessionManager
- .requestSave()
- .catch((err) => log.warn({ err, taskId: id }, 'discovery save failed'))
- // Orphan adopt: sync task_files too if engine has files for this gid.
+ // The complete parent is durable now, so FK-backed sidecars can be
+ // written immediately instead of waiting for a later batch save.
if (translated.fileCount > 0) {
runShellAsyncWork('task-files orphan sync', () =>
syncTaskFilesIfMissing(id, raw.gid)
@@ -1014,6 +1028,11 @@ async function startEngineAndRestore(
notificationCenter,
log,
})
+ registerEngineCompatibilitySubscriber({
+ eventBus,
+ notificationCenter,
+ log,
+ })
// ─── occurrence consumer registration ─────────────────
// F5: registered here, BEFORE supervisor.start() and its two early
diff --git a/src/main/main-process-work-coordinator.test.ts b/src/main/main-process-work-coordinator.test.ts
index 2630870f..85c06563 100644
--- a/src/main/main-process-work-coordinator.test.ts
+++ b/src/main/main-process-work-coordinator.test.ts
@@ -259,6 +259,37 @@ describe('MainProcessWorkCoordinator', () => {
expect(orphanId).toBeGreaterThan(retiredGate)
})
+ it('persists an engine-discovered parent before Activity samples and publication', () => {
+ const source = readFileSync(
+ path.resolve(process.cwd(), 'src/main/index.ts'),
+ 'utf8'
+ )
+ const handler = source.indexOf('async function handlePolledTasks(')
+ const discoveredTask = source.indexOf(
+ 'const discoveredTask: DownloadTask =',
+ handler
+ )
+ const persistParent = source.indexOf(
+ 'persistTask(discoveredTask)',
+ discoveredTask
+ )
+ const parentBarrier = source.indexOf(
+ 'taskInspectorActivityRuntime.parentTaskCreated(',
+ persistParent
+ )
+ const publish = source.indexOf(
+ 'taskManager.set(id, discoveredTask)',
+ parentBarrier
+ )
+ const samples = source.indexOf('recordSamples(tasks)', publish)
+
+ expect(discoveredTask).toBeGreaterThan(handler)
+ expect(persistParent).toBeGreaterThan(discoveredTask)
+ expect(parentBarrier).toBeGreaterThan(persistParent)
+ expect(publish).toBeGreaterThan(parentBarrier)
+ expect(samples).toBeGreaterThan(publish)
+ })
+
it('starts bridge cancellation and stops the engine before awaiting general shell work', () => {
const source = readFileSync(
path.resolve(process.cwd(), 'src/main/index.ts'),
diff --git a/src/renderer/hooks/use-notification-toasts.test.tsx b/src/renderer/hooks/use-notification-toasts.test.tsx
index a81b7c6b..8f4a5c90 100644
--- a/src/renderer/hooks/use-notification-toasts.test.tsx
+++ b/src/renderer/hooks/use-notification-toasts.test.tsx
@@ -3,6 +3,7 @@ import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import { EngineFailureReason, EngineState } from '@shared/types/engine'
import type { AppNotification } from '@shared/types/notification'
+import { NotificationKinds } from '@shared/types/notification'
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useNotificationToasts } from './use-notification-toasts'
@@ -207,6 +208,35 @@ describe('useNotificationToasts', () => {
expect(toastAddMock).not.toHaveBeenCalled()
})
+ it('surfaces the engine compatibility notification as a warning toast', () => {
+ renderHook(() => useNotificationToasts())
+
+ act(() => {
+ fire(
+ Events.NotificationAdded,
+ notification({
+ severity: 'warning',
+ kind: NotificationKinds.EngineCompatibility,
+ titleKey: 'notification.engineCompatibility.title',
+ titleParams: null,
+ bodyKey: 'notification.engineCompatibility.body',
+ bodyParams: { version: '1.37.0', limit: '16' },
+ taskId: null,
+ })
+ )
+ })
+
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'notification-error',
+ title: 'Non-Motrix aria2 detected',
+ description:
+ 'aria2 1.37.0 is not the Motrix fork. Connection settings are limited to at most 16, and SQLite history persistence is unavailable. Restore the bundled aria2_motrix engine for full support.',
+ type: 'warning',
+ })
+ )
+ })
+
it('bullet 1: kind engine-failure toasts the STICKY variant via close-then-add, with no foreground gate', () => {
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
renderHook(() => useNotificationToasts())
diff --git a/src/renderer/hooks/use-notification-toasts.ts b/src/renderer/hooks/use-notification-toasts.ts
index a9053095..bc99e6b3 100644
--- a/src/renderer/hooks/use-notification-toasts.ts
+++ b/src/renderer/hooks/use-notification-toasts.ts
@@ -75,11 +75,9 @@ const FOCUSED_ERROR_TOAST_ID = 'notification-error'
* failed query (transport not ready yet, etc.) is swallowed — a later
* engine event or app reload will retry it.
*
- * Only `severity === 'error'` rows toast at all — `task-complete`/info rows
- * stay silent (they still land in the bell badge / `/notifications` page via
- * `useNotifications()`); this is purely the "surface it now, loudly" path
- * for errors while the user is looking at the app (plus the always-on
- * sticky engine-failure surface above).
+ * Only `severity === 'error'` rows and the engine-compatibility warning toast
+ * at all — `task-complete`/info rows stay silent (they still land in the bell
+ * badge / `/notifications` page via `useNotifications()`).
*
* Mount exactly once at the top of the app tree (AppLayout), mirroring
* `useToastEvents`/`usePairRequestPrompts`: `t` and `i18n` are threaded
@@ -176,7 +174,9 @@ export function useNotificationToasts(): void {
const handler = (...args: unknown[]) => {
const n = args[0] as AppNotification
- if (n.severity !== 'error') return
+ const isCompatibilityWarning =
+ n.kind === NotificationKinds.EngineCompatibility
+ if (n.severity !== 'error' && !isCompatibilityWarning) return
// Bullet 1: engine-failure rows get the sticky action-bearing toast —
// no foreground gate, no FOCUSED_ERROR_TOAST_ID coalescing.
@@ -207,7 +207,7 @@ export function useNotificationToasts(): void {
title: resolve(n.titleKey, n.titleParams),
description:
n.bodyKey != null ? resolve(n.bodyKey, n.bodyParams) : undefined,
- type: 'error',
+ type: isCompatibilityWarning ? 'warning' : 'error',
})
}
diff --git a/src/server/index.ts b/src/server/index.ts
index 36b90af1..1066d078 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -34,6 +34,7 @@ import {
} from '@core/inspector-activity'
import { newTaskId } from '@core/lib/ids'
import { getLogger, initLogger } from '@core/logger'
+import { registerEngineCompatibilitySubscriber } from '@core/notifications/engine-compatibility-subscriber'
import { registerEngineFailureSubscriber } from '@core/notifications/engine-failure-subscriber'
import { NotificationCenter } from '@core/notifications/notification-center'
import { createNotificationOccurrenceConsumer } from '@core/notifications/occurrence-consumer'
@@ -742,7 +743,22 @@ async function main() {
dirty = true
} else {
const id = newTaskId()
- taskManager.set(id, { ...translated, id })
+ const discoveredTask: DownloadTask = { ...translated, id }
+ try {
+ await taskInspectorActivityRuntime.parentTaskCreated(
+ discoveredTask,
+ () => persistTask(discoveredTask)
+ )
+ } catch (err) {
+ // Persistence rejected before publication. The next poll can retry
+ // adoption without exposing a task whose Activity parent is absent.
+ log.warn(
+ { err, gid: raw.gid, taskId: id },
+ 'engine task adoption failed'
+ )
+ continue
+ }
+ taskManager.set(id, discoveredTask)
log.info(
{ gid: raw.gid, taskId: id, name: translated.name },
'new task discovered from engine'
@@ -1101,6 +1117,11 @@ async function main() {
notificationCenter,
log,
})
+ registerEngineCompatibilitySubscriber({
+ eventBus,
+ notificationCenter,
+ log,
+ })
try {
await supervisor.start(platform.aria2BinaryPath)
diff --git a/src/server/shutdown.test.ts b/src/server/shutdown.test.ts
index 1094f0bc..68bab52c 100644
--- a/src/server/shutdown.test.ts
+++ b/src/server/shutdown.test.ts
@@ -320,6 +320,37 @@ describe('server lifecycle production wiring', () => {
expect(orphanId).toBeGreaterThan(retiredGate)
})
+ it('persists an engine-discovered parent before Activity samples and publication', () => {
+ const source = readFileSync(
+ path.resolve(process.cwd(), 'src/server/index.ts'),
+ 'utf8'
+ )
+ const handler = source.indexOf('async function handlePolledTasks(')
+ const discoveredTask = source.indexOf(
+ 'const discoveredTask: DownloadTask =',
+ handler
+ )
+ const parentBarrier = source.indexOf(
+ 'taskInspectorActivityRuntime.parentTaskCreated(',
+ discoveredTask
+ )
+ const persistParent = source.indexOf(
+ 'persistTask(discoveredTask)',
+ parentBarrier
+ )
+ const publish = source.indexOf(
+ 'taskManager.set(id, discoveredTask)',
+ persistParent
+ )
+ const samples = source.indexOf('recordSamples(tasks)', publish)
+
+ expect(discoveredTask).toBeGreaterThan(handler)
+ expect(parentBarrier).toBeGreaterThan(discoveredTask)
+ expect(persistParent).toBeGreaterThan(parentBarrier)
+ expect(publish).toBeGreaterThan(persistParent)
+ expect(samples).toBeGreaterThan(publish)
+ })
+
it('constructs shutdown before early acquisitions, producers, or HTTP ingress', () => {
const source = readFileSync(
path.resolve(process.cwd(), 'src/server/index.ts'),
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 182a7df0..36eefbd4 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -2133,6 +2133,10 @@
"engineFailure": {
"title": "Download engine failed"
},
+ "engineCompatibility": {
+ "title": "Non-Motrix aria2 detected",
+ "body": "aria2 {{version}} is not the Motrix fork. Connection settings are limited to at most {{limit}}, and SQLite history persistence is unavailable. Restore the bundled aria2_motrix engine for full support."
+ },
"engineRestartRequired": {
"title": "Restart the download engine to apply settings",
"body": "Your settings are saved. Restart the download engine when convenient.",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 291a77d4..85cf4d4f 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -2113,6 +2113,10 @@
"engineFailure": {
"title": "下载引擎故障"
},
+ "engineCompatibility": {
+ "title": "检测到非 Motrix 版 aria2",
+ "body": "当前 aria2 {{version}} 不是 Motrix fork。连接设置已限制为不超过 {{limit}},且 SQLite 历史持久化不可用。请恢复内置 aria2_motrix 引擎以获得完整支持。"
+ },
"engineRestartRequired": {
"title": "重启下载引擎以应用设置",
"body": "设置已保存,可在方便时重启下载引擎。",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 8eb15238..9b9d0c18 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1734,6 +1734,10 @@
"engineFailure": {
"title": "下載引擎失敗"
},
+ "engineCompatibility": {
+ "title": "偵測到非 Motrix 版 aria2",
+ "body": "目前的 aria2 {{version}} 不是 Motrix fork。連線設定已限制為不超過 {{limit}},且 SQLite 歷史持久化無法使用。請還原內建 aria2_motrix 引擎以取得完整支援。"
+ },
"engineRestartRequired": {
"title": "重新啟動下載引擎以套用設定",
"body": "設定已儲存,您可以在方便時重新啟動下載引擎。",
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index 7af7aa8d..d942ec85 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -96,6 +96,9 @@ export const Events = {
// Payload: EngineFailurePayload (Task 13). NOT included in
// ForwardableEvents — internal main-process producer signal only.
EngineFailureOccurred: 'event:engineFailureOccurred',
+ // Payload: EngineCompatibilityWarningPayload. Internal shell signal; the
+ // resulting durable NotificationAdded event is what reaches renderers.
+ EngineCompatibilityWarning: 'event:engineCompatibilityWarning',
ApplicationMenuChanged: 'event:applicationMenuChanged',
} as const
diff --git a/src/shared/types/engine.ts b/src/shared/types/engine.ts
index c8f14b2e..a77fb978 100644
--- a/src/shared/types/engine.ts
+++ b/src/shared/types/engine.ts
@@ -79,6 +79,12 @@ export interface EngineRestartRequiredPayload {
changedKeys: string[]
}
+/** Emitted when the pre-spawn binary probe selects compatibility limits. */
+export interface EngineCompatibilityWarningPayload {
+ version: string
+ connectionLimit: number
+}
+
export interface EngineProcessInfo {
pid: number
name: string
diff --git a/src/shared/types/notification.ts b/src/shared/types/notification.ts
index e7edaae7..0fcddf0d 100644
--- a/src/shared/types/notification.ts
+++ b/src/shared/types/notification.ts
@@ -5,6 +5,7 @@ export const NotificationKinds = {
TaskError: 'task-error',
TaskComplete: 'task-complete',
EngineFailure: 'engine-failure',
+ EngineCompatibility: 'engine-compatibility',
EngineRestartRequired: 'engine-restart-required',
DnsFallback: 'dns-fallback',
} as const
diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.ts
index ada803f2..4aa9fd4b 100644
--- a/tests/check-third-party-notices.test.ts
+++ b/tests/check-third-party-notices.test.ts
@@ -256,9 +256,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.6')
+ expect(notice).toContain('1.37.0-motrix.10')
expect(notice).toContain(
- 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.6'
+ 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.10'
)
expect(notice).toContain('GPL-2.0-or-later')
expect(notice).toContain('THIRD_PARTY_LICENSES/aria2-COPYING')
diff --git a/tests/generate-third-party-notices.test.ts b/tests/generate-third-party-notices.test.ts
index 0b91b7d7..29da7639 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.3 |')
- expect(inventory).toContain('| aria2 | 1.37.0-motrix.6 |')
+ expect(inventory).toContain('| aria2 | 1.37.0-motrix.10 |')
expect(inventory).toContain('| motrix.filename-template | 1.1.1 |')
expect(inventory).toContain('Apple San Francisco tray font')
expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')