Skip to content

A full-featured download manager.

fix: stabilize browser bridge and FFmpeg media workflow (#2019)

Dr_rOot0caa7e1aebec
diff --git a/packages/native-host/src/flatpak_companion.rs b/packages/native-host/src/flatpak_companion.rs
index 01e4720b..6fda249a 100644
--- a/packages/native-host/src/flatpak_companion.rs
+++ b/packages/native-host/src/flatpak_companion.rs
@@ -1356,7 +1356,7 @@ mod tests {
use crate::resolve::{ResolveError, ResolveResult};
const CHROMIUM_ID: &str = "ibpkjhgpbidfmbmomagmldcdlpbmchgi";
- const FIREFOX_ID: &str = "[email protected]";
+ const FIREFOX_ID: &str = "[email protected]";
const NONCE: &str = "AbCdEfGhIjKlMnOpQrStUv";
struct TempDir {
diff --git a/src/core/bridge-receiver/bridge-receiver.ts b/src/core/bridge-receiver/bridge-receiver.ts
index b804f7f1..dd7d7f79 100644
--- a/src/core/bridge-receiver/bridge-receiver.ts
+++ b/src/core/bridge-receiver/bridge-receiver.ts
@@ -73,6 +73,11 @@ export interface BridgeReceiverDeps {
localize: (code: BridgeErrorCode) => string
/** Path to ffmpeg binary. When null, hls/dash/mux submissions are rejected. */
ffmpegBinaryPath: string | null
+ /**
+ * Live resolver used immediately before muxing. Defaults to the startup
+ * path for shells/tests that do not provide dynamic resolution.
+ */
+ resolveFfmpegBinaryPath?: () => Promise<string | null>
taskManager: TaskManager
activityRecorder: TaskActivityRecorder
/** Coalesced / immediate TaskUpdated publication (TaskUpdatePublisher),
@@ -214,7 +219,9 @@ export class BridgeReceiver {
eventBus: eventBusWithEmit,
publishTaskUpdate: deps.publishTaskUpdate,
publishTaskUpdateNow: deps.publishTaskUpdateNow,
- ffmpegBinaryPath: deps.ffmpegBinaryPath,
+ resolveFfmpegBinaryPath:
+ deps.resolveFfmpegBinaryPath ??
+ (() => Promise.resolve(deps.ffmpegBinaryPath)),
pickName: deps.pickName,
persist: deps.persistTask,
persistTaskWithOccurrence: deps.persistTaskWithOccurrence,
diff --git a/src/core/ffmpeg/ffmpeg-locator.test.ts b/src/core/ffmpeg/ffmpeg-locator.test.ts
index e08d61a7..87e9f733 100644
--- a/src/core/ffmpeg/ffmpeg-locator.test.ts
+++ b/src/core/ffmpeg/ffmpeg-locator.test.ts
@@ -2,11 +2,9 @@ import { describe, expect, it, vi } from 'vitest'
import { locateFfmpeg } from './ffmpeg-locator'
describe('locateFfmpeg', () => {
- it('returns the active binary when PATH probe succeeds', async () => {
- const probe = vi.fn(async (p: string) =>
- p === 'ffmpeg'
- ? { available: true, binaryPath: 'ffmpeg', version: '7.1' }
- : { available: false }
+ it('returns the resolved PATH binary without probing its version', async () => {
+ const resolveExecutable = vi.fn(async (p: string) =>
+ p === 'ffmpeg' ? '/usr/local/bin/ffmpeg' : null
)
const r = await locateFfmpeg(
{
@@ -15,15 +13,45 @@ describe('locateFfmpeg', () => {
platform: 'linux',
envPath: null,
},
- probe
+ resolveExecutable
)
expect(r.available).toBe(true)
- expect(r.binaryPath).toBe('ffmpeg')
- expect(r.version).toBe('7.1')
+ expect(r.binaryPath).toBe('/usr/local/bin/ffmpeg')
+ expect(r.version).toBeNull()
+ expect(resolveExecutable).toHaveBeenCalledWith('/x/ffmpeg')
+ expect(resolveExecutable).toHaveBeenCalledWith('ffmpeg')
})
- it('reports unavailable when nothing probes', async () => {
- const probe = vi.fn(async () => ({ available: false }))
+ it('preserves manual, user data, environment, then PATH priority', async () => {
+ const resolveExecutable = vi.fn(async (candidate: string) =>
+ candidate === '/environment/ffmpeg' ? candidate : null
+ )
+ const r = await locateFfmpeg(
+ {
+ manualPath: '/manual/ffmpeg',
+ userDataBinariesDir: '/user-data/binaries',
+ platform: 'linux',
+ envPath: '/environment/ffmpeg',
+ },
+ resolveExecutable
+ )
+
+ expect(r).toEqual({
+ available: true,
+ binaryPath: '/environment/ffmpeg',
+ version: null,
+ })
+ expect(
+ resolveExecutable.mock.calls.map(([candidate]) => candidate)
+ ).toEqual([
+ '/manual/ffmpeg',
+ '/user-data/binaries/ffmpeg',
+ '/environment/ffmpeg',
+ ])
+ })
+
+ it('reports unavailable when no executable path resolves', async () => {
+ const resolveExecutable = vi.fn(async () => null)
const r = await locateFfmpeg(
{
manualPath: '',
@@ -31,9 +59,10 @@ describe('locateFfmpeg', () => {
platform: 'linux',
envPath: null,
},
- probe
+ resolveExecutable
)
expect(r.available).toBe(false)
expect(r.binaryPath).toBeNull()
+ expect(r.version).toBeNull()
})
})
diff --git a/src/core/ffmpeg/ffmpeg-locator.ts b/src/core/ffmpeg/ffmpeg-locator.ts
index d3d45862..16a43ebb 100644
--- a/src/core/ffmpeg/ffmpeg-locator.ts
+++ b/src/core/ffmpeg/ffmpeg-locator.ts
@@ -1,8 +1,6 @@
import {
- detectInOrder,
- type FfmpegDetection,
type FfmpegDetectionInput,
- probeBinary,
+ ffmpegCandidatesInOrder,
} from '@core/plugin/capabilities/ffmpeg-detect'
export interface FfmpegLocation {
@@ -11,16 +9,26 @@ export interface FfmpegLocation {
version: string | null
}
+export type ResolveExecutable = (candidate: string) => Promise<string | null>
+
+/**
+ * Locate the first executable FFmpeg candidate without running it.
+ *
+ * This is intentionally different from the explicit Settings detector, which
+ * executes `ffmpeg -version` to report a verified version. Startup callers
+ * must use this non-executing locator so quarantined user-provided binaries do
+ * not trigger an operating-system security prompt before they are used.
+ */
export async function locateFfmpeg(
input: FfmpegDetectionInput,
- probe: (p: string) => Promise<FfmpegDetection> = probeBinary
+ resolveExecutable: ResolveExecutable
): Promise<FfmpegLocation> {
- const result = await detectInOrder(input, probe)
- if (result.active) {
- return {
- available: true,
- binaryPath: result.active.path,
- version: result.active.version,
+ for (const candidate of ffmpegCandidatesInOrder(input)) {
+ if (!candidate.path) continue
+ // eslint-disable-next-line no-await-in-loop
+ const binaryPath = await resolveExecutable(candidate.path)
+ if (binaryPath) {
+ return { available: true, binaryPath, version: null }
}
}
return { available: false, binaryPath: null, version: null }
diff --git a/src/core/plugin/capabilities/ffmpeg-detect.test.ts b/src/core/plugin/capabilities/ffmpeg-detect.test.ts
index 591421bf..65c8ee2e 100644
--- a/src/core/plugin/capabilities/ffmpeg-detect.test.ts
+++ b/src/core/plugin/capabilities/ffmpeg-detect.test.ts
@@ -204,6 +204,32 @@ describe('detectInOrder', () => {
expect(r.candidates[1].state).toBe('missing')
})
+ it('keeps a macOS trust failure distinct from a missing binary', async () => {
+ const probe = makeProbe({
+ '/data/binaries/ffmpeg': {
+ available: false,
+ binaryPath: '/data/binaries/ffmpeg',
+ failureReason: 'untrusted',
+ },
+ })
+ const r = await detectInOrder(
+ {
+ manualPath: '',
+ userDataBinariesDir: '/data/binaries',
+ platform: 'darwin',
+ envPath: null,
+ },
+ probe
+ )
+
+ expect(r.active).toBeNull()
+ expect(r.candidates[1]).toMatchObject({
+ kind: 'userData',
+ path: '/data/binaries/ffmpeg',
+ state: 'untrusted',
+ })
+ })
+
it('derives the Windows userData candidate from the supplied platform', async () => {
const probe = makeProbe({})
const r = await detectInOrder(
diff --git a/src/core/plugin/capabilities/ffmpeg-detect.ts b/src/core/plugin/capabilities/ffmpeg-detect.ts
index 36d0f362..4d22f93a 100644
--- a/src/core/plugin/capabilities/ffmpeg-detect.ts
+++ b/src/core/plugin/capabilities/ffmpeg-detect.ts
@@ -8,9 +8,9 @@
// the active winner plus per-candidate state across the 4 detection
// layers (manual / userData / env / PATH) in a fixed order, regardless
// of which ones are configured. States: 'active' | 'available' |
-// 'missing' | 'unconfigured' | 'version_mismatch'. The last is reserved
-// for a future semver gate and never emitted here. The `probe` argument
-// is for test injection; production callers omit it.
+// 'missing' | 'untrusted' | 'unconfigured' | 'version_mismatch'. The last
+// is reserved for a future semver gate and never emitted here. The `probe`
+// argument is for test injection; production callers omit it.
//
// Used by shell wrappers (Electron + Server) that supply the candidate list.
// This module MUST NOT import electron, @main/, or @server/.
@@ -23,10 +23,14 @@ import path from 'node:path'
// Types
// ---------------------------------------------------------------------------
+export type FfmpegDetectionFailureReason = 'missing' | 'untrusted'
+
export interface FfmpegDetection {
available: boolean
binaryPath?: string
version?: string
+ /** Why a host-specific preflight declined to execute this candidate. */
+ failureReason?: FfmpegDetectionFailureReason
}
// ---------------------------------------------------------------------------
@@ -139,10 +143,16 @@ export interface FfmpegDetectionInput {
export type CandidateKind = 'manual' | 'userData' | 'env' | 'path'
+export interface FfmpegCandidate {
+ kind: CandidateKind
+ path: string | null
+}
+
export type CandidateState =
| 'active'
| 'available'
| 'missing'
+ | 'untrusted'
| 'unconfigured'
| 'version_mismatch'
@@ -160,6 +170,25 @@ function ffmpegBinName(platform: string): string {
return platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
}
+/**
+ * Build the fixed-priority candidate list without touching the filesystem or
+ * executing any candidate. Startup discovery and explicit version probing use
+ * this same list so their precedence cannot drift.
+ */
+export function ffmpegCandidatesInOrder(
+ input: FfmpegDetectionInput
+): FfmpegCandidate[] {
+ return [
+ { kind: 'manual', path: input.manualPath || null },
+ {
+ kind: 'userData',
+ path: path.join(input.userDataBinariesDir, ffmpegBinName(input.platform)),
+ },
+ { kind: 'env', path: input.envPath },
+ { kind: 'path', path: 'ffmpeg' },
+ ]
+}
+
/**
* Probe all 4 detection layers in fixed order and return a per-candidate
* report plus the active winner.
@@ -174,7 +203,8 @@ function ffmpegBinName(platform: string): string {
* rewrite to an absolute path).
* - Probe succeeds but a higher-priority candidate already won →
* `'available'` (still includes version).
- * - Probe fails → `'missing'`.
+ * - Probe reports `failureReason: 'untrusted'` → `'untrusted'`.
+ * - Any other probe failure → `'missing'`.
* - `'version_mismatch'` is reserved for a future semver gate; this
* function never emits it.
*
@@ -184,21 +214,10 @@ export async function detectInOrder(
input: FfmpegDetectionInput,
probe: (binaryPath: string) => Promise<FfmpegDetection> = probeBinary
): Promise<FfmpegDetectionResult> {
- const userDataCandidate = path.join(
- input.userDataBinariesDir,
- ffmpegBinName(input.platform)
- )
- const order: Array<{ kind: CandidateKind; path: string | null }> = [
- { kind: 'manual', path: input.manualPath || null },
- { kind: 'userData', path: userDataCandidate },
- { kind: 'env', path: input.envPath },
- { kind: 'path', path: 'ffmpeg' },
- ]
-
const candidates: FfmpegDetectionResult['candidates'] = []
let active: FfmpegDetectionResult['active'] = null
- for (const entry of order) {
+ for (const entry of ffmpegCandidatesInOrder(input)) {
const p = entry.path
if (!p) {
candidates.push({ kind: entry.kind, path: null, state: 'unconfigured' })
@@ -227,7 +246,11 @@ export async function detectInOrder(
})
}
} else {
- candidates.push({ kind: entry.kind, path: p, state: 'missing' })
+ candidates.push({
+ kind: entry.kind,
+ path: p,
+ state: result.failureReason === 'untrusted' ? 'untrusted' : 'missing',
+ })
}
}
diff --git a/src/core/task/media-mux-e2e.test.ts b/src/core/task/media-mux-e2e.test.ts
index 1f779f02..e6a82899 100644
--- a/src/core/task/media-mux-e2e.test.ts
+++ b/src/core/task/media-mux-e2e.test.ts
@@ -138,7 +138,7 @@ describe.skipIf(
eventBus: { emit() {} },
publishTaskUpdate: () => {},
publishTaskUpdateNow: () => {},
- ffmpegBinaryPath: FFMPEG as string,
+ resolveFfmpegBinaryPath: async () => FFMPEG as string,
makeDownloader: (tmpDir) =>
new SegmentDownloader({ aria2: segmentClient, tmpDir }),
decryptor: new SegmentDecryptor(),
diff --git a/src/core/task/media-task-coordinator.test.ts b/src/core/task/media-task-coordinator.test.ts
index 40782ebb..593a1a34 100644
--- a/src/core/task/media-task-coordinator.test.ts
+++ b/src/core/task/media-task-coordinator.test.ts
@@ -146,7 +146,7 @@ function makeDeps(overrides?: Partial<MediaCoordinatorDeps>): {
recordDownloadCompleted: vi.fn(),
},
eventBus,
- ffmpegBinaryPath: '/usr/bin/ffmpeg',
+ resolveFfmpegBinaryPath: vi.fn(async () => '/usr/bin/ffmpeg'),
makeDownloader: (_tmpDir: string) => {
const fake = makeDownloaderFake()
downloaderFakes.push(fake)
@@ -399,6 +399,42 @@ describe('MediaTaskCoordinator.start', () => {
expect(jobArg?.fromMpegts).toBe(false)
})
+ it('resolves the current ffmpeg path immediately before muxing', async () => {
+ const resolveFfmpegBinaryPath = vi.fn(
+ async () => '/opt/homebrew/bin/ffmpeg'
+ )
+ const { deps, downloaderFakes, ffmpegFakes } = makeDeps({
+ resolveFfmpegBinaryPath,
+ })
+
+ await new MediaTaskCoordinator(deps).start(baseJob())
+
+ const jobArg = ffmpegFakes[0]?.run.mock.calls[0]?.[0] as {
+ binaryPath: string
+ }
+ expect(resolveFfmpegBinaryPath).toHaveBeenCalledOnce()
+ expect(jobArg.binaryPath).toBe('/opt/homebrew/bin/ffmpeg')
+ expect(
+ resolveFfmpegBinaryPath.mock.invocationCallOrder[0] ?? -1
+ ).toBeGreaterThan(downloaderFakes[0]?.run.mock.invocationCallOrder[0] ?? -1)
+ })
+
+ it('does not spawn ffmpeg when no executable is available at mux time', async () => {
+ const { deps, ffmpegFakes, taskManager } = makeDeps({
+ resolveFfmpegBinaryPath: vi.fn(async () => null),
+ mintTaskId: () => 'ffmpeg-missing-at-mux',
+ })
+
+ await expect(
+ new MediaTaskCoordinator(deps).start(baseJob())
+ ).rejects.toThrow('mux-failed: ffmpeg executable is unavailable')
+
+ expect(ffmpegFakes[0]?.run).not.toHaveBeenCalled()
+ expect(taskManager.getById('ffmpeg-missing-at-mux')?.errorMessage).toBe(
+ 'mux-failed'
+ )
+ })
+
it('calls decryptor.decrypt for segments with keys', async () => {
const keyBytes = new Uint8Array(16).fill(0xab)
const iv = new Uint8Array(16).fill(0x01)
diff --git a/src/core/task/media-task-coordinator.ts b/src/core/task/media-task-coordinator.ts
index 79951fa7..60749963 100644
--- a/src/core/task/media-task-coordinator.ts
+++ b/src/core/task/media-task-coordinator.ts
@@ -75,7 +75,12 @@ export interface MediaCoordinatorDeps {
*/
publishTaskUpdate: () => void
publishTaskUpdateNow: () => void
- ffmpegBinaryPath: string
+ /**
+ * Resolve the executable immediately before muxing. Media downloads can run
+ * for a long time, so a path captured at app startup may have been removed
+ * or superseded by a settings change before FFmpeg is actually spawned.
+ */
+ resolveFfmpegBinaryPath: () => Promise<string | null>
makeDownloader: (tmpDir: string) => SegmentDownloader
decryptor: SegmentDecryptor
assemble: typeof assembleSegments
@@ -586,9 +591,14 @@ export class MediaTaskCoordinator {
const ffmpeg = this.deps.makeFfmpeg()
state.ffmpeg = ffmpeg
+ const ffmpegBinaryPath = await this.deps.resolveFfmpegBinaryPath()
+ if (!ffmpegBinaryPath) {
+ throw new Error('mux-failed: ffmpeg executable is unavailable')
+ }
+
await ffmpeg.run(
{
- binaryPath: this.deps.ffmpegBinaryPath,
+ binaryPath: ffmpegBinaryPath,
videoPath: videoAssembled,
audioPath: audioAssembled,
// Mux INTO the placeholder — the final name only appears on disk
diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.ts
index 518af9e0..a414320c 100644
--- a/src/main/bridge/index.ts
+++ b/src/main/bridge/index.ts
@@ -376,6 +376,8 @@ export async function bootstrapBridge(args: {
// T14/T15 media pipeline deps. Threaded here so T15 can inject real values.
// Until T15 wires them, ffmpegBinaryPath=null disables the media pipeline.
ffmpegBinaryPath: string | null
+ /** Re-resolves the current executable immediately before each mux. */
+ resolveFfmpegBinaryPath?: BridgeReceiverDeps['resolveFfmpegBinaryPath']
/** Coalesced / immediate TaskUpdated publication (TaskUpdatePublisher),
* threaded through BridgeReceiver into the MediaTaskCoordinator. */
publishTaskUpdate: () => void
@@ -508,6 +510,7 @@ export async function bootstrapBridge(args: {
bridgeBus: bus,
localize,
ffmpegBinaryPath: args.ffmpegBinaryPath,
+ resolveFfmpegBinaryPath: args.resolveFfmpegBinaryPath,
publishTaskUpdate: args.publishTaskUpdate,
publishTaskUpdateNow: args.publishTaskUpdateNow,
taskManager: args.taskManager,
diff --git a/src/main/bridge/native-host-path.test.ts b/src/main/bridge/native-host-path.test.ts
index 061778a3..7371c5e6 100644
--- a/src/main/bridge/native-host-path.test.ts
+++ b/src/main/bridge/native-host-path.test.ts
@@ -142,7 +142,7 @@ describe('resolveNativeHostBinaryPath', () => {
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const manifest = JSON.parse(
@@ -192,7 +192,7 @@ describe('resolveNativeHostBinaryPath', () => {
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const manifest = JSON.parse(
diff --git a/src/main/bridge/native-messaging-extensions.test.ts b/src/main/bridge/native-messaging-extensions.test.ts
index 78527818..f5c2dec7 100644
--- a/src/main/bridge/native-messaging-extensions.test.ts
+++ b/src/main/bridge/native-messaging-extensions.test.ts
@@ -19,4 +19,17 @@ describe('native messaging extension allowlist', () => {
]
expect(new Set(all).size).toBe(all.length)
})
+
+ // Cross-repo contract: these literals must match the extension's real
+ // store identities. The Firefox ID is declared in
+ // motrix-extension/packages/ext/manifest.config.ts and pinned by a mirror
+ // test there; changing either side requires changing both.
+ it('allowlists the store-signed extension identities', () => {
+ expect(nativeMessagingExtensions.chromium).toContain(
+ 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'
+ )
+ expect(nativeMessagingExtensions.firefox).toContain(
+ )
+ })
})
diff --git a/src/main/bridge/native-messaging-installer.test.ts b/src/main/bridge/native-messaging-installer.test.ts
index 862b44de..7946066f 100644
--- a/src/main/bridge/native-messaging-installer.test.ts
+++ b/src/main/bridge/native-messaging-installer.test.ts
@@ -50,7 +50,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
})
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const chromeContent = JSON.parse(
await readFile(
@@ -76,7 +76,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
})
await installer.syncManifests({
chromium: [],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const ff = JSON.parse(
await readFile(
@@ -87,7 +87,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
'utf-8'
)
)
- expect(ff.allowed_extensions).toEqual(['[email protected]'])
+ expect(ff.allowed_extensions).toEqual(['[email protected]'])
})
it('leaves host-side manifests to an external Flatpak companion', async () => {
@@ -107,7 +107,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
await installer.unregister()
@@ -134,7 +134,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
})
await installer.syncManifests({
chromium: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
expect(JSON.parse(await readFile(paths.chromium, 'utf-8'))).toEqual(
@@ -165,7 +165,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
})
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
expect(JSON.parse(await readFile(paths.chromium, 'utf-8')).path).toBe(
@@ -183,7 +183,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
})
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const replacement = {
@@ -295,7 +295,7 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {
'chromewebstoreidaaaaaaaaaaaaaaaa',
'edgeaddonsidbbbbbbbbbbbbbbbbbbbb',
],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const edge = JSON.parse(
await readFile(
@@ -325,7 +325,7 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {
'chromewebstoreidaaaaaaaaaaaaaaaa',
'edgeaddonsidbbbbbbbbbbbbbbbbbbbb',
],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
const keyPaths = written.map(({ entry }) => entry.keyPath)
@@ -357,7 +357,7 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {
})
await installer.syncManifests({
chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
expect(written).toEqual([])
})
@@ -375,7 +375,7 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {
})
await installer.syncManifests({
chromium: ['chromewebstoreidaaaaaaaaaaaaaaaa'],
- firefox: ['[email protected]'],
+ firefox: ['[email protected]'],
})
await installer.unregister()
diff --git a/src/main/index.ts b/src/main/index.ts
index f5c81c30..be22ac80 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -128,6 +128,7 @@ import {
resolvePackagedLinuxSnapEnvironment,
} from './bridge/snap-environment'
import { CliToolService } from './cli/cli-tool-service'
+import { resolveExecutable } from './cli/shell-environment'
import { CommandRegistry } from './commands/command-registry'
import { ContextStore } from './commands/context-store'
import { registerAllCommands } from './commands/definitions'
@@ -168,6 +169,7 @@ import { createElectronPlatformServices } from './platform/services'
import { setupTray } from './platform/tray'
import { createElectronCapabilityHost } from './plugin/capability-host'
import { startDevWatcher } from './plugin/dev-watcher'
+import { resolveElectronFfmpegEnvPath } from './plugin/ffmpeg-detect-electron'
import { resolvePluginHostLanguage } from './plugin/host-language'
import { resolvePluginsDir } from './plugin/plugins-dir'
import { createMainProxyApplier } from './proxy/wiring'
@@ -2174,15 +2176,20 @@ async function initializeMainProcess(): Promise<void> {
publishTaskUpdateNow,
}
const ffmpegBinariesDir = path.join(platform.userDataDir, 'binaries')
- // Honor the user's configured ffmpeg path (Settings → Media). Without this
- // the locator ignored the setting and silently fell back to a bundled/PATH
- // binary, so a working user-configured ffmpeg never took effect.
- const ff = await locateFfmpeg({
- manualPath: settingsManager.getMedia().ffmpegBinaryPath,
- userDataBinariesDir: ffmpegBinariesDir,
- platform: process.platform,
- envPath: process.env.MOTRIX_FFMPEG_BIN ?? null,
- })
+ // Resolve the configured/user-provided FFmpeg path without executing it.
+ // Running `ffmpeg -version` here would trigger Gatekeeper for quarantined
+ // user binaries during app startup, before any media task needs FFmpeg.
+ const resolveFfmpegLocation = () =>
+ locateFfmpeg(
+ {
+ manualPath: settingsManager.getMedia().ffmpegBinaryPath,
+ userDataBinariesDir: ffmpegBinariesDir,
+ platform: process.platform,
+ envPath: resolveElectronFfmpegEnvPath(),
+ },
+ (candidate) => resolveExecutable(candidate, process.env)
+ )
+ const ff = await resolveFfmpegLocation()
const segmentAria2Client = new Aria2SegmentClient(rpcClient)
segmentClient = segmentAria2Client
// mediaTmpDir / mediaTmpRoot were computed once at bootstrap (above) so
@@ -2232,6 +2239,8 @@ async function initializeMainProcess(): Promise<void> {
(await torrentParser.parse(base64)).files.length,
},
ffmpegBinaryPath: ff.binaryPath,
+ resolveFfmpegBinaryPath: async () =>
+ (await resolveFfmpegLocation()).binaryPath,
publishTaskUpdate,
publishTaskUpdateNow,
taskManager,
diff --git a/src/main/plugin/capability-host.test.ts b/src/main/plugin/capability-host.test.ts
index eaf64637..3bb3c795 100644
--- a/src/main/plugin/capability-host.test.ts
+++ b/src/main/plugin/capability-host.test.ts
@@ -14,16 +14,28 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// Electron mocks — hoisted so vi.mock factories can reference them.
// ---------------------------------------------------------------------------
-const { MockNotification } = vi.hoisted(() => {
- class MockNotification {
- static isSupported = vi.fn(() => true)
- on(_ev: string, _fn: () => void): void {}
- show(): void {}
- close(): void {}
- }
-
- return { MockNotification }
-})
+const { MockNotification, mockLocateFfmpeg, mockVersionDetectorFactory } =
+ vi.hoisted(() => {
+ class MockNotification {
+ static isSupported = vi.fn(() => true)
+ on(_ev: string, _fn: () => void): void {}
+ show(): void {}
+ close(): void {}
+ }
+
+ return {
+ MockNotification,
+ mockLocateFfmpeg: vi.fn(async () => ({
+ available: false,
+ binaryPath: null as string | null,
+ version: null,
+ })),
+ mockVersionDetectorFactory: vi.fn(() => async () => ({
+ active: null,
+ candidates: [],
+ })),
+ }
+ })
// Note: no safeStorage mock — the Electron capability host no longer uses
// Electron's keychain-backed safeStorage. Secrets are handled by the
@@ -36,13 +48,15 @@ vi.mock('electron', () => ({
},
}))
-// Mock ffmpeg-detect-electron to avoid spawning a real process. The factory
-// returns a closure that yields the enriched FfmpegDetectionResult shape.
+vi.mock('@core/ffmpeg/ffmpeg-locator', () => ({
+ locateFfmpeg: mockLocateFfmpeg,
+}))
+
+// The eager detector remains mocked as a regression sentinel: capability-host
+// construction must never invoke it because it executes `ffmpeg -version`.
vi.mock('./ffmpeg-detect-electron', () => ({
- makeElectronFfmpegDetect: vi.fn(() => async () => ({
- active: null,
- candidates: [],
- })),
+ makeElectronFfmpegDetect: mockVersionDetectorFactory,
+ resolveElectronFfmpegEnvPath: vi.fn(() => null),
}))
// ---------------------------------------------------------------------------
@@ -88,6 +102,8 @@ describe('createElectronCapabilityHost', () => {
beforeEach(() => {
db = makeDb()
MockNotification.isSupported.mockClear()
+ mockLocateFfmpeg.mockClear()
+ mockVersionDetectorFactory.mockClear()
})
afterEach(() => {
@@ -126,6 +142,31 @@ describe('createElectronCapabilityHost', () => {
expect(MockNotification.isSupported).not.toHaveBeenCalled()
})
+ it('locates FFmpeg without running the version detector at startup', async () => {
+ mockLocateFfmpeg.mockResolvedValueOnce({
+ available: true,
+ binaryPath: '/user-data/binaries/ffmpeg',
+ version: null,
+ })
+
+ const host = await createElectronCapabilityHost({
+ appVersion: '2.0.0',
+ hostLanguage: 'en-US',
+ db,
+ userDataDir: '/user-data',
+ pluginsDir: path.join(tmpdir(), 'plugins'),
+ settingsManager: makeSettingsManager(),
+ configReader: () => ({}),
+ secretFieldsFor: () => new Set(),
+ manifestCommandIdsFor: () => new Set(),
+ })
+
+ expect(mockLocateFfmpeg).toHaveBeenCalledOnce()
+ expect(mockVersionDetectorFactory).not.toHaveBeenCalled()
+ expect(host.ffmpeg.available).toBe(true)
+ expect(host.ffmpeg.version).toBeUndefined()
+ })
+
it('returns a CapabilityHost with a functional storage host', async () => {
const host = await createElectronCapabilityHost({
appVersion: '2.0.0',
diff --git a/src/main/plugin/capability-host.ts b/src/main/plugin/capability-host.ts
index 1b00d135..c782b18f 100644
--- a/src/main/plugin/capability-host.ts
+++ b/src/main/plugin/capability-host.ts
@@ -1,10 +1,10 @@
import path from 'node:path'
+import { locateFfmpeg } from '@core/ffmpeg/ffmpeg-locator'
import { AppCapabilityHost } from '@core/plugin/capabilities/app'
import { CommandsCapabilityHost } from '@core/plugin/capabilities/commands'
import { ConfigCapabilityHost } from '@core/plugin/capabilities/config'
import { CryptoCapabilityHost } from '@core/plugin/capabilities/crypto'
import { FfmpegCapabilityHost } from '@core/plugin/capabilities/ffmpeg'
-import { projectActiveToLegacy } from '@core/plugin/capabilities/ffmpeg-detect'
import { FsStorageCapabilityHost } from '@core/plugin/capabilities/fs-storage'
import { FsTaskCapabilityHost } from '@core/plugin/capabilities/fs-task'
import { HttpCapabilityHost } from '@core/plugin/capabilities/http'
@@ -28,7 +28,8 @@ import { LibsodiumSecretStore } from '@core/plugin/secret-store-libsodium'
import type { SettingsManager } from '@core/settings/settings-manager'
import type { SupportedLocale } from '@shared/constants/locales'
import type Database from 'better-sqlite3'
-import { makeElectronFfmpegDetect } from './ffmpeg-detect-electron'
+import { resolveExecutable } from '../cli/shell-environment'
+import { resolveElectronFfmpegEnvPath } from './ffmpeg-detect-electron'
import { ElectronNotifyHost } from './notify-electron'
export interface ElectronCapabilityHostOptions {
@@ -40,8 +41,8 @@ export interface ElectronCapabilityHostOptions {
/** Root dir for per-plugin logs, storage, etc. */
pluginsDir: string
/**
- * Provides live MediaSettings (read on every ffmpeg detect) plus any other
- * settings the capability host needs going forward.
+ * Provides MediaSettings for non-executing FFmpeg path discovery plus any
+ * other settings the capability host needs going forward.
*/
settingsManager: SettingsManager
/** Provides stored config values for a plugin. */
@@ -107,13 +108,20 @@ export async function createElectronCapabilityHost(
userDataDir: opts.userDataDir,
envSeed: process.env.MOTRIX_SECRETS_SEED,
})
- const detectFfmpeg = makeElectronFfmpegDetect({
- settingsManager: opts.settingsManager,
- userDataDir: opts.userDataDir,
+ const ffmpegLocation = await locateFfmpeg(
+ {
+ manualPath: opts.settingsManager.get().media.ffmpegBinaryPath,
+ userDataBinariesDir: path.join(opts.userDataDir, 'binaries'),
+ platform: process.platform,
+ envPath: resolveElectronFfmpegEnvPath(),
+ },
+ (candidate) => resolveExecutable(candidate, process.env)
+ )
+ const ffmpeg = new FfmpegCapabilityHost({
+ detect: ffmpegLocation.binaryPath
+ ? { available: true, binaryPath: ffmpegLocation.binaryPath }
+ : { available: false },
})
- const ffmpegResult = await detectFfmpeg()
- const ffmpegDetection = projectActiveToLegacy(ffmpegResult)
- const ffmpeg = new FfmpegCapabilityHost({ detect: ffmpegDetection })
const http = new HttpCapabilityHost() // per-plugin jar injected by Task 19 bridge
return {
diff --git a/src/main/plugin/ffmpeg-detect-electron.test.ts b/src/main/plugin/ffmpeg-detect-electron.test.ts
index 7f60415c..5c139c8e 100644
--- a/src/main/plugin/ffmpeg-detect-electron.test.ts
+++ b/src/main/plugin/ffmpeg-detect-electron.test.ts
@@ -13,6 +13,7 @@ vi.mock('@core/plugin/capabilities/ffmpeg-detect', () => ({
active: null,
candidates: [],
})),
+ probeBinary: vi.fn(async () => ({ available: false })),
}))
// Import after mock is registered.
@@ -65,6 +66,7 @@ describe('makeElectronFfmpegDetect', () => {
expect(mockedDetectInOrder).toHaveBeenCalledTimes(1)
const arg = mockedDetectInOrder.mock.calls[0][0]
expect(arg.manualPath).toBe('/custom/ffmpeg')
+ expect(mockedDetectInOrder.mock.calls[0][1]).toBeInstanceOf(Function)
})
it('joins userDataDir with "binaries" for userDataBinariesDir', async () => {
@@ -84,8 +86,8 @@ describe('makeElectronFfmpegDetect', () => {
)
})
- it('reads MOTRIX_FFMPEG_PATH into envPath', async () => {
- vi.stubEnv('MOTRIX_FFMPEG_PATH', '/opt/ff')
+ it('reads MOTRIX_FFMPEG_BIN into envPath', async () => {
+ vi.stubEnv('MOTRIX_FFMPEG_BIN', '/opt/ff')
const { manager } = makeSettingsManager({
ffmpegBinaryPath: '',
ffmpegStagingMB: 4096,
@@ -100,6 +102,39 @@ describe('makeElectronFfmpegDetect', () => {
expect(arg.envPath).toBe('/opt/ff')
})
+ it('keeps MOTRIX_FFMPEG_PATH as a legacy fallback', async () => {
+ vi.stubEnv('MOTRIX_FFMPEG_PATH', '/legacy/ffmpeg')
+ const { manager } = makeSettingsManager({
+ ffmpegBinaryPath: '',
+ ffmpegStagingMB: 4096,
+ ffmpegOpTimeoutSec: 1800,
+ })
+ const detect = makeElectronFfmpegDetect({
+ settingsManager: manager,
+ userDataDir: '/tmp/userdata',
+ })
+ await detect()
+ const arg = mockedDetectInOrder.mock.calls[0][0]
+ expect(arg.envPath).toBe('/legacy/ffmpeg')
+ })
+
+ it('prefers MOTRIX_FFMPEG_BIN over the legacy spelling', async () => {
+ vi.stubEnv('MOTRIX_FFMPEG_BIN', '/current/ffmpeg')
+ vi.stubEnv('MOTRIX_FFMPEG_PATH', '/legacy/ffmpeg')
+ const { manager } = makeSettingsManager({
+ ffmpegBinaryPath: '',
+ ffmpegStagingMB: 4096,
+ ffmpegOpTimeoutSec: 1800,
+ })
+ const detect = makeElectronFfmpegDetect({
+ settingsManager: manager,
+ userDataDir: '/tmp/userdata',
+ })
+ await detect()
+ const arg = mockedDetectInOrder.mock.calls[0][0]
+ expect(arg.envPath).toBe('/current/ffmpeg')
+ })
+
it('passes the Electron host platform and normalizes an unset env path', async () => {
const { manager } = makeSettingsManager({
ffmpegBinaryPath: '',
diff --git a/src/main/plugin/ffmpeg-detect-electron.ts b/src/main/plugin/ffmpeg-detect-electron.ts
index e19d5e10..48b65fe8 100644
--- a/src/main/plugin/ffmpeg-detect-electron.ts
+++ b/src/main/plugin/ffmpeg-detect-electron.ts
@@ -6,8 +6,8 @@
// userDataDir, and delegates to detectInOrder. The wrapper itself does NOT
// import electron — the caller (main/index.ts) passes app.getPath('userData').
//
-// Returns the enriched FfmpegDetectionResult; capability-host projects it down
-// to the legacy FfmpegDetection shape consumed by FfmpegCapabilityHost.
+// Returns the enriched FfmpegDetectionResult for explicit Settings checks.
+// Startup uses the separate non-executing locator.
import path from 'node:path'
import {
@@ -15,6 +15,7 @@ import {
type FfmpegDetectionResult,
} from '@core/plugin/capabilities/ffmpeg-detect'
import type { SettingsManager } from '@core/settings/settings-manager'
+import { makeElectronFfmpegProbe } from './ffmpeg-probe-electron'
export interface ElectronFfmpegDetectOptions {
settingsManager: SettingsManager
@@ -22,15 +23,29 @@ export interface ElectronFfmpegDetectOptions {
userDataDir: string
}
+/**
+ * Desktop builds document MOTRIX_FFMPEG_BIN. Keep the earlier
+ * MOTRIX_FFMPEG_PATH spelling as a fallback for existing installations.
+ */
+export function resolveElectronFfmpegEnvPath(
+ env: NodeJS.ProcessEnv = process.env
+): string | null {
+ return env.MOTRIX_FFMPEG_BIN ?? env.MOTRIX_FFMPEG_PATH ?? null
+}
+
export function makeElectronFfmpegDetect(
opts: ElectronFfmpegDetectOptions
): () => Promise<FfmpegDetectionResult> {
const userDataBinariesDir = path.join(opts.userDataDir, 'binaries')
+ const probe = makeElectronFfmpegProbe()
return async () =>
- detectInOrder({
- manualPath: opts.settingsManager.get().media.ffmpegBinaryPath,
- userDataBinariesDir,
- platform: process.platform,
- envPath: process.env.MOTRIX_FFMPEG_PATH ?? null,
- })
+ detectInOrder(
+ {
+ manualPath: opts.settingsManager.get().media.ffmpegBinaryPath,
+ userDataBinariesDir,
+ platform: process.platform,
+ envPath: resolveElectronFfmpegEnvPath(),
+ },
+ probe
+ )
}
diff --git a/src/main/plugin/ffmpeg-probe-electron.test.ts b/src/main/plugin/ffmpeg-probe-electron.test.ts
new file mode 100644
index 00000000..5b4203b9
--- /dev/null
+++ b/src/main/plugin/ffmpeg-probe-electron.test.ts
@@ -0,0 +1,211 @@
+import type { FfmpegDetection } from '@core/plugin/capabilities/ffmpeg-detect'
+import { describe, expect, it, vi } from 'vitest'
+import type { RunCommand, RunResult } from '../cli/command-runner'
+import { makeElectronFfmpegProbe } from './ffmpeg-probe-electron'
+
+function result(code: number | null, overrides: Partial<RunResult> = {}) {
+ return { code, stdout: '', stderr: '', ...overrides }
+}
+
+function successfulProbe(binaryPath: string): FfmpegDetection {
+ return { available: true, binaryPath, version: '7.1' }
+}
+
+describe('makeElectronFfmpegProbe', () => {
+ it('reports a candidate that cannot be resolved as missing', async () => {
+ const env = { PATH: '/tools' }
+ const resolve = vi.fn(async () => null)
+ const run: RunCommand = vi.fn(async () => result(0))
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'darwin',
+ env,
+ resolve,
+ run,
+ probe,
+ })
+
+ await expect(detect('/missing/ffmpeg')).resolves.toEqual({
+ available: false,
+ failureReason: 'missing',
+ })
+ expect(resolve).toHaveBeenCalledWith('/missing/ffmpeg', env, {
+ platform: 'darwin',
+ })
+ expect(run).not.toHaveBeenCalled()
+ expect(probe).not.toHaveBeenCalled()
+ })
+
+ it('probes an unquarantined macOS executable', async () => {
+ const run: RunCommand = vi.fn(async () => result(0))
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'darwin',
+ env: {},
+ resolve: vi.fn(async () => '/custom/ffmpeg'),
+ run,
+ probe,
+ })
+
+ await expect(detect('/custom/ffmpeg')).resolves.toEqual(
+ successfulProbe('/custom/ffmpeg')
+ )
+ expect(run).toHaveBeenCalledTimes(1)
+ expect(run).toHaveBeenCalledWith(
+ '/usr/bin/xattr',
+ ['/custom/ffmpeg'],
+ expect.any(Object)
+ )
+ expect(probe).toHaveBeenCalledWith('/custom/ffmpeg')
+ })
+
+ it('does not execute when quarantine attributes cannot be inspected', async () => {
+ const run: RunCommand = vi.fn(async () =>
+ result(1, { stderr: 'Operation not permitted' })
+ )
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'darwin',
+ env: {},
+ resolve: vi.fn(async () => '/custom/ffmpeg'),
+ run,
+ probe,
+ })
+
+ await expect(detect('/custom/ffmpeg')).resolves.toMatchObject({
+ available: false,
+ binaryPath: '/custom/ffmpeg',
+ failureReason: 'untrusted',
+ })
+ expect(probe).not.toHaveBeenCalled()
+ })
+
+ it('probes a quarantined executable accepted by Gatekeeper', async () => {
+ const run: RunCommand = vi.fn(async (command) =>
+ command === '/usr/bin/xattr'
+ ? result(0, { stdout: 'com.apple.quarantine\n' })
+ : result(0)
+ )
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'darwin',
+ env: {},
+ resolve: vi.fn(async () => '/downloads/ffmpeg'),
+ run,
+ probe,
+ })
+
+ await expect(detect('/downloads/ffmpeg')).resolves.toEqual(
+ successfulProbe('/downloads/ffmpeg')
+ )
+ expect(run).toHaveBeenNthCalledWith(
+ 2,
+ '/usr/sbin/spctl',
+ ['--assess', '--type', 'execute', '--verbose=4', '/downloads/ffmpeg'],
+ expect.any(Object)
+ )
+ expect(probe).toHaveBeenCalledWith('/downloads/ffmpeg')
+ })
+
+ it('does not execute a quarantined executable rejected by Gatekeeper', async () => {
+ const run: RunCommand = vi.fn(async (command) =>
+ command === '/usr/bin/xattr'
+ ? result(0, { stdout: 'com.apple.quarantine\n' })
+ : result(3, { stderr: 'rejected' })
+ )
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'darwin',
+ env: {},
+ resolve: vi.fn(async () => '/downloads/ffmpeg'),
+ run,
+ probe,
+ })
+
+ await expect(detect('/downloads/ffmpeg')).resolves.toEqual({
+ available: false,
+ binaryPath: '/downloads/ffmpeg',
+ failureReason: 'untrusted',
+ })
+ expect(run).toHaveBeenCalledTimes(2)
+ expect(probe).not.toHaveBeenCalled()
+ })
+
+ it('handles a failed Gatekeeper assessment conservatively', async () => {
+ const run: RunCommand = vi.fn(async (command) =>
+ command === '/usr/bin/xattr'
+ ? result(0, { stdout: 'com.apple.quarantine\n' })
+ : result(null, { timedOut: true })
+ )
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'darwin',
+ env: {},
+ resolve: vi.fn(async () => '/downloads/ffmpeg'),
+ run,
+ probe,
+ })
+
+ await expect(detect('/downloads/ffmpeg')).resolves.toMatchObject({
+ available: false,
+ binaryPath: '/downloads/ffmpeg',
+ failureReason: 'untrusted',
+ })
+ expect(probe).not.toHaveBeenCalled()
+ })
+
+ it('skips xattr and spctl outside macOS', async () => {
+ const run: RunCommand = vi.fn(async () => result(0))
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'linux',
+ env: {},
+ resolve: vi.fn(async () => '/usr/bin/ffmpeg'),
+ run,
+ probe,
+ })
+
+ await expect(detect('/usr/bin/ffmpeg')).resolves.toEqual(
+ successfulProbe('/usr/bin/ffmpeg')
+ )
+ expect(run).not.toHaveBeenCalled()
+ expect(probe).toHaveBeenCalledWith('/usr/bin/ffmpeg')
+ })
+
+ it('resolves a bare PATH candidate before probing it', async () => {
+ const env = { PATH: '/opt/homebrew/bin:/usr/bin' }
+ const resolve = vi.fn(async () => '/opt/homebrew/bin/ffmpeg')
+ const probe = vi.fn(async (binaryPath: string) =>
+ successfulProbe(binaryPath)
+ )
+ const detect = makeElectronFfmpegProbe({
+ platform: 'linux',
+ env,
+ resolve,
+ run: vi.fn(async () => result(0)),
+ probe,
+ })
+
+ await expect(detect('ffmpeg')).resolves.toEqual(
+ successfulProbe('/opt/homebrew/bin/ffmpeg')
+ )
+ expect(resolve).toHaveBeenCalledWith('ffmpeg', env, {
+ platform: 'linux',
+ })
+ expect(probe).toHaveBeenCalledWith('/opt/homebrew/bin/ffmpeg')
+ })
+})
diff --git a/src/main/plugin/ffmpeg-probe-electron.ts b/src/main/plugin/ffmpeg-probe-electron.ts
new file mode 100644
index 00000000..936c7dfb
--- /dev/null
+++ b/src/main/plugin/ffmpeg-probe-electron.ts
@@ -0,0 +1,129 @@
+// Electron-host FFmpeg probe with a non-executing macOS trust preflight.
+//
+// Candidate paths are resolved to an existing executable before any probe is
+// attempted. On macOS, quarantined binaries are assessed by Gatekeeper first,
+// so a rejected binary is never spawned merely to discover its version.
+
+import path from 'node:path'
+import {
+ type FfmpegDetection,
+ type FfmpegDetectionFailureReason,
+ probeBinary,
+} from '@core/plugin/capabilities/ffmpeg-detect'
+import { type RunCommand, runCommand } from '../cli/command-runner'
+import { resolveExecutable } from '../cli/shell-environment'
+
+const XATTR_BIN = '/usr/bin/xattr'
+const SPCTL_BIN = '/usr/sbin/spctl'
+const STATIC_CHECK_TIMEOUT_MS = 3_000
+const STATIC_CHECK_MAX_BUFFER = 64_000
+
+export type ElectronFfmpegProbeFailureReason = FfmpegDetectionFailureReason
+
+export interface ElectronFfmpegProbeResult extends FfmpegDetection {
+ failureReason?: ElectronFfmpegProbeFailureReason
+}
+
+type ResolveFfmpegExecutable = (
+ name: string,
+ env: NodeJS.ProcessEnv,
+ dependencies?: { platform?: NodeJS.Platform }
+) => Promise<string | null>
+
+type ProbeFfmpegBinary = (
+ binaryPath: string
+) => Promise<ElectronFfmpegProbeResult>
+
+export interface ElectronFfmpegProbeOptions {
+ platform?: NodeJS.Platform
+ env?: NodeJS.ProcessEnv
+ run?: RunCommand
+ resolve?: ResolveFfmpegExecutable
+ probe?: ProbeFfmpegBinary
+}
+
+function unavailable(
+ failureReason: ElectronFfmpegProbeFailureReason,
+ binaryPath?: string
+): ElectronFfmpegProbeResult {
+ return { available: false, binaryPath, failureReason }
+}
+
+/**
+ * Create a probe suitable for injection into `detectInOrder`.
+ *
+ * A quarantined macOS candidate is only executed when `spctl` accepts it.
+ * Failures to run either static inspection tool are handled conservatively.
+ */
+export function makeElectronFfmpegProbe(
+ options: ElectronFfmpegProbeOptions = {}
+): ProbeFfmpegBinary {
+ const platform = options.platform ?? process.platform
+ const env = options.env ?? process.env
+ const run = options.run ?? runCommand
+ const resolve = options.resolve ?? resolveExecutable
+ const probe = options.probe ?? probeBinary
+ const pathApi = platform === 'win32' ? path.win32 : path
+
+ return async (candidate) => {
+ let resolved: string | null
+ try {
+ resolved = await resolve(candidate, env, { platform })
+ } catch {
+ return unavailable('missing')
+ }
+
+ if (!resolved || !pathApi.isAbsolute(resolved)) {
+ return unavailable('missing')
+ }
+
+ if (platform !== 'darwin') return probe(resolved)
+
+ let quarantineResult: Awaited<ReturnType<RunCommand>>
+ try {
+ quarantineResult = await run(XATTR_BIN, [resolved], {
+ env,
+ timeoutMs: STATIC_CHECK_TIMEOUT_MS,
+ maxBuffer: STATIC_CHECK_MAX_BUFFER,
+ })
+ } catch {
+ return unavailable('untrusted', resolved)
+ }
+
+ if (
+ quarantineResult.code !== 0 ||
+ quarantineResult.timedOut ||
+ quarantineResult.spawnError
+ ) {
+ return unavailable('untrusted', resolved)
+ }
+
+ const attributes = quarantineResult.stdout.split(/\r?\n/)
+ if (!attributes.includes('com.apple.quarantine')) return probe(resolved)
+
+ let assessmentResult: Awaited<ReturnType<RunCommand>>
+ try {
+ assessmentResult = await run(
+ SPCTL_BIN,
+ ['--assess', '--type', 'execute', '--verbose=4', resolved],
+ {
+ env,
+ timeoutMs: STATIC_CHECK_TIMEOUT_MS,
+ maxBuffer: STATIC_CHECK_MAX_BUFFER,
+ }
+ )
+ } catch {
+ return unavailable('untrusted', resolved)
+ }
+
+ if (
+ assessmentResult.code !== 0 ||
+ assessmentResult.timedOut ||
+ assessmentResult.spawnError
+ ) {
+ return unavailable('untrusted', resolved)
+ }
+
+ return probe(resolved)
+ }
+}
diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsx
index d75fb91d..d974ebab 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -271,7 +271,36 @@ describe('AddTaskForm', () => {
expect(onSubmitSuccess).toHaveBeenCalledWith('ok-gid')
})
- it('uses the current performance profile split for new downloads', async () => {
+ it('surfaces the create failure reason without Electron IPC prefixes', async () => {
+ const onSubmitSuccess = vi.fn()
+ const user = userEvent.setup()
+ const { transport } = await import('@renderer/lib/transport')
+ const reason =
+ '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.'
+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
+ if (channel === 'query:getSettings') return { app: {} }
+ throw new Error(
+ `Error invoking remote method 'command:createTask': AppError: ${reason}`
+ )
+ })
+ renderForm({ onSubmitSuccess })
+
+ await user.type(screen.getByRole('textbox'), 'https://a/video')
+ const submit = screen.getByRole('button', { name: /download/i })
+ await user.click(submit)
+
+ await waitFor(() =>
+ expect(mockServices.notify).toHaveBeenCalledWith(
+ 'error',
+ 'task.add.createFailedWithReason',
+ { reason }
+ )
+ )
+ expect(onSubmitSuccess).not.toHaveBeenCalled()
+ await waitFor(() => expect(submit).toBeEnabled())
+ })
+
+ it('leaves connections unset so new downloads use the app setting', async () => {
const user = userEvent.setup()
const { transport } = await import('@renderer/lib/transport')
vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
@@ -294,7 +323,7 @@ describe('AddTaskForm', () => {
await waitFor(() =>
expect(transport.invoke).toHaveBeenCalledWith(
'command:createTask',
- expect.objectContaining({ connections: 32 })
+ expect.not.objectContaining({ connections: expect.any(Number) })
)
)
})
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 01035906..63700cf2 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -27,7 +27,6 @@ import {
type TaskCreateCommandResult,
type TaskCreateRequest,
} from '@shared/schemas/add-task'
-import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
type DeepPartial,
@@ -58,7 +57,15 @@ const BASE_DEFAULTS: DeepPartial<AddTaskFormValues> = {
tab: 'links',
urls: '',
saveDir: '',
- split: DEFAULT_ENGINE_SETTINGS.split,
+}
+
+function taskCreateFailureReason(error: unknown): string | null {
+ if (!(error instanceof Error)) return null
+ const reason = error.message
+ .replace(/^Error invoking remote method '[^']+':\s*/u, '')
+ .replace(/^(?:AppError|Error):\s*/u, '')
+ .trim()
+ return reason || null
}
export function AddTaskForm({
@@ -84,11 +91,6 @@ export function AddTaskForm({
})
const clipboardAutofillRequest = useRef(0)
- const hasExplicitSplitDefault = useRef(
- defaultValues !== undefined &&
- 'split' in defaultValues &&
- defaultValues.split !== undefined
- )
// Read once for each actual open. The desktop add-task window is precreated
// while hidden, so only its user-triggered SetAddTaskMode event starts a
@@ -124,15 +126,14 @@ export function AddTaskForm({
useExternalHydration(form, subscribeEvents, autofillClipboardLinks)
- // Backfill settings that affect each new task. URL params or explicit
- // caller defaults retain precedence over this asynchronous hydration.
+ // Backfill the default save directory for each new task. Per-task advanced
+ // overrides stay empty unless the caller or user supplies them explicitly.
useEffect(() => {
let cancelled = false
;(async () => {
try {
const settings = (await transport.invoke(Queries.GetSettings)) as {
app?: { defaultSaveDir?: string }
- engine?: { split?: number }
}
const dir = settings?.app?.defaultSaveDir
if (!cancelled && dir && !form.getValues('saveDir')) {
@@ -140,15 +141,6 @@ export function AddTaskForm({
shouldValidate: false,
})
}
- const split = settings?.engine?.split
- if (
- !cancelled &&
- !hasExplicitSplitDefault.current &&
- !form.getFieldState('split').isDirty &&
- typeof split === 'number'
- ) {
- form.setValue('split', split, { shouldValidate: false })
- }
} catch {
// Best effort — local defaults keep the form usable.
}
@@ -178,6 +170,7 @@ export function AddTaskForm({
Extract<TaskCreateCommandResult, { gid: string }>
> = []
let failed = 0
+ let firstFailureReason: string | null = null
let blockedByConflict = false
for (const request of requests) {
try {
@@ -193,6 +186,7 @@ export function AddTaskForm({
successes.push(result)
} catch (err) {
failed += 1
+ firstFailureReason ??= taskCreateFailureReason(err)
console.error(err)
}
}
@@ -205,7 +199,13 @@ export function AddTaskForm({
failed,
})
} else if (failed > 0) {
- platform.notify('error', 'task.add.createFailed')
+ if (firstFailureReason) {
+ platform.notify('error', 'task.add.createFailedWithReason', {
+ reason: firstFailureReason,
+ })
+ } else {
+ platform.notify('error', 'task.add.createFailed')
+ }
}
if (successes.length > 0) {
onSubmitSuccess?.(successes[0].taskId ?? successes[0].gid)
@@ -234,7 +234,12 @@ export function AddTaskForm({
onSubmitSuccess?.(result.taskId)
} catch (error) {
console.error(error)
- platform.notify('error', 'task.add.createFailed')
+ const reason = taskCreateFailureReason(error)
+ if (reason) {
+ platform.notify('error', 'task.add.createFailedWithReason', { reason })
+ } else {
+ platform.notify('error', 'task.add.createFailed')
+ }
} finally {
setSubmitting(false)
}
diff --git a/src/renderer/components/add-task/advanced-panel.test.tsx b/src/renderer/components/add-task/advanced-panel.test.tsx
index 682b8c31..01a70748 100644
--- a/src/renderer/components/add-task/advanced-panel.test.tsx
+++ b/src/renderer/components/add-task/advanced-panel.test.tsx
@@ -17,7 +17,7 @@ function Wrapper({
const form = useForm({
defaultValues:
tab === 'links'
- ? { tab: 'links', urls: '', saveDir: '/d', split: 5 }
+ ? { tab: 'links', urls: '', saveDir: '/d' }
: {
tab: 'torrent',
source: 'magnet',
@@ -48,6 +48,7 @@ describe('AdvancedPanel', () => {
await user.click(screen.getByRole('button', { name: /advanced/i }))
expect(screen.getByLabelText(/filename/i)).toBeInTheDocument()
expect(screen.getByLabelText(/user-agent/i)).toBeInTheDocument()
+ expect(screen.getByLabelText(/connections/i)).toHaveValue(null)
})
it('renders Torrent-flavored fields when tab=torrent', async () => {
diff --git a/src/renderer/components/add-task/advanced-panel.tsx b/src/renderer/components/add-task/advanced-panel.tsx
index 45db0d33..4bd21274 100644
--- a/src/renderer/components/add-task/advanced-panel.tsx
+++ b/src/renderer/components/add-task/advanced-panel.tsx
@@ -15,7 +15,6 @@ import { Textarea } from '@renderer/components/ui/textarea'
import { cn } from '@renderer/lib/utils'
import { EXTERNAL_URLS } from '@shared/external-urls'
import type { AddTaskFormValues } from '@shared/schemas/add-task'
-import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'
import { ChevronRight, CircleQuestionMark } from 'lucide-react'
import { type ReactNode, useLayoutEffect, useState } from 'react'
import { useFormContext, useWatch } from 'react-hook-form'
@@ -78,7 +77,6 @@ function LinksAdvancedFields() {
type="number"
min={1}
max={128}
- defaultValue={DEFAULT_ENGINE_SETTINGS.split}
/>
<DenseField
control={control}
@@ -170,7 +168,6 @@ interface DenseFieldProps {
min?: number
max?: number
step?: string
- defaultValue?: number
multiline?: boolean
}
@@ -183,7 +180,6 @@ function DenseField({
min,
max,
step,
- defaultValue,
multiline,
}: DenseFieldProps) {
return (
@@ -227,7 +223,7 @@ function DenseField({
typeof field.value === 'number' ||
typeof field.value === 'string'
? field.value
- : (defaultValue ?? '')
+ : ''
}
onChange={(e) => {
if (type === 'number') {
diff --git a/src/renderer/components/add-task/use-external-hydration.test.ts b/src/renderer/components/add-task/use-external-hydration.test.ts
index 8e9653fa..59cd9a7f 100644
--- a/src/renderer/components/add-task/use-external-hydration.test.ts
+++ b/src/renderer/components/add-task/use-external-hydration.test.ts
@@ -116,7 +116,7 @@ describe('useExternalHydration', () => {
expect(values.urls).toBe('https://a/b')
})
- it('SetAddTaskMode preserves the hydrated split setting', () => {
+ it('SetAddTaskMode clears a stale per-task connection override', () => {
const { result } = renderHook(() =>
useForm({
defaultValues: {
@@ -138,9 +138,9 @@ describe('useExternalHydration', () => {
fire(Events.SetAddTaskMode, { mode: 'links', url: 'https://a/b' })
})
- expect((result.current.getValues() as Record<string, unknown>).split).toBe(
- 32
- )
+ expect(
+ (result.current.getValues() as Record<string, unknown>).split
+ ).toBeUndefined()
})
it('notifies after SetAddTaskMode resets the form', () => {
diff --git a/src/renderer/components/add-task/use-external-hydration.ts b/src/renderer/components/add-task/use-external-hydration.ts
index 0895d746..7e13ef1d 100644
--- a/src/renderer/components/add-task/use-external-hydration.ts
+++ b/src/renderer/components/add-task/use-external-hydration.ts
@@ -58,10 +58,7 @@ export function useExternalHydration(
const onSetMode = (...args: unknown[]) => {
const parsed = setAddTaskModeEventPayloadSchema.safeParse(args[0])
if (!parsed.success) return
- const defaults = {
- ...urlParamsToFormDefaults(parsed.data),
- split: form.getValues('split'),
- }
+ const defaults = urlParamsToFormDefaults(parsed.data)
// A mode switch without an explicit saveDir must not wipe whatever
// is already in the field (e.g. the user's defaultSaveDir that the
// form backfilled at mount). Symmetric to onProtocol below.
diff --git a/src/renderer/components/desktop-kit/copy-button.tsx b/src/renderer/components/desktop-kit/copy-button.tsx
index 44466c18..dd58bd7d 100644
--- a/src/renderer/components/desktop-kit/copy-button.tsx
+++ b/src/renderer/components/desktop-kit/copy-button.tsx
@@ -13,12 +13,14 @@ type CopyButtonProps = Omit<
'onClick' | 'content'
> & {
content?: string | (() => string | Promise<string>)
+ iconPosition?: 'start' | 'end'
onClick?: () => void | Promise<void>
resetMs?: number
}
export function CopyButton({
content,
+ iconPosition = 'start',
onClick,
resetMs = 1500,
children,
@@ -59,8 +61,9 @@ export function CopyButton({
return (
<Button type="button" onClick={handleClick} {...rest}>
- <Icon />
+ {iconPosition === 'start' && <Icon />}
{children}
+ {iconPosition === 'end' && <Icon />}
</Button>
)
}
diff --git a/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx b/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
new file mode 100644
index 00000000..bbecda35
--- /dev/null
+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
@@ -0,0 +1,174 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { transport } from '@renderer/lib/transport'
+import { EXTERNAL_URLS } from '@shared/external-urls'
+import { DEFAULT_MEDIA_SETTINGS } from '@shared/schemas'
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
+import { FormProvider, useForm } from 'react-hook-form'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { IntegrationFormValues } from './integration-dialog'
+import { MediaToolsSection } from './media-tools-section'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ invoke: vi.fn(),
+ },
+}))
+
+function TestForm() {
+ const form = useForm<IntegrationFormValues>({
+ defaultValues: {
+ app: {
+ browserBridgeEnabled: false,
+ protocols: { magnet: false },
+ },
+ media: { ...DEFAULT_MEDIA_SETTINGS },
+ },
+ })
+ return (
+ <FormProvider {...form}>
+ <MediaToolsSection />
+ </FormProvider>
+ )
+}
+
+describe('MediaToolsSection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: vi.fn().mockResolvedValue(undefined) },
+ })
+ })
+
+ it('places the FFmpeg download action before refresh without a separate card', async () => {
+ vi.mocked(transport.invoke).mockResolvedValue({
+ active: null,
+ candidates: [],
+ })
+ render(<TestForm />)
+
+ const card = await screen.findByTestId('media-detection-card')
+ const download = within(card).getByRole('link', {
+ name: 'Download FFmpeg',
+ })
+ const refresh = within(card).getByRole('button', { name: 'Refresh' })
+
+ expect(download).toHaveAttribute(
+ 'href',
+ EXTERNAL_URLS.github.ffmpegStaticReleases
+ )
+ expect(
+ download.compareDocumentPosition(refresh) &
+ Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy()
+ expect(screen.queryByText('Motrix static FFmpeg')).not.toBeInTheDocument()
+ })
+
+ it('copies the complete Motrix data FFmpeg path when clicked', async () => {
+ const managedPath =
+ '/Users/example/Library/Application Support/Motrix/ffmpeg/bin/ffmpeg'
+ vi.mocked(transport.invoke).mockResolvedValue({
+ active: null,
+ candidates: [
+ { kind: 'manual', path: null, state: 'unconfigured' },
+ { kind: 'userData', path: managedPath, state: 'missing' },
+ ],
+ })
+ render(<TestForm />)
+
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Show detection details' })
+ )
+ const managedPathButton = await screen.findByRole('button', {
+ name: 'Copy Motrix FFmpeg path',
+ })
+ const managedRow = screen.getByTestId('candidate-row-userData')
+ expect(within(managedRow).getByText(managedPath)).toHaveAttribute(
+ 'title',
+ managedPath
+ )
+ expect(managedPathButton).toHaveAttribute('data-size', 'icon-xs')
+ expect(managedPathButton.lastElementChild).toHaveClass('lucide-copy')
+
+ fireEvent.click(managedPathButton)
+
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(managedPath)
+ )
+ })
+
+ it('edits the custom FFmpeg path directly in the detection row', async () => {
+ vi.mocked(transport.invoke).mockResolvedValue({
+ active: null,
+ candidates: [
+ { kind: 'manual', path: null, state: 'unconfigured' },
+ { kind: 'env', path: null, state: 'unconfigured' },
+ ],
+ })
+ render(<TestForm />)
+
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Show detection details' })
+ )
+ const manualRow = await screen.findByTestId('candidate-row-manual')
+ expect(within(manualRow).queryByRole('textbox')).not.toBeInTheDocument()
+ expect(within(manualRow).getAllByText('Not set')).toHaveLength(2)
+
+ fireEvent.click(
+ within(manualRow).getByRole('button', {
+ name: 'Edit custom FFmpeg path',
+ })
+ )
+ const input = within(manualRow).getByRole('textbox', {
+ name: 'Custom FFmpeg path',
+ })
+
+ expect(input).toHaveAttribute('placeholder', 'Not set')
+ fireEvent.change(input, { target: { value: '/opt/ffmpeg/bin/ffmpeg' } })
+ expect(input).toHaveValue('/opt/ffmpeg/bin/ffmpeg')
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(within(manualRow).queryByRole('textbox')).not.toBeInTheDocument()
+ expect(within(manualRow).getByText('/opt/ffmpeg/bin/ffmpeg')).toBeVisible()
+ expect(
+ within(manualRow).getByRole('button', {
+ name: 'Edit custom FFmpeg path',
+ })
+ ).toBeVisible()
+ expect(
+ within(await screen.findByTestId('candidate-row-env')).queryByRole(
+ 'textbox'
+ )
+ ).not.toBeInTheDocument()
+ })
+
+ it('shows a macOS trust failure instead of reporting the file as missing', async () => {
+ vi.mocked(transport.invoke).mockResolvedValue({
+ active: null,
+ candidates: [
+ { kind: 'manual', path: null, state: 'unconfigured' },
+ {
+ kind: 'userData',
+ path: '/Users/example/ffmpeg',
+ state: 'untrusted',
+ },
+ ],
+ })
+ render(<TestForm />)
+
+ expect(
+ await screen.findByText('FFmpeg was blocked by macOS')
+ ).toBeInTheDocument()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Show detection details' })
+ )
+ expect(await screen.findByText('Blocked by macOS')).toBeInTheDocument()
+ expect(screen.queryByText('Not found')).not.toBeInTheDocument()
+ })
+})
diff --git a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx b/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
index b6d30fbb..617391ab 100644
--- a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
@@ -1,3 +1,4 @@
+import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
import { Badge } from '@renderer/components/ui/badge'
import { Button } from '@renderer/components/ui/button'
import {
@@ -15,9 +16,18 @@ import {
import { Input } from '@renderer/components/ui/input'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
+import { EXTERNAL_URLS } from '@shared/external-urls'
import { Queries } from '@shared/protocol/queries'
import { DEFAULT_MEDIA_SETTINGS } from '@shared/schemas'
-import { BadgeCheck, ChevronRight, RefreshCw } from 'lucide-react'
+import {
+ BadgeCheck,
+ Check,
+ ChevronRight,
+ Download,
+ Pencil,
+ RefreshCw,
+ ShieldAlert,
+} from 'lucide-react'
import { useEffect, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
@@ -32,6 +42,7 @@ type CandidateStateUI =
| 'active'
| 'available'
| 'missing'
+ | 'untrusted'
| 'unconfigured'
| 'version_mismatch'
@@ -48,7 +59,9 @@ interface FfmpegDetectionResultUI {
function candidateStateVariant(state: CandidateStateUI) {
if (state === 'active') return 'default'
if (state === 'available') return 'secondary'
- if (state === 'version_mismatch') return 'destructive'
+ if (state === 'version_mismatch' || state === 'untrusted') {
+ return 'destructive'
+ }
return 'outline'
}
@@ -59,6 +72,7 @@ export function MediaToolsSection() {
null
)
const [detailsOpen, setDetailsOpen] = useState(false)
+ const [customPathEditing, setCustomPathEditing] = useState(false)
useEffect(() => {
let cancelled = false
@@ -87,16 +101,23 @@ export function MediaToolsSection() {
const activeSource = activeCandidate
? t(`settings.integration.media.candidateKind.${activeCandidate.kind}`)
: null
+ const hasUntrustedCandidate =
+ !detection?.active &&
+ detection?.candidates.some((candidate) => candidate.state === 'untrusted')
const activeLabel = detection?.active
? t('settings.integration.media.detection.readyTitle', {
version: detection.active.version,
})
- : t('settings.integration.media.detection.unavailableTitle')
+ : hasUntrustedCandidate
+ ? t('settings.integration.media.detection.untrustedTitle')
+ : t('settings.integration.media.detection.unavailableTitle')
const activeDescription = detection?.active
? t('settings.integration.media.detection.usingSource', {
source: activeSource,
})
- : t('settings.integration.media.detection.unavailableDesc')
+ : hasUntrustedCandidate
+ ? t('settings.integration.media.detection.untrustedDesc')
+ : t('settings.integration.media.detection.unavailableDesc')
const candidateCount = detection?.candidates.length ?? 0
return (
@@ -110,20 +131,43 @@ export function MediaToolsSection() {
<div className="flex flex-wrap items-center gap-2">
<div className="text-sm font-medium">{activeLabel}</div>
{detection?.active && <BadgeCheck className="size-4" />}
+ {hasUntrustedCandidate && (
+ <ShieldAlert className="size-4 text-destructive" />
+ )}
</div>
<div className="text-xs text-muted-foreground">
{activeDescription}
</div>
</div>
- <Button
- type="button"
- size="icon-sm"
- variant="ghost"
- aria-label={t('settings.integration.media.refresh')}
- onClick={refresh}
- >
- <RefreshCw className="size-4 text-muted-foreground" />
- </Button>
+ <div className="flex shrink-0 items-center gap-1">
+ <Button
+ render={
+ <a
+ href={EXTERNAL_URLS.github.ffmpegStaticReleases}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={t('settings.integration.media.download.action')}
+ title={t('settings.integration.media.download.action')}
+ // biome-ignore lint/a11y/noRedundantRoles: Base UI Button applies button semantics unless this rendered anchor explicitly overrides them.
+ role="link"
+ />
+ }
+ nativeButton={false}
+ size="icon-sm"
+ variant="ghost"
+ >
+ <Download className="size-4 text-muted-foreground" aria-hidden />
+ </Button>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ aria-label={t('settings.integration.media.refresh')}
+ onClick={refresh}
+ >
+ <RefreshCw className="size-4 text-muted-foreground" />
+ </Button>
+ </div>
</div>
<Collapsible open={detailsOpen} onOpenChange={setDetailsOpen}>
@@ -172,18 +216,109 @@ export function MediaToolsSection() {
<div
key={c.kind}
data-testid={`candidate-row-${c.kind}`}
- className="grid grid-cols-[10rem_minmax(0,1fr)_7rem] items-center gap-2 border-b border-border px-3 py-2 last:border-b-0"
+ className="grid h-11 grid-cols-[10rem_minmax(0,1fr)_7rem] items-center gap-2 border-b border-border px-3 py-2 last:border-b-0"
>
<span className="font-medium text-foreground">
{t(`settings.integration.media.candidateKind.${c.kind}`)}
</span>
- <span
- className="truncate font-mono text-muted-foreground"
- title={c.path ?? undefined}
- >
- {c.path ??
- t('settings.integration.media.detection.notConfigured')}
- </span>
+ {c.kind === 'manual' ? (
+ <FormField
+ control={form.control}
+ name="media.ffmpegBinaryPath"
+ render={({ field }) => (
+ <div className="grid h-7 min-w-0 grid-cols-[minmax(0,1fr)_1.5rem] items-center gap-1">
+ {customPathEditing ? (
+ <Input
+ {...field}
+ autoFocus
+ data-testid="media-binary-path-input"
+ aria-label={t(
+ 'settings.integration.media.binaryPath'
+ )}
+ placeholder={t(
+ 'settings.integration.media.detection.notConfigured'
+ )}
+ className="h-7 min-w-0 px-2 font-mono text-xs text-foreground placeholder:text-xs md:text-xs md:placeholder:text-xs"
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ setCustomPathEditing(false)
+ } else if (event.key === 'Escape') {
+ setCustomPathEditing(false)
+ }
+ }}
+ />
+ ) : (
+ <span
+ className="min-w-0 flex-1 truncate font-mono text-muted-foreground"
+ title={field.value || undefined}
+ >
+ {field.value ||
+ t(
+ 'settings.integration.media.detection.notConfigured'
+ )}
+ </span>
+ )}
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ className="shrink-0 text-muted-foreground"
+ aria-label={t(
+ customPathEditing
+ ? 'settings.integration.media.detection.finishEditingCustomPath'
+ : 'settings.integration.media.detection.editCustomPath'
+ )}
+ title={t(
+ customPathEditing
+ ? 'settings.integration.media.detection.finishEditingCustomPath'
+ : 'settings.integration.media.detection.editCustomPath'
+ )}
+ onClick={() =>
+ setCustomPathEditing((editing) => !editing)
+ }
+ >
+ {customPathEditing ? (
+ <Check aria-hidden />
+ ) : (
+ <Pencil aria-hidden />
+ )}
+ </Button>
+ </div>
+ )}
+ />
+ ) : c.kind === 'userData' && c.path ? (
+ <div className="grid h-7 min-w-0 grid-cols-[minmax(0,1fr)_1.5rem] items-center gap-1">
+ <span
+ dir="ltr"
+ title={c.path}
+ className="min-w-0 truncate font-mono text-muted-foreground"
+ >
+ {c.path}
+ </span>
+ <CopyButton
+ content={c.path}
+ iconPosition="end"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t(
+ 'settings.integration.media.detection.copyManagedPath'
+ )}
+ title={t(
+ 'settings.integration.media.detection.copyManagedPath'
+ )}
+ className="shrink-0 text-muted-foreground hover:text-foreground"
+ />
+ </div>
+ ) : (
+ <span
+ className="truncate font-mono text-muted-foreground"
+ title={c.path ?? undefined}
+ >
+ {c.path ??
+ t('settings.integration.media.detection.notConfigured')}
+ </span>
+ )}
<Badge
variant={candidateStateVariant(c.state)}
className="justify-self-end rounded-md"
@@ -197,31 +332,6 @@ export function MediaToolsSection() {
</Collapsible>
</section>
- <FormField
- control={form.control}
- name="media.ffmpegBinaryPath"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.integration.media.binaryPath')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.integration.media.binaryPathDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Input
- data-testid="media-binary-path-input"
- className="w-56 h-8"
- value={field.value}
- onChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
<FormField
control={form.control}
name="media.ffmpegStagingMB"
diff --git a/src/renderer/windows/add-task-window.test.tsx b/src/renderer/windows/add-task-window.test.tsx
new file mode 100644
index 00000000..d1b8cd8a
--- /dev/null
+++ b/src/renderer/windows/add-task-window.test.tsx
@@ -0,0 +1,75 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { toast } from '@renderer/components/ui/toast'
+import { i18n } from '@renderer/lib/i18n'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { act, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { AddTaskWindow } from './add-task-window'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ invoke: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
+ platform: 'darwin',
+ },
+}))
+
+vi.mock('@renderer/hooks/use-adaptive-window-height', () => ({
+ useAdaptiveWindowHeight: vi.fn(),
+}))
+
+describe('AddTaskWindow', () => {
+ beforeEach(async () => {
+ vi.clearAllMocks()
+ await i18n.changeLanguage('en-US')
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetSettings) {
+ return { app: { defaultSaveDir: '/downloads' } }
+ }
+ if (channel === Commands.CreateTask) {
+ throw new Error(
+ "Error invoking remote method 'command:createTask': AppError: 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."
+ )
+ }
+ return undefined
+ })
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
+ })
+
+ afterEach(() => {
+ act(() => toast.close())
+ vi.restoreAllMocks()
+ })
+
+ it('hosts and displays task creation errors in the standalone window', async () => {
+ const user = userEvent.setup()
+ const { baseElement } = render(<AddTaskWindow />)
+
+ expect(
+ baseElement.querySelector('[aria-label="Notifications"]')
+ ).toBeInTheDocument()
+
+ await user.type(
+ screen.getByRole('textbox', { name: 'URLs' }),
+ 'https://example.com/video'
+ )
+ const downloadButton = screen.getByRole('button', { name: 'Download' })
+ await waitFor(() => expect(downloadButton).toBeEnabled())
+ await user.click(downloadButton)
+
+ expect(
+ await screen.findByText(
+ 'Failed to create download task: 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.'
+ )
+ ).toBeVisible()
+ expect(
+ screen.queryByText(/Error invoking remote method/u)
+ ).not.toBeInTheDocument()
+ expect(screen.queryByText(/AppError:/u)).not.toBeInTheDocument()
+ })
+})
diff --git a/src/renderer/windows/add-task-window.tsx b/src/renderer/windows/add-task-window.tsx
index 170bc98c..88112124 100644
--- a/src/renderer/windows/add-task-window.tsx
+++ b/src/renderer/windows/add-task-window.tsx
@@ -1,4 +1,5 @@
import { AddTaskForm } from '@renderer/components/add-task/add-task-form'
+import { Toaster } from '@renderer/components/ui/toast'
import { useAdaptiveWindowHeight } from '@renderer/hooks/use-adaptive-window-height'
import { electronServices } from '@renderer/platform/electron-services'
import { PlatformServicesProvider } from '@renderer/platform/services'
@@ -55,6 +56,7 @@ export function AddTaskWindow() {
subscribeEvents
/>
</PlatformServicesProvider>
+ <Toaster />
</div>
)
}
diff --git a/src/shared/config/native-messaging-extensions.json b/src/shared/config/native-messaging-extensions.json
index d2eac81c..d0b82117 100644
--- a/src/shared/config/native-messaging-extensions.json
+++ b/src/shared/config/native-messaging-extensions.json
@@ -1,4 +1,4 @@
{
"chromium": ["ibpkjhgpbidfmbmomagmldcdlpbmchgi"],
- "firefox": ["[email protected]"]
+ "firefox": ["[email protected]"]
}
diff --git a/src/shared/external-urls.test.ts b/src/shared/external-urls.test.ts
index 160c86a1..4a0268fe 100644
--- a/src/shared/external-urls.test.ts
+++ b/src/shared/external-urls.test.ts
@@ -2,6 +2,12 @@ import { describe, expect, it } from 'vitest'
import { EXTERNAL_URLS, getNatTroubleshootingUrl } from './external-urls'
describe('getNatTroubleshootingUrl', () => {
+ it('points FFmpeg downloads at the standalone motrixapp project', () => {
+ expect(EXTERNAL_URLS.github.ffmpegStaticReleases).toBe(
+ 'https://github.com/motrixapp/ffmpeg-static/releases/latest'
+ )
+ })
+
it('uses the Chinese manual for Chinese locales', () => {
expect(getNatTroubleshootingUrl('zh-CN')).toBe(
EXTERNAL_URLS.motrix.manual.natTroubleshooting.zh
diff --git a/src/shared/external-urls.ts b/src/shared/external-urls.ts
index cead8ba8..f5676b99 100644
--- a/src/shared/external-urls.ts
+++ b/src/shared/external-urls.ts
@@ -9,6 +9,8 @@ export const EXTERNAL_URLS = {
repository: 'https://github.com/agalwood/Motrix/',
author: 'https://github.com/agalwood/',
issues: 'https://github.com/agalwood/Motrix/issues/',
+ ffmpegStaticReleases:
+ 'https://github.com/motrixapp/ffmpeg-static/releases/latest',
},
motrix: {
home: 'https://motrix.app/',
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 16be472e..2e669921 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -783,6 +783,7 @@
"dropTorrent": "Drop .torrent file here or click to select",
"clearSelection": "Clear selection",
"createFailed": "Failed to create download task.",
+ "createFailedWithReason": "Failed to create download task: {{reason}}",
"parseFailed": "Failed to parse torrent file.",
"urlsCount_one": "{{count}} URL",
"urlsCount_other": "{{count}} URLs",
@@ -1572,13 +1573,17 @@
"notDetected": "FFmpeg not detected",
"refresh": "Refresh",
"binaryPath": "Custom FFmpeg path",
- "binaryPathDesc": "Optional. Leave empty to use the bundled copy, environment override, or system PATH automatically. Custom paths are tried first.",
"browse": "Browse…",
+ "download": {
+ "action": "Download FFmpeg"
+ },
"detection": {
"readyTitle": "FFmpeg {{version}}",
"unavailableTitle": "FFmpeg is not available",
+ "untrustedTitle": "FFmpeg was blocked by macOS",
"usingSource": "Using {{source}}",
"unavailableDesc": "Set a custom path, install FFmpeg, or add it to PATH, then refresh.",
+ "untrustedDesc": "The file exists but did not pass macOS security verification. Install a trusted build or approve it in Privacy & Security, then refresh.",
"showDetails": "Show detection details",
"hideDetails": "Hide detection details",
"sourcesChecked_one": "{{count}} source checked",
@@ -1586,18 +1591,22 @@
"source": "Source",
"location": "Checked location",
"result": "Result",
+ "copyManagedPath": "Copy Motrix FFmpeg path",
+ "editCustomPath": "Edit custom FFmpeg path",
+ "finishEditingCustomPath": "Finish editing custom FFmpeg path",
"notConfigured": "Not set"
},
"candidateKind": {
"manual": "Custom path",
- "userData": "Bundled copy",
- "env": "MOTRIX_FFMPEG_PATH",
+ "userData": "Motrix data directory",
+ "env": "MOTRIX_FFMPEG_BIN",
"path": "System PATH"
},
"state": {
"active": "In use",
"available": "Found",
"missing": "Not found",
+ "untrusted": "Blocked by macOS",
"unconfigured": "Not set",
"version_mismatch": "Unsupported"
},
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index fd258f76..a91168b3 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -772,6 +772,7 @@
"dropTorrent": "拖拽 .torrent 文件到此处,或点击选择",
"clearSelection": "清除选择",
"createFailed": "创建下载任务失败。",
+ "createFailedWithReason": "创建下载任务失败:{{reason}}",
"parseFailed": "解析种子文件失败。",
"urlsCount_other": "{{count}} 个 URL",
"urlsWithInvalid": "{{valid}} 个有效,{{invalid}} 个无效",
@@ -1559,31 +1560,39 @@
"notDetected": "未探测到 FFmpeg",
"refresh": "刷新",
"binaryPath": "自定义 FFmpeg 路径",
- "binaryPathDesc": "可选。留空时会自动尝试内置副本、环境变量覆盖和系统 PATH。自定义路径优先级最高。",
"browse": "浏览…",
+ "download": {
+ "action": "下载 FFmpeg"
+ },
"detection": {
"readyTitle": "FFmpeg {{version}}",
"unavailableTitle": "FFmpeg 不可用",
+ "untrustedTitle": "FFmpeg 已被 macOS 阻止",
"usingSource": "当前使用 {{source}}",
"unavailableDesc": "请设置自定义路径、安装 FFmpeg,或将它加入 PATH 后刷新。",
+ "untrustedDesc": "文件存在,但未通过 macOS 安全验证。请安装可信版本,或在“隐私与安全性”中批准后刷新。",
"showDetails": "显示检测详情",
"hideDetails": "隐藏检测详情",
"sourcesChecked_other": "已检查 {{count}} 个来源",
"source": "来源",
"location": "检测位置",
"result": "结果",
+ "copyManagedPath": "复制 Motrix FFmpeg 路径",
+ "editCustomPath": "编辑自定义 FFmpeg 路径",
+ "finishEditingCustomPath": "完成编辑自定义 FFmpeg 路径",
"notConfigured": "未设置"
},
"candidateKind": {
"manual": "自定义路径",
- "userData": "内置副本",
- "env": "MOTRIX_FFMPEG_PATH",
+ "userData": "Motrix 数据目录",
+ "env": "MOTRIX_FFMPEG_BIN",
"path": "系统 PATH"
},
"state": {
"active": "使用中",
"available": "已找到",
"missing": "未找到",
+ "untrusted": "macOS 已阻止",
"unconfigured": "未设置",
"version_mismatch": "不受支持"
},
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 62630cae..b0c3094c 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -772,6 +772,7 @@
"dropTorrent": "將 .torrent 檔案拖放到這裡,或按一下以選擇檔案",
"clearSelection": "清除選取項目",
"createFailed": "無法建立下載任務。",
+ "createFailedWithReason": "無法建立下載任務:{{reason}}",
"parseFailed": "無法解析 Torrent 檔案。",
"urlsCount_other": "{{count}} 個 URL",
"urlsWithInvalid": "{{valid}} 個有效,{{invalid}} 個無效",
@@ -1559,31 +1560,39 @@
"notDetected": "未偵測到 FFmpeg",
"refresh": "重新整理",
"binaryPath": "自訂 FFmpeg 路徑",
- "binaryPathDesc": "選填。留空會自動使用內建副本、環境變數覆寫或系統 PATH。自訂路徑會優先嘗試。",
"browse": "瀏覽...",
+ "download": {
+ "action": "下載 FFmpeg"
+ },
"detection": {
"readyTitle": "FFmpeg {{version}}",
"unavailableTitle": "無法使用 FFmpeg",
+ "untrustedTitle": "FFmpeg 已被 macOS 阻擋",
"usingSource": "使用 {{source}}",
"unavailableDesc": "設定自訂路徑、安裝 FFmpeg 或將其加入 PATH,然後重新整理。",
+ "untrustedDesc": "檔案存在,但未通過 macOS 安全驗證。請安裝可信版本,或在「隱私權與安全性」中允許後重新整理。",
"showDetails": "顯示偵測詳細資料",
"hideDetails": "隱藏偵測詳細資料",
"sourcesChecked_other": "已檢查 {{count}} 個來源",
"source": "來源",
"location": "檢查位置",
"result": "結果",
+ "copyManagedPath": "複製 Motrix FFmpeg 路徑",
+ "editCustomPath": "編輯自訂 FFmpeg 路徑",
+ "finishEditingCustomPath": "完成編輯自訂 FFmpeg 路徑",
"notConfigured": "未設定"
},
"candidateKind": {
"manual": "自訂路徑",
- "userData": "內建副本",
- "env": "MOTRIX_FFMPEG_PATH",
+ "userData": "Motrix 資料目錄",
+ "env": "MOTRIX_FFMPEG_BIN",
"path": "系統 PATH"
},
"state": {
"active": "使用中",
"available": "已找到",
"missing": "找不到",
+ "untrusted": "macOS 已阻擋",
"unconfigured": "未設定",
"version_mismatch": "不支援"
},
diff --git a/src/shared/schemas/add-task.test.ts b/src/shared/schemas/add-task.test.ts
index 31a3056e..c1003725 100644
--- a/src/shared/schemas/add-task.test.ts
+++ b/src/shared/schemas/add-task.test.ts
@@ -8,7 +8,6 @@ import {
taskCreateRequestSchema,
urlParamsToFormDefaults,
} from './add-task'
-import { DEFAULT_ENGINE_SETTINGS } from './engine-settings'
describe('addTaskFormSchema', () => {
it('accepts minimal links tab', () => {
@@ -19,7 +18,7 @@ describe('addTaskFormSchema', () => {
})
expect(result.success).toBe(true)
if (result.success && result.data.tab === 'links') {
- expect(result.data.split).toBe(DEFAULT_ENGINE_SETTINGS.split)
+ expect(result.data.split).toBeUndefined()
}
})
@@ -227,17 +226,27 @@ describe('formValuesToTaskCreateRequest', () => {
tab: 'links',
urls: 'https://a/b\nhttps://c/d',
saveDir: '/d',
- split: 5,
})
expect(req).toEqual({
type: 'http',
uris: ['https://a/b', 'https://c/d'],
saveDir: '/d',
filename: undefined,
- connections: 5,
headers: [],
proxy: undefined,
})
+ expect(req).not.toHaveProperty('connections')
+ })
+
+ it('uses connections only when the task override is explicit', () => {
+ const req = formValuesToTaskCreateRequest({
+ tab: 'links',
+ urls: 'https://a/b',
+ saveDir: '/d',
+ split: 5,
+ })
+
+ expect(req).toMatchObject({ type: 'http', connections: 5 })
})
it('drops empty url lines', () => {
diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.ts
index cd494756..8e28444a 100644
--- a/src/shared/schemas/add-task.ts
+++ b/src/shared/schemas/add-task.ts
@@ -1,5 +1,4 @@
import { z } from 'zod'
-import { DEFAULT_ENGINE_SETTINGS } from './engine-settings'
const torrentFileSchema = z.object({
index: z.number().int().nonnegative(),
@@ -22,12 +21,7 @@ const linksTabSchema = z.object({
urls: z.string().min(1, { message: 'task.add.errors.urlsRequired' }),
saveDir: z.string().min(1, { message: 'task.add.errors.saveDirRequired' }),
filename: z.string().optional(),
- split: z
- .number()
- .int()
- .min(1)
- .max(128)
- .default(DEFAULT_ENGINE_SETTINGS.split),
+ split: z.number().int().min(1).max(128).optional(),
userAgent: z.string().optional(),
referer: z.string().optional(),
cookie: z.string().optional(),
@@ -269,7 +263,7 @@ export function formValuesToTaskCreateRequest(
uris,
saveDir: v.saveDir,
filename: trimmed(v.filename),
- connections: v.split,
+ ...(v.split === undefined ? {} : { connections: v.split }),
headers,
proxy: trimmed(v.allProxy),
}