A full-featured download manager.
feat(downloads): show HTTP piece progress reliably (#1878)
Dr_rOot81f438cb0397
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 457cceed..5e669eee 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -748,7 +748,7 @@ describe('Aria2Adapter', () => {})describe('getTaskPieces', () => {- it('returns parsed piece state for a BT task', async () => {+ it('returns parsed piece state for an engine-backed task', async () => {const rpc = createMockRpc()vi.mocked(rpc.tellStatus).mockResolvedValue({pieceLength: '16384',@@ -771,7 +771,7 @@ describe('Aria2Adapter', () => {])})- it('returns zero-shape when fields are missing (HTTP task)', async () => {+ it('normalizes missing piece fields to zero-shape', async () => {const rpc = createMockRpc()vi.mocked(rpc.tellStatus).mockResolvedValue({} as unknown as Aria2RawStatusdiff --git a/src/core/engine/aria2/translate.test.ts b/src/core/engine/aria2/translate.test.tsindex 08a2af20..5ea7e094 100644--- a/src/core/engine/aria2/translate.test.ts+++ b/src/core/engine/aria2/translate.test.ts@@ -109,6 +109,7 @@ describe('translateRawToTask path fields', () => {expect(task.diskPath).toBe('/downloads/sample.bin.motrix')expect(task.finalPath).toBe('/downloads/sample.bin')expect(task.finalName).toBe('sample.bin')+ expect(task.pieceLength).toBe(1000)expect(task.transitionPhase).toBe(TransitionPhase.Idle)expect(task.torrentMetaPath).toBeNull()})diff --git a/src/core/engine/aria2/translate.ts b/src/core/engine/aria2/translate.tsindex de99ad79..fa6fd3c3 100644--- a/src/core/engine/aria2/translate.ts+++ b/src/core/engine/aria2/translate.ts@@ -226,7 +226,6 @@ export function translateBtExtension(isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: Number(raw.pieceLength) || 0,}}@@ -373,6 +372,7 @@ export function translateRawToTask(raw: Aria2RawStatus): DownloadTask {fileCount: raw.files?.length ?? 0,connections: Number(raw.connections),+ pieceLength: Number(raw.pieceLength) || 0,infoHash: raw.infoHash ?? null,metadataProgress: 0,diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex b4a79d24..ecdfa568 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -144,16 +144,11 @@ export interface EngineAdapter {): Promise<void>/**- * Fetch BT piece state for the given engine task.+ * Fetch piece state for an engine-backed download task.*- * - Returns `null` if the engine has no record of `engineTaskId`.- * - Returns zero-shape (`{ pieceLength: 0, numPieces: 0, bitfield: '' }`)- * for HTTP/FTP tasks, mirroring how aria2's `tellStatus` omits piece- * fields for non-BT tasks.- *- * Bitfield is large (~2KB on big torrents); call only when the consumer- * is actively viewing the pieces visualization. Not bundled into- * `getTaskStatus` to keep the ListTasks hot path lean.+ * Returns `null` if the engine has no record of `engineTaskId`. Bitfield can+ * be large, so call only while the consumer is viewing the visualization;+ * it is deliberately excluded from the ListTasks hot path.*/getTaskPieces(engineTaskId: string): Promise<TaskPiecesResult | null>diff --git a/src/core/plugin/hooks/hook-context.test.ts b/src/core/plugin/hooks/hook-context.test.tsindex 1f218f1e..80c05250 100644--- a/src/core/plugin/hooks/hook-context.test.ts+++ b/src/core/plugin/hooks/hook-context.test.ts@@ -95,6 +95,7 @@ const BASE_TASK: DownloadTask = {uploadedBytesBaseline: 0,fileCount: 1,connections: 0,+ pieceLength: 1000,infoHash: null,errorCode: null,errorDetailKey: null,diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 187e7764..88c5c0de 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -124,6 +124,7 @@ function createMockRpc(opts: { activeTasks?: Aria2RawStatus[] } = {}): Aria2RpcClient {return {+ tellStatus: vi.fn().mockRejectedValue(new Error('tellStatus not mocked')),tellActive: vi.fn().mockResolvedValue(opts.activeTasks ?? []),tellWaiting: vi.fn().mockResolvedValue([]),tellStopped: vi.fn().mockResolvedValue([]),@@ -693,6 +694,7 @@ describe('SessionManager', () => {uploadedBytes: 256,uploadedBytesBaseline: 0,fileCount: 3,+ pieceLength: 256,})taskManager.add(task)await session.save()@@ -702,6 +704,7 @@ describe('SessionManager', () => {expect(saved?.task.sizeWhenDone).toBe(1024)expect(saved?.instances[0]?.uploadedBytes).toBe(256)expect(saved?.task.fileCount).toBe(3)+ expect(saved?.task.pieceLength).toBe(256)})it('preserves isPrivate=true across save (round-trip)', async () => {@@ -724,7 +727,6 @@ describe('SessionManager', () => {isPrivate: true,magnetUri: null,sequentialDownload: false,- pieceLength: 0,},})taskManager.add(task)@@ -1424,6 +1426,232 @@ describe('SessionManager', () => {expect(restored?.status).toBe(TaskStatus.Paused)})+ it('prefers a paused live row over a stale stopped error with the same gid', async () => {+ const gid = 'gid-http-paused-with-stale-error'+ const totalBytes = 6_976_131_072+ const downloadedBytes = 2_654_994_432++ seedAsPair(db, {+ motrixId: 'm-http-paused-with-stale-error',+ gid,+ name: 'deepin.iso',+ type: TaskType.Http,+ kind: TaskKind.Direct,+ status: TaskStatus.Paused,+ totalBytes,+ downloadedBytes,+ pieceLength: 1_048_576,+ uris: ['https://example.com/deepin.iso'],+ diskPath: '/tmp/deepin.iso.motrix',+ finalPath: '/tmp/deepin.iso',+ finalName: 'deepin.iso',+ })++ // A just-restored paused row may not materialize its control data until+ // unpaused, so it reports zero metrics. motrix.db still has the last+ // good 38% snapshot.+ rpc.tellWaiting = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'paused',+ totalLength: '0',+ completedLength: '0',+ }),+ ])+ // aria2's history store retains an older failure for the same GID. It+ // must not overwrite the current paused lifecycle row or its progress.+ rpc.tellStopped = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'error',+ errorCode: '7',+ totalLength: String(totalBytes),+ completedLength: '189513728',+ }),+ ])+ rpc.tellStatus = vi.fn(async () =>+ makeRawStatus({+ gid,+ status: 'paused',+ totalLength: '0',+ completedLength: '0',+ })+ )++ await sessionManager.restore()++ const restored = taskManager.getById('m-http-paused-with-stale-error')+ expect(restored).toMatchObject({+ engineTaskId: gid,+ status: TaskStatus.Paused,+ totalBytes,+ downloadedBytes,+ })+ expect(restored?.progress).toBeCloseTo(downloadedBytes / totalBytes)+ expect(db.persistTaskWithOccurrence).not.toHaveBeenCalled()+ expect(adapter.forceRemoveTask).not.toHaveBeenCalled()+ expect(adapter.removeDownloadResult).not.toHaveBeenCalled()+ expect(rpc.tellStatus).toHaveBeenCalledExactlyOnceWith(gid)+ })++ it('keeps active when tellStatus confirms it over duplicate waiting and stopped rows', async () => {+ const gid = 'gid-active-wins-all-duplicates'+ seedAsPair(db, {+ motrixId: 'm-active-wins-all-duplicates',+ gid,+ status: TaskStatus.Downloading,+ totalBytes: 1000,+ downloadedBytes: 500,+ })+ rpc.tellActive = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'active',+ totalLength: '1000',+ completedLength: '700',+ }),+ ])+ rpc.tellWaiting = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'paused',+ totalLength: '1000',+ completedLength: '600',+ }),+ ])+ rpc.tellStopped = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'complete',+ totalLength: '1000',+ completedLength: '1000',+ }),+ ])+ rpc.tellStatus = vi.fn(async () =>+ makeRawStatus({+ gid,+ status: 'active',+ totalLength: '1000',+ completedLength: '700',+ })+ )++ await sessionManager.restore()++ expect(taskManager.getById('m-active-wins-all-duplicates')).toMatchObject(+ {+ status: TaskStatus.Downloading,+ totalBytes: 1000,+ downloadedBytes: 700,+ progress: 0.7,+ }+ )+ expect(db.persistTaskWithOccurrence).not.toHaveBeenCalled()+ expect(rpc.tellStatus).toHaveBeenCalledExactlyOnceWith(gid)+ })++ it('falls back to the live row when duplicate-GID arbitration fails', async () => {+ const gid = 'gid-duplicate-arbitration-failed'+ seedAsPair(db, {+ motrixId: 'm-duplicate-arbitration-failed',+ gid,+ status: TaskStatus.Paused,+ totalBytes: 1000,+ downloadedBytes: 400,+ })+ rpc.tellWaiting = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'paused',+ totalLength: '0',+ completedLength: '0',+ }),+ ])+ rpc.tellStopped = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'error',+ errorCode: '7',+ totalLength: '1000',+ completedLength: '100',+ }),+ ])+ rpc.tellStatus = vi.fn().mockRejectedValue(new Error('rpc unavailable'))++ await sessionManager.restore()++ expect(+ taskManager.getById('m-duplicate-arbitration-failed')+ ).toMatchObject({+ status: TaskStatus.Paused,+ totalBytes: 1000,+ downloadedBytes: 400,+ progress: 0.4,+ })+ expect(db.persistTaskWithOccurrence).not.toHaveBeenCalled()+ })++ it('does not hide a terminal transition that occurs during the list snapshot race', async () => {+ const gid = 'gid-completed-during-restore-scan'+ seedAsPair(db, {+ motrixId: 'm-completed-during-restore-scan',+ gid,+ status: TaskStatus.Downloading,+ totalBytes: 1000,+ downloadedBytes: 500,+ })+ // tellActive captured the task immediately before it completed.+ rpc.tellActive = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'active',+ totalLength: '1000',+ completedLength: '700',+ }),+ ])+ // tellStopped captured the terminal row from the other side of the+ // transition. Fixed active-first precedence would incorrectly hide it.+ rpc.tellStopped = vi.fn(async () => [+ makeRawStatus({+ gid,+ status: 'complete',+ totalLength: '1000',+ completedLength: '1000',+ }),+ ])+ rpc.tellStatus = vi.fn(async () =>+ makeRawStatus({+ gid,+ status: 'complete',+ totalLength: '1000',+ completedLength: '1000',+ })+ )++ await sessionManager.restore()++ expect(+ taskManager.getById('m-completed-during-restore-scan')+ ).toMatchObject({+ status: TaskStatus.Completed,+ downloadedBytes: 1000,+ progress: 1,+ })+ expect(db.persistTaskWithOccurrence).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ task: expect.objectContaining({+ motrixId: 'm-completed-during-restore-scan',+ aggStatus: TaskStatus.Completed,+ }),+ }),+ expect.objectContaining({+ taskId: 'm-completed-during-restore-scan',+ fromStatus: TaskStatus.Downloading,+ toStatus: TaskStatus.Completed,+ })+ )+ })+describe('persisted Error task with a resurrected engine row (shield)', () => {function seedErroredHttpTask(gid: string): void {seedAsPair(db, {@@ -1452,6 +1680,12 @@ describe('SessionManager', () => {rpc.tellWaiting = vi.fn(async () => [makeRawStatus({ gid, status: 'waiting' }),])+ rpc.tellStopped = vi.fn(async () => [+ makeRawStatus({ gid, status: 'error', errorCode: '3' }),+ ])+ rpc.tellStatus = vi.fn(async () =>+ makeRawStatus({ gid, status: 'waiting' })+ )await sessionManager.restore()@@ -1461,6 +1695,8 @@ describe('SessionManager', () => {expect(restored?.errorMessage).toBe('Resource not found')expect(adapter.forceRemoveTask).toHaveBeenCalledWith(gid)expect(adapter.removeDownloadResult).toHaveBeenCalledWith(gid)+ expect(adapter.forceRemoveTask).toHaveBeenCalledTimes(1)+ expect(adapter.removeDownloadResult).toHaveBeenCalledTimes(1)expect(adapter.createDownload).not.toHaveBeenCalled()expect(db.persistTaskWithOccurrence).not.toHaveBeenCalled()})diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 5156b511..1e038aef 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -65,6 +65,119 @@ async function fetchAll(return all}+/**+ * aria2's live task store and stopped-history store can contain the same GID+ * at the same time. This happens when a resumable HTTP task has a historical+ * error row but its current task row is paused/waiting. tellStopped is history,+ * not a newer lifecycle observation, so a stopped duplicate must never+ * overwrite the active/waiting row during restore.+ *+ * The caller supplies rows in fallback order: active, then waiting, then+ * stopped. Conflicting GIDs are re-read through tellStatus so a task that+ * genuinely completed during the concurrent list snapshots still settles to+ * its terminal state. First row wins only when that arbitration fails.+ */+const DUPLICATE_GID_ARBITRATION_CONCURRENCY = 16++async function resolveCurrentAria2Rows(+ rpc: Pick<Aria2RpcClient, 'tellStatus'>,+ activeTasks: readonly Aria2RawStatus[],+ waitingTasks: readonly Aria2RawStatus[],+ stoppedTasks: readonly Aria2RawStatus[]+): Promise<{+ tasks: Aria2RawStatus[]+ ignoredDuplicateCount: number+ duplicateGidCount: number+ arbitrationFailureCount: number+ ignoredDuplicateSample: Array<{+ gid: string+ keptStatus: string+ ignoredStatus: string+ }>+}> {+ const tasks: Aria2RawStatus[] = []+ const ignoredDuplicateSample: Array<{+ gid: string+ keptStatus: string+ ignoredStatus: string+ }> = []+ const currentStatusByGid = new Map<string, string>()+ const taskIndexByGid = new Map<string, number>()+ const duplicateGids = new Set<string>()+ let ignoredDuplicateCount = 0++ for (const group of [activeTasks, waitingTasks, stoppedTasks]) {+ for (const task of group) {+ const currentStatus = currentStatusByGid.get(task.gid)+ if (currentStatus !== undefined) {+ ignoredDuplicateCount += 1+ duplicateGids.add(task.gid)+ if (ignoredDuplicateSample.length < 20) {+ ignoredDuplicateSample.push({+ gid: task.gid,+ keptStatus: currentStatus,+ ignoredStatus: task.status,+ })+ }+ continue+ }+ currentStatusByGid.set(task.gid, task.status)+ taskIndexByGid.set(task.gid, tasks.length)+ tasks.push(task)+ }+ }++ // The three list RPCs above are concurrent snapshots. A task can complete+ // between tellActive and tellStopped, so fixed source priority alone could+ // discard a genuinely newer terminal row. Resolve only conflicting GIDs+ // through tellStatus, which is aria2's current authoritative view. Bound the+ // fan-out so a large retained history cannot create an RPC burst at startup.+ const gids = [...duplicateGids]+ let arbitrationFailureCount = 0+ for (+ let offset = 0;+ offset < gids.length;+ offset += DUPLICATE_GID_ARBITRATION_CONCURRENCY+ ) {+ const batch = gids.slice(+ offset,+ offset + DUPLICATE_GID_ARBITRATION_CONCURRENCY+ )+ const results = await Promise.allSettled(+ batch.map((gid) => rpc.tellStatus(gid))+ )+ for (let i = 0; i < results.length; i++) {+ const gid = batch[i]+ const result = results[i]+ const taskIndex = taskIndexByGid.get(gid)+ if (+ result.status === 'fulfilled' &&+ result.value.gid === gid &&+ taskIndex !== undefined+ ) {+ tasks[taskIndex] = result.value+ } else {+ arbitrationFailureCount += 1+ }+ }+ }++ for (const duplicate of ignoredDuplicateSample) {+ const taskIndex = taskIndexByGid.get(duplicate.gid)+ if (taskIndex !== undefined) {+ duplicate.keptStatus = tasks[taskIndex].status+ }+ }++ return {+ tasks,+ ignoredDuplicateCount,+ duplicateGidCount: duplicateGids.size,+ arbitrationFailureCount,+ ignoredDuplicateSample,+ }+}+// Trailing-edge debounce window for requestSave(). 50ms is large enough// that a synchronous burst of identity/transition writes (e.g. pasting// 100 URLs in AddTaskWindow → 100 createAndPersist calls in the same@@ -244,7 +357,7 @@ export class SessionManager {// (effective trackers, ~200 rows of global trackers) — that's// runtime state, reconstructible from settings.trackers: task.bt?.announceList ?? [],- pieceLength: task.bt?.pieceLength ?? 0,+ pieceLength: task.pieceLength,aggStatus: task.status,finishedAt: task.finishedAt,errorMessage: task.errorMessage,@@ -321,7 +434,29 @@ export class SessionManager {fetchAll((offset, num) => this.rpc.tellWaiting(offset, num)),fetchAll((offset, num) => this.rpc.tellStopped(offset, num)),])- const aria2Tasks = [...activeTasks, ...waitingTasks, ...stoppedTasks]+ const {+ tasks: aria2Tasks,+ ignoredDuplicateCount,+ duplicateGidCount,+ arbitrationFailureCount,+ ignoredDuplicateSample,+ } = await resolveCurrentAria2Rows(+ this.rpc,+ activeTasks,+ waitingTasks,+ stoppedTasks+ )+ if (ignoredDuplicateCount > 0) {+ log.warn(+ {+ duplicateCount: ignoredDuplicateCount,+ duplicateGidCount,+ arbitrationFailureCount,+ duplicates: ignoredDuplicateSample,+ },+ 'restore: reconciled duplicate aria2 rows'+ )+ }const aria2GidSet = new Set(aria2Tasks.map((t) => t.gid))this.taskManager.clear()@@ -795,7 +930,6 @@ export class SessionManager {trackers: taskPart.trackers.flat(),announceList: taskPart.trackers,isPrivate: taskPart.isPrivate,- pieceLength: taskPart.pieceLength,})}@@ -860,6 +994,7 @@ export class SessionManager {uploadedBytesBaseline,fileCount,connections: Number(aria2.connections),+ pieceLength: Number(aria2.pieceLength) || taskPart.pieceLength,infoHash: aria2.infoHash ?? taskPart.infoHash,metadataProgress: 0,priority: taskPart.priority,@@ -906,7 +1041,6 @@ export class SessionManager {trackers: taskPart.trackers.flat(),announceList: taskPart.trackers,isPrivate: taskPart.isPrivate,- pieceLength: taskPart.pieceLength,}): undefinedconst terminalFields = applyTerminalTransition(@@ -950,6 +1084,7 @@ export class SessionManager {uploadedBytesBaseline,fileCount: taskPart.fileCount,connections: 0,+ pieceLength: taskPart.pieceLength,infoHash: taskPart.infoHash,metadataProgress: 0,priority: taskPart.priority,@@ -1177,6 +1312,7 @@ export class SessionManager {uploadedBytesBaseline: 0,fileCount: 0,connections: 0,+ pieceLength: taskPart.pieceLength,infoHash: taskPart.infoHash,errorCode: null,errorDetailKey: null,diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex b91ba46f..79704df3 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -364,8 +364,8 @@ describe('finalizeTask failure-path publication routing', () => {// can finish between two polling ticks, so finalize sees totalBytes=0// and persists Completed with Size 0 / 0%. The fix is a pre-finalize// tellStatus refresh before removeDownloadResult retires the gid.-describe('finalizeTask HTTP pre-refresh byte counters', () => {- it('fills totalBytes/sizeWhenDone/downloadedBytes from aria2 when polling never observed them', async () => {+describe('finalizeTask HTTP pre-refresh transfer metadata', () => {+ it('fills byte counters and piece length when polling never observed them', async () => {const deps = makeDeps()const task = makeTask({totalBytes: 0,@@ -380,6 +380,7 @@ describe('finalizeTask HTTP pre-refresh byte counters', () => {totalBytes: 1234,downloadedBytes: 1234,sizeWhenDone: 1234,+ pieceLength: 1024,} as DownloadTask)@@ -388,6 +389,7 @@ describe('finalizeTask HTTP pre-refresh byte counters', () => {expect(task.totalBytes).toBe(1234)expect(task.sizeWhenDone).toBe(1234)expect(task.downloadedBytes).toBe(1234)+ expect(task.pieceLength).toBe(1024)expect(task.progress).toBe(1)expect(task.status).toBe(TaskStatus.Completed)})@@ -500,6 +502,7 @@ describe('finalizeTask HTTP pre-refresh byte counters', () => {totalBytes: 500,downloadedBytes: 500,sizeWhenDone: 500,+ pieceLength: 256,});(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(task@@ -512,6 +515,7 @@ describe('finalizeTask HTTP pre-refresh byte counters', () => {totalBytes: 999,downloadedBytes: 999,sizeWhenDone: 999,+ pieceLength: 1024,} as DownloadTask)@@ -524,6 +528,7 @@ describe('finalizeTask HTTP pre-refresh byte counters', () => {expect(task.totalBytes).toBe(500)expect(task.sizeWhenDone).toBe(500)expect(task.downloadedBytes).toBe(500)+ expect(task.pieceLength).toBe(256)})})@@ -971,7 +976,6 @@ describe('finalizeTask BT branch', () => {comment: null,magnetUri: null,sequentialDownload: false,- pieceLength: 0,},});(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex bf63959b..38e7a5b4 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -202,8 +202,9 @@ async function finalizeHttp(const desiredFinalPath = finalizeOutcome.finalFilePath ?? task.finalPathawait persistDesiredFinalPath(task, desiredFinalPath, deps)- // Refresh byte counters from aria2 BEFORE removeDownloadResult retires- // the gid. The polling loop only sees active/waiting tasks, so a+ // Refresh byte counters and piece length from aria2 BEFORE+ // removeDownloadResult retires the gid. The polling loop only sees+ // active/waiting tasks, so a// super-tiny HTTP download that completes between two ticks never gets// its totalLength/completedLength merged into our task — finalize would// then persist `Completed` with `totalBytes=0`, leaving the UI showing@@ -318,6 +319,9 @@ async function refreshTaskBytesBeforeFinalize(if (task.sizeWhenDone === 0 && refreshed.sizeWhenDone > 0) {task.sizeWhenDone = refreshed.sizeWhenDone}+ if (task.pieceLength === 0 && refreshed.pieceLength > 0) {+ task.pieceLength = refreshed.pieceLength+ }} catch (err) {deps.log.warn({ err, taskId: task.id, gid: task.engineTaskId },diff --git a/src/core/task/get-task-pieces.test.ts b/src/core/task/get-task-pieces.test.tsnew file mode 100644index 00000000..0fca32f9--- /dev/null+++ b/src/core/task/get-task-pieces.test.ts@@ -0,0 +1,126 @@+import type { DownloadTask } from '@shared/types/task'+import { TaskStatus } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'+import { describe, expect, it, vi } from 'vitest'+import { createGetTaskPiecesHandler } from './get-task-pieces'++function task(over: Partial<DownloadTask> = {}): DownloadTask {+ return makeDownloadTask(over)+}++describe('getTaskPieces handler', () => {+ it('returns engine-reported pieces for a live HTTP task', async () => {+ const engineAdapter = {+ getTaskPieces: vi.fn().mockResolvedValue({+ pieceLength: 1_048_576,+ numPieces: 8,+ bitfield: 'c0',+ }),+ }+ const taskManager = {+ getById: vi.fn().mockReturnValue(task({ engineTaskId: 'gid-http' })),+ }+ const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })++ await expect(handler({ taskId: 'task-http' })).resolves.toEqual({+ pieceLength: 1_048_576,+ numPieces: 8,+ bitfield: 'c0',+ })+ expect(engineAdapter.getTaskPieces).toHaveBeenCalledWith('gid-http')+ })++ it('synthesizes a complete map for a completed task whose engine row is gone', async () => {+ const engineAdapter = { getTaskPieces: vi.fn().mockResolvedValue(null) }+ const taskManager = {+ getById: vi.fn().mockReturnValue(+ task({+ engineTaskId: 'gid-complete',+ status: TaskStatus.Completed,+ totalBytes: 100,+ pieceLength: 30,+ })+ ),+ }+ const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })++ await expect(handler({ taskId: 'task-complete' })).resolves.toEqual({+ pieceLength: 30,+ numPieces: 4,+ bitfield: 'f',+ })+ })++ it('synthesizes when a completed engine row has no piece fields', async () => {+ const engineAdapter = {+ getTaskPieces: vi.fn().mockResolvedValue({+ pieceLength: 0,+ numPieces: 0,+ bitfield: '',+ }),+ }+ const taskManager = {+ getById: vi.fn().mockReturnValue(+ task({+ status: TaskStatus.Completed,+ totalBytes: 5 * 16_384,+ pieceLength: 16_384,+ })+ ),+ }+ const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })++ await expect(handler({ taskId: 'task-complete' })).resolves.toEqual({+ pieceLength: 16_384,+ numPieces: 5,+ bitfield: 'ff',+ })+ })++ it.each([TaskStatus.Error, TaskStatus.Removed])(+ 'does not synthesize an all-complete map for %s tasks',+ async (status) => {+ const engineAdapter = { getTaskPieces: vi.fn().mockResolvedValue(null) }+ const taskManager = {+ getById: vi+ .fn()+ .mockReturnValue(task({ status, totalBytes: 100, pieceLength: 30 })),+ }+ const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })++ await expect(handler({ taskId: 'task-terminal' })).resolves.toEqual({+ pieceLength: 0,+ numPieces: 0,+ bitfield: '',+ })+ }+ )++ it('returns zero-shape without calling the engine for an engine-less task', async () => {+ const engineAdapter = { getTaskPieces: vi.fn() }+ const taskManager = {+ getById: vi.fn().mockReturnValue(task({ engineTaskId: '' })),+ }+ const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })++ await expect(handler({ taskId: 'media-task' })).resolves.toEqual({+ pieceLength: 0,+ numPieces: 0,+ bitfield: '',+ })+ expect(engineAdapter.getTaskPieces).not.toHaveBeenCalled()+ })++ it('returns zero-shape when the task does not exist', async () => {+ const engineAdapter = { getTaskPieces: vi.fn() }+ const taskManager = { getById: vi.fn().mockReturnValue(undefined) }+ const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })++ await expect(handler({ taskId: 'missing' })).resolves.toEqual({+ pieceLength: 0,+ numPieces: 0,+ bitfield: '',+ })+ expect(engineAdapter.getTaskPieces).not.toHaveBeenCalled()+ })+})diff --git a/src/main/ipc/queries/get-task-pieces.ts b/src/core/task/get-task-pieces.tssimilarity index 50%rename from src/main/ipc/queries/get-task-pieces.tsrename to src/core/task/get-task-pieces.tsindex dc1b6b82..6fe17786 100644--- a/src/main/ipc/queries/get-task-pieces.ts+++ b/src/core/task/get-task-pieces.ts@@ -1,6 +1,7 @@import type { EngineAdapter } from '@core/engine/engine-adapter'import type { TaskPiecesResult } from '@shared/types/pieces'import type { DownloadTask } from '@shared/types/task'+import { TaskStatus } from '@shared/types/task'export interface GetTaskPiecesDeps {engineAdapter: Pick<EngineAdapter, 'getTaskPieces'>@@ -20,20 +21,15 @@ const EMPTY: TaskPiecesResult = {}/**- * For BT tasks evicted from aria2 post-seeding, the engine returns null.- * Synthesize a "fully complete" piece map from the persisted pieceLength- * (motrix.db) and totalBytes — bitfield filled with 'f' so every piece- * cell renders as done. Returns EMPTY when pieceLength is 0 (non-BT,- * legacy row pre-v4 migration, or polling never captured it).+ * Reconstruct the final all-complete map after finalize retires the engine+ * result. The exact piece length was captured from aria2 and persisted on the+ * task; trailing bits are ignored by the renderer.*/function synthesizeCompletePieces(task: DownloadTask): TaskPiecesResult {- const pieceLength = task.bt?.pieceLength ?? 0- if (pieceLength <= 0 || task.totalBytes <= 0) return EMPTY- const numPieces = Math.ceil(task.totalBytes / pieceLength)- // 4 pieces per hex char (nibble). Trailing bits past `numPieces` are- // ignored by statesFromBitfield, so over-filling with 'f' is safe.+ if (task.pieceLength <= 0 || task.totalBytes <= 0) return EMPTY+ const numPieces = Math.ceil(task.totalBytes / task.pieceLength)const bitfield = 'f'.repeat(Math.ceil(numPieces / 4))- return { pieceLength, numPieces, bitfield }+ return { pieceLength: task.pieceLength, numPieces, bitfield }}export function createGetTaskPiecesHandler(deps: GetTaskPiecesDeps) {@@ -42,8 +38,20 @@ export function createGetTaskPiecesHandler(deps: GetTaskPiecesDeps) {}: GetTaskPiecesPayload): Promise<TaskPiecesResult> => {const task = deps.taskManager.getById(taskId)if (!task) return EMPTY- const result = await deps.engineAdapter.getTaskPieces(task.engineTaskId)- if (result) return result++ if (task.engineTaskId) {+ const result = await deps.engineAdapter.getTaskPieces(task.engineTaskId)+ if (+ result &&+ (result.numPieces > 0 || task.status !== TaskStatus.Completed)+ ) {+ return result+ }+ }++ // A missing engine row does not prove completion: error rows are evicted+ // too, and synthesizing those as all-green would misrepresent the failure.+ if (task.status !== TaskStatus.Completed) return EMPTYreturn synthesizeCompletePieces(task)}}diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex 74c543ec..6643d438 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -62,6 +62,7 @@ export function mergeEngineTask(uploadSpeed: protected_.uploadSpeed,etaSeconds: protected_.etaSeconds,connections: protected_.connections,+ pieceLength: protected_.pieceLength,uploadedBytes,uploadedBytesBaseline: existing.uploadedBytesBaseline,fileCount: protected_.fileCount,@@ -86,6 +87,7 @@ export function hasEngineTaskDelta(before.uploadSpeed !== after.uploadSpeed ||before.etaSeconds !== after.etaSeconds ||before.connections !== after.connections ||+ before.pieceLength !== after.pieceLength ||before.uploadedBytes !== after.uploadedBytes ||before.fileCount !== after.fileCount ||before.errorMessage !== after.errorMessage ||diff --git a/src/core/task/non-zero-merge.ts b/src/core/task/non-zero-merge.tsindex 1d916c9f..bd3c0f01 100644--- a/src/core/task/non-zero-merge.ts+++ b/src/core/task/non-zero-merge.ts@@ -10,11 +10,12 @@ const MIRROR_FIELDS = ['downloadedBytes','sizeWhenDone','fileCount',+ 'pieceLength',] as const satisfies ReadonlyArray<keyof DownloadTask>/*** Merge an incoming engine snapshot into existing in-memory task state,- * preserving the five mirror fields when the engine reports zero against+ * preserving the mirror fields when the engine reports zero against* an existing non-zero value. This is the I-2 invariant: zero never* overwrites non-zero (root-cause fix for aria2_motrix paused-state collapse).*/diff --git a/src/core/task/task-row-to-download-task.test.ts b/src/core/task/task-row-to-download-task.test.tsindex 5d6a8214..cd2ad445 100644--- a/src/core/task/task-row-to-download-task.test.ts+++ b/src/core/task/task-row-to-download-task.test.ts@@ -94,6 +94,7 @@ describe('taskRowToDownloadTask', () => {downloadedBytes: 400,sizeWhenDone: 1000,fileCount: 3,+ pieceLength: 256,aggStatus: TaskStatus.Error,finishedAt: 1234,errorMessage: 'failed',@@ -111,6 +112,7 @@ describe('taskRowToDownloadTask', () => {downloadedBytes: 400,sizeWhenDone: 1000,fileCount: 3,+ pieceLength: 256,status: TaskStatus.Error,finishedAt: 1234,errorMessage: 'failed',diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.tsindex 46d03e68..ef789add 100644--- a/src/core/task/task-row-to-download-task.ts+++ b/src/core/task/task-row-to-download-task.ts@@ -32,7 +32,6 @@ export function taskRowToDownloadTask(trackers: task.trackers.flat(),announceList: task.trackers,isPrivate: task.isPrivate,- pieceLength: task.pieceLength,}): undefined@@ -59,6 +58,7 @@ export function taskRowToDownloadTask(uploadedBytesBaseline: task.uploadedBytesBaseline,fileCount: task.fileCount,connections: 0,+ pieceLength: task.pieceLength,infoHash: task.infoHash,errorCode: task.errorCode,errorDetailKey: task.errorDetailKey,diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.tsindex 35ef569c..f10a97fc 100644--- a/src/main/ipc/queries.ts+++ b/src/main/ipc/queries.ts@@ -26,6 +26,7 @@ import type {TaskSpeedHistoryStore,TransferStatsRuntime,} from '@core/stats'+import { createGetTaskPiecesHandler } from '@core/task/get-task-pieces'import { slimTasksForBroadcast } from '@core/task/slim-task-for-broadcast'import type { TaskManager } from '@core/task/task-manager'import type { TrackerManager } from '@core/tracker'@@ -50,7 +51,6 @@ import { createGetGeoIPStatusHandler } from './queries/get-geo-ip-status'import { createGetTaskBtTrackerHandler } from './queries/get-task-bt-tracker'import { createGetTaskFilesHandler } from './queries/get-task-files'import { createGetTaskPeersHandler } from './queries/get-task-peers'-import { createGetTaskPiecesHandler } from './queries/get-task-pieces'import { registerTrustedIpcHandler } from './trusted-ipc'export interface QueryContext {diff --git a/src/main/ipc/queries/get-task-pieces.test.ts b/src/main/ipc/queries/get-task-pieces.test.tsdeleted file mode 100644index c2e7750b..00000000--- a/src/main/ipc/queries/get-task-pieces.test.ts+++ /dev/null@@ -1,110 +0,0 @@-import type { DownloadTask } from '@shared/types/task'-import { makeDownloadTask } from '@test-utils/task'-import { describe, expect, it, vi } from 'vitest'-import { createGetTaskPiecesHandler } from './get-task-pieces'--// Minimal task fixture — handler reads engineTaskId, totalBytes, bt.pieceLength.-function task(over: Partial<DownloadTask> = {}): DownloadTask {- return makeDownloadTask(over)-}--describe('getTaskPieces handler', () => {- it('returns engine-reported pieces when task is found', async () => {- const engineAdapter = {- getTaskPieces: vi.fn().mockResolvedValue({- pieceLength: 16384,- numPieces: 8,- bitfield: 'ff',- }),- }- const taskManager = {- getById: vi.fn().mockReturnValue(task({ engineTaskId: 'gid-1' })),- }- const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })- const result = await handler({ taskId: 'task-1' })- expect(result).toEqual({- pieceLength: 16384,- numPieces: 8,- bitfield: 'ff',- })- expect(engineAdapter.getTaskPieces).toHaveBeenCalledWith('gid-1')- })-- it('synthesizes full-complete piece map when engine returns null and pieceLength is known', async () => {- const engineAdapter = {- getTaskPieces: vi.fn().mockResolvedValue(null),- }- // 100 bytes / 30-byte pieces → ceil = 4 pieces; 4/4 = 1 hex char of 'f'- const taskManager = {- getById: vi.fn().mockReturnValue(- task({- engineTaskId: 'gid-2',- totalBytes: 100,- bt: { pieceLength: 30 } as DownloadTask['bt'],- })- ),- }- const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })- expect(await handler({ taskId: 'task-2' })).toEqual({- pieceLength: 30,- numPieces: 4,- bitfield: 'f',- })- })-- it('synthesizes for typical 4-piece torrent (over-fills bitfield safely)', async () => {- const engineAdapter = {- getTaskPieces: vi.fn().mockResolvedValue(null),- }- // 5 pieces → ceil(5/4) = 2 hex chars 'ff'; statesFromBitfield only- // reads first 5 bits, the 3 trailing 1-bits are ignored.- const taskManager = {- getById: vi.fn().mockReturnValue(- task({- engineTaskId: 'gid-3',- totalBytes: 5 * 16384,- bt: { pieceLength: 16384 } as DownloadTask['bt'],- })- ),- }- const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })- expect(await handler({ taskId: 'task-3' })).toEqual({- pieceLength: 16384,- numPieces: 5,- bitfield: 'ff',- })- })-- it('returns zero-shape when engine null and pieceLength is unknown (legacy / non-BT)', async () => {- const engineAdapter = {- getTaskPieces: vi.fn().mockResolvedValue(null),- }- const taskManager = {- getById: vi.fn().mockReturnValue(- task({- engineTaskId: 'gid-x',- totalBytes: 1024,- // bt undefined — non-BT, or BT with pre-v4 metadata- })- ),- }- const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })- expect(await handler({ taskId: 'task-x' })).toEqual({- pieceLength: 0,- numPieces: 0,- bitfield: '',- })- })-- it('returns zero-shape without calling engine when taskManager has no record', async () => {- const engineAdapter = { getTaskPieces: vi.fn() }- const taskManager = { getById: vi.fn().mockReturnValue(undefined) }- const handler = createGetTaskPiecesHandler({ engineAdapter, taskManager })- expect(await handler({ taskId: 'missing' })).toEqual({- pieceLength: 0,- numPieces: 0,- bitfield: '',- })- expect(engineAdapter.getTaskPieces).not.toHaveBeenCalled()- })-})diff --git a/src/renderer/routes/dashboard/tiles/tasks-tile.fixture.ts b/src/renderer/routes/dashboard/tiles/tasks-tile.fixture.tsindex 989c1f9a..ea2e4453 100644--- a/src/renderer/routes/dashboard/tiles/tasks-tile.fixture.ts+++ b/src/renderer/routes/dashboard/tiles/tasks-tile.fixture.ts@@ -56,7 +56,6 @@ function btExtension(ratio: number): BtExtension {isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,}}@@ -107,6 +106,7 @@ function makeTask(uploadedBytesBaseline: 0,fileCount: 1,connections: 8,+ pieceLength: 1_048_576,infoHash: null,errorCode: null,errorDetailKey: null,diff --git a/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx b/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsxindex ba4aec8c..444e3297 100644--- a/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx+++ b/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx@@ -137,7 +137,6 @@ function bt(ratio: number): BtExtension {isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,}}diff --git a/src/renderer/routes/downloads/inspector/files-tab.test.tsx b/src/renderer/routes/downloads/inspector/files-tab.test.tsxindex e6b6bedc..d851f1f2 100644--- a/src/renderer/routes/downloads/inspector/files-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/files-tab.test.tsx@@ -76,7 +76,6 @@ const mockTask = (over: Partial<DownloadTask> = {}): DownloadTask =>isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,},...over,})@@ -162,7 +161,6 @@ describe('FilesTab', () => {isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,},})}/>diff --git a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx b/src/renderer/routes/downloads/inspector/overview-tab.test.tsxindex be26c49a..3971b0a9 100644--- a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx@@ -62,6 +62,7 @@ const task: DownloadTask = {uploadedBytesBaseline: 0,fileCount: 42,connections: 0,+ pieceLength: 1_048_576,infoHash: 'abc',errorCode: null,errorDetailKey: null,@@ -94,7 +95,6 @@ const task: DownloadTask = {isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,},}diff --git a/src/renderer/routes/downloads/inspector/pieces-tab.test.tsx b/src/renderer/routes/downloads/inspector/pieces-tab.test.tsxindex 4a29b2a2..f74bbb69 100644--- a/src/renderer/routes/downloads/inspector/pieces-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/pieces-tab.test.tsx@@ -40,24 +40,25 @@ describe('PiecesTab', () => {expect(root?.getAttribute('dir')).toBe('ltr')})- it.each([- [TaskStatus.Completed],- [TaskStatus.Error],- [TaskStatus.Removed],- ] as const)(- 'renders full-complete canvas for synthesized pieces (status=%s)',- (status) => {- // Mirror the IPC handler synthesizing a fully-done piece map for- // an evicted BT task: every piece is `done`, all-green canvas.- mockPieces.value = { pieceLength: 16384, numPieces: 5, bitfield: 'ff' }- const { container } = render(- <PiecesTab task={makeTask('t-evicted', status)} />- )- const canvas = container.querySelector('canvas')- expect(canvas).not.toBeNull()- expect(canvas?.getAttribute('data-piece-count')).toBe('5')- }- )+ it('renders full-complete canvas for synthesized completed pieces', () => {+ mockPieces.value = { pieceLength: 16384, numPieces: 5, bitfield: 'ff' }+ const { container } = render(+ <PiecesTab task={makeTask('t-evicted', TaskStatus.Completed)} />+ )+ const canvas = container.querySelector('canvas')+ expect(canvas).not.toBeNull()+ expect(canvas?.getAttribute('data-piece-count')).toBe('5')+ })++ it('renders the empty state when no trustworthy piece map remains', () => {+ mockPieces.value = { pieceLength: 0, numPieces: 0, bitfield: '' }+ const { container } = render(+ <PiecesTab task={makeTask('t-error', TaskStatus.Error)} />+ )++ expect(container.querySelector('canvas')).toBeNull()+ expect(container.textContent).toContain('No pieces data')+ })it('keeps loading-shaped placeholder when pieces=null on a live status', () => {mockPieces.value = nulldiff --git a/src/renderer/routes/downloads/inspector/pieces-tab.tsx b/src/renderer/routes/downloads/inspector/pieces-tab.tsxindex 3a902754..4cbfe60c 100644--- a/src/renderer/routes/downloads/inspector/pieces-tab.tsx+++ b/src/renderer/routes/downloads/inspector/pieces-tab.tsx@@ -8,10 +8,9 @@ import { useTranslation } from 'react-i18next'// Statuses where the bitfield is actively changing and warrants the 2s// polling cadence. For other statuses (paused / seeding / completed /// error / removed) the hook still fetches once on mount so the user sees-// the last-known piece map — it just stops polling after that. For-// evicted-from-aria2 tasks (Completed BT after removeDownloadResult),-// the IPC handler synthesizes a full-complete piece map from-// task.bt.pieceLength + totalBytes, so PiecesTab still renders an+// an available last-known piece map — it just stops polling after that.+// For completed tasks evicted from aria2, the query handler synthesizes a+// full-complete piece map from task.pieceLength + totalBytes, so this renders an// all-green canvas without needing to know about the eviction here.const PIECES_LIVE_STATUSES = new Set<TaskStatus>([TaskStatus.FetchingMetadata,@@ -194,7 +193,7 @@ export function PiecesTab({ task }: { task: DownloadTask }) {<canvasref={canvasRef}data-piece-count={cells.length}- aria-label="BT piece map"+ aria-label={t('panel.downloads.inspector.pieces.mapLabel')}className="block max-w-full"/></div>diff --git a/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx b/src/renderer/routes/downloads/inspector/trackers-tab.test.tsxindex 4f2bd641..c0600b4b 100644--- a/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/trackers-tab.test.tsx@@ -75,7 +75,6 @@ function makeBtTask(overrides: Partial<DownloadTask> = {}): DownloadTask {isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,},...overrides,})diff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsxindex cf32bded..e76ce2b3 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx@@ -4,7 +4,7 @@ import { createSelectionStore } from '@renderer/components/desktop-kit/selectionimport type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'import { DownloadErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'-import { TaskStatus, TaskType } from '@shared/types/task'+import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'import {TaskHistoryAccuracy,TaskHistoryEventKind,@@ -181,6 +181,32 @@ describe('TaskInspectorDrawer', () => {)})+ it('shows Pieces for a direct HTTP task', () => {+ const selection = createSelectionStore<DownloadTask>((t) => t.id)+ const tasks = [+ fake({ id: 'a', type: TaskType.Http, kind: TaskKind.Direct }),+ ]+ selection.getState().setItems([...tasks])+ selection.getState().select('a')++ render(<TestHarness selection={selection} tasks={tasks} />)++ expect(screen.getByRole('tab', { name: /pieces/i })).toBeInTheDocument()+ expect(screen.queryByRole('tab', { name: /peers/i })).toBeNull()+ expect(screen.queryByRole('tab', { name: /trackers/i })).toBeNull()+ })++ it('does not show Pieces for a multi-instance HTTP media task', () => {+ const selection = createSelectionStore<DownloadTask>((t) => t.id)+ const tasks = [fake({ id: 'a', type: TaskType.Http, kind: TaskKind.Hls })]+ selection.getState().setItems([...tasks])+ selection.getState().select('a')++ render(<TestHarness selection={selection} tasks={tasks} />)++ expect(screen.queryByRole('tab', { name: /pieces/i })).toBeNull()+ })+it('reuses one keyed Activity cache across tab remounts', async () => {const user = userEvent.setup()const selection = createSelectionStore<DownloadTask>((t) => t.id)diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex 7f1b6786..9c3d2ace 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -14,6 +14,7 @@ import { cn } from '@renderer/lib/utils'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import { TaskType } from '@shared/types/task'+import { canInspectPieces } from '@shared/types/task-actions'import {Files,Grid3x3,@@ -73,6 +74,7 @@ export function TaskInspectorDrawer({const open = selected.length > 0const single = selected.length === 1 ? selected[0] : nullconst isBt = single?.type === TaskType.Bt || single?.type === TaskType.Magnet+ const showPieces = single !== null && canInspectPieces(single)const [subtab, setSubtab] = useState<SubTab>('overview')const activitySnapshotCache = useMemo(createTaskInspectorActivitySnapshotCache,@@ -177,7 +179,7 @@ export function TaskInspectorDrawer({><Files className="size-3.5" /></TabsTrigger>- {isBt && (+ {showPieces && (<TabsTriggervalue="pieces"className="text-xs px-5"@@ -222,7 +224,7 @@ export function TaskInspectorDrawer({<TabsContent value="files" className="min-h-0"><FilesTab task={single} /></TabsContent>- {isBt && (+ {showPieces && (<TabsContent value="pieces" className="min-h-0"><PiecesTab task={single} /></TabsContent>diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.tsindex e46167ed..105b13bb 100644--- a/src/server/ipc/queries.test.ts+++ b/src/server/ipc/queries.test.ts@@ -7,6 +7,7 @@ import { NotificationCenter } from '@core/notifications/notification-center'import { MotrixDatabase } from '@core/session/motrix-database'import { ErrorCode } from '@shared/errors'import { Queries } from '@shared/protocol/queries'+import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { buildServerQueryHandlers, type ServerQueryContext } from './queries'@@ -323,6 +324,38 @@ describe('buildServerQueryHandlers — GetTaskDetail parity', () => {})})+describe('buildServerQueryHandlers — GetTaskPieces parity', () => {+ it('uses the shared piece query handler in web mode', async () => {+ const task = makeDownloadTask({ id: 'task-http', engineTaskId: 'gid-http' })+ const getTaskPieces = vi.fn().mockResolvedValue({+ pieceLength: 1_048_576,+ numPieces: 8,+ bitfield: 'c0',+ })+ const handlers = buildServerQueryHandlers(+ makeCtx({+ taskManager: {+ getAll: vi.fn(() => [task]),+ getById: vi.fn(() => task),+ },+ engineAdapter: {+ getTaskBtTracker: vi.fn(),+ getTaskPieces,+ },+ }) as unknown as ServerQueryContext+ )++ await expect(+ handlers[Queries.GetTaskPieces]?.({ taskId: 'task-http' })+ ).resolves.toEqual({+ pieceLength: 1_048_576,+ numPieces: 8,+ bitfield: 'c0',+ })+ expect(getTaskPieces).toHaveBeenCalledWith('gid-http')+ })+})+describe('buildServerQueryHandlers — notification center', () => {let db: MotrixDatabaselet notificationCenter: NotificationCenterdiff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.tsindex bc61e7d9..f1f031f3 100644--- a/src/server/ipc/queries.ts+++ b/src/server/ipc/queries.ts@@ -21,6 +21,7 @@ import type {TaskSpeedHistoryStore,TransferStatsRuntime,} from '@core/stats'+import { createGetTaskPiecesHandler } from '@core/task/get-task-pieces'import { slimTasksForBroadcast } from '@core/task/slim-task-for-broadcast'import type { TaskManager } from '@core/task/task-manager'import type { TrackerManager } from '@core/tracker'@@ -146,6 +147,11 @@ export function buildServerQueryHandlers([Queries.GetTaskDetail]: async (taskId: string) =>taskManager.getById(taskId) ?? null,+ [Queries.GetTaskPieces]: createGetTaskPiecesHandler({+ engineAdapter,+ taskManager,+ }),+[Queries.GetStats]: async () => statsAggregator.getStats(),[Queries.GetSpeedHistory]: async (params?: { limit?: number }) =>diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 441b02f5..c0dd733c 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -641,6 +641,7 @@}},"pieces": {+ "mapLabel": "Download piece map","legend": {"done": "Completed","active": "Downloading",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 00b8fefa..d61e570f 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -634,6 +634,7 @@}},"pieces": {+ "mapLabel": "下载分片图","legend": {"done": "已下载","active": "下载中",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex f9c12586..a116687d 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -634,6 +634,7 @@}},"pieces": {+ "mapLabel": "下載區塊圖","legend": {"done": "已完成","active": "下載中",diff --git a/src/shared/types/pieces.ts b/src/shared/types/pieces.tsindex 95a67333..575eacfd 100644--- a/src/shared/types/pieces.ts+++ b/src/shared/types/pieces.ts@@ -1,19 +1,13 @@-/**- * BT piece state for a single task.- *- * For non-BT tasks (HTTP/FTP/SFTP) the engine returns no piece info;- * this type uses zero-shape values rather than nulls so callers don't- * have to branch on task type.- */+/** Piece state for a single engine-backed download task. */export interface TaskPiecesResult {- /** Bytes per piece. 0 when the engine has no piece concept. */+ /** Bytes per piece. 0 until the engine knows the piece layout. */pieceLength: number- /** Total piece count. 0 for non-BT tasks. */+ /** Total piece count. 0 until the engine knows the content length. */numPieces: number/*** Hex-encoded bitfield from aria2 `tellStatus.bitfield`.* Each hex char encodes 4 pieces (MSB = piece i, LSB = piece i+3).- * Empty string for non-BT tasks.+ * Empty while the download has not started or no live map is available.*/bitfield: string}diff --git a/src/shared/types/task-actions.test.ts b/src/shared/types/task-actions.test.tsindex 1c822906..dd5fa796 100644--- a/src/shared/types/task-actions.test.ts+++ b/src/shared/types/task-actions.test.ts@@ -11,6 +11,7 @@ import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it } from 'vitest'import {canAttemptRetry,+ canInspectPieces,canPause,canRebuildTaskInputs,canRemove,@@ -57,6 +58,20 @@ function makeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {})}+describe('canInspectPieces', () => {+ it.each([+ [TaskKind.Direct, TaskType.Http, true],+ [TaskKind.Direct, TaskType.Ftp, true],+ [TaskKind.Direct, TaskType.Metalink, true],+ [TaskKind.Bt, TaskType.Bt, true],+ [TaskKind.Bt, TaskType.Magnet, true],+ [TaskKind.Hls, TaskType.Http, false],+ [TaskKind.Mux, TaskType.Http, false],+ ] as const)('returns %s/%s -> %s', (kind, type, expected) => {+ expect(canInspectPieces(makeTask({ kind, type }))).toBe(expected)+ })+})+describe('canPause', () => {it.each([TaskStatus.Queued,diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex 790c956a..e2c21529 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -21,6 +21,11 @@ export function isMediaKind(kind: TaskKind): boolean {return kind === TaskKind.Mux || kind === TaskKind.Hls}+/** Whether a task has one engine-level piece map that the inspector can show. */+export function canInspectPieces(t: DownloadTask): boolean {+ return t.kind === TaskKind.Direct || isTorrentLike(t)+}+/*** Terminal in the occurrence/terminal-metadata sense: the two statuses that* carry `finishedAt`/`error*` fields and qualify for a terminal occurrence.diff --git a/src/shared/types/task.ts b/src/shared/types/task.tsindex 1a706d37..7310a914 100644--- a/src/shared/types/task.ts+++ b/src/shared/types/task.ts@@ -103,6 +103,10 @@ export interface DownloadTask {// ── connection & metadata ────────────────────────connections: number+ // aria2 piece size in bytes. Applies to direct HTTP/FTP downloads as+ // well as BitTorrent; persisted so completed tasks can reconstruct their+ // fully-downloaded piece map after the engine result has been retired.+ pieceLength: numberinfoHash: string | nullerrorCode: DownloadErrorCode | nullerrorDetailKey: string | null@@ -155,17 +159,12 @@ export interface BtExtension {isPrivate: booleanmagnetUri: string | nullsequentialDownload: boolean- // .torrent-fixed piece length in bytes. Persisted so a task evicted- // from aria2 (post-seeding) can still synthesize a full piece map- // for the inspector — `numPieces = ceil(totalBytes / pieceLength)`,- // bitfield filled with 'f'. 0 for non-BT or until first poll.- pieceLength: number}/*** Build a BtExtension with all-zero/empty defaults. Use at creation and* restore sites that start from defaults and override only the few fields- * they actually know — keeps the 13-field shape in one place so a new field+ * they actually know — keeps the extension shape in one place so a new field* gets one default here instead of being missed at a copy. Sites that derive* most fields from an engine snapshot (e.g. aria2 translate) keep an explicit* literal so the compiler still flags any unhandled field.@@ -213,6 +212,7 @@ export function makeDownloadTask(uploadedBytesBaseline: 0,fileCount: 0,connections: 0,+ pieceLength: 0,infoHash: null,errorCode: null,errorDetailKey: null,@@ -246,7 +246,6 @@ export function makeDefaultBtExtension(isPrivate: false,magnetUri: null,sequentialDownload: false,- pieceLength: 0,...overrides,}}diff --git a/src/test-utils/task.ts b/src/test-utils/task.tsindex 97f0e433..c949d142 100644--- a/src/test-utils/task.ts+++ b/src/test-utils/task.ts@@ -39,6 +39,7 @@ export function makeDownloadTask(uploadedBytesBaseline: 0,fileCount: 0,connections: 0,+ pieceLength: 0,infoHash: null,errorCode: null,errorDetailKey: null,