A full-featured download manager.
fix(task): recover interrupted download finalization (#2115)
Dr_rOot6d594419625d
diff --git a/e2e/fixtures/electron-app.ts b/e2e/fixtures/electron-app.tsindex ac0741c0..6927bc32 100644--- a/e2e/fixtures/electron-app.ts+++ b/e2e/fixtures/electron-app.ts@@ -96,10 +96,21 @@ export async function waitForEngineReady(}).motrixif (!api) return null- const result = (await api.invoke('query:getEngineStatus')) as {- state: string+ try {+ const result = (await api.invoke('query:getEngineStatus')) as {+ state: string+ }+ return result?.state ?? null+ } catch (error) {+ // The first window can appear before main finishes registering IPC.+ if (+ String(error).includes(+ "No handler registered for 'query:getEngineStatus'"+ )+ )+ return null+ throw error}- return result?.state ?? null})if (state === 'ready') returnawait new Promise((r) => setTimeout(r, 250))diff --git a/src/core/engine/aria2/aria2-adapter.integration.test.ts b/src/core/engine/aria2/aria2-adapter.integration.test.tsindex a0bb5473..b33bec76 100644--- a/src/core/engine/aria2/aria2-adapter.integration.test.ts+++ b/src/core/engine/aria2/aria2-adapter.integration.test.ts@@ -210,6 +210,38 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(}}, 15_000)+ it('retires active seeders and immediately releases their output for finalize', async () => {+ for (let attempt = 0; attempt < 3; attempt++) {+ const staging = path.join(baseDir, `finalize-${attempt}.part`)+ const output = path.join(baseDir, `finalize-${attempt}`)+ await fs.mkdir(staging, { recursive: true })+ await fs.cp(SAMPLE_DATA_DIR, path.join(staging, 'sample-data'), {+ recursive: true,+ })+ const gid = await adapter.addTorrent({+ metadata: new Uint8Array(readFileSync(SAMPLE_TORRENT)),+ saveDir: staging,+ btSeedUnverified: true,+ seedTime: 60,+ pause: false,+ })+ try {+ await waitFor(async () => {+ const state = await adapter.getTaskStatus(gid)+ return state?.status === TaskStatus.Seeding ? state : null+ }, 5000)+ await adapter.forceRemoveTask(gid)+ // No test-side wait for the result: this is the failing sequence in #2084.+ await adapter.removeDownloadResult(gid)+ await fs.rename(staging, output)+ expect(await fs.readdir(output)).toContain('sample-data')+ await expect(rpc.tellStatus(gid)).rejects.toThrow(/not found/i)+ } finally {+ await discardTask(adapter, gid)+ }+ }+ }, 30_000)+it('removeDownloadResult succeeds after aria2.remove on a stopped task', async () => {const stagingDir = path.join(baseDir, 'removeresult-staging')await fs.mkdir(stagingDir, { recursive: true })diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex a5ec90b9..99f9fa47 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -1916,6 +1916,48 @@ describe('Aria2Adapter', () => {})describe('removeDownloadResult', () => {+ it('waits only when the force-remove result is not available yet', async () => {+ vi.useFakeTimers()+ try {+ const rpc = createMockRpc()+ const gid = 'bbfd794b501706e6'+ vi.mocked(rpc.removeDownloadResult)+ .mockRejectedValueOnce(+ new Error(`Could not remove download result of GID#${gid}`)+ )+ .mockRejectedValueOnce(+ new Error(`Could not remove download result of GID#${gid}`)+ )+ .mockResolvedValue('OK')+ const adapter = new Aria2Adapter(rpc)+ const result = adapter.removeDownloadResult(gid)+ await vi.runAllTimersAsync()+ await result+ expect(rpc.removeDownloadResult).toHaveBeenCalledTimes(3)+ } finally {+ vi.useRealTimers()+ }+ })++ it('bounds pending-stop retries and retains the failure', async () => {+ vi.useFakeTimers()+ try {+ const rpc = createMockRpc()+ const gid = '88ca340e39b2c3d6'+ const error = new Error(+ `Could not remove download result of GID#${gid}`+ )+ vi.mocked(rpc.removeDownloadResult).mockRejectedValue(error)+ const result = new Aria2Adapter(rpc).removeDownloadResult(gid)+ const assertion = expect(result).rejects.toBe(error)+ await vi.runAllTimersAsync()+ await assertion+ expect(rpc.removeDownloadResult).toHaveBeenCalledTimes(7)+ } finally {+ vi.useRealTimers()+ }+ })+it('calls aria2.removeDownloadResult', async () => {const rpc = createMockRpc()vi.mocked(rpc.removeDownloadResult).mockResolvedValue('OK')diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex 8a6d2262..e8ae39dd 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -1,5 +1,6 @@import { access } from 'node:fs/promises'import path from 'node:path'+import { setTimeout as delay } from 'node:timers/promises'import { getLogger } from '@core/logger'import {extractAria2ProxyCredentials,@@ -797,15 +798,21 @@ export class Aria2Adapter implements EngineAdapter {}async removeDownloadResult(engineTaskId: string): Promise<void> {- try {- await this.rpc.removeDownloadResult(engineTaskId)- } catch (err) {- // Idempotent only when aria2 explicitly says the GID is gone AND this- // engine's not-found is trustworthy. Transport, other RPC failures, and- // untrusted not-found (pre-.3 persistent fork) must remain observable so- // callers do not erase local history while the engine row survives.- if (isNotFoundError(err) && this.trustsNotFound()) return- throw err+ // forceRemove acknowledges a halt request before aria2 creates its stopped+ // result. Retry only that precise transition race; successful cleanups add+ // no delay, and transport/persistent-delete failures remain observable.+ for (let attempt = 0; ; attempt++) {+ try {+ await this.rpc.removeDownloadResult(engineTaskId)+ return+ } catch (err) {+ if (isNotFoundError(err) && this.trustsNotFound()) return+ const message = err instanceof Error ? err.message : String(err)+ const pendingStop =+ message === `Could not remove download result of GID#${engineTaskId}`+ if (!pendingStop || attempt >= 6) throw err+ await delay(Math.min(100 * 2 ** attempt, 1000))+ }}}diff --git a/src/core/fs/finalize-path.test.ts b/src/core/fs/finalize-path.test.tsnew file mode 100644index 00000000..df8ea9ba--- /dev/null+++ b/src/core/fs/finalize-path.test.ts@@ -0,0 +1,45 @@+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import { resolveFinalizeTarget } from './finalize-path'++describe('resolveFinalizeTarget', () => {+ it.each([+ ['/downloads/', 'sub/file', '/downloads/sub/file'],+ ['/', 'file', '/file'],+ ])('resolves %s + %s', (root, target, expected) => {+ expect(resolveFinalizeTarget(root, target, path.posix)).toBe(expected)+ })++ it.each(['', '.', '/downloads', '../file', '/downloads-other/file'])(+ 'rejects %s',+ (target) => {+ expect(() =>+ resolveFinalizeTarget('/downloads', target, path.posix)+ ).toThrow('descendant')+ }+ )++ it.each([+ ['C:\\Downloads\\', 'c:\\downloads\\file'],+ ['C:\\', 'C:\\file'],+ ['\\\\server\\share\\', '\\\\SERVER\\share\\file'],+ ['C:\\Downloads', '\\\\?\\C:\\Downloads\\file'],+ ['\\\\?\\C:\\Downloads', 'C:\\Downloads\\file'],+ ['\\\\server\\share', '\\\\?\\UNC\\server\\share\\file'],+ ])('accepts equivalent Windows roots: %s -> %s', (root, target) => {+ expect(resolveFinalizeTarget(root, target, path.win32)).toBe(+ path.win32.resolve(root, target)+ )+ })++ it.each([+ ['C:\\Downloads', 'D:\\file'],+ ['C:\\Downloads', 'C:\\Downloads2\\file'],+ ['C:\\Downloads', '\\\\?\\C:\\Downloads'],+ ['\\\\server\\share', '\\\\server\\other\\file'],+ ])('rejects a different or equal Windows root: %s -> %s', (root, target) => {+ expect(() => resolveFinalizeTarget(root, target, path.win32)).toThrow(+ 'descendant'+ )+ })+})diff --git a/src/core/fs/finalize-path.ts b/src/core/fs/finalize-path.tsnew file mode 100644index 00000000..9f716029--- /dev/null+++ b/src/core/fs/finalize-path.ts@@ -0,0 +1,36 @@+import path from 'node:path'++/** Resolve plugin-relative targets and apply the same boundary at commit time. */+export function resolveFinalizeTarget(+ saveDir: string,+ targetPath: string,+ paths: typeof path = path+): string {+ if (+ !paths.isAbsolute(saveDir) ||+ saveDir.includes('\0') ||+ targetPath.includes('\0')+ ) {+ throw new Error('finalize save directory must be an absolute path')+ }+ const target = paths.resolve(saveDir, targetPath)+ // Windows API paths and user-selected paths can name the same directory+ // using different namespace prefixes. Keep the original IO representation,+ // but compare both with the same Win32 path semantics.+ const comparable = (value: string): string =>+ paths.sep === '\\'+ ? value+ .replace(/^\\\\\?\\UNC\\/i, '\\\\')+ .replace(/^\\\\\?\\([a-z]:\\)/i, '$1')+ : value+ const relative = paths.relative(comparable(saveDir), comparable(target))+ if (+ relative === '' ||+ relative === '..' ||+ relative.startsWith(`..${paths.sep}`) ||+ paths.isAbsolute(relative)+ ) {+ throw new Error('finalize target must be a descendant of saveDir')+ }+ return target+}diff --git a/src/core/plugin/finalize/hook-plan.ts b/src/core/plugin/finalize/hook-plan.tsindex 6834db32..311d3875 100644--- a/src/core/plugin/finalize/hook-plan.ts+++ b/src/core/plugin/finalize/hook-plan.ts@@ -1,4 +1,5 @@import path from 'node:path'+import { resolveFinalizeTarget } from '@core/fs/finalize-path'import type { ArtifactIdentity } from './artifact-identity'export interface FinalizeReplacement {@@ -27,19 +28,19 @@ export interface HookPlan {contributors: readonly string[]}-export function assertValidHookPlan(plan: HookPlan): void {- if (!path.isAbsolute(plan.sourcePath) || !path.isAbsolute(plan.targetPath)) {+export function assertFinalizePaths(+ saveDir: string,+ sourcePath: string,+ targetPath: string+): void {+ if (!path.isAbsolute(sourcePath) || !path.isAbsolute(targetPath)) {throw new Error('finalize paths must be absolute')}- const relative = path.relative(plan.saveDir, plan.targetPath)- if (- relative === '' ||- relative === '..' ||- relative.startsWith(`..${path.sep}`) ||- path.isAbsolute(relative)- ) {- throw new Error('finalize target must be a descendant of saveDir')- }+ resolveFinalizeTarget(saveDir, targetPath)+}++export function assertValidHookPlan(plan: HookPlan): void {+ assertFinalizePaths(plan.saveDir, plan.sourcePath, plan.targetPath)if (plan.replacement?.identity.kind !== undefined &&!plan.replacement.pluginIddiff --git a/src/core/plugin/hooks/ctx-update.test.ts b/src/core/plugin/hooks/ctx-update.test.tsindex d82e5a49..672df651 100644--- a/src/core/plugin/hooks/ctx-update.test.ts+++ b/src/core/plugin/hooks/ctx-update.test.ts@@ -158,7 +158,7 @@ describe('validateFinalizePatch', () => {{ filePath: 'subdir/x.mp4' },makeOpts({ saveDir: '/downloads' }))- expect(result.filePath).toBe('subdir/x.mp4')+ expect(result.filePath).toBe('/downloads/subdir/x.mp4')})it('accepts filePath when saveDir has a trailing slash', () => {@@ -166,7 +166,7 @@ describe('validateFinalizePatch', () => {{ filePath: 'x.mp4' },makeOpts({ saveDir: '/tmp/save/' }))- expect(result.filePath).toBe('x.mp4')+ expect(result.filePath).toBe('/tmp/save/x.mp4')})it('rejects filePath that escapes saveDir via ../', () => {@@ -233,3 +233,9 @@ describe('validateFinalizePatch', () => {}})})++it('rejects a plugin target equal to the save directory before committing it', () => {+ expect(() => validateFinalizePatch({ filePath: '.' }, makeOpts())).toThrow(+ 'descendant'+ )+})diff --git a/src/core/plugin/hooks/ctx-update.ts b/src/core/plugin/hooks/ctx-update.tsindex 503da172..480d54c0 100644--- a/src/core/plugin/hooks/ctx-update.ts+++ b/src/core/plugin/hooks/ctx-update.ts@@ -1,4 +1,4 @@-import path from 'node:path'+import { resolveFinalizeTarget } from '@core/fs/finalize-path'import {extractAria2ProxyCredentials,normalizeAria2TaskProxyUrl,@@ -87,14 +87,16 @@ export function validateFinalizePatch(ErrorCode.PluginRuntimeFault,`CtxUpdateInvalid: ${parsed.error.issues[0]?.message ?? 'invalid patch'}`)- // Normalize trailing separators so /downloads/ does not produce /downloads//- const base = opts.saveDir.replace(/[/\\]+$/, '')- const resolved = path.resolve(base, parsed.data.filePath)- // Invariant I31: filePath must not escape the saveDir sandbox- if (!resolved.startsWith(base + path.sep) && resolved !== base)+ try {+ return {+ ...parsed.data,+ filePath: resolveFinalizeTarget(opts.saveDir, parsed.data.filePath),+ }+ } catch (cause) {throw new AppError(ErrorCode.PluginRuntimeFault,- 'CtxUpdateInvalid: filePath escapes saveDir'+ `CtxUpdateInvalid: ${(cause as Error).message}`,+ cause)- return parsed.data+ }}diff --git a/src/core/session/durable-finalize-runtime.test.ts b/src/core/session/durable-finalize-runtime.test.tsindex 3f6a7e15..c1e154d5 100644--- a/src/core/session/durable-finalize-runtime.test.ts+++ b/src/core/session/durable-finalize-runtime.test.ts@@ -9,9 +9,10 @@ import {import { ArtifactMutationLeaseCoordinator } from '@core/plugin/finalize/artifact-mutation-lease'import type { FinalizeArtifactOperations } from '@core/plugin/finalize/finalize-committer'import { migrate } from '@core/session/migrations'-import { makeDownloadTask, TaskKind, TaskType } from '@shared/types/task'+import { TaskKind, TaskType } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'import Database from 'better-sqlite3'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { DurableFinalizeRuntime } from './durable-finalize-runtime'describe('DurableFinalizeRuntime', () => {@@ -108,3 +109,32 @@ describe('DurableFinalizeRuntime', () => {db.close()})})++it('rejects an invalid target before acquiring leases or reading file identities', async () => {+ const db = new Database(':memory:')+ try {+ const fs = { identity: vi.fn() } as unknown as FinalizeArtifactOperations+ const quiesce = vi.fn(async () => () => {})+ const runtime = new DurableFinalizeRuntime({+ db,+ fs,+ session: { persistFinalizedArtifact: vi.fn() },+ leases: new ArtifactMutationLeaseCoordinator([{ quiesce }]),+ })+ await expect(+ runtime.commit({+ task: makeDownloadTask({ id: 'invalid', saveDir: '/save' }),+ occurrence: null,+ sourcePath: '/save/temp',+ targetPath: '/save',+ metadataOps: [],+ contributors: [],+ postDeliveries: [],+ })+ ).rejects.toThrow('descendant')+ expect(fs.identity).not.toHaveBeenCalled()+ expect(quiesce).not.toHaveBeenCalled()+ } finally {+ db.close()+ }+})diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.tsindex 54ececb3..e902906a 100644--- a/src/core/session/durable-finalize-runtime.ts+++ b/src/core/session/durable-finalize-runtime.ts@@ -1,5 +1,6 @@import { randomUUID } from 'node:crypto'import path from 'node:path'+import { getLogger } from '@core/logger'import {ArtifactIdentityError,artifactContentEquals,@@ -12,7 +13,10 @@ import {FinalizeCommitter,} from '@core/plugin/finalize/finalize-committer'import { FinalizeRecovery } from '@core/plugin/finalize/finalize-recovery'-import { freezeHookPlan } from '@core/plugin/finalize/hook-plan'+import {+ assertFinalizePaths,+ freezeHookPlan,+} from '@core/plugin/finalize/hook-plan'import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'import type { PostDeliveryAdmission } from '@core/plugin/post/delivery-types'import type { DownloadTask } from '@shared/types/task'@@ -55,6 +59,27 @@ export class DurableFinalizeRuntime {async commit(input: DurableFinalizeArtifactInput): Promise<FinalizeCommitResult> {+ // Reject invalid output plans before quiescing writers or hashing large files.+ try {+ assertFinalizePaths(+ input.task.saveDir,+ input.sourcePath,+ input.targetPath+ )+ } catch (err) {+ getLogger('finalize').warn(+ {+ taskId: input.task.id,+ phase: input.task.transitionPhase,+ saveDir: input.task.saveDir,+ sourcePath: input.sourcePath,+ targetPath: input.targetPath,+ err,+ },+ 'finalize_path_validation_failed'+ )+ throw err+ }const lease = await this.leases.acquire(input.task.id)try {// H8: identity capture is inside the mutation lease, after everydiff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex a21c4418..044ec490 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -1611,6 +1611,30 @@ describe('SessionManager', () => {fs.rmSync(tmpDir, { recursive: true, force: true })})+ it('restores a live retiring GID without counting its settled upload twice', async () => {+ const gid = 'settled-finalize-gid'+ seedAsPair(db, {+ motrixId: 'settled-finalize',+ gid,+ type: TaskType.Bt,+ status: TaskStatus.Finalizing,+ transitionPhase: TransitionPhase.Renaming,+ diskPath: '/tmp/output.motrix',+ finalPath: '/tmp/output',+ uploadedBytesBaseline: 125,+ uploadedBytes: 25,+ payload: { btFinalizeUpload: { gid, bytes: 25 } },+ })+ rpc.tellActive = vi.fn(async () => [+ makeRawStatus({ gid, uploadLength: '30' }),+ ])+ await sessionManager.restore()+ const restored = taskManager.getById('settled-finalize')+ expect(restored?.uploadedBytes).toBe(130)+ expect(restored?.uploadedBytesBaseline).toBe(125)+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ })+it('does NOT reAdd when aria2 has the gid (sqlite-persistence intact)', async () => {// This is the crucial regression: motrix.db says gid X is paused;// aria2 has gid X loaded (fork's Sqlite3SessionStore did its job).diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex ecec824c..96cf517d 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -54,6 +54,7 @@ import {parseBtFileLayout,shouldPrioritizeBtPreviewPiecesFromMetadata,} from '../task/bt-storage-layout'+import { unsettledBtUpload } from '../task/bt-upload-settlement'import { isCompletedDirectOutput } from '../task/completed-direct-task-policy'import {canMirrorAria2MetadataHeaders,@@ -1237,7 +1238,12 @@ export class SessionManager {const sizeWhenDone = Number(aria2.totalLength) || taskPart.sizeWhenDoneconst uploadedBytesBaseline = taskPart.uploadedBytesBaselineconst uploadedBytes =- uploadedBytesBaseline + Number(aria2.uploadLength || 0)+ uploadedBytesBaseline ++ unsettledBtUpload(+ pair.instances,+ aria2.gid,+ Number(aria2.uploadLength || 0)+ )const fileCount = aria2.files?.length || taskPart.fileCountlet bt = translateBtExtension(aria2)diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex fbb72e2d..f8293060 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -338,14 +338,21 @@ describe('finalizeTask HTTP/FTP branch', () => {await expect(finalizeTask('t1', deps)).rejects.toThrow('database busy')- expect(deps.recordTransition).toHaveBeenCalledExactlyOnceWith(+ expect(deps.recordTransition).toHaveBeenCalledTimes(2)+ expect(deps.recordTransition).toHaveBeenNthCalledWith(+ 1,expect.objectContaining({ nextStatus: TaskStatus.Finalizing }))- expect(deps.eventBus.emit).toHaveBeenCalledExactlyOnceWith(+ expect(deps.recordTransition).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ nextStatus: TaskStatus.Error })+ )+ expect(deps.eventBus.emit).toHaveBeenCalledTimes(2)+ expect(deps.eventBus.emit).toHaveBeenCalledWith(Events.TaskUpdated,- []+ expect.any(Array))- expect(task.status).toBe(TaskStatus.Finalizing)+ expect(task.status).toBe(TaskStatus.Error)expect(task.transitionPhase).toBe(TransitionPhase.Renaming)expect(task.diskPath).toBe('/d/foo.mp4.motrix')})@@ -2389,3 +2396,61 @@ describe('finalizeTask instance diskPath sync', () => {expect(task.instances[0].diskPath).toBe('/d/renamed.mp4')})})++describe('finalize pre-commit failure recovery', () => {+ it.each([TaskType.Bt, TaskType.Http])(+ 'publishes an error when engine cleanup fails (%s)',+ async (type) => {+ const deps = makeDeps()+ const task = makeTask({ type, instances: [makePrimaryInstance()] })+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ const error = new Error('Could not remove download result of GID#gid-1')+ vi.mocked(deps.adapter.removeDownloadResult).mockRejectedValue(error)+ await expect(finalizeTask(task.id, deps)).rejects.toBe(error)+ expect(task).toMatchObject({+ status: TaskStatus.Error,+ transitionPhase: TransitionPhase.Renaming,+ errorCode: 'DL_UNKNOWN',+ errorDetailKey: 'task.error.detail.finalizeFailed',+ })+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()+ expect(deps.adapter.addTorrent).not.toHaveBeenCalled()+ expect(deps.eventBus.emit).toHaveBeenCalledWith(+ Events.TaskUpdated,+ expect.any(Array)+ )+ }+ )++ it.each([25, 35])(+ 'settles only new upload when retrying finalize (%s)',+ async (retryUpload) => {+ const deps = makeDeps()+ const task = makeTask({+ type: TaskType.Bt,+ torrentMetaPath: '/meta',+ uploadedBytesBaseline: 100,+ instances: [+ makePrimaryInstance({+ phase: TaskInstancePhase.BtDownload,+ uploadedBytes: 25,+ }),+ ],+ })+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getUploadLength).mockResolvedValue(25)+ vi.mocked(deps.adapter.removeDownloadResult).mockRejectedValueOnce(+ new Error('engine disconnected')+ )+ await expect(finalizeTask(task.id, deps)).rejects.toThrow(+ 'engine disconnected'+ )+ expect(task.uploadedBytesBaseline).toBe(125)+ vi.mocked(deps.adapter.getUploadLength).mockResolvedValue(retryUpload)+ await finalizeTask(task.id, deps)+ expect(task.uploadedBytesBaseline).toBe(100 + retryUpload)+ expect(task.instances[0].uploadedBytes).toBe(0)+ expect(deps.fs.renameAtomic).toHaveBeenCalledTimes(1)+ }+ )+})diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex ee3a79c6..f730d724 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -3,7 +3,7 @@ import { newEngineTaskId } from '@core/lib/ids'import type { HookAuditLog } from '@core/plugin/hooks/audit-log'import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'-import { AppError, ErrorCode } from '@shared/errors'+import { AppError, DownloadErrorCode, ErrorCode } from '@shared/errors'import { Events } from '@shared/protocol/events'import type {BeforeFinalizeContextDTO,@@ -26,6 +26,7 @@ import {getBtStorageLayout,parseBtFileLayout,} from '../bt-storage-layout'+import { settleBtUpload } from '../bt-upload-settlement'import { fireAfterComplete, fireOnError } from '../hook-dispatch'import { normalizeTerminalRuntimeMetrics } from '../normalize-terminal-runtime-metrics'import type { OccurrenceDispatcher } from '../occurrences/occurrence-dispatcher'@@ -33,6 +34,7 @@ import {applyCompletedTaskAfterRename,applyTerminalStatusToTask,completeTaskAfterRename,+ pickPrimaryInstance,setTaskTransitionPhase,syncPrimaryInstanceIdentity,} from '../task-instance'@@ -207,6 +209,32 @@ async function finalizeTaskSerialized(} else {await finalizeHttp(task, deps)}+ } catch (err) {+ // The last durable snapshot, not the working candidate, decides whether+ // this is an unfinished rename. Never demote an already committed output+ // because a later notification or reseed operation failed.+ const current = deps.taskManager.getById(taskId)+ if (+ current?.transitionPhase === TransitionPhase.Renaming &&+ current.status !== TaskStatus.Error &&+ current.diskPath !== current.finalPath+ ) {+ try {+ await failFinalize(structuredClone(current), deps, {+ errorMessage: (err as Error).message,+ errorDetailKey: 'task.error.detail.finalizeFailed',+ errorDetailParams: { cause: (err as Error).message },+ hookCode: ErrorCode.TaskFinalizeFailed,+ errorCode: DownloadErrorCode.Unknown,+ })+ } catch (persistError) {+ deps.log.error(+ { taskId, err, persistError },+ 'finalize_failure_persistence_failed'+ )+ }+ }+ throw err} finally {finalizationsInFlight.delete(taskId)}@@ -480,6 +508,7 @@ async function finalizeBt(return}+ const recovering = task.transitionPhase !== TransitionPhase.Idleconst previousStatus = task.statusObject.assign(task, applyTerminalTransition(task, TaskStatus.Finalizing))setTaskTransitionPhase(task, TransitionPhase.Renaming)@@ -523,8 +552,7 @@ async function finalizeBt(// double-count. Sync it from the new baseline instead; the new gid// contributes 0 at this point.const upload = await deps.adapter.getUploadLength(task.engineTaskId)- task.uploadedBytesBaseline += upload- task.uploadedBytes = task.uploadedBytesBaseline+ settleBtUpload(task, upload, recovering)await persistTaskState(task, deps)// Snapshot unselected files BEFORE forceRemove. aria2 drops the@@ -545,8 +573,8 @@ async function finalizeBt(// Stop the active seeding task BEFORE rename + re-add. `removeDownloadResult`// alone is insufficient: it only clears tasks already in stopped/error/// removed state, so an active seeder would survive in aria2 and reappear- // as an orphan task on the next polling tick. forceRemove also releases- // file handles, making the rename safe on Windows (sharing-violation safe).+ // as an orphan task on the next polling tick. forceRemove only requests a+ // stop; result cleanup waits out that transition before the rename begins.try {await deps.adapter.forceRemoveTask(task.engineTaskId)} catch (err) {@@ -781,6 +809,8 @@ async function finalizeBtAfterRename(const previousStatus = task.statusconst reseedCandidate = structuredClone(task)reseedCandidate.engineTaskId = newGid+ const reseedInstance = pickPrimaryInstance(reseedCandidate.instances)+ if (reseedInstance) reseedInstance.uploadedBytes = 0setTaskTransitionPhase(reseedCandidate, TransitionPhase.Idle)Object.assign(reseedCandidate,@@ -925,10 +955,12 @@ async function failFinalize(errorDetailKey: stringerrorDetailParams: Record<string, string>hookCode: string+ errorCode?: DownloadErrorCode}): Promise<void> {const previousStatus = task.statusapplyTerminalStatusToTask(task, TaskStatus.Error, {+ errorCode: fail.errorCode,errorMessage: fail.errorMessage,errorDetailKey: fail.errorDetailKey,errorDetailParams: fail.errorDetailParams,diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.tsindex b4c0afd4..51ee8141 100644--- a/src/core/task/actions/re-add-task.test.ts+++ b/src/core/task/actions/re-add-task.test.ts@@ -11,6 +11,7 @@ import {TaskKind,TaskStatus,TaskType,+ TransitionPhase,} from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'@@ -1138,3 +1139,17 @@ describe('characterization: reAddTask adapter call params', () => {)})})++it('retries an interrupted finalize without re-adding its torrent', async () => {+ const task = makeBtTask({+ status: TaskStatus.Error,+ transitionPhase: TransitionPhase.Renaming,+ diskPath: '/tmp/sample.motrix',+ })+ const deps = makeDeps(task)+ const recoverFinalization = vi.fn(async () => {})+ await reAddTask(task.id, { ...deps, recoverFinalization })+ expect(recoverFinalization).toHaveBeenCalledExactlyOnceWith(task.id)+ expect(deps.adapter.addTorrent).not.toHaveBeenCalled()+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()+})diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.tsindex 39a825d0..3346c168 100644--- a/src/core/task/actions/re-add-task.ts+++ b/src/core/task/actions/re-add-task.ts@@ -5,7 +5,11 @@ import { AppError, ErrorCode } from '@shared/errors'import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'import type { EngineTaskOptions } from '@shared/types/engine-task-options'import type { DownloadTask } from '@shared/types/task'-import { TaskInstancePhase, TaskStatus } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'import {canRebuildTaskInputs,canReseed,@@ -37,6 +41,7 @@ import type { TorrentMetaStore } from '../torrent-meta-store'import { commitTaskUpdate, getTaskOrWarn, type TaskActionDeps } from './shared'export interface ReAddTaskDeps extends TaskActionDeps {+ recoverFinalization?: (taskId: string) => Promise<void>runTaskMutation: NonNullable<TaskActionDeps['runTaskMutation']>persistTask: NonNullable<TaskActionDeps['persistTask']>torrentMetaStore: TorrentMetaStore@@ -444,6 +449,21 @@ export async function reAddTask(taskId: string,deps: ReAddTaskDeps): Promise<void> {+ const task = deps.taskManager.getById(taskId)+ if (+ task &&+ (task.transitionPhase === TransitionPhase.Renaming ||+ task.transitionPhase === TransitionPhase.Reseeding)+ ) {+ if (!deps.recoverFinalization) {+ throw new AppError(+ ErrorCode.TaskNotRetryable,+ 'Finalize recovery is unavailable'+ )+ }+ await deps.recoverFinalization(taskId)+ return+ }const run = (getProxyOptions: DirectResourceProxyOptionsProvider,assertProxyCurrent?: () => voiddiff --git a/src/core/task/bt-upload-settlement.ts b/src/core/task/bt-upload-settlement.tsnew file mode 100644index 00000000..3230cb60--- /dev/null+++ b/src/core/task/bt-upload-settlement.ts@@ -0,0 +1,53 @@+import type { DownloadTask, TaskInstance } from '@shared/types/task'+import { pickPrimaryInstance } from './task-instance'++const KEY = 'btFinalizeUpload'++function accountedUpload(+ instances: readonly TaskInstance[],+ gid: string+): number | null {+ for (const instance of instances) {+ const value = instance.payload[KEY] as+ | { gid?: unknown; bytes?: unknown }+ | undefined+ if (+ value?.gid === gid &&+ typeof value.bytes === 'number' &&+ Number.isFinite(value.bytes) &&+ value.bytes >= 0+ )+ return value.bytes+ }+ return null+}++/** Only the unaccounted part of the current GID belongs above the baseline. */+export function unsettledBtUpload(+ instances: readonly TaskInstance[],+ gid: string,+ uploadedBytes: number+): number {+ return Math.max(0, uploadedBytes - (accountedUpload(instances, gid) ?? 0))+}++/** Persist this marker together with the task baseline before retiring its GID. */+export function settleBtUpload(+ task: DownloadTask,+ upload: number,+ recovering: boolean+): void {+ const primary = pickPrimaryInstance(task.instances)+ const accounted = accountedUpload(task.instances, task.engineTaskId)+ // Old interrupted finalizes already saved their baseline without a marker.+ // Preserve that total instead of guessing and crediting the same GID twice.+ const previous = accounted ?? (recovering && primary ? upload : 0)+ task.uploadedBytesBaseline += Math.max(0, upload - previous)+ task.uploadedBytes = task.uploadedBytesBaseline+ if (primary) {+ primary.payload = {+ ...primary.payload,+ [KEY]: { gid: task.engineTaskId, bytes: Math.max(previous, upload) },+ }+ }+}diff --git a/src/core/task/merge-engine-task.test.ts b/src/core/task/merge-engine-task.test.tsindex 940e99c5..14f7cf10 100644--- a/src/core/task/merge-engine-task.test.ts+++ b/src/core/task/merge-engine-task.test.ts@@ -34,6 +34,28 @@ function instance(status: TaskStatus, index = 0): TaskInstance {}describe('mergeEngineTask', () => {+ it.each([+ ['gid1', 25, 125],+ ['gid1', 30, 130],+ ['reseed-gid', 10, 135],+ ])(+ 'merges settled upload for %s without double counting',+ (gid, upload, expected) => {+ const primary = instance(TaskStatus.Error)+ primary.payload.btFinalizeUpload = { gid: 'gid1', bytes: 25 }+ const existing = baseTask({+ uploadedBytesBaseline: 125,+ transitionPhase: TransitionPhase.Renaming,+ instances: [primary],+ })+ const merged = mergeEngineTask(+ existing,+ baseTask({ engineTaskId: gid, uploadedBytes: upload })+ )+ expect(merged.uploadedBytes).toBe(expected)+ }+ )+it.each([TaskStatus.Queued, TaskStatus.Downloading].flatMap((from) =>[TaskStatus.Error, TaskStatus.Completed].flatMap((to) =>diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.tsindex 4b08e721..55234d4f 100644--- a/src/core/task/merge-engine-task.ts+++ b/src/core/task/merge-engine-task.ts@@ -1,6 +1,7 @@import type { DownloadTask } from '@shared/types/task'import { TaskStatus, TransitionPhase } from '@shared/types/task'import { applyTerminalTransition } from './apply-terminal-transition'+import { unsettledBtUpload } from './bt-upload-settlement'import { isCompletedDirectOutput } from './completed-direct-task-policy'import { nonZeroMerge } from './non-zero-merge'import { syncTerminalInstanceStatus } from './task-instance'@@ -40,7 +41,12 @@ export function mergeEngineTask(// The persistent baseline lives on `existing` and is bumped only at// gid swap points (finalize reseed, restart reAdd) — never here.const uploadedBytes =- existing.uploadedBytesBaseline + engineTask.uploadedBytes+ existing.uploadedBytesBaseline ++ unsettledBtUpload(+ existing.instances,+ engineTask.engineTaskId,+ engineTask.uploadedBytes+ )// A non-idle transition phase means the application owns the lifecycle// state until its filesystem + persistence transaction commits. aria2 can// report Completed while HTTP finalize is still renaming `.motrix`, or adiff --git a/src/core/task/task-recovery-service.test.ts b/src/core/task/task-recovery-service.test.tsindex 7e71e69d..dbcb7619 100644--- a/src/core/task/task-recovery-service.test.ts+++ b/src/core/task/task-recovery-service.test.ts@@ -943,3 +943,65 @@ describe('TaskRecoveryService plugin-hook chain (Plan C / T15)', () => {expect(task.status).toBe(TaskStatus.Error)})})++describe('targeted finalize recovery', () => {+ it('recovers only the requested task', async () => {+ const first = makeTask({+ id: 'first',+ transitionPhase: TransitionPhase.Renaming,+ diskPath: '/d/first.part',+ finalPath: '/d/first',+ })+ const other = makeTask({+ id: 'other',+ transitionPhase: TransitionPhase.Renaming,+ diskPath: '/d/other.part',+ finalPath: '/d/other',+ })+ const deps = makeDeps({+ taskManager: {+ getAll: () => [first, other],+ persist: vi.fn(async () => {}),+ },+ fs: makeFs(new Set(['/d/first.part', '/d/other.part'])),+ })+ const report = await new TaskRecoveryServiceImpl(deps).recoverTaskById(+ 'first'+ )+ expect(report.totalScanned).toBe(1)+ expect(deps.finalizeTask).toHaveBeenCalledExactlyOnceWith('first')+ })++ it('preserves the rename intent when output paths cannot be accessed', async () => {+ let task = makeTask({+ status: TaskStatus.Finalizing,+ transitionPhase: TransitionPhase.Renaming,+ })+ const deps = makeDeps({+ taskManager: {+ getAll: () => [task],+ set: (_id, next) => {+ task = next+ },+ persist: vi.fn(async () => {}),+ },+ fs: {+ ...makeFs(new Set()),+ pathExists: vi.fn(async () => {+ throw Object.assign(new Error('EACCES: permission denied'), {+ code: 'EACCES',+ })+ }),+ },+ })+ const report = await new TaskRecoveryServiceImpl(deps).recoverOnStartup()+ expect(task).toMatchObject({+ status: TaskStatus.Error,+ transitionPhase: TransitionPhase.Renaming,+ errorDetailKey: 'task.error.detail.recoveryFailed',+ })+ expect(report.errors[0].issue).toContain('EACCES')+ expect(deps.finalizeTask).not.toHaveBeenCalled()+ expect(deps.fs.removePathRecursive).not.toHaveBeenCalled()+ })+})diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.tsindex 3ccd9f2f..1a809770 100644--- a/src/core/task/task-recovery-service.ts+++ b/src/core/task/task-recovery-service.ts@@ -1,9 +1,8 @@-import { rename, rm } from 'node:fs/promises'+import { access, rename, rm } from 'node:fs/promises'import type { EngineAdapter } from '@core/engine/engine-adapter'-import { pathExists } from '@core/fs/path-exists'import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { MotrixDatabase } from '@core/session/motrix-database'-import { ErrorCode } from '@shared/errors'+import { DownloadErrorCode, ErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'import { TaskStatus, type TaskType, TransitionPhase } from '@shared/types/task'import { isMediaKind, isTorrentLikeType } from '@shared/types/task-actions'@@ -102,8 +101,15 @@ export interface RecoveryFs {}export const defaultRecoveryFs: RecoveryFs = {- pathExists(p: string): Promise<boolean> {- return pathExists(p)+ async pathExists(p: string): Promise<boolean> {+ try {+ await access(p)+ return true+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code+ if (code === 'ENOENT' || code === 'ENOTDIR') return false+ throw error+ }},renameAtomic(src: string, dst: string): Promise<void> {return rename(src, dst)@@ -173,6 +179,14 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {constructor(private readonly deps: RecoveryDeps) {}async recoverOnStartup(): Promise<RecoveryReport> {+ return this.recover()+ }++ async recoverTaskById(taskId: string): Promise<RecoveryReport> {+ return this.recover(taskId)+ }++ private async recover(taskId?: string): Promise<RecoveryReport> {const start = Date.now()const report: RecoveryReport = {totalScanned: 0,@@ -190,8 +204,9 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {// them would sit on the awaited startup path.const inFlightPublished = publishedTasks.filter((t) =>- t.transitionPhase !== TransitionPhase.Idle ||- t.status === TaskStatus.Finalizing+ (taskId === undefined || t.id === taskId) &&+ (t.transitionPhase !== TransitionPhase.Idle ||+ t.status === TaskStatus.Finalizing))const inFlight = this.deps.taskManager.set? inFlightPublished.map((task) => structuredClone(task))@@ -231,15 +246,26 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {}for (const task of inFlight) {- try {- const recover = () =>- this.recoverTask(- task,+ const recover = async () => {+ const current = this.deps.taskManager+ .getAll()+ .find((t) => t.id === task.id)+ if (!current) return+ try {+ await this.recoverTask(+ this.deps.taskManager.set ? structuredClone(current) : current,byInfoHash,ownerByGid,taskIdsByInfoHash,report)+ } catch (error) {+ // Publish failure while still holding the same task mutation lock.+ await this.recordRecoveryFailure(task.id, error)+ throw error+ }+ }+ try {await (this.deps.runTaskMutation? this.deps.runTaskMutation([task.id], recover): recover())@@ -266,6 +292,39 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {return report}+ private async recordRecoveryFailure(+ taskId: string,+ e: unknown+ ): Promise<void> {+ const current = this.deps.taskManager.getAll().find((t) => t.id === taskId)+ if (+ current &&+ current.transitionPhase !== TransitionPhase.Idle &&+ current.status !== TaskStatus.Error+ ) {+ const failed = structuredClone(current)+ const previousStatus = failed.status+ applyTerminalStatusToTask(failed, TaskStatus.Error, {+ errorCode: DownloadErrorCode.Unknown,+ errorMessage: (e as Error).message,+ errorDetailKey: 'task.error.detail.recoveryFailed',+ errorDetailParams: { cause: (e as Error).message },+ })+ try {+ await this.persistRecoveredTransition(failed, previousStatus)+ } catch (persistError) {+ this.deps.log.error(+ { taskId, err: e, persistError },+ 'recovery_failure_persistence_failed'+ )+ }+ }+ this.deps.log.error(+ { taskId, err: e, phase: current?.transitionPhase },+ 'task_recovery_failed'+ )+ }+private async recoverTask(task: DownloadTask,byInfoHash: Map<string, Set<string>>,diff --git a/src/core/task/task-row-to-download-task.test.ts b/src/core/task/task-row-to-download-task.test.tsindex 028af18f..1056b5c1 100644--- a/src/core/task/task-row-to-download-task.test.ts+++ b/src/core/task/task-row-to-download-task.test.ts@@ -69,6 +69,24 @@ function makeInstance(phase: TaskInstancePhase): TaskInstanceRow {}describe('taskRowToDownloadTask', () => {+ it.each([+ ['g1', 25, 125],+ ['reseed-gid', 10, 135],+ ])(+ 'restores settled upload for %s without double counting',+ (gid, upload, expected) => {+ const primary = makeInstance(TaskInstancePhase.BtDownload)+ primary.gid = gid+ primary.uploadedBytes = upload+ primary.payload.btFinalizeUpload = { gid: 'g1', bytes: 25 }+ const restored = taskRowToDownloadTask(+ makeTaskRow({ uploadedBytesBaseline: 125 }),+ [primary]+ )+ expect(restored.uploadedBytes).toBe(expected)+ }+ )+it('uses the canonical persisted BT type', () => {const task = taskRowToDownloadTask(makeTaskRow(), [makeInstance(TaskInstancePhase.BtDownload),diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.tsindex 6c903c55..278adc7e 100644--- a/src/core/task/task-row-to-download-task.ts+++ b/src/core/task/task-row-to-download-task.ts@@ -6,6 +6,7 @@ import {TransitionPhase,} from '@shared/types/task'import { isTorrentLikeType } from '@shared/types/task-actions'+import { unsettledBtUpload } from './bt-upload-settlement'import { restoreTaskSaveDirectory } from './task-save-directory'/** Build a generic DownloadTask domain object from canonical TaskRow data.@@ -26,7 +27,12 @@ export function taskRowToDownloadTask(? task.downloadedBytes / task.totalBytes: 0const uploadedBytes =- task.uploadedBytesBaseline + (primary?.uploadedBytes ?? 0)+ task.uploadedBytesBaseline ++ unsettledBtUpload(+ instances,+ primary?.gid ?? '',+ primary?.uploadedBytes ?? 0+ )const bt = isTorrentLikeType(task.taskType)? makeDefaultBtExtension({ratio: task.totalBytes > 0 ? uploadedBytes / task.totalBytes : 0,diff --git a/src/main/index.ts b/src/main/index.tsindex bce67618..be710117 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -440,6 +440,7 @@ let notificationCenter: NotificationCenter// Constructed and registered in startEngineAndRestore; its task retry is// late-bound by buildCommandHandlers to the ReAddTasks deps bundle.let dnsFallbackConsumer: DnsFallbackConsumer | undefined+let recoveryService: TaskRecoveryServiceImpl | undefinedlet dnsFallbackRetry: ((taskId: string) => Promise<unknown>) | undefinedlet trayHandle: ReturnType<typeof setupTray> | null = nulllet natManager: NatManager | null = null@@ -1266,7 +1267,7 @@ async function startEngineAndRestore(// renderer observes a self-healed state as soon as updates start// flowing. See design spec §6.6.const finalizeDepsFactory = () => buildFinalizeDeps(adapter)- const recoveryService = new TaskRecoveryServiceImpl({+ recoveryService = new TaskRecoveryServiceImpl({taskManager: {getAll: () => taskManager.getAll(),set: (id: string, task: DownloadTask) => taskManager.set(id, task),@@ -2560,6 +2561,15 @@ async function initializeMainProcess(): Promise<void> {bindTaskRetry: (fn) => {dnsFallbackRetry = fn},+ recoverFinalization: async (taskId) => {+ if (!recoveryService) throw new Error('Task recovery is not ready')+ try {+ const report = await recoveryService.recoverTaskById(taskId)+ if (report.errors.length > 0) throw new Error(report.errors[0].issue)+ } finally {+ publishTaskUpdateNow()+ }+ },sessionManager,settingsManager,protocolManager,diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 80661539..82c402ef 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -9,7 +9,13 @@ import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import type { AppImageIntegrationView } from '@shared/types/appimage-integration'import { CliPackageManager } from '@shared/types/cli-tool'-import { TaskInstancePhase, TaskStatus, TaskType } from '@shared/types/task'+import {+ TaskInstancePhase,+ TaskStatus,+ TaskType,+ TransitionPhase,+} from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { afterEach, describe, expect, it, vi } from 'vitest'import { MainProcessWorkCoordinator } from '../main-process-work-coordinator'@@ -2391,3 +2397,25 @@ describe('Commands.RevertBuiltinToBundled', () => {expect(result).toMatchObject({ ok: true, restartRequired: false })})})++describe('main finalize retry wiring', () => {+ it.each([Commands.ReAddTask, Commands.RetryTasks])(+ 'routes %s to recovery for an interrupted finalize',+ async (command) => {+ const ctx = fakeCtx() as unknown as CommandContext+ const task = makeDownloadTask({+ id: 'interrupted-finalize',+ type: TaskType.Bt,+ status: TaskStatus.Error,+ transitionPhase: TransitionPhase.Renaming,+ })+ vi.spyOn(ctx.taskManager, 'getById').mockReturnValue(task)+ const recoverFinalization = vi.fn().mockResolvedValue(undefined)+ const handlers = buildCommandHandlers({ ...ctx, recoverFinalization })+ await handlers[command]?.(+ command === Commands.ReAddTask ? task.id : [task.id]+ )+ expect(recoverFinalization).toHaveBeenCalledExactlyOnceWith(task.id)+ }+ )+})diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 477073cb..4ca95b9a 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -151,6 +151,7 @@ export interface CommandContext {* paths cannot drift. Called synchronously during handler construction.*/bindTaskRetry?: (fn: (taskId: string) => Promise<unknown>) => void+ recoverFinalization?: (taskId: string) => Promise<void>sessionManager: SessionManagersettingsManager: SettingsManagerprotocolManager: ReturnType<typeof createProtocolManager>@@ -396,6 +397,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {publishTaskUpdateNow,}const reAddDeps = {+ recoverFinalization: ctx.recoverFinalization,taskManager,adapter,eventBus,diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.test.ts b/src/renderer/routes/downloads/inspector/use-task-actions.test.tsindex df6f0343..7b87e8a5 100644--- a/src/renderer/routes/downloads/inspector/use-task-actions.test.ts+++ b/src/renderer/routes/downloads/inspector/use-task-actions.test.ts@@ -169,6 +169,25 @@ describe('useTaskActions', () => {expect(openAddTaskDialog).toHaveBeenCalled()})+ it.each([false, true])(+ 'retries finalization directly with alt=%s',+ async (alt) => {+ const task = makeTask({+ id: 'finalize-failed',+ status: TaskStatus.Error,+ transitionPhase: TransitionPhase.Renaming,+ })+ const { result } = renderHook(() => useTaskActions([task]))+ expect(result.current.retryCount).toBe(1)+ await result.current.onRetry({ alt })+ expect(transport.invoke).toHaveBeenCalledExactlyOnceWith(+ Commands.RetryTasks,+ [task.id]+ )+ expect(openAddTaskDialog).not.toHaveBeenCalled()+ }+ )+it('onRetry({ alt: true }) on multi falls back to generic RetryTasks', async () => {const tasks = [makeRetryableErrorTask({ id: 'a' }),diff --git a/src/server/index.ts b/src/server/index.tsindex c44bde8e..0ceea2c7 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1041,6 +1041,7 @@ async function main() {// its latch; registered on the occurrence dispatcher further down with// the other consumers. The retry fn is late-bound by// buildServerCommandHandlers to the ReAddTasks deps bundle.+ let recoveryService: TaskRecoveryServiceImpl | undefinedlet dnsFallbackRetry: ((taskId: string) => Promise<unknown>) | undefinedconst dnsFallbackConsumer = createDnsFallbackConsumer({getDnsMode: () => settingsManager.get().engine.dnsMode,@@ -1090,6 +1091,15 @@ async function main() {bindTaskRetry: (fn) => {dnsFallbackRetry = fn},+ recoverFinalization: async (taskId) => {+ if (!recoveryService) throw new Error('Task recovery is not ready')+ try {+ const report = await recoveryService.recoverTaskById(taskId)+ if (report.errors.length > 0) throw new Error(report.errors[0].issue)+ } finally {+ publishTaskUpdateNow()+ }+ },rpcClient,adapter,trackerManager,@@ -1515,7 +1525,7 @@ async function main() {// Startup recovery: replay intent markers before polling/events// open so the renderer observes a self-healed state. See design// spec §6.6.- const recoveryService = new TaskRecoveryServiceImpl({+ recoveryService = new TaskRecoveryServiceImpl({taskManager: {getAll: () => taskManager.getAll(),set: (id: string, task: DownloadTask) => taskManager.set(id, task),diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex 4e4cfd76..9166183d 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -28,7 +28,9 @@ import {TaskKind,TaskStatus,TaskType,+ TransitionPhase,} from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ServerPluginInstallService } from '../plugin/install-service'import type { ServerCommandContext } from './commands'@@ -1413,3 +1415,28 @@ describe('buildServerCommandHandlers — notification center', () => {expect(notificationCenter.list()).toHaveLength(0)})})++describe('server finalize retry wiring', () => {+ it.each([Commands.ReAddTask, Commands.RetryTasks])(+ 'routes %s to recovery for an interrupted finalize',+ async (command) => {+ const ctx = makeFakeCtx() as unknown as ServerCommandContext+ const task = makeDownloadTask({+ id: 'interrupted-finalize',+ type: TaskType.Bt,+ status: TaskStatus.Error,+ transitionPhase: TransitionPhase.Renaming,+ })+ vi.spyOn(ctx.taskManager, 'getById').mockReturnValue(task)+ const recoverFinalization = vi.fn().mockResolvedValue(undefined)+ const handlers = buildServerCommandHandlers({+ ...ctx,+ recoverFinalization,+ })+ await handlers[command]?.(+ command === Commands.ReAddTask ? task.id : [task.id]+ )+ expect(recoverFinalization).toHaveBeenCalledExactlyOnceWith(task.id)+ }+ )+})diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex f7891a82..cc06bad5 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -98,6 +98,7 @@ export interface ServerCommandContext {* paths cannot drift. Called synchronously during handler construction.*/bindTaskRetry?: (fn: (taskId: string) => Promise<unknown>) => void+ recoverFinalization?: (taskId: string) => Promise<void>rpcClient: Aria2RpcClientadapter: EngineAdaptertrackerManager: TrackerManager@@ -287,6 +288,7 @@ export function buildServerCommandHandlers(publishTaskUpdateNow,}const reAddDeps = {+ recoverFinalization: ctx.recoverFinalization,taskManager,adapter,eventBus,diff --git a/src/shared/errors.ts b/src/shared/errors.tsindex 4ed4d55c..936d1a57 100644--- a/src/shared/errors.ts+++ b/src/shared/errors.ts@@ -60,6 +60,7 @@ export enum ErrorCode {// Incomplete-suffix featureTaskCreateDedupExhausted = 'TASK_CREATE_DEDUP_EXHAUSTED',TaskCreateTorrentMetaFailed = 'TASK_CREATE_TORRENT_META_FAILED',+ TaskFinalizeFailed = 'TASK_FINALIZE_FAILED',TaskFinalizeRenameFailed = 'TASK_FINALIZE_RENAME_FAILED',TaskFinalizeReseedFailed = 'TASK_FINALIZE_RESEED_FAILED',TaskFinalizeMetaMissing = 'TASK_FINALIZE_META_MISSING',diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex c43ff525..683f321f 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -893,6 +893,8 @@},"error": {"detail": {+ "finalizeFailed": "Could not finish the download: {{cause}}",+ "recoveryFailed": "Could not recover the download: {{cause}}","recoveryOutputConflict": "Both the temporary and final files exist; both were preserved for manual review","filesMissing": "Files are missing after the app restarted","renameFileFailed": "Failed to rename the file: {{cause}}",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 97fdf95a..4700ee7d 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -880,6 +880,8 @@},"error": {"detail": {+ "finalizeFailed": "无法完成下载收尾:{{cause}}",+ "recoveryFailed": "无法恢复下载:{{cause}}","recoveryOutputConflict": "临时文件和最终文件同时存在,已保留两者以供人工检查","filesMissing": "应用重启后文件缺失","renameFileFailed": "重命名文件失败:{{cause}}",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 5833cce8..b5916cf2 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -880,6 +880,8 @@},"error": {"detail": {+ "finalizeFailed": "無法完成下載收尾:{{cause}}",+ "recoveryFailed": "無法恢復下載:{{cause}}","recoveryOutputConflict": "暫存檔與最終檔案皆存在,兩者均已保留以供手動檢查","filesMissing": "應用程式重新啟動後找不到檔案","renameFileFailed": "無法重新命名檔案:{{cause}}",diff --git a/src/shared/types/task-actions.test.ts b/src/shared/types/task-actions.test.tsindex 9eb9e9c3..3f90a440 100644--- a/src/shared/types/task-actions.test.ts+++ b/src/shared/types/task-actions.test.ts@@ -501,6 +501,29 @@ describe('canAttemptRetry', () => {expect(canAttemptRetry(task)).toBe(expected)})+ it.each([TransitionPhase.Renaming, TransitionPhase.Reseeding])(+ 'offers recovery for %s without replayable engine inputs',+ (transitionPhase) => {+ for (const [kind, type] of [+ [TaskKind.Direct, TaskType.Http],+ [TaskKind.Bt, TaskType.Bt],+ [TaskKind.Mux, TaskType.Http],+ ] as const) {+ const task = makeTask({+ kind,+ type,+ status: TaskStatus.Error,+ transitionPhase,+ torrentMetaPath: null,+ instances: [],+ })+ expect(canRebuildTaskInputs(task)).toBe(false)+ expect(getTaskRetryKind(task)).toBe('finalize-recovery')+ expect(canAttemptRetry(task)).toBe(true)+ }+ }+ )+it('offers a distinct retry for failed magnet metadata without a sidecar', () => {const task = makeTask({kind: TaskKind.Bt,diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex 393654a6..c2644e29 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -5,6 +5,7 @@ import {TaskKind,TaskStatus,TaskType,+ TransitionPhase,} from './task'/** Coordinator-managed media task (Mux/Hls) — has no single aria2 handle. */@@ -156,7 +157,11 @@ export function canRetryMagnetMetadata(t: DownloadTask): boolean {)}-export type TaskRetryKind = 'torrent-readd' | 'direct-readd' | 'magnet-metadata'+export type TaskRetryKind =+ | 'torrent-readd'+ | 'direct-readd'+ | 'magnet-metadata'+ | 'finalize-recovery'const NON_RETRYABLE_DIRECT_RECOVERY_ERRORS = new Set(['task.recovery.startup.resumeCheckpointMissing',@@ -170,6 +175,14 @@ const NON_RETRYABLE_DIRECT_RECOVERY_ERRORS = new Set([/** Resolve the concrete replay operation behind the generic Retry UI. */export function getTaskRetryKind(t: DownloadTask): TaskRetryKind | null {if (!canRetry(t)) return null+ // Completed bytes need a filesystem recovery, so original download+ // credentials or torrent metadata are not prerequisites for Retry.+ if (+ t.status === TaskStatus.Error &&+ (t.transitionPhase === TransitionPhase.Renaming ||+ t.transitionPhase === TransitionPhase.Reseeding)+ )+ return 'finalize-recovery'if (canRebuildTaskInputs(t)) {if (isTorrentLike(t)) return 'torrent-readd'// Removed direct tasks are user-retired occurrences. Only an Error is an@@ -193,9 +206,8 @@ export function getTaskRetryKind(t: DownloadTask): TaskRetryKind | null {return null}-/** A retry the UI should actually offer: the task is in a retryable status- * AND its engine dispatch can be rebuilt from the persisted record. This- * includes pre-sidecar magnet metadata retries as a distinct operation. */+/** A retry the UI should offer: its finalization can be recovered or its+ * engine dispatch can be rebuilt from the persisted record. */export function canAttemptRetry(t: DownloadTask): boolean {return getTaskRetryKind(t) !== null}