Skip to content

A full-featured download manager.

fix(server): complete media tools and settings controls (#2497)

Dr_rOotc3ed8342e8c3
diff --git a/docs/docker-server.md b/docs/docker-server.md
index c33bbd6d..073369ff 100644
--- a/docs/docker-server.md
+++ b/docs/docker-server.md
@@ -658,7 +658,16 @@ Operator-managed options are:
The official image does not include FFmpeg. Browser Extension HLS/DASH downloads,
separate audio/video merging, and plugins that require FFmpeg need an executable
-inside the container. For example, use a derived image with Alpine's `ffmpeg`
+inside the container. In **Settings → Integration → Media Tools**, click
+**Download FFmpeg**, then **Download and verify**. The Server downloads the
+official Motrix build for its own OS and architecture, verifies its signature
+and checksums, and installs it under `/data/binaries/ffmpeg-verified`. Progress
+and errors appear in the Web UI; the installed files persist with the `/data`
+volume. Installation requires write access to that directory and outbound
+HTTPS access to GitHub releases. Failed verification leaves the previous
+verified installation intact.
+
+Alternatively, use a derived image with Alpine's `ffmpeg`
package and `MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`. A compatible executable in
`/data/binaries/ffmpeg` or a custom path configured in the Web UI also works.
Confirm detection in **Settings → Integration → Media Tools**, then click
@@ -668,6 +677,13 @@ make it available inside the container.
## Upgrade, rollback, backup, and restore
+**Settings → About** can check for new Server versions using the same stable
+and beta release feeds as the desktop app. The selected channel and automatic
+startup checks are saved in settings. Checks compare against the running
+Server version and never offer a downgrade. When a newer version is available,
+open its release notes and update the deployment manually. The Server does not
+download installers, replace application files, or restart to install an update.
+
Before an upgrade, record the current image digest and back up `/data`. Stop the
service for a filesystem-level backup so SQLite and the aria2 session are
consistent:
diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.md
index 7711b003..cb229475 100644
--- a/docs/docker-server.zh-CN.md
+++ b/docs/docker-server.zh-CN.md
@@ -558,7 +558,14 @@ operator 可用的管理选项包括:
store;否则会生成并持久化 `/data/secrets.lockbox`。
官方镜像不包含 FFmpeg。浏览器扩展的 HLS/DASH 下载、分离音视频合并,以及
-依赖 FFmpeg 的插件,都需要容器内可执行的 FFmpeg。例如,基于官方镜像安装
+依赖 FFmpeg 的插件,都需要容器内可执行的 FFmpeg。在 **设置 → 集成 → 媒体工具**
+中点击 **下载 FFmpeg**,再点击 **下载并验证**。Server 会根据自身的操作系统和
+架构下载 Motrix 官方构建,校验签名和摘要后安装到
+`/data/binaries/ffmpeg-verified`。Web 界面会显示进度和错误,安装文件随 `/data`
+卷持久保存。安装需要该目录的写入权限,以及访问 GitHub Releases 的出站 HTTPS
+连接。校验失败时会保留此前已验证的安装。
+
+也可以基于官方镜像安装
Alpine `ffmpeg` 包,并设置 `MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`。也可以将
兼容的可执行文件放在 `/data/binaries/ffmpeg`,或在 Web 界面配置自定义路径。
在 **设置 → 集成 → 媒体工具** 中确认检测成功后,点击扩展中的 **重新扫描**。
@@ -567,6 +574,11 @@ Server 会刷新媒体能力,无需重启;仅在浏览器所在电脑安装
## 升级、回滚、备份与恢复
+**设置 → 关于** 支持检查 Server 新版本,使用与桌面版相同的稳定版和测试版发布源。
+更新通道和启动时自动检查的偏好会保存在设置中。检查以正在运行的 Server 版本为准,
+不会提示降级。发现新版本后,可以打开对应的更新日志,由管理员手动更新部署。
+Server 不会下载安装包、替换应用文件,或为安装更新而自动重启。
+
升级前记录当前镜像 digest 并备份 `/data`。做文件系统级备份前先停止服务,
确保 SQLite 与 aria2 session 一致:
diff --git a/package.json b/package.json
index c8c1b710..a0f973c7 100644
--- a/package.json
+++ b/package.json
@@ -111,7 +111,6 @@
"electron": "45.2.1",
"electron-builder": "26.18.1",
"esbuild": "^0.28.2",
- "js-yaml": "^5.5.0",
"jsdom": "^30.1.3",
"playwright": "^1.64.1",
"tsx": "^4.23.15",
@@ -147,6 +146,7 @@
"elkjs": "^0.12.1",
"fastify": "^5.12.7",
"i18next": "^26.5.12",
+ "js-yaml": "^5.5.0",
"libsodium-wrappers": "^0.8.4",
"lucide-react": "^1.66.0",
"mmdb-lib": "^3.0.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f2351f6a..c7958ff7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -251,6 +251,9 @@ importers:
i18next:
specifier: ^26.5.12
version: 26.5.12([email protected])
+ js-yaml:
+ specifier: ^5.5.0
+ version: 5.5.0
libsodium-wrappers:
specifier: ^0.8.4
version: 0.8.4
@@ -396,9 +399,6 @@ importers:
esbuild:
specifier: ^0.28.2
version: 0.28.2
- js-yaml:
- specifier: ^5.5.0
- version: 5.5.0
jsdom:
specifier: ^30.1.3
version: 30.1.3(@noble/[email protected])
diff --git a/scripts/server-runtime-dependencies.json b/scripts/server-runtime-dependencies.json
index cca80388..9ba5bfac 100644
--- a/scripts/server-runtime-dependencies.json
+++ b/scripts/server-runtime-dependencies.json
@@ -23,6 +23,7 @@
"chokidar",
"fastify",
"i18next",
+ "js-yaml",
"libsodium-wrappers",
"mmdb-lib",
"pino",
diff --git a/scripts/third-party-notices.config.json b/scripts/third-party-notices.config.json
index 81d3c3a0..8418a545 100644
--- a/scripts/third-party-notices.config.json
+++ b/scripts/third-party-notices.config.json
@@ -16,7 +16,8 @@
"MPL-2.0",
"NOASSERTION",
"OFL-1.1",
- "Python-2.0"
+ "Python-2.0",
+ "PSF-2.0"
],
"reviewedRepositoryLicenseFiles": {
"THIRD_PARTY_LICENSES/MPL-2.0": "5eba353fe5076ac3432177f8ab1cf75e3afcd0584251e37c3bfead5f447d040e",
diff --git a/src/core/ffmpeg/ffmpeg-macos-trust.ts b/src/core/ffmpeg/ffmpeg-macos-trust.ts
new file mode 100644
index 00000000..23b6f7e6
--- /dev/null
+++ b/src/core/ffmpeg/ffmpeg-macos-trust.ts
@@ -0,0 +1,168 @@
+import { randomUUID } from 'node:crypto'
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { sha256 } from '@core/ffmpeg/verified-release'
+import { type RunCommand, runCommand } from '@core/process/command-runner'
+import certificate from '@shared/config/ffmpeg-macos-certificate.json'
+import type { FfmpegTarget } from '@shared/schemas/ffmpeg-release'
+
+function parseSecureTimestamp(value: string): string {
+ // codesign uses system date preferences even with LC_ALL=C. Normalize only
+ // horizontal separators, then accept the explicit English date orders.
+ const raw = value.replace(/[ \t\u00a0\u202f]+/g, ' ')
+ const timestamp =
+ /^(?:([A-Z][a-z]{2}) (\d{1,2}),|(\d{1,2}) ([A-Z][a-z]{2})) (\d{4}) at (\d{1,2}):(\d{2}):(\d{2})(?: (AM|PM))?$/.exec(
+ raw
+ )
+ if (!timestamp) throw new Error('Missing secure FFmpeg timestamp')
+ const month = [
+ 'Jan',
+ 'Feb',
+ 'Mar',
+ 'Apr',
+ 'May',
+ 'Jun',
+ 'Jul',
+ 'Aug',
+ 'Sep',
+ 'Oct',
+ 'Nov',
+ 'Dec',
+ ].indexOf(timestamp[1] ?? timestamp[4])
+ const day = Number(timestamp[2] ?? timestamp[3])
+ const year = Number(timestamp[5])
+ let hour = Number(timestamp[6])
+ const minute = Number(timestamp[7])
+ const second = Number(timestamp[8])
+ if (timestamp[9]) {
+ if (hour < 1 || hour > 12)
+ throw new Error('Invalid secure FFmpeg timestamp')
+ hour = (hour % 12) + (timestamp[9] === 'PM' ? 12 : 0)
+ }
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second))
+ if (
+ month < 0 ||
+ date.getUTCFullYear() !== year ||
+ date.getUTCMonth() !== month ||
+ date.getUTCDate() !== day ||
+ date.getUTCHours() !== hour ||
+ date.getUTCMinutes() !== minute ||
+ date.getUTCSeconds() !== second
+ )
+ throw new Error('Invalid secure FFmpeg timestamp')
+ return date.toISOString().replace('.000Z', 'Z')
+}
+
+/** Static OS checks only. Never execute an unverified payload or remove quarantine. */
+export async function verifyMacFfmpegTrust(
+ directory: string,
+ target: FfmpegTarget,
+ sourceUrl: string,
+ run: RunCommand = runCommand
+): Promise<void> {
+ if (
+ !sourceUrl.startsWith(
+ 'https://github.com/motrixapp/ffmpeg-static/releases/download/'
+ )
+ )
+ throw new Error('Unexpected FFmpeg source')
+ for (const name of ['ffmpeg', 'ffprobe'] as const) {
+ const binary = path.join(directory, name)
+ // Network clients do not propagate Finder quarantine; mark this Internet download explicitly.
+ await checked(run, '/usr/bin/xattr', [
+ '-w',
+ 'com.apple.quarantine',
+ `0081;${Math.floor(Date.now() / 1000).toString(16)};Motrix;${randomUUID()}`,
+ binary,
+ ])
+ await verifyMacFfmpegBinaryTrust(binary, name, target, run)
+ }
+}
+
+async function checked(run: RunCommand, command: string, args: string[]) {
+ const result = await run(command, args, {
+ env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
+ timeoutMs: 30_000,
+ maxBuffer: 64_000,
+ })
+ if (
+ result.code !== 0 ||
+ result.spawnError ||
+ result.timedOut ||
+ result.truncated
+ )
+ throw new Error('FFmpeg system trust check failed')
+ return result
+}
+
+/** The caller authenticates the target and binary hash before these CLI checks. */
+export async function verifyMacFfmpegBinaryTrust(
+ binary: string,
+ name: 'ffmpeg' | 'ffprobe',
+ target: FfmpegTarget,
+ run: RunCommand = runCommand
+): Promise<void> {
+ const signing = target.signing
+ if (
+ target.platform !== 'darwin' ||
+ !signing ||
+ signing.identity.certificateSha256 !== certificate.certificateSha256
+ )
+ throw new Error('Unexpected Developer ID identity')
+ const temporary = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-ffmpeg-certificate-')
+ )
+ try {
+ await checked(run, '/usr/bin/codesign', [
+ '--verify',
+ '--strict',
+ '--check-notarization',
+ '--verbose=2',
+ '-R',
+ '=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and notarized',
+ binary,
+ ])
+ const display = await checked(run, '/usr/bin/codesign', [
+ '--display',
+ '--verbose=4',
+ binary,
+ ])
+ const text = `${display.stdout}\n${display.stderr}`
+ const field = (label: string) => {
+ const values = text
+ .split(/\r?\n/)
+ .filter((line) => line.startsWith(`${label}=`))
+ .map((line) => line.slice(label.length + 1))
+ if (values.length !== 1)
+ throw new Error('Ambiguous FFmpeg signing identity')
+ return values[0]
+ }
+ const record = signing.binaries[name]
+ const canonicalTimestamp = parseSecureTimestamp(field('Timestamp'))
+ const flags = /flags=0x([0-9a-f]+)\(/i.exec(text)
+ // The Team ID is authenticated by the pinned manifest and compared only in memory.
+ if (
+ field('TeamIdentifier') !== signing.identity.teamId ||
+ field('CDHash') !== record.cdHash ||
+ canonicalTimestamp !== record.timestamp ||
+ field('Identifier') !== `net.agalwood.motrix.${name}` ||
+ !text.split(/\r?\n/).includes(`Authority=${signing.identity.subject}`) ||
+ !flags ||
+ (Number.parseInt(flags[1], 16) & 0x10000) === 0
+ )
+ throw new Error('FFmpeg signature evidence mismatch')
+ const prefix = path.join(temporary, name)
+ await checked(run, '/usr/bin/codesign', [
+ '--display',
+ `--extract-certificates=${prefix}`,
+ binary,
+ ])
+ if (sha256(await readFile(`${prefix}0`)) !== certificate.certificateSha256)
+ throw new Error('FFmpeg leaf certificate mismatch')
+ // Apple prescribes the notarized requirement for standalone CLI tools;
+ // spctl's application assessment rejects valid non-app executables.
+ } finally {
+ await rm(temporary, { recursive: true, force: true })
+ }
+}
diff --git a/src/core/process/command-runner.ts b/src/core/process/command-runner.ts
new file mode 100644
index 00000000..81c6ecef
--- /dev/null
+++ b/src/core/process/command-runner.ts
@@ -0,0 +1,282 @@
+import { spawn } from 'node:child_process'
+import path from 'node:path'
+
+export interface RunResult {
+ code: number | null
+ stdout: string
+ stderr: string
+ spawnError?: NodeJS.ErrnoException
+ commandMissing?: boolean
+ timedOut?: boolean
+ truncated?: boolean
+}
+
+export interface RunOptions {
+ cwd?: string
+ env?: NodeJS.ProcessEnv
+ timeoutMs?: number
+ maxBuffer?: number
+}
+
+export type RunCommand = (
+ command: string,
+ args: readonly string[],
+ options?: RunOptions
+) => Promise<RunResult>
+
+interface CommandRunnerDependencies {
+ platform?: NodeJS.Platform
+ systemRoot?: string
+ spawnProcess?: typeof spawn
+ killProcess?: typeof process.kill
+}
+
+const DEFAULT_MAX_BUFFER = 1_000_000
+const PROCESS_KILL_GRACE_MS = 2_000
+const TIMEOUT_FORCE_SETTLE_MS = 3_000
+const WINDOWS_FALLBACK_ROOT = 'C:\\Windows'
+const CMD_META = /([()\][%!^"`<>&|;, *?])/g
+
+export function escapeCmdCommand(command: string): string {
+ return command.replace(CMD_META, '^$1')
+}
+
+export function escapeCmdArgument(
+ argument: string,
+ doubleEscapeMetaChars = false
+): string {
+ let escaped = `${argument}`
+ escaped = escaped.replace(/(\\*)"/g, '$1$1\\"')
+ escaped = escaped.replace(/(\\*)$/, '$1$1')
+ escaped = `"${escaped}"`
+ escaped = escaped.replace(CMD_META, '^$1')
+ if (doubleEscapeMetaChars) escaped = escaped.replace(CMD_META, '^$1')
+ return escaped
+}
+
+export function windowsSystemBinary(
+ name: 'cmd.exe' | 'taskkill.exe',
+ systemRoot: string | undefined
+): string {
+ const root =
+ systemRoot && path.win32.isAbsolute(systemRoot)
+ ? systemRoot
+ : WINDOWS_FALLBACK_ROOT
+ return path.win32.join(root, 'System32', name)
+}
+
+export function isCommandMissing(
+ code: number | null,
+ stderr: string,
+ platform: NodeJS.Platform = process.platform
+): boolean {
+ if (platform !== 'win32') return false
+ return (
+ code === 9009 ||
+ /is not recognized as an internal or external command/i.test(stderr)
+ )
+}
+
+function isAbsoluteForPlatform(
+ command: string,
+ platform: NodeJS.Platform
+): boolean {
+ return platform === 'win32'
+ ? path.win32.isAbsolute(command)
+ : path.isAbsolute(command)
+}
+
+function invalidCommandResult(command: string): RunResult {
+ const error = new Error(
+ `Command must be an absolute path: ${command}`
+ ) as NodeJS.ErrnoException
+ error.code = 'EINVAL'
+ return { code: null, stdout: '', stderr: '', spawnError: error }
+}
+
+function appendTail(
+ current: Buffer<ArrayBufferLike>,
+ chunk: Buffer<ArrayBufferLike>,
+ cap: number
+): { value: Buffer<ArrayBufferLike>; truncated: boolean } {
+ const combined = Buffer.concat([current, chunk])
+ if (combined.byteLength <= cap) {
+ return { value: combined, truncated: false }
+ }
+ return {
+ value: combined.subarray(combined.byteLength - cap),
+ truncated: true,
+ }
+}
+
+export function createCommandRunner(
+ dependencies: CommandRunnerDependencies = {}
+): RunCommand {
+ const platform = dependencies.platform ?? process.platform
+ const spawnProcess = dependencies.spawnProcess ?? spawn
+ const killProcess = dependencies.killProcess ?? process.kill.bind(process)
+ const systemRoot = dependencies.systemRoot ?? process.env.SystemRoot
+
+ return (command, args, options) => {
+ if (!isAbsoluteForPlatform(command, platform)) {
+ return Promise.resolve(invalidCommandResult(command))
+ }
+
+ return new Promise((resolve) => {
+ const isWindows = platform === 'win32'
+ const batchShim = isWindows && /\.(?:cmd|bat)$/i.test(command)
+ const cap = Math.max(1, options?.maxBuffer ?? DEFAULT_MAX_BUFFER)
+ let child: ReturnType<typeof spawn>
+
+ try {
+ child = spawnProcess(
+ batchShim ? escapeCmdCommand(command) : command,
+ batchShim
+ ? args.map((argument) => escapeCmdArgument(argument, true))
+ : [...args],
+ {
+ cwd: options?.cwd,
+ env: options?.env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: batchShim
+ ? windowsSystemBinary('cmd.exe', systemRoot)
+ : false,
+ detached: !isWindows,
+ windowsHide: isWindows,
+ }
+ )
+ } catch (error) {
+ const spawnError = error as NodeJS.ErrnoException
+ resolve({
+ code: null,
+ stdout: '',
+ stderr: '',
+ spawnError,
+ commandMissing: spawnError.code === 'ENOENT' || undefined,
+ })
+ return
+ }
+
+ let stdout: Buffer<ArrayBufferLike> = Buffer.alloc(0)
+ let stderr: Buffer<ArrayBufferLike> = Buffer.alloc(0)
+ let truncated = false
+ let timedOut = false
+ let settled = false
+ let timeout: NodeJS.Timeout | undefined
+ let killGrace: NodeJS.Timeout | undefined
+ let forceSettle: NodeJS.Timeout | undefined
+
+ child.stdout?.on('data', (data: Buffer | string) => {
+ const appended = appendTail(stdout, Buffer.from(data), cap)
+ stdout = appended.value
+ truncated ||= appended.truncated
+ })
+ child.stderr?.on('data', (data: Buffer | string) => {
+ const appended = appendTail(stderr, Buffer.from(data), cap)
+ stderr = appended.value
+ truncated ||= appended.truncated
+ })
+
+ const finish = (result: Omit<RunResult, 'stdout' | 'stderr'>) => {
+ if (settled) return
+ settled = true
+ if (timeout) clearTimeout(timeout)
+ if (forceSettle) clearTimeout(forceSettle)
+ // Once a timeout starts process-tree termination, keep the escalation
+ // timer alive even if the direct child closes first. Descendants in the
+ // detached process group may have ignored SIGTERM and still need the
+ // delayed SIGKILL.
+ if (killGrace && !timedOut) clearTimeout(killGrace)
+ resolve({
+ ...result,
+ stdout: stdout.toString('utf8'),
+ stderr: stderr.toString('utf8'),
+ timedOut: timedOut || result.timedOut || undefined,
+ truncated: truncated || undefined,
+ })
+ }
+
+ const killTree = () => {
+ const pid = child.pid
+ if (pid == null) return
+ if (isWindows) {
+ try {
+ const taskkill = spawnProcess(
+ windowsSystemBinary('taskkill.exe', systemRoot),
+ ['/pid', String(pid), '/t', '/f'],
+ { stdio: 'ignore', shell: false, windowsHide: true }
+ )
+ // A failed spawn is normally reported asynchronously through the
+ // child error event, outside the surrounding try/catch.
+ taskkill.once('error', () => {})
+ } catch {
+ // Best effort: the child may have exited between timeout and kill.
+ }
+ killGrace = setTimeout(() => {
+ try {
+ child.kill('SIGKILL')
+ } catch {
+ // taskkill already terminated the process tree.
+ }
+ }, PROCESS_KILL_GRACE_MS)
+ killGrace.unref?.()
+ return
+ }
+
+ try {
+ killProcess(-pid, 'SIGTERM')
+ } catch {
+ try {
+ killProcess(pid, 'SIGTERM')
+ } catch {
+ return
+ }
+ }
+ killGrace = setTimeout(() => {
+ try {
+ killProcess(-pid, 'SIGKILL')
+ } catch {
+ try {
+ killProcess(pid, 'SIGKILL')
+ } catch {
+ // Already gone.
+ }
+ }
+ }, PROCESS_KILL_GRACE_MS)
+ killGrace.unref?.()
+ }
+
+ if (options?.timeoutMs && options.timeoutMs > 0) {
+ timeout = setTimeout(() => {
+ timedOut = true
+ // Tree termination is best-effort. Guarantee the public timeout is
+ // still an actual upper bound when the OS never delivers close/error.
+ forceSettle = setTimeout(() => {
+ finish({ code: null, timedOut: true })
+ }, TIMEOUT_FORCE_SETTLE_MS)
+ forceSettle.unref?.()
+ killTree()
+ }, options.timeoutMs)
+ timeout.unref?.()
+ }
+
+ child.on('error', (spawnError: NodeJS.ErrnoException) => {
+ finish({
+ code: null,
+ spawnError,
+ commandMissing: spawnError.code === 'ENOENT' || undefined,
+ })
+ })
+ child.on('close', (code) => {
+ const stderrText = stderr.toString('utf8')
+ finish({
+ code,
+ commandMissing:
+ isCommandMissing(code, stderrText, platform) || undefined,
+ })
+ })
+ })
+ }
+}
+
+export const runCommand = createCommandRunner()
diff --git a/src/main/cli/command-runner.ts b/src/main/cli/command-runner.ts
index 81c6ecef..420096b9 100644
--- a/src/main/cli/command-runner.ts
+++ b/src/main/cli/command-runner.ts
@@ -1,282 +1 @@
-import { spawn } from 'node:child_process'
-import path from 'node:path'
-
-export interface RunResult {
- code: number | null
- stdout: string
- stderr: string
- spawnError?: NodeJS.ErrnoException
- commandMissing?: boolean
- timedOut?: boolean
- truncated?: boolean
-}
-
-export interface RunOptions {
- cwd?: string
- env?: NodeJS.ProcessEnv
- timeoutMs?: number
- maxBuffer?: number
-}
-
-export type RunCommand = (
- command: string,
- args: readonly string[],
- options?: RunOptions
-) => Promise<RunResult>
-
-interface CommandRunnerDependencies {
- platform?: NodeJS.Platform
- systemRoot?: string
- spawnProcess?: typeof spawn
- killProcess?: typeof process.kill
-}
-
-const DEFAULT_MAX_BUFFER = 1_000_000
-const PROCESS_KILL_GRACE_MS = 2_000
-const TIMEOUT_FORCE_SETTLE_MS = 3_000
-const WINDOWS_FALLBACK_ROOT = 'C:\\Windows'
-const CMD_META = /([()\][%!^"`<>&|;, *?])/g
-
-export function escapeCmdCommand(command: string): string {
- return command.replace(CMD_META, '^$1')
-}
-
-export function escapeCmdArgument(
- argument: string,
- doubleEscapeMetaChars = false
-): string {
- let escaped = `${argument}`
- escaped = escaped.replace(/(\\*)"/g, '$1$1\\"')
- escaped = escaped.replace(/(\\*)$/, '$1$1')
- escaped = `"${escaped}"`
- escaped = escaped.replace(CMD_META, '^$1')
- if (doubleEscapeMetaChars) escaped = escaped.replace(CMD_META, '^$1')
- return escaped
-}
-
-export function windowsSystemBinary(
- name: 'cmd.exe' | 'taskkill.exe',
- systemRoot: string | undefined
-): string {
- const root =
- systemRoot && path.win32.isAbsolute(systemRoot)
- ? systemRoot
- : WINDOWS_FALLBACK_ROOT
- return path.win32.join(root, 'System32', name)
-}
-
-export function isCommandMissing(
- code: number | null,
- stderr: string,
- platform: NodeJS.Platform = process.platform
-): boolean {
- if (platform !== 'win32') return false
- return (
- code === 9009 ||
- /is not recognized as an internal or external command/i.test(stderr)
- )
-}
-
-function isAbsoluteForPlatform(
- command: string,
- platform: NodeJS.Platform
-): boolean {
- return platform === 'win32'
- ? path.win32.isAbsolute(command)
- : path.isAbsolute(command)
-}
-
-function invalidCommandResult(command: string): RunResult {
- const error = new Error(
- `Command must be an absolute path: ${command}`
- ) as NodeJS.ErrnoException
- error.code = 'EINVAL'
- return { code: null, stdout: '', stderr: '', spawnError: error }
-}
-
-function appendTail(
- current: Buffer<ArrayBufferLike>,
- chunk: Buffer<ArrayBufferLike>,
- cap: number
-): { value: Buffer<ArrayBufferLike>; truncated: boolean } {
- const combined = Buffer.concat([current, chunk])
- if (combined.byteLength <= cap) {
- return { value: combined, truncated: false }
- }
- return {
- value: combined.subarray(combined.byteLength - cap),
- truncated: true,
- }
-}
-
-export function createCommandRunner(
- dependencies: CommandRunnerDependencies = {}
-): RunCommand {
- const platform = dependencies.platform ?? process.platform
- const spawnProcess = dependencies.spawnProcess ?? spawn
- const killProcess = dependencies.killProcess ?? process.kill.bind(process)
- const systemRoot = dependencies.systemRoot ?? process.env.SystemRoot
-
- return (command, args, options) => {
- if (!isAbsoluteForPlatform(command, platform)) {
- return Promise.resolve(invalidCommandResult(command))
- }
-
- return new Promise((resolve) => {
- const isWindows = platform === 'win32'
- const batchShim = isWindows && /\.(?:cmd|bat)$/i.test(command)
- const cap = Math.max(1, options?.maxBuffer ?? DEFAULT_MAX_BUFFER)
- let child: ReturnType<typeof spawn>
-
- try {
- child = spawnProcess(
- batchShim ? escapeCmdCommand(command) : command,
- batchShim
- ? args.map((argument) => escapeCmdArgument(argument, true))
- : [...args],
- {
- cwd: options?.cwd,
- env: options?.env,
- stdio: ['ignore', 'pipe', 'pipe'],
- shell: batchShim
- ? windowsSystemBinary('cmd.exe', systemRoot)
- : false,
- detached: !isWindows,
- windowsHide: isWindows,
- }
- )
- } catch (error) {
- const spawnError = error as NodeJS.ErrnoException
- resolve({
- code: null,
- stdout: '',
- stderr: '',
- spawnError,
- commandMissing: spawnError.code === 'ENOENT' || undefined,
- })
- return
- }
-
- let stdout: Buffer<ArrayBufferLike> = Buffer.alloc(0)
- let stderr: Buffer<ArrayBufferLike> = Buffer.alloc(0)
- let truncated = false
- let timedOut = false
- let settled = false
- let timeout: NodeJS.Timeout | undefined
- let killGrace: NodeJS.Timeout | undefined
- let forceSettle: NodeJS.Timeout | undefined
-
- child.stdout?.on('data', (data: Buffer | string) => {
- const appended = appendTail(stdout, Buffer.from(data), cap)
- stdout = appended.value
- truncated ||= appended.truncated
- })
- child.stderr?.on('data', (data: Buffer | string) => {
- const appended = appendTail(stderr, Buffer.from(data), cap)
- stderr = appended.value
- truncated ||= appended.truncated
- })
-
- const finish = (result: Omit<RunResult, 'stdout' | 'stderr'>) => {
- if (settled) return
- settled = true
- if (timeout) clearTimeout(timeout)
- if (forceSettle) clearTimeout(forceSettle)
- // Once a timeout starts process-tree termination, keep the escalation
- // timer alive even if the direct child closes first. Descendants in the
- // detached process group may have ignored SIGTERM and still need the
- // delayed SIGKILL.
- if (killGrace && !timedOut) clearTimeout(killGrace)
- resolve({
- ...result,
- stdout: stdout.toString('utf8'),
- stderr: stderr.toString('utf8'),
- timedOut: timedOut || result.timedOut || undefined,
- truncated: truncated || undefined,
- })
- }
-
- const killTree = () => {
- const pid = child.pid
- if (pid == null) return
- if (isWindows) {
- try {
- const taskkill = spawnProcess(
- windowsSystemBinary('taskkill.exe', systemRoot),
- ['/pid', String(pid), '/t', '/f'],
- { stdio: 'ignore', shell: false, windowsHide: true }
- )
- // A failed spawn is normally reported asynchronously through the
- // child error event, outside the surrounding try/catch.
- taskkill.once('error', () => {})
- } catch {
- // Best effort: the child may have exited between timeout and kill.
- }
- killGrace = setTimeout(() => {
- try {
- child.kill('SIGKILL')
- } catch {
- // taskkill already terminated the process tree.
- }
- }, PROCESS_KILL_GRACE_MS)
- killGrace.unref?.()
- return
- }
-
- try {
- killProcess(-pid, 'SIGTERM')
- } catch {
- try {
- killProcess(pid, 'SIGTERM')
- } catch {
- return
- }
- }
- killGrace = setTimeout(() => {
- try {
- killProcess(-pid, 'SIGKILL')
- } catch {
- try {
- killProcess(pid, 'SIGKILL')
- } catch {
- // Already gone.
- }
- }
- }, PROCESS_KILL_GRACE_MS)
- killGrace.unref?.()
- }
-
- if (options?.timeoutMs && options.timeoutMs > 0) {
- timeout = setTimeout(() => {
- timedOut = true
- // Tree termination is best-effort. Guarantee the public timeout is
- // still an actual upper bound when the OS never delivers close/error.
- forceSettle = setTimeout(() => {
- finish({ code: null, timedOut: true })
- }, TIMEOUT_FORCE_SETTLE_MS)
- forceSettle.unref?.()
- killTree()
- }, options.timeoutMs)
- timeout.unref?.()
- }
-
- child.on('error', (spawnError: NodeJS.ErrnoException) => {
- finish({
- code: null,
- spawnError,
- commandMissing: spawnError.code === 'ENOENT' || undefined,
- })
- })
- child.on('close', (code) => {
- const stderrText = stderr.toString('utf8')
- finish({
- code,
- commandMissing:
- isCommandMissing(code, stderrText, platform) || undefined,
- })
- })
- })
- }
-}
-
-export const runCommand = createCommandRunner()
+export * from '@core/process/command-runner'
diff --git a/src/main/core/update-manager.ts b/src/main/core/update-manager.ts
index b8cc4588..e96b5c93 100644
--- a/src/main/core/update-manager.ts
+++ b/src/main/core/update-manager.ts
@@ -1,5 +1,6 @@
import type { EventBus } from '@core/events/event-bus'
import { getLogger } from '@core/logger'
+import { isVersionAllowedForChannel } from '@shared/app-update-channel'
import { type EventChannel, Events } from '@shared/protocol/events'
import type {
AppUpdateProgress,
@@ -8,6 +9,8 @@ import type {
import type { AppUpdateChannel } from '@shared/types/settings'
import type { VerifyUpdateSupport } from 'electron-updater'
+export { isVersionAllowedForChannel } from '@shared/app-update-channel'
+
export interface Updater {
autoDownload: boolean
autoInstallOnAppQuit: boolean
@@ -355,20 +358,6 @@ export class UpdateManager {
}
}
-const STRICT_SEMVER_PATTERN =
- /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
-
-export function isVersionAllowedForChannel(
- version: string,
- channel: AppUpdateChannel
-): boolean {
- const match = STRICT_SEMVER_PATTERN.exec(version)
- if (!match) return false
- const prerelease = match[4]
- if (prerelease === undefined) return true
- return channel === 'beta' && prerelease.split('.')[0] === 'beta'
-}
-
function asRecord(value: unknown): Record<string, unknown> | null {
return typeof value === 'object' && value !== null
? (value as Record<string, unknown>)
diff --git a/src/main/plugin/ffmpeg-macos-trust.ts b/src/main/plugin/ffmpeg-macos-trust.ts
index 180c4954..1362d9f1 100644
--- a/src/main/plugin/ffmpeg-macos-trust.ts
+++ b/src/main/plugin/ffmpeg-macos-trust.ts
@@ -1,168 +1,4 @@
-import { randomUUID } from 'node:crypto'
-import { mkdtemp, readFile, rm } from 'node:fs/promises'
-import os from 'node:os'
-import path from 'node:path'
-import { sha256 } from '@core/ffmpeg/verified-release'
-import certificate from '@shared/config/ffmpeg-macos-certificate.json'
-import type { FfmpegTarget } from '@shared/schemas/ffmpeg-release'
-import { type RunCommand, runCommand } from '../cli/command-runner'
-
-function parseSecureTimestamp(value: string): string {
- // codesign uses system date preferences even with LC_ALL=C. Normalize only
- // horizontal separators, then accept the explicit English date orders.
- const raw = value.replace(/[ \t\u00a0\u202f]+/g, ' ')
- const timestamp =
- /^(?:([A-Z][a-z]{2}) (\d{1,2}),|(\d{1,2}) ([A-Z][a-z]{2})) (\d{4}) at (\d{1,2}):(\d{2}):(\d{2})(?: (AM|PM))?$/.exec(
- raw
- )
- if (!timestamp) throw new Error('Missing secure FFmpeg timestamp')
- const month = [
- 'Jan',
- 'Feb',
- 'Mar',
- 'Apr',
- 'May',
- 'Jun',
- 'Jul',
- 'Aug',
- 'Sep',
- 'Oct',
- 'Nov',
- 'Dec',
- ].indexOf(timestamp[1] ?? timestamp[4])
- const day = Number(timestamp[2] ?? timestamp[3])
- const year = Number(timestamp[5])
- let hour = Number(timestamp[6])
- const minute = Number(timestamp[7])
- const second = Number(timestamp[8])
- if (timestamp[9]) {
- if (hour < 1 || hour > 12)
- throw new Error('Invalid secure FFmpeg timestamp')
- hour = (hour % 12) + (timestamp[9] === 'PM' ? 12 : 0)
- }
- const date = new Date(Date.UTC(year, month, day, hour, minute, second))
- if (
- month < 0 ||
- date.getUTCFullYear() !== year ||
- date.getUTCMonth() !== month ||
- date.getUTCDate() !== day ||
- date.getUTCHours() !== hour ||
- date.getUTCMinutes() !== minute ||
- date.getUTCSeconds() !== second
- )
- throw new Error('Invalid secure FFmpeg timestamp')
- return date.toISOString().replace('.000Z', 'Z')
-}
-
-/** Static OS checks only. Never execute an unverified payload or remove quarantine. */
-export async function verifyMacFfmpegTrust(
- directory: string,
- target: FfmpegTarget,
- sourceUrl: string,
- run: RunCommand = runCommand
-): Promise<void> {
- if (
- !sourceUrl.startsWith(
- 'https://github.com/motrixapp/ffmpeg-static/releases/download/'
- )
- )
- throw new Error('Unexpected FFmpeg source')
- for (const name of ['ffmpeg', 'ffprobe'] as const) {
- const binary = path.join(directory, name)
- // Chromium networking does not propagate Finder quarantine; mark this Internet download explicitly.
- await checked(run, '/usr/bin/xattr', [
- '-w',
- 'com.apple.quarantine',
- `0081;${Math.floor(Date.now() / 1000).toString(16)};Motrix;${randomUUID()}`,
- binary,
- ])
- await verifyMacFfmpegBinaryTrust(binary, name, target, run)
- }
-}
-
-async function checked(run: RunCommand, command: string, args: string[]) {
- const result = await run(command, args, {
- env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
- timeoutMs: 30_000,
- maxBuffer: 64_000,
- })
- if (
- result.code !== 0 ||
- result.spawnError ||
- result.timedOut ||
- result.truncated
- )
- throw new Error('FFmpeg system trust check failed')
- return result
-}
-
-/** The caller authenticates the target and binary hash before these CLI checks. */
-export async function verifyMacFfmpegBinaryTrust(
- binary: string,
- name: 'ffmpeg' | 'ffprobe',
- target: FfmpegTarget,
- run: RunCommand = runCommand
-): Promise<void> {
- const signing = target.signing
- if (
- target.platform !== 'darwin' ||
- !signing ||
- signing.identity.certificateSha256 !== certificate.certificateSha256
- )
- throw new Error('Unexpected Developer ID identity')
- const temporary = await mkdtemp(
- path.join(os.tmpdir(), 'motrix-ffmpeg-certificate-')
- )
- try {
- await checked(run, '/usr/bin/codesign', [
- '--verify',
- '--strict',
- '--check-notarization',
- '--verbose=2',
- '-R',
- '=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and notarized',
- binary,
- ])
- const display = await checked(run, '/usr/bin/codesign', [
- '--display',
- '--verbose=4',
- binary,
- ])
- const text = `${display.stdout}\n${display.stderr}`
- const field = (label: string) => {
- const values = text
- .split(/\r?\n/)
- .filter((line) => line.startsWith(`${label}=`))
- .map((line) => line.slice(label.length + 1))
- if (values.length !== 1)
- throw new Error('Ambiguous FFmpeg signing identity')
- return values[0]
- }
- const record = signing.binaries[name]
- const canonicalTimestamp = parseSecureTimestamp(field('Timestamp'))
- const flags = /flags=0x([0-9a-f]+)\(/i.exec(text)
- // The Team ID is authenticated by the pinned manifest and compared only in memory.
- if (
- field('TeamIdentifier') !== signing.identity.teamId ||
- field('CDHash') !== record.cdHash ||
- canonicalTimestamp !== record.timestamp ||
- field('Identifier') !== `net.agalwood.motrix.${name}` ||
- !text.split(/\r?\n/).includes(`Authority=${signing.identity.subject}`) ||
- !flags ||
- (Number.parseInt(flags[1], 16) & 0x10000) === 0
- )
- throw new Error('FFmpeg signature evidence mismatch')
- const prefix = path.join(temporary, name)
- await checked(run, '/usr/bin/codesign', [
- '--display',
- `--extract-certificates=${prefix}`,
- binary,
- ])
- if (sha256(await readFile(`${prefix}0`)) !== certificate.certificateSha256)
- throw new Error('FFmpeg leaf certificate mismatch')
- // Apple prescribes the notarized requirement for standalone CLI tools;
- // spctl's application assessment rejects valid non-app executables.
- } finally {
- await rm(temporary, { recursive: true, force: true })
- }
-}
+export {
+ verifyMacFfmpegBinaryTrust,
+ verifyMacFfmpegTrust,
+} from '@core/ffmpeg/ffmpeg-macos-trust'
diff --git a/src/renderer/components/notification-center/notifications-nav-item.test.tsx b/src/renderer/components/notification-center/notifications-nav-item.test.tsx
index 260c8bc1..f60e93a4 100644
--- a/src/renderer/components/notification-center/notifications-nav-item.test.tsx
+++ b/src/renderer/components/notification-center/notifications-nav-item.test.tsx
@@ -172,17 +172,19 @@ describe('<NotificationsNavItem>', () => {
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
- it('keeps the Web badge numeric even if desktop settings hide it', async () => {
+ it('applies the Web badge preference and refreshes it after settings change', async () => {
Object.defineProperty(transport, 'platform', {
value: 'web',
configurable: true,
})
- mockInvoke(7, 'hidden')
+ mockInvoke(7, 'dot')
renderNavItem()
- expect(await screen.findByTestId('notification-badge')).toHaveTextContent(
- '7'
- )
- expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetSettings)
+ await screen.findByTestId('notification-badge-dot')
+ expect(screen.queryByTestId('notification-badge')).not.toBeInTheDocument()
+ mockInvoke(7, 'hidden')
+ await act(() => refreshRendererSettings())
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ expect(screen.getByRole('link', { name: 'Notifications' })).toBeVisible()
})
it('hides the badge when the unread count is zero', async () => {
diff --git a/src/renderer/components/notification-center/use-notifications.ts b/src/renderer/components/notification-center/use-notifications.ts
index 558df2dd..de6dd104 100644
--- a/src/renderer/components/notification-center/use-notifications.ts
+++ b/src/renderer/components/notification-center/use-notifications.ts
@@ -15,7 +15,7 @@ import { useCallback, useState } from 'react'
export interface UseNotificationsOptions {
/**
* Skip `Queries.ListNotifications` entirely and leave `items` at `[]`.
- * The always-mounted sidebar reads the count and, on desktop, its badge
+ * The always-mounted sidebar reads the count and its badge
* preference. It never needs the list's up to 100 rows and their params.
*
* Mount-constant: the mirror captures wiring at mount; flipping this
@@ -52,7 +52,7 @@ export interface UseNotificationsResult {
* `{ countOnly: true }` (e.g. `NotificationsNavItem`, the always-mounted
* sidebar badge) skips the `ListNotifications` invoke and leaves `items`
* at `[]` — the return shape is unchanged so callers that only destructure
- * `unreadCount` need no other change. The desktop badge preference is loaded
+ * `unreadCount` need no other change. The badge preference is loaded
* before publishing the count so a hidden badge never flashes at startup.
*
* Mutations (`markRead`/`markAllRead`/`remove`/`clear`) only invoke the
@@ -77,7 +77,7 @@ export function useNotifications(
const load = useCallback(
async (stale: () => boolean, read: SettingsReader) => {
let style: NotificationBadgeStyle = 'count'
- if (countOnly && transport.platform !== 'web') {
+ if (countOnly) {
const settings = (await read(Queries.GetSettings)) as
| AppSettings
| undefined
@@ -101,7 +101,7 @@ export function useNotifications(
const { refresh } = useTransportMirror({
events: [Events.NotificationsChanged],
- refreshOnSettingsSave: transport.platform !== 'web',
+ refreshOnSettingsSave: true,
load,
})
diff --git a/src/renderer/features/directory-preferences/directory-preferences-section.tsx b/src/renderer/features/directory-preferences/directory-preferences-section.tsx
index ae199ff7..ea2f215f 100644
--- a/src/renderer/features/directory-preferences/directory-preferences-section.tsx
+++ b/src/renderer/features/directory-preferences/directory-preferences-section.tsx
@@ -1,8 +1,8 @@
import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import {
+ AddIcon,
ChevronRightIcon,
FavoriteIcon,
- FolderAddIcon,
FolderIcon,
RemoveIcon,
} from '@renderer/components/icons'
@@ -257,12 +257,12 @@ export function DirectoryPreferencesSection({
<Button
ref={add}
type="button"
- size="sm"
+ size="xs"
variant="outline"
disabled={busy || full}
onClick={() => void addFavorite()}
>
- <FolderAddIcon />
+ <AddIcon />
{t('directoryPreferences.addFavorite')}
</Button>
</div>
@@ -278,7 +278,7 @@ export function DirectoryPreferencesSection({
</CollapsibleContent>
</Collapsible>
<Collapsible open={recentOpen} onOpenChange={setRecentOpen}>
- <div className="mb-2 flex items-center justify-between gap-2">
+ <div className="mb-2 flex min-h-6 items-center justify-between gap-2">
<CollapsibleTrigger
disabled={busy}
className="flex min-w-0 items-center gap-1 text-xs font-medium"
@@ -294,7 +294,7 @@ export function DirectoryPreferencesSection({
{recentOpen && (
<Button
type="button"
- size="sm"
+ size="xs"
variant="ghost"
disabled={busy || preferences.recent.length === 0}
onClick={() => change({ ...preferences, recent: [] })}
diff --git a/src/renderer/hooks/use-ffmpeg-install.ts b/src/renderer/hooks/use-ffmpeg-install.ts
index c3972997..865d7edd 100644
--- a/src/renderer/hooks/use-ffmpeg-install.ts
+++ b/src/renderer/hooks/use-ffmpeg-install.ts
@@ -27,7 +27,6 @@ export function useFfmpegInstall() {
events: [Events.FfmpegInstallStatusChanged],
refreshOnSettingsSave: false,
load: async (stale) => {
- if (transport.platform === 'web') return
const next = ffmpegInstallStatusSchema.parse(
await transport.invoke(Queries.GetFfmpegInstallStatus)
)
diff --git a/src/renderer/hooks/use-notification-toasts.ts b/src/renderer/hooks/use-notification-toasts.ts
index 3ef7f879..3154ea5b 100644
--- a/src/renderer/hooks/use-notification-toasts.ts
+++ b/src/renderer/hooks/use-notification-toasts.ts
@@ -43,7 +43,7 @@ const FOCUSED_COMPLETE_TOAST_ID = 'notification-complete'
* 1. Generic error rows (`n.severity === 'error'`, any kind other than
* `engine-failure`) toast through `FOCUSED_ERROR_TOAST_ID`, gated on
* document foreground (see below) and coalesced via close-then-add
- * (F9). Desktop event forwarding filters muted task outcomes before they
+ * (F9). Host event forwarding filters muted task outcomes before they
* reach this hook. Native download notifications independently follow the
* system preference, including while this document is in the foreground.
*
diff --git a/src/renderer/routes/settings/cards/about-dialog.test.tsx b/src/renderer/routes/settings/cards/about-dialog.test.tsx
index 530c1385..7c6423f7 100644
--- a/src/renderer/routes/settings/cards/about-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.test.tsx
@@ -7,12 +7,11 @@ import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import type { AppUpdateState } from '@shared/types/app-update'
-import { act, render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import packageJson from '../../../../../package.json'
import { AboutDialog } from './about-dialog'
-import * as appUpdateSection from './app-update-section'
// These lifecycle tests cover the ordinary desktop host. Portable capability
// presentation is exercised with the real hook in e2e/portable-mode.spec.ts.
@@ -35,6 +34,10 @@ const idleState: AppUpdateState = {
}
beforeEach(() => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'darwin',
+ })
vi.mocked(transport.invoke).mockReset()
vi.mocked(transport.on).mockReset()
vi.mocked(transport.off).mockReset()
@@ -671,31 +674,66 @@ describe('<AboutDialog>', () => {
)
})
- it('renders the web note without querying or subscribing to app updates', () => {
- const showUpdates = vi
- .spyOn(appUpdateSection, 'shouldShowAppUpdate')
- .mockReturnValue(false)
- try {
- renderDialog()
- expect(
- screen.getByText(
- 'This web edition is updated by its deployment administrator.'
- )
- ).toBeInTheDocument()
- expectNoUpdateControls()
- expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetUpdateState)
- expect(transport.on).not.toHaveBeenCalledWith(
- Events.UpdateStateChanged,
- expect.any(Function)
+ it('lets the web host check versions without offering an installer', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'web',
+ })
+ renderDialog()
+ const check = await screen.findByRole('button', {
+ name: 'Check for updates',
+ })
+ expect(
+ screen.getByText(
+ 'This web edition is updated by its deployment administrator.'
)
- } finally {
- showUpdates.mockRestore()
- }
+ ).toBeInTheDocument()
+ await userEvent.click(check)
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.CheckForUpdates)
+ await emitState({
+ phase: 'available',
+ currentVersion: '2.1.0',
+ availableVersion: '2.2.0',
+ updateAuthority: 'administrator',
+ })
+ expect(screen.getByText('Version 2.1.0')).toBeInTheDocument()
+ expect(
+ within(screen.getByRole('group', { name: 'App updates' })).getByRole(
+ 'link',
+ { name: 'Changelog' }
+ )
+ ).toHaveAttribute('href', `${EXTERNAL_URLS.github.releases}/tag/v2.2.0`)
+ expect(
+ screen.queryByRole('button', { name: 'Download update' })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'Restart and install' })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByRole('switch', { name: 'Check automatically' })
+ ).toBeInTheDocument()
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.DownloadUpdate)
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.InstallUpdate)
})
- it('does not expose app updates to the web target', () => {
- expect(appUpdateSection.shouldShowAppUpdate('web')).toBe(false)
- expect(appUpdateSection.shouldShowAppUpdate('electron')).toBe(true)
+ it('keeps web error retries limited to checking, even with an available version', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'web',
+ })
+ renderDialog()
+ await emitState({
+ phase: 'error',
+ currentVersion: '2.1.0',
+ availableVersion: '2.2.0',
+ error: { message: 'private backend detail' },
+ })
+ expect(screen.queryByText(/private backend detail/)).not.toBeInTheDocument()
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Check for updates' })
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.CheckForUpdates)
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.DownloadUpdate)
})
})
diff --git a/src/renderer/routes/settings/cards/about-dialog.tsx b/src/renderer/routes/settings/cards/about-dialog.tsx
index 3e5a9284..7acc7b12 100644
--- a/src/renderer/routes/settings/cards/about-dialog.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.tsx
@@ -17,7 +17,7 @@ import { usePortableMode } from '@renderer/hooks/use-portable-mode'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { AppUpdateSection, shouldShowAppUpdate } from './app-update-section'
+import { AppUpdateSection } from './app-update-section'
import { AutomaticUpdateSetting } from './automatic-update-setting'
import type { SettingsCardDialogProps } from './card-types'
import { useAppUpdate } from './use-app-update'
@@ -52,8 +52,7 @@ export function AboutDialog({
const portable = usePortableMode()
const heading = useRef<HTMLHeadingElement>(null)
const metadata = __MOTRIX_APP_METADATA__
- const showUpdates = shouldShowAppUpdate(__MOTRIX_TARGET__)
- const update = useAppUpdate(showUpdates && open)
+ const update = useAppUpdate(open)
return (
<Dialog open={open} onOpenChange={(value) => !value && onClose()}>
@@ -90,7 +89,7 @@ export function AboutDialog({
</h2>
<p className="text-sm font-medium tabular-nums text-muted-foreground">
{t('settings.about.version', {
- version: metadata.version,
+ version: update.state.currentVersion,
})}
</p>
{portable && (
@@ -165,13 +164,7 @@ export function AboutDialog({
className="min-h-0 flex-1 overscroll-contain"
>
<ScrollAreaContent style={{ minWidth: '100%' }}>
- {showUpdates ? (
- <AppUpdateSection update={update} />
- ) : (
- <p className="px-6 py-5 text-xs text-muted-foreground">
- {t('settings.about.webVersionNote')}
- </p>
- )}
+ <AppUpdateSection update={update} />
</ScrollAreaContent>
</ScrollAreaViewport>
<ScrollBar />
diff --git a/src/renderer/routes/settings/cards/app-update-section.tsx b/src/renderer/routes/settings/cards/app-update-section.tsx
index 6643aa29..6a8f702f 100644
--- a/src/renderer/routes/settings/cards/app-update-section.tsx
+++ b/src/renderer/routes/settings/cards/app-update-section.tsx
@@ -18,7 +18,8 @@ import type { AppUpdateController } from './use-app-update'
export function AppUpdateSection({ update }: { update: AppUpdateController }) {
const { t } = useTranslation()
- const { state, loading, showControls, check, download, install } = update
+ const { state, loading, showControls, checkOnly, check, download, install } =
+ update
const betaWarningId = useId()
const [channel, setChannel] = useState<AppUpdateChannel>('stable')
@@ -42,7 +43,9 @@ export function AppUpdateSection({ update }: { update: AppUpdateController }) {
</h3>
{!loading && (
<p className="mt-1 text-xs leading-normal text-muted-foreground">
- {statusDescription(state, t)}
+ {checkOnly && state.phase === 'available'
+ ? t('settings.about.webVersionNote')
+ : statusDescription(state, t)}
</p>
)}
</div>
@@ -62,6 +65,7 @@ export function AppUpdateSection({ update }: { update: AppUpdateController }) {
>
<UpdateActionButton
state={state}
+ checkOnly={checkOnly}
check={check}
download={download}
install={install}
@@ -70,6 +74,12 @@ export function AppUpdateSection({ update }: { update: AppUpdateController }) {
)}
</div>
+ {checkOnly && state.phase !== 'available' && (
+ <p className="mt-2 text-xs text-muted-foreground">
+ {t('settings.about.webVersionNote')}
+ </p>
+ )}
+
{showControls && channel === 'beta' && (
<Alert
id={betaWarningId}
@@ -85,9 +95,11 @@ export function AppUpdateSection({ update }: { update: AppUpdateController }) {
variant={state.phase === 'error' ? 'destructive' : 'default'}
>
{state.phase === 'error'
- ? t('settings.about.update.error', {
- message: state.error?.message,
- })
+ ? checkOnly
+ ? t('settings.about.update.errorDescription')
+ : t('settings.about.update.error', {
+ message: state.error?.message,
+ })
: t('settings.about.update.cancelled')}
</Alert>
)}
@@ -97,6 +109,7 @@ export function AppUpdateSection({ update }: { update: AppUpdateController }) {
interface UpdateActionButtonProps {
state: AppUpdateState
+ checkOnly: boolean
check: () => Promise<unknown>
download: () => Promise<unknown>
install: () => Promise<unknown>
@@ -113,12 +126,54 @@ interface UpdateAction {
function UpdateActionButton({
state,
+ checkOnly,
check,
download,
install,
}: UpdateActionButtonProps) {
const { t } = useTranslation()
+ if (checkOnly) {
+ const checking = state.phase === 'checking'
+ return (
+ <>
+ {state.phase === 'available' && state.availableVersion && (
+ <a
+ href={`${EXTERNAL_URLS.github.releases}/tag/v${encodeURIComponent(state.availableVersion)}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(
+ buttonVariants({ size: 'sm' }),
+ 'h-7! rounded-md! px-2 text-xs shadow-none'
+ )}
+ >
+ {t('settings.about.resources.changelog')}
+ </a>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ className="h-7! gap-1.5 rounded-md! px-2 text-xs shadow-none"
+ disabled={checking}
+ aria-busy={checking || undefined}
+ aria-label={t('settings.about.update.check')}
+ onClick={() => void check()}
+ >
+ {checking ? (
+ <Spinner className="size-3.5" aria-hidden />
+ ) : (
+ <RefreshIcon className="size-3.5" aria-hidden />
+ )}
+ {t(
+ checking
+ ? 'settings.about.update.checking'
+ : 'settings.about.update.checkAction'
+ )}
+ </Button>
+ </>
+ )
+ }
+
if (state.manualInstallReason && state.availableVersion) {
return (
<a
@@ -323,7 +378,3 @@ function statusDescription(
})
}
}
-
-export function shouldShowAppUpdate(target: 'electron' | 'web'): boolean {
- return target === 'electron'
-}
diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsx
index 01b03871..867e8c5b 100644
--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx
@@ -204,37 +204,75 @@ describe('General settings', () => {
expect(saves()[0]?.[1]).toMatchObject({ app: { runMode: 2 } })
}
)
- it('keeps unsupported desktop controls out of the Web dialog', async () => {
+ it('saves Web notification preferences without changing desktop-only settings', async () => {
transport.platform = 'web'
- render(
- <GeneralDialog
- open
- onClose={vi.fn()}
- labelKey="settings.cards.general.title"
- descKey="settings.cards.general.desc"
- />
- )
- expect(screen.queryByRole('switch')).toBeNull()
- expect(screen.queryByRole('combobox')).toBeNull()
- expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
- })
- it('disables writes after a failed load and supports retry', async () => {
- vi.mocked(transport.invoke).mockRejectedValueOnce(new Error('offline'))
- render(<GeneralDialog open onClose={vi.fn()} labelKey="" descKey="" />)
- await screen.findByRole('button', { name: 'Retry' })
- expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ snapshot.app.notifyInAppOnComplete = true
+ snapshot.app.notifyInAppOnError = true
+ const close = await openGeneral()
+ const user = userEvent.setup()
expect(
- screen.getByRole('switch', { name: 'Open at login' })
- ).toHaveAttribute('aria-disabled', 'true')
- fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
- await waitFor(() =>
- expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ screen.queryByRole('switch', { name: 'Open at login' })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('combobox', { name: 'Download completed' })
+ ).not.toBeInTheDocument()
+ await user.click(
+ screen.getByRole('switch', { name: 'Show completed downloads' })
+ )
+ await user.click(
+ screen.getByRole('switch', { name: 'Show failed downloads' })
)
- expect(transport.invoke).toHaveBeenCalledWith(
- Queries.GetGeneralSettingsDraft,
- {}
+ await user.click(screen.getByRole('combobox', { name: 'Unread badge' }))
+ await user.click(await screen.findByRole('option', { name: 'Dot' }))
+ expect(saves()).toHaveLength(0)
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ expect(saves()[0]?.[1]).toEqual({
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: {
+ notifyInAppOnComplete: false,
+ notifyInAppOnError: false,
+ notificationBadgeStyle: 'dot',
+ },
+ directories: { addFavorites: [], removeFavorites: [], removeRecent: [] },
+ })
+ expect(close).toHaveBeenCalledOnce()
+ })
+
+ it('discards Web notification edits on Cancel', async () => {
+ transport.platform = 'web'
+ const close = await openGeneral()
+ const user = userEvent.setup()
+ await user.click(
+ screen.getByRole('switch', { name: 'Show completed downloads' })
)
+ await user.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(saves()).toHaveLength(0)
+ expect(close).toHaveBeenCalledOnce()
})
+ it.each(['darwin', 'web'] as const)(
+ 'disables writes after a failed load and supports retry on %s',
+ async (platform) => {
+ transport.platform = platform
+ vi.mocked(transport.invoke).mockRejectedValueOnce(new Error('offline'))
+ render(<GeneralDialog open onClose={vi.fn()} labelKey="" descKey="" />)
+ await screen.findByRole('button', { name: 'Retry' })
+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ expect(
+ screen.getByRole('switch', {
+ name:
+ platform === 'web' ? 'Show completed downloads' : 'Open at login',
+ })
+ ).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Queries.GetGeneralSettingsDraft,
+ {}
+ )
+ }
+ )
it('preserves intent after an uncertain committed save and reversal', async () => {
let lost = true
vi.mocked(transport.invoke).mockImplementation(async (channel, raw) => {
diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsx
index c8c71c79..0a53d59e 100644
--- a/src/renderer/routes/settings/cards/general-dialog.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.tsx
@@ -76,7 +76,7 @@ export function GeneralDialog({
generalFormSchema.parse({
...authority,
runMode:
- !isMac && authority.runMode === RunMode.HideTray
+ !isWeb && !isMac && authority.runMode === RunMode.HideTray
? RunMode.Standard
: authority.runMode,
})
@@ -91,7 +91,7 @@ export function GeneralDialog({
const busy = form.formState.isSubmitting || directories.saving
const disabled = !directories.ready || directories.loading || busy
const onSubmit = useSettingsSubmit(form, async () => {
- if (!directories.ready || directories.loading || isWeb) return
+ if (!directories.ready || directories.loading) return
if (await directories.save()) onClose()
})
const close = () => {
@@ -102,7 +102,9 @@ export function GeneralDialog({
| 'launchAtStartup'
| 'showMainWindowAtLogin'
| 'lightweightMode'
- | 'warnBeforeQuit',
+ | 'warnBeforeQuit'
+ | 'notifyInAppOnComplete'
+ | 'notifyInAppOnError',
description?: string,
dependsOn = true
) => (
@@ -230,7 +232,11 @@ export function GeneralDialog({
<DialogHeader className="shrink-0 px-6 pt-6">
<DialogTitle>{t(labelKey)}</DialogTitle>
<DialogDescription>
- {t('settings.general.description')}
+ {t(
+ isWeb
+ ? 'settings.general.inAppNotificationsDesc'
+ : 'settings.general.description'
+ )}
</DialogDescription>
</DialogHeader>
<ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">
@@ -248,173 +254,180 @@ export function GeneralDialog({
disabled={busy}
onRetry={() => void directories.refresh()}
/>
- {isWeb ? (
- <p className="text-sm text-muted-foreground">
- {t('settings.general.desktopOnly')}
- </p>
- ) : (
- <Form {...form}>
- <form noValidate onSubmit={onSubmit}>
- <fieldset
- inert={disabled}
- disabled={disabled}
- className="min-w-0 space-y-4"
- >
- <h3 className="text-sm font-semibold">
- {t('settings.general.startupAndQuitting')}
- </h3>
- {isLinux ? (
- <div className="space-y-1">
- <p className="text-sm font-medium">
- {t('settings.general.launchAtStartup')}
- </p>
- <p className="text-xs text-muted-foreground">
- {t('settings.general.linuxAutostartDesc')}
- </p>
- <a
- href={getLinuxAutostartUrl(
- i18n.resolvedLanguage ?? i18n.language
+ <Form {...form}>
+ <form noValidate onSubmit={onSubmit}>
+ <fieldset
+ inert={disabled}
+ disabled={disabled}
+ className="min-w-0 space-y-4"
+ >
+ {!isWeb && (
+ <>
+ <h3 className="text-sm font-semibold">
+ {t('settings.general.startupAndQuitting')}
+ </h3>
+ {isLinux ? (
+ <div className="space-y-1">
+ <p className="text-sm font-medium">
+ {t('settings.general.launchAtStartup')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings.general.linuxAutostartDesc')}
+ </p>
+ <a
+ href={getLinuxAutostartUrl(
+ i18n.resolvedLanguage ?? i18n.language
+ )}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-0.5 rounded-sm py-0.5 text-xs text-muted-foreground underline-offset-4 outline-none hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {t('settings.general.linuxAutostartGuide')}
+ <ArrowUpRightIcon
+ aria-hidden="true"
+ className="size-3"
+ />
+ </a>
+ </div>
+ ) : (
+ <>
+ {boolRow(
+ 'launchAtStartup',
+ portable
+ ? 'settings.portable.integrationUnavailable'
+ : undefined,
+ !portable
)}
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center gap-0.5 rounded-sm py-0.5 text-xs text-muted-foreground underline-offset-4 outline-none hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring"
- >
- {t('settings.general.linuxAutostartGuide')}
- <ArrowUpRightIcon
- aria-hidden="true"
- className="size-3"
- />
- </a>
- </div>
- ) : (
- <>
- {boolRow(
- 'launchAtStartup',
- portable
- ? 'settings.portable.integrationUnavailable'
- : undefined,
- !portable
- )}
- {boolRow(
- 'showMainWindowAtLogin',
- undefined,
- !portable && form.watch('launchAtStartup')
- )}
- </>
- )}
- <FormField
- control={form.control}
- name="runMode"
- render={({ field }) => (
- <SettingsFormRow>
- <div className="space-y-1">
- <FormLabel>
- {t(
- isMac
- ? 'settings.general.runMode'
- : 'settings.appearance.runModeLaunch'
+ {boolRow(
+ 'showMainWindowAtLogin',
+ undefined,
+ !portable && form.watch('launchAtStartup')
+ )}
+ </>
+ )}
+ <FormField
+ control={form.control}
+ name="runMode"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t(
+ isMac
+ ? 'settings.general.runMode'
+ : 'settings.appearance.runModeLaunch'
+ )}
+ </FormLabel>
+ {isLinux && (
+ <FormDescription className="text-xs">
+ {t('settings.appearance.runModeLinuxDesc')}
+ </FormDescription>
)}
- </FormLabel>
- {isLinux && (
- <FormDescription className="text-xs">
- {t('settings.appearance.runModeLinuxDesc')}
- </FormDescription>
- )}
- </div>
- <FormControl>
- <Select
- items={runModeOptions}
- value={field.value}
- disabled={disabled}
- onValueChange={(v) =>
- v !== null && field.onChange(v)
- }
- >
- <SettingsSelectTrigger className="min-w-48">
- <SelectValue />
- </SettingsSelectTrigger>
- <SelectContent position="popper" align="end">
- <SelectGroup>
- {runModeOptions.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- </SettingsFormRow>
+ </div>
+ <FormControl>
+ <Select
+ items={runModeOptions}
+ value={field.value}
+ disabled={disabled}
+ onValueChange={(v) =>
+ v !== null && field.onChange(v)
+ }
+ >
+ <SettingsSelectTrigger className="min-w-48">
+ <SelectValue />
+ </SettingsSelectTrigger>
+ <SelectContent position="popper" align="end">
+ <SelectGroup>
+ {runModeOptions.map((o) => (
+ <SelectItem
+ key={o.value}
+ value={o.value}
+ >
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ {boolRow(
+ 'lightweightMode',
+ 'settings.general.lightweightModeDesc'
)}
- />
- {boolRow(
- 'lightweightMode',
- 'settings.general.lightweightModeDesc'
- )}
- {boolRow(
- 'warnBeforeQuit',
- 'settings.general.warnBeforeQuitDesc'
- )}
- <Separator className="my-4" />
- <h3 className="text-sm font-semibold">
- {t('settings.general.notifications')}
- </h3>
+ {boolRow(
+ 'warnBeforeQuit',
+ 'settings.general.warnBeforeQuitDesc'
+ )}
+ <Separator className="my-4" />
+ </>
+ )}
+ <h3 className="text-sm font-semibold">
+ {t('settings.general.notifications')}
+ </h3>
+ {!isWeb && (
<p className="text-xs text-muted-foreground">
{t('settings.general.notificationsDesc')}
</p>
- {notificationRow(
- 'notifyOnComplete',
- 'notifyInAppOnComplete',
- 'settings.general.downloadCompleted'
- )}
- {notificationRow(
- 'notifyOnError',
- 'notifyInAppOnError',
- 'settings.general.downloadFailed'
- )}
- <FormField
- control={form.control}
- name="notificationBadgeStyle"
- render={({ field }) => (
- <SettingsFormRow>
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.notificationBadgeStyle')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.notificationBadgeDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Select
- items={badgeOptions}
- value={field.value}
- disabled={disabled}
- onValueChange={(v) =>
- v !== null && field.onChange(v)
- }
- >
- <SettingsSelectTrigger>
- <SelectValue />
- </SettingsSelectTrigger>
- <SelectContent position="popper" align="end">
- <SelectGroup>
- {badgeOptions.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FormControl>
- </SettingsFormRow>
+ )}
+ {isWeb
+ ? boolRow('notifyInAppOnComplete')
+ : notificationRow(
+ 'notifyOnComplete',
+ 'notifyInAppOnComplete',
+ 'settings.general.downloadCompleted'
+ )}
+ {isWeb
+ ? boolRow('notifyInAppOnError')
+ : notificationRow(
+ 'notifyOnError',
+ 'notifyInAppOnError',
+ 'settings.general.downloadFailed'
)}
- />
- </fieldset>
- </form>
- </Form>
- )}
+ <FormField
+ control={form.control}
+ name="notificationBadgeStyle"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.notificationBadgeStyle')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.notificationBadgeDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Select
+ items={badgeOptions}
+ value={field.value}
+ disabled={disabled}
+ onValueChange={(v) =>
+ v !== null && field.onChange(v)
+ }
+ >
+ <SettingsSelectTrigger>
+ <SelectValue />
+ </SettingsSelectTrigger>
+ <SelectContent position="popper" align="end">
+ <SelectGroup>
+ {badgeOptions.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ </fieldset>
+ </form>
+ </Form>
</ScrollAreaContent>
</ScrollAreaViewport>
<ScrollBar />
@@ -432,18 +445,16 @@ export function GeneralDialog({
disabled={busy}
onClick={close}
>
- {t(isWeb ? 'common.close' : 'common.cancel')}
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={onSubmit}
+ disabled={disabled}
+ >
+ {t('common.save')}
</Button>
- {!isWeb && (
- <Button
- type="button"
- size="sm"
- onClick={onSubmit}
- disabled={disabled}
- >
- {t('common.save')}
- </Button>
- )}
</DialogFooter>
</DialogContent>
</Dialog>
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
index 00a0690b..a765df77 100644
--- a/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
@@ -5,7 +5,6 @@ import {
} from '@renderer/components/settings-kit/use-settings-form'
import { i18n } from '@renderer/lib/i18n'
import { transport } from '@renderer/lib/transport'
-import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
@@ -80,7 +79,7 @@ function mockInstallStatus(status: Partial<FfmpegInstallStatus>) {
}
describe('MediaToolsSection', () => {
- it.each(['darwin', 'linux'])(
+ it.each(['darwin', 'linux', 'web'])(
'offers verified one-click install on %s only after consent',
async (platform) => {
Object.defineProperty(transport, 'platform', {
@@ -116,6 +115,13 @@ describe('MediaToolsSection', () => {
'Verified and installed.'
)
)
+ if (platform === 'web') {
+ expect(
+ screen.queryByText(
+ 'Restart Motrix for active plugins to detect the installation.'
+ )
+ ).not.toBeInTheDocument()
+ }
expect(
screen.queryByRole('button', { name: 'Download and verify' })
).not.toBeInTheDocument()
@@ -438,6 +444,10 @@ describe('MediaToolsSection', () => {
})
it('places the FFmpeg download action before refresh without a separate card', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'web',
+ })
vi.mocked(transport.invoke).mockResolvedValue({
active: null,
candidates: [],
@@ -445,15 +455,12 @@ describe('MediaToolsSection', () => {
render(<TestForm />)
const card = await screen.findByTestId('media-detection-card')
- const download = within(card).getByRole('link', {
+ const download = within(card).getByRole('button', {
name: 'Download FFmpeg',
})
const refresh = within(card).getByRole('button', { name: 'Refresh' })
- expect(download).toHaveAttribute(
- 'href',
- EXTERNAL_URLS.github.ffmpegStaticReleases
- )
+ expect(download).not.toHaveAttribute('href')
expect(
download.compareDocumentPosition(refresh) &
Node.DOCUMENT_POSITION_FOLLOWING
@@ -461,6 +468,36 @@ describe('MediaToolsSection', () => {
expect(screen.queryByText('Motrix static FFmpeg')).not.toBeInTheDocument()
})
+ it('restores server installation progress in the browser and refreshes it after reconnect', async () => {
+ const status = mockInstallStatus({})
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'web',
+ })
+ const onConnectionChange = vi.fn()
+ Object.defineProperty(transport, 'onConnectionChange', {
+ configurable: true,
+ value: onConnectionChange,
+ })
+ const view = render(<TestForm />)
+ expect(
+ await screen.findByRole('button', { name: 'Downloading FFmpeg… 50%' })
+ ).toBeDisabled()
+ status.bytesReceived = 80
+ status.percent = 0.8
+ await act(async () =>
+ onConnectionChange.mock.calls[0][0]({ state: 'connected' })
+ )
+ expect(
+ await screen.findByRole('button', { name: 'Downloading FFmpeg… 80%' })
+ ).toBeDisabled()
+ view.unmount()
+ Object.defineProperty(transport, 'onConnectionChange', {
+ configurable: true,
+ value: undefined,
+ })
+ })
+
it('copies the complete Motrix data FFmpeg path when clicked', async () => {
const managedPath =
'/Users/example/Library/Application Support/Motrix/binaries/ffmpeg-verified/releases/hash-darwin-arm64/ffmpeg'
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 50c2e068..dd06245b 100644
--- a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
@@ -94,7 +94,9 @@ export function MediaToolsSection() {
const [installError, setInstallError] = useState<string | null>(null)
const [detectionRefreshFailed, setDetectionRefreshFailed] = useState(false)
const detectionGeneration = useRef(0)
- const canInstall = ['darwin', 'linux', 'win32'].includes(transport.platform)
+ const canInstall = ['darwin', 'linux', 'win32', 'web'].includes(
+ transport.platform
+ )
const visibleResult =
installResult ?? (installStatus?.phase === 'failed' ? 'failed' : null)
const visibleError = installError ?? installStatus?.error
@@ -405,12 +407,15 @@ export function MediaToolsSection() {
)}
</span>
)}
- {visibleResult === 'installed' && (
- <span>
- {' '}
- {t('settings.integration.media.download.restartPluginHint')}
- </span>
- )}
+ {visibleResult === 'installed' &&
+ transport.platform !== 'web' && (
+ <span>
+ {' '}
+ {t(
+ 'settings.integration.media.download.restartPluginHint'
+ )}
+ </span>
+ )}
</p>
)}
{installStatus?.directory && (
diff --git a/src/renderer/routes/settings/cards/use-app-update.ts b/src/renderer/routes/settings/cards/use-app-update.ts
index bac8be67..36f3fe4b 100644
--- a/src/renderer/routes/settings/cards/use-app-update.ts
+++ b/src/renderer/routes/settings/cards/use-app-update.ts
@@ -14,6 +14,8 @@ export function useAppUpdate(enabled = true) {
const [state, setState] = useState<AppUpdateState>(initialState)
const [hasState, setHasState] = useState(false)
const [loading, setLoading] = useState(true)
+ const checkOnly =
+ transport.platform === 'web' || state.updateAuthority === 'administrator'
const systemManaged = useRef(false)
const installRequested = useRef(false)
@@ -96,7 +98,12 @@ export function useAppUpdate(enabled = true) {
const showControls = enabled && hasState && !isSystemManaged(state)
const invoke = useCallback(
async (command: (typeof Commands)[keyof typeof Commands]) => {
- if (!showControls || systemManaged.current) return
+ if (
+ !showControls ||
+ systemManaged.current ||
+ (checkOnly && command !== Commands.CheckForUpdates)
+ )
+ return
try {
await transport.invoke(command)
} catch (error) {
@@ -115,17 +122,19 @@ export function useAppUpdate(enabled = true) {
)
}
},
- [showControls]
+ [showControls, checkOnly]
)
return {
state,
loading,
showControls,
+ checkOnly,
check: () => invoke(Commands.CheckForUpdates),
download: () => invoke(Commands.DownloadUpdate),
install: () => {
- if (installRequested.current || !showControls) return Promise.resolve()
+ if (checkOnly || installRequested.current || !showControls)
+ return Promise.resolve()
installRequested.current = true
setState((current) => ({
...current,
diff --git a/src/renderer/routes/settings/settings-page.tsx b/src/renderer/routes/settings/settings-page.tsx
index 2137b29e..8581d4db 100644
--- a/src/renderer/routes/settings/settings-page.tsx
+++ b/src/renderer/routes/settings/settings-page.tsx
@@ -1,4 +1,5 @@
import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'
+import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import { useTranslation } from 'react-i18next'
import { useLocation, useNavigate, useParams } from 'react-router'
@@ -31,7 +32,11 @@ export function SettingsPage() {
key={card.id}
icon={card.icon}
labelKey={card.labelKey}
- descKey={card.descKey}
+ descKey={
+ card.id === 'general' && transport.platform === 'web'
+ ? 'settings.general.inAppNotificationsDesc'
+ : card.descKey
+ }
onClick={() => navigate(`/settings/${card.id}`)}
className={cn(
'border-border',
diff --git a/src/server/app-update-service.test.ts b/src/server/app-update-service.test.ts
new file mode 100644
index 00000000..2de0382d
--- /dev/null
+++ b/src/server/app-update-service.test.ts
@@ -0,0 +1,156 @@
+import { EventBus } from '@core/events/event-bus'
+import { Events } from '@shared/protocol/events'
+import type { AppUpdateState } from '@shared/types/app-update'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ fetchServerUpdateMetadata,
+ ServerUpdateService,
+} from './app-update-service'
+
+afterEach(() => vi.unstubAllGlobals())
+
+function createService(
+ version = '2.2.0',
+ channel: 'stable' | 'beta' = 'stable'
+) {
+ const eventBus = new EventBus()
+ const states: AppUpdateState[] = []
+ eventBus.on(Events.UpdateStateChanged, (state) =>
+ states.push(state as AppUpdateState)
+ )
+ const loadMetadata = vi.fn<typeof fetchServerUpdateMetadata>(async () => ({
+ version: '2.3.0',
+ }))
+ const service = new ServerUpdateService({
+ eventBus,
+ currentVersion: version,
+ channel,
+ loadMetadata,
+ })
+ return { service, states, loadMetadata }
+}
+
+describe('Server version checking', () => {
+ it('publishes checking and available states without downloading an installer', async () => {
+ const { service, states, loadMetadata } = createService()
+ await service.check()
+ expect(states.map((state) => state.phase)).toEqual([
+ 'checking',
+ 'available',
+ ])
+ expect(service.getState()).toMatchObject({
+ currentVersion: '2.2.0',
+ availableVersion: '2.3.0',
+ updateAuthority: 'administrator',
+ })
+ expect(loadMetadata).toHaveBeenCalledWith('stable', expect.any(AbortSignal))
+ })
+
+ it.each([
+ ['2.2.0', '2.2.0', 'stable', 'up-to-date'],
+ ['2.3.0', '2.2.0', 'stable', 'up-to-date'],
+ ['2.3.0-beta.10', '2.3.0-beta.9', 'beta', 'up-to-date'],
+ ['2.3.0-beta.9', '2.3.0-beta.10', 'beta', 'available'],
+ ['2.3.0-beta.9', '2.3.0', 'beta', 'available'],
+ ['2.3.0-beta.9', '2.2.0', 'stable', 'up-to-date'],
+ ['2.2.0+local', '2.2.0+release', 'stable', 'up-to-date'],
+ ] as const)(
+ 'compares %s with %s on %s without downgrading',
+ async (current, next, channel, phase) => {
+ const { service, loadMetadata } = createService(current, channel)
+ loadMetadata.mockResolvedValue({ version: next })
+ await service.check()
+ expect(service.getState().phase).toBe(phase)
+ }
+ )
+
+ it.each(['2.3.0-beta.1', '2.3.0-rc.1', '02.3.0', 'garbage'])(
+ 'rejects an invalid stable feed version %s',
+ async (version) => {
+ const { service, loadMetadata } = createService()
+ loadMetadata.mockResolvedValue({ version })
+ await expect(service.check()).rejects.toThrow()
+ expect(service.getState()).toMatchObject({
+ phase: 'error',
+ updateAuthority: 'administrator',
+ })
+ }
+ )
+
+ it('coalesces concurrent checks and retries after a failure', async () => {
+ const { service, loadMetadata } = createService()
+ loadMetadata.mockRejectedValueOnce(new Error('remote error detail'))
+ const first = service.check()
+ expect(service.check()).toBe(first)
+ await expect(first).rejects.toThrow(
+ 'settings.about.update.errorDescription'
+ )
+ expect(loadMetadata).toHaveBeenCalledOnce()
+ expect(JSON.stringify(service.getState())).not.toContain(
+ 'remote error detail'
+ )
+ await service.check()
+ expect(service.getState().phase).toBe('available')
+ })
+
+ it('discards a response from the old channel and aborts that request', async () => {
+ const { service, loadMetadata } = createService()
+ let finish!: (value: { version: string }) => void
+ loadMetadata.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve
+ })
+ )
+ const old = service.check()
+ await vi.waitFor(() => expect(loadMetadata).toHaveBeenCalledOnce())
+ const signal = vi.mocked(loadMetadata).mock.calls[0][1] as AbortSignal
+ service.setChannel('beta')
+ expect(signal.aborted).toBe(true)
+ loadMetadata.mockResolvedValue({ version: '2.4.0-beta.1' })
+ await service.check()
+ finish({ version: '2.3.0' })
+ await old
+ expect(service.getState().availableVersion).toBe('2.4.0-beta.1')
+ })
+})
+
+describe('Server published update metadata', () => {
+ it.each([
+ ['stable', 'latest'],
+ ['beta', 'beta'],
+ ] as const)(
+ 'reads the desktop %s feed, without following package URLs',
+ async (channel, name) => {
+ const fetcher = vi.fn(
+ async () =>
+ new Response(
+ 'version: 2.3.0\nreleaseName: Motrix 2.3.0\nfiles:\n - url: https://unused.invalid/installer.exe\n'
+ )
+ )
+ vi.stubGlobal('fetch', fetcher)
+ const signal = new AbortController().signal
+ await expect(
+ fetchServerUpdateMetadata(channel, signal)
+ ).resolves.toMatchObject({ version: '2.3.0' })
+ expect(fetcher).toHaveBeenCalledExactlyOnceWith(
+ `https://dl.motrix.app/releases/${name}.yml`,
+ expect.objectContaining({ signal, redirect: 'error' })
+ )
+ }
+ )
+
+ it('rejects HTTP failures and oversized responses', async () => {
+ const fetcher = vi
+ .fn()
+ .mockResolvedValueOnce(new Response('unavailable', { status: 503 }))
+ .mockResolvedValueOnce(new Response('x'.repeat(256 * 1024 + 1)))
+ vi.stubGlobal('fetch', fetcher)
+ await expect(
+ fetchServerUpdateMetadata('stable', new AbortController().signal)
+ ).rejects.toThrow('503')
+ await expect(
+ fetchServerUpdateMetadata('stable', new AbortController().signal)
+ ).rejects.toThrow('size limit')
+ })
+})
diff --git a/src/server/app-update-service.ts b/src/server/app-update-service.ts
new file mode 100644
index 00000000..fdac35c4
--- /dev/null
+++ b/src/server/app-update-service.ts
@@ -0,0 +1,155 @@
+import type { EventBus } from '@core/events/event-bus'
+import { isVersionAllowedForChannel } from '@shared/app-update-channel'
+import { AppError, ErrorCode } from '@shared/errors'
+import { EXTERNAL_URLS } from '@shared/external-urls'
+import { Events } from '@shared/protocol/events'
+import { compareSemver } from '@shared/semver'
+import type { AppUpdateState } from '@shared/types/app-update'
+import type { AppUpdateChannel } from '@shared/types/settings'
+import { JSON_SCHEMA, load } from 'js-yaml'
+import { z } from 'zod'
+
+const MAX_METADATA_BYTES = 256 * 1024
+const metadataSchema = z.object({
+ version: z.string().max(128),
+ releaseName: z.string().max(256).optional(),
+})
+
+export async function fetchServerUpdateMetadata(
+ channel: AppUpdateChannel,
+ signal: AbortSignal
+): Promise<unknown> {
+ const filename = channel === 'stable' ? 'latest.yml' : 'beta.yml'
+ const response = await fetch(
+ `${EXTERNAL_URLS.motrix.updateFeed}${filename}`,
+ {
+ signal,
+ redirect: 'error',
+ headers: { 'Cache-Control': 'no-cache' },
+ }
+ )
+ if (!response.ok || !response.body) {
+ await response.body?.cancel()
+ throw new Error(`Update feed unavailable (${response.status})`)
+ }
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let size = 0
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ size += value.byteLength
+ if (size > MAX_METADATA_BYTES)
+ throw new Error('Update feed exceeds size limit')
+ chunks.push(value)
+ }
+ return load(Buffer.concat(chunks).toString('utf8'), { schema: JSON_SCHEMA })
+ } finally {
+ await reader.cancel().catch(() => {})
+ reader.releaseLock()
+ }
+}
+
+export interface ServerUpdateServiceOptions {
+ eventBus: EventBus
+ currentVersion: string
+ channel: AppUpdateChannel
+ loadMetadata?: typeof fetchServerUpdateMetadata
+}
+
+/** Checks published versions only; installation belongs to the deployment administrator. */
+export class ServerUpdateService {
+ private state: AppUpdateState
+ private channel: AppUpdateChannel
+ private generation = 0
+ private pending: Promise<void> | null = null
+ private controller: AbortController | null = null
+
+ constructor(private readonly options: ServerUpdateServiceOptions) {
+ this.channel = options.channel
+ this.state = this.snapshot('idle')
+ }
+
+ getState(): AppUpdateState {
+ return {
+ ...this.state,
+ ...(this.state.error ? { error: { ...this.state.error } } : {}),
+ }
+ }
+
+ setChannel(channel: AppUpdateChannel): void {
+ if (channel === this.channel) return
+ this.channel = channel
+ this.generation++
+ this.controller?.abort()
+ this.pending = null
+ this.transition(this.snapshot('idle'))
+ }
+
+ check(): Promise<void> {
+ if (this.pending) return this.pending
+ const generation = ++this.generation
+ const channel = this.channel
+ const controller = new AbortController()
+ this.controller = controller
+ const signal = AbortSignal.any([
+ controller.signal,
+ AbortSignal.timeout(15_000),
+ ])
+ this.transition(this.snapshot('checking'))
+ this.pending = Promise.resolve().then(async () => {
+ try {
+ const metadata = metadataSchema.parse(
+ await (this.options.loadMetadata ?? fetchServerUpdateMetadata)(
+ channel,
+ signal
+ )
+ )
+ if (generation !== this.generation) return
+ if (
+ !isVersionAllowedForChannel(metadata.version, channel) ||
+ !isVersionAllowedForChannel(this.options.currentVersion, 'beta')
+ ) {
+ throw new Error('Invalid application update version')
+ }
+ const available =
+ compareSemver(metadata.version, this.options.currentVersion) > 0
+ this.transition({
+ ...this.snapshot(available ? 'available' : 'up-to-date'),
+ checkedAt: new Date().toISOString(),
+ ...(available
+ ? {
+ availableVersion: metadata.version,
+ releaseName: metadata.releaseName,
+ }
+ : {}),
+ })
+ } catch {
+ if (generation !== this.generation) return
+ const message = 'settings.about.update.errorDescription'
+ this.transition({ ...this.snapshot('error'), error: { message } })
+ throw new AppError(ErrorCode.AppUpdateCheckFailed, message)
+ } finally {
+ if (generation === this.generation) {
+ this.pending = null
+ this.controller = null
+ }
+ }
+ })
+ return this.pending
+ }
+
+ private snapshot(phase: AppUpdateState['phase']): AppUpdateState {
+ return {
+ phase,
+ currentVersion: this.options.currentVersion,
+ updateAuthority: 'administrator',
+ }
+ }
+
+ private transition(state: AppUpdateState): void {
+ this.state = state
+ this.options.eventBus.emit(Events.UpdateStateChanged, this.getState())
+ }
+}
diff --git a/src/server/http/app.ts b/src/server/http/app.ts
index 4351078c..848b1eb5 100644
--- a/src/server/http/app.ts
+++ b/src/server/http/app.ts
@@ -117,6 +117,7 @@ export interface AppOptions {
bridgeQueryHandlers?: Record<string, Handler>
remoteExtensionConfig?: RemoteExtensionConfig
eventBus?: EventBus
+ getHiddenNotificationKinds?: () => readonly string[]
pluginLogSource?: Pick<CapabilityHost, 'subscribeLog'>
rendererDir?: string
healthCheck?: () => { ok: boolean } | Promise<{ ok: boolean }>
@@ -253,7 +254,10 @@ export async function createApp(
)
if (opts.eventBus) {
- const broadcaster = bindEventBroadcaster(opts.eventBus)
+ const broadcaster = bindEventBroadcaster(
+ opts.eventBus,
+ opts.getHiddenNotificationKinds
+ )
const unsubscribePluginLogs = opts.pluginLogSource?.subscribeLog(
(pluginId, entry) => {
broadcaster.broadcast(`${Events.PluginLog}:${pluginId}`, [entry])
diff --git a/src/server/http/events.test.ts b/src/server/http/events.test.ts
index 6fec6fbf..b57236cb 100644
--- a/src/server/http/events.test.ts
+++ b/src/server/http/events.test.ts
@@ -1,9 +1,47 @@
import { EventEmitter } from 'node:events'
import { Events } from '@shared/protocol/events'
+import {
+ getHiddenNotificationKinds,
+ NotificationKinds,
+} from '@shared/types/notification'
import { describe, expect, it } from 'vitest'
import { bindEventBroadcaster } from './events'
describe('bindEventBroadcaster', () => {
+ it('applies live notification preferences while preserving application alerts and refresh events', () => {
+ const bus = new EventEmitter()
+ const preferences = {
+ notifyInAppOnComplete: false,
+ notifyInAppOnError: false,
+ }
+ const sent: unknown[] = []
+ const broadcaster = bindEventBroadcaster(bus as never, () =>
+ getHiddenNotificationKinds(preferences)
+ )
+ broadcaster.register({ send: (message) => sent.push(JSON.parse(message)) })
+ for (const kind of [
+ NotificationKinds.TaskComplete,
+ NotificationKinds.TaskError,
+ NotificationKinds.EngineFailure,
+ ]) {
+ bus.emit(Events.NotificationAdded, { kind })
+ }
+ bus.emit(Events.NotificationsChanged)
+ expect(sent).toEqual([
+ {
+ channel: Events.NotificationAdded,
+ args: [{ kind: NotificationKinds.EngineFailure }],
+ },
+ { channel: Events.NotificationsChanged, args: [] },
+ ])
+ preferences.notifyInAppOnComplete = true
+ bus.emit(Events.NotificationAdded, { kind: NotificationKinds.TaskComplete })
+ expect(sent.at(-1)).toEqual({
+ channel: Events.NotificationAdded,
+ args: [{ kind: NotificationKinds.TaskComplete }],
+ })
+ })
+
it('forwards eventBus emissions to registered sockets', () => {
const bus = new EventEmitter()
const sent: unknown[] = []
diff --git a/src/server/http/events.ts b/src/server/http/events.ts
index e8edfc34..3894709b 100644
--- a/src/server/http/events.ts
+++ b/src/server/http/events.ts
@@ -1,6 +1,8 @@
import type { EventBus } from '@core/events/event-bus'
import { subscribeForwardableEvents } from '@core/events/forward-events'
import { getLogger } from '@core/logger'
+import { Events } from '@shared/protocol/events'
+import type { AppNotification } from '@shared/types/notification'
const log = getLogger('web-events')
@@ -9,7 +11,10 @@ interface SocketLike {
terminate?(): void
}
-export function bindEventBroadcaster(bus: EventBus) {
+export function bindEventBroadcaster(
+ bus: EventBus,
+ getHiddenKinds: () => readonly string[] = () => []
+) {
const sockets = new Map<
SocketLike,
{
@@ -24,6 +29,13 @@ export function bindEventBroadcaster(bus: EventBus) {
function broadcast(channel: string, args: unknown[]): void {
if (sockets.size === 0) return
+ if (
+ channel === Events.NotificationAdded &&
+ getHiddenKinds().includes(
+ (args[0] as AppNotification | undefined)?.kind ?? ''
+ )
+ )
+ return
const frame = JSON.stringify({ channel, args })
for (const [s, { eligible, accepts }] of sockets) {
if (!eligible()) {
diff --git a/src/server/index.ts b/src/server/index.ts
index 2d3f30b5..acd64588 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -134,11 +134,13 @@ import { Events } from '@shared/protocol/events'
import type { TaskCreateCommandResult } from '@shared/schemas/add-task'
import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'
import { EngineState } from '@shared/types/engine'
+import { getHiddenNotificationKinds } from '@shared/types/notification'
import type { AppSettings } from '@shared/types/settings'
import type { DownloadTask } from '@shared/types/task'
import { TaskType } from '@shared/types/task'
import pino from 'pino'
import packageJson from '../../package.json' with { type: 'json' }
+import { ServerUpdateService } from './app-update-service'
import {
bootstrapBridgeForServer,
type ServerBridgeRuntime,
@@ -329,6 +331,13 @@ async function main() {
defaultSaveDir: configuredDefaultSaveDir,
onChange: (old, updated) => {
eventBus.emit(Events.SettingsChanged, { old, updated })
+ if (
+ old.app.notifyInAppOnComplete !== updated.app.notifyInAppOnComplete ||
+ old.app.notifyInAppOnError !== updated.app.notifyInAppOnError ||
+ old.app.notificationBadgeStyle !== updated.app.notificationBadgeStyle
+ ) {
+ eventBus.emit(Events.NotificationsChanged)
+ }
if (old.app.sidebarColor !== updated.app.sidebarColor) {
eventBus.emit(Events.SidebarColorChanged, {
sidebarColor: updated.app.sidebarColor,
@@ -1143,6 +1152,7 @@ async function main() {
store: db,
emit: eventBus.emit.bind(eventBus),
log,
+ getHiddenKinds: () => getHiddenNotificationKinds(settingsManager.getApp()),
})
// Auto DNS fallback: constructed here so the command context can reset
@@ -1192,7 +1202,15 @@ async function main() {
// ─── HTTP App ─────────────────────────────────────────────────
const serverDirectoryService = new ServerDirectoryService(downloadPathPolicy)
+ const updateService = new ServerUpdateService({
+ eventBus,
+ currentVersion: appVersion,
+ channel: settingsManager.getApp().updateChannel,
+ })
const commandHandlers = buildServerCommandHandlers({
+ updateService,
+ userDataDir: platform.userDataDir,
+ trackAsyncWork: (operation) => shellAsyncWork.run(operation),
btStorageRuntime: durableFinalizeRuntime,
persistBtStorage: (task, source, target) =>
sessionManager.persistBtStorage(task, source, target),
@@ -1284,6 +1302,7 @@ async function main() {
])
}
const queryHandlers = buildServerQueryHandlers({
+ updateService,
getResolvedLanguage: () => hostLanguage,
mediaMetaStore,
serverDirectoryService,
@@ -1332,6 +1351,8 @@ async function main() {
const remoteExtensionConfig = parseRemoteExtensionConfig(process.env)
const app = await createApp({
+ getHiddenNotificationKinds: () =>
+ getHiddenNotificationKinds(settingsManager.getApp()),
remoteExtensionConfig,
torrentBodyLimitBytes,
commandHandlers,
@@ -1479,6 +1500,9 @@ async function main() {
log.warn({ err }, 'initial proxy apply failed')
}
if (!shellAsyncWork.isAccepting()) return
+ if (settingsManager.getApp().checkForUpdatesOnLaunch) {
+ runShellAsyncWork('automatic update check', () => updateService.check())
+ }
runShellAsyncWork('tracker manager init', async () => {
try {
await trackerManager.init()
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index 475d2946..8978e622 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -39,12 +39,25 @@ import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'
import { makeDownloadTask } from '@test-utils/task'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createServerDownloadPathPolicy } from '../download-path-policy'
+import { makeServerFfmpegDetect } from '../plugin/ffmpeg-detect-server'
import type { ServerPluginInstallService } from '../plugin/install-service'
+import { installServerFfmpeg } from '../plugin/verified-ffmpeg-server'
import { ServerDirectoryService } from '../server-directory-service'
import type { ServerCommandContext } from './commands'
import { buildServerCommandHandlers } from './commands'
import { buildServerQueryHandlers } from './queries'
+vi.mock('../plugin/verified-ffmpeg-server', () => ({
+ installServerFfmpeg: vi.fn(),
+ probeServerFfmpeg: vi.fn(),
+}))
+vi.mock('../plugin/ffmpeg-detect-server', () => ({
+ makeServerFfmpegDetect: vi.fn(() => async () => ({
+ active: null,
+ candidates: [],
+ })),
+}))
+
const PROXY_OFF = {
enabled: false,
protocol: 'http' as const,
@@ -66,6 +79,10 @@ function makeFakeCtx() {
const setEnabled = vi.fn()
const refreshState = vi.fn()
return {
+ updateService: {
+ check: vi.fn().mockResolvedValue(undefined),
+ setChannel: vi.fn(),
+ },
supervisor: {
stop: vi.fn().mockResolvedValue(undefined),
start: vi.fn().mockResolvedValue(undefined),
@@ -214,7 +231,61 @@ function makeFakeCtx() {
}
}
-describe('desktop-only FFmpeg installation boundary', () => {
+describe('server application update checks', () => {
+ it('applies the persisted channel to subsequent version checks', async () => {
+ const ctx = makeFakeCtx()
+ const base = makeSettings(PROXY_OFF)
+ let settings = { ...base, app: { ...base.app, updateChannel: 'stable' } }
+ vi.mocked(ctx.settingsManager.get).mockImplementation(
+ () => settings as never
+ )
+ vi.mocked(ctx.settingsManager.getApp).mockImplementation(
+ () => settings.app as never
+ )
+ vi.mocked(ctx.settingsManager.update).mockImplementation(async () => {
+ settings = {
+ ...settings,
+ app: { ...settings.app, updateChannel: 'beta' },
+ }
+ return {
+ saved: true,
+ requiresRestart: false,
+ changedRestartKeys: [],
+ requiresAppRestart: false,
+ changedAppRestartKeys: [],
+ }
+ })
+ const handlers = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )
+ await handlers[Commands.UpdateSettings]?.({
+ app: { updateChannel: 'beta' },
+ })
+ expect(ctx.updateService.setChannel).toHaveBeenCalledWith('beta')
+ })
+
+ it('checks through the server service and never exposes download or installation', async () => {
+ const ctx = makeFakeCtx()
+ const handlers = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )
+ await expect(handlers[Commands.CheckForUpdates]?.()).resolves.toEqual({
+ ok: true,
+ })
+ expect(ctx.updateService.check).toHaveBeenCalledOnce()
+ for (const command of [Commands.DownloadUpdate, Commands.InstallUpdate]) {
+ await expect(handlers[command]?.()).rejects.toMatchObject({
+ code: 'APP_UPDATE_MANAGED',
+ })
+ }
+ await expect(
+ handlers[Commands.CheckForUpdates]?.({ url: 'https://invalid.test' })
+ ).rejects.toThrow()
+ expect(ctx.updateService.check).toHaveBeenCalledOnce()
+ })
+})
+
+describe('server FFmpeg installation', () => {
it('does not open a server settings directory through web commands', async () => {
const handlers = buildServerCommandHandlers(
makeFakeCtx() as ServerCommandContext
@@ -227,18 +298,81 @@ describe('desktop-only FFmpeg installation boundary', () => {
).rejects.toThrow()
})
- it('does not install server executables through web commands', async () => {
+ it('rejects caller-supplied URLs or paths before starting an install', async () => {
+ vi.mocked(installServerFfmpeg).mockClear()
const handlers = buildServerCommandHandlers(
makeFakeCtx() as ServerCommandContext
)
- await expect(handlers[Commands.InstallFfmpeg]?.()).resolves.toEqual({
- ok: false,
- error: 'unsupported',
- })
await expect(
handlers[Commands.InstallFfmpeg]?.({ url: 'https://evil.test' })
).rejects.toThrow()
+ expect(installServerFfmpeg).not.toHaveBeenCalled()
+ })
+
+ it('installs on the server, broadcasts progress, and refreshes media capabilities', async () => {
+ const ctx = makeFakeCtx()
+ const refreshDetection = vi
+ .fn()
+ .mockResolvedValue({ active: null, candidates: [] })
+ const trackAsyncWork = vi.fn(async (operation: () => Promise<unknown>) =>
+ operation()
+ )
+ const result = { ok: true as const, releaseVersion: '9.0.2-motrix.2' }
+ const status = {
+ phase: 'downloading' as const,
+ bytesReceived: 50,
+ bytesTotal: 100,
+ percent: 0.5,
+ releaseVersion: null,
+ directory: null,
+ error: null,
+ }
+ vi.mocked(installServerFfmpeg).mockImplementationOnce(
+ async (_directory, onStatus) => {
+ onStatus?.(status)
+ return result
+ }
+ )
+ const handlers = buildServerCommandHandlers({
+ ...ctx,
+ trackAsyncWork,
+ capabilityHost: { ffmpeg: { refreshDetection } },
+ } as unknown as ServerCommandContext)
+ await expect(handlers[Commands.InstallFfmpeg]?.()).resolves.toEqual(result)
+ expect(trackAsyncWork).toHaveBeenCalledOnce()
+ expect(installServerFfmpeg).toHaveBeenLastCalledWith(
+ ctx.userDataDir,
+ expect.any(Function)
+ )
+ expect(ctx.eventBus.emit).toHaveBeenCalledWith(
+ Events.FfmpegInstallStatusChanged,
+ status
+ )
+ expect(refreshDetection).toHaveBeenCalledWith(
+ vi.mocked(makeServerFfmpegDetect).mock.results.at(-1)?.value
+ )
})
+
+ it.each([false, true])(
+ 'preserves install results when detection fails (installed: %s)',
+ async (installed) => {
+ const refreshDetection = vi
+ .fn()
+ .mockRejectedValue(new Error('probe unavailable'))
+ const result = installed
+ ? { ok: true as const, releaseVersion: '9.0.2-motrix.2' }
+ : { ok: false as const, error: 'verification' as const }
+ vi.mocked(installServerFfmpeg).mockResolvedValueOnce(result)
+ const handlers = buildServerCommandHandlers({
+ ...makeFakeCtx(),
+ capabilityHost: { ffmpeg: { refreshDetection } },
+ } as unknown as ServerCommandContext)
+ await expect(handlers[Commands.InstallFfmpeg]?.()).resolves.toEqual(
+ result
+ )
+ expect(refreshDetection).toHaveBeenCalledTimes(installed ? 1 : 0)
+ }
+ )
})
function makeSettings(
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 5135aac2..d24037f0 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -110,13 +110,19 @@ import { canRetryMagnetMetadata } from '@shared/types/task-actions'
import type { TaskActivityRecorder } from '@shared/types/task-activity'
import type { TaskOccurrence } from '@shared/types/task-occurrence'
import { z } from 'zod'
+import type { ServerUpdateService } from '../app-update-service'
import type { ServerDownloadPathPolicy } from '../download-path-policy'
+import { makeServerFfmpegDetect } from '../plugin/ffmpeg-detect-server'
import type { ServerPluginInstallService } from '../plugin/install-service'
+import { installServerFfmpeg } from '../plugin/verified-ffmpeg-server'
import type { createServerProxyApplier } from '../proxy/wiring'
import type { ServerDirectoryService } from '../server-directory-service'
import { unsupportedLegacyImportCommands } from './legacy-import'
export interface ServerCommandContext {
+ updateService: Pick<ServerUpdateService, 'check' | 'setChannel'>
+ userDataDir: string
+ trackAsyncWork?: <T>(operation: () => Promise<T>) => Promise<T>
btStorageRuntime?: Pick<
DurableFinalizeRuntime,
'commit' | 'withArtifactLease' | 'hasPendingFinalization'
@@ -460,9 +466,39 @@ export function buildServerCommandHandlers(
z.undefined().parse(payload)
return false
},
+ [Commands.CheckForUpdates]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ const operation = () => ctx.updateService.check()
+ await (ctx.trackAsyncWork ? ctx.trackAsyncWork(operation) : operation())
+ return { ok: true }
+ },
+ [Commands.DownloadUpdate]: async () => {
+ throw new AppError(
+ ErrorCode.AppUpdateManaged,
+ 'settings.about.webVersionNote'
+ )
+ },
+ [Commands.InstallUpdate]: async () => {
+ throw new AppError(
+ ErrorCode.AppUpdateManaged,
+ 'settings.about.webVersionNote'
+ )
+ },
[Commands.InstallFfmpeg]: async (payload: unknown) => {
z.undefined().parse(payload)
- return { ok: false, error: 'unsupported' }
+ const operation = async () => {
+ const result = await installServerFfmpeg(ctx.userDataDir, (status) =>
+ eventBus.emit(Events.FfmpegInstallStatusChanged, status)
+ )
+ if (result.ok) {
+ // Detection failure must not overwrite an already committed install.
+ await capabilityHost.ffmpeg
+ .refreshDetection(makeServerFfmpegDetect(ctx))
+ .catch(() => {})
+ }
+ return result
+ }
+ return ctx.trackAsyncWork ? ctx.trackAsyncWork(operation) : operation()
},
[Commands.CreateServerDirectory]: async (request: unknown) =>
ctx.serverDirectoryService.create(request),
@@ -911,6 +947,10 @@ export function buildServerCommandHandlers(
await supervisor.applyDefaultSaveDir(newFull.app.defaultSaveDir)
}
+ if (oldFull.app.updateChannel !== newFull.app.updateChannel) {
+ ctx.updateService.setChannel(settingsManager.getApp().updateChannel)
+ }
+
if (
oldFull.app.browserBridgeEnabled !==
newFull.app.browserBridgeEnabled
diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.ts
index dc11c163..24b8ceee 100644
--- a/src/server/ipc/queries.test.ts
+++ b/src/server/ipc/queries.test.ts
@@ -2,6 +2,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { TaskActivityService, type TaskActivityStore } from '@core/activity'
+import { getFfmpegInstallStatus } from '@core/ffmpeg/verified-install'
import { createTaskInspectorActivityQuery } from '@core/inspector-activity'
import { NotificationCenter } from '@core/notifications/notification-center'
import { FfmpegCapabilityHost } from '@core/plugin/capabilities/ffmpeg'
@@ -21,6 +22,10 @@ vi.mock('../plugin/ffmpeg-detect-server', () => ({
})),
}))
+vi.mock('@core/ffmpeg/verified-install', () => ({
+ getFfmpegInstallStatus: vi.fn(),
+}))
+
const NOW = 1_800_000_000_000
const WINDOW_MS = 24 * 60 * 60 * 1000
const TRANSFER_PARAMS = {
@@ -165,6 +170,19 @@ function makeCtx(over: Record<string, unknown> = {}) {
}
describe('buildServerQueryHandlers — allowed save directories', () => {
+ it('returns the Server update snapshot', async () => {
+ const state = {
+ phase: 'available',
+ currentVersion: '2.2.0',
+ availableVersion: '2.3.0',
+ updateAuthority: 'administrator',
+ }
+ const updateService = { getState: vi.fn(() => state) }
+ const handlers = buildServerQueryHandlers(
+ makeCtx({ updateService }) as unknown as ServerQueryContext
+ )
+ await expect(handlers[Queries.GetUpdateState]?.()).resolves.toEqual(state)
+ })
it('returns the server settings path for custom profiles', async () => {
const handlers = buildServerQueryHandlers(
makeCtx({
@@ -793,6 +811,30 @@ describe('plugin diagnostic state query', () => {
})
describe('server FFmpeg detection refresh', () => {
+ it('returns the live installation snapshot and rejects unexpected payloads', async () => {
+ const status = {
+ phase: 'downloading',
+ bytesReceived: 50,
+ bytesTotal: 100,
+ percent: 0.5,
+ releaseVersion: null,
+ directory: null,
+ error: null,
+ }
+ vi.mocked(getFfmpegInstallStatus).mockReturnValue(
+ status as ReturnType<typeof getFfmpegInstallStatus>
+ )
+ const handlers = buildServerQueryHandlers(
+ makeCtx({ userDataDir: '/data' }) as unknown as ServerQueryContext
+ )
+ await expect(handlers[Queries.GetFfmpegInstallStatus]?.()).resolves.toEqual(
+ status
+ )
+ expect(getFfmpegInstallStatus).toHaveBeenCalledWith('/data')
+ await expect(
+ handlers[Queries.GetFfmpegInstallStatus]?.({ path: '/other' })
+ ).rejects.toThrow()
+ })
it('updates the operation capability after explicit detection and when FFmpeg disappears', async () => {
const ffmpeg = new FfmpegCapabilityHost({ detect: { available: false } })
const detected = {
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index 7fdde3a1..47b09b60 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -4,6 +4,7 @@ import type { EngineAdapter } from '@core/engine/engine-adapter'
import type { EngineSupervisor } from '@core/engine/engine-supervisor'
import { createGetEngineTaskOptionsHandler } from '@core/engine/get-engine-task-options'
import { getTuningRecommendation } from '@core/engine/get-tuning-recommendation'
+import { getFfmpegInstallStatus } from '@core/ffmpeg/verified-install'
import { pathExists } from '@core/fs/path-exists'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { createGetGeoIPStatusHandler } from '@core/geoip/get-geo-ip-status'
@@ -47,7 +48,6 @@ import { checkTaskFileExistsPayloadSchema } from '@shared/schemas/check-task-fil
import { PluginLogRequestSchema } from '@shared/schemas/plugin-logs'
import { ListServerDirectoryLocationsRequestSchema } from '@shared/schemas/server-directory'
import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'
-import type { AppUpdateState } from '@shared/types/app-update'
import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
import {
CliInstallCapability,
@@ -58,6 +58,8 @@ import {
} from '@shared/types/cli-tool'
import type { GetTransferStatsParams } from '@shared/types/stats'
import type { GetTaskActivityParams } from '@shared/types/task-activity'
+import { z } from 'zod'
+import type { ServerUpdateService } from '../app-update-service'
import type { ServerDownloadPathPolicy } from '../download-path-policy'
import { makeServerFfmpegDetect } from '../plugin/ffmpeg-detect-server'
import type { ServerDirectoryService } from '../server-directory-service'
@@ -107,6 +109,7 @@ const UNSUPPORTED_APPIMAGE_INTEGRATION: AppImageIntegrationView = {
}
export interface ServerQueryContext {
+ updateService: Pick<ServerUpdateService, 'getState'>
getResolvedLanguage: () => SupportedLocale
taskManager: TaskManager
statsAggregator: StatsAggregator
@@ -178,15 +181,10 @@ export function buildServerQueryHandlers(
return {
...unsupportedLegacyImportQueries(),
- [Queries.GetFfmpegInstallStatus]: async () => ({
- phase: 'idle',
- bytesReceived: 0,
- bytesTotal: 0,
- percent: null,
- releaseVersion: null,
- directory: null,
- error: 'unsupported',
- }),
+ [Queries.GetFfmpegInstallStatus]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ return getFfmpegInstallStatus(userDataDir)
+ },
[Queries.ListServerDirectoryLocations]: async (request: unknown) => {
if (
!ListServerDirectoryLocationsRequestSchema.safeParse(request).success
@@ -298,10 +296,10 @@ export function buildServerQueryHandlers(
[Queries.GetSystemProxy]: async () => parseProxyEnvironment(environment),
- [Queries.GetUpdateState]: async (): Promise<AppUpdateState> => ({
- phase: 'unsupported',
- currentVersion: hostVersion,
- }),
+ [Queries.GetUpdateState]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ return ctx.updateService.getState()
+ },
[Queries.GetAppImageIntegrationStatus]: async () =>
UNSUPPORTED_APPIMAGE_INTEGRATION,
diff --git a/src/server/plugin/capability-host.ts b/src/server/plugin/capability-host.ts
index ca1affb5..7ce000e4 100644
--- a/src/server/plugin/capability-host.ts
+++ b/src/server/plugin/capability-host.ts
@@ -1,4 +1,5 @@
import path from 'node:path'
+import { assertManagedFfmpegTrusted } from '@core/ffmpeg/verified-install'
import { AppCapabilityHost } from '@core/plugin/capabilities/app'
import { CommandsCapabilityHost } from '@core/plugin/capabilities/commands'
import { ConfigCapabilityHost } from '@core/plugin/capabilities/config'
@@ -114,7 +115,12 @@ export async function createServerCapabilityHost(
})
const ffmpegResult = await detectFfmpeg()
const ffmpegDetection = projectActiveToLegacy(ffmpegResult)
- const ffmpeg = new FfmpegCapabilityHost({ detect: ffmpegDetection })
+ const ffmpeg = new FfmpegCapabilityHost({
+ detect: ffmpegDetection,
+ validateBinaryPath: (binaryPath) => {
+ assertManagedFfmpegTrusted(opts.userDataDir, binaryPath)
+ },
+ })
const http = new HttpCapabilityHost() // per-plugin jar injected by Task 19 bridge
return {
diff --git a/src/server/plugin/ffmpeg-detect-server.ts b/src/server/plugin/ffmpeg-detect-server.ts
index be5a200c..a9d58fe3 100644
--- a/src/server/plugin/ffmpeg-detect-server.ts
+++ b/src/server/plugin/ffmpeg-detect-server.ts
@@ -13,6 +13,7 @@ import {
type FfmpegDetectionResult,
} from '@core/plugin/capabilities/ffmpeg-detect'
import type { SettingsManager } from '@core/settings/settings-manager'
+import { probeServerFfmpeg } from './verified-ffmpeg-server'
export interface ServerFfmpegDetectOptions {
settingsManager: SettingsManager
@@ -25,10 +26,13 @@ export function makeServerFfmpegDetect(
): () => Promise<FfmpegDetectionResult> {
const userDataBinariesDir = path.join(opts.userDataDir, 'binaries')
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: process.env.MOTRIX_FFMPEG_PATH ?? null,
+ },
+ (candidate) => probeServerFfmpeg(opts.userDataDir, candidate)
+ )
}
diff --git a/src/server/plugin/verified-ffmpeg-server.test.ts b/src/server/plugin/verified-ffmpeg-server.test.ts
new file mode 100644
index 00000000..0cbc58d5
--- /dev/null
+++ b/src/server/plugin/verified-ffmpeg-server.test.ts
@@ -0,0 +1,156 @@
+import { verifyMacFfmpegTrust } from '@core/ffmpeg/ffmpeg-macos-trust'
+import {
+ assertManagedFfmpegTrusted,
+ getFfmpegInstallStatus,
+ installVerifiedFfmpeg,
+ resolveManagedFfmpegCandidate,
+} from '@core/ffmpeg/verified-install'
+import { probeBinary } from '@core/plugin/capabilities/ffmpeg-detect'
+import { AppError, ErrorCode } from '@shared/errors'
+import type { FfmpegTarget } from '@shared/schemas/ffmpeg-release'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ installServerFfmpeg,
+ probeServerFfmpeg,
+} from './verified-ffmpeg-server'
+
+vi.mock('@core/ffmpeg/verified-install', () => ({
+ installVerifiedFfmpeg: vi.fn(),
+ getFfmpegInstallStatus: vi.fn(),
+ resolveManagedFfmpegCandidate: vi.fn(),
+ assertManagedFfmpegTrusted: vi.fn(),
+}))
+vi.mock('@core/ffmpeg/ffmpeg-macos-trust', () => ({
+ verifyMacFfmpegTrust: vi.fn(),
+}))
+vi.mock('@core/plugin/capabilities/ffmpeg-detect', () => ({
+ probeBinary: vi.fn(),
+}))
+
+const userDataDir = '/data'
+const binary = '/data/binaries/ffmpeg-verified/releases/verified/ffmpeg'
+const installed = { ok: true as const, releaseVersion: '9.0.2-motrix.2' }
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ vi.mocked(installVerifiedFfmpeg).mockResolvedValue(installed)
+ vi.mocked(resolveManagedFfmpegCandidate).mockReturnValue(binary)
+ vi.mocked(probeBinary).mockResolvedValue({
+ available: true,
+ binaryPath: binary,
+ version: '9.0.2',
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('server verified FFmpeg installation', () => {
+ it.each(['linux', 'darwin', 'win32'] as const)(
+ 'uses the %s server target and forwards progress',
+ async (platform) => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue(platform)
+ vi.spyOn(process, 'arch', 'get').mockReturnValue('arm64')
+ const onStatus = vi.fn()
+ await expect(installServerFfmpeg(userDataDir, onStatus)).resolves.toEqual(
+ installed
+ )
+ expect(installVerifiedFfmpeg).toHaveBeenCalledWith({
+ userDataDir,
+ platform,
+ arch: 'arm64',
+ onStatus,
+ systemTrust: verifyMacFfmpegTrust,
+ })
+ }
+ )
+
+ it('does not start downloads for unsupported architectures', async () => {
+ vi.spyOn(process, 'arch', 'get').mockReturnValue('arm')
+ await expect(installServerFfmpeg(userDataDir)).resolves.toEqual({
+ ok: false,
+ error: 'unsupported',
+ })
+ expect(installVerifiedFfmpeg).not.toHaveBeenCalled()
+ })
+
+ it('reports concurrent installs as busy without overwriting the running status', async () => {
+ vi.mocked(installVerifiedFfmpeg).mockRejectedValue(
+ new AppError(ErrorCode.FfmpegInstallBusy, 'busy')
+ )
+ await expect(installServerFfmpeg(userDataDir)).resolves.toEqual({
+ ok: false,
+ error: 'busy',
+ })
+ expect(getFfmpegInstallStatus).not.toHaveBeenCalled()
+ })
+
+ it('returns a bounded failure code without leaking remote errors', async () => {
+ vi.mocked(installVerifiedFfmpeg).mockRejectedValue(
+ new Error('untrusted remote text')
+ )
+ vi.mocked(getFfmpegInstallStatus).mockReturnValue({
+ phase: 'failed',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ directory: null,
+ releaseVersion: null,
+ error: 'verification',
+ })
+ await expect(installServerFfmpeg(userDataDir)).resolves.toEqual({
+ ok: false,
+ error: 'verification',
+ })
+ })
+})
+
+describe('server managed FFmpeg detection', () => {
+ it('probes the verified release instead of the conventional candidate path', async () => {
+ await expect(
+ probeServerFfmpeg(userDataDir, '/data/binaries/ffmpeg')
+ ).resolves.toMatchObject({ available: true, binaryPath: binary })
+ expect(probeBinary).toHaveBeenCalledWith(binary)
+ expect(assertManagedFfmpegTrusted).toHaveBeenCalledWith(userDataDir, binary)
+ })
+
+ it('never executes a managed binary that fails verification', async () => {
+ vi.mocked(resolveManagedFfmpegCandidate).mockImplementation(() => {
+ throw new Error('modified binary')
+ })
+ await expect(
+ probeServerFfmpeg(userDataDir, '/data/binaries/ffmpeg')
+ ).resolves.toEqual({ available: false, failureReason: 'untrusted' })
+ expect(probeBinary).not.toHaveBeenCalled()
+ })
+
+ it('requires macOS trust before probing managed tools', async () => {
+ vi.mocked(assertManagedFfmpegTrusted).mockReturnValue({
+ platform: 'darwin',
+ releaseVersion: installed.releaseVersion,
+ archive: 'ffmpeg.zip',
+ } as FfmpegTarget)
+ await probeServerFfmpeg(userDataDir, '/data/binaries/ffmpeg')
+ expect(verifyMacFfmpegTrust).toHaveBeenCalledWith(
+ '/data/binaries/ffmpeg-verified/releases/verified',
+ expect.any(Object),
+ `https://github.com/motrixapp/ffmpeg-static/releases/download/v${installed.releaseVersion}/ffmpeg.zip`
+ )
+ expect(
+ vi.mocked(verifyMacFfmpegTrust).mock.invocationCallOrder[0]
+ ).toBeLessThan(vi.mocked(probeBinary).mock.invocationCallOrder[0])
+ vi.mocked(probeBinary).mockClear()
+ vi.mocked(verifyMacFfmpegTrust).mockRejectedValue(
+ new Error('not notarized')
+ )
+ await expect(
+ probeServerFfmpeg(userDataDir, '/data/binaries/ffmpeg')
+ ).resolves.toMatchObject({ available: false, failureReason: 'untrusted' })
+ expect(probeBinary).not.toHaveBeenCalled()
+ })
+
+ it('keeps manually configured tools usable', async () => {
+ vi.mocked(resolveManagedFfmpegCandidate).mockReturnValue('/opt/ffmpeg')
+ await probeServerFfmpeg(userDataDir, '/opt/ffmpeg')
+ expect(probeBinary).toHaveBeenCalledWith('/opt/ffmpeg')
+ expect(verifyMacFfmpegTrust).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/server/plugin/verified-ffmpeg-server.ts b/src/server/plugin/verified-ffmpeg-server.ts
new file mode 100644
index 00000000..96ede38b
--- /dev/null
+++ b/src/server/plugin/verified-ffmpeg-server.ts
@@ -0,0 +1,68 @@
+import path from 'node:path'
+import { verifyMacFfmpegTrust } from '@core/ffmpeg/ffmpeg-macos-trust'
+import {
+ assertManagedFfmpegTrusted,
+ getFfmpegInstallStatus,
+ installVerifiedFfmpeg,
+ resolveManagedFfmpegCandidate,
+} from '@core/ffmpeg/verified-install'
+import {
+ type FfmpegDetection,
+ probeBinary,
+} from '@core/plugin/capabilities/ffmpeg-detect'
+import { AppError, ErrorCode } from '@shared/errors'
+import {
+ FFMPEG_REPOSITORY,
+ type FfmpegInstallStatus,
+ type FfmpegPlatform,
+} from '@shared/schemas/ffmpeg-release'
+
+export async function installServerFfmpeg(
+ userDataDir: string,
+ onStatus?: (status: FfmpegInstallStatus) => void
+) {
+ if (
+ !['darwin', 'linux', 'win32'].includes(process.platform) ||
+ !['x64', 'arm64'].includes(process.arch)
+ )
+ return { ok: false as const, error: 'unsupported' as const }
+ try {
+ return await installVerifiedFfmpeg({
+ userDataDir,
+ arch: process.arch as 'x64' | 'arm64',
+ platform: process.platform as FfmpegPlatform,
+ onStatus,
+ systemTrust: verifyMacFfmpegTrust,
+ })
+ } catch (error) {
+ return {
+ ok: false as const,
+ error:
+ error instanceof AppError && error.code === ErrorCode.FfmpegInstallBusy
+ ? ('busy' as const)
+ : (getFfmpegInstallStatus(userDataDir).error ?? ('install' as const)),
+ }
+ }
+}
+
+/** Resolve and verify the managed release before executing a version probe. */
+export async function probeServerFfmpeg(
+ userDataDir: string,
+ candidate: string
+): Promise<FfmpegDetection> {
+ let resolved: string
+ try {
+ resolved = resolveManagedFfmpegCandidate(userDataDir, candidate)
+ const target = assertManagedFfmpegTrusted(userDataDir, resolved)
+ if (target?.platform === 'darwin') {
+ await verifyMacFfmpegTrust(
+ path.dirname(resolved),
+ target,
+ `https://github.com/${FFMPEG_REPOSITORY}/releases/download/v${target.releaseVersion}/${target.archive}`
+ )
+ }
+ } catch {
+ return { available: false, failureReason: 'untrusted' }
+ }
+ return probeBinary(resolved)
+}
diff --git a/src/shared/app-update-channel.ts b/src/shared/app-update-channel.ts
new file mode 100644
index 00000000..57595f1a
--- /dev/null
+++ b/src/shared/app-update-channel.ts
@@ -0,0 +1,18 @@
+import type { AppUpdateChannel } from './types/settings'
+
+const STRICT_SEMVER_PATTERN =
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
+
+/** Stable and beta are the only published application update channels. */
+export function isVersionAllowedForChannel(
+ version: string,
+ channel: AppUpdateChannel
+): boolean {
+ const match = STRICT_SEMVER_PATTERN.exec(version)
+ if (!match) return false
+ const prerelease = match[4]
+ return (
+ prerelease === undefined ||
+ (channel === 'beta' && prerelease.split('.')[0] === 'beta')
+ )
+}
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 0086ae76..57f08043 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -1,5 +1,6 @@
export enum ErrorCode {
AppUpdateManaged = 'APP_UPDATE_MANAGED',
+ AppUpdateCheckFailed = 'APP_UPDATE_CHECK_FAILED',
EngineStartFailed = 'ENGINE_START_FAILED',
EngineConnectionLost = 'ENGINE_CONNECTION_LOST',
EngineTimeout = 'ENGINE_TIMEOUT',
diff --git a/src/shared/external-urls.ts b/src/shared/external-urls.ts
index da93e6f6..8d545143 100644
--- a/src/shared/external-urls.ts
+++ b/src/shared/external-urls.ts
@@ -25,6 +25,7 @@ export const EXTERNAL_URLS = {
'https://github.com/motrixapp/ffmpeg-static/releases/latest',
},
motrix: {
+ updateFeed: 'https://dl.motrix.app/releases/',
home: 'https://motrix.app/',
acknowledgments: 'https://motrix.app/acknowledgments',
plugins: 'https://motrix.app/plugins',
diff --git a/src/shared/types/app-update.ts b/src/shared/types/app-update.ts
index 88b29569..b0769da2 100644
--- a/src/shared/types/app-update.ts
+++ b/src/shared/types/app-update.ts
@@ -22,12 +22,12 @@ export interface AppUpdateError {
message: string
}
-/** Stable renderer-facing snapshot. Raw electron-updater payloads stay in main. */
+/** Stable renderer-facing snapshot shared by the desktop and Server hosts. */
export interface AppUpdateState {
phase: AppUpdatePhase
currentVersion: string
/** Absent on older hosts that predate externally managed updates. */
- updateAuthority?: 'application' | 'system'
+ updateAuthority?: 'application' | 'system' | 'administrator'
availableVersion?: string
releaseName?: string
progress?: AppUpdateProgress
diff --git a/tests/ffmpeg-public-release.test.ts b/tests/ffmpeg-public-release.test.ts
index 5e4a441a..7b4c871a 100644
--- a/tests/ffmpeg-public-release.test.ts
+++ b/tests/ffmpeg-public-release.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import {
@@ -22,8 +22,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { runCommand } from '../src/main/cli/command-runner'
import { verifyMacFfmpegTrust } from '../src/main/plugin/ffmpeg-macos-trust'
import { makeElectronFfmpegProbe } from '../src/main/plugin/ffmpeg-probe-electron'
+import {
+ installServerFfmpeg,
+ probeServerFfmpeg,
+} from '../src/server/plugin/verified-ffmpeg-server'
-// macOS-only explicit opt-in: checks actual Apple trust for both Darwin archives.
+// Explicit opt-in: checks native Server installation; the desktop matrix also
+// checks actual Apple trust for both Darwin archives on macOS.
// Uses only the latest public immutable GitHub Release, never CI artifacts.
// Run: MOTRIX_FFMPEG_PUBLIC_RELEASE_TEST=1 pnpm exec vitest run tests/ffmpeg-public-release.test.ts
const enabled = process.env.MOTRIX_FFMPEG_PUBLIC_RELEASE_TEST === '1'
@@ -100,6 +105,48 @@ async function checkedInstallation(
return { candidate, verified, directory }
}
+describe.skipIf(
+ !enabled || !['darwin', 'linux', 'win32'].includes(process.platform)
+)('public FFmpeg server installation', () => {
+ it('installs on the server, detects the managed release, and rejects later tampering', async () => {
+ const userDataDir = await isolatedData()
+ const progress: FfmpegInstallStatus[] = []
+ const result = await installServerFfmpeg(userDataDir, (status) =>
+ progress.push(status)
+ )
+ expect(result.ok).toBe(true)
+ expect(
+ progress.some(
+ (status) => status.phase === 'downloading' && status.bytesReceived > 0
+ )
+ ).toBe(true)
+ expect(progress.at(-1)?.phase).toBe('installed')
+ const { directory, verified } = await checkedInstallation(
+ userDataDir,
+ process.platform as FfmpegPlatform,
+ process.arch as 'x64' | 'arm64'
+ )
+ const candidate = path.join(
+ userDataDir,
+ 'binaries',
+ process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
+ )
+ await expect(
+ probeServerFfmpeg(userDataDir, candidate)
+ ).resolves.toMatchObject({
+ available: true,
+ binaryPath: path.join(directory, verified.target.binaryPath),
+ })
+ await writeFile(
+ path.join(directory, verified.target.ffprobePath),
+ 'tampered'
+ )
+ await expect(
+ probeServerFfmpeg(userDataDir, candidate)
+ ).resolves.toMatchObject({ available: false, failureReason: 'untrusted' })
+ }, 600_000)
+})
+
describe.skipIf(!enabled || process.platform !== 'darwin')(
'public FFmpeg release download and installation',
() => {
diff --git a/tests/scripts/audit-server-runtime.test.ts b/tests/scripts/audit-server-runtime.test.ts
index df266bae..05467950 100644
--- a/tests/scripts/audit-server-runtime.test.ts
+++ b/tests/scripts/audit-server-runtime.test.ts
@@ -318,6 +318,7 @@ describe('Server package contracts', () => {
'chokidar',
'fastify',
'i18next',
+ 'js-yaml',
'libsodium-wrappers',
'mmdb-lib',
'pino',