A full-featured download manager.
feat(media): store segment metadata outside task database (#2156)
Dr_rOotc4dc8bf1caf0
diff --git a/e2e/disclaimer.spec.ts b/e2e/disclaimer.spec.tsindex 89633ce8..544c0268 100644--- a/e2e/disclaimer.spec.ts+++ b/e2e/disclaimer.spec.ts@@ -35,11 +35,11 @@ test.describe('disclaimer startup gate', () => {.getByTestId('onboarding-language').boundingBox()expect(languageBounds).not.toBeNull()- // Preserve the beta.29 onboarding geometry: the 32px language trigger- // sits with its centerline at y=34 in the 40px compact chrome region.+ // The shared chrome supplies the vertical offset; the language picker+ // must not add a second offset of its own.expect((languageBounds?.y ?? 0) + (languageBounds?.height ?? 0) / 2- ).toBeCloseTo(34, 1)+ ).toBeCloseTo(27, 1)expect(app.windows().some((page) => page.url().includes('w=main'))).toBe(falsediff --git a/e2e/downloads-visibility.spec.ts b/e2e/downloads-visibility.spec.tsindex b62d4a6e..e5ce78c5 100644--- a/e2e/downloads-visibility.spec.ts+++ b/e2e/downloads-visibility.spec.ts@@ -3,7 +3,12 @@ import { DownloadErrorCode } from '@shared/errors'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import { Queries } from '@shared/protocol/queries'-import { type DownloadTask, TaskStatus, TaskType } from '@shared/types/task'+import {+ type DownloadTask,+ TaskKind,+ TaskStatus,+ TaskType,+} from '@shared/types/task'import { makeDownloadTask } from '../src/test-utils/task'import {expect,@@ -93,6 +98,77 @@ async function expectDrawerSettled(drawer: Locator) {.toBe(true)}+test('media file list shows every segment through virtual scrolling and stays read-only', async ({+ electronApp,+ mainWindow,+}, testInfo) => {+ await waitForEngineReady(mainWindow)+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)+ await electronApp.evaluate(({ ipcMain }, channel) => {+ ipcMain.removeHandler(channel)+ ipcMain.handle(channel, () =>+ Array.from({ length: 2000 }, (_, index) => ({+ index,+ path:+ index === 0+ ? 'video/init.mp4'+ : index === 1999+ ? 'audio/001000.aac'+ : `video/${String(index).padStart(6, '0')}.ts`,+ size: index < 2 ? 1000 : 0,+ selected: true,+ completedBytes: index === 0 ? 1000 : index === 1 ? 500 : 0,+ progress: index === 0 ? 1 : index === 1 ? 0.5 : 0,+ }))+ )+ }, Queries.GetTaskFiles)+ const task = makeDownloadTask({+ id: 'hls-segments',+ name: 'Playlist.mp4',+ kind: TaskKind.Hls,+ status: TaskStatus.Downloading,+ progress: 0.25,+ fileCount: 1,+ })+ await publish(electronApp, [task])+ await mainWindow.locator('[data-task-id="hls-segments"]').dblclick()+ const inspector = mainWindow.getByRole('dialog', { name: 'Task Inspector' })+ await inspector.getByRole('tab', { name: 'Files', exact: true }).click()+ const list = inspector.getByTestId('virtual-list-container')+ await expect(list.getByText('video/init.mp4', { exact: true })).toBeVisible()+ await expect(list.getByText('100%', { exact: true })).toBeVisible()+ await expect(list.getByText('50%', { exact: true })).toBeVisible()+ expect(await list.getByRole('checkbox').count()).toBeLessThan(50)+ await expect(list.getByRole('checkbox').first()).toHaveAttribute(+ 'aria-disabled',+ 'true'+ )+ await expect(+ inspector.getByRole('button', { name: 'Save', exact: true })+ ).toHaveCount(0)+ await mainWindow.screenshot({+ path: testInfo.outputPath('media-segments.png'),+ })++ await list.evaluate((element) => {+ element.scrollTop = element.scrollHeight+ })+ await expect(+ list.getByText('audio/001000.aac', { exact: true })+ ).toBeVisible()+ expect(await list.getByRole('checkbox').count()).toBeLessThan(50)+ expect(+ await mainWindow.evaluate(+ () => document.documentElement.scrollHeight <= window.innerHeight+ )+ ).toBe(true)+ await mainWindow.screenshot({+ path: testInfo.outputPath('media-segments-last.png'),+ })+})+test('download columns sort live tasks without losing selection or filter state', async ({electronApp,mainWindow,diff --git a/src/core/bridge-receiver/bridge-receiver.test.ts b/src/core/bridge-receiver/bridge-receiver.test.tsindex c7f0c7df..6505033c 100644--- a/src/core/bridge-receiver/bridge-receiver.test.ts+++ b/src/core/bridge-receiver/bridge-receiver.test.ts@@ -5,6 +5,7 @@ import { ErrorCodes } from '@motrix/mdxp'import { Events } from '@shared/protocol/events'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'+import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'import { makeDownloadTask } from '@test-utils/task'import { describe, expect, it, vi } from 'vitest'import { BridgeReceiver } from './bridge-receiver'@@ -23,6 +24,7 @@ function fakeDeps(over: Partial<ConstructorParameters<typeof BridgeReceiver>[0]> = {}) {return {+ mediaMetaStore: makeMediaMetaStoreStub(),getDefaultSaveDir: () => '/tmp/save',pickName: async (_d: string, n: string) => n,createTask: vi.fn(async () => ({ gid: 'gid-1', taskId: 'task-abc' })),diff --git a/src/core/bridge-receiver/bridge-receiver.ts b/src/core/bridge-receiver/bridge-receiver.tsindex ff94e2bb..f39bb54c 100644--- a/src/core/bridge-receiver/bridge-receiver.ts+++ b/src/core/bridge-receiver/bridge-receiver.ts@@ -53,6 +53,9 @@ export function serializeCookieHeader(}export interface BridgeReceiverDeps {+ mediaMetaStore: ConstructorParameters<+ typeof MediaTaskCoordinator+ >[0]['mediaMetaStore']getDefaultSaveDir: AdapterDeps['getDefaultSaveDir']pickName: AdapterDeps['pickName']createTask: ConstructorParameters<typeof DirectPipeline>[0]['createTask']@@ -212,6 +215,7 @@ export class BridgeReceiver {}const tmpRoot = deps.tmpRootconst coordinator = new MediaTaskCoordinator({+ mediaMetaStore: deps.mediaMetaStore,taskManager: deps.taskManager,activityRecorder: deps.activityRecorder,eventBus: eventBusWithEmit,diff --git a/src/core/bridge-receiver/pipelines/hls-dash-pipeline.test.ts b/src/core/bridge-receiver/pipelines/hls-dash-pipeline.test.tsindex 5adac30d..bf8b9f7b 100644--- a/src/core/bridge-receiver/pipelines/hls-dash-pipeline.test.ts+++ b/src/core/bridge-receiver/pipelines/hls-dash-pipeline.test.ts@@ -171,6 +171,9 @@ describe('HlsDashPipeline', () => {// coordinator.submit called with correct jobexpect(coordinator.submit).toHaveBeenCalledTimes(1)const job = captured[0]!+ expect(job.manifests).toEqual([+ { name: 'video.m3u8', url: adapted.manifestUrl, text: MEDIA_VOD },+ ])expect(job.taskId).toBe('task-hls-1')expect(job.saveDir).toBe('/downloads')expect(job.finalName).toBe('video.ts')@@ -237,6 +240,11 @@ describe('HlsDashPipeline', () => {expect(fetchManifest).toHaveBeenCalledTimes(3)const job = coordinator.submit.mock.calls[0]![0] as MediaJob+ expect(job.manifests).toEqual([+ { name: 'master.m3u8', url: MASTER_URL, text: MASTER_WITH_AUDIO },+ { name: 'video.m3u8', url: VARIANT_URL, text: VARIANT_MEDIA },+ { name: 'audio.m3u8', url: AUDIO_URL, text: AUDIO_MEDIA },+ ])expect(job.video.segments).toHaveLength(2) // from VARIANT_MEDIAexpect(job.audio).toBeDefined()expect(job.audio!.segments).toHaveLength(1) // from AUDIO_MEDIA@@ -275,6 +283,9 @@ describe('HlsDashPipeline', () => {expect(fetchManifest).toHaveBeenCalledTimes(1)const job = captured[0]!+ expect(job.manifests).toEqual([+ { name: 'manifest.mpd', url: adapted.manifestUrl, text: DASH_MPD },+ ])expect(job.taskId).toBe('task-dash-1')expect(job.video).toBeDefined()expect(job.video.segments.length).toBeGreaterThan(0)diff --git a/src/core/bridge-receiver/pipelines/hls-dash-pipeline.ts b/src/core/bridge-receiver/pipelines/hls-dash-pipeline.tsindex 38e45d5b..6457bef9 100644--- a/src/core/bridge-receiver/pipelines/hls-dash-pipeline.ts+++ b/src/core/bridge-receiver/pipelines/hls-dash-pipeline.ts@@ -1,6 +1,7 @@import { parseDash } from '@core/media/dash-parser'import { parseHlsMaster, parseHlsMedia } from '@core/media/hls-parser'import { MediaParseError } from '@core/media/segment-plan'+import type { MediaManifest } from '@core/task/media-meta-store'import type {MediaJob,MediaTaskCoordinator,@@ -64,6 +65,13 @@ export class HlsDashPipeline {const job: MediaJob = {taskId: adapted.taskId,kind: 'dash',+ manifests: [+ {+ name: 'manifest.mpd',+ url: adapted.manifestUrl,+ text: manifestText,+ },+ ],video,...(audio !== undefined ? { audio } : {}),headers,@@ -97,6 +105,10 @@ export class HlsDashPipeline {)}const video = parseHlsMedia(variantText, variantUrl)+ const manifests: MediaManifest[] = [+ { name: 'master.m3u8', url: adapted.manifestUrl, text: manifestText },+ { name: 'video.m3u8', url: variantUrl, text: variantText },+ ]let audioJob: ReturnType<typeof parseHlsMedia> | undefinedif (audioUrl !== undefined) {@@ -111,11 +123,13 @@ export class HlsDashPipeline {)}audioJob = parseHlsMedia(audioText, audioUrl)+ manifests.push({ name: 'audio.m3u8', url: audioUrl, text: audioText })}const job: MediaJob = {taskId: adapted.taskId,kind: 'hls',+ manifests,video,...(audioJob !== undefined ? { audio: audioJob } : {}),headers,@@ -134,6 +148,9 @@ export class HlsDashPipeline {const job: MediaJob = {taskId: adapted.taskId,kind: 'hls',+ manifests: [+ { name: 'video.m3u8', url: adapted.manifestUrl, text: manifestText },+ ],video,headers,saveDir: adapted.saveDir,diff --git a/src/core/download/segment-downloader.test.ts b/src/core/download/segment-downloader.test.tsindex 2e432690..a531d604 100644--- a/src/core/download/segment-downloader.test.ts+++ b/src/core/download/segment-downloader.test.ts@@ -1,7 +1,11 @@import path from 'node:path'import type { SegmentPlan } from '@core/media/segment-plan'import { describe, expect, it } from 'vitest'-import type { PollScheduler, SegmentAria2 } from './segment-downloader'+import type {+ PollScheduler,+ SegmentAria2,+ SegmentFileProgress,+} from './segment-downloader'import { SegmentDownloader } from './segment-downloader'// A poll scheduler that swallows the callback: polls NEVER auto-fire. Tests@@ -142,6 +146,66 @@ const TMP = '/tmp/test-seg'// ---------------------------------------------------------------------------describe('SegmentDownloader', () => {+ it('reports file progress by plan index across polling, retries and out-of-order completion', async () => {+ const fake = makeFakeAria2()+ const clock = makeManualScheduler()+ const dl = new SegmentDownloader({+ aria2: fake.aria2,+ tmpDir: TMP,+ concurrency: 2,+ pollScheduler: clock.scheduler,+ })+ const updates = new Map<number, SegmentFileProgress>()+ const run = dl.run(+ makePlan({+ init: { url: 'https://cdn.example/init.mp4' },+ segments: [+ { url: 'https://cdn.example/1.m4s' },+ { url: 'https://cdn.example/2.m4s' },+ ],+ }),+ {},+ () => {},+ (p) => updates.set(p.index, p)+ )+ await new Promise((resolve) => setImmediate(resolve))+ fake.setBytes('gid1', 5, 10)+ fake.setBytes('gid2', 0, 0)+ await clock.tick()+ expect(updates.get(0)).toMatchObject({+ downloadedBytes: 5,+ totalBytes: 10,+ completed: false,+ })+ expect(updates.has(2)).toBe(false)++ fake.fireError('gid1')+ await new Promise((resolve) => setImmediate(resolve))+ expect(updates.get(0)).toMatchObject({+ downloadedBytes: 0,+ completed: false,+ })+ // The terminal size must replace a prior poll's unknown length.+ fake.setBytes('gid2', 25, 25)+ fake.fireComplete('gid2')+ await new Promise((resolve) => setImmediate(resolve))+ expect(updates.get(1)).toMatchObject({+ downloadedBytes: 25,+ totalBytes: 25,+ completed: true,+ })+ fake.setBytes('gid3', 10, 10)+ fake.fireComplete('gid3')+ // A completed transfer with unavailable lengths is still complete.+ fake.fireComplete('gid4')+ await run+ expect(updates.get(0)).toMatchObject({+ downloadedBytes: 10,+ completed: true,+ })+ expect(updates.get(2)).toMatchObject({ totalBytes: 0, completed: true })+ })+it('(a) submits exactly one addUri per part — uris array length is always 1', async () => {const fake = makeFakeAria2()const dl = new SegmentDownloader({diff --git a/src/core/download/segment-downloader.ts b/src/core/download/segment-downloader.tsindex 80814a8f..d8eb62b0 100644--- a/src/core/download/segment-downloader.ts+++ b/src/core/download/segment-downloader.ts@@ -66,6 +66,14 @@ export interface SegmentProgress {totalBytes: number}+/** A stable index in the plan's [init?, ...segments] order, across retries. */+export interface SegmentFileProgress {+ index: number+ downloadedBytes: number+ totalBytes: number+ completed: boolean+}+/*** Injectable timer seam for the byte-polling loop. Returns a stop function.* Production uses `setInterval`; tests inject a manual scheduler to drive@@ -222,7 +230,8 @@ export class SegmentDownloader {run(plan: SegmentPlan,headers: Record<string, string>,- onProgress: (p: SegmentProgress) => void+ onProgress: (p: SegmentProgress) => void,+ onFileProgress?: (p: SegmentFileProgress) => void): Promise<{ initPath?: string; partPaths: string[] }> {this.cancelled = falsethis.rejectRun = null@@ -341,17 +350,25 @@ export class SegmentDownloader {this.settlingGids.add(gid)const operation = (async () => {const ls = lastSeen.get(gid)- if (ls) {- // Size known from a prior poll: move it to finished before the- // gid leaves the active set so the running total never dips.- lastSeen.delete(gid)- addFinished(ls.total)- } else {- // Query before purging: terminal downloads remain queryable only- // until removeDownloadResult succeeds.- const status = await this.aria2.tellStatus(gid).catch(() => null)- if (status) addFinished(status.totalLength)- }+ // A prior poll may have seen an unknown length. Read the final+ // size before removing the engine result, retaining the last poll+ // (or declared byte range) if the terminal query fails.+ const status = ls?.total+ ? null+ : await this.aria2.tellStatus(gid).catch(() => null)+ const size =+ status?.totalLength ||+ ls?.total ||+ job.part.byteRange?.length ||+ 0+ lastSeen.delete(gid)+ onFileProgress?.({+ index: job.jobIndex,+ downloadedBytes: size,+ totalBytes: size,+ completed: true,+ })+ if (size > 0) addFinished(size)await this.purgeResult(gid)this.settlingGids.delete(gid)@@ -372,6 +389,13 @@ export class SegmentDownloader {// A retry restarts this segment from zero; drop its cached bytes so// the active sum reflects only live in-flight segments.lastSeen.delete(gid)+ onFileProgress?.({+ index: job.jobIndex,+ downloadedBytes: 0,+ totalBytes: job.part.byteRange?.length ?? 0,+ completed: false,+ })+ report()const operation = (async () => {await this.purgeResult(gid)this.settlingGids.delete(gid)@@ -415,6 +439,15 @@ export class SegmentDownloader {completed: s.completedLength,total: s.totalLength,})+ const job = this.activeJobs.get(gid)+ if (job) {+ onFileProgress?.({+ index: job.jobIndex,+ downloadedBytes: s.completedLength,+ totalBytes: s.totalLength,+ completed: false,+ })+ }}}}diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex d0f0977d..349154bd 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -29,6 +29,7 @@ import {getBtPayloadPath,parseBtFileLayout,} from '../task/bt-storage-layout'+import { getMediaMetaPath } from '../task/media-task-files'import { TaskManager } from '../task/task-manager'import { computeUriHash } from './content-key'import type {@@ -880,6 +881,37 @@ describe('SessionManager', () => {TaskInstancePhase.HlsSegment,])})++ it.each([TaskStatus.Completed, TaskStatus.Error])(+ 'restores the media metadata reference for a %s task',+ async (status) => {+ const task = makeMultiInstanceTask()+ task.status = status+ task.engineTaskId = ''+ for (const instance of task.instances) {+ instance.gid = null+ instance.status = status+ }+ task.instances[0].payload.mediaMetaPath =+ '/metadata/media/m-multi/files.json'+ // Equal creation timestamps do not guarantee an instance row order.+ task.instances.reverse()+ taskManager.add(task)+ await session.save()+ const saved = db.getTask(task.id)+ expect(saved).not.toBeNull()+ db.saveTaskWithInstances(JSON.parse(JSON.stringify(saved)))+ taskManager.clear()++ await session.restore()++ const restored = taskManager.getById(task.id)+ expect(restored?.status).toBe(status)+ expect(getMediaMetaPath(restored as DownloadTask)).toEqual(+ getMediaMetaPath(task)+ )+ }+ )})describe('exclusive persistence queue', () => {diff --git a/src/core/task/actions/clear-stopped-tasks.test.ts b/src/core/task/actions/clear-stopped-tasks.test.tsindex f586c983..7ee1d171 100644--- a/src/core/task/actions/clear-stopped-tasks.test.ts+++ b/src/core/task/actions/clear-stopped-tasks.test.ts@@ -96,6 +96,54 @@ function createDeps(initial: readonly DownloadTask[]) {}describe('clearStoppedTasks', () => {+ it('cleans metadata only for successfully deleted media tasks', async () => {+ const completed = task('media-done', TaskStatus.Completed, {+ engineTaskId: '',+ })+ const active = task('media-active', TaskStatus.Downloading, {+ engineTaskId: '',+ })+ for (const item of [completed, active]) {+ item.instances = [+ {+ ...instance(item.id, '', 0),+ phase: TaskInstancePhase.HlsSegment,+ gid: null,+ payload: { mediaMetaPath: `/metadata/media/${item.id}/files.json` },+ },+ ]+ }+ const { deps } = createDeps([completed, active])+ const mediaMetaStore = { remove: vi.fn(async () => {}) }+ await clearStoppedTasks({ ...deps, mediaMetaStore })+ expect(mediaMetaStore.remove).toHaveBeenCalledExactlyOnceWith(+ '/metadata/media/media-done/files.json'+ )+ })++ it('keeps media metadata if the batch database deletion fails', async () => {+ const completed = task('media-done', TaskStatus.Completed, {+ engineTaskId: '',+ })+ completed.instances = [+ {+ ...instance(completed.id, '', 0),+ phase: TaskInstancePhase.HlsSegment,+ gid: null,+ payload: { mediaMetaPath: '/metadata/media/media-done/files.json' },+ },+ ]+ const { deps } = createDeps([completed])+ const mediaMetaStore = { remove: vi.fn(async () => {}) }+ deps.db.deleteTasks.mockImplementation(() => {+ throw new Error('disk full')+ })+ await expect(+ clearStoppedTasks({ ...deps, mediaMetaStore })+ ).rejects.toThrow('disk full')+ expect(mediaMetaStore.remove).not.toHaveBeenCalled()+ })+it('clears only frozen candidate IDs, preserving newly stopped tasks and files', async () => {const { deps, tasks } = createDeps([task('first', TaskStatus.Completed),diff --git a/src/core/task/actions/clear-stopped-tasks.ts b/src/core/task/actions/clear-stopped-tasks.tsindex bb2e034d..65ec0522 100644--- a/src/core/task/actions/clear-stopped-tasks.ts+++ b/src/core/task/actions/clear-stopped-tasks.ts@@ -5,6 +5,8 @@ import type { SessionManager } from '@core/session/session-manager'import type { DownloadTask } from '@shared/types/task'import { isStoppedTaskStatus } from '@shared/types/task-actions'import type { Logger } from '../../logger'+import type { MediaMetaStore } from '../media-meta-store'+import { getMediaMetaPath } from '../media-task-files'import { collectTaskGids } from '../task-instance'import type { TaskManager } from '../task-manager'@@ -14,6 +16,7 @@ interface Candidate {}export interface ClearStoppedTasksDeps {+ mediaMetaStore?: Pick<MediaMetaStore, 'remove'>taskManager: Pick<TaskManager, 'getAll' | 'getById' | 'remove'>adapter: Pick<EngineAdapter, 'removeDownloadResults'>db: Pick<MotrixDatabase, 'deleteTasks'>@@ -140,6 +143,12 @@ export async function clearStoppedTasks(if (ids.length === 0) return 0+ const mediaPaths = ids.flatMap((id) => {+ const task = deps.taskManager.getById(id)+ const metaPath = task && getMediaMetaPath(task)+ return metaPath ? [metaPath] : []+ })+const deleteParents = (): void => {deps.db.deleteTasks(ids)for (const id of ids) deps.taskManager.remove(id)@@ -150,6 +159,11 @@ export async function clearStoppedTasks(deleteParents()}succeeded.push(...ids)+ for (const metaPath of mediaPaths) {+ await deps.mediaMetaStore?.remove(metaPath).catch((err) => {+ deps.log.warn({ err, metaPath }, 'Failed to remove media metadata')+ })+ }deps.publishTaskUpdateNow()return ids.length})diff --git a/src/core/task/actions/remove-task.test.ts b/src/core/task/actions/remove-task.test.tsindex 9b6b51c4..006b2c47 100644--- a/src/core/task/actions/remove-task.test.ts+++ b/src/core/task/actions/remove-task.test.ts@@ -77,7 +77,75 @@ function makeDeps(overrides: Partial<RemoveTaskDeps> = {}): RemoveTaskDeps {return { ...base, ...directTaskUpdatePublication(base), ...overrides }}+function mediaTaskWithMetadata() {+ return makeDownloadTask({+ engineTaskId: '',+ saveDir: '/d',+ diskPath: '/d/video.mp4',+ instances: [+ {+ instanceId: 'video',+ motrixId: 'task-1',+ gid: null,+ phase: TaskInstancePhase.HlsSegment,+ status: TaskStatus.Downloading,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '/d/video.mp4',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ createdAt: 0,+ updatedAt: 0,+ payload: { mediaMetaPath: '/metadata/media/task-1/files.json' },+ },+ ],+ })+}+describe('removeTask', () => {+ it.each([false, true])(+ 'removes associated media metadata when deleteWithFiles=%s',+ async (deleteWithFiles) => {+ const mediaMetaStore = { remove: vi.fn(async () => {}) }+ const deps = makeDeps({+ mediaMetaStore,+ cancelMedia: vi.fn(async () => {}),+ })+ const task = mediaTaskWithMetadata()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ await removeTask(task.id, { deleteWithFiles }, deps)+ expect(mediaMetaStore.remove).toHaveBeenCalledWith(+ '/metadata/media/task-1/files.json'+ )+ expect(+ vi.mocked(deps.cancelMedia!).mock.invocationCallOrder[0]+ ).toBeLessThan(mediaMetaStore.remove.mock.invocationCallOrder[0])+ expect(+ vi.mocked(deps.db.deleteTask).mock.invocationCallOrder[0]+ ).toBeLessThan(mediaMetaStore.remove.mock.invocationCallOrder[0])+ expect(deps.fileCleanupService.cleanup).toHaveBeenCalledTimes(+ deleteWithFiles ? 1 : 0+ )+ }+ )++ it('retains media metadata if the durable task delete fails', async () => {+ const mediaMetaStore = { remove: vi.fn(async () => {}) }+ const deps = makeDeps({ mediaMetaStore })+ const task = mediaTaskWithMetadata()+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.db.deleteTask).mockImplementation(() => {+ throw new Error('disk full')+ })+ await expect(+ removeTask(task.id, { deleteWithFiles: false }, deps)+ ).rejects.toThrow('disk full')+ expect(mediaMetaStore.remove).not.toHaveBeenCalled()+ })+it('tears down the coordinator for a media task and never calls the engine with an empty gid', async () => {// A coordinator-managed media task (Mux/Hls) has engineTaskId ''. Removing// it must abort the in-flight SegmentDownloaders + ffmpeg (via cancelMedia)diff --git a/src/core/task/actions/remove-task.ts b/src/core/task/actions/remove-task.tsindex 556bf0b3..495ce739 100644--- a/src/core/task/actions/remove-task.ts+++ b/src/core/task/actions/remove-task.ts@@ -24,6 +24,8 @@ import {parseBtFileLayout,} from '../bt-storage-layout'import type { FileCleanupService } from '../file-cleanup-service'+import type { MediaMetaStore } from '../media-meta-store'+import { getMediaMetaPath } from '../media-task-files'import { outputPathIdentity } from '../output-path-identity'import type { TorrentMetaStore } from '../torrent-meta-store'import { getTaskOrWarn, type TaskActionDeps } from './shared'@@ -37,6 +39,7 @@ export interface RemoveTaskDeps extends TaskActionDeps {taskPersistence: Pick<SessionManager, 'runExclusivePersistence'>fileCleanupService: FileCleanupServicetorrentMetaStore: TorrentMetaStore+ mediaMetaStore?: Pick<MediaMetaStore, 'remove'>// Structural slice of MotrixDatabase. Removal needs `deleteTask` for// normal tasks; magnet_metadata_resolution removal also reads via// `getTask` and writes the quarantine tombstone via@@ -289,6 +292,13 @@ async function removeTaskUnderMutation(deps.taskManager.remove(taskId)})+ const mediaMetaPath = getMediaMetaPath(task)+ if (mediaMetaPath) {+ await deps.mediaMetaStore?.remove(mediaMetaPath).catch((err) => {+ deps.log.warn({ err, taskId }, 'Failed to remove media metadata')+ })+ }+// Publish the removal through the coalescing publisher: the flush-time// snapshot no longer contains the deleted id, and handlePolledTasks does// not reconcile deletions, so this publication is the one thatdiff --git a/src/core/task/get-task-files.ts b/src/core/task/get-task-files.tsindex d9ca2fd9..13c91abb 100644--- a/src/core/task/get-task-files.ts+++ b/src/core/task/get-task-files.ts@@ -11,6 +11,8 @@ import type { TaskManager } from '@core/task/task-manager'import { relativizeTorrentPath } from '@shared/lib/path-ext'import type { DownloadTask, TaskFile } from '@shared/types/task'import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'+import type { MediaMetaStore } from './media-meta-store'+import { getMediaMetaPath } from './media-task-files'const log = getLogger('TaskFilesProvider')const ACTIVE_STATES = new Set<TaskStatus>([@@ -20,6 +22,7 @@ const ACTIVE_STATES = new Set<TaskStatus>([])interface Deps {+ mediaMetaStore?: Pick<MediaMetaStore, 'read'>db: Pick<MotrixDatabase, 'getTaskFiles'>taskManager: Pick<TaskManager, 'getById'>engine: Pick<EngineAdapter, 'getTaskFiles'>@@ -60,6 +63,11 @@ function toDisplayPath(physicalPath: string, task: DownloadTask): string {export function createGetTaskFilesHandler(deps: Deps) {return async function getTaskFiles(taskId: string): Promise<TaskFile[]> {const task = deps.taskManager.getById(taskId)+ const metaPath = task ? getMediaMetaPath(task) : undefined+ const mediaFiles = metaPath+ ? await deps.mediaMetaStore?.read(metaPath)+ : null+ if (mediaFiles) return mediaFilesconst base: TaskFile[] = deps.db.getTaskFiles(taskId).map((row) => ({index: row.fileIndex,path: task ? toDisplayPath(row.path, task) : row.path,diff --git a/src/core/task/media-meta-store.test.ts b/src/core/task/media-meta-store.test.tsnew file mode 100644index 00000000..ae1b6c21--- /dev/null+++ b/src/core/task/media-meta-store.test.ts@@ -0,0 +1,230 @@+import fs from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import type { SegmentPlan } from '@core/media/segment-plan'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import writeFileAtomic from 'write-file-atomic'+import { MediaMetaStoreImpl } from './media-meta-store'++vi.mock('write-file-atomic', async (importOriginal) => {+ const original = await importOriginal<{ default: typeof writeFileAtomic }>()+ return { default: vi.fn(original.default) }+})++const video: SegmentPlan = {+ container: 'fmp4',+ isComplete: true,+ init: { url: 'https://cdn.test/init.mp4?token=secret' },+ segments: [+ {+ index: 0,+ url: 'https://cdn.test/seg.mp4?token=secret',+ byteRange: { offset: 50, length: 100 },+ },+ ],+}+const completed = {+ index: 0,+ downloadedBytes: 20,+ totalBytes: 20,+ completed: true,+}++describe('MediaMetaStore', () => {+ let root: string+ let store: MediaMetaStoreImpl+ let metaPath: string++ beforeEach(async () => {+ vi.clearAllMocks()+ root = await fs.mkdtemp(path.join(tmpdir(), 'media-meta-'))+ store = new MediaMetaStoreImpl(path.join(root, 'media'))+ metaPath = await store.persist('task-1', {+ video,+ audio: { ...video, init: undefined },+ manifests: [+ {+ name: 'video.m3u8',+ url: 'https://cdn.test/video.m3u8',+ text: '#EXTM3U\nseg.mp4?token=secret\n',+ },+ ],+ })+ })++ afterEach(async () => {+ vi.useRealTimers()+ await store.remove(metaPath)+ await fs.rm(root, { recursive: true, force: true })+ })++ it('keeps original manifests and display metadata together in application storage', async () => {+ expect(metaPath).toBe(path.join(root, 'media', 'task-1', 'files.json'))+ expect(await fs.readdir(path.dirname(metaPath))).toEqual([+ 'files.json',+ 'video.m3u8',+ ])+ expect(+ await fs.readFile(path.join(path.dirname(metaPath), 'video.m3u8'), 'utf8')+ ).toContain('token=secret')+ expect(JSON.stringify(await store.read(metaPath))).not.toContain('secret')+ expect((await store.read(metaPath))?.map((f) => f.path)).toEqual([+ 'video/init-init.mp4',+ 'video/000001-seg.mp4',+ 'audio/000001-seg.mp4',+ ])+ if (process.platform !== 'win32') {+ expect((await fs.stat(metaPath)).mode & 0o777).toBe(0o600)+ expect((await fs.stat(path.dirname(metaPath))).mode & 0o777).toBe(0o700)+ }+ })++ it('returns live progress and saves it across store recreation without caching history', async () => {+ store.update(metaPath, 'video', completed)+ store.update(metaPath, 'audio', {+ ...completed,+ totalBytes: 100,+ downloadedBytes: 50,+ completed: false,+ })+ expect((await store.read(metaPath))?.[0]).toMatchObject({+ size: 20,+ progress: 1,+ })+ await store.release(metaPath)+ const restored = new MediaMetaStoreImpl(path.join(root, 'media'))+ expect((await restored.read(metaPath))?.[2]).toMatchObject({+ size: 100,+ completedBytes: 50,+ progress: 0.5,+ })+ await fs.unlink(metaPath)+ expect(await restored.read(metaPath)).toBeNull()+ })++ it('coalesces progress writes and flushes the final checkpoint', async () => {+ vi.useFakeTimers()+ vi.mocked(writeFileAtomic).mockClear()+ for (let i = 0; i < 100; i++) store.update(metaPath, 'video', completed)+ expect(writeFileAtomic).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(15_000)+ store.update(metaPath, 'audio', completed)+ await store.release(metaPath)+ expect(writeFileAtomic).toHaveBeenCalledTimes(2)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('coalesces checkpoints while a slow disk write is in flight', async () => {+ vi.useFakeTimers()+ vi.mocked(writeFileAtomic).mockClear()+ const gate = Promise.withResolvers<void>()+ vi.mocked(writeFileAtomic).mockImplementationOnce(() => gate.promise)+ for (let i = 1; i <= 4; i++) {+ store.update(metaPath, 'video', {+ ...completed,+ downloadedBytes: i,+ totalBytes: i,+ })+ await vi.advanceTimersByTimeAsync(15_000)+ }+ const release = store.release(metaPath)+ gate.resolve()+ await release+ expect(writeFileAtomic).toHaveBeenCalledTimes(2)+ const restored = new MediaMetaStoreImpl(path.join(root, 'media'))+ expect((await restored.read(metaPath))?.[0]).toMatchObject({+ size: 4,+ completedBytes: 4,+ })+ })++ it('drains pending writes before deletion and ignores late callbacks', async () => {+ store.update(metaPath, 'video', completed)+ const flush = store.release(metaPath)+ await store.remove(metaPath)+ await flush+ store.update(metaPath, 'video', completed)+ await store.release(metaPath)+ await store.remove(metaPath)+ await expect(fs.stat(path.dirname(metaPath))).rejects.toMatchObject({+ code: 'ENOENT',+ })+ expect(await fs.readdir(path.join(root, 'media'))).toEqual([])+ })++ it('does not overwrite metadata belonging to an existing task', async () => {+ await expect(store.persist('task-1', { video })).rejects.toMatchObject({+ code: 'EEXIST',+ })+ expect(await store.read(metaPath)).toHaveLength(3)+ })++ it('retains the latest snapshot after a transient final checkpoint failure so release can retry', async () => {+ store.update(metaPath, 'video', completed)+ vi.mocked(writeFileAtomic).mockRejectedValueOnce(new Error('ENOSPC'))+ await expect(store.release(metaPath)).rejects.toThrow('ENOSPC')+ expect((await store.read(metaPath))?.[0]).toMatchObject({ progress: 1 })+ await store.release(metaPath)+ const restored = new MediaMetaStoreImpl(path.join(root, 'media'))+ expect((await restored.read(metaPath))?.[0]).toMatchObject({ progress: 1 })+ })++ it('recovers orphaned metadata at startup while preserving every durable task', async () => {+ await store.release(metaPath)+ const removed = await store.persist('removed-task', { video })+ await store.release(removed)+ const partialDir = path.join(root, 'media', 'interrupted-create')+ await fs.mkdir(partialDir)+ await fs.writeFile(path.join(partialDir, 'video.m3u8'), '#EXTM3U')+ const restored = new MediaMetaStoreImpl(path.join(root, 'media'))+ await restored.pruneOrphans(['task-1'])+ expect(await fs.readdir(path.join(root, 'media'))).toEqual(['task-1'])+ expect(await restored.read(metaPath)).toHaveLength(3)+ })++ it('does not collect live metadata or follow directory links during recovery', async () => {+ const outside = path.join(root, 'outside')+ await fs.mkdir(outside)+ await fs.writeFile(path.join(outside, 'keep.txt'), 'keep')+ await fs.symlink(+ outside,+ path.join(root, 'media', 'linked-task'),+ 'junction'+ )+ await store.pruneOrphans([])+ expect(await store.read(metaPath)).toHaveLength(3)+ expect(await fs.readFile(path.join(outside, 'keep.txt'), 'utf8')).toBe(+ 'keep'+ )+ })++ it('uses the same cache identity for equivalent paths during reads and deletion', async () => {+ store.update(metaPath, 'video', completed)+ const alias = `${path.join(path.dirname(metaPath), 'child')}/../files.json`+ expect((await store.read(alias))?.[0]).toMatchObject({ progress: 1 })+ await store.remove(alias)+ await store.release(metaPath)+ await expect(fs.stat(metaPath)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('rejects paths outside its task directories and tolerates missing or malformed metadata', async () => {+ await expect(store.persist('../escape', { video })).rejects.toThrow(+ 'Invalid'+ )+ await expect(store.remove(root)).rejects.toThrow('Invalid')+ expect(await store.read(path.join(root, 'files.json'))).toBeNull()+ await store.release(metaPath)+ await fs.writeFile(metaPath, '{invalid')+ expect(await store.read(metaPath)).toBeNull()+ await fs.writeFile(+ metaPath,+ JSON.stringify({+ version: 1,+ video: [{ path: 'x', size: -1 }],+ audio: [],+ manifests: [],+ })+ )+ expect(await store.read(metaPath)).toBeNull()+ })+})diff --git a/src/core/task/media-meta-store.ts b/src/core/task/media-meta-store.tsnew file mode 100644index 00000000..cf463a03--- /dev/null+++ b/src/core/task/media-meta-store.ts@@ -0,0 +1,240 @@+import fs from 'node:fs/promises'+import path from 'node:path'+import type { SegmentFileProgress } from '@core/download/segment-downloader'+import { getLogger } from '@core/logger'+import type { SegmentPlan } from '@core/media/segment-plan'+import type { TaskFile } from '@shared/types/task'+import writeFileAtomic from 'write-file-atomic'+import { z } from 'zod'+import {+ createMediaTaskFiles,+ mediaFileSchema,+ toMediaTaskFiles,+ updateMediaTaskFile,+} from './media-task-files'++const log = getLogger('MediaMetaStore')+const CHECKPOINT_MS = 15_000+const metadataSchema = z.object({+ version: z.literal(1),+ video: z.array(mediaFileSchema),+ audio: z.array(mediaFileSchema),+ manifests: z.array(z.object({ file: z.string(), url: z.string() })),+})++export interface MediaManifest {+ name: 'master.m3u8' | 'video.m3u8' | 'audio.m3u8' | 'manifest.mpd'+ url: string+ text: string+}++export interface MediaMetadataInput {+ video: SegmentPlan+ audio?: SegmentPlan+ manifests?: MediaManifest[]+}++export interface MediaMetaStore {+ persist(taskId: string, input: MediaMetadataInput): Promise<string>+ read(metaPath: string): Promise<TaskFile[] | null>+ update(+ metaPath: string,+ stream: 'video' | 'audio',+ progress: SegmentFileProgress+ ): void+ release(metaPath: string): Promise<void>+ remove(metaPath: string): Promise<void>+}++interface ActiveMetadata {+ data: z.infer<typeof metadataSchema>+ pending: Promise<void>+ writing: boolean+ revision: number+ savedRevision: number+ timer?: ReturnType<typeof setTimeout>+ releasing: boolean+}++/** Central application metadata, independent of the user's output directory.+ * Only the returned path belongs in SQLite. Active progress is kept in memory+ * and checkpointed at most once per interval, plus once when the run settles.+ */+export class MediaMetaStoreImpl implements MediaMetaStore {+ private readonly active = new Map<string, ActiveMetadata>()++ constructor(private readonly baseDir: string) {}++ async persist(taskId: string, input: MediaMetadataInput): Promise<string> {+ if (!/^[a-zA-Z0-9_-]+$/.test(taskId))+ throw new Error('Invalid media task id')+ const dir = path.resolve(this.baseDir, taskId)+ const metaPath = path.join(dir, 'files.json')+ const data: ActiveMetadata['data'] = {+ version: 1,+ video: createMediaTaskFiles(input.video, 'video'),+ audio: input.audio ? createMediaTaskFiles(input.audio, 'audio') : [],+ manifests: (input.manifests ?? []).map(({ name, url }) => ({+ file: name,+ url,+ })),+ }+ // Task ids are unique. Refuse to overwrite an existing task's metadata.+ await fs.mkdir(this.baseDir, { recursive: true })+ await fs.mkdir(dir, { mode: 0o700 })+ try {+ for (const manifest of input.manifests ?? []) {+ await writeFileAtomic(path.join(dir, manifest.name), manifest.text, {+ mode: 0o600,+ })+ }+ await writeFileAtomic(metaPath, JSON.stringify(data), { mode: 0o600 })+ } catch (error) {+ await fs.rm(dir, { recursive: true, force: true }).catch(() => {})+ throw error+ }+ this.active.set(metaPath, {+ data,+ pending: Promise.resolve(),+ writing: false,+ revision: 0,+ savedRevision: 0,+ releasing: false,+ })+ return metaPath+ }++ async read(metaPath: string): Promise<TaskFile[] | null> {+ if (!this.owns(metaPath)) return null+ metaPath = path.resolve(metaPath)+ const entry = this.active.get(metaPath)+ if (entry)+ return toMediaTaskFiles([...entry.data.video, ...entry.data.audio])+ try {+ const data = metadataSchema.parse(+ JSON.parse(await fs.readFile(metaPath, 'utf8'))+ )+ return toMediaTaskFiles([...data.video, ...data.audio])+ } catch (error) {+ log.warn({ err: error, metaPath }, 'Media metadata unavailable')+ return null+ }+ }++ update(+ metaPath: string,+ stream: 'video' | 'audio',+ progress: SegmentFileProgress+ ): void {+ metaPath = path.resolve(metaPath)+ const entry = this.active.get(metaPath)+ if (!entry || entry.releasing) return+ updateMediaTaskFile(entry.data[stream], progress)+ entry.revision+++ if (!entry.timer) {+ entry.timer = setTimeout(() => {+ entry.timer = undefined+ void this.checkpoint(metaPath, entry).catch((err) => {+ log.warn({ err, metaPath }, 'Media progress checkpoint failed')+ })+ }, CHECKPOINT_MS)+ entry.timer.unref?.()+ }+ }++ async release(metaPath: string): Promise<void> {+ metaPath = path.resolve(metaPath)+ const entry = this.active.get(metaPath)+ if (!entry) return+ if (entry.releasing) return entry.pending+ entry.releasing = true+ clearTimeout(entry.timer)+ try {+ await this.checkpoint(metaPath, entry)+ } catch (error) {+ // The coordinator retries release in its finalizer. Keep the latest+ // progress readable until that retry instead of falling back to stale IO.+ entry.releasing = false+ entry.timer = undefined+ throw error+ }+ if (this.active.get(metaPath) === entry) this.active.delete(metaPath)+ }++ async remove(metaPath: string): Promise<void> {+ if (!this.owns(metaPath)) throw new Error('Invalid media metadata path')+ metaPath = path.resolve(metaPath)+ const entry = this.active.get(metaPath)+ // Detach before awaiting IO: late progress/release cannot recreate files.+ this.active.delete(metaPath)+ if (entry) {+ clearTimeout(entry.timer)+ await entry.pending.catch(() => {})+ }+ await fs.rm(path.dirname(metaPath), { recursive: true, force: true })+ }++ /** Run at startup, before admitting submissions. Use durable DB ids rather+ * than restored in-memory tasks: engine recovery may omit a persisted task.+ * Recovers crashes between metadata creation/task insertion or task deletion/+ * metadata cleanup, including cleanup that previously failed on the OS.+ */+ async pruneOrphans(retainedTaskIds: readonly string[]): Promise<void> {+ const retained = new Set(retainedTaskIds)+ let entries: string[]+ try {+ entries = await fs.readdir(this.baseDir)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw error+ }+ for (const id of entries) {+ if (retained.has(id) || !/^[a-zA-Z0-9_-]+$/.test(id)) continue+ const metaPath = path.resolve(this.baseDir, id, 'files.json')+ if (this.active.has(metaPath)) continue+ try {+ // Never follow a directory link while collecting metadata.+ if (!(await fs.lstat(path.dirname(metaPath))).isDirectory()) continue+ await this.remove(metaPath)+ } catch (err) {+ log.warn({ err, metaPath }, 'Orphan media metadata cleanup failed')+ }+ }+ }++ private checkpoint(metaPath: string, entry: ActiveMetadata): Promise<void> {+ if (entry.writing) return entry.pending+ if (entry.savedRevision === entry.revision) return Promise.resolve()+ entry.writing = true+ // At most one write plus the latest in-memory state. Never queue a full+ // serialized snapshot every 15s while a slow filesystem is still busy.+ entry.pending = (async () => {+ do {+ const revision = entry.revision+ await writeFileAtomic(metaPath, JSON.stringify(entry.data), {+ mode: 0o600,+ })+ entry.savedRevision = revision+ } while (+ this.active.get(metaPath) === entry &&+ entry.savedRevision !== entry.revision+ )+ })().finally(() => {+ entry.writing = false+ })+ return entry.pending+ }++ private owns(metaPath: string): boolean {+ const relative = path.relative(+ path.resolve(this.baseDir),+ path.resolve(metaPath)+ )+ const parts = relative.split(path.sep)+ return (+ parts.length === 2 &&+ /^[a-zA-Z0-9_-]+$/.test(parts[0]) &&+ parts[1] === 'files.json'+ )+ }+}diff --git a/src/core/task/media-mux-e2e.test.ts b/src/core/task/media-mux-e2e.test.tsindex fb2ab4cc..0c342357 100644--- a/src/core/task/media-mux-e2e.test.ts+++ b/src/core/task/media-mux-e2e.test.ts@@ -29,6 +29,7 @@ import { SegmentDownloader } from '../download/segment-downloader'import { FfmpegService } from '../ffmpeg/ffmpeg-service'import { assembleSegments } from '../media/segment-assembler'import { SegmentDecryptor } from '../media/segment-decryptor'+import { MediaMetaStoreImpl } from './media-meta-store'import { type MediaJob, MediaTaskCoordinator } from './media-task-coordinator'import { TaskManager } from './task-manager'@@ -135,6 +136,7 @@ describe.skipIf(const segmentClient = new Aria2SegmentClient(rpc, adapter)const taskManager = new TaskManager()const coordinator = new MediaTaskCoordinator({+ mediaMetaStore: new MediaMetaStoreImpl(path.join(outRoot, 'metadata')),taskManager,activityRecorder: NOOP_TASK_ACTIVITY_RECORDER,eventBus: { emit() {} },diff --git a/src/core/task/media-task-coordinator.test.ts b/src/core/task/media-task-coordinator.test.tsindex 2c3a8b6a..9e46051c 100644--- a/src/core/task/media-task-coordinator.test.ts+++ b/src/core/task/media-task-coordinator.test.ts@@ -1,5 +1,8 @@import fs from 'node:fs'-import type { SegmentProgress } from '@core/download/segment-downloader'+import type {+ SegmentFileProgress,+ SegmentProgress,+} from '@core/download/segment-downloader'import { Events } from '@shared/protocol/events'import type { DownloadTask } from '@shared/types/task'import {@@ -8,9 +11,11 @@ import {TaskStatus,TransitionPhase,} from '@shared/types/task'+import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { MediaCoordinatorDeps, MediaJob } from './media-task-coordinator'import { MediaTaskCoordinator } from './media-task-coordinator'+import { getMediaMetaPath } from './media-task-files'import { TaskManager } from './task-manager'// ---------------------------------------------------------------------------@@ -24,6 +29,7 @@ function makeDownloaderFake(opts?: {hang?: boolean/** Progress sequence to emit; defaults to a byte-less 0.5 → 1 fraction. */report?: SegmentProgress[]+ fileReports?: SegmentFileProgress[]/** Active segment gids this stream reports (Bug B). */activeGids?: string[]error?: Error@@ -35,7 +41,8 @@ function makeDownloaderFake(opts?: {async (_plan: unknown,_headers: unknown,- onProgress: (p: SegmentProgress) => void+ onProgress: (p: SegmentProgress) => void,+ onFileProgress?: (p: SegmentFileProgress) => void): Promise<{ initPath?: string; partPaths: string[] }> => {if (opts?.error) throw opts.errorif (opts?.hang) {@@ -49,6 +56,7 @@ function makeDownloaderFake(opts?: {})}+ for (const p of opts?.fileReports ?? []) onFileProgress?.(p)const reports = opts?.report ?? [{ fraction: 0.5, downloadedBytes: 0, totalBytes: 0 },{ fraction: 1, downloadedBytes: 0, totalBytes: 0 },@@ -142,6 +150,7 @@ function makeDeps(overrides?: Partial<MediaCoordinatorDeps>): {const decryptorFake = makeDecryptorFake()const deps: MediaCoordinatorDeps = {+ mediaMetaStore: makeMediaMetaStoreStub(),taskManager,activityRecorder: {recordSubmitted: vi.fn(),@@ -230,6 +239,103 @@ describe('MediaTaskCoordinator.start', () => {vi.restoreAllMocks()})+ it('registers every queued video/audio segment before downloading', async () => {+ const { deps, taskManager } = makeDeps({+ makeDownloader: () => makeDownloaderFake({ hang: true }) as never,+ })+ const coordinator = new MediaTaskCoordinator(deps)+ const { taskId } = await coordinator.submit({+ ...baseJob(),+ video: { ...videoOnlyPlan(), init: { url: 'https://cdn/init.mp4' } },+ audio: {+ ...videoOnlyPlan(),+ segments: [{ index: 0, url: 'https://cdn/audio.aac' }],+ },+ })+ const task = taskManager.getById(taskId)+ expect(task).toBeDefined()+ expect(getMediaMetaPath(task as DownloadTask)).toBe(+ `/metadata/media/${taskId}/files.json`+ )+ expect(deps.mediaMetaStore.persist).toHaveBeenCalledWith(+ taskId,+ expect.objectContaining({+ video: expect.objectContaining({+ init: { url: 'https://cdn/init.mp4' },+ }),+ audio: expect.objectContaining({+ segments: [{ index: 0, url: 'https://cdn/audio.aac' }],+ }),+ })+ )+ expect(JSON.stringify(task)).not.toContain('mediaFiles')+ await coordinator.stopAndDrain()+ })++ it('keeps a ten-thousand-segment task small enough for database snapshots', async () => {+ const { deps, taskManager } = makeDeps({+ makeDownloader: () => makeDownloaderFake({ hang: true }) as never,+ })+ const coordinator = new MediaTaskCoordinator(deps)+ const job = baseJob()+ job.video.segments = Array.from({ length: 10_000 }, (_, index) => ({+ index,+ url: `https://cdn/segment-${index}.ts`,+ }))+ const { taskId } = await coordinator.submit(job)+ const task = taskManager.getById(taskId)+ expect(task?.instances[0].payload).toEqual({+ mediaMetaPath: `/metadata/media/${taskId}/files.json`,+ })+ expect(JSON.stringify(task).length).toBeLessThan(4_000)+ expect(JSON.stringify(task)).not.toContain('segment-9999')+ await coordinator.stopAndDrain()+ })++ it('removes new metadata if the parent task cannot be persisted', async () => {+ const { deps, taskManager } = makeDeps({+ parentTaskCreated: vi.fn(async () => {+ throw new Error('database busy')+ }),+ })+ const unlink = vi.spyOn(fs.promises, 'unlink').mockResolvedValue(undefined)+ await expect(+ new MediaTaskCoordinator(deps).start(baseJob())+ ).rejects.toThrow('database busy')+ expect(deps.mediaMetaStore.remove).toHaveBeenCalledWith(+ '/metadata/media/stable-task-id/files.json'+ )+ expect(unlink).toHaveBeenCalledWith('/save/video.mp4.motrix')+ expect(taskManager.getAll()).toEqual([])+ })++ it('persists downloaded file metadata after muxing and temporary segment cleanup', async () => {+ const { deps, taskManager } = makeDeps({+ makeDownloader: () =>+ makeDownloaderFake({+ fileReports: [+ { index: 0, downloadedBytes: 64, totalBytes: 64, completed: true },+ ],+ }) as never,+ // Exercise the production transition path that replaces task snapshots.+ recordTransition: vi.fn(),+ })+ const coordinator = new MediaTaskCoordinator(deps)+ const { taskId } = await coordinator.start(baseJob())+ expect(taskManager.getById(taskId)?.status).toBe(TaskStatus.Completed)+ const saved = vi.mocked(deps.persist).mock.calls.at(-1)?.[0]+ expect(saved).toBeDefined()+ const metaPath = getMediaMetaPath(saved as DownloadTask)+ expect(deps.mediaMetaStore.update).toHaveBeenCalledWith(metaPath, 'video', {+ index: 0,+ downloadedBytes: 64,+ totalBytes: 64,+ completed: true,+ })+ expect(deps.mediaMetaStore.release).toHaveBeenCalledWith(metaPath)+ expect(JSON.stringify(saved)).not.toContain('mediaFiles')+ })+it.each(['segment', 'init', 'key'])('rejects an invalid %s before saving or creating directories',async (kind) => {@@ -540,6 +646,61 @@ describe('MediaTaskCoordinator.start', () => {expect(task?.errorMessage).toBe('mux-aborted')})+ it.each(['metadata', 'ffmpeg-location'] as const)(+ 'does not resume media work after cancellation during %s IO',+ async (phase) => {+ const gate = Promise.withResolvers<void>()+ const entered = Promise.withResolvers<void>()+ const { deps, taskManager, assembleFake, ffmpegFakes } = makeDeps()+ if (phase === 'metadata') {+ vi.mocked(deps.mediaMetaStore.release).mockImplementation(async () => {+ entered.resolve()+ await gate.promise+ })+ } else {+ vi.mocked(deps.resolveFfmpegBinaryPath).mockImplementation(async () => {+ entered.resolve()+ await gate.promise+ return '/usr/bin/ffmpeg'+ })+ }+ const coordinator = new MediaTaskCoordinator(deps)+ const run = coordinator.start(baseJob()).catch((error) => error)+ await entered.promise+ const cancel = coordinator.cancel('stable-task-id')+ gate.resolve()+ await cancel+ await run+ expect(taskManager.getById('stable-task-id')?.status).toBe(+ TaskStatus.Error+ )+ expect(+ ffmpegFakes.every((ffmpeg) => ffmpeg.run.mock.calls.length === 0)+ ).toBe(true)+ expect(fs.promises.rename).not.toHaveBeenCalled()+ if (phase === 'metadata') expect(assembleFake).not.toHaveBeenCalled()+ }+ )++ it('does not publish a queued task or retain metadata when temporary storage is unavailable', async () => {+ const { deps, taskManager } = makeDeps({+ mkdtemp: vi.fn(async () => {+ throw new Error('ENOSPC')+ }),+ parentTaskCreated: vi.fn(async (_task, persist) => persist()),+ })+ const unlink = vi.spyOn(fs.promises, 'unlink').mockResolvedValue(undefined)+ await expect(+ new MediaTaskCoordinator(deps).submit(baseJob())+ ).rejects.toThrow('ENOSPC')+ expect(taskManager.getAll()).toEqual([])+ expect(deps.persist).not.toHaveBeenCalled()+ expect(deps.mediaMetaStore.remove).toHaveBeenCalledWith(+ '/metadata/media/stable-task-id/files.json'+ )+ expect(unlink).toHaveBeenCalledWith('/save/video.mp4.motrix')+ })+it('cancel writes the terminal occurrence with cause "user-cancel" (not "media") and dispatches it', async () => {const blockingFfmpeg = makeBlockingFfmpegFake()const persistTaskWithOccurrence = vi.fn(async () => {})diff --git a/src/core/task/media-task-coordinator.ts b/src/core/task/media-task-coordinator.tsindex 64acfdbe..801867fb 100644--- a/src/core/task/media-task-coordinator.ts+++ b/src/core/task/media-task-coordinator.ts@@ -3,6 +3,7 @@ import os from 'node:os'import path from 'node:path'import type {SegmentDownloader,+ SegmentFileProgress,SegmentProgress,} from '@core/download/segment-downloader'import {@@ -35,6 +36,7 @@ import {} from './actions/shared'import { applyTerminalTransition } from './apply-terminal-transition'import type { CreateRequestReceipt } from './create-request-id'+import type { MediaManifest, MediaMetaStore } from './media-meta-store'import type { OccurrenceDispatcher } from './occurrences/occurrence-dispatcher'import { toTempPath } from './paths'import { admitHttpSource } from './source-admission'@@ -56,6 +58,7 @@ export interface MediaJob {taskId?: stringvideo: SegmentPlanaudio?: SegmentPlan+ manifests?: MediaManifest[]headers: Record<string, string>saveDir: stringfinalName: string@@ -66,6 +69,7 @@ export interface MediaJob {}export interface MediaCoordinatorDeps {+ mediaMetaStore: MediaMetaStoretaskManager: TaskManageractivityRecorder: TaskActivityRecordereventBus: { emit(event: string, payload: unknown): void }@@ -138,6 +142,7 @@ export interface MediaCoordinatorDeps {// ---------------------------------------------------------------------------interface RunState {+ mediaMetaPath: stringdownloaders: SegmentDownloader[]ffmpeg: FfmpegService | nulltmpDir: string@@ -335,6 +340,15 @@ export class MediaTaskCoordinator {))+ let mediaMetaPath: string+ try {+ mediaMetaPath = await this.deps.mediaMetaStore.persist(taskId, job)+ } catch (error) {+ await fs.promises.unlink(diskPath).catch(() => {})+ throw error+ }+ instances[0].payload.mediaMetaPath = mediaMetaPath+const task = this.makeTask(taskId,job,@@ -344,33 +358,46 @@ export class MediaTaskCoordinator {instances,now)- if (this.deps.parentTaskCreated) {- await this.deps.parentTaskCreated(task, () => this.deps.persist(task))- }- this.deps.taskManager.add(task)- this.deps.activityRecorder.recordSubmitted({- taskId: task.id,- occurredAt: task.createdAt,- })- this.emitUpdate(true)-- // Create temp dir+ // Prepare task-owned IO before publication. Once visible, every task must+ // already have cancellation ownership; a failed temp-directory setup must+ // not leave a durable queued task or metadata without a runnable pipeline.const mkdtemp = this.deps.mkdtemp ?? defaultMkdtemp- const tmpDir = await mkdtemp()+ let tmpDir: string | undefined+ try {+ tmpDir = await mkdtemp()+ await fs.promises.mkdir(path.join(tmpDir, 'video'), { recursive: true })+ if (job.audio) {+ await fs.promises.mkdir(path.join(tmpDir, 'audio'), { recursive: true })+ }+ if (this.deps.parentTaskCreated) {+ await this.deps.parentTaskCreated(task, () => this.deps.persist(task))+ }+ } catch (error) {+ await this.deps.mediaMetaStore.remove(mediaMetaPath).catch(() => {})+ await fs.promises.unlink(diskPath).catch(() => {})+ if (tmpDir) await cleanDir(tmpDir).catch(() => {})+ throw error+ }// Per-stream subdirs so segment filenames (000000.seg…) never collide.const videoDir = path.join(tmpDir, 'video')const audioDir = path.join(tmpDir, 'audio')- await fs.promises.mkdir(videoDir, { recursive: true })// Register run state for cancel supportconst state: RunState = {+ mediaMetaPath,downloaders: [],ffmpeg: null,tmpDir,cancelled: false,}this.running.set(taskId, state)+ this.deps.taskManager.add(task)+ this.deps.activityRecorder.recordSubmitted({+ taskId: task.id,+ occurredAt: task.createdAt,+ })+ this.emitUpdate(true)onAccepted?.()// A shutdown can race a submit while the latter is crossing its durable@@ -384,8 +411,14 @@ export class MediaTaskCoordinator {// When a genuine (non-cancel) failure preserves the temp inputs for// inspection, this flips true and the finally block skips cleanDir.let keepTmp = false+ const assertActive = () => {+ if (state.cancelled || !this.deps.taskManager.getById(taskId)) {+ throw new Error('mux-aborted')+ }+ }try {+ assertActive()// -----------------------------------------------------------------------// Phase: downloading// -----------------------------------------------------------------------@@ -408,6 +441,7 @@ export class MediaTaskCoordinator {} else {this.updateTask(taskId, toDownloading)}+ assertActive()// Total segment count across video + audio — the fallback for aggregate// progress when byte counts are not yet known (e.g. before the first@@ -487,6 +521,7 @@ export class MediaTaskCoordinator {segTotal: number) =>(p: SegmentProgress) => {+ if (state.cancelled) returnstreamBytes.downloaded = p.downloadedBytesstreamBytes.total = p.totalBytesstreamBytes.completed = Math.round(p.fraction * segTotal)@@ -504,7 +539,6 @@ export class MediaTaskCoordinator {const audioPlan = job.audiolet audioDownloader: SegmentDownloader | null = nullif (audioPlan) {- await fs.promises.mkdir(audioDir, { recursive: true })audioDownloader = this.deps.makeDownloader(audioDir)state.downloaders.push(audioDownloader)}@@ -521,10 +555,18 @@ export class MediaTaskCoordinator {})}+ // File progress stays outside the task aggregate and SQLite snapshots.+ const onFileProgress =+ (stream: 'video' | 'audio') => (p: SegmentFileProgress) => {+ if (state.cancelled) return+ this.deps.mediaMetaStore.update(mediaMetaPath, stream, p)+ }+const runVideo = videoDownloader.run(job.video,job.headers,- onStreamProgress(videoBytes, TaskInstancePhase.HlsSegment, videoTotal)+ onStreamProgress(videoBytes, TaskInstancePhase.HlsSegment, videoTotal),+ onFileProgress('video'))const runAudio: Promise<{@@ -539,20 +581,25 @@ export class MediaTaskCoordinator {audioBytes,TaskInstancePhase.HlsAudio,audioTotal- )+ ),+ onFileProgress('audio')): Promise.resolve(null)// Concurrent download; decrypt/assemble below already run only after both// streams finish, so awaiting both together is safe.const [videoResult, audioResult] = await Promise.all([runVideo, runAudio])+ await this.releaseMetadata(mediaMetaPath)+ assertActive()// -----------------------------------------------------------------------// Phase: decrypt// -----------------------------------------------------------------------await decryptPlan(job.video, videoResult, this.deps.decryptor)+ assertActive()if (job.audio && audioResult) {await decryptPlan(job.audio, audioResult, this.deps.decryptor)+ assertActive()}// -----------------------------------------------------------------------@@ -569,6 +616,7 @@ export class MediaTaskCoordinator {initPath: videoResult.initPath,partPaths: videoResult.partPaths,})+ assertActive()let audioAssembled: string | undefinedif (job.audio && audioResult) {@@ -579,6 +627,7 @@ export class MediaTaskCoordinator {initPath: audioResult.initPath,partPaths: audioResult.partPaths,})+ assertActive()}// -----------------------------------------------------------------------@@ -598,6 +647,7 @@ export class MediaTaskCoordinator {// case the user deleted it during a long download — ffmpeg does NOT// create its output's parent dir and would ENOENT after a full download.await fs.promises.mkdir(job.saveDir, { recursive: true })+ assertActive()// DIAGNOSTIC: inspect the assembled inputs right before mux. ffmpeg// exit 234 (EINVAL) means a mapped stream type is absent from an input;@@ -612,10 +662,12 @@ export class MediaTaskCoordinator {'mux inputs before ffmpeg')+ assertActive()const ffmpeg = this.deps.makeFfmpeg()state.ffmpeg = ffmpegconst ffmpegBinaryPath = await this.deps.resolveFfmpegBinaryPath()+ assertActive()if (!ffmpegBinaryPath) {throw new Error('mux-failed: ffmpeg executable is unavailable')}@@ -647,6 +699,7 @@ export class MediaTaskCoordinator {)state.ffmpeg = null+ assertActive()// -----------------------------------------------------------------------// Phase: finalizing → Completed@@ -655,6 +708,7 @@ export class MediaTaskCoordinator {taskId,(t) => {t.progress = 1+ assertActive()Object.assign(t, applyTerminalTransition(t, TaskStatus.Finalizing))setTaskTransitionPhase(t, TransitionPhase.Renaming)},@@ -665,7 +719,9 @@ export class MediaTaskCoordinator {// Same-dir rename `.motrix` → final (atomic; mirrors finalizeHttp). Must// land BEFORE the Completed flip: the bridge emits $/task/completed with// finalPath off that status change and the extension may open it at once.+ assertActive()await fs.promises.rename(diskPath, finalPath)+ assertActive()const completedAt = this.now()await this.transition(@@ -725,6 +781,7 @@ export class MediaTaskCoordinator {}throw err} finally {+ await this.releaseMetadata(mediaMetaPath)if (!keepTmp) {await cleanDir(tmpDir).catch(() => {})}@@ -734,6 +791,12 @@ export class MediaTaskCoordinator {return { taskId }}+ private async releaseMetadata(metaPath: string): Promise<void> {+ await this.deps.mediaMetaStore.release(metaPath).catch((err) => {+ log.warn({ err, metaPath }, 'Failed to save media file progress')+ })+ }+/*** Close the submit gate synchronously, cancel every coordinator-owned media* process, and wait only for those background runs to settle. Idempotent.@@ -768,6 +831,8 @@ export class MediaTaskCoordinator {this.running.delete(taskId)+ await this.releaseMetadata(state.mediaMetaPath)+await this.transition(taskId,(t) => {diff --git a/src/core/task/media-task-files.test.ts b/src/core/task/media-task-files.test.tsnew file mode 100644index 00000000..72617e3d--- /dev/null+++ b/src/core/task/media-task-files.test.ts@@ -0,0 +1,80 @@+import type { SegmentPlan } from '@core/media/segment-plan'+import { describe, expect, it } from 'vitest'+import {+ createMediaTaskFiles,+ toMediaTaskFiles,+ updateMediaTaskFile,+} from './media-task-files'++const plan: SegmentPlan = {+ container: 'fmp4',+ isComplete: true,+ init: { url: 'https://cdn.example/init.mp4?token=secret' },+ segments: [+ {+ index: 0,+ url: 'https://cdn.example/video.mp4?token=secret',+ byteRange: { offset: 100, length: 50 },+ },+ {+ index: 1,+ url: 'https://cdn.example/video.mp4?token=secret',+ byteRange: { offset: 150, length: 60 },+ },+ ],+}++describe('media task files', () => {+ it('lists every init and segment in stream order with unique indices and no URL credentials', () => {+ const files = toMediaTaskFiles([+ ...createMediaTaskFiles(plan, 'video'),+ ...createMediaTaskFiles({ ...plan, init: undefined }, 'audio'),+ ])+ expect(files?.map((file) => file.path)).toEqual([+ 'video/init-init.mp4',+ 'video/000001-video.mp4',+ 'video/000002-video.mp4',+ 'audio/000001-video.mp4',+ 'audio/000002-video.mp4',+ ])+ expect(files?.map((file) => file.index)).toEqual([0, 1, 2, 3, 4])+ expect(files?.map((file) => file.size)).toEqual([0, 50, 60, 50, 60])+ expect(files?.every((file) => file.selected && file.progress === 0)).toBe(+ true+ )+ expect(JSON.stringify(files)).not.toContain('secret')+ })++ it('retains stream-specific progress in metadata and keeps unknown-size completions at 100%', () => {+ const video = createMediaTaskFiles(plan, 'video')+ const audio = createMediaTaskFiles({ ...plan, init: undefined }, 'audio')+ updateMediaTaskFile(video, {+ index: 0,+ downloadedBytes: 0,+ totalBytes: 0,+ completed: true,+ })+ updateMediaTaskFile(audio, {+ index: 1,+ downloadedBytes: 30,+ totalBytes: 60,+ completed: false,+ })+ const files = toMediaTaskFiles([...video, ...audio])+ expect(files?.[0]).toMatchObject({ size: 0, progress: 1 })+ expect(files?.[2]).toMatchObject({ completedBytes: 0, progress: 0 })+ expect(files?.[4]).toMatchObject({ completedBytes: 30, progress: 0.5 })++ updateMediaTaskFile(audio, {+ index: 1,+ downloadedBytes: 0,+ totalBytes: 0,+ completed: false,+ })+ expect(toMediaTaskFiles(audio)[1]).toMatchObject({+ size: 60,+ completedBytes: 0,+ progress: 0,+ })+ })+})diff --git a/src/core/task/media-task-files.ts b/src/core/task/media-task-files.tsnew file mode 100644index 00000000..55986639--- /dev/null+++ b/src/core/task/media-task-files.ts@@ -0,0 +1,67 @@+import type { SegmentFileProgress } from '@core/download/segment-downloader'+import type { SegmentPlan } from '@core/media/segment-plan'+import {+ type DownloadTask,+ type TaskFile,+ TaskInstancePhase,+} from '@shared/types/task'+import { z } from 'zod'++// Display metadata only; source manifests live in the central media store.+export const mediaFileSchema = z.object({+ path: z.string(),+ size: z.number().finite().nonnegative(),+ completedBytes: z.number().finite().nonnegative(),+ progress: z.number().min(0).max(1),+})+export type MediaFile = z.infer<typeof mediaFileSchema>++export function createMediaTaskFiles(+ plan: SegmentPlan,+ stream: 'video' | 'audio'+): MediaFile[] {+ const parts = plan.init ? [plan.init, ...plan.segments] : plan.segments+ return parts.map((part, index) => {+ const name = new URL(part.url).pathname.split('/').at(-1) || 'segment'+ const order =+ plan.init && index === 0+ ? 'init'+ : String(index + (plan.init ? 0 : 1)).padStart(6, '0')+ return {+ path: `${stream}/${order}-${name}`,+ size: part.byteRange?.length ?? 0,+ completedBytes: 0,+ progress: 0,+ }+ })+}++export function updateMediaTaskFile(+ files: MediaFile[],+ update: SegmentFileProgress+): void {+ const file = files[update.index]+ if (!file) return+ const size = update.totalBytes || file.size+ files[update.index] = {+ ...file,+ size,+ completedBytes: update.completed ? size : update.downloadedBytes,+ progress: update.completed+ ? 1+ : size > 0+ ? Math.min(update.downloadedBytes / size, 1)+ : 0,+ } satisfies MediaFile+}++export function toMediaTaskFiles(files: MediaFile[]): TaskFile[] {+ return files.map((file, index) => ({ ...file, index, selected: true }))+}++export function getMediaMetaPath(task: DownloadTask): string | undefined {+ const value = task.instances?.find(+ (instance) => instance.phase === TaskInstancePhase.HlsSegment+ )?.payload.mediaMetaPath+ return typeof value === 'string' ? value : undefined+}diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.tsindex 89f49cb3..a1dabd04 100644--- a/src/main/bridge/bootstrap-lifecycle.test.ts+++ b/src/main/bridge/bootstrap-lifecycle.test.ts@@ -29,6 +29,7 @@ import {makeDirectSubmit,makeExtensionContext,} from '@test-utils/bridge-receiver'+import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {computeManifestPaths,@@ -144,6 +145,7 @@ function args(): Parameters<typeof bootstrapBridge>[0] {},ffmpegBinaryPath: null,taskManager: {} as never,+ mediaMetaStore: makeMediaMetaStoreStub(),segmentAria2: {} as never,tmpRoot: '/tmp/media',persistTask: vi.fn(async () => {}),diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex ea05b9ca..1487ec3b 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -439,6 +439,7 @@ export async function bootstrapBridge(args: {* threaded through BridgeReceiver into the MediaTaskCoordinator. */publishTaskUpdate: () => voidpublishTaskUpdateNow: () => void+ mediaMetaStore: BridgeReceiverDeps['mediaMetaStore']taskManager: BridgeReceiverDeps['taskManager']segmentAria2: BridgeReceiverDeps['segmentAria2']tmpRoot: string@@ -592,6 +593,7 @@ export async function bootstrapBridge(args: {args.pluginHost)const receiver = new BridgeReceiver({+ mediaMetaStore: args.mediaMetaStore,getDefaultSaveDir: args.getDefaultSaveDir,pickName: (saveDir, desired) =>args.finalNamePicker.pick(saveDir, desired),diff --git a/src/main/index.ts b/src/main/index.tsindex 1e848bd3..b2189710 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -91,6 +91,7 @@ import { handleCreateTask } from '@core/task/create-task-handler'import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'import { FileCleanupServiceImpl } from '@core/task/file-cleanup-service'import { FinalNamePickerImpl } from '@core/task/final-name-picker'+import { MediaMetaStoreImpl } from '@core/task/media-meta-store'import {hasEngineTaskDelta,mergeEngineTask,@@ -442,6 +443,9 @@ const finalNamePicker = new FinalNamePickerImpl({const torrentMetaStore = new TorrentMetaStoreImpl(path.join(platform.userDataDir, 'torrents'))+const mediaMetaStore = new MediaMetaStoreImpl(+ path.join(platform.userDataDir, 'media')+)const fileCleanupService = new FileCleanupServiceImpl({removePathRecursive,})@@ -1759,6 +1763,10 @@ async function initializeMainProcess(): Promise<void> {)motrixDb.init()+ await mediaMetaStore+ .pruneOrphans(motrixDb.getAllTasks().map(({ task }) => task.motrixId))+ .catch((err) => log.warn({ err }, 'Media metadata recovery failed'))+const activityEnvironment = taskInspectorActivityEnvironment(process.env)const activeTaskInspectorActivityRuntime = new TaskInspectorActivityRuntime(new TaskInspectorActivityStore(motrixDb.database),@@ -2357,6 +2365,7 @@ async function initializeMainProcess(): Promise<void> {adapter,log,fileCleanupService,+ mediaMetaStore,torrentMetaStore,eventBus,db: motrixDb,@@ -2435,6 +2444,7 @@ async function initializeMainProcess(): Promise<void> {// mediaTmpDir / mediaTmpRoot were computed once at bootstrap (above) so// SessionManager.restore() and the poll loop share the exact same root.return bootstrapBridge({+ mediaMetaStore,getMainWindow: () => windowManager?.get('main') ?? null,motrixVersion: app.getVersion(),ffmpegAvailable: ff.available,@@ -2590,6 +2600,7 @@ async function initializeMainProcess(): Promise<void> {})const disposeCommandHandlers = registerCommandHandlers({+ mediaMetaStore,cliToolService,supervisor,dnsFallback: { reset: () => dnsFallbackConsumer?.reset() },@@ -2667,6 +2678,7 @@ async function initializeMainProcess(): Promise<void> {overlayDir,})const disposeQueryHandlers = registerQueryHandlers({+ mediaMetaStore,cliToolService,taskManager,statsAggregator,diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex a8b5b067..281834e2 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -16,6 +16,7 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'import { makeDownloadTask } from '@test-utils/task'import { directTaskUpdatePublication } from '@test-utils/task-update'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -206,6 +207,7 @@ function fakeCtx() {finalNamePicker: {pick: vi.fn(async (_dir: string, name: string) => name),},+ mediaMetaStore: makeMediaMetaStoreStub(),torrentMetaStore: {persist: vi.fn(async () => '/tmp/x.torrent'),read: vi.fn(),diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex b383aaa2..700b02fd 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -74,6 +74,7 @@ import {import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'import type { FileCleanupService } from '@core/task/file-cleanup-service'import type { FinalNamePicker } from '@core/task/final-name-picker'+import type { MediaMetaStore } from '@core/task/media-meta-store'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'import {admitTaskCreateRequest,@@ -188,6 +189,7 @@ export interface CommandContext {trackerManager: TrackerManagercontextStore: ContextStorefinalNamePicker: FinalNamePicker+ mediaMetaStore: MediaMetaStoretorrentMetaStore: TorrentMetaStorefileCleanupService: FileCleanupServiceeventBus: EventBus@@ -279,6 +281,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {trackerManager,contextStore,finalNamePicker,+ mediaMetaStore,torrentMetaStore,fileCleanupService,eventBus,@@ -444,6 +447,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {adapter,log,fileCleanupService,+ mediaMetaStore,torrentMetaStore,eventBus,db: motrixDatabase,diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.tsindex 3b84f8a9..6f86a10f 100644--- a/src/main/ipc/queries.ts+++ b/src/main/ipc/queries.ts@@ -30,6 +30,7 @@ import type {} from '@core/stats'import { createGetTaskPeersHandler } from '@core/task/get-task-peers'import { createGetTaskPiecesHandler } from '@core/task/get-task-pieces'+import type { MediaMetaStore } from '@core/task/media-meta-store'import { slimTasksForBroadcast } from '@core/task/slim-task-for-broadcast'import type { TaskManager } from '@core/task/task-manager'import type { TrackerManager } from '@core/tracker'@@ -78,6 +79,7 @@ export interface QueryContext {natManager: NatManagertrackerManager: TrackerManagerengineAdapter: EngineAdapter+ mediaMetaStore: MediaMetaStoremotrixDatabase: MotrixDatabasegeoipManager: GeoIPManagerpluginRegistry: PluginRegistry@@ -214,6 +216,7 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {[Queries.GetSpeedLimitState]: async () => speedLimitController.getState(),[Queries.GetTaskFiles]: createGetTaskFilesHandler({+ mediaMetaStore: ctx.mediaMetaStore,db: motrixDatabase,taskManager,engine: engineAdapter,diff --git a/src/main/ipc/queries/get-task-files.test.ts b/src/main/ipc/queries/get-task-files.test.tsindex 139debc6..6bfc551f 100644--- a/src/main/ipc/queries/get-task-files.test.ts+++ b/src/main/ipc/queries/get-task-files.test.ts@@ -21,6 +21,94 @@ const mkTask = (over: Partial<DownloadTask> = {}): DownloadTask =>})describe('getTaskFiles handler', () => {+ it.each([+ TaskStatus.Downloading,+ TaskStatus.Paused,+ TaskStatus.Error,+ TaskStatus.Completed,+ ])(+ 'returns retained media segments while %s without querying a parent engine GID',+ async (status) => {+ const task = mkTask({+ kind: TaskKind.Hls,+ type: TaskType.Http,+ engineTaskId: '',+ status,+ })+ task.instances = [+ {+ instanceId: 'video',+ motrixId: task.id,+ gid: null,+ phase: TaskInstancePhase.HlsSegment,+ status,+ progress: 0,+ totalBytes: 0,+ downloadedBytes: 0,+ uploadedBytes: 0,+ diskPath: '',+ transitionPhase: TransitionPhase.Idle,+ uris: [],+ uriHash: null,+ payload: {},+ createdAt: 0,+ updatedAt: 0,+ },+ ]+ task.instances[0].payload.mediaMetaPath = '/metadata/media/t1/files.json'+ const files = [+ {+ path: 'video/000001-first.ts',+ size: 100,+ completedBytes: 100,+ progress: 1,+ },+ {+ path: 'video/000002-second.ts',+ size: 0,+ completedBytes: 0,+ progress: 0,+ },+ ]+ const mediaMetaStore = {+ read: vi.fn(async () =>+ files.map((file, index) => ({ ...file, index, selected: true }))+ ),+ }+ const db = { getTaskFiles: vi.fn(() => []) }+ const engine = { getTaskFiles: vi.fn() }+ const handler = createGetTaskFilesHandler({+ mediaMetaStore,+ db,+ engine,+ taskManager: { getById: () => task },+ })+ expect(await handler(task.id)).toEqual([+ {+ index: 0,+ path: 'video/000001-first.ts',+ size: 100,+ completedBytes: 100,+ progress: 1,+ selected: true,+ },+ {+ index: 1,+ path: 'video/000002-second.ts',+ size: 0,+ completedBytes: 0,+ progress: 0,+ selected: true,+ },+ ])+ expect(mediaMetaStore.read).toHaveBeenCalledWith(+ '/metadata/media/t1/files.json'+ )+ expect(db.getTaskFiles).not.toHaveBeenCalled()+ expect(engine.getTaskFiles).not.toHaveBeenCalled()+ }+ )+it('merges db structure with engine completedBytes when active', async () => {const db = {getTaskFiles: vi.fn(() => [diff --git a/src/renderer/components/file-list/file-list.tsx b/src/renderer/components/file-list/file-list.tsxindex 89ee93a8..b83d0675 100644--- a/src/renderer/components/file-list/file-list.tsx+++ b/src/renderer/components/file-list/file-list.tsx@@ -18,6 +18,7 @@ interface FileListProps<T extends BaseFileRow = BaseFileRow> {headerClassName?: string/** Optional trailing renderer per row (e.g. progress percent in detail). */renderRowTrailing?: (file: T) => ReactNode+ renderRowSize?: (file: T) => ReactNode}export function FileList<T extends BaseFileRow = BaseFileRow>({@@ -30,6 +31,7 @@ export function FileList<T extends BaseFileRow = BaseFileRow>({headerSlot,headerClassName,renderRowTrailing,+ renderRowSize,}: FileListProps<T>) {const { formatBytes } = useByteFormat()@@ -122,7 +124,7 @@ export function FileList<T extends BaseFileRow = BaseFileRow>({{file.path}</span><span className="shrink-0 text-xs tabular-nums text-muted-foreground">- {formatBytes(file.size)}+ {renderRowSize ? renderRowSize(file) : formatBytes(file.size)}</span>{renderRowTrailing?.(file)}</div>diff --git a/src/renderer/components/onboarding/onboarding-language-select.tsx b/src/renderer/components/onboarding/onboarding-language-select.tsxindex fed361e0..904f00f3 100644--- a/src/renderer/components/onboarding/onboarding-language-select.tsx+++ b/src/renderer/components/onboarding/onboarding-language-select.tsx@@ -35,7 +35,7 @@ export function OnboardingLanguageSelect() {}return (- <div className="flex items-center pt-3.5">+ <div className="flex items-center"><Selectitems={LANGUAGE_OPTIONS}value={i18n.resolvedLanguage ?? i18n.language}diff --git a/src/renderer/routes/downloads/inspector/files-tab.test.tsx b/src/renderer/routes/downloads/inspector/files-tab.test.tsxindex 5c5dd134..1dc3773d 100644--- a/src/renderer/routes/downloads/inspector/files-tab.test.tsx+++ b/src/renderer/routes/downloads/inspector/files-tab.test.tsx@@ -104,6 +104,47 @@ beforeEach(() => {})describe('FilesTab', () => {+ it.each([TaskStatus.Downloading, TaskStatus.Completed, TaskStatus.Error])(+ 'shows media segment progress independently of mux progress while %s',+ (status) => {+ vi.mocked(useTaskFiles).mockReturnValue({+ files: [+ {+ index: 0,+ path: 'video/000001-first.ts',+ size: 0,+ completedBytes: 0,+ selected: true,+ progress: 1,+ },+ ],+ loading: false,+ refetch: vi.fn(),+ })+ render(+ <FilesTab+ task={mockTask({+ kind: TaskKind.Hls,+ type: TaskType.Http,+ status,+ progress: 0.25,+ })}+ />+ )+ expect(screen.getByText('video/000001-first.ts')).toBeInTheDocument()+ expect(screen.getByText('100%')).toBeInTheDocument()+ expect(screen.queryByText('25%')).not.toBeInTheDocument()+ expect(screen.getByText('—')).toBeInTheDocument()+ expect(screen.getByRole('checkbox')).toHaveAttribute(+ 'aria-disabled',+ 'true'+ )+ expect(+ screen.queryByRole('button', { name: /save/i })+ ).not.toBeInTheDocument()+ }+ )+it('shows readOnly mode for completed tasks (no save button)', () => {render(<FilesTab task={mockTask({ status: TaskStatus.Completed })} />)for (const cb of screen.getAllByRole('checkbox')) {diff --git a/src/renderer/routes/downloads/inspector/files-tab.tsx b/src/renderer/routes/downloads/inspector/files-tab.tsxindex 6d1f690a..a612b954 100644--- a/src/renderer/routes/downloads/inspector/files-tab.tsx+++ b/src/renderer/routes/downloads/inspector/files-tab.tsx@@ -1,11 +1,12 @@import { FileList } from '@renderer/components/file-list/file-list'import { Button } from '@renderer/components/ui/button'+import { useByteFormat } from '@renderer/hooks/use-byte-format'import { useTaskFiles } from '@renderer/hooks/use-task-files'import { formatProgressPercent } from '@renderer/lib/format'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import type { DownloadTask, TaskFile } from '@shared/types/task'-import { TaskStatus, TaskType } from '@shared/types/task'+import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'import { useState } from 'react'import { useTranslation } from 'react-i18next'@@ -30,14 +31,17 @@ function arraysEqualSorted(a: number[], b: number[]): boolean {export function FilesTab({ task }: { task: DownloadTask }) {const { t } = useTranslation()+ const { formatBytes } = useByteFormat()+ const isMedia = task.kind === TaskKind.Hls || task.kind === TaskKind.Muxconst isActive = ACTIVE_DOWNLOAD.has(task.status)const { files } = useTaskFiles(task.id, isActive)const initial = task.bt?.selectedFiles ?? []const [draft, setDraft] = useState<number[]>(initial)- // Single-file tasks (HTTP/FTP always; single-file BT/Magnet/Metalink) have- // no meaningful selection to make — there's only one file. Treat them as- // read-only so the select-all checkbox + Save/Cancel footer disappear.+ // Direct HTTP/FTP and single-file tasks have no file selection to make.+ // Media tasks require the entire segment plan, so their list is read-only+ // too, with no select-all checkbox or Save/Cancel controls.const isStructurallyImmutable =+ isMedia ||task.type === TaskType.Http ||task.type === TaskType.Ftp ||files.length <= 1@@ -67,12 +71,18 @@ export function FilesTab({ task }: { task: DownloadTask }) {selectedIndices={selectedIndices}onSelectionChange={isReadOnly ? undefined : setDraft}readOnly={isReadOnly}+ renderRowSize={+ isMedia ? (f) => (f.size > 0 ? formatBytes(f.size) : '—') : undefined+ }renderRowTrailing={(f) =>- isActive ? (+ isActive || isMedia ? (<span className="shrink-0 text-xs tabular-nums text-muted-foreground">- {files.length === 1- ? formatProgressPercent(task.progress)- : formatProgressPercent(f.completedBytes / Math.max(f.size, 1))}+ {formatProgressPercent(+ f.progress ??+ (files.length === 1 && !isMedia+ ? task.progress+ : f.completedBytes / Math.max(f.size, 1))+ )}%</span>) : nulldiff --git a/src/renderer/windows/onboarding-window.test.tsx b/src/renderer/windows/onboarding-window.test.tsxindex bc6c6d40..1738d8ea 100644--- a/src/renderer/windows/onboarding-window.test.tsx+++ b/src/renderer/windows/onboarding-window.test.tsx@@ -27,9 +27,7 @@ describe('OnboardingWindow', () => {expect(transport.invoke).not.toHaveBeenCalled()expect(screen.getByTestId('disclaimer-panel')).toBeVisible()expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()- expect(screen.getByTestId('onboarding-language').parentElement).toHaveClass(- 'pt-3.5'- )+ expect(screen.getByRole('combobox', { name: '语言' })).toBeVisible()expect(screen.getByRole('heading', { name: '使用声明' })).toBeVisible()const surface = document.querySelector('[data-slot="onboarding-surface"]'diff --git a/src/server/index.ts b/src/server/index.tsindex f0b0c5ea..434ceac5 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -95,6 +95,7 @@ import { handleCreateTask } from '@core/task/create-task-handler'import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'import { FileCleanupServiceImpl } from '@core/task/file-cleanup-service'import { FinalNamePickerImpl } from '@core/task/final-name-picker'+import { MediaMetaStoreImpl } from '@core/task/media-meta-store'import {hasEngineTaskDelta,mergeEngineTask,@@ -1018,6 +1019,12 @@ async function main() {const torrentMetaStore = new TorrentMetaStoreImpl(runtimeDirectories.torrentsDir)+ const mediaMetaStore = new MediaMetaStoreImpl(+ path.join(platform.userDataDir, 'media')+ )+ await mediaMetaStore+ .pruneOrphans(db.getAllTasks().map(({ task }) => task.motrixId))+ .catch((err) => log.warn({ err }, 'Media metadata recovery failed'))const fileCleanupService = new FileCleanupServiceImpl({async removePathRecursive(absPath: string): Promise<void> {await fs.rm(absPath, { recursive: true, force: true })@@ -1111,6 +1118,7 @@ async function main() {// ─── HTTP App ─────────────────────────────────────────────────const serverDirectoryService = new ServerDirectoryService(downloadPathPolicy)const commandHandlers = buildServerCommandHandlers({+ mediaMetaStore,serverDirectoryService,supervisor,settingsManager,@@ -1193,6 +1201,7 @@ async function main() {])}const queryHandlers = buildServerQueryHandlers({+ mediaMetaStore,serverDirectoryService,taskManager,statsAggregator,@@ -1771,6 +1780,7 @@ async function main() {adapter,log,fileCleanupService,+ mediaMetaStore,torrentMetaStore,eventBus,db,@@ -1912,6 +1922,7 @@ async function main() {trustedExtensionRegistry,createExtensionReceiver: ({ bridgeBus }) =>new BridgeReceiver({+ mediaMetaStore,getDefaultSaveDir: () => settingsManager.getApp().defaultSaveDir,pickName: (saveDir, desired) =>finalNamePicker.pick(saveDir, desired),diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex d2cc19fb..313e8ba8 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -34,6 +34,7 @@ import {TaskType,TransitionPhase,} from '@shared/types/task'+import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { createServerDownloadPathPolicy } from '../download-path-policy'@@ -96,6 +97,7 @@ function makeFakeCtx() {},aria2BinaryPath: '/usr/bin/aria2c',finalNamePicker: {} as FinalNamePicker,+ mediaMetaStore: makeMediaMetaStoreStub(),torrentMetaStore: {} as TorrentMetaStore,taskManager: {getById: vi.fn(() => undefined),diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 2784fdec..53d9bfc8 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -61,6 +61,7 @@ import {import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'import type { FileCleanupService } from '@core/task/file-cleanup-service'import type { FinalNamePicker } from '@core/task/final-name-picker'+import type { MediaMetaStore } from '@core/task/media-meta-store'import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'import { createSetSelectedFilesHandler } from '@core/task/set-selected-files'import {@@ -120,6 +121,7 @@ export interface ServerCommandContext {}aria2BinaryPath: stringfinalNamePicker: FinalNamePicker+ mediaMetaStore: MediaMetaStoretorrentMetaStore: TorrentMetaStoretaskManager: TaskManagerfileCleanupService: FileCleanupService@@ -189,6 +191,7 @@ export function buildServerCommandHandlers(trackerManager,bridgeControl,finalNamePicker,+ mediaMetaStore,torrentMetaStore,taskManager,fileCleanupService,@@ -335,6 +338,7 @@ export function buildServerCommandHandlers(adapter,log,fileCleanupService,+ mediaMetaStore,torrentMetaStore,eventBus,db: motrixDatabase,diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.tsindex 88f06037..db704c0b 100644--- a/src/server/ipc/queries.ts+++ b/src/server/ipc/queries.ts@@ -33,6 +33,7 @@ import type {import { createGetTaskFilesHandler } from '@core/task/get-task-files'import { createGetTaskPeersHandler } from '@core/task/get-task-peers'import { createGetTaskPiecesHandler } from '@core/task/get-task-pieces'+import type { MediaMetaStore } from '@core/task/media-meta-store'import { slimTasksForBroadcast } from '@core/task/slim-task-for-broadcast'import type { TaskManager } from '@core/task/task-manager'import type { TrackerManager } from '@core/tracker'@@ -111,6 +112,7 @@ export interface ServerQueryContext {settingsManager: SettingsManagertrackerManager: TrackerManagerengineAdapter: EngineAdapter+ mediaMetaStore: MediaMetaStoremotrixDatabase: MotrixDatabasegeoipManager: Pick<GeoIPManager, 'getStatus' | 'isEnabled' | 'lookupCountry'>notificationCenter: NotificationCenter@@ -198,6 +200,7 @@ export function buildServerQueryHandlers(taskManager.getById(taskId) ?? null,[Queries.GetTaskFiles]: createGetTaskFilesHandler({+ mediaMetaStore: ctx.mediaMetaStore,db: motrixDatabase,taskManager,engine: engineAdapter,diff --git a/src/shared/types/task.ts b/src/shared/types/task.tsindex fc67aa97..94889f32 100644--- a/src/shared/types/task.ts+++ b/src/shared/types/task.ts@@ -276,4 +276,6 @@ export interface TaskFile {size: numbercompletedBytes: numberselected: boolean+ /** Media segment progress, independent of the parent task's mux progress. */+ progress?: number}diff --git a/src/test-utils/bridge-receiver.ts b/src/test-utils/bridge-receiver.tsindex 5ad13596..716b01e7 100644--- a/src/test-utils/bridge-receiver.ts+++ b/src/test-utils/bridge-receiver.ts@@ -5,6 +5,7 @@ import type { MdxpSessionContext } from '@core/bridge/mdxp-session-context'import type { BridgeReceiverDeps } from '@core/bridge-receiver/bridge-receiver'import { TaskManager } from '@core/task/task-manager'import type { DownloadSubmitParams } from '@motrix/mdxp'+import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'import { vi } from 'vitest'/** Typed receiver dependencies with inert IO; each call owns independent state. */@@ -13,6 +14,7 @@ export function makeBridgeReceiverDeps(): BridgeReceiverDeps {let serial = 0return {+ mediaMetaStore: makeMediaMetaStoreStub(),getDefaultSaveDir: () => '/downloads',pickName: vi.fn(async (_dir, name) => name),createTask: vi.fn(async () => ({diff --git a/src/test-utils/media-meta-store.ts b/src/test-utils/media-meta-store.tsnew file mode 100644index 00000000..1bbd8844--- /dev/null+++ b/src/test-utils/media-meta-store.ts@@ -0,0 +1,14 @@+import type { MediaMetaStore } from '@core/task/media-meta-store'+import { vi } from 'vitest'++export function makeMediaMetaStoreStub() {+ return {+ persist: vi.fn<MediaMetaStore['persist']>(+ async (id) => `/metadata/media/${id}/files.json`+ ),+ read: vi.fn<MediaMetaStore['read']>(async () => null),+ update: vi.fn<MediaMetaStore['update']>(),+ release: vi.fn<MediaMetaStore['release']>(async () => {}),+ remove: vi.fn<MediaMetaStore['remove']>(async () => {}),+ } satisfies MediaMetaStore+}