A full-featured download manager.
fix(media): refresh ffmpeg support without restarting downloads (#2160)
Dr_rOot852293ac2c7c
diff --git a/src/core/bridge-receiver/bridge-receiver.test.ts b/src/core/bridge-receiver/bridge-receiver.test.tsindex 6505033c..c089bd5d 100644--- a/src/core/bridge-receiver/bridge-receiver.test.ts+++ b/src/core/bridge-receiver/bridge-receiver.test.ts@@ -1,5 +1,6 @@import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'import type { SegmentAria2 } from '@core/download/segment-downloader'+import { MediaTaskCoordinator } from '@core/task/media-task-coordinator'import { TaskManager } from '@core/task/task-manager'import { ErrorCodes } from '@motrix/mdxp'import { Events } from '@shared/protocol/events'@@ -303,6 +304,82 @@ describe('BridgeReceiver', () => {},} as never+ it.each(['hls', 'dash', 'mux', 'resolved-page', 'desktop-mux'] as const)(+ 'uses newly configured FFmpeg without rebuilding the %s pipeline',+ async (kind) => {+ let binaryPath: string | null = null+ const deps = fakeDeps({+ ffmpegBinaryPath: null,+ resolveFfmpegBinaryPath: async () => binaryPath,+ fetchManifest: vi.fn(+ async () =>+ '#EXTM3U\n#EXTINF:5,\nhttps://example.com/0.ts\n#EXT-X-ENDLIST'+ ),+ resolveToMux: async () => ({+ videoUrl: 'https://example.com/v.mp4',+ audioUrl: 'https://example.com/a.m4a',+ container: 'mp4' as const,+ }),+ })+ const receiver = new BridgeReceiver(deps as never)+ const submit = vi+ .spyOn(MediaTaskCoordinator.prototype, 'submit')+ .mockResolvedValue({ taskId: 'accepted' })+ try {+ const attempt = () => {+ if (kind === 'desktop-mux')+ return receiver.muxPipeline!.dispatch({+ kind: 'mux',+ taskId: 'desktop',+ saveDir: '/tmp/save',+ finalName: 'out.mp4',+ videoUrl: 'https://example.com/v.mp4',+ audioUrl: 'https://example.com/a.m4a',+ sanitizedHeaders: {},+ container: 'mp4',+ sourceMeta: {},+ } as never)+ const params =+ kind === 'mux'+ ? muxSubmitParams+ : kind === 'resolved-page'+ ? {+ ...hlsSubmitParams,+ selection: {+ kind: 'direct',+ primary: hlsSubmitParams.selection.primary,+ },+ }+ : {+ ...hlsSubmitParams,+ selection: { ...hlsSubmitParams.selection, kind },+ }+ return receiver.handle(params as never, extCtx)+ }+ expect(receiver.muxPipeline).toBeDefined()+ await expect(attempt()).rejects.toMatchObject({+ code: 'unsupported-kind',+ })+ expect(submit).not.toHaveBeenCalled()+ expect(deps.fetchManifest).not.toHaveBeenCalled()+ binaryPath = '/configured/ffmpeg'+ if (kind === 'dash')+ vi.mocked(deps.fetchManifest!).mockResolvedValue(+ '<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>'+ )+ await expect(attempt()).resolves.toEqual({ taskId: 'accepted' })+ expect(submit).toHaveBeenCalledTimes(1)+ binaryPath = null+ await expect(attempt()).rejects.toMatchObject({+ code: 'unsupported-kind',+ })+ expect(submit).toHaveBeenCalledTimes(1)+ } finally {+ submit.mockRestore()+ }+ }+ )+it('hls submit throws unsupported-kind when ffmpegBinaryPath is null', async () => {const deps = fakeDeps({ ffmpegBinaryPath: null })const r = new BridgeReceiver(deps as never)diff --git a/src/core/bridge-receiver/bridge-receiver.ts b/src/core/bridge-receiver/bridge-receiver.tsindex f39bb54c..d7261a64 100644--- a/src/core/bridge-receiver/bridge-receiver.ts+++ b/src/core/bridge-receiver/bridge-receiver.ts@@ -73,11 +73,12 @@ export interface BridgeReceiverDeps {}bridgeBus: BridgeEventBuslocalize: (code: BridgeErrorCode) => string- /** Path to ffmpeg binary. When null, hls/dash/mux submissions are rejected. */+ /** Static fallback for shells without a live FFmpeg resolver. */ffmpegBinaryPath: string | null/**- * Live resolver used immediately before muxing. Defaults to the startup- * path for shells/tests that do not provide dynamic resolution.+ * Live resolver used before accepting media and immediately before muxing.+ * Providing it enables the pipeline even if FFmpeg is absent at startup.+ * Defaults to the startup path for shells/tests without dynamic resolution.*/resolveFfmpegBinaryPath?: () => Promise<string | null>taskManager: TaskManager@@ -207,7 +208,18 @@ export class BridgeReceiver {})this.publisher = new ProgressPublisher(deps.bridgeBus, deps.localize)- if (deps.ffmpegBinaryPath !== null) {+ if (deps.resolveFfmpegBinaryPath || deps.ffmpegBinaryPath !== null) {+ const resolveFfmpegBinaryPath =+ deps.resolveFfmpegBinaryPath ??+ (() => Promise.resolve(deps.ffmpegBinaryPath))+ const assertFfmpegAvailable = async () => {+ if (!(await resolveFfmpegBinaryPath())) {+ throw new BridgeReceiverError(+ 'unsupported-kind',+ 'ffmpeg is unavailable; configure it in Settings and retry'+ )+ }+ }const eventBusWithEmit = deps.eventBus as {on(event: string, listener: (payload: unknown) => void): unknownoff(event: string, listener: (payload: unknown) => void): unknown@@ -221,9 +233,7 @@ export class BridgeReceiver {eventBus: eventBusWithEmit,publishTaskUpdate: deps.publishTaskUpdate,publishTaskUpdateNow: deps.publishTaskUpdateNow,- resolveFfmpegBinaryPath:- deps.resolveFfmpegBinaryPath ??- (() => Promise.resolve(deps.ffmpegBinaryPath)),+ resolveFfmpegBinaryPath,pickName: deps.pickName,persist: deps.persistTask,persistTaskWithOccurrence: deps.persistTaskWithOccurrence,@@ -250,8 +260,9 @@ export class BridgeReceiver {this.hlsDash = new HlsDashPipeline({fetchManifest: resolvedFetchManifest,coordinator,+ assertFfmpegAvailable,})- this.mux = new MuxPipeline({ coordinator })+ this.mux = new MuxPipeline({ coordinator, assertFfmpegAvailable })}}@@ -260,7 +271,8 @@ export class BridgeReceiver {* Add-Task path (main/index.ts createDeps) to reuse the same* coordinator/mux-pipeline instance — avoids the SP-1 phantom-task* bug that would arise from constructing a second coordinator.- * Undefined when ffmpeg is unavailable (mux pipeline not active).+ * Undefined only when this shell provides no media runtime. Availability+ * is checked from the live resolver on every dispatch.*/get muxPipeline(): MuxPipeline | undefined {return this.mux@@ -270,7 +282,7 @@ export class BridgeReceiver {* Active aria2 segment gids for a coordinator-managed media task (kind* Mux/Hls). These ARE real aria2 gids — unlike the task's empty engineTaskId* — so pause/resume can act on them. Returns [] when the task is unknown, is- * past the download phase, or ffmpeg (and thus the coordinator) is absent.+ * past the download phase, or this shell has no media runtime.*/getMediaSegmentGids(taskId: string): string[] {return this.coordinator?.getActiveSegmentGids(taskId) ?? []diff --git a/src/core/bridge-receiver/pipelines/hls-dash-pipeline.ts b/src/core/bridge-receiver/pipelines/hls-dash-pipeline.tsindex 6457bef9..13fb9f50 100644--- a/src/core/bridge-receiver/pipelines/hls-dash-pipeline.ts+++ b/src/core/bridge-receiver/pipelines/hls-dash-pipeline.ts@@ -16,6 +16,8 @@ export interface HlsDashPipelineDeps {opts: { headers?: Record<string, string> }) => Promise<string>coordinator: Pick<MediaTaskCoordinator, 'submit'>+ /** Reject before fetching manifests or creating a task if FFmpeg is absent. */+ assertFfmpegAvailable?: () => Promise<void>}/**@@ -40,6 +42,7 @@ export class HlsDashPipeline {async dispatch(adapted: AdaptedHls | AdaptedDash): Promise<{ taskId: string }> {+ await this.deps.assertFfmpegAvailable?.()const { fetchManifest, coordinator } = this.depsconst headers = adapted.sanitizedHeaders// ffmpeg needs an output extension or it can't pick a muxer (exit 234) —diff --git a/src/core/bridge-receiver/pipelines/mux-pipeline.ts b/src/core/bridge-receiver/pipelines/mux-pipeline.tsindex adfd8785..479ed2af 100644--- a/src/core/bridge-receiver/pipelines/mux-pipeline.ts+++ b/src/core/bridge-receiver/pipelines/mux-pipeline.ts@@ -7,6 +7,8 @@ import { ensureMediaExtension } from './media-final-name'export interface MuxPipelineDeps {coordinator: Pick<MediaTaskCoordinator, 'submit'>+ /** Reject before fetching manifests or creating a task if FFmpeg is absent. */+ assertFfmpegAvailable?: () => Promise<void>}/**@@ -17,6 +19,7 @@ export class MuxPipeline {constructor(private readonly deps: MuxPipelineDeps) {}async dispatch(adapted: AdaptedMux): Promise<{ taskId: string }> {+ await this.deps.assertFfmpegAvailable?.()const job: MediaJob = {taskId: adapted.taskId,kind: 'mux',diff --git a/src/core/bridge/__tests__/initialize-handler.test.ts b/src/core/bridge/__tests__/initialize-handler.test.tsindex b926899a..b533572e 100644--- a/src/core/bridge/__tests__/initialize-handler.test.ts+++ b/src/core/bridge/__tests__/initialize-handler.test.ts@@ -181,6 +181,31 @@ describe('initialize handler', () => {).rejects.toMatchObject({ code: ErrorCodes.InvalidParams })})+ it('rechecks FFmpeg on each capability exchange after configuration changes', async () => {+ let available = false+ const detect = vi.fn(async () => available)+ const handler = createInitializeHandler({+ ...baseCapabilities,+ ffmpegAvailable: detect,+ })+ const read = () => handler(validClientInfo as never, makeCtx({}))+ expect((await read()).capabilities).toMatchObject({+ ffmpegAvailable: false,+ selectionKinds: ['direct'],+ })+ available = true+ expect((await read()).capabilities).toMatchObject({+ ffmpegAvailable: true,+ selectionKinds: ['direct', 'hls', 'dash', 'mux'],+ })+ available = false+ expect((await read()).capabilities).toMatchObject({+ ffmpegAvailable: false,+ selectionKinds: ['direct'],+ })+ expect(detect).toHaveBeenCalledTimes(3)+ })+it('ffmpegAvailable:false → selectionKinds is only ["direct"]', async () => {const handler = createInitializeHandler({...baseCapabilities,diff --git a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts b/src/core/bridge/__tests__/web-socket-bridge-server.test.tsindex 220603f5..7e8e343f 100644--- a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts+++ b/src/core/bridge/__tests__/web-socket-bridge-server.test.ts@@ -19,6 +19,8 @@ import {WS_CLOSE_PROTOCOL_ERROR,} from '@core/bridge/web-socket-bridge-server'import type { WebSocketLike } from '@core/bridge/web-socket-message-stream'+import { BridgeReceiverError } from '@core/bridge-receiver/errors'+import { ErrorCodes } from '@motrix/mdxp'import type { ClientIdentity } from '@shared/protocol/bridge'import { EngineState } from '@shared/types/engine'import { TaskStatus } from '@shared/types/task'@@ -321,10 +323,12 @@ function makeFakeWriteDeps(describe('WebSocketBridgeServer – v1 control-plane over WS', () => {let server: WebSocketBridgeServerlet mbp1: Mbp1TestWiring+ let ffmpegAvailable = truelet port: numberlet revealTask: Mock<(taskId: string) => Promise<void>>beforeEach(async () => {+ ffmpegAvailable = truembp1 = await makeMbp1TestWiring([['chromium', EXTENSION_ID]])server = new WebSocketBridgeServer({pairing: makeStatefulFakePairing(),@@ -337,7 +341,7 @@ describe('WebSocketBridgeServer – v1 control-plane over WS', () => {} as unknown as TrustedExtensionRegistry,motrixVersion: '2.0',runtime: 'electron',- ffmpegAvailable: true,+ ffmpegAvailable: async () => ffmpegAvailable,localToken: 'test-token',...mbp1.options,})@@ -394,6 +398,65 @@ describe('WebSocketBridgeServer – v1 control-plane over WS', () => {paired.wire.ws.close()})+ it('refreshes live capabilities and preserves a missing-media rejection on the authenticated wire', async () => {+ const submitDownload = vi.fn(async () => {+ throw new BridgeReceiverError(+ 'unsupported-kind',+ '/private/path/ffmpeg unavailable'+ )+ })+ server.setHandlers({ submitDownload })+ const paired = await pairAndExchange({+ port,+ origin: ORIGIN,+ browser: 'chromium',+ claimedExtensionId: EXTENSION_ID,+ code: () => mbp1.dialogs.latestCode(),+ })+ const conn = mdxpOverChannel(paired.wire, paired.channel)+ try {+ ffmpegAvailable = false+ const read = () =>+ conn.sendRequest('motrix/initialize', initializeParams(EXTENSION_ID))+ expect((await read()).capabilities.selectionKinds).toEqual(['direct'])+ conn.sendNotification('motrix/initialized', undefined)+ ffmpegAvailable = true+ expect((await read()).capabilities.selectionKinds).toContain('mux')+ ffmpegAvailable = false+ expect((await read()).capabilities.selectionKinds).toEqual(['direct'])+ await expect(+ conn.sendRequest('download/submit', {+ source: {+ pageUrl: 'https://example.com',+ pageTitle: 'Video',+ detectedAt: 1,+ },+ selection: {+ kind: 'direct',+ primary: {+ url: 'https://example.com/video.mp4',+ headers: {},+ cookies: [],+ refererPolicy: 'strict-origin-when-cross-origin',+ },+ },+ meta: { suggestedFilename: 'video.mp4', qualityLabel: '' },+ })+ ).rejects.toMatchObject({+ code: ErrorCodes.CapabilityNotSupported,+ message: 'Media selection is not supported',+ })+ expect(submitDownload).toHaveBeenCalledTimes(1)+ await expect(conn.sendRequest('task/list', {})).resolves.toEqual({+ tasks: [],+ total: 0,+ })+ } finally {+ conn.dispose()+ paired.wire.ws.close()+ }+ })+it('round-trips system/ping inside the AEAD channel', async () => {const paired = await pairAndExchange({port,diff --git a/src/core/bridge/handlers/initialize-handler.ts b/src/core/bridge/handlers/initialize-handler.tsindex 1af98065..5ce5f870 100644--- a/src/core/bridge/handlers/initialize-handler.ts+++ b/src/core/bridge/handlers/initialize-handler.ts@@ -9,7 +9,7 @@ import type { MdxpSessionContext } from '../mdxp-session-context'export interface InitializeHandlerDeps {motrixVersion: stringruntime: 'electron' | 'server'- ffmpegAvailable: boolean+ ffmpegAvailable: boolean | (() => Promise<boolean>)/** Read lazily so capabilities match the methods actually registered. */supportsTaskReveal: () => boolean}@@ -74,7 +74,13 @@ export function createInitializeHandler(}}-function buildResult(deps: InitializeHandlerDeps): InitializeResult {+async function buildResult(+ deps: InitializeHandlerDeps+): Promise<InitializeResult> {+ const ffmpegAvailable =+ typeof deps.ffmpegAvailable === 'function'+ ? await deps.ffmpegAvailable()+ : deps.ffmpegAvailablereturn {protocolVersion: '1.0',server: {@@ -83,8 +89,8 @@ function buildResult(deps: InitializeHandlerDeps): InitializeResult {runtime: deps.runtime,},capabilities: {- ffmpegAvailable: deps.ffmpegAvailable,- selectionKinds: deps.ffmpegAvailable+ ffmpegAvailable,+ selectionKinds: ffmpegAvailable? ['direct', 'hls', 'dash', 'mux']: ['direct'],progress: true,diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.tsindex e016b792..75e34b57 100644--- a/src/core/bridge/web-socket-bridge-server.ts+++ b/src/core/bridge/web-socket-bridge-server.ts@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'import type { IncomingMessage, ServerResponse } from 'node:http'import { createServer, type Server as HttpServer } from 'node:http'import type { Duplex } from 'node:stream'+import { BridgeReceiverError } from '@core/bridge-receiver/errors'import { AsyncWorkTracker } from '@core/inspector-activity/async-work-tracker'import { DownloadSourceError } from '@core/task/source-admission'import {@@ -74,7 +75,7 @@ export interface BridgeServerOptions {registry: TrustedExtensionRegistrymotrixVersion: stringruntime: 'electron' | 'server'- ffmpegAvailable: boolean+ ffmpegAvailable: boolean | (() => Promise<boolean>)/*** Machine-owner Bearer token for the unary `POST /mdxp` transport. Generated* per bridge start, mirrored into `endpoint.json` (mode 0600). Held in memory@@ -1073,10 +1074,28 @@ export class WebSocketBridgeServer {/** Register the shell's domain handlers. Call BEFORE the first connection. */setHandlers(handlers: MethodHandlers): void {if (handlers.submitDownload) {+ const submit = handlers.submitDownloadthis.dispatcher.register('download/submit',DownloadSubmitParamsSchema,- handlers.submitDownload+ async (params, ctx) => {+ try {+ return await submit(params, ctx)+ } catch (error) {+ // This rejection occurs before a media task is created. Preserve+ // its public MDXP code so clients can safely offer a retry.+ if (+ error instanceof BridgeReceiverError &&+ error.code === 'unsupported-kind'+ ) {+ throw new ResponseError(+ ErrorCodes.CapabilityNotSupported,+ 'Media selection is not supported'+ )+ }+ throw error+ }+ })}if (handlers.cancelDownload) {diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex 1487ec3b..6dd603c9 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -240,7 +240,7 @@ export interface BridgeRuntime {* The shared MuxPipeline used by BridgeReceiver. Exposed read-only so the* desktop Add-Task path can reuse the SAME coordinator instance — never* construct a second one (that would reintroduce the SP-1 phantom-task bug).- * Undefined when ffmpeg is unavailable.+ * Undefined when this runtime has no media pipeline.*/muxPipeline:| import('@core/bridge-receiver/pipelines/mux-pipeline').MuxPipeline@@ -401,7 +401,7 @@ export async function syncNativeMessagingManifests(args: {export async function bootstrapBridge(args: {getMainWindow: () => Electron.BrowserWindow | nullmotrixVersion: string- ffmpegAvailable: boolean+ ffmpegAvailable: boolean | (() => Promise<boolean>)enabled: boolean// new — required for ③. `off` is needed so the SSE stream source can// unsubscribe on shutdown (else listeners leak dead server instances across@@ -430,8 +430,8 @@ export async function bootstrapBridge(args: {readHandlerDeps: ReadHandlerDeps// Spec 4 — v1 WRITE methods (pause/resume/remove/add).writeHandlerDeps: WriteHandlerDeps- // T14/T15 media pipeline deps. Threaded here so T15 can inject real values.- // Until T15 wires them, ffmpegBinaryPath=null disables the media pipeline.+ // A live resolver keeps the media pipeline available when FFmpeg is+ // configured after startup. Shells without media support omit it.ffmpegBinaryPath: string | null/** Re-resolves the current executable immediately before each mux. */resolveFfmpegBinaryPath?: BridgeReceiverDeps['resolveFfmpegBinaryPath']diff --git a/src/main/index.ts b/src/main/index.tsindex b2189710..ec9cb1fe 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2429,7 +2429,6 @@ async function initializeMainProcess(): Promise<void> {},(candidate) => resolveExecutable(candidate, process.env))- const ff = await resolveFfmpegLocation()const segmentAria2Client = new Aria2SegmentClient(rpcClient, adapter)segmentClient = segmentAria2Clientconst revealInFolder = createRevealInFolderHandler({@@ -2447,7 +2446,7 @@ async function initializeMainProcess(): Promise<void> {mediaMetaStore,getMainWindow: () => windowManager?.get('main') ?? null,motrixVersion: app.getVersion(),- ffmpegAvailable: ff.available,+ ffmpegAvailable: async () => (await resolveFfmpegLocation()).available,enabled: true,// Read fresh on every factory invocation (including a hot restart from// BridgeManager.restart()), so a `bridge.fixedPort`/`instanceId` change@@ -2494,7 +2493,7 @@ async function initializeMainProcess(): Promise<void> {(await torrentParser.parse(base64)).files.length,revealTask: (taskId) => revealInFolder({ taskId }),},- ffmpegBinaryPath: ff.binaryPath,+ ffmpegBinaryPath: null,resolveFfmpegBinaryPath: async () =>(await resolveFfmpegLocation()).binaryPath,publishTaskUpdate,diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 700b02fd..81988efe 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -1,5 +1,6 @@import { realpath } from 'node:fs/promises'import path from 'node:path'+import { BridgeReceiverError } from '@core/bridge-receiver/errors'import type { AdaptedMux } from '@core/bridge-receiver/submit-download-adapter'import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'import { dnsModeToAsyncDns } from '@core/engine/aria2/dns-fallback'@@ -135,6 +136,7 @@ import type { CliToolService } from '../cli/cli-tool-service'import { MenuContextPatchSchema } from '../commands/context-schema'import type { ContextStore } from '../commands/context-store'import type { UpdateManager } from '../core/update-manager'+import { i18n } from '../lib/i18n'import {enableAppImageIntegrationFromSettings,reconcileAppImageIntegrationFromSettings,@@ -359,20 +361,29 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {// Bilibili HD comes via the extension submit path, which carries cookies.resolveToMux: (url: string) =>bridgeManager.current?.resolveToMux(url) ?? Promise.resolve(null),- // A resolver can produce a mux pair WITHOUT ffmpeg (it only queries APIs),- // but actually downloading it needs the MuxPipeline, which exists only when- // ffmpeg is available. Throw a clear, actionable error instead of a- // TypeError when the pipeline is absent (bridge disabled / no ffmpeg) —- // mirrors the extension path's "ffmpeg unavailable" guard in BridgeReceiver.- dispatchMux: (adapted: AdaptedMux) => {+ // Share the receiver's live FFmpeg check with desktop submissions.+ dispatchMux: async (adapted: AdaptedMux) => {const mux = bridgeManager.current?.muxPipelineif (!mux) {throw new AppError(ErrorCode.EngineFeatureUnavailable,- 'ffmpeg is required to download this video: its video and audio are separate streams that must be muxed. Install ffmpeg (or set MOTRIX_FFMPEG_BIN) and restart Motrix.'+ i18n.t('settings.integration.media.pipelineUnavailable'))}- return mux.dispatch(adapted)+ try {+ return await mux.dispatch(adapted)+ } catch (error) {+ if (+ error instanceof BridgeReceiverError &&+ error.code === 'unsupported-kind'+ ) {+ throw new AppError(+ ErrorCode.EngineFeatureUnavailable,+ i18n.t('settings.integration.media.ffmpegRequired')+ )+ }+ throw error+ }},}diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsxindex 1b941f61..2f60bf01 100644--- a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx@@ -1,16 +1,19 @@import '@test-utils/dom-animations'import '@renderer/lib/i18n'import '@testing-library/jest-dom/vitest'+import { toast } from '@renderer/components/ui/toast'import {CliInstallCapability,CliPackageManager,CliToolPhase,CliToolReason,} from '@shared/types/cli-tool'-import { render, screen } from '@testing-library/react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'+vi.mock('@renderer/components/ui/toast', () => ({ toast: { add: vi.fn() } }))+// Mutable so individual tests can flip the bridge's reported port status// (Task 21) without redefining the whole `vi.mock` factory per test.const bridgeStatus = vi.hoisted(() => ({@@ -192,6 +195,71 @@ describe('IntegrationDialog scaffold', () => {)})+ it.each([true, false])(+ 'shows the plugin restart reminder only after a successful FFmpeg save (%s)',+ async (saved) => {+ const original = vi.mocked(transport.invoke).getMockImplementation()!+ vi.mocked(transport.invoke).mockImplementation(+ async (channel, ...args) => {+ if (channel === 'command:updateSettings') {+ if (!saved) throw new Error('Save failed')+ return { ok: true }+ }+ return original(channel, ...args)+ }+ )+ const onClose = vi.fn()+ try {+ render(+ <IntegrationDialog+ open+ onClose={onClose}+ labelKey="settings.cards.integration.title"+ descKey="settings.cards.integration.desc"+ />+ )+ fireEvent.click(+ await screen.findByRole('button', { name: 'Show detection details' })+ )+ fireEvent.click(+ screen.getByRole('button', { name: 'Edit custom FFmpeg path' })+ )+ fireEvent.change(+ screen.getByRole('textbox', { name: 'Custom FFmpeg path' }),+ { target: { value: '/configured/ffmpeg' } }+ )+ expect(toast.add).not.toHaveBeenCalled()+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ 'command:updateSettings',+ { media: { ffmpegBinaryPath: '/configured/ffmpeg' } }+ )+ )+ if (saved) {+ await waitFor(() =>+ expect(toast.add).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'FFmpeg settings saved',+ description: expect.stringContaining(+ 'Restart Motrix for active plugins'+ ),+ timeout: 0,+ })+ )+ )+ expect(onClose).toHaveBeenCalled()+ } else {+ await screen.findByText('Couldn’t save your changes. Try again.')+ expect(toast.add).not.toHaveBeenCalled()+ expect(onClose).not.toHaveBeenCalled()+ }+ } finally {+ vi.mocked(transport.invoke).mockImplementation(original)+ }+ }+ )+it('keeps the dialog open when the saved magnet association was rejected', async () => {const onClose = vi.fn()vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsxindex e239b8f5..bd34e329 100644--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx@@ -19,6 +19,7 @@ import {ScrollBar,} from '@renderer/components/ui/scroll-area'import { Separator } from '@renderer/components/ui/separator'+import { toast } from '@renderer/components/ui/toast'import { pickDirty } from '@renderer/lib/form-utils'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'@@ -107,6 +108,18 @@ export function IntegrationDialog({const result = (await transport.invoke(Commands.UpdateSettings, patch)) as {protocolAssociationApplied?: boolean}+ if (dirty.media?.ffmpegBinaryPath !== undefined) {+ toast.add({+ title: t('settings.integration.media.savedTitle'),+ description: t(+ isWeb+ ? 'settings.integration.media.restartHint'+ : 'settings.integration.media.desktopSavedHint'+ ),+ type: 'info',+ timeout: 0,+ })+ }if (result.protocolAssociationApplied === false) {setSaveError(t('settings.integration.system.protocolMagnetApplyFailed'))returndiff --git a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx b/src/renderer/routes/settings/cards/integration/media-tools-section.tsxindex d4fe5a24..7d54a0ad 100644--- a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.tsx@@ -178,6 +178,12 @@ export function MediaToolsSection() {</div></div>+ {transport.platform !== 'web' && (+ <p className="text-xs text-muted-foreground">+ {t('settings.integration.media.applyHint')}+ </p>+ )}+<Collapsibleopen={detailsOpen || Boolean(pathError)}onOpenChange={setDetailsOpen}diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 39618f97..99d93f20 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1797,7 +1797,12 @@"restartNow": "Restart now","validation": {"fileMissing": "File does not exist at this path."- }+ },+ "applyHint": "Save to apply the custom path. Media downloads use the current FFmpeg path without restarting Motrix; rescan in the browser extension to refresh support.",+ "savedTitle": "FFmpeg settings saved",+ "desktopSavedHint": "New media downloads read the saved path. Restart Motrix for active plugins to detect the change.",+ "pipelineUnavailable": "Media download support is unavailable.",+ "ffmpegRequired": "This download requires FFmpeg. Configure it in Settings → Integration → Media tools, save, then retry."},"pairResolveFailed": "Couldn’t submit your decision — try again.","appimage": {diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 733beaa7..add7214f 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1779,11 +1779,16 @@"opTimeoutSecDesc": "单次 FFmpeg 操作的最长执行时间。默认 1800 秒(30 分钟),上限 3600。","cleanupStaging": "清理临时文件残留","cleanupConfirm": "删除所有 FFmpeg 临时目录?",- "restartHint": "已保存。重启 Motrix 后,已激活的插件才能感知变化。",+ "restartHint": "已保存。重启 Motrix 后,已启用的插件才能检测到更改。","restartNow": "立即重启","validation": {"fileMissing": "该路径不存在。"- }+ },+ "applyHint": "修改自定义路径后需点击“保存”。媒体下载会读取当前 FFmpeg 路径,无须重启 Motrix;请在浏览器扩展中重新扫描以刷新支持状态。",+ "savedTitle": "FFmpeg 配置已保存",+ "desktopSavedHint": "新媒体下载会读取保存的路径。已启用的插件需要重启 Motrix 才能检测到此次更改。",+ "pipelineUnavailable": "媒体下载功能当前不可用。",+ "ffmpegRequired": "此下载需要 FFmpeg。请在“设置 → 集成 → 媒体工具”中配置并保存后重试。"},"pairResolveFailed": "提交决定失败,请重试。","appimage": {diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 59f916f3..ff5a6a00 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1779,11 +1779,16 @@"opTimeoutSecDesc": "單一 FFmpeg 作業的最長時間。預設為 1800 秒 (30 分鐘),上限為 3600。","cleanupStaging": "清理暫存檔案","cleanupConfirm": "要移除所有 FFmpeg 暫存目錄嗎?",- "restartHint": "已儲存。請重新啟動 Motrix,讓使用中的外掛程式偵測變更。",+ "restartHint": "已儲存。重新啟動 Motrix 後,已啟用的外掛才能偵測到變更。","restartNow": "立即重新啟動","validation": {"fileMissing": "此路徑不存在檔案。"- }+ },+ "applyHint": "修改自訂路徑後需點選「儲存」。媒體下載會讀取目前的 FFmpeg 路徑,無須重新啟動 Motrix;請在瀏覽器擴充功能中重新掃描以更新支援狀態。",+ "savedTitle": "FFmpeg 設定已儲存",+ "desktopSavedHint": "新的媒體下載會讀取儲存的路徑。已啟用的外掛需要重新啟動 Motrix 才能偵測到此次變更。",+ "pipelineUnavailable": "媒體下載功能目前無法使用。",+ "ffmpegRequired": "此下載需要 FFmpeg。請在「設定 → 整合 → 媒體工具」中設定並儲存後重試。"},"pairResolveFailed": "無法提交您的決定,請再試一次。","appimage": {