A full-featured download manager.
fix(torrent): support large tasks and streamline detail updates (#2453)
Dr_rOotccfae79334e2
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.tsindex e6912b6b..48a29c89 100644--- a/src/core/engine/aria2/aria2-config-builder.test.ts+++ b/src/core/engine/aria2/aria2-config-builder.test.ts@@ -325,9 +325,7 @@ 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-max-request-size=64M')expect(args).toContain(`--rpc-listen-port=${DEFAULT_ENGINE_SETTINGS.rpcPort}`)diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.tsindex 559b384a..271e3ce4 100644--- a/src/core/engine/aria2/aria2-config-builder.ts+++ b/src/core/engine/aria2/aria2-config-builder.ts@@ -6,6 +6,7 @@ import {stripAria2ProxyCredentials,} from '@core/proxy/aria2-proxy-routing'import type { Aria2ProxyOptions } from '@core/proxy/serializers'+import { MAX_TORRENT_RPC_BODY_LIMIT_BYTES } from '@shared/lib/torrent-meta'import { torrentRpcBodyLimitSchema } from '@shared/schemas/torrent-request-limits'import type { EngineSettings } from '@shared/types/settings'import writeFileAtomic from 'write-file-atomic'@@ -31,7 +32,7 @@ export class Aria2ConfigBuilder {private readonly dhtFilePath: stringprivate readonly dht6FilePath: stringprivate readonly rpcListenAll: boolean- private readonly rpcMaxRequestSizeBytes?: number+ private readonly rpcMaxRequestSizeBytes: numberprivate readonly supervisorPid?: numberprivate readonly persistenceDirectory?: stringprivate configuredInputFile = false@@ -58,7 +59,7 @@ export class Aria2ConfigBuilder {this.rpcListenAll = options.rpcListenAll ?? falsethis.rpcMaxRequestSizeBytes =options.rpcMaxRequestSizeBytes === undefined- ? undefined+ ? MAX_TORRENT_RPC_BODY_LIMIT_BYTES: torrentRpcBodyLimitSchema.parse(options.rpcMaxRequestSizeBytes)if (options.supervisorPid !== undefined) {if (@@ -298,11 +299,11 @@ export class Aria2ConfigBuilder {)// ── L1 product-contract invariants — DO NOT REMOVE without spec change ──- if (this.rpcMaxRequestSizeBytes !== undefined) {- args.push(- `--rpc-max-request-size=${this.rpcMaxRequestSizeBytes / (1024 * 1024)}M`- )- }+ // Desktop accepts up to 50 MiB of Base64 plus per-file output mappings.+ // Never inherit aria2's 2 MiB default or an older copied config value.+ args.push(+ `--rpc-max-request-size=${this.rpcMaxRequestSizeBytes / (1024 * 1024)}M`+ )if (this.supervisorPid !== undefined) {args.push(`--stop-with-process=${this.supervisorPid}`)}diff --git a/src/core/engine/aria2/aria2-rpc-client.test.ts b/src/core/engine/aria2/aria2-rpc-client.test.tsindex 9fcb97c3..6f15a908 100644--- a/src/core/engine/aria2/aria2-rpc-client.test.ts+++ b/src/core/engine/aria2/aria2-rpc-client.test.ts@@ -81,6 +81,40 @@ describe('Aria2RpcClient', () => {vi.restoreAllMocks()})+ it('invalidates metadata after successful single and batch option edits, and on reconnect', async () => {+ const changed = vi.fn()+ const unsubscribe = client.onTaskMetadataChanged(changed)+ fakeProtocol.nextResult = 'OK'+ await client.changeOption('gid1', { 'select-file': '2' })+ expect(changed).toHaveBeenLastCalledWith('gid1')+ fakeProtocol.nextResult = ['OK']+ await client.multicall([+ { method: 'aria2.changeOption', params: ['gid2', { dir: '/new' }] },+ ])+ expect(changed).toHaveBeenLastCalledWith('gid2')+ fakeProtocol.nextResult = [+ { status: 'fulfilled', value: 'OK' },+ { status: 'rejected', reason: new Error('denied') },+ ]+ await client.multicallSettled([+ {+ method: 'aria2.changeOption',+ params: ['gid3', { 'select-file': '1' }],+ },+ {+ method: 'aria2.changeOption',+ params: ['gid4', { 'select-file': '1' }],+ },+ ])+ expect(changed.mock.calls).toEqual([['gid1'], ['gid2'], ['gid3']])+ await client.connect(6800)+ expect(changed).toHaveBeenLastCalledWith(undefined)+ unsubscribe()+ changed.mockClear()+ client.disconnect()+ expect(changed).not.toHaveBeenCalled()+ })+it.each([true, false])('reports the actual WebSocket connection state: %s',(connected) => {diff --git a/src/core/engine/aria2/aria2-rpc-client.ts b/src/core/engine/aria2/aria2-rpc-client.tsindex 488a8e59..3b234720 100644--- a/src/core/engine/aria2/aria2-rpc-client.ts+++ b/src/core/engine/aria2/aria2-rpc-client.ts@@ -36,6 +36,16 @@ export class Aria2RpcClient {private notificationHandlers = new Map<string, Set<EventHandler>>()private pauseState = new Aria2PauseState()private requestSequence = 0+ private metadataListeners = new Set<(gid?: string) => void>()++ onTaskMetadataChanged(handler: (gid?: string) => void): Unsubscribe {+ this.metadataListeners.add(handler)+ return () => this.metadataListeners.delete(handler)+ }++ private invalidateTaskMetadata(gid?: string): void {+ for (const listener of this.metadataListeners) listener(gid)+ }constructor(private transport: WebSocketTransport,@@ -51,6 +61,7 @@ export class Aria2RpcClient {async connect(port: number, retries = 10, delayMs = 500): Promise<void> {this.pauseState.clear()+ this.invalidateTaskMetadata()const url = `ws://127.0.0.1:${port}/jsonrpc`for (let attempt = 0; attempt < retries; attempt++) {try {@@ -65,6 +76,7 @@ export class Aria2RpcClient {disconnect(): void {this.pauseState.clear()+ this.invalidateTaskMetadata()this.transport.disconnect()}@@ -92,8 +104,31 @@ export class Aria2RpcClient {const finalParams = SECRET_EXEMPT_METHODS.has(method)? params: this.withSecret(params)- const result = await this.protocol.call<T>(method, finalParams)- return this.pauseState.reconcile(method, params, result, sequence) as T+ // Large file maps can take longer to initialize even when the request is+ // within the wire budget. Keep ordinary status/control deadlines short.+ const result = await this.protocol.call<T>(+ method,+ finalParams,+ method === 'aria2.addTorrent' ? { timeoutMs: 60_000 } : undefined+ )+ return this.reconcileResult(method, params, result, sequence) as T+ }++ private reconcileResult(+ method: string,+ params: unknown[],+ result: unknown,+ sequence: number+ ): unknown {+ if (+ method === 'aria2.changeOption' &&+ result === 'OK' &&+ typeof params[0] === 'string'+ ) {+ // Includes selection, output paths and URI-affecting task options.+ this.invalidateTaskMetadata(params[0])+ }+ return this.pauseState.reconcile(method, params, result, sequence)}// ─── Download management ─────────────────────────────────────@@ -321,7 +356,7 @@ export class Aria2RpcClient {}))const results = await this.protocol.multicall(withSecret)return results.map((result, index) =>- this.pauseState.reconcile(+ this.reconcileResult(calls[index].method,calls[index].params,result,@@ -351,7 +386,7 @@ export class Aria2RpcClient {result.status === 'fulfilled'? {status: 'fulfilled',- value: this.pauseState.reconcile(+ value: this.reconcileResult(calls[index].method,calls[index].params,result.value,diff --git a/src/core/engine/aria2/json-rpc-protocol.test.ts b/src/core/engine/aria2/json-rpc-protocol.test.tsindex d47c151a..1e540be1 100644--- a/src/core/engine/aria2/json-rpc-protocol.test.ts+++ b/src/core/engine/aria2/json-rpc-protocol.test.ts@@ -1,5 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { JsonRpcProtocol } from './json-rpc-protocol'+import {+ JsonRpcProtocol,+ JsonRpcRequestTooLargeError,+} from './json-rpc-protocol'import type { WebSocketTransport } from './web-socket-transport'class FakeTransport {@@ -62,6 +65,96 @@ describe('JsonRpcProtocol', () => {})describe('call', () => {+ it('rejects the complete UTF-8 request before sending or creating a timeout', async () => {+ const params = [+ 'small torrent',+ [],+ { 'index-out': ['1=目录/文件.bin'.repeat(20)] },+ ]+ const request = JSON.stringify({+ jsonrpc: '2.0',+ id: '1',+ method: 'aria2.addTorrent',+ params,+ })+ const bytes = Buffer.byteLength(request)+ const limited = new JsonRpcProtocol(+ transport as unknown as WebSocketTransport,+ { maxRequestBytes: bytes - 1 }+ )+ await expect(+ limited.call('aria2.addTorrent', params)+ ).rejects.toBeInstanceOf(JsonRpcRequestTooLargeError)+ expect(transport.sent).toHaveLength(0)+ expect(vi.getTimerCount()).toBe(0)+ const exact = new JsonRpcProtocol(+ transport as unknown as WebSocketTransport,+ { maxRequestBytes: bytes }+ )+ const accepted = exact.call('aria2.addTorrent', params)+ transport._respondTo('1', 'gid')+ await expect(accepted).resolves.toBe('gid')+ })++ it('reports an uncorrelated parse error immediately when there is only one pending call', async () => {+ const result = protocol.call('aria2.addTorrent', ['torrent'])+ transport._receive(+ JSON.stringify({+ jsonrpc: '2.0',+ id: null,+ error: { code: -32700, message: 'Parse error.' },+ })+ )+ await expect(result).rejects.toThrow(+ 'JSON-RPC peer reported -32700: Parse error.'+ )+ expect(vi.getTimerCount()).toBe(0)+ })++ it('does not attribute a null-id error to successful concurrent calls', async () => {+ const failed = protocol.call('aria2.addTorrent', ['torrent'])+ const healthy = protocol.call('aria2.getVersion', [])+ transport._receive(+ JSON.stringify({+ jsonrpc: '2.0',+ id: null,+ error: { code: -32700, message: 'Parse error.' },+ })+ )+ transport._respondTo('2', 'version')+ await expect(healthy).resolves.toBe('version')+ const failure = expect(failed).rejects.toThrow(+ /Parse error.*outcome is unknown/+ )+ await vi.advanceTimersByTimeAsync(5001)+ await failure+ expect(vi.getTimerCount()).toBe(0)+ })++ it('allows a longer add deadline without extending ordinary control calls', async () => {+ const add = protocol.call('aria2.addTorrent', ['torrent'], {+ timeoutMs: 60_000,+ })+ const control = protocol.call('aria2.getGlobalStat', [])+ const controlFailure = expect(control).rejects.toThrow(+ 'timed out after 5000ms'+ )+ await vi.advanceTimersByTimeAsync(10_001)+ await controlFailure+ transport._respondTo('1', 'gid')+ await expect(add).resolves.toBe('gid')+ })++ it('cleans pending state and the timer when sending fails', async () => {+ vi.spyOn(transport, 'send').mockImplementationOnce(() => {+ throw new Error('not connected')+ })+ await expect(protocol.call('aria2.addTorrent', [])).rejects.toThrow(+ 'not connected'+ )+ expect(vi.getTimerCount()).toBe(0)+ })+it('sends a JSON-RPC 2.0 request and resolves on response', async () => {const resultPromise = protocol.call<string>('aria2.getVersion', [])expect(transport.sent).toHaveLength(1)diff --git a/src/core/engine/aria2/json-rpc-protocol.ts b/src/core/engine/aria2/json-rpc-protocol.tsindex ba720787..6b03a0de 100644--- a/src/core/engine/aria2/json-rpc-protocol.ts+++ b/src/core/engine/aria2/json-rpc-protocol.ts@@ -1,9 +1,11 @@+import { MAX_TORRENT_RPC_BODY_LIMIT_BYTES } from '@shared/lib/torrent-meta'import type { WebSocketTransport } from './web-socket-transport'interface PendingRequest {resolve: (value: unknown) => voidreject: (reason: Error) => voidtimer: ReturnType<typeof setTimeout>+ uncorrelatedError?: Error}interface JsonRpcRequest {@@ -15,7 +17,7 @@ interface JsonRpcRequest {interface JsonRpcResponse {jsonrpc: '2.0'- id?: string+ id?: string | nullmethod?: stringparams?: unknown[]result?: unknown@@ -29,6 +31,20 @@ interface MulticallEntry {export interface JsonRpcProtocolOptions {timeoutMs?: number+ maxRequestBytes?: number+}++export interface JsonRpcCallOptions {+ timeoutMs?: number+}++export class JsonRpcRequestTooLargeError extends Error {+ constructor(method: string, requestBytes: number, maxRequestBytes: number) {+ super(+ `JSON-RPC request "${method}" is ${requestBytes} bytes, exceeding the configured ${maxRequestBytes}-byte limit (including metadata and options)`+ )+ this.name = 'JsonRpcRequestTooLargeError'+ }}export class JsonRpcProtocol {@@ -38,16 +54,29 @@ export class JsonRpcProtocol {| ((method: string, params: unknown[]) => void)| null = nullprivate readonly timeoutMs: number+ private readonly maxRequestBytes: numberconstructor(private transport: WebSocketTransport,options: JsonRpcProtocolOptions = {}) {this.timeoutMs = options.timeoutMs ?? 10_000+ this.maxRequestBytes =+ options.maxRequestBytes ?? MAX_TORRENT_RPC_BODY_LIMIT_BYTES+ if (+ !Number.isSafeInteger(this.maxRequestBytes) ||+ this.maxRequestBytes <= 0+ ) {+ throw new TypeError('maxRequestBytes must be a positive safe integer')+ }this.transport.onMessage((data) => this.handleMessage(data))}- call<T>(method: string, params: unknown[]): Promise<T> {+ call<T>(+ method: string,+ params: unknown[],+ options: JsonRpcCallOptions = {}+ ): Promise<T> {const id = String(this.nextId++)const request: JsonRpcRequest = {jsonrpc: '2.0',@@ -57,14 +86,32 @@ export class JsonRpcProtocol {}return new Promise<T>((resolve, reject) => {+ // Measure the exact UTF-8 envelope, including tokens, index-out and+ // select-file. A Base64-only check misses large multi-file requests.+ const serialized = JSON.stringify(request)+ const requestBytes = Buffer.byteLength(serialized, 'utf8')+ if (requestBytes > this.maxRequestBytes) {+ reject(+ new JsonRpcRequestTooLargeError(+ method,+ requestBytes,+ this.maxRequestBytes+ )+ )+ return+ }+ const timeoutMs = options.timeoutMs ?? this.timeoutMsconst timer = setTimeout(() => {+ const diagnostic = this.pending.get(id)?.uncorrelatedErrorthis.pending.delete(id)reject(new Error(- `JSON-RPC call "${method}" timed out after ${this.timeoutMs}ms`+ diagnostic+ ? `No matching JSON-RPC response for "${method}" after ${timeoutMs}ms; ${diagnostic.message}; request outcome is unknown`+ : `JSON-RPC call "${method}" timed out after ${timeoutMs}ms`))- }, this.timeoutMs)+ }, timeoutMs)this.pending.set(id, {resolve: resolve as (value: unknown) => void,@@ -72,7 +119,13 @@ export class JsonRpcProtocol {timer,})- this.transport.send(JSON.stringify(request))+ try {+ this.transport.send(serialized)+ } catch (error) {+ clearTimeout(timer)+ this.pending.delete(id)+ reject(error)+ }})}@@ -136,7 +189,29 @@ export class JsonRpcProtocol {return}- if (msg.id !== undefined) {+ if (msg.id === null && msg.error) {+ const error = new Error(+ `JSON-RPC peer reported ${msg.error.code}: ${msg.error.message} without a request id`+ )+ const single =+ this.pending.size === 1+ ? this.pending.entries().next().value+ : undefined+ if (single) {+ const [id, pending] = single+ clearTimeout(pending.timer)+ this.pending.delete(id)+ pending.reject(error)+ } else {+ // Do not guess which concurrent mutation failed or reject successful+ // unrelated calls. Preserve the peer's diagnostic for unresolved calls.+ for (const pending of this.pending.values())+ pending.uncorrelatedError = error+ }+ return+ }++ if (typeof msg.id === 'string') {const pending = this.pending.get(msg.id)if (!pending) returndiff --git a/src/core/engine/aria2/large-torrent.integration.test.ts b/src/core/engine/aria2/large-torrent.integration.test.tsnew file mode 100644index 00000000..d00372b9--- /dev/null+++ b/src/core/engine/aria2/large-torrent.integration.test.ts@@ -0,0 +1,128 @@+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'+import { TorrentParser } from '@core/torrent/torrent-parser'+import {+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { expect, it } from 'vitest'+import { Aria2ConfigBuilder } from './aria2-config-builder'++it.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'adds a 78.02 GB, 7,458-file torrent whose metadata and output mappings exceed 2 MiB',+ async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-large-torrent-'))+ let handle: Awaited<ReturnType<typeof spawnAria2ForTest>> | undefined+ let disconnect: (() => void) | undefined+ try {+ const count = 7458+ const total = 78_020_000_000+ const pieceLength = 4 * 1024 * 1024+ const names = Array.from({ length: count }, (_, index) => [+ `folder-${Math.floor(index / 100)}`,+ `${String(index).padStart(5, '0')}-${'x'.repeat(50)}.bin`,+ ])+ const files = names+ .map((parts, index) => {+ const length =+ Math.floor(total / count) ++ (index === count - 1 ? total % count : 0)+ return `d6:lengthi${length}e4:pathl${parts.map((part) => `${part.length}:${part}`).join('')}ee`+ })+ .join('')+ const pieces = Buffer.alloc(Math.ceil(total / pieceLength) * 20, 1)+ const metadata = Buffer.concat([+ Buffer.from(+ `d4:infod5:filesl${files}e4:name6:bundle12:piece lengthi${pieceLength}e6:pieces${pieces.length}:`+ ),+ pieces,+ Buffer.from('7:privatei1eee'),+ ])+ const parsed = await new TorrentParser().parse(+ metadata.toString('base64')+ )+ expect(parsed.files).toHaveLength(count)+ expect(parsed.totalSize).toBe(total)+ const outputRoot = path.join(root, 'downloads', 'bundle')+ const mappings = names.map((parts, fileIndex) => ({+ fileIndex,+ relativePath: parts.join('/'),+ }))+ const requestBytes = Buffer.byteLength(+ JSON.stringify({+ jsonrpc: '2.0',+ id: '1',+ method: 'aria2.addTorrent',+ params: [+ metadata.toString('base64'),+ [],+ {+ 'select-file': names.map((_, index) => index + 1).join(','),+ 'index-out': mappings.map(+ (file) =>+ `${file.fileIndex + 1}=${path.join(outputRoot, file.relativePath)}`+ ),+ },+ ],+ })+ )+ expect(requestBytes).toBeGreaterThan(2 * 1024 * 1024)+ // Exercise the production default, overriding a stale copied 2M config.+ const builder = new Aria2ConfigBuilder('', root)+ const args = builder.buildArgs(+ DEFAULT_ENGINE_SETTINGS,+ false,+ null,+ { download: 0, upload: 0 },+ root+ )+ handle = await spawnAria2ForTest({+ baseDir: root,+ extraArgs: [+ '--rpc-max-request-size=2M',+ ...args.filter((arg) => arg.startsWith('--rpc-max-request-size=')),+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ '--file-allocation=none',+ '--enable-sqlite3-persistence=true',+ `--sqlite3-db-path=${path.join(root, 'engine.db')}`,+ ],+ })+ const wired = await connectAdapter(handle)+ disconnect = wired.disconnect+ const start = performance.now()+ const gid = await wired.adapter.addTorrent({+ metadata,+ saveDir: path.join(root, 'metadata.state'),+ outputRoot,+ outputFilePaths: mappings,+ selectedFiles: names.map((_, index) => index + 1),+ pause: true,+ isPrivate: true,+ })+ const elapsedMs = performance.now() - start+ const result = await wired.adapter.getTaskFiles(gid)+ expect(result).toHaveLength(count)+ expect(result.every((file) => file.selected)).toBe(true)+ expect(result.at(-1)?.path).toBe(path.join(outputRoot, ...names.at(-1)!))+ expect((await wired.rpc.tellStatus(gid, ['status'])).status).toBe(+ 'paused'+ )+ console.info('large-torrent regression', {+ files: count,+ metadataBytes: metadata.length,+ requestBytes,+ elapsedMs,+ })+ } finally {+ disconnect?.()+ await handle?.kill()+ await rm(root, { recursive: true, force: true })+ }+ },+ 20_000+)diff --git a/src/core/engine/aria2/polling-scheduler.test.ts b/src/core/engine/aria2/polling-scheduler.test.tsindex e6595b58..aaac1090 100644--- a/src/core/engine/aria2/polling-scheduler.test.ts+++ b/src/core/engine/aria2/polling-scheduler.test.ts@@ -7,13 +7,20 @@ import {PollingScheduler,type PollingTaskUpdateSource,} from './polling-scheduler'-import type { Aria2RawGlobalStat, Aria2RawStatus } from './types'+import { TASK_STATUS_FIELDS } from './task-status-fields'+import type {+ Aria2RawGlobalStat,+ Aria2RawStatus,+ Aria2TaskStatus,+} from './types'// ─── Mock RpcClient ─────────────────────────────────────────function createMockRpc(): Aria2RpcClient {return {getGlobalStat: vi.fn(),+ getFiles: vi.fn(),+ onTaskMetadataChanged: vi.fn(() => vi.fn()),tellStatus: vi.fn(),multicall: vi.fn(),} as unknown as Aria2RpcClient@@ -88,7 +95,7 @@ describe('PollingScheduler', () => {let eventBus: EventBuslet onStats: ((stats: GlobalStats) => void) & ReturnType<typeof vi.fn>let onTasksUpdate: ((- tasks: Aria2RawStatus[],+ tasks: Aria2TaskStatus[],source: PollingTaskUpdateSource) => void) &ReturnType<typeof vi.fn>@@ -101,7 +108,7 @@ describe('PollingScheduler', () => {onStats = vi.fn() as ((stats: GlobalStats) => void) &ReturnType<typeof vi.fn>onTasksUpdate = vi.fn() as ((- tasks: Aria2RawStatus[],+ tasks: Aria2TaskStatus[],source: PollingTaskUpdateSource) => void) &ReturnType<typeof vi.fn>@@ -114,6 +121,67 @@ describe('PollingScheduler', () => {vi.restoreAllMocks()})+ it('keeps steady list polls compact while refreshing metadata after an option edit', async () => {+ const { files: _files, ...summary } = ACTIVE_TASKS[0]+ vi.mocked(rpc.getFiles).mockResolvedValue([+ {+ index: '1',+ path: '/tmp/file',+ length: '100',+ completedLength: '50',+ selected: 'true',+ uris: [],+ },+ ])+ vi.mocked(rpc.multicall).mockResolvedValue([ACTIVE_STAT, [summary], []])+ scheduler.start()+ await vi.advanceTimersByTimeAsync(5000)+ expect(rpc.getFiles).toHaveBeenCalledTimes(1)+ const latest = onTasksUpdate.mock.calls.at(-1)?.[0][0]+ expect(latest).not.toHaveProperty('files')+ expect(latest).toMatchObject({+ fileMetadata: { fileCount: 1, selectedFiles: [0] },+ })+ // Exercise the scheduler's actual RPC request rather than just its constant.+ for (const calls of vi.mocked(rpc.multicall).mock.calls) {+ const keys = calls[0][1].params[0] as string[]+ expect(keys).not.toContain('files')+ expect(keys).not.toContain('bitfield')+ }+ vi.mocked(rpc.getFiles).mockResolvedValue([+ {+ index: '1',+ path: '/tmp/file',+ length: '100',+ completedLength: '50',+ selected: 'false',+ uris: [],+ },+ ])+ vi.mocked(rpc.onTaskMetadataChanged).mock.calls[0][0]('gid1')+ await vi.advanceTimersByTimeAsync(0)+ expect(rpc.getFiles).toHaveBeenCalledTimes(2)+ expect(onTasksUpdate.mock.calls.at(-1)?.[0][0]).toMatchObject({+ fileMetadata: { selectedFiles: [] },+ })+ })++ it('ignores a list response captured before reconnect instead of repopulating old metadata', async () => {+ let resolveOld!: (value: unknown[]) => void+ vi.mocked(rpc.multicall).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve+ })+ )+ scheduler.start()+ vi.mocked(rpc.onTaskMetadataChanged).mock.calls[0][0]()+ resolveOld([ACTIVE_STAT, ACTIVE_TASKS, []])+ await vi.advanceTimersByTimeAsync(0)+ expect(onTasksUpdate).not.toHaveBeenCalled()+ expect(rpc.getFiles).not.toHaveBeenCalled()+ })+describe('start / stop', () => {it('starts in idle mode and polls at 10s interval', async () => {vi.mocked(rpc.multicall).mockResolvedValue([IDLE_STAT, [], []])@@ -270,8 +338,11 @@ describe('PollingScheduler', () => {gid: 'gid1',})- expect(rpc.tellStatus).toHaveBeenCalledWith('gid1')- expect(onTasksUpdate).toHaveBeenCalledWith([PAUSED_TASK], 'notification')+ expect(rpc.tellStatus).toHaveBeenCalledWith('gid1', TASK_STATUS_FIELDS)+ expect(onTasksUpdate).toHaveBeenCalledWith(+ [expect.objectContaining({ gid: 'gid1', status: 'paused' })],+ 'notification'+ )expect(emitted).toEqual([false])})@@ -320,7 +391,7 @@ describe('PollingScheduler', () => {expect(rpc.multicall).toHaveBeenCalledTimes(3)expect(onStats).toHaveBeenCalledWith(ACTIVE_STATS_TRANSLATED)expect(onTasksUpdate).toHaveBeenCalledWith(- ACTIVE_TASKS,+ [expect.objectContaining({ gid: 'gid1', status: 'active' })],'authoritative-poll')})diff --git a/src/core/engine/aria2/polling-scheduler.ts b/src/core/engine/aria2/polling-scheduler.tsindex a9190b99..44dc3c65 100644--- a/src/core/engine/aria2/polling-scheduler.ts+++ b/src/core/engine/aria2/polling-scheduler.ts@@ -3,8 +3,10 @@ import { Events } from '@shared/protocol/events'import type { GlobalStats } from '@shared/types/stats'import type { EventBus } from '../../events/event-bus'import type { Aria2RpcClient } from './aria2-rpc-client'+import { TaskFileMetadata } from './task-file-metadata'+import { TASK_STATUS_FIELDS } from './task-status-fields'import { translateGlobalStat } from './translate'-import type { Aria2RawStatus } from './types'+import type { Aria2RawStatus, Aria2TaskStatus } from './types'const log = getLogger('polling-scheduler')@@ -33,18 +35,32 @@ export class PollingScheduler {private pendingPoll = falseprivate inFlightPoll: Promise<void> | null = nullprivate drainPromise: Promise<void> | null = null+ private metadata: TaskFileMetadata+ private unsubscribeMetadata: (() => void) | null = null+ private epoch = 0constructor(private rpc: Aria2RpcClient,private eventBus: EventBus,private onStats: (stats: GlobalStats) => void,private onTasksUpdate: (- tasks: Aria2RawStatus[],+ tasks: Aria2TaskStatus[],source: PollingTaskUpdateSource) => void | Promise<void>- ) {}+ ) {+ this.metadata = new TaskFileMetadata(rpc)+ }start(): void {+ this.epoch += 1+ this.unsubscribeMetadata?.()+ this.metadata.invalidate()+ this.unsubscribeMetadata = this.rpc.onTaskMetadataChanged((gid) => {+ this.metadata.invalidate(gid)+ if (gid === undefined) this.epoch += 1+ if (gid !== undefined) this.requestPoll()+ })+ this.drainPromise = nullthis.mode = 'idle'this.stopped = false// Fire an immediate first poll, then chain@@ -58,8 +74,12 @@ export class PollingScheduler {stopAndDrain(): Promise<void> {if (this.drainPromise) return this.drainPromisethis.stopped = true+ this.epoch += 1this.pendingPoll = falsethis.clearTimer()+ this.unsubscribeMetadata?.()+ this.unsubscribeMetadata = null+ this.metadata.invalidate()const inFlight = this.inFlightPollthis.drainPromise = inFlight? inFlight.then(@@ -104,10 +124,13 @@ export class PollingScheduler {}private async syncNotifiedTask(gid: string): Promise<void> {+ const epoch = this.epochtry {- const task = await this.rpc.tellStatus(gid)- if (this.stopped) return- await this.onTasksUpdate([task], 'notification')+ const raw = await this.rpc.tellStatus(gid, TASK_STATUS_FIELDS)+ if (this.stopped || epoch !== this.epoch) return+ const task = await this.metadata.hydrate(raw)+ if (this.stopped || epoch !== this.epoch) return+ if (task) await this.onTasksUpdate([task], 'notification')} catch (err) {log.debug({ err, gid }, 'notification task sync failed')}@@ -200,12 +223,13 @@ export class PollingScheduler {// aria2.onDownloadStart, leaving freshly added tasks stuck at the// renderer's initial Queued placeholder until polling reconciles.private async pollOnce(): Promise<void> {+ const epoch = this.epochconst results = await this.rpc.multicall([{ method: 'aria2.getGlobalStat', params: [] },- { method: 'aria2.tellActive', params: [] },- { method: 'aria2.tellWaiting', params: [0, 1000] },+ { method: 'aria2.tellActive', params: [TASK_STATUS_FIELDS] },+ { method: 'aria2.tellWaiting', params: [0, 1000, TASK_STATUS_FIELDS] },])- if (this.stopped) return+ if (this.stopped || epoch !== this.epoch) returnconst rawStats = results[0] as import('./types').Aria2RawGlobalStatconst rawActive = results[1] as Aria2RawStatus[]@@ -221,9 +245,19 @@ export class PollingScheduler {}this.onStats(translateGlobalStat(rawStats))- await this.onTasksUpdate(- [...rawActive, ...rawWaiting],- 'authoritative-poll'- )+ const statuses = [...rawActive, ...rawWaiting]+ this.metadata.retain(new Set(statuses.map((task) => task.gid)))+ // Bound metadata fan-out during restore; ordinary list polls do no file IO.+ const tasks: Aria2TaskStatus[] = []+ for (let offset = 0; offset < statuses.length; offset += 4) {+ const batch = await Promise.all(+ statuses+ .slice(offset, offset + 4)+ .map((raw) => this.metadata.hydrate(raw))+ )+ if (this.stopped || epoch !== this.epoch) return+ for (const task of batch) if (task) tasks.push(task)+ }+ await this.onTasksUpdate(tasks, 'authoritative-poll')}}diff --git a/src/core/engine/aria2/task-data-streams.integration.test.ts b/src/core/engine/aria2/task-data-streams.integration.test.tsnew file mode 100644index 00000000..04fade98--- /dev/null+++ b/src/core/engine/aria2/task-data-streams.integration.test.ts@@ -0,0 +1,90 @@+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { EventBus } from '@core/events/event-bus'+import { TaskStatus } from '@shared/types/task'+import {+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import { expect, it, vi } from 'vitest'+import { PollingScheduler } from './polling-scheduler'+import { translateRawToTask } from './translate'+import type { Aria2TaskStatus } from './types'++it.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'keeps 7,458-file tasks out of list RPC payloads and reconciles selection edits (real aria2)',+ async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-task-streams-'))+ const handle = await spawnAria2ForTest({ baseDir: root })+ const wired = await connectAdapter(handle)+ const getFiles = vi.spyOn(wired.rpc, 'getFiles')+ const multicall = vi.spyOn(wired.rpc, 'multicall')+ let latest: Aria2TaskStatus | undefined+ let updates = 0+ const scheduler = new PollingScheduler(+ wired.rpc,+ new EventBus(),+ () => {},+ (tasks) => {+ if (tasks[0]) latest = tasks[0]+ updates += 1+ }+ )+ try {+ const count = 7458+ const names = Array.from(+ { length: count },+ (_, index) => `file-${index}.bin`+ )+ const files = names+ .map((name) => `d6:lengthi1e4:pathl${name.length}:${name}ee`)+ .join('')+ const torrent = Buffer.concat([+ Buffer.from(+ `d4:infod5:filesl${files}e4:name6:bundle12:piece lengthi16384e6:pieces20:`+ ),+ Buffer.alloc(20, 1),+ Buffer.from('7:privatei1eee'),+ ])+ const gid = await wired.adapter.addTorrent({+ metadata: torrent,+ saveDir: root,+ pause: true,+ })+ scheduler.start()+ await vi.waitFor(() => expect(latest?.gid).toBe(gid))+ expect(translateRawToTask(latest!).fileCount).toBe(count)+ expect(translateRawToTask(latest!).bt?.selectedFiles).toHaveLength(count)+ expect(translateRawToTask(latest!).status).toBe(TaskStatus.Paused)+ const before = updates+ await scheduler.handleNotification('aria2.onDownloadPause', { gid })+ await vi.waitFor(() => expect(updates).toBeGreaterThan(before + 1))+ expect(getFiles).toHaveBeenCalledTimes(1)+ const results = (await multicall.mock.results.at(-1)!.value) as unknown[]+ // The wire results themselves, before cache hydration, stay small.+ expect(Buffer.byteLength(JSON.stringify(results))).toBeLessThan(10_000)+ expect(JSON.stringify(results)).not.toContain('file-7457.bin')++ await wired.rpc.changeOption(gid, { 'select-file': '2-3' })+ await vi.waitFor(() =>+ expect(translateRawToTask(latest!).bt?.selectedFiles).toEqual([1, 2])+ )+ expect(getFiles).toHaveBeenCalledTimes(2)+ const details = await wired.adapter.getTaskFiles(gid)+ expect(details).toHaveLength(count)+ expect(+ details.filter((file) => file.selected).map((file) => file.index)+ ).toEqual([1, 2])+ expect(details.at(-1)?.path).toContain('file-7457.bin')+ } finally {+ await scheduler.stopAndDrain()+ wired.disconnect()+ await handle.kill()+ await rm(root, { recursive: true, force: true })+ }+ },+ 20_000+)diff --git a/src/core/engine/aria2/task-file-metadata.test.ts b/src/core/engine/aria2/task-file-metadata.test.tsnew file mode 100644index 00000000..bac243fc--- /dev/null+++ b/src/core/engine/aria2/task-file-metadata.test.ts@@ -0,0 +1,305 @@+import {+ hasEngineTaskDelta,+ mergeEngineTask,+} from '@core/task/merge-engine-task'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { TaskFileMetadata } from './task-file-metadata'+import { TASK_STATUS_FIELDS } from './task-status-fields'+import { translateRawToTask } from './translate'+import type { Aria2RawFile, Aria2RawStatus } from './types'++const file: Aria2RawFile = {+ index: '1',+ path: '/downloads/video.mp4.motrix',+ length: '1000',+ completedLength: '400',+ selected: 'true',+ uris: [{ uri: 'https://example.test/video.mp4', status: 'used' }],+}+const raw: Aria2RawStatus = {+ gid: 'a000000000000001',+ status: 'active',+ totalLength: '1000',+ completedLength: '400',+ uploadLength: '300',+ downloadSpeed: '10',+ uploadSpeed: '20',+ connections: '3',+ numSeeders: '7',+ seeder: 'false',+ pieceLength: '100',+ numPieces: '10',+ dir: '/downloads',+ files: [file],+ followedBy: ['next'],+ following: 'previous',+ belongsTo: 'parent',+}+const bt = {+ mode: 'multi' as const,+ info: { name: 'bundle' },+ announceList: [['https://tracker.test']],+ comment: 'comment',+}+function compact(status: Aria2RawStatus) {+ return Object.fromEntries(+ TASK_STATUS_FIELDS.filter((key) => key in status).map((key) => [+ key,+ status[key],+ ])+ ) as Omit<Aria2RawStatus, 'files'>+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(100_000)+})+afterEach(() => vi.useRealTimers())++describe('file metadata stream', () => {+ it.each([+ ['HTTP with a server-provided filename', raw],+ [+ 'FTP',+ {+ ...raw,+ files: [+ {+ ...file,+ uris: [{ uri: 'ftp://host/file', status: 'used' as const }],+ },+ ],+ },+ ],+ [+ 'magnet metadata',+ {+ ...raw,+ totalLength: '0',+ bittorrent: bt,+ files: [+ {+ ...file,+ uris: [{ uri: 'magnet:?xt=urn:btih:abc', status: 'used' as const }],+ },+ ],+ },+ ],+ [+ 'BT download',+ {+ ...raw,+ bittorrent: bt,+ infoHash: 'a'.repeat(40),+ files: [+ { ...file, uris: [] },+ { ...file, index: '2', selected: 'false', uris: [] },+ ],+ },+ ],+ [+ 'BT seeding',+ {+ ...raw,+ bittorrent: bt,+ seeder: 'true',+ completedLength: '1000',+ files: [{ ...file, uris: [] }],+ },+ ],+ ['paused', { ...raw, status: 'paused' as const }],+ ['completed', { ...raw, status: 'complete' as const }],+ [+ 'error diagnosis',+ {+ ...raw,+ status: 'error' as const,+ errorCode: '9',+ errorMessage: 'No space left on device',+ },+ ],+ ])('preserves full-snapshot behavior for %s', async (_label, full) => {+ const rpc = { getFiles: vi.fn().mockResolvedValue(full.files) }+ const metadata = new TaskFileMetadata(rpc)+ const polled = await metadata.hydrate(compact(full))+ expect(translateRawToTask(polled!)).toEqual(translateRawToTask(full))+ expect(polled?.following).toBe(full.following)+ expect(polled?.followedBy).toEqual(full.followedBy)+ expect(polled?.belongsTo).toBe(full.belongsTo)+ expect(polled).not.toHaveProperty('files')+ })++ it('updates dynamic metrics without rereading or rebuilding file selection', async () => {+ const rpc = {+ getFiles: vi.fn().mockResolvedValue(+ Array.from({ length: 7458 }, (_, i) => ({+ ...file,+ index: String(i + 1),+ }))+ ),+ }+ const metadata = new TaskFileMetadata(rpc)+ const first = await metadata.hydrate(compact(raw))+ const next = await metadata.hydrate({+ ...compact(raw),+ completedLength: '900',+ uploadLength: '500',+ seeder: 'true',+ })+ expect(rpc.getFiles).toHaveBeenCalledTimes(1)+ expect(next?.fileMetadata).toBe(first?.fileMetadata)+ expect(translateRawToTask(next!).downloadedBytes).toBe(900)+ expect(translateRawToTask(next!).uploadedBytes).toBe(500)+ expect(translateRawToTask(next!).fileCount).toBe(7458)+ })++ it('coalesces reads and discards an old response after selection invalidation', async () => {+ let resolveOld!: (files: Aria2RawFile[]) => void+ const rpc = {+ getFiles: vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve+ })+ )+ .mockResolvedValue([{ ...file, selected: 'false' }]),+ }+ const metadata = new TaskFileMetadata(rpc)+ const first = metadata.hydrate(compact(raw))+ const second = metadata.hydrate(compact(raw))+ expect(rpc.getFiles).toHaveBeenCalledTimes(1)+ metadata.invalidate(raw.gid)+ const current = await metadata.hydrate(compact(raw))+ resolveOld([file])+ expect(await first).toBeNull()+ expect(await second).toBeNull()+ expect(current?.fileMetadata.selectedFiles).toEqual([])+ expect((await metadata.hydrate(compact(raw)))?.fileMetadata).toBe(+ current?.fileMetadata+ )+ })++ it('retries metadata arrival and a failed read without adopting an incomplete identity', async () => {+ const rpc = {+ getFiles: vi+ .fn()+ .mockRejectedValueOnce(new Error('unavailable'))+ .mockResolvedValueOnce([])+ .mockResolvedValue([file]),+ }+ const metadata = new TaskFileMetadata(rpc)+ expect(await metadata.hydrate(compact(raw))).toBeNull()+ await vi.advanceTimersByTimeAsync(1000)+ expect((await metadata.hydrate(compact(raw)))?.fileMetadata.fileCount).toBe(+ 0+ )+ await vi.advanceTimersByTimeAsync(1000)+ expect((await metadata.hydrate(compact(raw)))?.fileMetadata.fileCount).toBe(+ 1+ )+ })++ it('refreshes on metadata resolution and preserves terminal errors if files were evicted', async () => {+ const rpc = {+ getFiles: vi+ .fn()+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([file])+ .mockRejectedValue(new Error('GID is not found')),+ }+ const metadata = new TaskFileMetadata(rpc)+ await metadata.hydrate({ ...compact(raw), totalLength: '0' })+ const ready = await metadata.hydrate(compact(raw))+ const failed = await metadata.hydrate({+ ...compact(raw),+ status: 'error',+ errorCode: '9',+ errorMessage: 'disk full',+ })+ expect(rpc.getFiles).toHaveBeenCalledTimes(3)+ expect(failed?.fileMetadata).toBe(ready?.fileMetadata)+ expect(translateRawToTask(failed!).errorMessage).toBe('disk full')+ })++ it('reconciles external selection edits and publishes metadata-only changes', async () => {+ const full = { ...raw, bittorrent: bt }+ const rpc = {+ getFiles: vi+ .fn()+ .mockResolvedValueOnce([file])+ .mockResolvedValue([{ ...file, selected: 'false' }]),+ }+ const metadata = new TaskFileMetadata(rpc)+ const before = translateRawToTask((await metadata.hydrate(compact(full)))!)+ await vi.advanceTimersByTimeAsync(60_000)+ const after = mergeEngineTask(+ before,+ translateRawToTask((await metadata.hydrate(compact(full)))!)+ )+ expect(after.bt?.selectedFiles).toEqual([])+ expect(hasEngineTaskDelta(before, after)).toBe(true)+ })++ it('clears metadata on reconnect and prunes tasks no longer in the live snapshot', async () => {+ const rpc = { getFiles: vi.fn().mockResolvedValue([file]) }+ const metadata = new TaskFileMetadata(rpc)+ await metadata.hydrate(compact(raw))+ metadata.invalidate()+ await metadata.hydrate(compact(raw))+ await vi.advanceTimersByTimeAsync(60_001)+ metadata.retain(new Set())+ await metadata.hydrate(compact(raw))+ expect(rpc.getFiles).toHaveBeenCalledTimes(3)+ })++ it('keeps terminal identity across live-list disappearance even before the notification arrives', async () => {+ const rpc = {+ getFiles: vi+ .fn()+ .mockResolvedValueOnce([file])+ .mockRejectedValue(new Error('GID is not found')),+ }+ const metadata = new TaskFileMetadata(rpc)+ await metadata.hydrate(compact(raw))+ metadata.retain(new Set())+ const terminal = await metadata.hydrate({+ ...compact(raw),+ status: 'complete',+ })+ expect(translateRawToTask(terminal!).name).toBe('video.mp4')+ expect(translateRawToTask(terminal!).fileCount).toBe(1)+ })++ it('does not reuse file identity for a different torrent under the same GID', async () => {+ const rpc = {+ getFiles: vi+ .fn()+ .mockResolvedValueOnce([file])+ .mockRejectedValue(new Error('unavailable')),+ }+ const metadata = new TaskFileMetadata(rpc)+ await metadata.hydrate({ ...compact(raw), infoHash: 'a'.repeat(40) })+ expect(+ await metadata.hydrate({ ...compact(raw), infoHash: 'b'.repeat(40) })+ ).toBeNull()+ })++ it('does not discard a terminal notification when a concurrent live poll omits its GID', async () => {+ let resolveFiles!: (files: Aria2RawFile[]) => void+ const rpc = {+ getFiles: vi.fn().mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveFiles = resolve+ })+ ),+ }+ const metadata = new TaskFileMetadata(rpc)+ const terminal = metadata.hydrate({ ...compact(raw), status: 'complete' })+ metadata.retain(new Set())+ resolveFiles([file])+ expect((await terminal)?.status).toBe('complete')+ })+})diff --git a/src/core/engine/aria2/task-file-metadata.ts b/src/core/engine/aria2/task-file-metadata.tsnew file mode 100644index 00000000..09ff7527--- /dev/null+++ b/src/core/engine/aria2/task-file-metadata.ts@@ -0,0 +1,123 @@+import { getLogger } from '@core/logger'+import type { Aria2RpcClient } from './aria2-rpc-client'+import { extractUris } from './translate'+import type {+ Aria2FileMetadata,+ Aria2PolledStatus,+ Aria2RawFile,+ Aria2RawStatus,+} from './types'++const log = getLogger('task-file-metadata')+// Also reconcile edits made by another RPC client, which cannot invalidate our+// local cache. Failed reads retry separately from this successful-read TTL.+const REFRESH_INTERVAL_MS = 60_000+const RETRY_INTERVAL_MS = 1_000++type ListStatus = Omit<Aria2RawStatus, 'files'> & { files?: Aria2RawFile[] }++interface Entry {+ fingerprint: string+ identity: string+ lastSeenAt: number+ metadata?: Aria2FileMetadata+ refreshAt: number+ loading?: Promise<void>+}++function project(files: Aria2RawFile[]): Aria2FileMetadata {+ const first = files[0]+ return {+ firstFile: first ? { path: first.path, uris: first.uris } : undefined,+ fileCount: files.length,+ uris: extractUris({ files } as Aria2RawStatus),+ selectedFiles: files+ .filter((file) => file.selected === 'true')+ .map((file) => Number(file.index) - 1),+ }+}++/** Shared by desktop and server; coalesces reads for one metadata generation. */+export class TaskFileMetadata {+ private entries = new Map<string, Entry>()++ constructor(private rpc: Pick<Aria2RpcClient, 'getFiles'>) {}++ invalidate(gid?: string): void {+ if (gid === undefined) this.entries.clear()+ else this.entries.delete(gid)+ }++ retain(gids: ReadonlySet<string>): void {+ for (const [gid, entry] of this.entries) {+ // Keep a short grace period for a terminal notification whose tellStatus+ // is still in flight when the task disappears from active/waiting. Its+ // later getFiles may race eviction, so it still needs last-known identity.+ if (+ !gids.has(gid) &&+ !entry.loading &&+ Date.now() - entry.lastSeenAt > REFRESH_INTERVAL_MS+ )+ this.entries.delete(gid)+ }+ }++ async hydrate(raw: ListStatus): Promise<Aria2PolledStatus | null> {+ const identity = JSON.stringify([raw.dir, raw.infoHash])+ const fingerprint = JSON.stringify([+ raw.dir,+ raw.totalLength,+ raw.infoHash,+ raw.bittorrent?.info?.name,+ raw.bittorrent?.mode,+ raw.status,+ raw.following,+ ])+ let entry = this.entries.get(raw.gid)+ if (!entry || entry.fingerprint !== fingerprint) {+ entry = {+ fingerprint,+ identity,+ lastSeenAt: Date.now(),+ // Keep last-known metadata if a terminal read races engine eviction.+ // Explicit invalidation (selection edits/reconnect) never reuses it.+ metadata: entry?.identity === identity ? entry.metadata : undefined,+ refreshAt: 0,+ }+ this.entries.set(raw.gid, entry)+ }+ const current = entry+ current.lastSeenAt = Date.now()+ if (raw.files !== undefined) {+ // Compatibility with an engine that ignores keys; project once and drop+ // the large response before publishing it to list consumers.+ current.metadata = project(raw.files)+ current.refreshAt = Date.now() + REFRESH_INTERVAL_MS+ } else if (!current.loading && Date.now() >= current.refreshAt) {+ current.loading = this.rpc+ .getFiles(raw.gid)+ .then((files) => {+ if (files.length > 0 || !current.metadata)+ current.metadata = project(files)+ // Empty/pre-metadata file structures must not delay magnet/HTTP+ // identity discovery for a minute.+ const complete = files.length > 0 && files.every((f) => f.path !== '')+ current.refreshAt =+ Date.now() + (complete ? REFRESH_INTERVAL_MS : RETRY_INTERVAL_MS)+ })+ .catch((err) => {+ current.refreshAt = Date.now() + RETRY_INTERVAL_MS+ log.debug({ err, gid: raw.gid }, 'file metadata sync failed')+ })+ .finally(() => {+ current.loading = undefined+ })+ }+ await current.loading+ // A selection edit, reconnect, or newer lifecycle sample won the race.+ // Do not let this older read repopulate the cache or overwrite the task.+ if (this.entries.get(raw.gid) !== current || !current.metadata) return null+ const { files: _files, ...status } = raw+ return { ...status, fileMetadata: current.metadata }+ }+}diff --git a/src/core/engine/aria2/task-status-fields.ts b/src/core/engine/aria2/task-status-fields.tsnew file mode 100644index 00000000..b4a0fb9c--- /dev/null+++ b/src/core/engine/aria2/task-status-fields.ts@@ -0,0 +1,26 @@+import type { Aria2RawStatus } from './types'++// Keep lifecycle, error and BT classification fields even when no inspector is+// open. `files` is synchronized separately; bitfield/peers belong to detail APIs.+export const TASK_STATUS_FIELDS = [+ 'gid',+ 'status',+ 'totalLength',+ 'completedLength',+ 'uploadLength',+ 'downloadSpeed',+ 'uploadSpeed',+ 'connections',+ 'numSeeders',+ 'seeder',+ 'pieceLength',+ 'numPieces',+ 'dir',+ 'bittorrent',+ 'infoHash',+ 'errorCode',+ 'errorMessage',+ 'followedBy',+ 'following',+ 'belongsTo',+] satisfies Array<keyof Aria2RawStatus>diff --git a/src/core/engine/aria2/translate.ts b/src/core/engine/aria2/translate.tsindex 77260f24..400a0ce6 100644--- a/src/core/engine/aria2/translate.ts+++ b/src/core/engine/aria2/translate.ts@@ -27,12 +27,12 @@ import type {Aria2RawFile,Aria2RawGlobalStat,Aria2RawPeer,- Aria2RawStatus,+ Aria2TaskStatus,} from './types'// ─── Status Translation ───────────────────────────────────────-export function translateStatus(raw: Aria2RawStatus): TaskStatus {+export function translateStatus(raw: Aria2TaskStatus): TaskStatus {// BT seeding detection: active + seeder === 'true'if (raw.status === 'active' && raw.seeder === 'true' && raw.bittorrent) {return TaskStatus.Seeding@@ -171,12 +171,16 @@ export function classifyTerminalError(}}+function firstFile(raw: Aria2TaskStatus) {+ return 'fileMetadata' in raw ? raw.fileMetadata.firstFile : raw.files?.[0]+}+// ─── Task Type Detection ──────────────────────────────────────-export function detectTaskType(raw: Aria2RawStatus): TaskType {+export function detectTaskType(raw: Aria2TaskStatus): TaskType {// Check first file's URI first — magnet links have bittorrent// metadata in aria2 but should be identified by their URI scheme- const firstUri = raw.files?.[0]?.uris?.[0]?.uri ?? ''+ const firstUri = firstFile(raw)?.uris?.[0]?.uri ?? ''if (firstUri.startsWith('magnet:')) return TaskType.Magnetif (firstUri.startsWith('ftp://')) return TaskType.Ftp@@ -210,21 +214,21 @@ export function computeEta(// ─── Name & URI Extraction ────────────────────────────────────-export function extractName(raw: Aria2RawStatus): string {+export function extractName(raw: Aria2TaskStatus): string {// BT downloads: use torrent name from metadataif (raw.bittorrent?.info?.name) {return raw.bittorrent.info.name}// File-based: use first file path's basename- const firstFile = raw.files?.[0]- if (firstFile?.path) {- const parts = firstFile.path.split('/')- return parts[parts.length - 1] || firstFile.path+ const file = firstFile(raw)+ if (file?.path) {+ const parts = file.path.split('/')+ return parts[parts.length - 1] || file.path}// Fallback: use first URI's filename- const firstUri = raw.files?.[0]?.uris?.[0]?.uri+ const firstUri = firstFile(raw)?.uris?.[0]?.uriif (firstUri) {try {const url = new URL(firstUri)@@ -238,7 +242,8 @@ export function extractName(raw: Aria2RawStatus): string {return raw.gid}-export function extractUris(raw: Aria2RawStatus): string[] {+export function extractUris(raw: Aria2TaskStatus): string[] {+ if ('fileMetadata' in raw) return raw.fileMetadata.urisconst seen = new Set<string>()const uris: string[] = []for (const file of raw.files ?? []) {@@ -255,7 +260,7 @@ export function extractUris(raw: Aria2RawStatus): string[] {// ─── BT Extension ────────────────────────────────────────────export function translateBtExtension(- raw: Aria2RawStatus+ raw: Aria2TaskStatus): BtExtension | undefined {if (!raw.bittorrent) return undefined@@ -264,12 +269,15 @@ export function translateBtExtension(seeds: Number(raw.numSeeders) || 0,ratio: shareRatio(Number(raw.uploadLength), Number(raw.totalLength)),trackers: (raw.bittorrent.announceList ?? []).flat(),- selectedFiles: (raw.files ?? [])- .filter((f) => f.selected === 'true')- // aria2 numbers files from 1; the engine-neutral domain uses 0-based- // indices (the same convention as TorrentFileInfo and selection- // commands). Keep that engine detail inside this adapter boundary.- .map((f) => Number(f.index) - 1),+ selectedFiles:+ 'fileMetadata' in raw+ ? raw.fileMetadata.selectedFiles+ : (raw.files ?? [])+ .filter((f) => f.selected === 'true')+ // aria2 numbers files from 1; the engine-neutral domain uses 0-based+ // indices (the same convention as TorrentFileInfo and selection+ // commands). Keep that engine detail inside this adapter boundary.+ .map((f) => Number(f.index) - 1),peersInSwarm: 0,seedsInSwarm: 0,announceList: raw.bittorrent.announceList ?? [],@@ -295,7 +303,7 @@ export interface DerivedPaths {finalName: string}-export function derivePathsFromRaw(raw: Aria2RawStatus): DerivedPaths {+export function derivePathsFromRaw(raw: Aria2TaskStatus): DerivedPaths {const taskType = detectTaskType(raw)const isBt = taskType === TaskType.Bt || taskType === TaskType.Magnet@@ -315,7 +323,7 @@ export function derivePathsFromRaw(raw: Aria2RawStatus): DerivedPaths {// HTTP/FTP: the first selected file's path is the canonical on-disk// location. Fallback to `raw.dir` + extracted name if files[] is// empty (e.g. pre-metadata state).- const filePath = raw.files?.[0]?.path+ const filePath = firstFile(raw)?.pathconst diskPath =filePath && filePath.length > 0? filePath@@ -337,7 +345,7 @@ export function derivePathsFromRaw(raw: Aria2RawStatus): DerivedPaths {// ─── Full Task Translation ────────────────────────────────────-export function translateRawToTask(raw: Aria2RawStatus): DownloadTask {+export function translateRawToTask(raw: Aria2TaskStatus): DownloadTask {const now = Date.now()const status = translateStatus(raw)const derivedPaths = derivePathsFromRaw(raw)@@ -420,7 +428,10 @@ export function translateRawToTask(raw: Aria2RawStatus): DownloadTask {// override the baseline if motrix.db has a saved value.uploadedBytes: Number(raw.uploadLength),uploadedBytesBaseline: 0,- fileCount: raw.files?.length ?? 0,+ fileCount:+ 'fileMetadata' in raw+ ? raw.fileMetadata.fileCount+ : (raw.files?.length ?? 0),connections: Number(raw.connections),pieceLength: Number(raw.pieceLength) || 0,diff --git a/src/core/engine/aria2/types.ts b/src/core/engine/aria2/types.tsindex 58460e45..d2a722e8 100644--- a/src/core/engine/aria2/types.ts+++ b/src/core/engine/aria2/types.ts@@ -36,6 +36,22 @@ export interface Aria2RawFile {uris: Aria2RawUri[]}+/** File-derived identity and selection; never contains per-file progress. */+export interface Aria2FileMetadata {+ firstFile?: Pick<Aria2RawFile, 'path' | 'uris'>+ fileCount: number+ uris: string[]+ selectedFiles: number[]+}++/** A list sample carries cached metadata, not a fabricated empty files array. */+export type Aria2PolledStatus = Omit<Aria2RawStatus, 'files'> & {+ files?: never+ fileMetadata: Aria2FileMetadata+}++export type Aria2TaskStatus = Aria2RawStatus | Aria2PolledStatus+export interface Aria2RawUri {uri: stringstatus: 'used' | 'waiting'diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 8ca8a21d..b5cab82a 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -4827,6 +4827,7 @@ it.each(['rpc', 'binding probe', 'persistence'])(log,})const onPolledTasks = vi.fn()+ rpc.onTaskMetadataChanged = vi.fn(() => vi.fn())const polling = new PollingScheduler(rpc, eventBus, vi.fn(), onPolledTasks)const startAutoSave = vi.spyOn(session, 'startAutoSave')diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex 9ba0acc0..68ef3830 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -144,8 +144,19 @@ export function hasEngineTaskDelta(before.errorCode !== after.errorCode ||before.finishedAt !== after.finishedAt ||before.infoHash !== after.infoHash ||+ !sameValues(before.uris, after.uris) ||+ !sameValues(before.bt?.selectedFiles, after.bt?.selectedFiles) ||+ !sameValues(before.bt?.trackers, after.bt?.trackers) ||+ before.bt?.comment !== after.bt?.comment ||before.bt?.peers !== after.bt?.peers ||before.bt?.seeds !== after.bt?.seeds ||before.bt?.ratio !== after.bt?.ratio)}++function sameValues<T>(a: readonly T[] = [], b: readonly T[] = []): boolean {+ return (+ a === b ||+ (a.length === b.length && a.every((value, index) => value === b[index]))+ )+}diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.tsindex 4c0087fc..56156f35 100644--- a/src/core/torrent/magnet-tracker.ts+++ b/src/core/torrent/magnet-tracker.ts@@ -3,7 +3,7 @@ import { mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises'import { tmpdir } from 'node:os'import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'import type { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'-import type { Aria2RawStatus } from '@core/engine/aria2/types'+import type { Aria2TaskStatus } from '@core/engine/aria2/types'import type { EventBus } from '@core/events/event-bus'import { AsyncWorkTracker } from '@core/inspector-activity/async-work-tracker'import { newTaskId } from '@core/lib/ids'@@ -942,7 +942,7 @@ export class MagnetTracker {}}- observe(raw: Aria2RawStatus): boolean {+ observe(raw: Aria2TaskStatus): boolean {// Source of truth for "this gid is metadata-only, polling should// skip it" is the cache Map. Returning true here makes the// PollingScheduler's shouldSkipForPendingMagnetMetadata helperdiff --git a/src/core/torrent/metadata-task-filter.ts b/src/core/torrent/metadata-task-filter.tsindex 41eca13c..6ba240d2 100644--- a/src/core/torrent/metadata-task-filter.ts+++ b/src/core/torrent/metadata-task-filter.ts@@ -1,11 +1,11 @@-import type { Aria2RawStatus } from '@core/engine/aria2/types'+import type { Aria2TaskStatus } from '@core/engine/aria2/types'export interface PendingMagnetMetadataObserver {- observe(raw: Aria2RawStatus): boolean+ observe(raw: Aria2TaskStatus): boolean}export function shouldSkipForPendingMagnetMetadata(- raw: Aria2RawStatus,+ raw: Aria2TaskStatus,tracker: PendingMagnetMetadataObserver | null): boolean {return tracker?.observe(raw) === truediff --git a/src/main/index.ts b/src/main/index.tsindex 5705e7c0..3b4b67ab 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -18,7 +18,7 @@ import {type PollingTaskUpdateSource,} from '@core/engine/aria2/polling-scheduler'import { translateRawToTask } from '@core/engine/aria2/translate'-import type { Aria2RawStatus } from '@core/engine/aria2/types'+import type { Aria2TaskStatus } from '@core/engine/aria2/types'import { WebSocketTransport } from '@core/engine/aria2/web-socket-transport'import {ENGINE_READY_TIMEOUT_MS,@@ -906,7 +906,7 @@ function runShellAsyncWork(// ─── Polling Callback ───────────────────────────────────async function handlePolledTasks(- rawTasks: Aria2RawStatus[],+ rawTasks: Aria2TaskStatus[],source: PollingTaskUpdateSource): Promise<void> {if (supervisor.getState() !== EngineState.Ready) returndiff --git a/src/renderer/hooks/use-polled-query.ts b/src/renderer/hooks/use-polled-query.tsindex 40f2fc15..a20ed7f9 100644--- a/src/renderer/hooks/use-polled-query.ts+++ b/src/renderer/hooks/use-polled-query.ts@@ -71,6 +71,13 @@ export function usePolledQuery<T>(const latest = useRef({ params, cache, equals, initial })latest.current = { params, cache, equals, initial }+ const [visible, setVisible] = useState(() => !document.hidden)++ useEffect(() => {+ const update = () => setVisible(!document.hidden)+ document.addEventListener('visibilitychange', update)+ return () => document.removeEventListener('visibilitychange', update)+ }, [])const [value, setValue] = useState<T | null>(() => {if (id !== null && cache) {@@ -94,38 +101,53 @@ export function usePolledQuery<T>(if (initialCache) {setValue(initialCache.get(activeId) ?? initialValue ?? null)}+ if (!visible) returnlet cancelled = false+ let inFlight = false+ let reloadPending = false+ let generation = 0const load = async () => {+ if (cancelled || inFlight) returnconst {params: nextParams,cache: nextCache,equals: nextEquals,} = latest.currentif (nextParams === null) return+ inFlight = true+ const requestGeneration = generationtry {const data = (await transport.invoke(channel, nextParams)) as T- nextCache?.set(activeId, data)- if (!cancelled) {+ if (!cancelled && requestGeneration === generation) {+ nextCache?.set(activeId, data)setValue((prev) =>prev !== null && nextEquals?.(prev, data) ? prev : data)}} catch {/* retry next tick */+ } finally {+ inFlight = false+ if (reloadPending && !cancelled) {+ reloadPending = false+ void load()+ }}}- load()- if (!enabled) {- return () => {- cancelled = true- }- }- const timer = setInterval(load, intervalMs)+ const detach = transport.onConnectionChange?.((event) => {+ if (event.state !== 'connected') return+ generation += 1+ if (inFlight) reloadPending = true+ else void load()+ })+ void load()+ const timer = enabled ? setInterval(load, intervalMs) : undefinedreturn () => {cancelled = trueclearInterval(timer)+ detach?.()}- }, [channel, id, intervalMs, enabled])+ }, [channel, id, intervalMs, enabled, visible])return value}diff --git a/src/renderer/hooks/use-task-files.test.ts b/src/renderer/hooks/use-task-files.test.tsindex 1586f748..c05bfdcb 100644--- a/src/renderer/hooks/use-task-files.test.ts+++ b/src/renderer/hooks/use-task-files.test.ts@@ -21,6 +21,7 @@ const transportMock = vi.hoisted(() => ({off: vi.fn((channel: string, cb: Listener) => {listeners.get(channel)?.delete(cb)}),+ onConnectionChange: vi.fn(),platform: 'darwin' as const,}))@@ -33,6 +34,7 @@ beforeEach(() => {transportMock.invoke.mockReset()transportMock.on.mockClear()transportMock.off.mockClear()+ transportMock.onConnectionChange.mockReset()transportMock.invoke.mockResolvedValue([{ index: 0, path: 'a', size: 1, completedBytes: 0, selected: true },])@@ -40,9 +42,148 @@ beforeEach(() => {afterEach(() => {vi.clearAllMocks()+ vi.useRealTimers()+ vi.restoreAllMocks()})describe('useTaskFiles', () => {+ it('does not fetch for a disabled panel', async () => {+ const { result } = renderHook(() => useTaskFiles(null, true))+ await act(async () => {})+ expect(result.current.loading).toBe(false)+ expect(transportMock.invoke).not.toHaveBeenCalled()+ })++ it('coalesces invalidations during a slow request and rejects its stale data', async () => {+ let resolveOld!: (value: unknown) => void+ transportMock.invoke.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve+ })+ )+ const { result } = renderHook(() => useTaskFiles('t1', true))+ act(() => {+ for (let index = 0; index < 10; index++)+ listeners.get(Events.TaskFilesUpdated)?.forEach((cb) => {+ cb({ taskId: 't1' })+ })+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)+ await act(async () => {+ resolveOld([+ {+ index: 9,+ path: 'stale',+ size: 1,+ completedBytes: 0,+ selected: false,+ },+ ])+ })+ await waitFor(() => expect(result.current.files[0]?.path).toBe('a'))+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)+ })++ it('does not overlap slow progress reads or apply responses after unmount', async () => {+ vi.useFakeTimers()+ let resolve!: (value: unknown) => void+ transportMock.invoke.mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done+ })+ )+ const { unmount } = renderHook(() => useTaskFiles('t1', true))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000)+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)+ unmount()+ await act(async () => {+ resolve([])+ await vi.advanceTimersByTimeAsync(10_000)+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)+ })++ it('discards responses from a previous engine instance of the same task', async () => {+ let resolveOld!: (value: unknown) => void+ transportMock.invoke.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve+ })+ )+ const { result, rerender } = renderHook(+ ({ gid }) => useTaskFiles('t1', true, gid),+ { initialProps: { gid: 'old' } }+ )+ rerender({ gid: 'new' })+ await waitFor(() => expect(result.current.files[0]?.path).toBe('a'))+ await act(async () => {+ resolveOld([{ index: 9, path: 'stale' }])+ })+ expect(result.current.files[0]?.path).toBe('a')+ })++ it('suspends when the document is hidden and immediately refreshes when visible', async () => {+ vi.useFakeTimers()+ const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)+ renderHook(() => useTaskFiles('t1', true))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+ hidden.mockReturnValue(true)+ act(() => document.dispatchEvent(new Event('visibilitychange')))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000)+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)+ hidden.mockReturnValue(false)+ act(() => document.dispatchEvent(new Event('visibilitychange')))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)+ })++ it('refreshes paused tasks after reconnect and retains references for unchanged files', async () => {+ const detach = vi.fn()+ transportMock.onConnectionChange.mockReturnValue(detach)+ const { result, unmount } = renderHook(() => useTaskFiles('t1'))+ await waitFor(() => expect(result.current.files).toHaveLength(1))+ const previous = result.current.files+ transportMock.invoke.mockResolvedValue(+ previous.map((file) => ({ ...file }))+ )+ await act(async () => {+ transportMock.onConnectionChange.mock.calls[0][0]({ state: 'connected' })+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)+ expect(result.current.files).toBe(previous)+ unmount()+ expect(detach).toHaveBeenCalledOnce()+ })++ it('retains last-known files across failures and retries on the next tick', async () => {+ vi.useFakeTimers()+ const { result } = renderHook(() => useTaskFiles('t1', true))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+ const previous = result.current.files+ transportMock.invoke.mockRejectedValueOnce(new Error('offline'))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000)+ })+ expect(result.current.files).toBe(previous)+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000)+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(3)+ })+it('fetches files on mount', async () => {const { result } = renderHook(() => useTaskFiles('t1'))await waitFor(() => expect(result.current.files).toHaveLength(1))@@ -78,21 +219,20 @@ describe('useTaskFiles', () => {expect(transportMock.invoke).toHaveBeenCalledTimes(1)})- it('refetches live files when the matching task updates', async () => {+ it('refreshes on its own cadence without subscribing to list updates', async () => {+ vi.useFakeTimers()renderHook(() => useTaskFiles('t1', true))- await waitFor(() => expect(transportMock.invoke).toHaveBeenCalledTimes(1))- expect(transportMock.on).toHaveBeenCalledWith(+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(transportMock.on).not.toHaveBeenCalledWith(Events.TaskUpdated,expect.any(Function))-- act(() => {- listeners.get(Events.TaskUpdated)?.forEach((cb) => {- cb([{ id: 't1' }])- })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000)})-- await waitFor(() => expect(transportMock.invoke).toHaveBeenCalledTimes(2))+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)})it('does not subscribe to task updates when live refresh is disabled', async () => {@@ -113,9 +253,6 @@ describe('useTaskFiles', () => {Events.TaskFilesUpdated,expect.any(Function))- expect(transportMock.off).toHaveBeenCalledWith(- Events.TaskUpdated,- expect.any(Function)- )+ expect(listeners.get(Events.TaskFilesUpdated)?.size).toBe(0)})})diff --git a/src/renderer/hooks/use-task-files.ts b/src/renderer/hooks/use-task-files.tsindex e5611883..b98e5ce2 100644--- a/src/renderer/hooks/use-task-files.ts+++ b/src/renderer/hooks/use-task-files.ts@@ -4,64 +4,125 @@ import { Queries } from '@shared/protocol/queries'import type { TaskFile } from '@shared/types/task'import { useCallback, useEffect, useRef, useState } from 'react'-interface TaskFilesUpdatedPayload {- taskId: string+const REFRESH_INTERVAL_MS = 2_000++function filesEqual(a: TaskFile[], b: TaskFile[]): boolean {+ return (+ a.length === b.length &&+ a.every((file, index) => {+ const other = b[index]+ return (+ file.index === other.index &&+ file.path === other.path &&+ file.size === other.size &&+ file.completedBytes === other.completedBytes &&+ file.selected === other.selected &&+ file.progress === other.progress+ )+ })+ )}-export function useTaskFiles(taskId: string, live = false) {+/** Mount only for a visible file panel; null disables all requests. */+export function useTaskFiles(+ taskId: string | null,+ live = false,+ engineTaskId?: string+) {const [files, setFiles] = useState<TaskFile[]>([])- const [loading, setLoading] = useState(true)- const requestGeneration = useRef(0)-- const fetchFiles = useCallback(- async (showLoading = true) => {- const request = ++requestGeneration.current- if (showLoading) setLoading(true)- try {- const result = (await transport.invoke(- Queries.GetTaskFiles,- taskId- )) as TaskFile[]- if (request !== requestGeneration.current) return- setFiles(result)- } finally {- if (request === requestGeneration.current) {- setLoading(false)- }- }- },- [taskId]+ const [loading, setLoading] = useState(taskId !== null)+ const [visible, setVisible] = useState(() => !document.hidden)+ const refresh = useRef<(() => Promise<void>) | null>(null)+ const lastIdentity = useRef({ taskId, engineTaskId })+ const refetch = useCallback(+ () => refresh.current?.() ?? Promise.resolve(),+ [])useEffect(() => {- const onUpdated = (...args: unknown[]) => {- const payload = args[0] as TaskFilesUpdatedPayload | undefined- if (payload?.taskId === taskId) void fetchFiles(false)+ const onVisibility = () => setVisible(!document.hidden)+ document.addEventListener('visibilitychange', onVisibility)+ return () => document.removeEventListener('visibilitychange', onVisibility)+ }, [])++ useEffect(() => {+ // A GID swap keeps the public task id but invalidates its file responses.+ // Clear old identity even while the document is hidden.+ if (+ lastIdentity.current.taskId !== taskId ||+ lastIdentity.current.engineTaskId !== engineTaskId+ ) {+ lastIdentity.current = { taskId, engineTaskId }+ setFiles([])+ }+ if (taskId === null || !visible) {+ setLoading(false)+ return}- const onTaskUpdated = (...args: unknown[]) => {- const payload = args[0]- if (- !Array.isArray(payload) ||- payload.some(- (task) =>- typeof task === 'object' &&- task !== null &&- 'id' in task &&- task.id === taskId- )- ) {- void fetchFiles(false)+ let disposed = false+ let inFlight: Promise<void> | null = null+ let queued = false+ let revision = 0+ let timer: ReturnType<typeof setTimeout> | undefined++ const load = (): Promise<void> => {+ clearTimeout(timer)+ if (disposed) return Promise.resolve()+ if (inFlight) {+ queued = true+ revision += 1+ return inFlight}+ const startedAtRevision = revision+ const request = (async () => {+ try {+ const result = (await transport.invoke(+ Queries.GetTaskFiles,+ taskId+ )) as TaskFile[]+ if (disposed || startedAtRevision !== revision) return+ setFiles((previous) =>+ filesEqual(previous, result) ? previous : result+ )+ } catch {+ // Keep last-known data. Live panels retry on their own cadence;+ // paused panels can retry on reconnect or an explicit invalidation.+ } finally {+ if (!disposed) setLoading(false)+ }+ })()+ inFlight = request+ void request.finally(() => {+ inFlight = null+ if (disposed) return+ if (queued) {+ queued = false+ void load()+ } else if (live) {+ timer = setTimeout(() => void load(), REFRESH_INTERVAL_MS)+ }+ })+ return request+ }+ const onUpdated = (...args: unknown[]) => {+ const payload = args[0] as { taskId?: string } | undefined+ if (payload?.taskId === taskId) void load()}+ const detachConnection = transport.onConnectionChange?.((event) => {+ if (event.state === 'connected') void load()+ })transport.on(Events.TaskFilesUpdated, onUpdated)- if (live) transport.on(Events.TaskUpdated, onTaskUpdated)- void fetchFiles()+ refresh.current = load+ setLoading(true)+ void load()return () => {+ disposed = true+ clearTimeout(timer)+ detachConnection?.()transport.off(Events.TaskFilesUpdated, onUpdated)- if (live) transport.off(Events.TaskUpdated, onTaskUpdated)- requestGeneration.current += 1+ if (refresh.current === load) refresh.current = null}- }, [taskId, live, fetchFiles])+ }, [taskId, live, visible, engineTaskId])- return { files, loading, refetch: () => fetchFiles(true) }+ return { files, loading, refetch }}diff --git a/src/renderer/hooks/use-task-pieces.test.tsx b/src/renderer/hooks/use-task-pieces.test.tsxindex 1eb76bdf..176afaf2 100644--- a/src/renderer/hooks/use-task-pieces.test.tsx+++ b/src/renderer/hooks/use-task-pieces.test.tsx@@ -1,12 +1,14 @@-import { renderHook } from '@testing-library/react'+import { act, renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const mockInvoke = vi.fn()+const mockConnectionChange = vi.fn()vi.mock('@renderer/lib/transport', () => ({transport: {invoke: (...a: unknown[]) => mockInvoke(...a),on: vi.fn(),off: vi.fn(),+ onConnectionChange: (...args: unknown[]) => mockConnectionChange(...args),platform: 'darwin',},}))@@ -17,9 +19,113 @@ describe('useTaskPieces', () => {beforeEach(() => {__clearPiecesCacheForTests()mockInvoke.mockReset()+ mockConnectionChange.mockReset()vi.useFakeTimers()})- afterEach(() => vi.useRealTimers())+ afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+ })++ it('never overlaps slow requests at the one-second cadence', async () => {+ let resolve!: (value: unknown) => void+ mockInvoke.mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done+ })+ )+ renderHook(() => useTaskPieces('slow'))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000)+ })+ expect(mockInvoke).toHaveBeenCalledTimes(1)+ mockInvoke.mockResolvedValue({+ pieceLength: 1,+ numPieces: 1,+ bitfield: '8',+ })+ await act(async () => {+ resolve({ pieceLength: 1, numPieces: 1, bitfield: '0' })+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000)+ })+ expect(mockInvoke).toHaveBeenCalledTimes(2)+ })++ it('suspends hidden documents and immediately refreshes when visible', async () => {+ const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)+ mockInvoke.mockResolvedValue({+ pieceLength: 1,+ numPieces: 1,+ bitfield: '8',+ })+ renderHook(() => useTaskPieces('visible'))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(4000)+ })+ expect(mockInvoke).not.toHaveBeenCalled()+ hidden.mockReturnValue(false)+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'))+ })+ expect(mockInvoke).toHaveBeenCalledTimes(1)+ hidden.mockReturnValue(true)+ act(() => document.dispatchEvent(new Event('visibilitychange')))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(4000)+ })+ expect(mockInvoke).toHaveBeenCalledTimes(1)+ })++ it('does not let a response from an unmounted panel poison its newer cache', async () => {+ let resolveOld!: (value: unknown) => void+ mockInvoke.mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolveOld = done+ })+ )+ const old = renderHook(() => useTaskPieces('cache-race'))+ old.unmount()+ const complete = { pieceLength: 1, numPieces: 8, bitfield: 'ff' }+ mockInvoke.mockResolvedValue(complete)+ const current = renderHook(() => useTaskPieces('cache-race'))+ await act(async () => {})+ await act(async () => {+ resolveOld({ ...complete, bitfield: '00' })+ })+ current.unmount()+ const remount = renderHook(() => useTaskPieces('cache-race'))+ expect(remount.result.current.pieces).toEqual(complete)+ })++ it('invalidates the old engine instance and refreshes paused pieces on reconnect', async () => {+ mockInvoke.mockResolvedValue({+ pieceLength: 1,+ numPieces: 8,+ bitfield: 'ff',+ })+ const hook = renderHook(+ ({ gid }) => useTaskPieces('same-task', false, gid),+ { initialProps: { gid: 'old' } }+ )+ await act(async () => {})+ expect(hook.result.current.pieces?.bitfield).toBe('ff')+ mockInvoke.mockResolvedValue({+ pieceLength: 1,+ numPieces: 8,+ bitfield: '00',+ })+ hook.rerender({ gid: 'new' })+ await act(async () => {})+ expect(hook.result.current.pieces?.bitfield).toBe('00')+ await act(async () => {+ mockConnectionChange.mock.calls.at(-1)?.[0]({ state: 'connected' })+ })+ expect(mockInvoke).toHaveBeenCalledTimes(3)+ })it('fetches pieces on mount', async () => {mockInvoke.mockResolvedValue({@@ -32,10 +138,10 @@ describe('useTaskPieces', () => {expect(result.current.pieces?.numPieces).toBe(8)})- it('re-fetches every 2 seconds while mounted', async () => {+ it('re-fetches every second while mounted', async () => {mockInvoke.mockResolvedValue({ pieceLength: 1, numPieces: 1, bitfield: '' })renderHook(() => useTaskPieces('t-poll'))- await vi.advanceTimersByTimeAsync(2100)+ await vi.advanceTimersByTimeAsync(1100)expect(mockInvoke).toHaveBeenCalledTimes(2)})diff --git a/src/renderer/hooks/use-task-pieces.ts b/src/renderer/hooks/use-task-pieces.tsindex 980fddda..c70a4e2b 100644--- a/src/renderer/hooks/use-task-pieces.ts+++ b/src/renderer/hooks/use-task-pieces.ts@@ -20,12 +20,20 @@ export function __clearPiecesCacheForTests(): void {piecesCache.clear()}-export function useTaskPieces(taskId: string | null, enabled = true) {+export function useTaskPieces(+ taskId: string | null,+ enabled = true,+ engineTaskId?: string+) {const pieces = usePolledQuery<TaskPiecesResult>(Queries.GetTaskPieces,- taskId,+ taskId === null+ ? null+ : engineTaskId === undefined+ ? taskId+ : `${taskId}:${engineTaskId}`,taskId !== null ? { taskId } : null,- { cache: piecesCache, equals: piecesEqual, enabled }+ { cache: piecesCache, equals: piecesEqual, enabled, intervalMs: 1_000 })return { pieces }}diff --git a/src/renderer/routes/downloads/inspector/files-tab.test.tsx b/src/renderer/routes/downloads/inspector/files-tab.test.tsxindex 997041c0..6d1e1408 100644--- a/src/renderer/routes/downloads/inspector/files-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/files-tab.test.tsx@@ -237,7 +237,7 @@ describe('FilesTab', () => {)expect(screen.getByText('53%')).toBeInTheDocument()- expect(useTaskFiles).toHaveBeenCalledWith('t1', true)+ expect(useTaskFiles).toHaveBeenCalledWith('t1', true, 'gid1')})it('shows every HTTP file as selected and read-only', () => {diff --git a/src/renderer/routes/downloads/inspector/files-tab.tsx b/src/renderer/routes/downloads/inspector/files-tab.tsxindex 146c35a8..1c1fafec 100644--- a/src/renderer/routes/downloads/inspector/files-tab.tsx+++ b/src/renderer/routes/downloads/inspector/files-tab.tsx@@ -35,7 +35,11 @@ export function FilesTab({ task }: { task: DownloadTask }) {const { formatBytes } = useByteFormat()const isMedia = task.kind === TaskKind.Hls || task.kind === TaskKind.Muxconst isActive = ACTIVE_DOWNLOAD.has(task.status)- const { files } = useTaskFiles(task.id, isActive)+ const { files } = useTaskFiles(+ task.id,+ isActive && task.status !== TaskStatus.Seeding,+ task.engineTaskId+ )const initial = task.bt?.selectedFiles ?? []const [draft, setDraft] = useState<number[]>(initial)// Direct HTTP/FTP and single-file tasks have no file selection to make.diff --git a/src/renderer/routes/downloads/inspector/piece-map.test.ts b/src/renderer/routes/downloads/inspector/piece-map.test.tsnew file mode 100644index 00000000..8a4d6458--- /dev/null+++ b/src/renderer/routes/downloads/inspector/piece-map.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest'+import { aggregatePieceMap } from './piece-map'++describe('piece map aggregation', () => {+ it('reads most-significant bits first and ignores padding and invalid/missing hex', () => {+ expect(aggregatePieceMap('8', 4)).toEqual({+ cells: ['done', 'pending', 'pending', 'pending'],+ donePieces: 1,+ pendingPieces: 3,+ })+ expect(aggregatePieceMap('FF', 5)).toEqual({+ cells: Array(5).fill('done'),+ donePieces: 5,+ pendingPieces: 0,+ })+ expect(aggregatePieceMap('Fg', 12).donePieces).toBe(4)+ expect(aggregatePieceMap('', 0)).toEqual({+ cells: [],+ donePieces: 0,+ pendingPieces: 0,+ })+ })++ it.each([1, 3, 4, 5, 3999, 4000, 4001, 7458, 297623])(+ 'preserves bucket coloring and counts real completed pieces for %i pieces',+ (count) => {+ const pattern = '9a7C0f'+ const bitfield = pattern.repeat(Math.ceil(count / 24))+ const bits = Array.from(+ { length: count },+ (_, index) =>+ (Number.parseInt(bitfield[Math.floor(index / 4)], 16) >>+ (3 - (index % 4))) &+ 1+ )+ const stride = Math.ceil(count / 4000)+ const cells = []+ for (let start = 0; start < count; start += stride) {+ const bucket = bits.slice(start, start + stride)+ cells.push(+ bucket.reduce((sum, bit) => sum + bit, 0) * 2 >= bucket.length+ ? 'done'+ : 'pending'+ )+ }+ const result = aggregatePieceMap(bitfield, count)+ expect(result.cells).toEqual(cells)+ expect(result.donePieces).toBe(bits.reduce((sum, bit) => sum + bit, 0))+ expect(result.pendingPieces + result.donePieces).toBe(count)+ }+ )++ it('keeps memory bounded for a huge declared piece count with truncated metadata', () => {+ const result = aggregatePieceMap('8', 100_000_000)+ expect(result.cells).toHaveLength(4000)+ expect(result.donePieces).toBe(1)+ expect(result.pendingPieces).toBe(99_999_999)+ })+})diff --git a/src/renderer/routes/downloads/inspector/piece-map.ts b/src/renderer/routes/downloads/inspector/piece-map.tsnew file mode 100644index 00000000..955a7a6d--- /dev/null+++ b/src/renderer/routes/downloads/inspector/piece-map.ts@@ -0,0 +1,47 @@+export type PieceState = 'done' | 'pending'++const MAX_CELLS = 4_000+const POPCOUNT = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]++function nibble(code: number): number {+ if (code >= 48 && code <= 57) return code - 48+ if (code >= 65 && code <= 70) return code - 55+ if (code >= 97 && code <= 102) return code - 87+ return 0+}++/** Aggregate directly from MSB-first hex, allocating only the visible cells. */+export function aggregatePieceMap(+ bitfield: string,+ numPieces: number+): {+ cells: PieceState[]+ donePieces: number+ pendingPieces: number+} {+ if (!Number.isSafeInteger(numPieces) || numPieces <= 0) {+ return { cells: [], donePieces: 0, pendingPieces: 0 }+ }+ const stride = Math.ceil(numPieces / MAX_CELLS)+ const availablePieces = Math.min(numPieces, bitfield.length * 4)+ const cells: PieceState[] = []+ let donePieces = 0+ for (let start = 0; start < numPieces; start += stride) {+ const end = Math.min(start + stride, numPieces)+ const availableEnd = Math.min(end, availablePieces)+ let done = 0+ for (let cursor = start; cursor < availableEnd; ) {+ const offset = cursor % 4+ const count = Math.min(4 - offset, availableEnd - cursor)+ const mask = ((1 << count) - 1) << (4 - offset - count)+ done +=+ POPCOUNT[nibble(bitfield.charCodeAt(Math.floor(cursor / 4))) & mask]+ cursor += count+ }+ donePieces += done+ // Preserve the existing majority coloring, including ties and the short+ // final bucket. Padding and missing bits never count as completed pieces.+ cells.push(done * 2 >= end - start ? 'done' : 'pending')+ }+ return { cells, donePieces, pendingPieces: numPieces - donePieces }+}diff --git a/src/renderer/routes/downloads/inspector/pieces-tab.test.tsx b/src/renderer/routes/downloads/inspector/pieces-tab.test.tsxindex f74bbb69..62d07a39 100644--- a/src/renderer/routes/downloads/inspector/pieces-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/pieces-tab.test.tsx@@ -33,6 +33,23 @@ describe('PiecesTab', () => {expect(canvas?.getAttribute('data-piece-count')).toBe('8')})+ it('shows real piece counts rather than the number of downsampled cells', () => {+ mockPieces.value = {+ pieceLength: 1024,+ numPieces: 10_000,+ bitfield: 'f'.repeat(1250) + '0'.repeat(1250),+ }+ const { getAllByText, container } = render(+ <PiecesTab task={makeTask('large')} />+ )+ expect(getAllByText('5000')).toHaveLength(2)+ expect(+ Number(+ container.querySelector('canvas')?.getAttribute('data-piece-count')+ )+ ).toBeLessThanOrEqual(4000)+ })+it('locks direction to LTR for piece ordering', () => {mockPieces.value = { pieceLength: 1024, numPieces: 8, bitfield: 'ff' }const { container } = render(<PiecesTab task={makeTask('t-1')} />)diff --git a/src/renderer/routes/downloads/inspector/pieces-tab.tsx b/src/renderer/routes/downloads/inspector/pieces-tab.tsxindex 8116d7c6..d7a655db 100644--- a/src/renderer/routes/downloads/inspector/pieces-tab.tsx+++ b/src/renderer/routes/downloads/inspector/pieces-tab.tsx@@ -5,8 +5,9 @@ import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'import { useLayoutEffect, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'+import { aggregatePieceMap, type PieceState } from './piece-map'-// Statuses where the bitfield is actively changing and warrants the 2s+// Statuses where the bitfield is actively changing and warrants the 1s// polling cadence. For other statuses (paused / seeding / completed /// error / removed) the hook still fetches once on mount so the user sees// an available last-known piece map — it just stops polling after that.@@ -19,36 +20,6 @@ const PIECES_LIVE_STATUSES = new Set<TaskStatus>([TaskStatus.Finalizing,])-type PieceState = 'done' | 'pending'--function statesFromBitfield(bitfield: string, numPieces: number): PieceState[] {- const out: PieceState[] = []- for (let i = 0; i < numPieces; i++) {- const byteIndex = i >> 2- const hex = bitfield[byteIndex]- if (!hex) {- out.push('pending')- continue- }- const nibble = Number.parseInt(hex, 16)- const bit = 3 - (i & 3)- out.push((nibble >> bit) & 1 ? 'done' : 'pending')- }- return out-}--function downsample(states: PieceState[], target = 4000): PieceState[] {- if (states.length <= target) return states- const stride = Math.ceil(states.length / target)- const out: PieceState[] = []- for (let i = 0; i < states.length; i += stride) {- const chunk = states.slice(i, i + stride)- const done = chunk.filter((s) => s === 'done').length- out.push(done * 2 >= chunk.length ? 'done' : 'pending')- }- return out-}-const CELL_PX = 4const GAP_PX = 1const COLOR_DONE = '#22c55e' // tailwind green-500@@ -122,19 +93,17 @@ export function PiecesTab({ task }: { task: DownloadTask }) {const { t } = useTranslation()const { pieces } = useTaskPieces(task.id,- PIECES_LIVE_STATUSES.has(task.status)+ PIECES_LIVE_STATUSES.has(task.status),+ task.engineTaskId)// Memoize on the bitfield primitive (not the pieces object) so the- // 2s polling refresh's new TaskPiecesResult identity doesn't churn+ // 1s polling refresh's new TaskPiecesResult identity doesn't churn// a 4000-cell rebuild when the underlying bytes are unchanged.const bitfield = pieces?.bitfield ?? ''const numPieces = pieces?.numPieces ?? 0- const cells = useMemo(- () =>- numPieces === 0- ? []- : downsample(statesFromBitfield(bitfield, numPieces)),+ const { cells, donePieces, pendingPieces } = useMemo(+ () => aggregatePieceMap(bitfield, numPieces),[bitfield, numPieces])@@ -166,11 +135,6 @@ export function PiecesTab({ task }: { task: DownloadTask }) {}}, [cells])- const doneCount = useMemo(- () => cells.reduce((n, c) => (c === 'done' ? n + 1 : n), 0),- [cells]- )-if (!pieces) {return <div aria-hidden="true" className={PIECES_MIN_H_CLASS} />}@@ -204,12 +168,12 @@ export function PiecesTab({ task }: { task: DownloadTask }) {<p className="flex items-center gap-1"><span className="me-1 inline-block size-2.5 rounded-[2px] bg-green-500" /><span>{t('panel.downloads.inspector.pieces.legend.done')}</span>- <span>{doneCount}</span>+ <span>{donePieces}</span></p><p className="flex items-center gap-1"><span className="me-1 inline-block size-2.5 rounded-[2px] bg-muted" /><span>{t('panel.downloads.inspector.pieces.legend.pending')}</span>- <span>{cells.length - doneCount}</span>+ <span>{pendingPieces}</span></p><p className="flex items-center gap-1 mt-3 text-muted-foreground/80"><span>{t('panel.downloads.inspector.pieces.pieceLength')}:</span>diff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsxindex a785ac18..90dde0dd 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx@@ -5,6 +5,8 @@ import { createSelectionStore } from '@renderer/components/desktop-kit/selectionimport type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'import { transport } from '@renderer/lib/transport'import { DownloadErrorCode } from '@shared/errors'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'import type { DownloadTask } from '@shared/types/task'import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'import {@@ -216,6 +218,49 @@ describe('TaskInspectorDrawer', () => {expect(screen.queryByRole('dialog')).toBeNull()})+ it('loads file details only in the visible Files tab and stops listening when closed', async () => {+ const originalInvoke = transport.invoke.bind(transport)+ const invoke = vi+ .spyOn(transport, 'invoke')+ .mockImplementation(async (channel, ...args) =>+ channel === Queries.GetTaskFiles ? [] : originalInvoke(channel, ...args)+ )+ const on = vi.spyOn(transport, 'on').mockImplementation(() => {})+ const off = vi.spyOn(transport, 'off').mockImplementation(() => {})+ try {+ const user = userEvent.setup()+ const selection = createSelectionStore<DownloadTask>((task) => task.id)+ const tasks = [fake({ status: TaskStatus.Downloading })]+ selection.getState().setItems(tasks)+ selection.getState().select('a')+ render(<TestHarness selection={selection} tasks={tasks} />)+ const reads = () =>+ invoke.mock.calls.filter(+ ([channel]) => channel === Queries.GetTaskFiles+ ).length+ expect(reads()).toBe(0)+ await user.click(screen.getByRole('tab', { name: 'Files' }))+ await waitFor(() => expect(reads()).toBe(1))+ await user.click(screen.getByRole('tab', { name: 'Overview' }))+ expect(off).toHaveBeenCalledWith(+ Events.TaskFilesUpdated,+ expect.any(Function)+ )+ await user.click(screen.getByRole('tab', { name: 'Files' }))+ await waitFor(() => expect(reads()).toBe(2))+ off.mockClear()+ await user.click(screen.getByRole('button', { name: 'Close' }))+ expect(off).toHaveBeenCalledWith(+ Events.TaskFilesUpdated,+ expect.any(Function)+ )+ } finally {+ invoke.mockRestore()+ on.mockRestore()+ off.mockRestore()+ }+ })+it('closes a restored inspector with no selection and keeps a subsequent single selection closed', () => {const selection = createSelectionStore<DownloadTask>((task) => task.id)const tasks = [fake()]diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex bc22ac93..4067aa57 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -249,11 +249,15 @@ export function TaskInspectorDrawer({/></TabsContent><TabsContent value="files" className="min-h-0">- <FilesTab key={single.id} task={single} />+ {open && activeSubtab === 'files' && (+ <FilesTab key={single.id} task={single} />+ )}</TabsContent>{showPieces && (<TabsContent value="pieces" className="min-h-0">- <PiecesTab task={single} />+ {open && activeSubtab === 'pieces' && (+ <PiecesTab task={single} />+ )}</TabsContent>)}{isBt && (diff --git a/src/server/index.ts b/src/server/index.tsindex 376ff843..600f21c5 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -27,7 +27,7 @@ import {type PollingTaskUpdateSource,} from '@core/engine/aria2/polling-scheduler'import { translateRawToTask } from '@core/engine/aria2/translate'-import type { Aria2RawStatus } from '@core/engine/aria2/types'+import type { Aria2TaskStatus } from '@core/engine/aria2/types'import { WebSocketTransport } from '@core/engine/aria2/web-socket-transport'import {ENGINE_READY_TIMEOUT_MS,@@ -469,7 +469,9 @@ async function main() {// ─── aria2 Infrastructure ─────────────────────────────────────const transport = new WebSocketTransport()- const protocol = new JsonRpcProtocol(transport)+ const protocol = new JsonRpcProtocol(transport, {+ maxRequestBytes: torrentBodyLimitBytes,+ })const processManager = new Aria2ProcessManager({ownershipFilePath: path.join(platform.userDataDir, 'aria2-owner.json'),})@@ -952,7 +954,7 @@ async function main() {// ─── Polling ──────────────────────────────────────────────────async function handlePolledTasks(- rawTasks: Aria2RawStatus[],+ rawTasks: Aria2TaskStatus[],source: PollingTaskUpdateSource): Promise<void> {if (supervisor.getState() !== EngineState.Ready) return