A full-featured download manager.
fix(task): repair durable finalize and avoid copies (#2056)
Dr_rOot2bb0f44bad37
diff --git a/src/core/plugin/finalize/finalize-committer.test.ts b/src/core/plugin/finalize/finalize-committer.test.tsindex e9da4a06..b634cd9b 100644--- a/src/core/plugin/finalize/finalize-committer.test.ts+++ b/src/core/plugin/finalize/finalize-committer.test.ts@@ -50,12 +50,19 @@ function makePlan(replacement = false): HookPlan {class FakeFilesystem implements FinalizeArtifactOperations {readonly artifacts = new Map<string, ArtifactIdentity>()readonly actions: string[] = []+ readonly identityReads = new Map<string, number>()++ constructor(private readonly sameDevice = true) {}async identity(artifactPath: string): Promise<ArtifactIdentity | null> {+ this.identityReads.set(+ artifactPath,+ (this.identityReads.get(artifactPath) ?? 0) + 1+ )return this.artifacts.get(artifactPath) ?? null}async sameFilesystem(): Promise<boolean> {- return true+ return this.sameDevice}async materializePrivate(sourcePath: string,@@ -135,6 +142,52 @@ function makeCommitter(}describe('FinalizeCommitter', () => {+ it('moves an ordinary same-filesystem source without copying it', async () => {+ const fs = new FakeFilesystem()+ const plan = makePlan()+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ const { repository, phases } = makeRepository()++ await makeCommitter(fs, repository).commit(plan)++ expect(fs.artifacts.has(plan.sourcePath)).toBe(false)+ expect(fs.artifacts.get(plan.targetPath)).toBe(sourceIdentity)+ expect(fs.actions).toContain(`move:${plan.sourcePath}->${plan.targetPath}`)+ expect(fs.actions.some((action) => action.startsWith('copy:'))).toBe(false)+ expect(fs.identityReads.get(plan.sourcePath)).toBe(1)+ expect(fs.identityReads.get(plan.targetPath)).toBe(1)+ expect(phases).toEqual([+ 'prepared',+ 'target_installed',+ 'db_committed',+ 'cleaned',+ ])+ })++ it('falls back to verified copy publication across filesystems', async () => {+ const fs = new FakeFilesystem(false)+ const plan = makePlan()+ fs.artifacts.set(plan.sourcePath, sourceIdentity)+ const { repository, phases } = makeRepository()++ await makeCommitter(fs, repository).commit(plan)++ expect(fs.actions).toContain(+ `copy:${plan.sourcePath}->/save/.motrix-private-plan-1`+ )+ expect(fs.artifacts.has(plan.sourcePath)).toBe(false)+ expect(fs.artifacts.get(plan.targetPath)).toMatchObject({+ sha256: sourceIdentity.sha256,+ })+ expect(phases).toEqual([+ 'prepared',+ 'target_staged',+ 'target_installed',+ 'db_committed',+ 'cleaned',+ ])+ })+it('installs a replacement and never renames the original over it', async () => {const fs = new FakeFilesystem()const plan = makePlan(true)@@ -187,6 +240,8 @@ describe('FinalizeCommitter', () => {)expect(fs.artifacts.has(plan.targetPath)).toBe(false)expect(fs.artifacts.get(plan.sourcePath)).toBe(sourceIdentity)+ expect(fs.actions).toContain(`move:${plan.targetPath}->${plan.sourcePath}`)+ expect(fs.actions.some((action) => action.startsWith('copy:'))).toBe(false)})it('quarantines an identity mismatch without deleting unknown bytes', async () => {diff --git a/src/core/plugin/finalize/finalize-committer.ts b/src/core/plugin/finalize/finalize-committer.tsindex d627634b..65962ad6 100644--- a/src/core/plugin/finalize/finalize-committer.ts+++ b/src/core/plugin/finalize/finalize-committer.ts@@ -19,6 +19,8 @@ export interface FinalizeJournalRecord {journalId: stringphase: FinalizeJournalPhaseplan: HookPlan+ /** Missing on journals created before the move fast path; treat as copy. */+ publicationMode?: 'copy' | 'move'privateTargetPath?: stringprivateTargetIdentity?: ArtifactIdentitytargetIdentity?: ArtifactIdentity@@ -131,6 +133,7 @@ export class FinalizeCommitter {journalId: plan.planId,phase: 'prepared',plan,+ publicationMode: 'copy',}try {await this.requireExactIdentity(@@ -145,6 +148,7 @@ export class FinalizeCommitter {record)}+ record.publicationMode = await this.selectPublicationMode(plan)await this.options.repository.prepare(record)return await this.commitPrepared(record, lease)} catch (error) {@@ -164,6 +168,7 @@ export class FinalizeCommitter {const selectedPath = plan.replacement?.stagedPath ?? plan.sourcePathconst selectedIdentity = plan.replacement?.identity ?? plan.sourceIdentityconst samePath = finalizePathsEquivalent(plan.sourcePath, plan.targetPath)+ const movesSource = record.publicationMode === 'move'if (samePath && !plan.replacement) {await this.requireExactIdentity(@@ -172,6 +177,15 @@ export class FinalizeCommitter {record)await this.options.fs.makeDurable(plan.sourcePath)+ } else if (movesSource) {+ // moveNoReplace validates the expected source identity while holding the+ // artifact and both roots. Avoid hashing large artifacts once more here.+ await this.options.fs.moveNoReplace(+ plan.sourcePath,+ plan.sourceIdentity,+ plan.targetPath+ )+ await this.options.fs.makeDurable(plan.targetPath)} else {if (samePath) {record.rollbackPath = this.options.rollbackPathFor(plan)@@ -227,13 +241,18 @@ export class FinalizeCommitter {await this.options.fs.makeDurable(plan.targetPath)}- const targetIdentity = await this.requireExactIdentity(- plan.targetPath,- samePath && !plan.replacement- ? plan.sourceIdentity- : (record.privateTargetIdentity as ArtifactIdentity),- record- )+ // A same-filesystem rename preserves the platform file identity and the+ // move operation already verifies the installed target. Persist that+ // identity directly, then retain the final pre-DB verification below.+ const targetIdentity = movesSource+ ? plan.sourceIdentity+ : await this.requireExactIdentity(+ plan.targetPath,+ samePath && !plan.replacement+ ? plan.sourceIdentity+ : (record.privateTargetIdentity as ArtifactIdentity),+ record+ )record.targetIdentity = targetIdentityawait this.options.repository.advance(record.journalId,@@ -249,7 +268,7 @@ export class FinalizeCommitter {record.phase = 'db_committed'let cleanupPending = falsetry {- if (!samePath) {+ if (!samePath && !movesSource) {await this.requireExactIdentity(plan.sourcePath,plan.sourceIdentity,@@ -303,19 +322,31 @@ export class FinalizeCommitter {): Promise<void> {if (record.phase === 'db_committed' || record.phase === 'cleaned') returntry {+ const movesSource = record.publicationMode === 'move'const installedIdentity =- record.targetIdentity ?? record.privateTargetIdentity+ record.targetIdentity ??+ record.privateTargetIdentity ??+ (movesSource ? record.plan.sourceIdentity : undefined)const target = await this.options.fs.identity(record.plan.targetPath)if (target &&installedIdentity &&this.options.exactIdentity(target, installedIdentity)) {- await this.removeTracked(- record,- record.plan.targetPath,- installedIdentity- )+ if (movesSource) {+ await this.options.fs.moveNoReplace(+ record.plan.targetPath,+ installedIdentity,+ record.plan.sourcePath+ )+ await this.options.fs.makeDurable(record.plan.sourcePath)+ } else {+ await this.removeTracked(+ record,+ record.plan.targetPath,+ installedIdentity+ )+ }} else if (target) {await this.quarantine(record, 'compensation target identity mismatch')}@@ -370,6 +401,23 @@ export class FinalizeCommitter {}}+ private async selectPublicationMode(+ plan: HookPlan+ ): Promise<'copy' | 'move'> {+ if (+ plan.replacement ||+ finalizePathsEquivalent(plan.sourcePath, plan.targetPath)+ ) {+ return 'copy'+ }+ return (await this.options.fs.sameFilesystem(+ plan.sourcePath,+ plan.targetPath+ ))+ ? 'move'+ : 'copy'+ }+private async requireExactIdentity(artifactPath: string,expected: ArtifactIdentity,diff --git a/src/core/plugin/finalize/finalize-recovery.test.ts b/src/core/plugin/finalize/finalize-recovery.test.tsindex dd007925..9e9620a6 100644--- a/src/core/plugin/finalize/finalize-recovery.test.ts+++ b/src/core/plugin/finalize/finalize-recovery.test.ts@@ -181,6 +181,61 @@ describe('FinalizeRecovery', () => {expect(state.phases).toEqual(['cleaned'])})+ it('cleans a prepared move journal when publication never started', async () => {+ const prepared = record('prepared')+ prepared.publicationMode = 'move'+ prepared.targetIdentity = undefined+ const state = fixture({ '/save/source': sourceIdentity })++ await state.recovery.recover(prepared)++ expect(state.artifacts.get('/save/source')).toBe(sourceIdentity)+ expect(state.artifacts.has('/save/target')).toBe(false)+ expect(state.phases).toEqual(['cleaned'])+ })++ it('restores a move published before target_installed was journaled', async () => {+ const prepared = record('prepared')+ prepared.publicationMode = 'move'+ prepared.targetIdentity = undefined+ const state = fixture({ '/save/target': sourceIdentity })++ await state.recovery.recover(prepared)++ expect(state.artifacts.get('/save/source')).toBe(sourceIdentity)+ expect(state.artifacts.has('/save/target')).toBe(false)+ expect(state.phases).toEqual(['cleaned'])+ })++ it('rolls an uncommitted move publication back to its source name', async () => {+ const installed = record('target_installed')+ installed.publicationMode = 'move'+ installed.targetIdentity = sourceIdentity+ const state = fixture(+ { '/save/target': sourceIdentity },+ { rollForwardTargetInstalled: false }+ )++ await state.recovery.recover(installed)++ expect(state.artifacts.get('/save/source')).toBe(sourceIdentity)+ expect(state.artifacts.has('/save/target')).toBe(false)+ expect(state.phases).toEqual(['cleaned'])+ })++ it('keeps a committed move publication without source cleanup', async () => {+ const committed = record('db_committed')+ committed.publicationMode = 'move'+ committed.targetIdentity = sourceIdentity+ const state = fixture({ '/save/target': sourceIdentity })++ await state.recovery.recover(committed)++ expect(state.artifacts.get('/save/target')).toBe(sourceIdentity)+ expect(state.artifacts.has('/save/source')).toBe(false)+ expect(state.phases).toEqual(['cleaned'])+ })+it('rolls back a target moved before target_installed was journaled', async () => {const staged = record('target_staged')staged.privateTargetPath = '/save/.private'diff --git a/src/core/plugin/finalize/finalize-recovery.ts b/src/core/plugin/finalize/finalize-recovery.tsindex c34713c6..ed39be11 100644--- a/src/core/plugin/finalize/finalize-recovery.ts+++ b/src/core/plugin/finalize/finalize-recovery.ts@@ -80,6 +80,8 @@ export class FinalizeRecovery {privateTarget,replacement)+ } else if (record.publicationMode === 'move') {+ await this.restoreMovedSource(record, source, target)} else {await this.restore(record,@@ -91,6 +93,10 @@ export class FinalizeRecovery {}return}+ if (record.publicationMode === 'move') {+ await this.restoreMovedSource(record, source, target)+ return+ }await this.restore(record, target, rollback, privateTarget, replacement)return}@@ -165,6 +171,10 @@ export class FinalizeRecovery {}if (record.phase === 'prepared') {+ if (record.publicationMode === 'move') {+ await this.restoreMovedSource(record, source, target)+ return+ }await this.restorePrepared(record,source,@@ -247,7 +257,14 @@ export class FinalizeRecovery {privateTarget: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>,replacement: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>): Promise<void> {+ if (record.publicationMode === 'move' && source) {+ await this.quarantine(+ record,+ 'moved source path unexpectedly exists after commit'+ )+ }if (+ record.publicationMode !== 'move' &&source &&!finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath)) {@@ -294,6 +311,43 @@ export class FinalizeRecovery {await this.options.repository.advance(record.journalId, 'cleaned')}+ private async restoreMovedSource(+ record: FinalizeJournalRecord,+ source: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>,+ target: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>+ ): Promise<void> {+ if (+ record.plan.replacement ||+ finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath)+ ) {+ await this.quarantine(record, 'invalid move publication journal')+ }+ if (source && target) {+ await this.quarantine(+ record,+ 'source and target both exist during move recovery'+ )+ }+ if (source) {+ if (!this.options.exactIdentity(source, record.plan.sourceIdentity)) {+ await this.quarantine(record, 'moved source identity mismatch')+ }+ await this.options.repository.advance(record.journalId, 'cleaned')+ return+ }+ const expectedTarget = record.targetIdentity ?? record.plan.sourceIdentity+ if (!target || !this.options.exactIdentity(target, expectedTarget)) {+ await this.quarantine(record, 'moved target is missing or changed')+ }+ await this.options.fs.moveNoReplace(+ record.plan.targetPath,+ expectedTarget,+ record.plan.sourcePath+ )+ await this.options.fs.makeDurable(record.plan.sourcePath)+ await this.options.repository.advance(record.journalId, 'cleaned')+ }+private async restorePrepared(record: FinalizeJournalRecord,source: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>,diff --git a/src/core/session/durable-finalize-runtime.test.ts b/src/core/session/durable-finalize-runtime.test.tsindex 5103b7bb..3f6a7e15 100644--- a/src/core/session/durable-finalize-runtime.test.ts+++ b/src/core/session/durable-finalize-runtime.test.ts@@ -40,7 +40,7 @@ describe('DurableFinalizeRuntime', () => {const fs = {identity: async (artifactPath: string) =>artifactPath === sourcePath ? readArtifactIdentity(artifactPath) : null,- sameFilesystem: async () => true,+ sameFilesystem: async () => false,materializePrivate: async (_source: string,identity: ArtifactIdentitydiff --git a/src/core/session/finalize-journal-repository.test.ts b/src/core/session/finalize-journal-repository.test.tsindex 9a74c239..d94830bd 100644--- a/src/core/session/finalize-journal-repository.test.ts+++ b/src/core/session/finalize-journal-repository.test.ts@@ -57,6 +57,30 @@ describe('SqliteFinalizeJournalRepository', () => {})})+ it('persists the direct-move mode and its shorter phase transition', async () => {+ const repository = new SqliteFinalizeJournalRepository(db, {+ now: () => 5,+ commitTerminalBoundary: vi.fn(),+ })+ const record = {+ ...makeRecord('plan-move'),+ publicationMode: 'move' as const,+ }++ await repository.prepare(record)+ await repository.advance(record.journalId, 'target_installed', {+ targetIdentity: record.plan.sourceIdentity,+ })++ expect(await repository.listRecoverable()).toEqual([+ {+ ...record,+ phase: 'target_installed',+ targetIdentity: record.plan.sourceIdentity,+ },+ ])+ })+it('rolls the journal and terminal callback writes back on failure', async () => {db.exec('CREATE TABLE terminal_probe (value TEXT NOT NULL)')const repository = new SqliteFinalizeJournalRepository(db, {diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.tsindex 817aa2bf..54d78242 100644--- a/src/core/session/finalize-journal-repository.ts+++ b/src/core/session/finalize-journal-repository.ts@@ -3,6 +3,7 @@ import type {FinalizeJournalRecord,FinalizeJournalRepository,} from '@core/plugin/finalize/finalize-committer'+import { finalizePathsEquivalent } from '@core/plugin/finalize/finalize-committer'import { assertValidHookPlan } from '@core/plugin/finalize/hook-plan'import type Database from 'better-sqlite3'@@ -141,7 +142,7 @@ export class SqliteFinalizeJournalRepositorythis.db.transaction(() => {const current = this.requireRecord(journalId)if (current.phase === phase) return- if (!transitionAllowed(current.phase, phase)) {+ if (!transitionAllowed(current, phase)) {throw new Error(`invalid finalize transition ${current.phase} -> ${phase}`)@@ -254,6 +255,20 @@ function parseRecord(raw: RawFinalizeJournal): FinalizeJournalRecord {if (record.phase !== raw.phase) {throw new TypeError('journal phase column does not match record')}+ if (+ record.publicationMode !== undefined &&+ record.publicationMode !== 'copy' &&+ record.publicationMode !== 'move'+ ) {+ throw new TypeError('journal publication mode is invalid')+ }+ if (+ record.publicationMode === 'move' &&+ (record.plan.replacement !== undefined ||+ finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath))+ ) {+ throw new TypeError('journal move publication plan is invalid')+ }assertValidHookPlan(record.plan)const sourceIdentity = JSON.stringify(record.plan.sourceIdentity)if (sourceIdentity !== JSON.stringify(JSON.parse(raw.source_identity_json))) {@@ -270,12 +285,16 @@ function parseRecord(raw: RawFinalizeJournal): FinalizeJournalRecord {}function transitionAllowed(- from: FinalizeJournalPhase,+ record: FinalizeJournalRecord,to: FinalizeJournalPhase): boolean {+ const from = record.phasereturn ((from === 'prepared' &&(to === 'source_preserved' || to === 'target_staged')) ||+ (from === 'prepared' &&+ record.publicationMode === 'move' &&+ to === 'target_installed') ||(from === 'source_preserved' && to === 'target_staged') ||(from === 'target_staged' && to === 'target_installed') ||((from === 'prepared' ||diff --git a/src/core/session/motrix-database.test.ts b/src/core/session/motrix-database.test.tsindex 8c9ad2e0..6b57638a 100644--- a/src/core/session/motrix-database.test.ts+++ b/src/core/session/motrix-database.test.ts@@ -203,6 +203,48 @@ describe('saveTaskWithInstances + getAllTasks (Plan A v1 schema)', () => {db.close()})+ it('rebases persisted task files inside the terminal commit transaction', () => {+ const db = new MotrixDatabase(':memory:')+ db.init()+ const task = makeTaskRow('m-finalize-files', TaskKind.Direct)+ const sourcePath = '/downloads/file.bin.motrix'+ const targetPath = '/downloads/file.bin'+ db.saveTaskWithInstances({ task, instances: [] })+ db.replaceTaskFiles(task.motrixId, [+ {+ fileIndex: 7,+ path: sourcePath,+ size: 42,+ selected: false,+ },+ ])++ expect(() =>+ db.commitTerminalHookBoundary({+ payload: {+ task: {+ ...task,+ finalPath: targetPath,+ aggStatus: TaskStatus.Completed,+ },+ instances: [],+ },+ occurrence: null,+ fileRebase: { sourceRoot: sourcePath, targetRoot: targetPath },+ })+ ).not.toThrow()+ expect(db.getTaskFiles(task.motrixId)).toEqual([+ {+ fileIndex: 7,+ path: targetPath,+ size: 42,+ selected: false,+ },+ ])++ db.close()+ })+it.each(Object.values(TaskType))('round-trips canonical task type %s',(taskType) => {diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.tsindex 8b9999f5..45d1436c 100644--- a/src/core/session/motrix-database.ts+++ b/src/core/session/motrix-database.ts@@ -966,7 +966,7 @@ export class MotrixDatabase {sourceRoot: string,targetRoot: string): void {- const rows = this.stmtGetFiles.all(taskId) as TaskFileRow[]+ const rows = this.getTaskFiles(taskId)let changed = falseconst rebased = rows.map((row) => {if (!row.path) return rowdiff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex 317fa9f0..efcf0e3e 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -1851,6 +1851,63 @@ describe('finalizeTask plugin-hook chain (Plan C / T15)', () => {expect(task.status).toBe(TaskStatus.Completed)})+ it('HTTP: durable commit failure preserves the recoverable rename intent', async () => {+ const deps: FinalizeTaskDeps = {+ ...makeDeps(),+ orchestrator: makeOrchestrator(makeBeforeFinalizeCommit()),+ auditLog: makeAuditLog(),+ commitFinalizedArtifact: vi.fn(async () => {+ throw new Error('database unavailable')+ }),+ }+ const task = makeTask({ instances: [makePrimaryInstance()] })+ ;(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(+ task+ )++ await expect(finalizeTask('t1', deps)).rejects.toThrow(+ 'Failed to commit finalized file: database unavailable'+ )++ expect(task).toMatchObject({+ status: TaskStatus.Error,+ diskPath: '/d/foo.mp4.motrix',+ finalPath: '/d/foo.mp4',+ transitionPhase: TransitionPhase.Renaming,+ })+ expect(task.instances[0]).toMatchObject({+ diskPath: '/d/foo.mp4.motrix',+ transitionPhase: TransitionPhase.Renaming,+ })+ expect(deps.activityRecorder.recordDownloadCompleted).not.toHaveBeenCalled()+ })++ it('BT: durable commit failure preserves the recoverable rename intent', async () => {+ const deps: FinalizeTaskDeps = {+ ...makeDeps(),+ orchestrator: makeOrchestrator(makeBeforeFinalizeCommit()),+ auditLog: makeAuditLog(),+ commitFinalizedArtifact: vi.fn(async () => {+ throw new Error('database unavailable')+ }),+ }+ const task = makeBtTask()+ ;(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(+ task+ )++ await expect(finalizeTask('t1', deps)).rejects.toThrow(+ 'Failed to commit finalized directory: database unavailable'+ )++ expect(task).toMatchObject({+ status: TaskStatus.Error,+ diskPath: '/d/torrent.motrix',+ finalPath: '/d/torrent',+ transitionPhase: TransitionPhase.Renaming,+ })+ })+it('HTTP: beforeFinalize can route a GitHub ZIP into Compressed through the durable seam', async () => {const commitFinalizedArtifact = vi.fn(async () => {})const deps: FinalizeTaskDeps = {diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex acbabaa5..26dde58f 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -30,6 +30,7 @@ import { fireAfterComplete, fireOnError } from '../hook-dispatch'import { normalizeTerminalRuntimeMetrics } from '../normalize-terminal-runtime-metrics'import type { OccurrenceDispatcher } from '../occurrences/occurrence-dispatcher'import {+ applyCompletedTaskAfterRename,applyTerminalStatusToTask,completeTaskAfterRename,setTaskTransitionPhase,@@ -343,17 +344,13 @@ async function commitHttpArtifactDurably(): Promise<void> {const completedAt = Date.now()const previousStatus = task.status- task.finalPath = desiredFinalPath- completeTaskAfterRename(- task,- desiredFinalPath,- completedAt,- deps.activityRecorder- )- syncCompletionMetrics(task)- normalizeTerminalRuntimeMetrics(task)+ const completedTask = structuredClone(task)+ completedTask.finalPath = desiredFinalPath+ applyCompletedTaskAfterRename(completedTask, desiredFinalPath, completedAt)+ syncCompletionMetrics(completedTask)+ normalizeTerminalRuntimeMetrics(completedTask)const occurrence = buildTerminalOccurrence(- terminalSnapshotFromTask(task),+ terminalSnapshotFromTask(completedTask),previousStatus,'finalize',completedAt@@ -361,7 +358,7 @@ async function commitHttpArtifactDurably(if (!occurrence)throw new Error('HTTP finalize did not produce an occurrence')await deps.commitFinalizedArtifact?.({- task,+ task: completedTask,occurrence,sourcePath: renameSource,targetPath: desiredFinalPath,@@ -373,17 +370,21 @@ async function commitHttpArtifactDurably(targetRoot: desiredFinalPath,},})- deps.taskManager.set(task.id, structuredClone(task))- await recordTaskTransitionOrWarn(task, previousStatus, deps, {+ deps.activityRecorder.recordDownloadCompleted({+ taskId: completedTask.id,+ occurredAt: completedAt,+ })+ deps.taskManager.set(completedTask.id, structuredClone(completedTask))+ await recordTaskTransitionOrWarn(completedTask, previousStatus, deps, {occurredAt: completedAt,accuracy: TaskActivityAccuracy.Exact,occurrenceId: occurrence.occurrenceId,failureMessage: FINALIZE_RECORD_FAILURE_MESSAGE,})await deps.occurrenceDispatcher?.dispatch(occurrence)- deps.eventBus.emit(Events.TaskFilesUpdated, { taskId: task.id })+ deps.eventBus.emit(Events.TaskFilesUpdated, { taskId: completedTask.id })deps.publishTaskUpdateNow()- deps.log.info({ taskId: task.id }, 'finalize_http_completed')+ deps.log.info({ taskId: completedTask.id }, 'finalize_http_completed')}/**@@ -552,22 +553,13 @@ async function finalizeBt(await deps.adapter.removeDownloadResult(task.engineTaskId)const completedAt = Date.now()- task.finalPath = desiredFinalPath- task.diskPath = desiredFinalPath- // Same instance-row sync as finalizeHttp: the on-disk rename just- // happened, so the instance rows must stop pointing at the `.motrix`- // container or restore() resurrects it after a restart. Status is- // left alone here — the task still heads into reseed and its- // terminal state (Seeding/Completed) is decided below.- for (const inst of task.instances) {- inst.diskPath = desiredFinalPath- }- setTaskTransitionPhase(task, TransitionPhase.Reseeding)if (deps.commitFinalizedArtifact) {+ const renamedTask = structuredClone(task)+ applyBtTaskAfterRename(renamedTask, desiredFinalPath)try {await deps.commitFinalizedArtifact({- task,+ task: renamedTask,occurrence: null,sourcePath: renameSource,targetPath: desiredFinalPath,@@ -579,6 +571,7 @@ async function finalizeBt(targetRoot: desiredFinalPath,},})+ Object.assign(task, structuredClone(renamedTask))deps.taskManager.set(task.id, structuredClone(task))deps.eventBus.emit(Events.TaskFilesUpdated, { taskId: task.id })} catch (e) {@@ -622,6 +615,7 @@ async function finalizeBt('finalize_bt_metadata_commit_failed')}+ applyBtTaskAfterRename(task, desiredFinalPath)await persistTaskState(task, deps)}@@ -645,6 +639,21 @@ async function finalizeBt(await finalizeBtAfterRename(task, deps, completedAt, unselectedRelPaths)}+function applyBtTaskAfterRename(+ task: DownloadTask,+ desiredFinalPath: string+): void {+ task.finalPath = desiredFinalPath+ task.diskPath = desiredFinalPath+ // The instance rows must stop pointing at the `.motrix` container or+ // restore() resurrects it after a restart. Status is left alone here — the+ // task still heads into reseed and its terminal state is decided below.+ for (const inst of task.instances) {+ inst.diskPath = desiredFinalPath+ }+ setTaskTransitionPhase(task, TransitionPhase.Reseeding)+}+async function finalizeBtAfterRename(task: DownloadTask,deps: FinalizeTaskDeps,diff --git a/src/core/task/task-instance.ts b/src/core/task/task-instance.tsindex a732d281..27cbc274 100644--- a/src/core/task/task-instance.ts+++ b/src/core/task/task-instance.ts@@ -131,11 +131,10 @@ export function applyTerminalStatusToTask(* instance path would resurrect the now-nonexistent placeholder after an* app restart, breaking reveal-in-folder and delete-with-files.*/-export function completeTaskAfterRename(+export function applyCompletedTaskAfterRename(task: DownloadTask,finalDiskPath: string,- completedAt: number,- activityRecorder: TaskActivityRecorder+ completedAt: number): void {task.diskPath = finalDiskPathsetTaskTransitionPhase(task, TransitionPhase.Idle)@@ -143,12 +142,21 @@ export function completeTaskAfterRename(for (const instance of task.instances) {instance.diskPath = finalDiskPath}- activityRecorder.recordDownloadCompleted({- taskId: task.id,- occurredAt: completedAt,- })Object.assign(task,applyTerminalTransition(task, TaskStatus.Completed, {}, completedAt))}++export function completeTaskAfterRename(+ task: DownloadTask,+ finalDiskPath: string,+ completedAt: number,+ activityRecorder: TaskActivityRecorder+): void {+ applyCompletedTaskAfterRename(task, finalDiskPath, completedAt)+ activityRecorder.recordDownloadCompleted({+ taskId: task.id,+ occurredAt: completedAt,+ })+}