A full-featured download manager.
feat(aria2): align runtime defaults and BT preview policy (#1982)
Dr_rOot9cb3898ee508
diff --git a/extra/aria2.conf b/extra/aria2.confindex 671e4d05..941416ad 100644--- a/extra/aria2.conf+++ b/extra/aria2.conf@@ -12,9 +12,10 @@############### File system / Disk ###########################################-# auto-save-interval intentionally omitted: with --enable-sqlite3-persistence-# the .aria2 control file is no longer produced. Piece progress and active-# task state live in the SQLite database with WAL durability instead.+# auto-save-interval is selected at runtime: Motrix injects 10 seconds when+# SQLite persistence is inactive, regardless of whether a text session is+# loaded. In SQLite mode Motrix keeps aria2's 60-second default; progress is+# saved to the database/WAL without adopting the text fallback's write cadence.# Skip preallocation entirely for files smaller than this. Avoids wasting# time on tiny files where allocation overhead dominates.diff --git a/src/core/download/aria2-segment-client.test.ts b/src/core/download/aria2-segment-client.test.tsindex 2fc04014..7c637d54 100644--- a/src/core/download/aria2-segment-client.test.ts+++ b/src/core/download/aria2-segment-client.test.ts@@ -104,6 +104,7 @@ describe('Aria2SegmentClient', () => {expect(options.header).toEqual(['Cookie: foo=bar'])expect(options['max-tries']).toBe('5')expect(options['retry-wait']).toBe('3')+ expect(options.continue).toBe('false')})it('forceRemove forwards the gid to rpc', async () => {diff --git a/src/core/download/aria2-segment-client.ts b/src/core/download/aria2-segment-client.tsindex 13c99b48..d6791615 100644--- a/src/core/download/aria2-segment-client.ts+++ b/src/core/download/aria2-segment-client.ts@@ -68,6 +68,7 @@ export class Aria2SegmentClient implements SegmentAria2 {}): Promise<string> {const options: Record<string, string | string[]> = {+ continue: 'false',dir: opts.dir,out: opts.out,}diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex b20b4c6d..44fa10a8 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -358,6 +358,7 @@ describe('Aria2Adapter', () => {expect(gid).toBe('gid123')expect(rpc.addUri).toHaveBeenCalledWith(['http://example.com/file.zip'], {+ continue: 'false',dir: '/tmp',out: 'custom.zip','max-download-limit': '1024',@@ -376,6 +377,7 @@ describe('Aria2Adapter', () => {})expect(rpc.addUri).toHaveBeenCalledWith(['http://example.com/f.zip'], {+ continue: 'false',dir: '/tmp',})})@@ -389,6 +391,7 @@ describe('Aria2Adapter', () => {uris: ['http://example.com/f.zip'],saveDir: '/tmp',resumePolicy: 'checkpoint',+ extraEngineOptions: { continue: 'true' },})expect(rpc.addUri).toHaveBeenCalledWith(@@ -444,7 +447,7 @@ describe('Aria2Adapter', () => {)})- it('does not inject resume options for ordinary new downloads', async () => {+ it('forces continue off for ordinary new downloads after extra engine options', async () => {const rpc = createMockRpc()vi.mocked(rpc.addUri).mockResolvedValue('new-gid')const adapter = new Aria2Adapter(rpc)@@ -453,11 +456,12 @@ describe('Aria2Adapter', () => {uris: ['http://example.com/f.zip'],saveDir: '/tmp',resumePolicy: 'none',+ extraEngineOptions: { continue: 'true' },})const options = vi.mocked(rpc.addUri).mock.calls[0][1]expect(options).not.toHaveProperty('always-resume')- expect(options).not.toHaveProperty('continue')+ expect(options?.continue).toBe('false')})it('forwards pause:true as aria2 pause option', async () => {@@ -712,7 +716,10 @@ describe('Aria2Adapter', () => {totalSizeBytes: 10 * 1024 * 1024 * 1024,})- expect(rpc.addUri).toHaveBeenCalledWith(['u'], { dir: '/d' })+ expect(rpc.addUri).toHaveBeenCalledWith(['u'], {+ continue: 'false',+ dir: '/d',+ })})it('auto tuning preserves an explicit connection count', async () => {@@ -1148,6 +1155,25 @@ describe('Aria2Adapter', () => {expect(opts).not.toHaveProperty('select-file')})+ it('maps preview piece priority only when requested by the product layer', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addTorrent).mockResolvedValue('g')+ const adapter = new Aria2Adapter(rpc)++ await adapter.addTorrent({+ metadata: new Uint8Array([0]),+ saveDir: '/d',+ prioritizePreviewPieces: true,+ })++ const [, , opts] = vi.mocked(rpc.addTorrent).mock.calls[0] as [+ string,+ string[],+ Record<string, string>,+ ]+ expect(opts['bt-prioritize-piece']).toBe('head=10M,tail=10M')+ })+it('maps zero-based output paths to repeated aria2 index-out options', async () => {const rpc = createMockRpc()vi.mocked(rpc.addTorrent).mockResolvedValue('g')diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex b9707bc2..b8f1407f 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -306,11 +306,10 @@ export class Aria2Adapter implements EngineAdapter {const resumePolicy = params.resumePolicy ?? 'none'if (resumePolicy === 'checkpoint') {options['always-resume'] = 'true'- options.continue = 'false'} else if (resumePolicy === 'sequential-prefix') {options['always-resume'] = 'true'- options.continue = 'true'}+ options.continue = resumePolicy === 'sequential-prefix' ? 'true' : 'false'const actualGid = await this.addUriWithConnectionFallback(params.uris,@@ -531,6 +530,9 @@ export class Aria2Adapter implements EngineAdapter {// Override aria2's engine-wide bt-tracker default with empty string.opts['bt-tracker'] = ''}+ if (params.prioritizePreviewPieces) {+ opts['bt-prioritize-piece'] = 'head=10M,tail=10M'+ }if (params.dlLimit !== undefined) {opts['max-download-limit'] = `${params.dlLimit}K`}diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.tsindex 5398b381..ea31518c 100644--- a/src/core/engine/aria2/aria2-config-builder.test.ts+++ b/src/core/engine/aria2/aria2-config-builder.test.ts@@ -23,9 +23,11 @@ vi.mock('node:fs/promises', () => ({}))import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'-import type { EngineSettings } from '@shared/types/settings'+import type { EngineSettings, ProxySettings } from '@shared/types/settings'import { Aria2ConfigBuilder } from './aria2-config-builder'+const DEFAULT_SAVE_DIR = '/home/user/Downloads'+function makeEngineSettings(overrides?: Partial<EngineSettings>): EngineSettings {@@ -41,6 +43,23 @@ function makeEngineSettings(describe('Aria2ConfigBuilder', () => {let builder: Aria2ConfigBuilder+ function buildArgs(+ settings: EngineSettings,+ hasSqlitePersistence: boolean,+ proxy: ProxySettings | null | undefined,+ effective: { download: number; upload: number },+ loadTextSession = false+ ): string[] {+ return builder.buildArgs(+ settings,+ hasSqlitePersistence,+ proxy,+ effective,+ DEFAULT_SAVE_DIR,+ loadTextSession+ )+ }+beforeEach(() => {vi.clearAllMocks()builder = new Aria2ConfigBuilder(@@ -147,7 +166,7 @@ describe('Aria2ConfigBuilder', () => {describe('buildArgs', () => {it('builds args array with default settings', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -156,6 +175,9 @@ describe('Aria2ConfigBuilder', () => {expect(args).toContain('--enable-rpc=true')expect(args).toContain('--rpc-allow-origin-all=true')expect(args).toContain('--rpc-listen-all=false')+ expect(+ args.some((arg) => arg.startsWith('--rpc-max-request-size='))+ ).toBe(false)expect(args).toContain(`--rpc-listen-port=${DEFAULT_ENGINE_SETTINGS.rpcPort}`)@@ -176,8 +198,20 @@ describe('Aria2ConfigBuilder', () => {)})+ it('uses the supplied default save directory for optionless RPC tasks', () => {+ const args = builder.buildArgs(+ DEFAULT_ENGINE_SETTINGS,+ true,+ null,+ { download: 0, upload: 0 },+ '/Volumes/Downloads with spaces'+ )++ expect(args).toContain('--dir=/Volumes/Downloads with spaces')+ })+it('includes save-session path in userConfigDir', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -189,13 +223,11 @@ describe('Aria2ConfigBuilder', () => {})it('loads the text session only when requested by the supervisor', () => {- const withoutInput = builder.buildArgs(- DEFAULT_ENGINE_SETTINGS,- false,- null,- { download: 0, upload: 0 }- )- const withInput = builder.buildArgs(+ const withoutInput = buildArgs(DEFAULT_ENGINE_SETTINGS, false, null, {+ download: 0,+ upload: 0,+ })+ const withInput = buildArgs(DEFAULT_ENGINE_SETTINGS,false,null,@@ -212,7 +244,7 @@ describe('Aria2ConfigBuilder', () => {})it('never combines text-session loading with active SQLite persistence', () => {- const args = builder.buildArgs(+ const args = buildArgs(makeEngineSettings({ sqlite3Persistence: true }),true,null,@@ -224,10 +256,37 @@ describe('Aria2ConfigBuilder', () => {expect(args).not.toContain('--input-file=/home/user/.config/motrix/aria2.session')+ expect(args).not.toContain('--auto-save-interval=10')+ })++ it.each([false, true])(+ 'uses a 10-second control-file interval without SQLite, loadTextSession=%s',+ (loadTextSession) => {+ const args = buildArgs(+ DEFAULT_ENGINE_SETTINGS,+ false,+ null,+ { download: 0, upload: 0 },+ loadTextSession+ )++ expect(args).toContain('--auto-save-interval=10')+ }+ )++ it('uses a 10-second control-file interval when SQLite is supported but disabled', () => {+ const args = buildArgs(+ makeEngineSettings({ sqlite3Persistence: false }),+ true,+ null,+ { download: 0, upload: 0 }+ )++ expect(args).toContain('--auto-save-interval=10')})it('keeps DHT state inside the writable user config directory', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -248,7 +307,7 @@ describe('Aria2ConfigBuilder', () => {listenPort: 6882,}- const args = builder.buildArgs(custom, true, null, {+ const args = buildArgs(custom, true, null, {download: 0,upload: 0,})@@ -260,7 +319,7 @@ describe('Aria2ConfigBuilder', () => {})it('always starts with --conf-path', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -269,11 +328,11 @@ describe('Aria2ConfigBuilder', () => {})it('returns a new array on each call', () => {- const args1 = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args1 = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})- const args2 = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args2 = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -288,7 +347,7 @@ describe('Aria2ConfigBuilder', () => {fileAllocation: 'falloc',diskCache: 33554432,}- const args = builder.buildArgs(settings, true, null, {+ const args = buildArgs(settings, true, null, {download: 0,upload: 0,})@@ -298,7 +357,7 @@ describe('Aria2ConfigBuilder', () => {})it('includes default file-allocation and disk-cache', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -312,7 +371,7 @@ describe('Aria2ConfigBuilder', () => {describe('L3 user-tunable flags', () => {it('injects all performance flags', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -332,7 +391,7 @@ describe('Aria2ConfigBuilder', () => {})it('injects all network-reliability flags', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -357,7 +416,7 @@ describe('Aria2ConfigBuilder', () => {})it('injects all BitTorrent flags', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -375,7 +434,7 @@ describe('Aria2ConfigBuilder', () => {})it('injects session-save-interval', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -398,7 +457,7 @@ describe('Aria2ConfigBuilder', () => {seedRatio: 2,seedTime: 0,}- const args = builder.buildArgs(custom, true, null, {+ const args = buildArgs(custom, true, null, {download: 0,upload: 0,})@@ -424,7 +483,7 @@ describe('Aria2ConfigBuilder', () => {})it('injects --enable-sqlite3-persistence with the configured boolean', () => {- const args = builder.buildArgs(baseSettings, true, null, {+ const args = buildArgs(baseSettings, true, null, {download: 0,upload: 0,})@@ -432,7 +491,7 @@ describe('Aria2ConfigBuilder', () => {})it('uses default DB path when sqlite3DbPath is empty', () => {- const args = builder.buildArgs(baseSettings, true, null, {+ const args = buildArgs(baseSettings, true, null, {download: 0,upload: 0,})@@ -442,7 +501,7 @@ describe('Aria2ConfigBuilder', () => {})it('uses explicit DB path when sqlite3DbPath is set', () => {- const args = builder.buildArgs(+ const args = buildArgs({ ...baseSettings, sqlite3DbPath: '/custom/path/db.sqlite' },true,null,@@ -455,7 +514,7 @@ describe('Aria2ConfigBuilder', () => {})it('passes -1 history limit through verbatim', () => {- const args = builder.buildArgs(baseSettings, true, null, {+ const args = buildArgs(baseSettings, true, null, {download: 0,upload: 0,})@@ -464,25 +523,21 @@ describe('Aria2ConfigBuilder', () => {it('passes 0 and positive history limits through verbatim', () => {expect(- builder.buildArgs(- { ...baseSettings, sqlite3HistoryLimit: 0 },- true,- null,- { download: 0, upload: 0 }- )+ buildArgs({ ...baseSettings, sqlite3HistoryLimit: 0 }, true, null, {+ download: 0,+ upload: 0,+ })).toContain('--sqlite3-history-limit=0')expect(- builder.buildArgs(- { ...baseSettings, sqlite3HistoryLimit: 10000 },- true,- null,- { download: 0, upload: 0 }- )+ buildArgs({ ...baseSettings, sqlite3HistoryLimit: 10000 }, true, null, {+ download: 0,+ upload: 0,+ })).toContain('--sqlite3-history-limit=10000')})it('omits all three sqlite flags when hasSqlitePersistence=false', () => {- const args = builder.buildArgs(baseSettings, false, null, {+ const args = buildArgs(baseSettings, false, null, {download: 0,upload: 0,})@@ -498,7 +553,7 @@ describe('Aria2ConfigBuilder', () => {})it('keeps L1 invariants at the tail regardless of flag injection', () => {- const args = builder.buildArgs(baseSettings, true, null, {+ const args = buildArgs(baseSettings, true, null, {download: 0,upload: 0,})@@ -512,7 +567,7 @@ describe('Aria2ConfigBuilder', () => {describe('incomplete-suffix required defaults', () => {it('sets bt-save-metadata=true', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -520,7 +575,7 @@ describe('Aria2ConfigBuilder', () => {})it('sets bt-metadata-only=false', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -528,7 +583,7 @@ describe('Aria2ConfigBuilder', () => {})it('sets auto-file-renaming=false', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -536,7 +591,7 @@ describe('Aria2ConfigBuilder', () => {})it('sets allow-overwrite=false', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -544,7 +599,7 @@ describe('Aria2ConfigBuilder', () => {})it('sets rpc-save-upload-metadata=true', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -552,16 +607,14 @@ describe('Aria2ConfigBuilder', () => {})it('emits the required defaults regardless of hasSqlitePersistence', () => {- const argsWith = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const argsWith = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ download: 0,+ upload: 0,+ })+ const argsWithout = buildArgs(DEFAULT_ENGINE_SETTINGS, false, null, {download: 0,upload: 0,})- const argsWithout = builder.buildArgs(- DEFAULT_ENGINE_SETTINGS,- false,- null,- { download: 0, upload: 0 }- )for (const args of [argsWith, argsWithout]) {expect(args).toContain('--bt-save-metadata=true')@@ -575,7 +628,7 @@ describe('Aria2ConfigBuilder', () => {describe('buildArgs effective limits', () => {it('injects effective limits into the args', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 999,upload: 111,})@@ -584,7 +637,7 @@ describe('Aria2ConfigBuilder', () => {})it('emits 0/0 when unlimited', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -606,7 +659,7 @@ describe('Aria2ConfigBuilder', () => {}it('injects --all-proxy when proxy enabled and download scope on', () => {- const args = builder.buildArgs(makeEngineSettings(), true, baseProxy, {+ const args = buildArgs(makeEngineSettings(), true, baseProxy, {download: 0,upload: 0,})@@ -614,7 +667,7 @@ describe('Aria2ConfigBuilder', () => {})it('injects --no-proxy when bypass list non-empty', () => {- const args = builder.buildArgs(+ const args = buildArgs(makeEngineSettings(),true,{@@ -627,7 +680,7 @@ describe('Aria2ConfigBuilder', () => {})it('omits --no-proxy when bypass empty', () => {- const args = builder.buildArgs(makeEngineSettings(), true, baseProxy, {+ const args = buildArgs(makeEngineSettings(), true, baseProxy, {download: 0,upload: 0,})@@ -635,7 +688,7 @@ describe('Aria2ConfigBuilder', () => {})it('omits proxy args when proxy is null', () => {- const args = builder.buildArgs(makeEngineSettings(), true, null, {+ const args = buildArgs(makeEngineSettings(), true, null, {download: 0,upload: 0,})@@ -643,7 +696,7 @@ describe('Aria2ConfigBuilder', () => {})it('omits proxy args when scope off', () => {- const args = builder.buildArgs(+ const args = buildArgs(makeEngineSettings(),true,{@@ -656,7 +709,7 @@ describe('Aria2ConfigBuilder', () => {})it('omits proxy args when proxy disabled', () => {- const args = builder.buildArgs(+ const args = buildArgs(makeEngineSettings(),true,{@@ -671,15 +724,24 @@ describe('Aria2ConfigBuilder', () => {describe('L1 product-contract invariants', () => {it('sets force-save=true', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})expect(args).toContain('--force-save=true')})+ it('sets continue=false so task resume remains an explicit decision', () => {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ download: 0,+ upload: 0,+ })++ expect(args).toContain('--continue=false')+ })+it('sets pause=false on add', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -688,7 +750,7 @@ describe('Aria2ConfigBuilder', () => {})it('keeps bt-seed-unverified=false (per-task only via finalizeTask)', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -696,7 +758,7 @@ describe('Aria2ConfigBuilder', () => {})it('sets bt-remove-unselected-file=true so partial placeholders are cleaned by aria2', () => {- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -706,7 +768,7 @@ describe('Aria2ConfigBuilder', () => {it('places L1 invariants after L3 user-tunable so duplicates resolve to L1', () => {// aria2 honors the LAST occurrence of a duplicated flag. The L1// contract guarantees a user-edited L4 conf cannot override these.- const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {download: 0,upload: 0,})@@ -722,12 +784,10 @@ describe('Aria2ConfigBuilder', () => {['engine', '--async-dns=true'],['system', '--async-dns=false'],] as const)('emits %s as %s', (dnsMode, flag) => {- const args = builder.buildArgs(- makeEngineSettings({ dnsMode }),- true,- null,- { download: 0, upload: 0 }- )+ const args = buildArgs(makeEngineSettings({ dnsMode }), true, null, {+ download: 0,+ upload: 0,+ })expect(args).toContain(flag)})diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.tsindex 2ee65242..6b62660d 100644--- a/src/core/engine/aria2/aria2-config-builder.ts+++ b/src/core/engine/aria2/aria2-config-builder.ts@@ -103,6 +103,8 @@ export class Aria2ConfigBuilder {* @param effective — effective speed limits from SpeedLimitController* (bytes/sec; 0 = unlimited). On cold start the EngineSupervisor passes* the controller's computed value, or { 0, 0 } if no provider is wired.+ * @param defaultSaveDir — application default used by JSON-RPC clients that+ * omit a per-task `dir` option.* @param loadTextSession — load the standard aria2.session fallback. The* supervisor enables this only when SQLite persistence is inactive and* the file was verified to exist.@@ -112,6 +114,7 @@ export class Aria2ConfigBuilder {hasSqlitePersistence = true,proxy: ProxySettings | null | undefined,effective: { download: number; upload: number },+ defaultSaveDir: string,loadTextSession = false): string[] {// Layer order in the produced argv:@@ -134,6 +137,7 @@ export class Aria2ConfigBuilder {'--rpc-listen-all=false',`--rpc-listen-port=${settings.rpcPort}`,`--rpc-secret=${settings.rpcSecret}`,+ `--dir=${defaultSaveDir}`,`--listen-port=${settings.listenPort}`,`--dht-listen-port=${settings.dhtListenPort}`,`--enable-dht=${settings.dhtEnabled}`,@@ -144,6 +148,9 @@ export class Aria2ConfigBuilder {)const sqliteActive =hasSqlitePersistence && settings.sqlite3Persistence === true+ if (!sqliteActive) {+ args.push('--auto-save-interval=10')+ }if (loadTextSession && !sqliteActive) {args.push(`--input-file=${this.saveSessionPath}`)}@@ -202,6 +209,7 @@ export class Aria2ConfigBuilder {'--allow-overwrite=false','--rpc-save-upload-metadata=true','--force-save=true',+ '--continue=false','--pause=false','--pause-metadata=false','--bt-seed-unverified=false',diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex db6afd51..ed948d72 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -56,6 +56,9 @@ export interface AddTorrentParams {// file is still on disk from a prior session.checkIntegrity?: booleanisPrivate?: boolean+ /** Prefer early and late pieces for a metadata-confirmed video-only+ * torrent. Concrete adapters translate this product policy. */+ prioritizePreviewPieces?: boolean// ── create-path additions ──dlLimit?: numberulLimit?: numberdiff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex 86d8043d..7d4b20b3 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -270,10 +270,40 @@ describe('EngineSupervisor', () => {expect.anything(),true,expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)})+ it('passes the configured default save directory on cold start', async () => {+ await supervisor.start('/usr/bin/aria2c')++ expect(configBuilder.buildArgs).toHaveBeenCalledWith(+ expect.anything(),+ true,+ expect.anything(),+ expect.anything(),+ '/Users/test/Downloads',+ false+ )+ })++ it('initializes continue for raw JSON-RPC tasks before becoming Ready', async () => {+ vi.mocked(rpcClient.changeGlobalOption).mockImplementation(+ async (opts) => {+ expect(opts).toEqual({ continue: 'true' })+ expect(supervisor.getState()).toBe(EngineState.Starting)+ return 'OK'+ }+ )++ await supervisor.start('/usr/bin/aria2c')++ expect(rpcClient.changeGlobalOption).toHaveBeenCalledOnce()+ expect(supervisor.getState()).toBe(EngineState.Ready)+ })+it('loads an existing text session when SQLite is disabled in settings', async () => {const configured = settings.getEngine()vi.mocked(settings.getEngine).mockReturnValue({@@ -290,6 +320,7 @@ describe('EngineSupervisor', () => {true,expect.anything(),expect.anything(),+ '/Users/test/Downloads',true)})@@ -311,6 +342,7 @@ describe('EngineSupervisor', () => {false,expect.anything(),expect.anything(),+ '/Users/test/Downloads',true)})@@ -330,7 +362,9 @@ describe('EngineSupervisor', () => {expect.objectContaining({ sqlite3Persistence: false }),true,expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)})@@ -365,7 +399,9 @@ describe('EngineSupervisor', () => {}),false,expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)expect(rpcClient.getVersion).not.toHaveBeenCalled()expect(settings.update).toHaveBeenCalledWith({@@ -401,7 +437,9 @@ describe('EngineSupervisor', () => {}),false,expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)})@@ -423,7 +461,9 @@ describe('EngineSupervisor', () => {}),true,expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)})@@ -455,7 +495,9 @@ describe('EngineSupervisor', () => {}),expect.anything(),expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)expect(settings.update).not.toHaveBeenCalled()})@@ -482,7 +524,9 @@ describe('EngineSupervisor', () => {}),expect.anything(),expect.anything(),- expect.anything()+ expect.anything(),+ '/Users/test/Downloads',+ false)})})@@ -548,6 +592,7 @@ describe('EngineSupervisor', () => {true,expect.anything(),expect.anything(),+ '/Users/test/Downloads',true)expect(failures).toHaveLength(0)@@ -1072,6 +1117,25 @@ describe('EngineSupervisor', () => {)})+ describe('applyDefaultSaveDir', () => {+ it('is a no-op unless Ready', async () => {+ await supervisor.applyDefaultSaveDir('/downloads/next')++ expect(rpcClient.changeGlobalOption).not.toHaveBeenCalled()+ })++ it('updates the global dir when Ready', async () => {+ await supervisor.start('/usr/bin/aria2c')+ vi.mocked(rpcClient.changeGlobalOption).mockClear()++ await supervisor.applyDefaultSaveDir('/downloads/next')++ expect(rpcClient.changeGlobalOption).toHaveBeenCalledExactlyOnceWith({+ dir: '/downloads/next',+ })+ })+ })+describe('applySpeedLimits', () => {it('is a no-op unless Ready', async () => {await supervisor.applySpeedLimits({ download: 100, upload: 50 })@@ -1098,7 +1162,9 @@ describe('EngineSupervisor', () => {expect.anything(),expect.anything(),expect.anything(),- { download: 500, upload: 250 }+ { download: 500, upload: 250 },+ '/Users/test/Downloads',+ false)})@@ -1109,7 +1175,9 @@ describe('EngineSupervisor', () => {expect.anything(),expect.anything(),expect.anything(),- { download: 0, upload: 0 }+ { download: 0, upload: 0 },+ '/Users/test/Downloads',+ false)})})@@ -1145,7 +1213,6 @@ describe('EngineSupervisor', () => {'user-agent': 'Motrix/Test','bt-enable-lpd': 'false','remote-time': 'true',- 'save-session-interval': '30',})})diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex 878c6e94..53dbf9d4 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -64,7 +64,6 @@ const HOT_ENGINE_OPTIONS = {seedRatio: 'seed-ratio',seedTime: 'seed-time',remoteTime: 'remote-time',- sessionSaveInterval: 'save-session-interval',} as const satisfies Partial<Record<keyof EngineSettings, string>>function getBackoffDelay(attempt: number): number {@@ -187,6 +186,16 @@ export class EngineSupervisor {})}+ /**+ * HOT-update the default directory inherited by downloads created directly+ * through aria2 JSON-RPC. Motrix-owned task creation continues to pass its+ * selected directory per task.+ */+ async applyDefaultSaveDir(dir: string): Promise<void> {+ if (this.state !== EngineState.Ready) return+ await this.rpcClient.changeGlobalOption({ dir })+ }+/** HOT-update changed runtime engine settings without restarting aria2. */async applyEngineSettings(previous: EngineSettings,@@ -384,6 +393,7 @@ export class EngineSupervisor {? { ...resolvedEngineSettings, sqlite3Persistence: false }: resolvedEngineSettingsconst proxy = this.settingsManager.getProxy()+ const defaultSaveDir = this.settingsManager.getApp().defaultSaveDir// Provider is wired by the shell (Task 8) before start() in production;// the { 0, 0 } (unlimited) fallback only fires in tests or if start()// runs before the controller attaches.@@ -397,20 +407,14 @@ export class EngineSupervisor {const loadTextSession =!sqliteActive && (await this.configBuilder.hasSavedSession())if (this.stopping) return- const args = loadTextSession- ? this.configBuilder.buildArgs(- engineSettings,- featureReport.hasSqlitePersistence,- proxy,- effective,- true- )- : this.configBuilder.buildArgs(- engineSettings,- featureReport.hasSqlitePersistence,- proxy,- effective- )+ const args = this.configBuilder.buildArgs(+ engineSettings,+ featureReport.hasSqlitePersistence,+ proxy,+ effective,+ defaultSaveDir,+ loadTextSession+ )this.lastStartArgs = args// Step 3: Port check@@ -444,6 +448,16 @@ export class EngineSupervisor {}phase = 'rpc'await this.rpcClient.connect(engineSettings.rpcPort)+ if (this.stopping) {+ this.rpcClient.disconnect()+ await this.processManager.gracefulStop()+ return+ }+ // Raw JSON-RPC clients commonly omit per-task options. Seed the global+ // template so their new HTTP/FTP tasks retain aria2's historical Motrix+ // resume behavior. Motrix-owned recovery still overrides `continue`+ // explicitly per task where safety requires it.+ await this.rpcClient.changeGlobalOption({ continue: 'true' })// Step 6: Readyif (this.stopping) {diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 563d69a6..806c0e57 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -29,6 +29,17 @@ import { SessionManager } from './session-manager'// ─── Task factory ───────────────────────────────────────────+function buildSingleFileTorrent(name: string): Uint8Array {+ const nameField = `4:name${Buffer.byteLength(name, 'utf8')}:${name}`+ const prefix = Buffer.from(+ `d4:infod6:lengthi1024e${nameField}12:piece lengthi16384e6:pieces20:`,+ 'utf8'+ )+ return new Uint8Array(+ Buffer.concat([prefix, Buffer.alloc(20), Buffer.from('ee')])+ )+}+function createTask(overrides: Partial<DownloadTask> = {}): DownloadTask {return makeDownloadTask({id: 'motrix-001',@@ -1319,6 +1330,9 @@ describe('SessionManager', () => {expect(adapter.addTorrent).toHaveBeenCalledWith(expect.objectContaining({ checkIntegrity: true }))+ const restoreParams = (adapter.addTorrent as ReturnType<typeof vi.fn>)+ .mock.calls[0][0]+ expect(restoreParams).not.toHaveProperty('prioritizePreviewPieces')const restored = taskManager.getAll().find((t) => t.id === 'm-bt-002')expect(restored?.engineTaskId).toMatch(/^[0-9a-f]{16}$/)expect(restored?.engineTaskId).not.toBe('lost-gid')@@ -1327,6 +1341,41 @@ describe('SessionManager', () => {fs.rmSync(tmpDir, { recursive: true, force: true })})+ it('restores preview piece priority for a lost video-only BT task', async () => {+ const tmpDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'motrix-restore-video-bt-')+ )+ const torrentPath = path.join(tmpDir, 'video.torrent')+ fs.writeFileSync(torrentPath, buildSingleFileTorrent('Movie.MP4'))++ seedAsPair(db, {+ motrixId: 'm-bt-video',+ gid: 'lost-video-gid',+ name: 'Movie.MP4',+ diskPath: '/tmp/Movie.MP4.motrix',+ finalPath: '/tmp/Movie.MP4',+ finalName: 'Movie.MP4',+ torrentMetaPath: torrentPath,+ status: TaskStatus.Downloading,+ })+ rpc.tellActive = vi.fn(async () => [])+ rpc.tellWaiting = vi.fn(async () => [])+ rpc.tellStopped = vi.fn(async () => [])+ ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockImplementation(+ async ({ gid }: { gid?: string }) => gid ?? ''+ )++ try {+ await sessionManager.restore()++ expect(adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({ prioritizePreviewPieces: true })+ )+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true })+ }+ })+it('adoptByMetadata derives progress from saved mirror columns', async () => {// Regression: paused tasks restored via the reAdd path (aria2 lost// the gid) had progress hardcoded to 0 even though totalBytes /@@ -3491,6 +3540,7 @@ describe('restore() with task_instances (Plan A Task 7)', () => {expect(addUri).toHaveBeenCalledWith(['magnet:?xt=urn:btih:abc'],expect.objectContaining({+ 'bt-load-saved-metadata': 'false','bt-metadata-only': 'true',dir: '/tmp/motrix-magnet-metadata-xyz','follow-torrent': 'false',diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 684eea06..61fbb6fa 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -36,6 +36,7 @@ import {applyTerminalTransition,terminalFieldsFromRow,} from '../task/apply-terminal-transition'+import { shouldPrioritizeBtPreviewPiecesFromMetadata } from '../task/bt-storage-layout'import { DirectResourceValidatorService } from '../task/direct-resource-validator'import { isTempPath } from '../task/paths'import { setTaskTransitionPhase } from '../task/task-instance'@@ -1143,6 +1144,8 @@ export class SessionManager {}try {const bytes = fs.readFileSync(taskPart.torrentMetaPath)+ const prioritizePreviewPieces =+ await shouldPrioritizeBtPreviewPiecesFromMetadata(bytes)return this.dispatchRecoveryCandidate(pair, (gid) =>this.adapter.addTorrent({metadata: bytes,@@ -1150,6 +1153,9 @@ export class SessionManager {saveDir: primary?.diskPath || taskPart.finalPath || '/',pause: taskPart.aggStatus === TaskStatus.Paused,checkIntegrity: true,+ ...(prioritizePreviewPieces+ ? { prioritizePreviewPieces: true }+ : {}),}))} catch (err) {@@ -1430,6 +1436,7 @@ export class SessionManager {try {const newGid = await this.rpc.addUri([magnetUri], {+ 'bt-load-saved-metadata': 'false','bt-metadata-only': 'true',dir: metadataDir,'follow-torrent': 'false',diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.tsindex 34df4e33..718f191e 100644--- a/src/core/settings/settings-manager.test.ts+++ b/src/core/settings/settings-manager.test.ts@@ -619,6 +619,15 @@ describe('SettingsManager', () => {expect(result.changedRestartKeys).toContain('rpcSecret')})+ it('requires an engine restart when the session save interval changes', async () => {+ const result = await manager.update({+ engine: { sessionSaveInterval: 30 },+ })++ expect(result.requiresRestart).toBe(true)+ expect(result.changedRestartKeys).toContain('sessionSaveInterval')+ })+it('does not flag restart for non-restart keys', async () => {await manager.update({ engine: { performanceProfile: 'custom' } })const result = await manager.update({diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex 6211bdb6..20433a38 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -898,5 +898,22 @@ describe('characterization: reAddTask adapter call params', () => {expect(deps.adapter.addTorrent).toHaveBeenCalledWith(expect.objectContaining({ saveDir: '/tmp/sample' }))+ const params = (deps.adapter.addTorrent as ReturnType<typeof vi.fn>).mock+ .calls[0][0]+ expect(params).not.toHaveProperty('prioritizePreviewPieces')+ })++ it('preserves preview piece priority when re-adding a video-only torrent', async () => {+ const task = makeBtErrorTask()+ const deps = makeDeps(task)+ ;(deps.torrentMetaStore.read as ReturnType<typeof vi.fn>).mockResolvedValue(+ buildSingleFileTorrent('Movie.mp4')+ )++ await reAddTask('t1', deps)++ expect(deps.adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({ prioritizePreviewPieces: true })+ )})})diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 657678fd..56c17031 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -23,6 +23,8 @@ import {buildStagingOutputFilePaths,getBtStorageLayout,parseBtFileLayout,+ shouldPrioritizeBtPreviewPieces,+ shouldPrioritizeBtPreviewPiecesFromMetadata,} from '../bt-storage-layout'import { DirectResourceValidatorService } from '../direct-resource-validator'import type { TorrentMetaStore } from '../torrent-meta-store'@@ -124,6 +126,11 @@ async function reAddBt(const storageLayout = getBtStorageLayout(task)const parsedLayout = storageLayout ? await parseBtFileLayout(metadata) : nullconst completed = task.status === TaskStatus.Completed+ const prioritizePreviewPieces =+ !completed &&+ (parsedLayout+ ? shouldPrioritizeBtPreviewPieces(parsedLayout)+ : await shouldPrioritizeBtPreviewPiecesFromMetadata(metadata))const selectedFiles = task.bt?.selectedFilesreturn deps.adapter.addTorrent({metadata,@@ -148,6 +155,7 @@ async function reAddBt(checkIntegrity: true,pause: false,isPrivate: task.bt?.isPrivate ?? false,+ ...(prioritizePreviewPieces ? { prioritizePreviewPieces: true } : {}),seedTime: opts?.['seed-time']? Number.parseInt(opts['seed-time'], 10): undefined,diff --git a/src/core/task/bt-storage-layout.test.ts b/src/core/task/bt-storage-layout.test.tsindex 19466596..499de7a7 100644--- a/src/core/task/bt-storage-layout.test.ts+++ b/src/core/task/bt-storage-layout.test.ts@@ -6,6 +6,7 @@ import {createBtStoragePlan,getBtStorageLayout,parseBtFileLayout,+ shouldPrioritizeBtPreviewPieces,} from './bt-storage-layout'const FIXTURE_PATH = path.resolve(@@ -71,6 +72,16 @@ describe('BT indexed storage layout', () => {).toEqual([{ fileIndex: 0, relativePath: 'Linux image.iso' }])})+ it('prioritizes only metadata-confirmed video-only torrents', async () => {+ const video = await parseBtFileLayout(singleFileTorrent('Movie.MP4'))+ const mixed = await parseBtFileLayout(+ new Uint8Array(readFileSync(FIXTURE_PATH))+ )++ expect(shouldPrioritizeBtPreviewPieces(video)).toBe(true)+ expect(shouldPrioritizeBtPreviewPieces(mixed)).toBe(false)+ })+it('rejects a torrent root that could escape the workspace', async () => {await expect(parseBtFileLayout(singleFileTorrent('..'))).rejects.toThrow('Invalid torrent name'diff --git a/src/core/task/bt-storage-layout.ts b/src/core/task/bt-storage-layout.tsindex b1abf083..97880764 100644--- a/src/core/task/bt-storage-layout.ts+++ b/src/core/task/bt-storage-layout.ts@@ -1,5 +1,6 @@import { createHash } from 'node:crypto'import path from 'node:path'+import { containsOnlyVideoFiles } from '@shared/constants/file-types'import type { DownloadTask } from '@shared/types/task'import parseTorrent from 'parse-torrent'@@ -101,6 +102,30 @@ export async function parseBtFileLayout(}}+/**+ * Enable preview-oriented piece ordering only when validated torrent metadata+ * proves that every declared file is a video. A mixed torrent stays on the+ * engine's normal piece policy even when the user selects only its videos.+ */+export function shouldPrioritizeBtPreviewPieces(+ parsed: ParsedBtFileLayout+): boolean {+ return containsOnlyVideoFiles(+ parsed.files.map((file) => file.pathInsideRoot ?? parsed.torrentRootName)+ )+}++/** Parse failures are an explicit "not proven video-only" result. */+export async function shouldPrioritizeBtPreviewPiecesFromMetadata(+ metadata: Uint8Array+): Promise<boolean> {+ try {+ return shouldPrioritizeBtPreviewPieces(await parseBtFileLayout(metadata))+ } catch {+ return false+ }+}+export function createBtStoragePlan(taskId: string,saveDir: string,diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex abcece8a..8724f50b 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -732,6 +732,28 @@ describe('handleCreateTask', () => {dir: task.diskPath,'index-out': ['1=p'],})+ expect(options).not.toHaveProperty('bt-prioritize-piece')+ })++ it('enables preview piece priority for a video-only torrent', async () => {+ const deps = makeDeps({ addTorrentGid: 'gid-bt' })+ const bytes = buildMinimalTorrentBytes('Movie.MP4', false)++ await handleCreateTask(+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: Buffer.from(bytes).toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/d',+ },+ deps+ )++ const [, , options] = deps.addTorrent.mock.calls[0]+ expect(options['bt-prioritize-piece']).toBe('head=10M,tail=10M')})it('falls back to "torrent" literal when bytes are unparseable', async () => {@@ -748,6 +770,8 @@ describe('handleCreateTask', () => {)const task = lastAddedTask(deps)expect(task.finalName).toBe('torrent')+ const [, , options] = deps.addTorrent.mock.calls[0]+ expect(options).not.toHaveProperty('bt-prioritize-piece')})it('rejects a parseable torrent with an unsafe root path', async () => {@@ -789,6 +813,8 @@ describe('handleCreateTask', () => {['magnet:?xt=urn:btih:x'],expect.any(Object))+ const [, options] = deps.addUri.mock.calls[0]+ expect(options).not.toHaveProperty('bt-prioritize-piece')})})diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 2c5fa150..91a4505c 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -56,6 +56,7 @@ import {createBtStoragePlan,type ParsedBtFileLayout,parseBtFileLayout,+ shouldPrioritizeBtPreviewPieces,UnsafeTorrentPathError,} from './bt-storage-layout'import {@@ -642,6 +643,9 @@ async function handleCreateTaskUnderAdmission(seedRatio: req.seedRatio,// Replaces the old inline `options['bt-tracker'] = ''` set.isPrivate: isPrivateFromTorrent,+ ...(parsedBtLayout && shouldPrioritizeBtPreviewPieces(parsedBtLayout)+ ? { prioritizePreviewPieces: true }+ : {}),}dispatchEngine = async (reservedGid) => {params.gid = reservedGiddiff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.tsindex 1befbc4e..2985ac16 100644--- a/src/core/torrent/magnet-tracker.test.ts+++ b/src/core/torrent/magnet-tracker.test.ts@@ -404,6 +404,7 @@ describe('MagnetTracker', () => {const metadataDir = lastMetadataDir()expect(metadataDir).not.toBe(dir)expect(rpc.addUri).toHaveBeenCalledWith(['magnet:?xt=urn:btih:abc123'], {+ 'bt-load-saved-metadata': 'false','bt-metadata-only': 'true',dir: metadataDir,'follow-torrent': 'false',@@ -2206,6 +2207,8 @@ describe('MagnetTracker', () => {const secondOptions = rpc.addUri.mock.calls[1][1]expect(rpc.addUri).toHaveBeenCalledTimes(2)+ expect(firstOptions?.['bt-load-saved-metadata']).toBe('false')+ expect(secondOptions?.['bt-load-saved-metadata']).toBe('false')expect(secondOptions?.gid).not.toBe(firstOptions?.gid)expect(secondOptions?.dir).not.toBe(firstOptions?.dir)expect(db.getTask(taskId)).toMatchObject({diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex 8bf2308c..7cb1695f 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -629,6 +629,7 @@ export class MagnetTracker {engineDispatchStarted = trueconst returnedGid = await this.rpcClient.addUri([uri], {+ 'bt-load-saved-metadata': 'false','bt-metadata-only': 'true',dir: metadataDir,'follow-torrent': 'false',@@ -852,6 +853,7 @@ export class MagnetTracker {engineDispatchStarted = trueconst returnedGid = await this.rpcClient.addUri([magnetUri], {+ 'bt-load-saved-metadata': 'false','bt-metadata-only': 'true',dir: metadataDir,'follow-torrent': 'false',diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.tsindex 61673e00..d07995a6 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts@@ -1155,6 +1155,38 @@ describe('swapMagnetMetadataForBt', () => {payloadEntry: 'p',torrentRootName: 'very-long-original-name.iso',})+ expect(params.prioritizePreviewPieces).toBeUndefined()+ })++ it('enables preview piece priority after video metadata resolves', async () => {+ const torrent = buildSingleFileTorrent('Movie.mkv')++ await swapMagnetMetadataForBt(+ {+ taskId: 'm-mag',+ base64: Buffer.from(torrent).toString('base64'),+ selectedFiles: [0],+ saveDir: '/Downloads',+ },+ {+ db,+ taskManager,+ adapter: adapter as never,+ magnetTracker: magnetTracker as never as MagnetTracker,+ publishTaskUpdate: () =>+ eventBus.emit(Events.TaskUpdated, taskManager.getAll()),+ publishTaskUpdateNow: () =>+ eventBus.emit(Events.TaskUpdated, taskManager.getAll()),+ finalNamePicker: finalNamePicker as never,+ torrentMetaStore: torrentMetaStore as never,+ runTaskMutation: runImmediately,+ runExclusivePersistence: persistImmediately,+ }+ )++ expect(adapter.addTorrent).toHaveBeenCalledWith(+ expect.objectContaining({ prioritizePreviewPieces: true })+ )})it('passes 1-based file indices to adapter.addTorrent (aria2 --select-file)', async () => {diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.ts b/src/core/torrent/swap-magnet-metadata-for-bt.tsindex 4740dc7e..3cb57a65 100644--- a/src/core/torrent/swap-magnet-metadata-for-bt.ts+++ b/src/core/torrent/swap-magnet-metadata-for-bt.ts@@ -20,6 +20,7 @@ import {createBtStoragePlan,type ParsedBtFileLayout,parseBtFileLayout,+ shouldPrioritizeBtPreviewPieces,UnsafeTorrentPathError,} from '@core/task/bt-storage-layout'import type { FinalNamePicker } from '@core/task/final-name-picker'@@ -535,6 +536,9 @@ async function swapMagnetMetadataForBtUnderMutation(outputFilePaths: btStoragePlan?.outputFilePaths,pause: false,isPrivate: parsedBtLayout?.isPrivate ?? false,+ ...(parsedBtLayout && shouldPrioritizeBtPreviewPieces(parsedBtLayout)+ ? { prioritizePreviewPieces: true }+ : {}),})if (addedGid !== newGid) {throw new Error(diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 4c24bcd7..bd08c10f 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -110,6 +110,7 @@ function fakeCtx() {restart: vi.fn(),applyEngineSettings: vi.fn().mockResolvedValue(undefined),applyAsyncDns: vi.fn().mockResolvedValue(undefined),+ applyDefaultSaveDir: vi.fn().mockResolvedValue(undefined),recover: vi.fn(),start: vi.fn(),stop: vi.fn(),@@ -1161,6 +1162,7 @@ describe('Commands.UpdateSettings', () => {app: {launchAtStartup: false,protocols: { magnet: false },+ defaultSaveDir: '/downloads',...app,},nat: {@@ -1348,6 +1350,38 @@ describe('Commands.UpdateSettings', () => {expect(ctx.supervisor.restart).not.toHaveBeenCalled()})+ it('hot-applies a changed default save directory', async () => {+ const ctx = fakeCtx()+ const before = makeSettingsLike(PROXY_OFF, {+ defaultSaveDir: '/downloads/old',+ })+ const after = makeSettingsLike(PROXY_OFF, {+ defaultSaveDir: '/downloads/new',+ })+ const settingsManager = {+ ...ctx.settingsManager,+ get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),+ update: vi.fn().mockResolvedValue({+ ok: true,+ requiresRestart: false,+ changedRestartKeys: [],+ }),+ }+ const handlers = buildCommandHandlers({+ ...ctx,+ settingsManager,+ protocolManager: { register: vi.fn() },+ } as unknown as CommandContext)++ await handlers[Commands.UpdateSettings]?.({+ app: { defaultSaveDir: '/downloads/new' },+ })++ expect(ctx.supervisor.applyDefaultSaveDir).toHaveBeenCalledExactlyOnceWith(+ '/downloads/new'+ )+ })+it('saves restart-required settings and publishes a reminder without restarting', async () => {const ctx = fakeCtx()const settings = makeSettingsLike(PROXY_OFF)diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 1464161e..0365c7fc 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -1005,6 +1005,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {await proxyApplier.apply(oldFull.proxy, newFull.proxy)}+ if (oldFull.app.defaultSaveDir !== newFull.app.defaultSaveDir) {+ await supervisor.applyDefaultSaveDir(newFull.app.defaultSaveDir)+ }+if (oldFull.tracker.sourcesEnabled !== newFull.tracker.sourcesEnabled) {await trackerManager.applySourcesChange(newFull.tracker.sourcesEnabled)}diff --git a/src/renderer/components/add-task/file-type-filters.tsx b/src/renderer/components/add-task/file-type-filters.tsxindex 45c933c7..825d5a6f 100644--- a/src/renderer/components/add-task/file-type-filters.tsx+++ b/src/renderer/components/add-task/file-type-filters.tsx@@ -5,6 +5,7 @@ import {TooltipProvider,TooltipTrigger,} from '@renderer/components/ui/tooltip'+import { VIDEO_FILE_EXTENSIONS } from '@shared/constants/file-types'import type { AddTaskFormValues } from '@shared/schemas/add-task'import { FileText, Film, Image, Music } from 'lucide-react'import type { ReactNode } from 'react'@@ -19,18 +20,7 @@ const FILTERS: Array<{{id: 'video',icon: <Film className="h-3.5 w-3.5" />,- exts: [- '.mp4',- '.mkv',- '.avi',- '.mov',- '.wmv',- '.flv',- '.webm',- '.m4v',- '.ts',- '.rmvb',- ],+ exts: [...VIDEO_FILE_EXTENSIONS],},{id: 'audio',diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex f8dc01d4..8cd23bdb 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -51,6 +51,7 @@ function makeFakeCtx() {start: vi.fn().mockResolvedValue(undefined),applyEngineSettings: vi.fn().mockResolvedValue(undefined),applyAsyncDns: vi.fn().mockResolvedValue(undefined),+ applyDefaultSaveDir: vi.fn().mockResolvedValue(undefined),} as unknown as EngineSupervisor,dnsFallback: { reset: vi.fn() },settingsManager: {@@ -153,9 +154,14 @@ function makeFakeCtx() {function makeSettings(proxy: typeof PROXY_OFF,tracker: { sourcesEnabled?: boolean; blacklistEnabled?: boolean } = {},- engine: { dnsMode?: 'auto' | 'system' | 'engine'; split?: number } = {}+ engine: { dnsMode?: 'auto' | 'system' | 'engine'; split?: number } = {},+ app: { defaultSaveDir?: string } = {}) {return {+ app: {+ defaultSaveDir: '/downloads',+ ...app,+ },proxy,tracker: {sourcesEnabled: true,@@ -202,6 +208,31 @@ describe('server Commands.UpdateSettings', () => {expect(ctx.proxyApplier.apply).toHaveBeenCalledWith(PROXY_OFF, PROXY_ON)})+ it('hot-applies a changed default save directory', async () => {+ const ctx = makeFakeCtx()+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)+ .mockReturnValueOnce(+ makeSettings(PROXY_OFF, {}, {}, { defaultSaveDir: '/downloads/old' })+ )+ .mockReturnValueOnce(+ makeSettings(PROXY_OFF, {}, {}, { defaultSaveDir: '/downloads/new' })+ )+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(+ { ok: true, requiresRestart: false, changedRestartKeys: [] }+ )+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )++ await handlers[Commands.UpdateSettings]?.({+ app: { defaultSaveDir: '/downloads/new' },+ })++ expect(ctx.supervisor.applyDefaultSaveDir).toHaveBeenCalledExactlyOnceWith(+ '/downloads/new'+ )+ })+it('hot-applies async-dns and resets the fallback latch when dnsMode changes', async () => {const ctx = makeFakeCtx();(ctx.settingsManager.get as ReturnType<typeof vi.fn>)diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 3e53af3e..3cec1e90 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -632,6 +632,10 @@ export function buildServerCommandHandlers(await proxyApplier.apply(oldFull.proxy, newFull.proxy)}+ if (oldFull.app.defaultSaveDir !== newFull.app.defaultSaveDir) {+ await supervisor.applyDefaultSaveDir(newFull.app.defaultSaveDir)+ }+if (oldFull.tracker.sourcesEnabled !== newFull.tracker.sourcesEnabled) {await trackerManager.applySourcesChange(newFull.tracker.sourcesEnabled)}diff --git a/src/shared/constants/file-types.test.ts b/src/shared/constants/file-types.test.tsnew file mode 100644index 00000000..435da472--- /dev/null+++ b/src/shared/constants/file-types.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest'+import {+ containsOnlyVideoFiles,+ isVideoFilePath,+ VIDEO_FILE_EXTENSIONS,+} from './file-types'++describe('video file classification', () => {+ it('matches the shared video extension list case-insensitively', () => {+ expect(isVideoFilePath('Movie.MP4')).toBe(true)+ expect(isVideoFilePath('folder/episode.rMvB')).toBe(true)+ expect(isVideoFilePath('movie.mp4.part')).toBe(false)+ expect(VIDEO_FILE_EXTENSIONS).toContain('.mkv')+ })++ it('requires every declared file to be a video', () => {+ expect(containsOnlyVideoFiles(['movie.mkv', 'extras/trailer.webm'])).toBe(+ true+ )+ expect(containsOnlyVideoFiles(['movie.mkv', 'readme.txt'])).toBe(false)+ expect(containsOnlyVideoFiles([])).toBe(false)+ })+})diff --git a/src/shared/constants/file-types.ts b/src/shared/constants/file-types.tsnew file mode 100644index 00000000..2634bfce--- /dev/null+++ b/src/shared/constants/file-types.ts@@ -0,0 +1,28 @@+import { extractExtension } from '@shared/lib/path-ext'++/** Video extensions recognized consistently by torrent filtering and core. */+export const VIDEO_FILE_EXTENSIONS = [+ '.mp4',+ '.mkv',+ '.avi',+ '.mov',+ '.wmv',+ '.flv',+ '.webm',+ '.m4v',+ '.ts',+ '.rmvb',+] as const++const VIDEO_FILE_EXTENSION_SET: ReadonlySet<string> = new Set(+ VIDEO_FILE_EXTENSIONS+)++export function isVideoFilePath(filePath: string): boolean {+ return VIDEO_FILE_EXTENSION_SET.has(extractExtension(filePath))+}++/** Empty and mixed file lists are deliberately not treated as video-only. */+export function containsOnlyVideoFiles(filePaths: readonly string[]): boolean {+ return filePaths.length > 0 && filePaths.every(isVideoFilePath)+}diff --git a/src/shared/constants/restart-keys.ts b/src/shared/constants/restart-keys.tsindex 8a2792d9..8dbb3fa9 100644--- a/src/shared/constants/restart-keys.ts+++ b/src/shared/constants/restart-keys.ts@@ -16,6 +16,7 @@ export const ENGINE_RESTART_REQUIRED_KEYS: ReadonlySet<keyof EngineSettings> ='sqlite3Persistence','sqlite3DbPath','sqlite3HistoryLimit',+ 'sessionSaveInterval',])// Consumed by SettingsManager.update(), which reports requiresAppRestart to