Skip to content

A full-featured download manager.

fix(server): enable extension media downloads with live ffmpeg (#2472)

Dr_rOot061a4e38fe69
diff --git a/docs/docker-server.md b/docs/docker-server.md
index d0ac441c..c33bbd6d 100644
--- a/docs/docker-server.md
+++ b/docs/docker-server.md
@@ -656,9 +656,15 @@ Operator-managed options are:
- `MOTRIX_SECRETS_SEED`: optional 64-hex secret from an orchestrator secret
store. Otherwise `/data/secrets.lockbox` is generated and persisted.
-The official image does not include FFmpeg. A plugin that requires it needs a
-derived image with Alpine's `ffmpeg` package and
-`MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`.
+The official image does not include FFmpeg. Browser Extension HLS/DASH downloads,
+separate audio/video merging, and plugins that require FFmpeg need an executable
+inside the container. For example, use a derived image with Alpine's `ffmpeg`
+package and `MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`. A compatible executable in
+`/data/binaries/ffmpeg` or a custom path configured in the Web UI also works.
+Confirm detection in **Settings → Integration → Media Tools**, then click
+**Rescan** in the Extension. The Server refreshes its media capabilities without
+requiring a restart; installing FFmpeg only on the browser's computer does not
+make it available inside the container.
## Upgrade, rollback, backup, and restore
diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.md
index a193b7a1..7711b003 100644
--- a/docs/docker-server.zh-CN.md
+++ b/docs/docker-server.zh-CN.md
@@ -557,8 +557,13 @@ operator 可用的管理选项包括:
- `MOTRIX_SECRETS_SEED`:可选的 64 位十六进制 secret,应来自编排器 secret
store;否则会生成并持久化 `/data/secrets.lockbox`。
-官方镜像不包含 FFmpeg。依赖 FFmpeg 的插件需要基于官方镜像安装 Alpine
-`ffmpeg` 包,并设置 `MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`。
+官方镜像不包含 FFmpeg。浏览器扩展的 HLS/DASH 下载、分离音视频合并,以及
+依赖 FFmpeg 的插件,都需要容器内可执行的 FFmpeg。例如,基于官方镜像安装
+Alpine `ffmpeg` 包,并设置 `MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`。也可以将
+兼容的可执行文件放在 `/data/binaries/ffmpeg`,或在 Web 界面配置自定义路径。
+在 **设置 → 集成 → 媒体工具** 中确认检测成功后,点击扩展中的 **重新扫描**。
+Server 会刷新媒体能力,无需重启;仅在浏览器所在电脑安装 FFmpeg,不会使其
+在容器内可用。
## 升级、回滚、备份与恢复
diff --git a/e2e/bridge/remote-extension-harness.ts b/e2e/bridge/remote-extension-harness.ts
index 0c58d0d4..91e6ad85 100644
--- a/e2e/bridge/remote-extension-harness.ts
+++ b/e2e/bridge/remote-extension-harness.ts
@@ -82,6 +82,8 @@ function createReceiver(
return { taskId }
},
cancel: async () => {},
+ cancelMedia: async () => {},
+ getMediaSegmentGids: () => [],
restoreInflight: async () => {},
start: () => {
stopped = false
diff --git a/scripts/vite-desktop-locales.ts b/scripts/vite-desktop-locales.ts
index 36ccba72..eed8e565 100644
--- a/scripts/vite-desktop-locales.ts
+++ b/scripts/vite-desktop-locales.ts
@@ -11,6 +11,13 @@ export function desktopLocaleProjection(localeDirectory: string): Plugin {
if (!file?.startsWith(prefix) || !file.endsWith('.json')) return null
const catalog = JSON.parse(source) as Record<string, unknown>
delete catalog.operatorAdmin
+ const settings = catalog.settings as Record<string, unknown> | undefined
+ const integration = settings?.integration as
+ | Record<string, unknown>
+ | undefined
+ // Extension settings and pairing prompts are rendered by the shared UI.
+ // Native integration prompts and media errors still need their catalogs.
+ if (integration) delete integration.browser
const task = catalog.task as Record<string, unknown> | undefined
const add = task?.add as Record<string, unknown> | undefined
if (add) delete add.duplicate
diff --git a/src/server/bridge/bootstrap.test.ts b/src/server/bridge/bootstrap.test.ts
index 26920baf..53228b89 100644
--- a/src/server/bridge/bootstrap.test.ts
+++ b/src/server/bridge/bootstrap.test.ts
@@ -152,6 +152,8 @@ function extensionReceiver(): ServerExtensionReceiver {
return {
handle: vi.fn(async () => ({ taskId: 'submitted' })),
cancel: vi.fn(async () => {}),
+ cancelMedia: vi.fn(async () => {}),
+ getMediaSegmentGids: vi.fn(() => []),
restoreInflight: vi.fn(async () => {}),
start: vi.fn(),
stopAndDrain: vi.fn(async () => {}),
diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.ts
index 9fb31cc1..aa753f5e 100644
--- a/src/server/bridge/bootstrap.ts
+++ b/src/server/bridge/bootstrap.ts
@@ -61,6 +61,8 @@ export interface ServerBridgeRuntime {
bridgeCommandHandlers: Record<string, Handler>
bridgeQueryHandlers: Record<string, Handler>
shutdown: () => Promise<void>
+ cancelMedia: (taskId: string) => Promise<void>
+ getMediaSegmentGids: (taskId: string) => string[]
}
/** Extension-only download application surface. The Server composition root
@@ -69,6 +71,8 @@ export interface ServerBridgeRuntime {
export interface ServerExtensionReceiver {
handle: NonNullable<MethodHandlers['submitDownload']>
cancel: (taskId: string) => Promise<void>
+ cancelMedia: (taskId: string) => Promise<void>
+ getMediaSegmentGids: (taskId: string) => string[]
restoreInflight: () => Promise<void>
start: () => void
stopAndDrain: () => Promise<void>
@@ -84,6 +88,8 @@ export interface ServerBridgeOptions {
* the requested listener port. */
fixedPort?: BridgeStatusInfo['fixedPort']
motrixVersion: string
+ /** Recheck the same live resolver used by the receiver on each handshake. */
+ ffmpegAvailable?: () => Promise<boolean>
/** The process-lifetime core EventBus (for the SSE firehose + re-emitting
* bridge approval events so the web broadcaster forwards them). */
eventBus: {
@@ -275,7 +281,8 @@ export async function bootstrapBridgeForServer(
registry,
motrixVersion: opts.motrixVersion,
runtime: 'server',
- ffmpegAvailable: false,
+ ffmpegAvailable:
+ extensionReceiver != null ? (opts.ffmpegAvailable ?? false) : false,
localToken,
deviceCode,
onPairRequested: (payload) => bridgeBus.emitPairRequested(payload),
@@ -479,6 +486,9 @@ export async function bootstrapBridgeForServer(
localToken,
bridgeCommandHandlers,
bridgeQueryHandlers,
+ cancelMedia: async (taskId) => extensionReceiver?.cancelMedia(taskId),
+ getMediaSegmentGids: (taskId) =>
+ extensionReceiver?.getMediaSegmentGids(taskId) ?? [],
shutdown: () => ownership.dispose(),
}
} catch (error) {
diff --git a/src/server/bridge/manager.test.ts b/src/server/bridge/manager.test.ts
index 01ea08ef..40936e67 100644
--- a/src/server/bridge/manager.test.ts
+++ b/src/server/bridge/manager.test.ts
@@ -20,6 +20,8 @@ function makeRegistry() {
function makeRuntime(): ServerBridgeRuntime {
return {
+ cancelMedia: vi.fn(async () => {}),
+ getMediaSegmentGids: vi.fn(() => []),
server: {} as ServerBridgeRuntime['server'],
port: 16801,
localToken: 'token',
@@ -43,6 +45,28 @@ describe('ServerBridgeManager', () => {
await registry.load()
})
+ it('keeps media cancellation reachable while a disabled bridge is draining', async () => {
+ const runtime = makeRuntime()
+ let release!: () => void
+ const drain = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ vi.mocked(runtime.shutdown).mockReturnValue(drain)
+ const manager = new ServerBridgeManager(registry, async () => runtime)
+ await manager.start()
+ await manager.cancelMedia('active')
+ expect(runtime.cancelMedia).toHaveBeenCalledWith('active')
+ const stopping = manager.stop()
+ await vi.waitFor(() => expect(runtime.shutdown).toHaveBeenCalledOnce())
+ expect(manager.current).toBeNull()
+ await manager.cancelMedia('removing')
+ expect(runtime.cancelMedia).toHaveBeenCalledWith('removing')
+ release()
+ await stopping
+ await manager.cancelMedia('already-stopped')
+ expect(runtime.cancelMedia).toHaveBeenCalledTimes(2)
+ })
+
it('keeps trusted-extension management available while disabled', async () => {
const manager = new ServerBridgeManager(registry, vi.fn())
diff --git a/src/server/bridge/manager.ts b/src/server/bridge/manager.ts
index 6a8f687b..71635169 100644
--- a/src/server/bridge/manager.ts
+++ b/src/server/bridge/manager.ts
@@ -18,6 +18,7 @@ export type ServerBridgeRuntimeFactory = () => Promise<ServerBridgeRuntime>
*/
export class ServerBridgeManager {
private runtime: ServerBridgeRuntime | null = null
+ private drainingRuntime: ServerBridgeRuntime | null = null
private transition: Promise<void> = Promise.resolve()
private registryTransition: Promise<void> = Promise.resolve()
private desiredEnabled = false
@@ -81,6 +82,13 @@ export class ServerBridgeManager {
return this.runtime
}
+ /** Web removal may race a bridge restart while holding the task mutation
+ * lock. Reach the draining receiver directly; waiting for the whole bridge
+ * transition here could deadlock its cancellation on that same lock. */
+ async cancelMedia(taskId: string): Promise<void> {
+ await (this.runtime ?? this.drainingRuntime)?.cancelMedia(taskId)
+ }
+
start(): Promise<void> {
this.desiredEnabled = true
return this.enqueue(() => this.startCurrent())
@@ -148,7 +156,12 @@ export class ServerBridgeManager {
private async stopCurrent(): Promise<void> {
const runtime = this.runtime
this.runtime = null
- await runtime?.shutdown()
+ this.drainingRuntime = runtime
+ try {
+ await runtime?.shutdown()
+ } finally {
+ this.drainingRuntime = null
+ }
}
private async availableRuntime(): Promise<ServerBridgeRuntime> {
diff --git a/src/server/bridge/media-download.integration.test.ts b/src/server/bridge/media-download.integration.test.ts
new file mode 100644
index 00000000..df70af17
--- /dev/null
+++ b/src/server/bridge/media-download.integration.test.ts
@@ -0,0 +1,375 @@
+// @vitest-environment node
+import {
+ copyFile,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import {
+ exchangeCredential,
+ initializeParams,
+ mdxpOverChannel,
+ runPake,
+ startPair,
+} from '@core/bridge/__tests__/mbp1-client'
+import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'
+import { EventBus } from '@core/events/event-bus'
+import { FfmpegService } from '@core/ffmpeg/ffmpeg-service'
+import { getLogger } from '@core/logger'
+import { pauseTask, removeTask, resumeTask } from '@core/task/actions'
+import { TaskManager } from '@core/task/task-manager'
+import {
+ type DownloadSubmitParams,
+ ErrorCodes,
+ type InitializeResult,
+ Methods,
+ Notifications,
+} from '@motrix/mdxp'
+import { BridgeQueries } from '@shared/protocol/bridge'
+import { Events } from '@shared/protocol/events'
+import { EngineState } from '@shared/types/engine'
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import {
+ makeBridgeReceiverDeps,
+ makeDirectSubmit,
+} from '@test-utils/bridge-receiver'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createServerMediaRuntime } from '../media-runtime'
+import { bootstrapBridgeForServer, type ServerBridgeRuntime } from './bootstrap'
+import { parseRemoteExtensionConfig } from './remote-extension-config'
+
+describe('Server extension media downloads', () => {
+ let root: string
+ let runtime: ServerBridgeRuntime | undefined
+ let closeClient: (() => void) | undefined
+
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'motrix-server-media-'))
+ })
+ afterEach(async () => {
+ closeClient?.()
+ closeClient = undefined
+ await runtime?.shutdown()
+ runtime = undefined
+ vi.restoreAllMocks()
+ await rm(root, { recursive: true, force: true })
+ })
+
+ async function setup() {
+ const eventBus = new EventBus()
+ const taskManager = new TaskManager()
+ const persisted = new Map<string, DownloadTask>()
+ const persistTask = vi.fn(async (task: DownloadTask) => {
+ persisted.set(task.id, structuredClone(task))
+ })
+ let binaryPath: string | null = null
+ const completeHandlers: Array<(event: { gid: string }) => void> = []
+ const segmentFiles = new Map<string, string>()
+ let serial = 0
+ const adapter = {
+ pauseTask: vi.fn(async () => {}),
+ resumeTask: vi.fn(async () => {}),
+ forceRemoveTask: vi.fn(async () => {}),
+ removeDownloadResult: vi.fn(async () => {}),
+ }
+ const media = createServerMediaRuntime({
+ tempDir: path.join(root, 'temp'),
+ detectFfmpeg: async () => ({
+ active: binaryPath ? { path: binaryPath, version: '9.0.2' } : null,
+ candidates: [],
+ }),
+ adapter,
+ rpcClient: {
+ addUri: vi.fn(async (_uris, options) => {
+ const gid = `segment-${++serial}`
+ const file = path.join(String(options.dir), String(options.out))
+ await writeFile(file, 'media fixture')
+ segmentFiles.set(gid, file)
+ return gid
+ }),
+ tellStatus: vi.fn(async () => ({
+ completedLength: '13',
+ totalLength: '13',
+ })),
+ onDownloadComplete: (callback) => {
+ completeHandlers.push(callback)
+ },
+ onDownloadError: vi.fn(),
+ },
+ })
+ // Keep the coordinator, segment assembly, publication and persistence real;
+ // only external aria2 and FFmpeg processes are replaced in this CI test.
+ const ffmpeg = vi
+ .spyOn(FfmpegService.prototype, 'run')
+ .mockImplementation(async (job, progress) => {
+ await copyFile(job.videoPath, job.output)
+ progress({ progress: 1 })
+ })
+ const saveDir = path.join(root, 'downloads')
+ await mkdir(saveDir)
+ const fetchManifest = vi.fn(async (url: string) =>
+ url.endsWith('.mpd')
+ ? '<MPD type="static" mediaPresentationDuration="PT5S"><Period><AdaptationSet mimeType="video/mp4"><Representation id="v" bandwidth="1000"><BaseURL>https://example.com/v.mp4</BaseURL><SegmentList duration="5"><SegmentURL media="https://example.com/0.m4s" /></SegmentList></Representation></AdaptationSet></Period></MPD>'
+ : '#EXTM3U\n#EXTINF:5,\nhttps://example.com/0.ts\n#EXT-X-ENDLIST'
+ )
+ const publish = () =>
+ eventBus.emit(Events.TaskUpdated, taskManager.getAll())
+ let receiver!: BridgeReceiver
+ const deps = makeBridgeReceiverDeps({
+ taskManager,
+ eventBus,
+ persistTask,
+ getDefaultSaveDir: () => saveDir,
+ resolveFfmpegBinaryPath: media.resolveFfmpegBinaryPath,
+ segmentAria2: media.segmentAria2,
+ tmpRoot: media.tmpRoot,
+ fetchManifest,
+ publishTaskUpdate: publish,
+ publishTaskUpdateNow: publish,
+ })
+ const actionDeps = {
+ ...deps,
+ eventBus,
+ adapter: adapter as never,
+ log: getLogger('server-media-test'),
+ getMediaSegmentGids: (id: string) => receiver.getMediaSegmentGids(id),
+ }
+ const remove = (id: string) =>
+ removeTask(
+ id,
+ { deleteWithFiles: false },
+ {
+ ...actionDeps,
+ cancelMedia: (taskId) => runtime!.cancelMedia(taskId),
+ db: {
+ deleteTask: (taskId) => {
+ persisted.delete(taskId)
+ },
+ getTask: () => null,
+ saveTaskWithInstances: vi.fn(),
+ },
+ fileCleanupService: {} as never,
+ torrentMetaStore: {} as never,
+ magnetTracker: { observe: () => false } as never,
+ taskPersistence: {
+ runExclusivePersistence: async (operation) => operation(),
+ },
+ runTaskMutation: async (_ids, operation) => operation(),
+ }
+ )
+ deps.removeTask = remove
+ runtime = await bootstrapBridgeForServer({
+ userDataDir: root,
+ host: '127.0.0.1',
+ port: 0,
+ motrixVersion: '2.1.1',
+ eventBus,
+ ffmpegAvailable: media.ffmpegAvailable,
+ remoteExtensionConfig: parseRemoteExtensionConfig({
+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',
+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://motrix.example/bridge',
+ MOTRIX_PUBLIC_URL: 'https://motrix.example',
+ }),
+ createExtensionReceiver: ({ bridgeBus }) =>
+ (receiver = new BridgeReceiver({ ...deps, bridgeBus })),
+ readHandlerDeps: {
+ taskManager,
+ statsAggregator: {
+ getStats: () => ({
+ totalDownloadSpeed: 0,
+ totalUploadSpeed: 0,
+ activeTasks: 0,
+ waitingTasks: 0,
+ stoppedTasks: 0,
+ }),
+ },
+ supervisor: {
+ getState: () => EngineState.Ready,
+ getFeatureReport: () => null,
+ },
+ },
+ writeHandlerDeps: {
+ taskManager,
+ pauseTask: (id) => pauseTask(id, actionDeps),
+ resumeTask: (id) => resumeTask(id, actionDeps),
+ removeTask: remove,
+ createTask: async () => ({ taskId: 'direct' }),
+ parseTorrentFileCount: async () => 0,
+ },
+ })
+ const extensionId = 'a'.repeat(32)
+ const handshake = await startPair({
+ port: runtime.port,
+ origin: `chrome-extension://${extensionId}`,
+ browser: 'chromium',
+ claimedExtensionId: extensionId,
+ routePrefix: '/bridge',
+ hostHeader: 'motrix.example',
+ })
+ closeClient = () => handshake.wire.ws.terminate()
+ const pending = (await runtime.bridgeQueryHandlers[
+ BridgeQueries.ListPendingPairRequests
+ ]()) as Array<{ code?: string }>
+ const { channel } = await runPake(handshake, pending[0].code!)
+ await exchangeCredential(handshake, channel)
+ const connection = mdxpOverChannel(handshake.wire, channel)
+ closeClient = () => {
+ connection.dispose()
+ handshake.wire.ws.terminate()
+ }
+ const initialize = () =>
+ connection.sendRequest(
+ Methods.MotrixInitialize,
+ initializeParams(extensionId)
+ ) as Promise<InitializeResult>
+ await initialize()
+ await connection.sendNotification(
+ Notifications.MotrixInitialized,
+ undefined
+ )
+ const completed = vi.fn()
+ connection.onNotification(Notifications.TaskCompleted, completed)
+ return {
+ media,
+ adapter,
+ persisted,
+ taskManager,
+ ffmpeg,
+ fetchManifest,
+ initialize,
+ completed,
+ setBinary: (value: string | null) => {
+ binaryPath = value
+ },
+ submit: (kind: 'hls' | 'dash' | 'mux') => {
+ const base = makeDirectSubmit()
+ if (base.selection.kind !== 'direct')
+ throw new Error('Expected direct fixture')
+ const resource = {
+ ...base.selection.primary,
+ url:
+ kind === 'dash'
+ ? 'https://example.com/a.mpd'
+ : 'https://example.com/a.m3u8',
+ }
+ const selection: DownloadSubmitParams['selection'] =
+ kind === 'mux'
+ ? {
+ kind,
+ video: { ...resource, url: 'https://example.com/v.mp4' },
+ audio: { ...resource, url: 'https://example.com/a.m4a' },
+ container: 'mp4',
+ }
+ : { kind, primary: resource, container: 'mp4' }
+ return connection.sendRequest(Methods.DownloadSubmit, {
+ ...base,
+ selection,
+ meta: { suggestedFilename: `${kind}.mp4`, qualityLabel: 'source' },
+ }) as Promise<{ taskId: string }>
+ },
+ request: (
+ method:
+ | typeof Methods.TaskPause
+ | typeof Methods.TaskResume
+ | typeof Methods.TaskRemove
+ | typeof Methods.DownloadCancel,
+ taskId: string
+ ) => connection.sendRequest(method, { taskId }),
+ completeSegments: () => {
+ for (const gid of segmentFiles.keys())
+ for (const callback of completeHandlers) callback({ gid })
+ },
+ }
+ }
+
+ it.each(['hls', 'dash', 'mux'] as const)(
+ 'refreshes capabilities and completes %s through the same authenticated connection',
+ async (kind) => {
+ const s = await setup()
+ expect((await s.initialize()).capabilities).toMatchObject({
+ ffmpegAvailable: false,
+ selectionKinds: ['direct'],
+ })
+ await expect(s.submit(kind)).rejects.toMatchObject({
+ code: ErrorCodes.CapabilityNotSupported,
+ })
+ expect(s.fetchManifest).not.toHaveBeenCalled()
+ expect(s.persisted.size).toBe(0)
+ s.setBinary('/data/binaries/ffmpeg')
+ expect((await s.initialize()).capabilities).toMatchObject({
+ ffmpegAvailable: true,
+ selectionKinds: ['direct', 'hls', 'dash', 'mux'],
+ })
+ const { taskId } = await s.submit(kind)
+ await vi.waitFor(() =>
+ expect(runtime!.getMediaSegmentGids(taskId)).toHaveLength(
+ kind === 'mux' ? 2 : 1
+ )
+ )
+ await s.request(Methods.TaskPause, taskId)
+ expect(s.taskManager.getById(taskId)?.status).toBe(TaskStatus.Paused)
+ expect(s.adapter.pauseTask).toHaveBeenCalledTimes(kind === 'mux' ? 2 : 1)
+ await s.request(Methods.TaskResume, taskId)
+ expect(s.taskManager.getById(taskId)?.status).toBe(TaskStatus.Downloading)
+ expect(s.adapter.resumeTask).toHaveBeenCalledTimes(kind === 'mux' ? 2 : 1)
+ s.setBinary('/new/ffmpeg')
+ s.completeSegments()
+ await vi.waitFor(() =>
+ expect(s.persisted.get(taskId)?.status).toBe(TaskStatus.Completed)
+ )
+ expect(s.ffmpeg).toHaveBeenCalledWith(
+ expect.objectContaining({ binaryPath: '/new/ffmpeg' }),
+ expect.any(Function)
+ )
+ expect(
+ await readFile(s.taskManager.getById(taskId)!.finalPath!, 'utf8')
+ ).toBe('media fixture')
+ await vi.waitFor(() =>
+ expect(s.completed).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId })
+ )
+ )
+ await vi.waitFor(async () =>
+ expect(await readdir(s.media.tmpRoot)).toEqual([])
+ )
+ s.setBinary(null)
+ expect((await s.initialize()).capabilities.ffmpegAvailable).toBe(false)
+ await expect(s.submit(kind)).rejects.toMatchObject({
+ code: ErrorCodes.CapabilityNotSupported,
+ })
+ }
+ )
+
+ it.each(['cancel', 'remove', 'shutdown'] as const)(
+ 'drains segments and temporary files on %s',
+ async (action) => {
+ const s = await setup()
+ s.setBinary('/data/binaries/ffmpeg')
+ const { taskId } = await s.submit('hls')
+ await vi.waitFor(() =>
+ expect(runtime!.getMediaSegmentGids(taskId)).toHaveLength(1)
+ )
+ if (action === 'shutdown') await runtime!.shutdown()
+ else
+ await s.request(
+ action === 'cancel' ? Methods.DownloadCancel : Methods.TaskRemove,
+ taskId
+ )
+ expect(s.adapter.forceRemoveTask).toHaveBeenCalledWith('segment-1')
+ expect(s.adapter.removeDownloadResult).toHaveBeenCalledWith('segment-1')
+ expect(s.ffmpeg).not.toHaveBeenCalled()
+ await vi.waitFor(async () =>
+ expect(await readdir(s.media.tmpRoot)).toEqual([])
+ )
+ expect(runtime!.getMediaSegmentGids(taskId)).toEqual([])
+ if (action !== 'shutdown')
+ expect(s.taskManager.getById(taskId)).toBeUndefined()
+ else expect(s.persisted.get(taskId)?.status).toBe(TaskStatus.Error)
+ }
+ )
+})
diff --git a/src/server/bridge/remote-extension-wss.integration.test.ts b/src/server/bridge/remote-extension-wss.integration.test.ts
index f5907347..c1ca66b4 100644
--- a/src/server/bridge/remote-extension-wss.integration.test.ts
+++ b/src/server/bridge/remote-extension-wss.integration.test.ts
@@ -31,6 +31,8 @@ function receiver(): ServerExtensionReceiver {
return {
handle: vi.fn(async () => ({ taskId: 'wss-task' })),
cancel: vi.fn(async () => {}),
+ cancelMedia: vi.fn(async () => {}),
+ getMediaSegmentGids: vi.fn(() => []),
restoreInflight: vi.fn(async () => {}),
start: vi.fn(),
stopAndDrain: vi.fn(async () => {}),
diff --git a/src/server/index.ts b/src/server/index.ts
index 600f21c5..9e57d19b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -13,7 +13,6 @@ import { FileRegistryStoreAdapter } from '@core/bridge/registry-store-adapter'
import { TrustedExtensionRegistry } from '@core/bridge/trusted-extension-registry'
import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'
import { createDownloadDirectories } from '@core/bridge-receiver/download-directories'
-import { Aria2SegmentClient } from '@core/download/aria2-segment-client'
import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'
import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'
import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'
@@ -167,6 +166,7 @@ import {
import { createApp } from './http/app'
import { buildServerCommandHandlers } from './ipc/commands'
import { buildServerQueryHandlers } from './ipc/queries'
+import { createServerMediaRuntime } from './media-runtime'
import { provisionOperatorToken } from './operator-token'
import { createNodePlatformServices } from './platform/services'
import { createServerCapabilityHost } from './plugin/capability-host'
@@ -744,12 +744,18 @@ async function main() {
await proxyBridge.close()
}
}
+ const mediaRuntime = createServerMediaRuntime({
+ rpcClient,
+ adapter,
+ tempDir: runtimeDirectories.tempDir,
+ detectFfmpeg: detectServerFfmpeg,
+ })
const sessionManager = new SessionManager(
taskManager,
rpcClient,
db,
adapter,
- undefined,
+ mediaRuntime.tmpRoot,
undefined,
undefined,
() => {
@@ -772,6 +778,9 @@ async function main() {
removeResult: (gid) => adapter.removeDownloadResult(gid),
})
)
+ supervisor.setPreReadyMaintenance(() =>
+ sessionManager.purgeEphemeralMediaRows()
+ )
shutdownActions.drainSession = () => sessionManager.stopAndDrain()
const persistTask = createServerPersistTask(taskManager, sessionManager)
let pluginHookRuntime: PluginHookRuntime | undefined
@@ -960,6 +969,7 @@ async function main() {
if (supervisor.getState() !== EngineState.Ready) return
let dirty = false
for (const raw of rawTasks) {
+ if (mediaRuntime.isSegmentTask(raw)) continue
if (shouldSkipForPendingMagnetMetadata(raw, magnetTracker)) {
continue
}
@@ -1207,6 +1217,9 @@ async function main() {
adapter,
trackerManager,
bridgeControl: bridgeManager,
+ getMediaSegmentGids: (taskId) =>
+ bridgeManager.current?.getMediaSegmentGids(taskId) ?? [],
+ cancelMedia: (taskId) => bridgeManager.cancelMedia(taskId),
aria2BinaryPath: platform.aria2BinaryPath,
finalNamePicker,
torrentMetaStore,
@@ -1857,7 +1870,9 @@ async function main() {
// The manager keeps every bridge:* RPC registered while this factory owns
// only the optional listener/runtime portion.
bridgeRuntimeFactory = async (): Promise<ServerBridgeRuntime> => {
+ let receiver: BridgeReceiver | null = null
const removeTaskDeps = {
+ cancelMedia: async (taskId: string) => receiver?.cancelMedia(taskId),
taskManager,
adapter,
log,
@@ -1924,6 +1939,8 @@ async function main() {
}),
}
const taskActionDeps = {
+ getMediaSegmentGids: (taskId: string) =>
+ receiver?.getMediaSegmentGids(taskId) ?? [],
onPauseRequested: (taskId: string) =>
trackerManager.noteTaskControl(taskId, true),
onResumeRequested: (taskId: string) =>
@@ -2005,13 +2022,14 @@ async function main() {
port: mdxpPort,
fixedPort,
motrixVersion: appVersion,
+ ffmpegAvailable: mediaRuntime.ffmpegAvailable,
eventBus,
bridgeDataDirLockRecoveryAuthority,
bridgeDataDirLock: dataDirLock,
remoteExtensionConfig,
trustedExtensionRegistry,
createExtensionReceiver: ({ bridgeBus }) =>
- new BridgeReceiver({
+ (receiver = new BridgeReceiver({
mediaMetaStore,
getDefaultSaveDir: () => settingsManager.getApp().defaultSaveDir,
resolveSaveDir: downloadDirectories.resolveSelection,
@@ -2042,17 +2060,14 @@ async function main() {
eventBus,
bridgeBus,
localize: (code) => code,
- // The Server currently advertises direct selection only. Keeping
- // media disabled here makes that capability statement executable,
- // while direct/magnet submissions reuse the same validated paths
- // and cookie/header hygiene as Desktop.
ffmpegBinaryPath: null,
+ resolveFfmpegBinaryPath: mediaRuntime.resolveFfmpegBinaryPath,
publishTaskUpdate,
publishTaskUpdateNow,
taskManager,
activityRecorder: taskActivityService,
- segmentAria2: new Aria2SegmentClient(rpcClient, adapter),
- tmpRoot: runtimeDirectories.tempDir,
+ segmentAria2: mediaRuntime.segmentAria2,
+ tmpRoot: mediaRuntime.tmpRoot,
persistTask,
persistTaskWithOccurrence,
occurrenceDispatcher,
@@ -2067,7 +2082,7 @@ async function main() {
taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),
waitForReady: () =>
supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),
- }),
+ })),
// The web approval UI is a separate (Fastify) service; the operator points
// device-code clients at it via MOTRIX_PUBLIC_URL. Unset → no URL printed.
verificationUri: process.env.MOTRIX_PUBLIC_URL,
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index 48a8a9b8..475d2946 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -21,7 +21,7 @@ import { MotrixDatabase } from '@core/session/motrix-database'
import { SettingsManager } from '@core/settings/settings-manager'
import type { FileCleanupService } from '@core/task/file-cleanup-service'
import type { FinalNamePicker } from '@core/task/final-name-picker'
-import type { TaskManager } from '@core/task/task-manager'
+import { TaskManager } from '@core/task/task-manager'
import type { TorrentMetaStore } from '@core/task/torrent-meta-store'
import type { MagnetTracker } from '@core/torrent/magnet-tracker'
import type { TrackerManager } from '@core/tracker'
@@ -1321,6 +1321,93 @@ describe('server Commands.CreateTask magnet metadata selection', () => {
})
describe('server plural task commands', () => {
+ it.each(['singular', 'plural'] as const)(
+ 'controls media segments through %s Web commands',
+ async (arity) => {
+ const ctx = makeFakeCtx()
+ ctx.taskManager = new TaskManager()
+ ctx.taskManager.set(
+ 'media',
+ makeDownloadTask({
+ id: 'media',
+ engineTaskId: '',
+ kind: TaskKind.Hls,
+ status: TaskStatus.Downloading,
+ })
+ )
+ ctx.adapter.pauseTask = vi.fn(async () => {})
+ ctx.adapter.resumeTask = vi.fn(async () => {})
+ let gids = ['video-segment', 'audio-segment']
+ const handlers = buildServerCommandHandlers({
+ ...ctx,
+ persistTask: vi.fn(async () => {}),
+ getMediaSegmentGids: () => gids,
+ } as ServerCommandContext)
+ await handlers[
+ arity === 'singular' ? Commands.PauseTask : Commands.PauseTasks
+ ]!(arity === 'singular' ? 'media' : ['media'])
+ expect(ctx.adapter.pauseTask).toHaveBeenCalledWith('video-segment')
+ expect(ctx.adapter.pauseTask).toHaveBeenCalledWith('audio-segment')
+ expect(ctx.taskManager.getById('media')?.status).toBe(TaskStatus.Paused)
+ gids = ['next-segment']
+ await handlers[
+ arity === 'singular' ? Commands.ResumeTask : Commands.ResumeTasks
+ ]!(arity === 'singular' ? 'media' : ['media'])
+ expect(ctx.adapter.resumeTask).toHaveBeenCalledExactlyOnceWith(
+ 'next-segment'
+ )
+ expect(ctx.taskManager.getById('media')?.status).toBe(
+ TaskStatus.Downloading
+ )
+ }
+ )
+
+ it.each(['singular', 'plural'] as const)(
+ 'awaits media cancellation before %s Web removal deletes the parent',
+ async (arity) => {
+ const ctx = makeFakeCtx()
+ ctx.taskManager = new TaskManager()
+ ctx.taskManager.set(
+ 'media',
+ makeDownloadTask({
+ id: 'media',
+ engineTaskId: '',
+ kind: TaskKind.Hls,
+ status: TaskStatus.Downloading,
+ })
+ )
+ ctx.motrixDatabase.deleteTask = vi.fn()
+ let release!: () => void
+ const draining = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const cancelMedia = vi.fn(() => draining)
+ const handlers = buildServerCommandHandlers({
+ ...ctx,
+ cancelMedia,
+ } as ServerCommandContext)
+ const pending =
+ arity === 'singular'
+ ? handlers[Commands.RemoveTask]!({
+ taskId: 'media',
+ deleteWithFiles: false,
+ })
+ : handlers[Commands.RemoveTasks]!({
+ taskIds: ['media'],
+ deleteWithFiles: false,
+ })
+ await vi.waitFor(() =>
+ expect(cancelMedia).toHaveBeenCalledExactlyOnceWith('media')
+ )
+ expect(ctx.taskManager.getById('media')).toBeDefined()
+ expect(ctx.motrixDatabase.deleteTask).not.toHaveBeenCalled()
+ release()
+ await pending
+ expect(ctx.taskManager.getById('media')).toBeUndefined()
+ expect(ctx.motrixDatabase.deleteTask).toHaveBeenCalledWith('media')
+ }
+ )
+
it('MoveTasks validates the payload and changes the actual engine queue', async () => {
const ctx = makeFakeCtx()
const queue = ['first', 'second']
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 5716ae52..5135aac2 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -147,6 +147,8 @@ export interface ServerCommandContext {
setEnabled(enabled: boolean): Promise<void>
restart(): Promise<void>
}
+ getMediaSegmentGids?: (taskId: string) => string[]
+ cancelMedia?: (taskId: string) => Promise<void>
aria2BinaryPath: string
finalNamePicker: FinalNamePicker
mediaMetaStore: MediaMetaStore
@@ -309,6 +311,7 @@ export function buildServerCommandHandlers(
// Shared by the singular AND plural task command handlers below — one
// deps bundle per action family so the two arities cannot drift.
const pauseResumeDeps = {
+ getMediaSegmentGids: ctx.getMediaSegmentGids,
onPauseRequested: (taskId: string) =>
trackerManager.noteTaskControl?.(taskId, true),
onResumeRequested: (taskId: string) =>
@@ -399,6 +402,7 @@ export function buildServerCommandHandlers(
// Commands.ReAddTasks so the automatic and user-initiated paths match.
bindTaskRetry?.((id) => reAddTask(id, reAddDeps))
const removeDeps = {
+ cancelMedia: ctx.cancelMedia,
taskManager,
adapter,
log,
diff --git a/src/server/media-runtime.test.ts b/src/server/media-runtime.test.ts
new file mode 100644
index 00000000..8a7901eb
--- /dev/null
+++ b/src/server/media-runtime.test.ts
@@ -0,0 +1,68 @@
+import path from 'node:path'
+import type { FfmpegDetectionResult } from '@core/plugin/capabilities/ffmpeg-detect'
+import { describe, expect, it, vi } from 'vitest'
+import { createServerMediaRuntime } from './media-runtime'
+
+describe('Server media runtime', () => {
+ function setup() {
+ const detectFfmpeg = vi.fn<() => Promise<FfmpegDetectionResult>>()
+ const runtime = createServerMediaRuntime({
+ tempDir: '/tmp/server-media',
+ detectFfmpeg,
+ rpcClient: {
+ addUri: vi.fn(async () => 'segment-1'),
+ tellStatus: vi.fn(async () => ({})),
+ onDownloadComplete: vi.fn(),
+ onDownloadError: vi.fn(),
+ },
+ adapter: {
+ forceRemoveTask: vi.fn(async () => {}),
+ removeDownloadResult: vi.fn(async () => {}),
+ },
+ })
+ return { runtime, detectFfmpeg }
+ }
+
+ it('uses live detection for capability refresh and muxing after path changes', async () => {
+ const { runtime, detectFfmpeg } = setup()
+ detectFfmpeg.mockResolvedValue({ active: null, candidates: [] })
+ expect(await runtime.ffmpegAvailable()).toBe(false)
+ expect(await runtime.resolveFfmpegBinaryPath()).toBeNull()
+ for (const binaryPath of ['/data/binaries/ffmpeg', '/custom/ffmpeg']) {
+ detectFfmpeg.mockResolvedValue({
+ active: { path: binaryPath, version: '9.0.2' },
+ candidates: [],
+ })
+ expect(await runtime.ffmpegAvailable()).toBe(true)
+ expect(await runtime.resolveFfmpegBinaryPath()).toBe(binaryPath)
+ }
+ detectFfmpeg.mockResolvedValue({ active: null, candidates: [] })
+ expect(await runtime.ffmpegAvailable()).toBe(false)
+ expect(await runtime.resolveFfmpegBinaryPath()).toBeNull()
+ })
+
+ it('filters owned GIDs and stale segment snapshots without hiding normal downloads', async () => {
+ const { runtime } = setup()
+ const segment = { gid: 'segment-1', dir: '' }
+ expect(runtime.isSegmentTask(segment)).toBe(false)
+ await runtime.segmentAria2.addUri(['https://example.com/part.ts'], {
+ dir: runtime.tmpRoot,
+ out: 'part.ts',
+ })
+ expect(runtime.isSegmentTask(segment)).toBe(true)
+ await runtime.segmentAria2.removeDownloadResult(segment.gid)
+ expect(runtime.isSegmentTask(segment)).toBe(false)
+
+ for (const dir of [
+ runtime.tmpRoot,
+ path.join(runtime.tmpRoot, 'run/video'),
+ ])
+ expect(runtime.isSegmentTask({ ...segment, dir })).toBe(true)
+ for (const dir of [
+ path.dirname(runtime.tmpRoot),
+ `${runtime.tmpRoot}-downloads`,
+ path.join(runtime.tmpRoot, '../normal'),
+ ])
+ expect(runtime.isSegmentTask({ ...segment, dir })).toBe(false)
+ })
+})
diff --git a/src/server/media-runtime.ts b/src/server/media-runtime.ts
new file mode 100644
index 00000000..c73ce9b9
--- /dev/null
+++ b/src/server/media-runtime.ts
@@ -0,0 +1,36 @@
+import path from 'node:path'
+import { Aria2SegmentClient } from '@core/download/aria2-segment-client'
+import type { FfmpegDetectionResult } from '@core/plugin/capabilities/ffmpeg-detect'
+
+/** Process-lifetime media resources shared by bridge restarts and task polling. */
+export function createServerMediaRuntime(opts: {
+ rpcClient: ConstructorParameters<typeof Aria2SegmentClient>[0]
+ adapter: ConstructorParameters<typeof Aria2SegmentClient>[1]
+ tempDir: string
+ detectFfmpeg: () => Promise<FfmpegDetectionResult>
+}) {
+ const tmpRoot = path.join(opts.tempDir, 'motrix-media')
+ const segmentAria2 = new Aria2SegmentClient(opts.rpcClient, opts.adapter)
+ const resolveFfmpegBinaryPath = async (): Promise<string | null> =>
+ (await opts.detectFfmpeg()).active?.path ?? null
+
+ return {
+ tmpRoot,
+ segmentAria2,
+ resolveFfmpegBinaryPath,
+ ffmpegAvailable: async () => (await resolveFfmpegBinaryPath()) !== null,
+ isSegmentTask: (task: { gid: string; dir: string }): boolean => {
+ if (segmentAria2.isSegmentGid(task.gid)) return true
+ if (!task.dir) return false
+ // Directory ownership also covers the window before addUri returns a GID
+ // and stale polling snapshots after a segment's result has been purged.
+ const relative = path.relative(tmpRoot, path.resolve(task.dir))
+ return (
+ relative === '' ||
+ (relative !== '..' &&
+ !relative.startsWith(`..${path.sep}`) &&
+ !path.isAbsolute(relative))
+ )
+ },
+ }
+}
diff --git a/src/server/shutdown.test.ts b/src/server/shutdown.test.ts
index e5ac087c..414a7e14 100644
--- a/src/server/shutdown.test.ts
+++ b/src/server/shutdown.test.ts
@@ -37,6 +37,35 @@ function actions(
}
describe('createServerShutdown', () => {
+ it('drains media cancellation before stopping engine RPC and Session writes', async () => {
+ const order: string[] = []
+ let release!: () => void
+ const mediaDrain = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const shutdown = createServerShutdown(
+ actions(order, {
+ closeBridge: async () => {
+ order.push('media-cancelling')
+ await mediaDrain
+ order.push('media-drained')
+ },
+ }),
+ vi.fn()
+ )
+ const pending = shutdown()
+ await vi.waitFor(() => expect(order).toContain('dispose-tracker'))
+ expect(order).not.toContain('stop-engine')
+ expect(order).not.toContain('drain-session')
+ release()
+ await pending
+ expect(order.indexOf('media-drained')).toBeLessThan(
+ order.indexOf('stop-engine')
+ )
+ expect(order.indexOf('media-drained')).toBeLessThan(
+ order.indexOf('drain-session')
+ )
+ })
it('closes ingress and drains every producer before closing SQLite', async () => {
const order: string[] = []
const shutdown = createServerShutdown(actions(order), vi.fn())
diff --git a/src/server/shutdown.ts b/src/server/shutdown.ts
index 034ae76f..7311bbf4 100644
--- a/src/server/shutdown.ts
+++ b/src/server/shutdown.ts
@@ -68,10 +68,13 @@ export function createServerShutdown(
// Startup/handlers may be blocked on the engine, plugin host, or session;
// waiting for tracked work first would deadlock the only operations able
// to release them.
+ const pollingDrain = safely('polling', actions.stopPolling)
+ const ingressDrain = safely('http-ingress', actions.closeIngress)
+ const bridgeDrain = safely('bridge-ingress', actions.closeBridge)
const cancellationDrain = Promise.all([
- safely('polling', actions.stopPolling),
- safely('http-ingress', actions.closeIngress),
- safely('bridge-ingress', actions.closeBridge),
+ pollingDrain,
+ ingressDrain,
+ bridgeDrain,
safely('rpc-notifications', actions.unsubscribeProducers),
safely('dev-watcher', actions.drainDevWatcher),
safely('plugin-host', actions.drainPluginHost),
@@ -84,6 +87,9 @@ export function createServerShutdown(
// persistence and engine RPC alive until its unconditional resume
// compensation settles.
await safely('tracker', actions.disposeTracker)
+ // Media cancellation purges aria2 segments and persists the parent task.
+ // Keep RPC and Session writes available until the bridge has drained it.
+ await bridgeDrain
await Promise.all([
cancellationDrain,
safely('session', actions.drainSession),
diff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.ts
index c51d16c9..17c2154f 100644
--- a/tests/scripts/production-build.test.ts
+++ b/tests/scripts/production-build.test.ts
@@ -5,8 +5,7 @@ import { beforeAll, describe, expect, it } from 'vitest'
const MIB = 1024 * 1024
const ROOT = path.resolve(import.meta.dirname, '../..')
const TARGETS = [
- // Installation-aware bridge routing and localized profile summaries add
- // ~5 KiB over the resource-lifetime baseline; retain the 2 MiB startup ceiling.
+ // Keep the 2 MiB startup ceiling and bound the complete lazy-loaded output.
{ name: 'main', initial: 2 * MIB, total: 5.5 * MIB + 12 * 1024 },
{ name: 'preload', initial: 80 * 1024, total: 80 * 1024 },
{ name: 'worker', initial: 48 * 1024, total: 48 * 1024 },
diff --git a/tests/scripts/vite-desktop-locales.test.ts b/tests/scripts/vite-desktop-locales.test.ts
index 88c8e20a..82916b89 100644
--- a/tests/scripts/vite-desktop-locales.test.ts
+++ b/tests/scripts/vite-desktop-locales.test.ts
@@ -20,6 +20,7 @@ describe('desktop main locale projection', () => {
expect(original.operatorAdmin).toBeDefined()
const result = JSON.parse(transform(source, path.join(root, file))!.code)
expect(result.operatorAdmin).toBeUndefined()
+ expect(result.settings.integration.browser).toBeUndefined()
expect(result.task.add.duplicate).toBeUndefined()
expect(result.task.storage).toEqual({
incomplete: original.task.storage.incomplete,
@@ -27,6 +28,7 @@ describe('desktop main locale projection', () => {
errors: original.task.storage.errors,
})
delete original.operatorAdmin
+ delete original.settings.integration.browser
delete original.task.add.duplicate
original.task.storage = {
incomplete: original.task.storage.incomplete,
@@ -35,6 +37,12 @@ describe('desktop main locale projection', () => {
}
expect(result).toEqual(original)
// The source catalogs, consumed by renderer and Server, stay complete.
+ expect(
+ JSON.parse(source).settings.integration.browser.profile
+ ).toBeDefined()
+ expect(
+ JSON.parse(source).settings.integration.browser.pairToast
+ ).toBeDefined()
expect(JSON.parse(source).task.storage.move).toBeDefined()
expect(JSON.parse(source).task.add.duplicate).toBeDefined()
}