Skip to content

A full-featured download manager.

feat(appimage): desktop self-integration, release re-enable, and settings toggle (#1902)

Dr_rOot0206eb79d824
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 7e3a244e..5eed6e0a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -11,11 +11,12 @@
# - a native GitHub-hosted runner;
# - a packages/native-host/build.mjs Rust target.
#
-# AppImage is intentionally excluded until its transient mount can persist a
-# browser native-messaging host that remains launchable after the app exits.
-# Snap has its own strict-confinement build and Store promotion workflows.
-# 32-bit targets remain unsupported. Windows arm64 remains reserved until the
-# aria2 lock supplies that architecture.
+# The Linux AppImage is published for x64 and arm64. It self-integrates its
+# desktop entry and URL-scheme handlers at runtime under the user's XDG data
+# tree (src/main/platform/appimage-integration.ts). Snap has its own
+# strict-confinement build and Store promotion workflows. 32-bit targets remain
+# unsupported. Windows arm64 remains reserved until the aria2 lock supplies that
+# architecture.
name: Build/Release
@@ -140,7 +141,7 @@ jobs:
platform: linux
arch: x64
rust_target: x86_64-unknown-linux-musl
- electron_builder_args: --linux deb rpm --x64
+ electron_builder_args: --linux deb rpm AppImage --x64
resources_dir: release/linux-unpacked/resources
app_path: release/linux-unpacked
- target: linux-arm64
@@ -148,7 +149,7 @@ jobs:
platform: linux
arch: arm64
rust_target: aarch64-unknown-linux-musl
- electron_builder_args: --linux deb rpm --arm64
+ electron_builder_args: --linux deb rpm AppImage --arm64
resources_dir: release/linux-arm64-unpacked/resources
app_path: release/linux-arm64-unpacked
- target: win32-x64
@@ -188,7 +189,10 @@ jobs:
if: matrix.platform == 'linux'
run: |
sudo apt-get update
- sudo apt-get install --yes rpm
+ # squashfs-tools provides `unsquashfs`, used by
+ # verify-appimage-artifact.mjs to read the AppImage's embedded
+ # desktop entry.
+ sudo apt-get install --yes rpm squashfs-tools
- name: Setup Rust
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
@@ -359,13 +363,22 @@ jobs:
shopt -s nullglob
debs=(release/*.deb)
rpms=(release/*.rpm)
- if (( ${#debs[@]} != 1 || ${#rpms[@]} != 1 )); then
- echo "Expected one deb and rpm for ${{ matrix.target }}" >&2
+ appimages=(release/*.AppImage)
+ if (( ${#debs[@]} != 1 || ${#rpms[@]} != 1 || ${#appimages[@]} != 1 )); then
+ echo "Expected one deb, rpm, and AppImage for ${{ matrix.target }}" >&2
exit 1
fi
dpkg-deb --info "${debs[0]}"
rpm -qip "${rpms[0]}"
+ - name: Verify AppImage artifact
+ if: matrix.platform == 'linux'
+ run: >-
+ node scripts/verify-appimage-artifact.mjs
+ --dir release
+ --version "${{ needs.preflight.outputs.version }}"
+ --arch ${{ matrix.arch }}
+
- name: Package Flatpak native host companion
if: matrix.platform == 'linux'
env:
@@ -434,6 +447,7 @@ jobs:
with:
name: release-input-${{ matrix.target }}
path: |
+ release/*.AppImage
release/*.blockmap
release/beta*.yml
release/*.deb
diff --git a/README.md b/README.md
index 3dcbfe52..aea7ebcc 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
[![GitHub release](https://img.shields.io/github/v/release/agalwood/Motrix.svg)](https://github.com/agalwood/Motrix/releases) ![Build/release](https://github.com/agalwood/Motrix/workflows/Build/release/badge.svg) ![Total Downloads](https://img.shields.io/github/downloads/agalwood/Motrix/total.svg)
-English | [简体中文](./README.zh-CN.md)
+English | [简体中文](./README.zh-CN.md)
## Overview
@@ -19,7 +19,7 @@ The same core powers two ways to run Motrix:
- **Desktop app:** Runs on macOS, Windows, and Linux
- **Headless server:** Runs without a desktop environment, either directly on Node.js or in Docker, and includes a web UI for NAS devices and home servers
-## 🧪 Beta testing
+## 🧪 Beta testing
Motrix Turbo v2 is currently in beta. After its remaining release gates pass,
download [v2.0.0-beta.19 from GitHub Releases](https://github.com/agalwood/Motrix/releases/tag/v2.0.0-beta.19)
@@ -57,26 +57,26 @@ account, machine, or Docker data directory.
<img alt="Motrix Settings" src="./screenshots/motrix-settings.webp">
</picture>
-## ✨ Features
-
-- 🕹 Clean, intuitive interface with dark mode
-- 🦄 BitTorrent downloads with per-file selection, plus magnet link support
-- 📡 Built-in tracker list management with automatic updates and health checks
-- 🔌 UPnP and NAT-PMP port mapping
-- 🚥 Upload and download limits with multiple speed-limit profiles
-- 💾 SQLite-backed sessions that restore downloads after a restart
-- 📊 Customizable Dashboard with transfer stats, live activity, and task tiles
-- 🔔 System notifications when downloads finish, plus an in-app notification center
-- 🧩 QuickJS-based plugin sandboxing, fine-grained permissions, and an in-app marketplace
-- 🌐 Chrome and Firefox extensions that hand browser downloads off to Motrix in one click
-- ⌨️ Official `@motrix/cli` client for everyday shell use and AI agents
-- 🐳 Docker-ready headless server with secure device-code pairing for remote CLI and agent clients
-- 🎬 Extensible URL Resolver plugins for extracting media from supported sites
-- 🤖 System tray integration and launch at startup
-- 🌍 Simplified Chinese and English UI, with more languages planned
-- 🔗 Handlers for `motrix://` and `magnet:` links, plus `.torrent` file associations
-
-## 🧩 Ecosystem
+## ✨ Features
+
+- 🕹 Clean, intuitive interface with dark mode
+- 🦄 BitTorrent downloads with per-file selection, plus magnet link support
+- 📡 Built-in tracker list management with automatic updates and health checks
+- 🔌 UPnP and NAT-PMP port mapping
+- 🚥 Upload and download limits with multiple speed-limit profiles
+- 💾 SQLite-backed sessions that restore downloads after a restart
+- 📊 Customizable Dashboard with transfer stats, live activity, and task tiles
+- 🔔 System notifications when downloads finish, plus an in-app notification center
+- 🧩 QuickJS-based plugin sandboxing, fine-grained permissions, and an in-app marketplace
+- 🌐 Chrome and Firefox extensions that hand browser downloads off to Motrix in one click
+- ⌨️ Official `@motrix/cli` client for everyday shell use and AI agents
+- 🐳 Docker-ready headless server with secure device-code pairing for remote CLI and agent clients
+- 🎬 Extensible URL Resolver plugins for extracting media from supported sites
+- 🤖 System tray integration and launch at startup
+- 🌍 Simplified Chinese and English UI, with more languages planned
+- 🔗 Handlers for `motrix://` and `magnet:` links, plus `.torrent` file associations
+
+## 🧩 Ecosystem
Motrix extends beyond the desktop app with a shared protocol library, command-line client, browser extensions, and a complete plugin toolchain:
@@ -117,7 +117,7 @@ The default scaffold starts with a `beforeCreate` URL resolver. Pass `post-actio
Plugins are bundled as a single ES2020 module and run inside a QuickJS sandbox without Node.js APIs or direct file and network access. Declare activation events, required capabilities, and URL-scoped host permissions in `motrix-plugin.json`; Motrix shows those requests to the user before granting access. See the [Plugin SDK documentation](https://github.com/motrixapp/plugin-sdk) for templates, the manifest and runtime API references, localization, sandbox constraints, packaging, and distribution.
-## 📦 Installation
+## 📦 Installation
### Desktop app
@@ -133,9 +133,13 @@ operating system and architecture:
|----------|---------------|--------------------|----------------|
| macOS 12+ | `arm64` (Apple Silicon), `x64` (Intel) | `.dmg` / `.zip` | Use the `.dmg` matching your Mac; choose `x64` only for an Intel-based Mac |
| Windows | `x64` | `.exe` (NSIS installer) / `.zip` | Use the `.exe` installer for a normal installation or `.zip` for a manually extracted copy |
-| Linux | `x64`, `arm64` | `.deb` / `.rpm` | Use `.deb` on Debian or Ubuntu, or `.rpm` on Fedora or openSUSE |
+| Linux | `x64`, `arm64` | `.AppImage` / `.deb` / `.rpm` | Use the portable `.AppImage` on any distribution, `.deb` on Debian or Ubuntu, or `.rpm` on Fedora or openSUSE |
-This beta does not publish an AppImage or Snap. Flatpak is validated separately
+The `.AppImage` asks on first launch whether to register its desktop entry and
+URL-scheme handlers under your user data directory; declining leaves your system
+untouched. You can enable or remove this desktop integration at any time from
+Settings → Integration.
+This beta does not publish a Snap. Flatpak is validated separately
and is not published by the release tag. Windows `arm64` and all 32-bit
packages are not available. Windows `x64` packages are unsigned and may
trigger a Windows SmartScreen warning.
@@ -146,7 +150,7 @@ trigger a Windows SmartScreen warning.
npm install -g @motrix/cli
```
-You can also install it from Settings → Integration → Command-line tools in the desktop app.
+You can also install it from Settings → Integration → Command-line tools in the desktop app.
### Headless server with Docker
@@ -188,7 +192,7 @@ TLS reverse proxy and firewall rules around the origin ports. See the
Docker Hub/GHCR image and tag selection, DSM 7 and fnOS installation, ports,
diagnostics, and backup/upgrade instructions.
-## 🛠 Development
+## 🛠 Development
Development requires Node.js 22 or later and pnpm. Use the pnpm version specified by the `packageManager` field in `package.json`.
@@ -222,12 +226,12 @@ flag because both Electron and Vite read it at startup.
This mode is intended for layout and command-item debugging. Electron routes
macOS role items through AppKit's native menu, so role-backed actions such as
-**Window → Minimize** do not behave identically when invoked from the preview
+**Window → Minimize** do not behave identically when invoked from the preview
dropdown. Validate those native role actions on Windows or Linux.
See the scripts in `package.json` for the available packaging commands. Platform-specific settings for macOS, Windows, and Linux live in `electron-builder.json`.
-## 🔧 Tech stack
+## 🔧 Tech stack
| Area | Stack |
|------|-------|
@@ -247,19 +251,19 @@ The codebase has four strict layers. CI enforces the dependency boundaries betwe
```
renderer (React UI)
- │ IPC via window.motrix
+ │ IPC via window.motrix
app core (tasks, settings, plugins, bridge)
- │
+ │
engine adapter
- │
+ │
aria2 (download engine)
```
The Electron desktop app and the Node.js headless server share the same core. Platform-specific capabilities such as notifications and secret storage have separate implementations with consistent behavior.
-## 📜 License
+## 📜 License
-[MIT](./LICENSE) © 2018-present Dr_rOot
+[MIT](./LICENSE) © 2018-present Dr_rOot
See [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md) for third-party license information.
Release packages also include a generated dependency inventory, consolidated license texts, and an SPDX 2.3 SBOM under `legal/`.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 585a321f..9f785dd2 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -129,9 +129,10 @@ pnpm exec motrix-plugin lint # 检查打包产物
|------|------|---------------|----------|
| macOS 12+ | `arm64`(Apple Silicon)、`x64`(Intel) | `.dmg` / `.zip` | 选择与 Mac 架构匹配的 `.dmg`;仅 Intel Mac 使用 `x64` |
| Windows | `x64` | `.exe`(NSIS 安装包)/ `.zip` | 常规安装使用 `.exe`;`.zip` 可解压后手动运行 |
-| Linux | `x64`、`arm64` | `.deb` / `.rpm` | Debian 或 Ubuntu 使用 `.deb`,Fedora 或 openSUSE 使用 `.rpm` |
+| Linux | `x64`、`arm64` | `.AppImage` / `.deb` / `.rpm` | 任意发行版可使用便携的 `.AppImage`,Debian 或 Ubuntu 使用 `.deb`,Fedora 或 openSUSE 使用 `.rpm` |
-本 beta 不发布 AppImage 或 Snap。Flatpak 会单独验证,不会随该版本 tag 发布。
+`.AppImage` 首次启动时会询问是否把桌面入口和 URL scheme 处理程序注册到你的用户数据目录;拒绝则不改动系统。之后随时可以在「设置 → 集成」中启用或移除该桌面集成。
+本 beta 不发布 Snap。Flatpak 会单独验证,不会随该版本 tag 发布。
同时不提供 Windows `arm64` 和任何 32 位安装包。Windows `x64` 安装包未签名,
可能触发 Windows SmartScreen 警告。
diff --git a/electron-builder.json b/electron-builder.json
index da5e8cba..9a0f4e6d 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -179,6 +179,7 @@
"GenericName": "Download Manager",
"Comment": "Full-featured download manager",
"Keywords": "download;bittorrent;magnet;aria2;",
+ "MimeType": "application/x-bittorrent;x-scheme-handler/magnet;x-scheme-handler/motrix;",
"StartupWMClass": "Motrix"
}
},
@@ -190,6 +191,10 @@
"extraResources": [
{ "from": "./extra/aria2.conf", "to": "./extra/aria2.conf" },
{ "from": "./dist/builtin-plugins", "to": "./builtin-plugins" },
+ {
+ "from": "./build/256x256.png",
+ "to": "./icons/motrix-appimage-256.png"
+ },
{ "from": "./extra/linux/${arch}/", "to": "./extra/linux/${arch}/" },
{
"from": "./packages/native-host/dist/linux-${arch}/motrix-native-host",
diff --git a/scripts/assemble-release-artifacts.mjs b/scripts/assemble-release-artifacts.mjs
index 620ab840..b02af59d 100644
--- a/scripts/assemble-release-artifacts.mjs
+++ b/scripts/assemble-release-artifacts.mjs
@@ -53,11 +53,13 @@ export const RELEASE_TARGETS = [
assetNames: (version) => [
`Motrix_${version}_amd64.deb`,
`Motrix-${version}.x86_64.rpm`,
+ `Motrix-${version}-x86_64.AppImage`,
flatpakCompanionArchiveName(version, 'x64'),
],
manifestAssetNames: (version) => [
`Motrix_${version}_amd64.deb`,
`Motrix-${version}.x86_64.rpm`,
+ `Motrix-${version}-x86_64.AppImage`,
],
legacyAssetName: (version) => `Motrix_${version}_amd64.deb`,
},
@@ -68,11 +70,13 @@ export const RELEASE_TARGETS = [
assetNames: (version) => [
`Motrix_${version}_arm64.deb`,
`Motrix-${version}.aarch64.rpm`,
+ `Motrix-${version}-arm64.AppImage`,
flatpakCompanionArchiveName(version, 'arm64'),
],
manifestAssetNames: (version) => [
`Motrix_${version}_arm64.deb`,
`Motrix-${version}.aarch64.rpm`,
+ `Motrix-${version}-arm64.AppImage`,
],
legacyAssetName: (version) => `Motrix_${version}_arm64.deb`,
},
diff --git a/scripts/verify-appimage-artifact.mjs b/scripts/verify-appimage-artifact.mjs
new file mode 100644
index 00000000..887945b1
--- /dev/null
+++ b/scripts/verify-appimage-artifact.mjs
@@ -0,0 +1,210 @@
+import { execFile } from 'node:child_process'
+import { mkdtemp, open, readdir, readFile, rm, stat } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { promisify } from 'node:util'
+
+// Release-time verification for the Linux AppImage target. Unlike a config-only
+// check, this inspects the BUILT artifact itself:
+// 1. Exactly one AppImage exists for the built architecture, named per the
+// electron-builder `appImage.artifactName` template.
+// 2. It is a regular, executable file.
+// 3. Its header is an ELF carrying the AppImage type-2 magic, and its ELF
+// machine matches the target architecture (a wrong-arch or non-AppImage
+// file with the right name is rejected).
+// 4. The desktop entry embedded INSIDE the AppImage declares all three
+// handler MimeTypes a browser needs (bittorrent, magnet, motrix:) — read
+// out of the artifact, not from the source config.
+// The runtime self-integration (src/main/platform/appimage-integration.ts) is a
+// separate, user-scope mechanism.
+
+const execFileAsync = promisify(execFile)
+
+export const REQUIRED_MIME_TYPES = [
+ 'application/x-bittorrent',
+ 'x-scheme-handler/magnet',
+ 'x-scheme-handler/motrix',
+]
+
+// electron-builder's `${arch}` macro for the AppImage target (builder-util
+// getArtifactArchName): x64 -> x86_64, arm64 -> arm64.
+const APPIMAGE_ARCH = {
+ x64: 'x86_64',
+ arm64: 'arm64',
+}
+
+// ELF e_machine values (offset 18, little-endian u16).
+const ELF_MACHINE = {
+ x64: 0x3e, // EM_X86_64
+ arm64: 0xb7, // EM_AARCH64
+}
+
+export function expectedAppImageName(version, arch) {
+ const archName = APPIMAGE_ARCH[arch]
+ if (!archName) throw new Error(`Unsupported AppImage arch: ${arch}`)
+ return `Motrix-${version}-${archName}.AppImage`
+}
+
+export function assertDesktopMimeTypes(mimeValue) {
+ const mime = typeof mimeValue === 'string' ? mimeValue : ''
+ const declared = new Set(mime.split(';').filter(Boolean))
+ const missing = REQUIRED_MIME_TYPES.filter((type) => !declared.has(type))
+ if (missing.length > 0) {
+ throw new Error(
+ `AppImage embedded desktop entry is missing MimeType handlers: ${missing.join(', ')}`
+ )
+ }
+}
+
+// Validate the first bytes of the artifact: ELF magic, AppImage type-2 magic
+// (`AI\x02` at offset 8), and the ELF machine for the target arch.
+export function assertAppImageHeader(head, arch) {
+ if (head.length < 20) throw new Error('AppImage header too short')
+ const isElf =
+ head[0] === 0x7f && head[1] === 0x45 && head[2] === 0x4c && head[3] === 0x46
+ if (!isElf) throw new Error('Artifact is not an ELF (not an AppImage)')
+ const hasAiMagic = head[8] === 0x41 && head[9] === 0x49 && head[10] === 0x02
+ if (!hasAiMagic) {
+ throw new Error('Missing AppImage type-2 magic (AI\\x02) at offset 8')
+ }
+ const machine = head[18] | (head[19] << 8)
+ const expected = ELF_MACHINE[arch]
+ if (machine !== expected) {
+ throw new Error(
+ `AppImage ELF machine 0x${machine.toString(16)} does not match ${arch} (expected 0x${expected.toString(16)})`
+ )
+ }
+}
+
+// Extract the MimeType line from the AppImage's embedded `.desktop` using
+// `unsquashfs` (cross-arch: reads the filesystem without executing the
+// binary). Returns the raw MimeType value, or throws if it cannot be read.
+async function defaultExtractMimeType(appImagePath) {
+ const head = await readHead(appImagePath, 64)
+ const offset = squashfsOffset(head)
+ if (offset == null) {
+ throw new Error('Could not locate the squashfs image inside the AppImage')
+ }
+ const dir = await mkdtemp(path.join(tmpdir(), 'motrix-appimage-verify-'))
+ try {
+ await execFileAsync('unsquashfs', [
+ '-o',
+ String(offset),
+ '-d',
+ path.join(dir, 'squashfs-root'),
+ '-f',
+ appImagePath,
+ ])
+ const root = path.join(dir, 'squashfs-root')
+ const names = await readdir(root)
+ const desktopName = names.find((n) => n.endsWith('.desktop'))
+ if (!desktopName) throw new Error('No .desktop entry in the AppImage')
+ const content = await readFile(path.join(root, desktopName), 'utf8')
+ return parseMimeTypeFromDesktop(content)
+ } finally {
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
+ }
+}
+
+// The squashfs image inside an AppImage begins at the end of the ELF; its start
+// is marked by the `hsqs` magic. Read it from the ELF section-header table end,
+// falling back to null if the header is unexpected.
+function squashfsOffset(head) {
+ // e_shoff (u64 LE @ 0x28), e_shentsize (u16 @ 0x3a), e_shnum (u16 @ 0x3c).
+ if (head.length < 64) return null
+ const shoff = Number(head.readBigUInt64LE(0x28))
+ const shentsize = head.readUInt16LE(0x3a)
+ const shnum = head.readUInt16LE(0x3c)
+ if (!shoff || !shentsize || !shnum) return null
+ return shoff + shentsize * shnum
+}
+
+function parseMimeTypeFromDesktop(content) {
+ let inGroup = false
+ for (const rawLine of content.split(/\r?\n/)) {
+ const line = rawLine.trim()
+ if (line.startsWith('[') && line.endsWith(']')) {
+ inGroup = line === '[Desktop Entry]'
+ continue
+ }
+ if (!inGroup || !line.startsWith('MimeType=')) continue
+ return line.slice('MimeType='.length)
+ }
+ return ''
+}
+
+async function readHead(filePath, n) {
+ const fh = await open(filePath, 'r')
+ try {
+ const buf = Buffer.alloc(n)
+ const { bytesRead } = await fh.read(buf, 0, n, 0)
+ return buf.subarray(0, bytesRead)
+ } finally {
+ await fh.close()
+ }
+}
+
+export async function verifyAppimageArtifact({
+ directory,
+ version,
+ arch,
+ // Injectable ports so the checks are unit-testable without a real AppImage.
+ statFile = stat,
+ readArtifactHead = readHead,
+ extractMimeType = defaultExtractMimeType,
+}) {
+ if (!version) throw new Error('Expected release version')
+ if (!arch) throw new Error('Expected target architecture')
+ if (!APPIMAGE_ARCH[arch])
+ throw new Error(`Unsupported AppImage arch: ${arch}`)
+
+ const entries = await readdir(directory)
+ const appImages = entries.filter((name) => name.endsWith('.AppImage'))
+ if (appImages.length !== 1) {
+ throw new Error(
+ `Expected exactly one AppImage for ${arch}, found ${appImages.length}: ${appImages.join(', ')}`
+ )
+ }
+
+ const expected = expectedAppImageName(version, arch)
+ if (appImages[0] !== expected) {
+ throw new Error(
+ `Unexpected AppImage name ${appImages[0]}; expected ${expected}`
+ )
+ }
+
+ const artifactPath = path.join(directory, expected)
+
+ const info = await statFile(artifactPath)
+ if (!info.isFile()) throw new Error(`${expected} is not a regular file`)
+ // At least one execute bit must be set (AppImages are run directly).
+ if ((info.mode & 0o111) === 0) {
+ throw new Error(
+ `${expected} is not executable (mode ${info.mode.toString(8)})`
+ )
+ }
+
+ const head = await readArtifactHead(artifactPath, 64)
+ assertAppImageHeader(head, arch)
+
+ const mime = await extractMimeType(artifactPath)
+ assertDesktopMimeTypes(mime)
+
+ return { appImage: expected }
+}
+
+function readArg(name) {
+ const index = process.argv.indexOf(name)
+ return index >= 0 ? process.argv[index + 1] : undefined
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const result = await verifyAppimageArtifact({
+ directory: path.resolve(readArg('--dir') ?? 'release'),
+ version:
+ readArg('--version') ?? process.env.GITHUB_REF_NAME?.replace(/^v/, ''),
+ arch: readArg('--arch'),
+ })
+ console.log(`Verified AppImage ${result.appImage}`)
+}
diff --git a/scripts/verify-update-artifacts.mjs b/scripts/verify-update-artifacts.mjs
index 241dad0b..9616dadc 100644
--- a/scripts/verify-update-artifacts.mjs
+++ b/scripts/verify-update-artifacts.mjs
@@ -12,12 +12,12 @@ const MANIFEST_PLATFORMS = [
{
suffix: '-linux',
legacyExtension: '.deb',
- requiredExtensions: ['.deb', '.rpm'],
+ requiredExtensions: ['.deb', '.rpm', '.AppImage'],
},
{
suffix: '-linux-arm64',
legacyExtension: '.deb',
- requiredExtensions: ['.deb', '.rpm'],
+ requiredExtensions: ['.deb', '.rpm', '.AppImage'],
},
]
diff --git a/src/main/index.ts b/src/main/index.ts
index 2ce86828..852d2650 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -151,6 +151,7 @@ import { MenuRegistry } from './menu/menu-registry'
import { createNatManager } from './nat/nat-manager-factory'
import { createOsNotificationBridge } from './notifications/os-bridge'
import { DisclaimerGate } from './onboarding/disclaimer-gate'
+import { setupAppImageIntegration } from './platform/appimage-integration-host'
import { syncAutoLaunch } from './platform/auto-launch'
import { removePathRecursive, renameAtomic } from './platform/fs-helpers'
import { setupNativeThemeSync } from './platform/native-theme-sync'
@@ -562,6 +563,9 @@ const protocolManager = createProtocolManager({
getWindow: () => windowManager?.get('main') ?? null,
settingsManager,
torrentParser,
+ // In an AppImage, appimage-integration owns the scheme defaults; don't let
+ // Electron's setAsDefaultProtocolClient race it (see ProtocolManagerDeps).
+ isAppImage: process.platform === 'linux' && Boolean(process.env.APPIMAGE),
// External URL clicks (magnet/http(s)/ftp and
// motrix://new-task?uri=...) open add-task with Links prefilled.
onOpenAddTask: (params) => {
@@ -1443,6 +1447,15 @@ async function initializeMainProcess(): Promise<void> {
syncAutoLaunch(settingsManager.getApp().launchAtStartup)
protocolManager.register()
+ // Linux AppImage self-integration (desktop entry, icon, URL-scheme handlers).
+ // No-op on other platforms/packagings; deferred so the one-time consent
+ // dialog never blocks startup.
+ runShellAsyncWork('appimage-integration', () =>
+ setupAppImageIntegration({
+ getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
+ })
+ )
+
// ── Phase 2: Initialize services while renderer loads ─────
// The renderer needs time to load JS bundles and render React.
// Use that window to set up IPC handlers and core services.
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index d9ddcb22..39763c1c 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -90,6 +90,10 @@ import type { CliToolService } from '../cli/cli-tool-service'
import { MenuContextPatchSchema } from '../commands/context-schema'
import type { ContextStore } from '../commands/context-store'
import type { UpdateManager } from '../core/update-manager'
+import {
+ enableAppImageIntegrationFromSettings,
+ removeAppImageIntegrationFromSettings,
+} from '../platform/appimage-integration-host'
import { syncAutoLaunch } from '../platform/auto-launch'
import type { createProtocolManager } from '../platform/protocol-manager'
import type { createMainProxyApplier } from '../proxy/wiring'
@@ -1045,6 +1049,16 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return { ok: true }
},
+ [Commands.EnableAppImageIntegration]: async () =>
+ enableAppImageIntegrationFromSettings({
+ getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
+ }),
+
+ [Commands.RemoveAppImageIntegration]: async () =>
+ removeAppImageIntegrationFromSettings({
+ getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
+ }),
+
[Commands.RequestDefaultTorrentHandler]: async () => {
if (process.platform === 'darwin') {
// macOS has no central default-apps panel. The previous implementation
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index f10a97fc..70220ce8 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -45,6 +45,7 @@ import type { TuningContext } from '@shared/types/tuning'
import { ipcMain, session } from 'electron'
import type { CliToolService } from '../cli/cli-tool-service'
import type { UpdateManager } from '../core/update-manager'
+import { getAppImageIntegrationView } from '../platform/appimage-integration-host'
import { makeElectronFfmpegDetect } from '../plugin/ffmpeg-detect-electron'
import { createGetEngineTaskOptionsHandler } from './queries/get-engine-task-options'
import { createGetGeoIPStatusHandler } from './queries/get-geo-ip-status'
@@ -169,6 +170,9 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
return parseElectronProxyChain(chain)
},
+ [Queries.GetAppImageIntegrationStatus]: async () =>
+ getAppImageIntegrationView(),
+
[Queries.GetEngineStatus]: async () => {
return supervisor.getStatus()
},
diff --git a/src/main/platform/appimage-integration-host.ts b/src/main/platform/appimage-integration-host.ts
new file mode 100644
index 00000000..aa258cb5
--- /dev/null
+++ b/src/main/platform/appimage-integration-host.ts
@@ -0,0 +1,214 @@
+import { execFile } from 'node:child_process'
+import { copyFile, mkdir, readFile, rm } from 'node:fs/promises'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { getLogger } from '@core/logger'
+import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
+import { app, dialog } from 'electron'
+import writeFileAtomic from 'write-file-atomic'
+import { i18n } from '../lib/i18n'
+import {
+ type AppImageIntegrationDeps,
+ type CommandResult,
+ DEFAULT_INTEGRATION_RECORD,
+ enableSystemIntegration,
+ type IntegrationFs,
+ type IntegrationRecord,
+ type IntegrationStore,
+ parseIntegrationRecord,
+ removeSystemIntegration,
+ runStartupIntegration,
+} from './appimage-integration'
+
+// Electron/Node adapter for the AppImage desktop integration. The core state
+// machine in `appimage-integration.ts` is port-only and fully unit-tested; this
+// file supplies the real filesystem, `xdg-*` runner, persisted store, consent
+// dialog, and startup guard.
+
+const execFileAsync = promisify(execFile)
+
+const INTEGRATION_FILE = 'appimage-integration.json'
+const ICON_RESOURCE = path.join('icons', 'motrix-appimage-256.png')
+const COMMAND_TIMEOUT_MS = 10_000
+
+function createFileIntegrationStore(filePath: string): IntegrationStore {
+ return {
+ async load() {
+ try {
+ const raw = await readFile(filePath, 'utf-8')
+ return parseIntegrationRecord(JSON.parse(raw))
+ } catch {
+ return { ...DEFAULT_INTEGRATION_RECORD }
+ }
+ },
+ async save(record: IntegrationRecord) {
+ await mkdir(path.dirname(filePath), { recursive: true })
+ await writeFileAtomic(filePath, JSON.stringify(record, null, 2), {
+ encoding: 'utf-8',
+ })
+ },
+ }
+}
+
+const hostFs: IntegrationFs = {
+ // Atomic write (temp + rename): never leaves a partially-written desktop
+ // entry, and does not follow a dangling symlink squatting the target path.
+ writeText: (filePath, data) =>
+ writeFileAtomic(filePath, data, { encoding: 'utf-8' }),
+ readText: (filePath) => readFile(filePath, 'utf-8'),
+ readBytes: (filePath) => readFile(filePath),
+ remove: (filePath) => rm(filePath, { force: true }),
+ mkdirp: async (dirPath) => {
+ await mkdir(dirPath, { recursive: true })
+ },
+ copyFile: (src, dest) => copyFile(src, dest),
+}
+
+async function runCommand(
+ command: string,
+ args: string[]
+): Promise<CommandResult> {
+ try {
+ const { stdout, stderr } = await execFileAsync(command, args, {
+ timeout: COMMAND_TIMEOUT_MS,
+ })
+ return { code: 0, stdout: String(stdout), stderr: String(stderr) }
+ } catch (err) {
+ const e = err as NodeJS.ErrnoException & {
+ code?: number | string
+ stdout?: string
+ stderr?: string
+ }
+ const numericCode = typeof e.code === 'number' ? e.code : 127
+ return {
+ code: numericCode,
+ stdout: String(e.stdout ?? ''),
+ stderr: String(e.stderr ?? ''),
+ }
+ }
+}
+
+export interface SetupAppImageIntegrationOptions {
+ getMagnetEnabled: () => boolean
+}
+
+// The AppImage environment gate: `process.env.APPIMAGE` is only set by the
+// AppImage runtime, and only a packaged Linux build can be one.
+function appImageEnvironmentPath(): string | null {
+ if (process.platform !== 'linux' || !app.isPackaged) return null
+ return process.env.APPIMAGE ?? null
+}
+
+function createHostStore(): IntegrationStore {
+ return createFileIntegrationStore(
+ path.join(app.getPath('userData'), INTEGRATION_FILE)
+ )
+}
+
+// One deps assembly shared by the startup path and the settings IPC entry
+// points; only the consent prompt differs (startup shows the dialog, a manual
+// settings action *is* the consent).
+function buildDeps(
+ appImagePath: string,
+ opts: SetupAppImageIntegrationOptions,
+ prompt: () => Promise<boolean>
+): AppImageIntegrationDeps {
+ return {
+ appImagePath,
+ env: process.env,
+ homedir: app.getPath('home'),
+ iconSourcePath: path.join(process.resourcesPath, ICON_RESOURCE),
+ store: createHostStore(),
+ fs: hostFs,
+ runCommand,
+ getMagnetEnabled: opts.getMagnetEnabled,
+ prompt,
+ log: getLogger('appimage'),
+ }
+}
+
+async function promptWithDialog(): Promise<boolean> {
+ const { response } = await dialog.showMessageBox({
+ type: 'question',
+ buttons: [
+ i18n.t('settings.integration.appimage.prompt.decline'),
+ i18n.t('settings.integration.appimage.prompt.accept'),
+ ],
+ defaultId: 1,
+ cancelId: 0,
+ title: i18n.t('settings.integration.appimage.prompt.title'),
+ message: i18n.t('settings.integration.appimage.prompt.message'),
+ detail: i18n.t('settings.integration.appimage.prompt.detail'),
+ })
+ return response === 1
+}
+
+function toView(record: IntegrationRecord): AppImageIntegrationView {
+ return {
+ supported: true,
+ decision: record.decision,
+ owner: record.owner,
+ status: record.status,
+ }
+}
+
+// Startup entry point wired from main/index.ts. No-op unless running as a
+// packaged Linux AppImage. Never throws into the caller.
+export async function setupAppImageIntegration(
+ opts: SetupAppImageIntegrationOptions
+): Promise<void> {
+ const appImagePath = appImageEnvironmentPath()
+ if (!appImagePath) return
+ const deps = buildDeps(appImagePath, opts, promptWithDialog)
+ try {
+ await runStartupIntegration(deps)
+ } catch (err) {
+ deps.log.warn({ err }, 'appimage desktop integration failed')
+ }
+}
+
+// Settings status query (Queries.GetAppImageIntegrationStatus): reads the
+// persisted record without running any integration step.
+export async function getAppImageIntegrationView(): Promise<AppImageIntegrationView> {
+ if (!appImageEnvironmentPath()) return { supported: false }
+ return toView(await createHostStore().load())
+}
+
+// Settings action (Commands.EnableAppImageIntegration). The user clicked the
+// enable button, so consent is already given — no dialog. Runs the full
+// install transaction, including from a previously `declined` state.
+export async function enableAppImageIntegrationFromSettings(
+ opts: SetupAppImageIntegrationOptions
+): Promise<AppImageIntegrationView> {
+ const appImagePath = appImageEnvironmentPath()
+ if (!appImagePath) return { supported: false }
+ const deps = buildDeps(appImagePath, opts, async () => true)
+ try {
+ return toView(await enableSystemIntegration(deps))
+ } catch (err) {
+ deps.log.warn({ err }, 'manual appimage integration enable failed')
+ return toView(await deps.store.load())
+ }
+}
+
+// Settings action (Commands.RemoveAppImageIntegration). Externally-owned
+// integrations are left untouched by the core module; the refreshed view
+// reports that state back to the UI.
+export async function removeAppImageIntegrationFromSettings(
+ opts: SetupAppImageIntegrationOptions
+): Promise<AppImageIntegrationView> {
+ const appImagePath = appImageEnvironmentPath()
+ if (!appImagePath) return { supported: false }
+ const deps = buildDeps(appImagePath, opts, async () => true)
+ try {
+ return toView(await removeSystemIntegration(deps))
+ } catch (err) {
+ deps.log.warn({ err }, 'manual appimage integration removal failed')
+ return toView(await deps.store.load())
+ }
+}
+
+// TODO(Layer 3a): the browser bridge unconditionally syncs native-messaging
+// manifests on startup (src/main/bridge/index.ts:648). That sync must become
+// gated on this module's `nmConsent` once Layer 3a lands, so an AppImage that
+// declined desktop integration never writes NM manifests. Not changed here.
diff --git a/src/main/platform/appimage-integration.test.ts b/src/main/platform/appimage-integration.test.ts
new file mode 100644
index 00000000..ba5ce231
--- /dev/null
+++ b/src/main/platform/appimage-integration.test.ts
@@ -0,0 +1,1250 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import {
+ buildDesktopEntry,
+ classifyDefaultHandler,
+ classifyDesktopFile,
+ DEFAULT_INTEGRATION_RECORD,
+ DESKTOP_ENTRY_ID,
+ desktopEntryFilePath,
+ enableSystemIntegration,
+ execTargetsAppImage,
+ type IntegrationFs,
+ type IntegrationRecord,
+ type IntegrationStore,
+ iconFilePath,
+ isOwnedBySelf,
+ isSafeAppImagePath,
+ isSafeDesktopId,
+ OWNERSHIP_ID_KEY,
+ OWNERSHIP_MARKER_KEY,
+ OWNERSHIP_MARKER_VALUE,
+ parseDesktopEntry,
+ parseExecValue,
+ parseIntegrationRecord,
+ removeSystemIntegration,
+ resolveXdgDataHome,
+ runStartupIntegration,
+ serializeExecValue,
+ sha256Hex,
+ UnsafeAppImagePathError,
+} from './appimage-integration'
+
+// ── Test doubles ────────────────────────────────────────
+
+// A fixed installId so tests can build files that our ownership check accepts.
+const TEST_INSTALL_ID = 'test-install-id-0001'
+
+function ownedEntry(
+ appImagePath: string,
+ installId: string = TEST_INSTALL_ID
+): string {
+ return buildDesktopEntry({ appImagePath, installId })
+}
+
+function createFakeStore(
+ initial?: Partial<IntegrationRecord>
+): IntegrationStore & {
+ record: IntegrationRecord
+} {
+ const state = {
+ record: parseIntegrationRecord({
+ ...DEFAULT_INTEGRATION_RECORD,
+ ...initial,
+ }),
+ }
+ return {
+ get record() {
+ return state.record
+ },
+ load: vi.fn(async () => state.record),
+ save: vi.fn(async (next: IntegrationRecord) => {
+ state.record = next
+ }),
+ }
+}
+
+function createFakeFs(
+ seed: Record<string, string> = {},
+ // Paths that "exist" but throw a non-ENOENT error on read (e.g. permission
+ // denied) — used to prove we never clobber an unreadable foreign file.
+ unreadable: Set<string> = new Set()
+): IntegrationFs & {
+ files: Map<string, string>
+} {
+ const files = new Map<string, string>(Object.entries(seed))
+ return {
+ files,
+ writeText: vi.fn(async (p: string, data: string) => {
+ files.set(p, data)
+ }),
+ readText: vi.fn(async (p: string) => {
+ if (unreadable.has(p))
+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' })
+ const value = files.get(p)
+ if (value === undefined) throw new Error(`ENOENT: ${p}`)
+ return value
+ }),
+ readBytes: vi.fn(async (p: string) => {
+ if (unreadable.has(p))
+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' })
+ const value = files.get(p)
+ if (value === undefined) throw new Error(`ENOENT: ${p}`)
+ return new TextEncoder().encode(value)
+ }),
+ remove: vi.fn(async (p: string) => {
+ files.delete(p)
+ }),
+ mkdirp: vi.fn(async () => {}),
+ copyFile: vi.fn(async (src: string, dest: string) => {
+ const value = files.get(src)
+ if (value === undefined) throw new Error(`ENOENT: ${src}`)
+ files.set(dest, value)
+ }),
+ }
+}
+
+interface FakeXdg {
+ runCommand: (
+ command: string,
+ args: string[]
+ ) => Promise<{
+ code: number
+ stdout: string
+ stderr: string
+ }>
+ defaults: Map<string, string>
+ calls: Array<{ command: string; args: string[] }>
+}
+
+function createFakeXdg(
+ initialDefaults: Record<string, string> = {},
+ // `setIsNoop`: the `default` command reports success but does not change the
+ // stored default (models a silent desktop-policy refusal). `setReturnsCode`:
+ // the `default` command fails with this exit code (and does not apply).
+ // `queryReturnsCode`: the `query default` command fails with this exit code
+ // (models a missing/timed-out `xdg-mime`).
+ opts: {
+ setIsNoop?: boolean
+ setReturnsCode?: number
+ queryReturnsCode?: number
+ } = {}
+): FakeXdg {
+ const defaults = new Map<string, string>(Object.entries(initialDefaults))
+ const calls: FakeXdg['calls'] = []
+ return {
+ defaults,
+ calls,
+ runCommand: vi.fn(async (command: string, args: string[]) => {
+ calls.push({ command, args })
+ if (
+ command === 'xdg-mime' &&
+ args[0] === 'query' &&
+ args[1] === 'default'
+ ) {
+ const code = opts.queryReturnsCode ?? 0
+ return {
+ code,
+ stdout: code === 0 ? `${defaults.get(args[2]) ?? ''}\n` : '',
+ stderr: '',
+ }
+ }
+ if (command === 'xdg-mime' && args[0] === 'default') {
+ const code = opts.setReturnsCode ?? 0
+ // args: ['default', '<desktop-id>', '<mime>...']
+ if (code === 0 && !opts.setIsNoop) {
+ for (const mime of args.slice(2)) defaults.set(mime, args[1])
+ }
+ return { code, stdout: '', stderr: '' }
+ }
+ if (command === 'update-desktop-database') {
+ return { code: 0, stdout: '', stderr: '' }
+ }
+ return { code: 0, stdout: '', stderr: '' }
+ }),
+ }
+}
+
+const APPIMAGE = '/home/u/Applications/Motrix-2.0.0-x86_64.AppImage'
+const HOME = '/home/u'
+const ICON_SOURCE = '/opt/resources/icons/motrix-appimage-256.png'
+
+function baseDeps(overrides: {
+ store: IntegrationStore
+ fs: IntegrationFs
+ xdg: FakeXdg
+ env?: NodeJS.ProcessEnv
+ appImagePath?: string
+ getMagnetEnabled?: () => boolean
+ prompt?: () => Promise<boolean>
+}) {
+ return {
+ appImagePath: overrides.appImagePath ?? APPIMAGE,
+ env: overrides.env ?? {},
+ homedir: HOME,
+ iconSourcePath: ICON_SOURCE,
+ store: overrides.store,
+ fs: overrides.fs,
+ runCommand: overrides.xdg.runCommand,
+ getMagnetEnabled: overrides.getMagnetEnabled ?? (() => false),
+ prompt: overrides.prompt ?? (async () => true),
+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+ }
+}
+
+// ── Safety validators ───────────────────────────────────
+
+describe('isSafeAppImagePath', () => {
+ it('accepts ordinary absolute paths, including spaces and unicode', () => {
+ expect(isSafeAppImagePath('/home/u/Motrix.AppImage')).toBe(true)
+ expect(isSafeAppImagePath('/home/u/My Apps/Motrix.AppImage')).toBe(true)
+ expect(isSafeAppImagePath('/home/u/下载/Motrix.AppImage')).toBe(true)
+ })
+
+ it('rejects LF, CR, NUL and other control characters', () => {
+ expect(isSafeAppImagePath('/tmp/A\nExec=sh -c id\n#/x.AppImage')).toBe(
+ false
+ )
+ expect(isSafeAppImagePath('/tmp/a\rb')).toBe(false)
+ expect(isSafeAppImagePath('/tmp/a\x00b')).toBe(false)
+ expect(isSafeAppImagePath('/tmp/a\x7fb')).toBe(false)
+ expect(isSafeAppImagePath('')).toBe(false)
+ })
+})
+
+describe('isSafeDesktopId', () => {
+ it('accepts a flat *.desktop basename', () => {
+ expect(isSafeDesktopId('motrix-appimage.desktop')).toBe(true)
+ expect(isSafeDesktopId('org.mozilla.firefox.desktop')).toBe(true)
+ })
+
+ it('rejects traversal, separators, leading dash, and non-desktop ids', () => {
+ expect(isSafeDesktopId('../../etc/passwd.desktop')).toBe(false)
+ expect(isSafeDesktopId('a/b.desktop')).toBe(false)
+ expect(isSafeDesktopId('-x.desktop')).toBe(false)
+ expect(isSafeDesktopId('firefox')).toBe(false)
+ expect(isSafeDesktopId('has space.desktop')).toBe(false)
+ expect(isSafeDesktopId('')).toBe(false)
+ })
+})
+
+// ── Exec serialization ──────────────────────────────────
+
+describe('serializeExecValue / parseExecValue', () => {
+ it('leaves a simple path unquoted and round-trips', () => {
+ expect(serializeExecValue(['/usr/bin/motrix'])).toBe('/usr/bin/motrix')
+ expect(parseExecValue('/usr/bin/motrix')).toEqual(['/usr/bin/motrix'])
+ })
+
+ it('quotes and round-trips paths with spaces, quotes, backtick, $ and backslash', () => {
+ const cases = [
+ '/home/user name/Motrix.AppImage',
+ '/path/with"quote/app',
+ '/path/with`backtick/app',
+ '/path/with$dollar/app',
+ '/path/with\\backslash/app',
+ '/weird/ & ; | > < ~ ( ) # * ?/app',
+ ]
+ for (const value of cases) {
+ const serialized = serializeExecValue([value])
+ expect(parseExecValue(serialized)).toEqual([value])
+ }
+ })
+
+ it('escapes a literal percent as %% and restores it', () => {
+ const serialized = serializeExecValue(['/tmp/50%off/app'])
+ expect(serialized).toContain('%%')
+ expect(serialized).not.toMatch(/[^%]%[^%]/)
+ expect(parseExecValue(serialized)).toEqual(['/tmp/50%off/app'])
+ })
+
+ it('doubles backslashes at the string-value layer for a quoted arg', () => {
+ // FDO note: a literal backslash inside a quoted argument needs four
+ // successive backslashes in the desktop-entry file.
+ const serialized = serializeExecValue(['/a\\b'])
+ expect(serialized).toBe('"/a\\\\\\\\b"')
+ })
+
+ it('round-trips a multi-argument Exec', () => {
+ const argv = ['/home/u/My Apps/Motrix.AppImage', '--flag', 'a$b']
+ expect(parseExecValue(serializeExecValue(argv))).toEqual(argv)
+ })
+})
+
+// ── XDG resolver ────────────────────────────────────────
+
+describe('resolveXdgDataHome', () => {
+ it('uses an absolute XDG_DATA_HOME', () => {
+ expect(resolveXdgDataHome({ XDG_DATA_HOME: '/custom/share' }, HOME)).toBe(
+ '/custom/share'
+ )
+ })
+
+ it('ignores a relative XDG_DATA_HOME and falls back to ~/.local/share', () => {
+ expect(resolveXdgDataHome({ XDG_DATA_HOME: 'relative/share' }, HOME)).toBe(
+ '/home/u/.local/share'
+ )
+ })
+
+ it('falls back when XDG_DATA_HOME is unset or empty', () => {
+ expect(resolveXdgDataHome({}, HOME)).toBe('/home/u/.local/share')
+ expect(resolveXdgDataHome({ XDG_DATA_HOME: '' }, HOME)).toBe(
+ '/home/u/.local/share'
+ )
+ })
+
+ it('derives desktop and icon paths under the data home', () => {
+ const dataHome = '/custom/share'
+ expect(desktopEntryFilePath(dataHome)).toBe(
+ '/custom/share/applications/motrix-appimage.desktop'
+ )
+ expect(iconFilePath(dataHome)).toBe(
+ '/custom/share/icons/hicolor/256x256/apps/motrix-appimage.png'
+ )
+ })
+})
+
+// ── Desktop entry ───────────────────────────────────────
+
+describe('buildDesktopEntry', () => {
+ const content = ownedEntry(APPIMAGE)
+
+ it('declares all three MimeType handlers', () => {
+ const entry = parseDesktopEntry(content)
+ const mime = entry.get('MimeType') ?? ''
+ expect(mime).toContain('application/x-bittorrent')
+ expect(mime).toContain('x-scheme-handler/magnet')
+ expect(mime).toContain('x-scheme-handler/motrix')
+ })
+
+ it('carries the ownership marker, install id, icon, and window class', () => {
+ const entry = parseDesktopEntry(content)
+ expect(entry.get(OWNERSHIP_MARKER_KEY)).toBe(OWNERSHIP_MARKER_VALUE)
+ expect(entry.get(OWNERSHIP_ID_KEY)).toBe(TEST_INSTALL_ID)
+ expect(entry.get('Icon')).toBe('motrix-appimage')
+ expect(entry.get('StartupWMClass')).toBe('Motrix')
+ expect(isOwnedBySelf(entry, TEST_INSTALL_ID)).toBe(true)
+ })
+
+ it('points Exec at the AppImage and appends the %U field code literally', () => {
+ const entry = parseDesktopEntry(content)
+ const exec = entry.get('Exec') ?? ''
+ expect(exec.endsWith(' %U')).toBe(true)
+ expect(execTargetsAppImage(exec, APPIMAGE)).toBe(true)
+ })
+
+ it('escapes an AppImage path that contains a space', () => {
+ const spaced = '/home/u/My Apps/Motrix.AppImage'
+ const entry = parseDesktopEntry(ownedEntry(spaced))
+ expect(execTargetsAppImage(entry.get('Exec') ?? '', spaced)).toBe(true)
+ })
+
+ it('refuses to serialize a path with control characters (Exec injection)', () => {
+ const injected = '/tmp/A\nExec=sh -c id\n#/Motrix.AppImage'
+ expect(() =>
+ buildDesktopEntry({ appImagePath: injected, installId: TEST_INSTALL_ID })
+ ).toThrow(UnsafeAppImagePathError)
+ })
+
+ it('refuses to serialize an install id with control characters (line injection)', () => {
+ expect(() =>
+ buildDesktopEntry({
+ appImagePath: APPIMAGE,
+ installId: 'id\nExec=sh -c id',
+ })
+ ).toThrow(UnsafeAppImagePathError)
+ })
+})
+
+// ── Ownership by install id (not just the marker) ───────
+
+describe('isOwnedBySelf', () => {
+ it('requires the marker AND a matching install id', () => {
+ const entry = parseDesktopEntry(ownedEntry(APPIMAGE, 'id-A'))
+ expect(isOwnedBySelf(entry, 'id-A')).toBe(true)
+ // A foreign file that copied our marker but has a different / no id is not ours.
+ expect(isOwnedBySelf(entry, 'id-B')).toBe(false)
+ expect(isOwnedBySelf(entry, null)).toBe(false)
+ const noMarker = parseDesktopEntry(
+ `[Desktop Entry]\nExec="${APPIMAGE}" %U\n`
+ )
+ expect(isOwnedBySelf(noMarker, 'id-A')).toBe(false)
+ })
+})
+
+describe('classifyDesktopFile', () => {
+ it('returns ok for our current file, drift for our stale file', () => {
+ expect(
+ classifyDesktopFile(ownedEntry(APPIMAGE), APPIMAGE, TEST_INSTALL_ID)
+ ).toBe('ok')
+ expect(
+ classifyDesktopFile(
+ ownedEntry('/old/Motrix.AppImage'),
+ APPIMAGE,
+ TEST_INSTALL_ID
+ )
+ ).toBe('drift')
+ })
+
+ it('returns conflict for a foreign file (missing or mismatched id)', () => {
+ // marker copied but different id
+ expect(
+ classifyDesktopFile(
+ ownedEntry(APPIMAGE, 'someone-else'),
+ APPIMAGE,
+ TEST_INSTALL_ID
+ )
+ ).toBe('conflict')
+ // no marker at all
+ expect(
+ classifyDesktopFile(
+ `[Desktop Entry]\nExec="${APPIMAGE}" %U\n`,
+ APPIMAGE,
+ TEST_INSTALL_ID
+ )
+ ).toBe('conflict')
+ })
+})
+
+// ── External-owner classification ───────────────────────
+
+const EXTERNAL_ENTRY = `[Desktop Entry]\nType=Application\nExec="${APPIMAGE}" %U\n`
+
+describe('classifyDefaultHandler', () => {
+ it('classifies our own marked desktop file as self', () => {
+ const entry = parseDesktopEntry(ownedEntry(APPIMAGE))
+ expect(
+ classifyDefaultHandler({
+ handlerId: DESKTOP_ENTRY_ID,
+ resolvedEntry: entry,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('self')
+ })
+
+ it('classifies a third-party handler that launches this AppImage as external', () => {
+ const entry = parseDesktopEntry(EXTERNAL_ENTRY)
+ expect(
+ classifyDefaultHandler({
+ handlerId: 'some-launcher.desktop',
+ resolvedEntry: entry,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('external')
+ })
+
+ it('does not classify a deb Motrix or stale entry as external', () => {
+ const deb = parseDesktopEntry(
+ '[Desktop Entry]\nType=Application\nExec=/opt/Motrix/motrix %U\n'
+ )
+ expect(
+ classifyDefaultHandler({
+ handlerId: 'motrix.desktop',
+ resolvedEntry: deb,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('none')
+ expect(
+ classifyDefaultHandler({
+ handlerId: null,
+ resolvedEntry: null,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('none')
+ })
+
+ it('does not treat a handler that merely lists the path as an argument as external', () => {
+ // argv[0] is /usr/bin/echo, the AppImage is only a parameter.
+ const echo = parseDesktopEntry(
+ `[Desktop Entry]\nType=Application\nExec=/usr/bin/echo ${APPIMAGE} %U\n`
+ )
+ expect(
+ classifyDefaultHandler({
+ handlerId: 'echo.desktop',
+ resolvedEntry: echo,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('none')
+ })
+
+ it('rejects a non-Application, hidden, or unsafe-id handler', () => {
+ const notApp = parseDesktopEntry(`[Desktop Entry]\nExec="${APPIMAGE}" %U\n`)
+ expect(
+ classifyDefaultHandler({
+ handlerId: 'x.desktop',
+ resolvedEntry: notApp,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('none')
+ const hidden = parseDesktopEntry(
+ `[Desktop Entry]\nType=Application\nHidden=true\nExec="${APPIMAGE}" %U\n`
+ )
+ expect(
+ classifyDefaultHandler({
+ handlerId: 'x.desktop',
+ resolvedEntry: hidden,
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('none')
+ expect(
+ classifyDefaultHandler({
+ handlerId: '../../evil.desktop',
+ resolvedEntry: parseDesktopEntry(EXTERNAL_ENTRY),
+ appImagePath: APPIMAGE,
+ installId: TEST_INSTALL_ID,
+ })
+ ).toBe('none')
+ })
+})
+
+// ── Persisted record schema ─────────────────────────────
+
+describe('parseIntegrationRecord', () => {
+ it('returns the default record for junk input', () => {
+ expect(parseIntegrationRecord(null)).toEqual(DEFAULT_INTEGRATION_RECORD)
+ expect(parseIntegrationRecord('nope')).toEqual(DEFAULT_INTEGRATION_RECORD)
+ })
+
+ it('coerces invalid fields to safe defaults but keeps valid ones', () => {
+ const parsed = parseIntegrationRecord({
+ decision: 'accepted',
+ owner: 'weird',
+ desktopId: 'motrix-appimage.desktop',
+ status: 'nope',
+ nmConsent: 'accepted',
+ installId: 'keep-me',
+ })
+ expect(parsed.decision).toBe('accepted')
+ expect(parsed.owner).toBe(null)
+ expect(parsed.desktopId).toBe('motrix-appimage.desktop')
+ expect(parsed.status).toBe(null)
+ expect(parsed.nmConsent).toBe('accepted')
+ expect(parsed.installId).toBe('keep-me')
+ expect(parsed.iconSha256).toBe(null)
+ })
+})
+
+// ── Startup state machine ───────────────────────────────
+
+describe('runStartupIntegration', () => {
+ it('does nothing when the decision is declined', async () => {
+ const store = createFakeStore({ decision: 'declined' })
+ const fs = createFakeFs()
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.writeText).not.toHaveBeenCalled()
+ expect(fs.copyFile).not.toHaveBeenCalled()
+ expect(xdg.calls).toHaveLength(0)
+ expect(store.save).not.toHaveBeenCalled()
+ })
+
+ it('never writes or repairs when a still-present external owner is accepted', async () => {
+ const dataHome = '/home/u/.local/share'
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'external',
+ desktopId: 'other.desktop',
+ })
+ const fs = createFakeFs({
+ [`${dataHome}/applications/other.desktop`]: EXTERNAL_ENTRY,
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'other.desktop' })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.writeText).not.toHaveBeenCalled()
+ expect(store.record.owner).toBe('external')
+ })
+
+ it('re-detects when a recorded external owner has vanished', async () => {
+ // External integration recorded, but the default handler is now gone.
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'external',
+ desktopId: 'other.desktop',
+ })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg() // no default handler → external is gone
+ // Prompt refuses, so we should end up declined rather than stuck healthy.
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, prompt: async () => false })
+ )
+ expect(store.record.decision).toBe('declined')
+ expect(store.record.owner).toBe(null)
+ })
+
+ it('records an external owner when a verified third-party handler exists', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const dataHome = '/home/u/.local/share'
+ const fs = createFakeFs({
+ [`${dataHome}/applications/thirdparty.desktop`]: EXTERNAL_ENTRY,
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': 'thirdparty.desktop',
+ })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(store.record.decision).toBe('accepted')
+ expect(store.record.owner).toBe('external')
+ expect(store.record.desktopId).toBe('thirdparty.desktop')
+ expect(fs.writeText).not.toHaveBeenCalled()
+ })
+
+ it('prompts and installs self integration on accept, in transactional order', async () => {
+ const dataHome0 = '/home/u/.local/share'
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({
+ [ICON_SOURCE]: 'PNGDATA',
+ // A real prior handler file, so it is eligible to be recorded as the
+ // previous default (a phantom id would not be).
+ [`${dataHome0}/applications/firefox.desktop`]:
+ '[Desktop Entry]\nType=Application\nExec=/usr/bin/firefox %u\n',
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'firefox.desktop' })
+ const prompt = vi.fn(async () => true)
+ await runStartupIntegration(baseDeps({ store, fs, xdg, prompt }))
+
+ expect(prompt).toHaveBeenCalledOnce()
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const iconPath = iconFilePath(dataHome)
+ // desktop file + icon written
+ expect(fs.files.get(desktopPath)).toContain('X-Motrix-Integration=appimage')
+ expect(fs.files.get(iconPath)).toBe('PNGDATA')
+
+ // previous handler recorded before override
+ expect(store.record.previousSchemeHandler).toBe('firefox.desktop')
+ // final state healthy, self-owned, with a persisted id + icon hash
+ expect(store.record.decision).toBe('accepted')
+ expect(store.record.owner).toBe('self')
+ expect(store.record.status).toBe('healthy')
+ expect(store.record.desktopId).toBe(DESKTOP_ENTRY_ID)
+ expect(store.record.installId).toBeTruthy()
+ expect(store.record.iconSha256).toBe(sha256Hex('PNGDATA'))
+
+ // the on-disk file is owned by the persisted install id
+ expect(
+ isOwnedBySelf(
+ parseDesktopEntry(fs.files.get(desktopPath) ?? ''),
+ store.record.installId
+ )
+ ).toBe(true)
+
+ // ordering: update-desktop-database precedes the default assignment
+ const dbIndex = xdg.calls.findIndex(
+ (c) => c.command === 'update-desktop-database'
+ )
+ const setIndex = xdg.calls.findIndex(
+ (c) => c.command === 'xdg-mime' && c.args[0] === 'default'
+ )
+ expect(dbIndex).toBeGreaterThanOrEqual(0)
+ expect(setIndex).toBeGreaterThan(dbIndex)
+ // default was verified by re-query afterwards
+ expect(xdg.defaults.get('x-scheme-handler/motrix')).toBe(DESKTOP_ENTRY_ID)
+ })
+
+ it('fails closed without writing when the AppImage path has control chars', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(
+ baseDeps({
+ store,
+ fs,
+ xdg,
+ appImagePath: '/tmp/A\nExec=sh -c id\n#/Motrix.AppImage',
+ })
+ )
+ expect(fs.writeText).not.toHaveBeenCalled()
+ expect(store.record.status).toBe('failed')
+ })
+
+ it('does not overwrite a foreign file occupying our desktop path (first install)', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const foreign =
+ '[Desktop Entry]\nType=Application\nName=NotUs\nExec=/x %U\n'
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({
+ [desktopPath]: foreign,
+ [ICON_SOURCE]: 'PNGDATA',
+ })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ // untouched
+ expect(fs.files.get(desktopPath)).toBe(foreign)
+ expect(store.record.status).toBe('failed')
+ })
+
+ it('does not overwrite an existing-but-unreadable foreign desktop file', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({ decision: 'unset' })
+ // The desktop path exists but cannot be read — must be treated as a foreign
+ // file (conflict), never assumed absent and overwritten.
+ const fs = createFakeFs(
+ { [ICON_SOURCE]: 'PNGDATA', [desktopPath]: 'FOREIGN-UNREADABLE' },
+ new Set([desktopPath])
+ )
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.get(desktopPath)).toBe('FOREIGN-UNREADABLE')
+ expect(store.record.status).toBe('failed')
+ })
+
+ it('does not overwrite a foreign icon squatting our icon path', async () => {
+ const dataHome = '/home/u/.local/share'
+ const iconPath = iconFilePath(dataHome)
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({
+ [ICON_SOURCE]: 'PNGDATA',
+ [iconPath]: 'FOREIGN-ICON',
+ })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ // foreign icon preserved; not overwritten with our bytes
+ expect(fs.files.get(iconPath)).toBe('FOREIGN-ICON')
+ // and its hash was never recorded as ours
+ expect(store.record.iconSha256).not.toBe(sha256Hex('PNGDATA'))
+ })
+
+ it('does not overwrite an existing-but-unreadable foreign icon', async () => {
+ const dataHome = '/home/u/.local/share'
+ const iconPath = iconFilePath(dataHome)
+ const store = createFakeStore({ decision: 'unset' })
+ // Icon path exists but cannot be read (permission denied), so we must not
+ // assume it is absent and clobber it.
+ const fs = createFakeFs(
+ { [ICON_SOURCE]: 'PNGDATA', [iconPath]: 'FOREIGN' },
+ new Set([iconPath])
+ )
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.get(iconPath)).toBe('FOREIGN')
+ expect(fs.copyFile).not.toHaveBeenCalled()
+ })
+
+ it('does not record a phantom previous handler that has no desktop file', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ // The current default points at an id with no backing desktop file (e.g. a
+ // handler a prior Electron registration left dangling). It must not be
+ // captured as the previous handler, or removal would restore a dead default.
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'ghost.desktop' })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(store.record.previousSchemeHandler).toBe(null)
+ })
+
+ it('aborts install without touching defaults when the current default cannot be queried', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ // The query command fails, so we cannot learn the user's real handler —
+ // integration must fail closed rather than persist null and overwrite it.
+ const xdg = createFakeXdg({}, { queryReturnsCode: 1 })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(store.record.status).toBe('failed')
+ expect(fs.writeText).not.toHaveBeenCalled()
+ // no default was set
+ expect(
+ xdg.calls.some((c) => c.command === 'xdg-mime' && c.args[0] === 'default')
+ ).toBe(false)
+ })
+
+ it('captures and persists the overwritten magnet handler before claiming it', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [ICON_SOURCE]: 'PNGDATA',
+ // A real prior magnet handler we are about to override.
+ [`${dataHome}/applications/qbittorrent.desktop`]:
+ '[Desktop Entry]\nType=Application\nExec=/usr/bin/qbittorrent %u\n',
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID,
+ 'x-scheme-handler/magnet': 'qbittorrent.desktop',
+ })
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, getMagnetEnabled: () => true })
+ )
+ // The prior handler is captured as previous, and persisted BEFORE the
+ // magnet default is overridden.
+ expect(store.record.previousMagnetHandler).toBe('qbittorrent.desktop')
+ const saveWithPrev = vi
+ .mocked(store.save)
+ .mock.calls.findIndex(
+ (c) => c[0]?.previousMagnetHandler === 'qbittorrent.desktop'
+ )
+ const magnetSetCallIndex = xdg.calls.findIndex(
+ (c) =>
+ c.command === 'xdg-mime' &&
+ c.args[0] === 'default' &&
+ c.args[2] === 'x-scheme-handler/magnet'
+ )
+ expect(saveWithPrev).toBeGreaterThanOrEqual(0)
+ expect(magnetSetCallIndex).toBeGreaterThanOrEqual(0)
+ const saveOrder = vi.mocked(store.save).mock.invocationCallOrder[
+ saveWithPrev
+ ]
+ const setOrder = vi.mocked(xdg.runCommand).mock.invocationCallOrder[
+ magnetSetCallIndex
+ ]
+ expect(saveOrder).toBeLessThan(setOrder)
+ expect(xdg.defaults.get('x-scheme-handler/magnet')).toBe(DESKTOP_ENTRY_ID)
+ })
+
+ it('claims the magnet default at startup when the setting is enabled (AppImage convergence)', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [ICON_SOURCE]: 'PNGDATA',
+ })
+ // Desktop is current (ok), but magnet default is not ours yet.
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, getMagnetEnabled: () => true })
+ )
+ expect(xdg.defaults.get('x-scheme-handler/magnet')).toBe(DESKTOP_ENTRY_ID)
+ })
+
+ it('hands the magnet default back at startup when the setting is disabled', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ previousMagnetHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [ICON_SOURCE]: 'PNGDATA',
+ // The prior handler must still resolve for restore to proceed.
+ [`${dataHome}/applications/firefox.desktop`]:
+ '[Desktop Entry]\nType=Application\nExec=/usr/bin/firefox %u\n',
+ })
+ // Both defaults currently ours; magnet setting is now off → magnet reverts.
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID,
+ 'x-scheme-handler/magnet': DESKTOP_ENTRY_ID,
+ })
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, getMagnetEnabled: () => false })
+ )
+ expect(xdg.defaults.get('x-scheme-handler/magnet')).toBe('firefox.desktop')
+ // the scheme default stays ours
+ expect(xdg.defaults.get('x-scheme-handler/motrix')).toBe(DESKTOP_ENTRY_ID)
+ })
+
+ it('persists the install id before writing files (crash recovery)', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ // The first store.save carrying a non-null installId must happen before the
+ // desktop file is ever written, so a crash cannot orphan our own file.
+ const save = vi.mocked(store.save)
+ const write = vi.mocked(fs.writeText)
+ const firstIdSaveIndex = save.mock.calls.findIndex(
+ (c) => c[0]?.installId != null
+ )
+ expect(firstIdSaveIndex).toBeGreaterThanOrEqual(0)
+ expect(save.mock.invocationCallOrder[firstIdSaveIndex]).toBeLessThan(
+ write.mock.invocationCallOrder[0]
+ )
+ })
+
+ it('regenerates an unsafe persisted install id instead of writing it', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'failed',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: 'bad\nExec=sh -c id',
+ })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ const content = fs.files.get(desktopPath) ?? ''
+ // The written file must not contain the injected line, and must be healthy.
+ expect(content).not.toContain('Exec=sh -c id')
+ expect(store.record.installId).not.toContain('\n')
+ expect(store.record.status).toBe('healthy')
+ })
+
+ it('sets the magnet default only when the magnet setting is enabled', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, getMagnetEnabled: () => true })
+ )
+ expect(xdg.defaults.get('x-scheme-handler/magnet')).toBe(DESKTOP_ENTRY_ID)
+ })
+
+ it('leaves the magnet default untouched when the setting is disabled', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg({ 'x-scheme-handler/magnet': 'other.desktop' })
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, getMagnetEnabled: () => false })
+ )
+ expect(xdg.defaults.get('x-scheme-handler/magnet')).toBe('other.desktop')
+ })
+
+ it('records status failed when the default cannot be verified', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg({}, { setIsNoop: true })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(store.record.status).toBe('failed')
+ })
+
+ it('records declined without writing when the prompt is refused', async () => {
+ const store = createFakeStore({ decision: 'unset' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, prompt: async () => false })
+ )
+ expect(store.record.decision).toBe('declined')
+ expect(fs.writeText).not.toHaveBeenCalled()
+ })
+
+ it('silently rewrites a self-owned desktop file whose Exec drifted', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const stale = ownedEntry('/old/Motrix.AppImage')
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({ [desktopPath]: stale, [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(
+ execTargetsAppImage(
+ parseDesktopEntry(fs.files.get(desktopPath) ?? '').get('Exec') ?? '',
+ APPIMAGE
+ )
+ ).toBe(true)
+ })
+
+ it('does not overwrite a foreign file during self-heal (ownership conflict)', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ // our marker but a DIFFERENT install id → not ours.
+ const foreign = ownedEntry(APPIMAGE, 'someone-else')
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({
+ [desktopPath]: foreign,
+ [ICON_SOURCE]: 'PNGDATA',
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.get(desktopPath)).toBe(foreign) // untouched
+ expect(store.record.status).toBe('failed')
+ })
+
+ it('does not rewrite a self-owned desktop file that is already current', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const current = ownedEntry(APPIMAGE)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({
+ [desktopPath]: current,
+ [ICON_SOURCE]: 'PNGDATA',
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.writeText).not.toHaveBeenCalled()
+ })
+
+ it('retries the full install when a self-owned record is marked failed', async () => {
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'failed',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await runStartupIntegration(baseDeps({ store, fs, xdg }))
+ const dataHome = '/home/u/.local/share'
+ expect(fs.files.get(desktopEntryFilePath(dataHome))).toContain(
+ 'X-Motrix-Integration=appimage'
+ )
+ expect(store.record.status).toBe('healthy')
+ })
+})
+
+// ── Manual enable / removal ─────────────────────────────
+
+describe('enableSystemIntegration', () => {
+ it('installs self integration regardless of a prior declined decision', async () => {
+ const store = createFakeStore({ decision: 'declined' })
+ const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
+ const xdg = createFakeXdg()
+ await enableSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(store.record.decision).toBe('accepted')
+ expect(store.record.owner).toBe('self')
+ })
+})
+
+describe('removeSystemIntegration', () => {
+ it('is a no-op for an externally-owned integration', async () => {
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'external',
+ desktopId: 'motrix.desktop',
+ status: 'healthy',
+ })
+ const fs = createFakeFs()
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'motrix.desktop' })
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(next.decision).toBe('accepted')
+ expect(next.owner).toBe('external')
+ expect(store.record.owner).toBe('external')
+ expect(xdg.calls).toEqual([])
+ expect(fs.remove).not.toHaveBeenCalled()
+ })
+
+ it('reverses the install: deletes owned files, restores default, sets declined', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const iconPath = iconFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ iconSha256: sha256Hex('PNGDATA'),
+ previousSchemeHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [iconPath]: 'PNGDATA',
+ // The recorded previous handler must still resolve for restore to run.
+ [`${dataHome}/applications/firefox.desktop`]:
+ '[Desktop Entry]\nType=Application\nExec=/usr/bin/firefox %u\n',
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.has(desktopPath)).toBe(false)
+ expect(fs.files.has(iconPath)).toBe(false)
+ expect(xdg.defaults.get('x-scheme-handler/motrix')).toBe('firefox.desktop')
+ expect(store.record.decision).toBe('declined')
+ expect(store.record.owner).toBe(null)
+ })
+
+ it('does not restore the default when it is no longer owned by Motrix', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ previousSchemeHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'chromium.desktop' })
+ await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ // still chromium — we must not clobber a handler the user re-pointed
+ expect(xdg.defaults.get('x-scheme-handler/motrix')).toBe('chromium.desktop')
+ })
+
+ it('only deletes a desktop file that is verifiably ours', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ // marker copied but a different install id → foreign, must be preserved.
+ const foreign = ownedEntry(APPIMAGE, 'someone-else')
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ previousSchemeHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({ [desktopPath]: foreign })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'firefox.desktop' })
+ await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.has(desktopPath)).toBe(true)
+ })
+
+ it('does not delete an icon whose bytes no longer match what we installed', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const iconPath = iconFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ iconSha256: sha256Hex('ORIGINAL-ICON'),
+ previousSchemeHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [iconPath]: 'USER-REPLACED-THIS',
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.has(iconPath)).toBe(true) // preserved
+ })
+
+ it('keeps the desktop file and stays failed when the default cannot be restored', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const iconPath = iconFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ iconSha256: sha256Hex('PNGDATA'),
+ previousSchemeHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [iconPath]: 'PNGDATA',
+ })
+ // The `default` command fails, so the restore cannot be verified.
+ const xdg = createFakeXdg(
+ { 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID },
+ { setReturnsCode: 1 }
+ )
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ // desktop kept so the default is not left dangling
+ expect(fs.files.has(desktopPath)).toBe(true)
+ expect(next.status).toBe('failed')
+ expect(next.decision).toBe('accepted')
+ })
+
+ it('keeps the desktop file when the current default cannot be queried', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ previousSchemeHandler: 'firefox.desktop',
+ })
+ const fs = createFakeFs({ [desktopPath]: ownedEntry(APPIMAGE) })
+ // The `query default` command itself fails — we cannot confirm the default
+ // is no longer ours, so deletion must be blocked.
+ const xdg = createFakeXdg(
+ { 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID },
+ { queryReturnsCode: 1 }
+ )
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.has(desktopPath)).toBe(true)
+ expect(next.status).toBe('failed')
+ })
+
+ it('keeps the desktop file when the recorded previous handler no longer resolves', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ // Recorded as previous, but the desktop file has since been uninstalled.
+ previousSchemeHandler: 'gone.desktop',
+ })
+ const fs = createFakeFs({ [desktopPath]: ownedEntry(APPIMAGE) })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ // must not restore to a dead handler, and must not delete our own desktop
+ expect(fs.files.has(desktopPath)).toBe(true)
+ expect(next.status).toBe('failed')
+ })
+
+ it('keeps the desktop file when the previous handler exists but is not launchable', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ previousSchemeHandler: 'broken.desktop',
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ // Present but disabled / no usable Exec → must not be restored to.
+ [`${dataHome}/applications/broken.desktop`]:
+ '[Desktop Entry]\nType=Application\nHidden=true\nExec=/x\n',
+ })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.has(desktopPath)).toBe(true)
+ expect(next.status).toBe('failed')
+ })
+
+ it('keeps the desktop file when there is no recorded previous handler to restore', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ previousSchemeHandler: null,
+ })
+ const fs = createFakeFs({ [desktopPath]: ownedEntry(APPIMAGE) })
+ const xdg = createFakeXdg({ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID })
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+ expect(fs.files.has(desktopPath)).toBe(true)
+ expect(next.status).toBe('failed')
+ })
+})
diff --git a/src/main/platform/appimage-integration.ts b/src/main/platform/appimage-integration.ts
new file mode 100644
index 00000000..368407da
--- /dev/null
+++ b/src/main/platform/appimage-integration.ts
@@ -0,0 +1,1126 @@
+import { createHash, randomUUID } from 'node:crypto'
+import path from 'node:path'
+import type {
+ AppImageIntegrationDecision,
+ AppImageIntegrationHealth,
+ AppImageIntegrationOwner,
+} from '@shared/types/appimage-integration'
+import { z } from 'zod'
+
+// AppImage desktop self-integration (Layer 2).
+//
+// When Motrix runs as a packaged Linux AppImage it is not installed through a
+// package manager, so nothing registers its desktop entry, icon, or the URL
+// scheme / mime handlers a browser needs to hand downloads back to it. This
+// module owns an opt-in, self-healing integration into the user-scope XDG data
+// tree. Everything here is pure or takes injected ports (`IntegrationFs`,
+// `CommandRunner`, `IntegrationStore`, `prompt`) so the whole state machine is
+// unit-testable without touching the real filesystem or spawning `xdg-*`.
+//
+// Scope boundary: this is desktop integration only. Native-messaging host
+// installation (Layer 3a) is intentionally NOT performed here — the `nmConsent`
+// sub-consent is threaded through the record and the transaction leaves marked
+// TODO seams where the NM copy/sync steps will slot in.
+
+// ── Persisted record ────────────────────────────────────
+
+// The decision/owner/health unions are shared with the renderer-facing view
+// (`AppImageIntegrationView`), so they live in the shared contract layer.
+export type IntegrationDecision = AppImageIntegrationDecision
+export type IntegrationOwner = AppImageIntegrationOwner
+export type IntegrationStatus = AppImageIntegrationHealth
+export type NmConsent = 'unset' | 'accepted' | 'declined'
+
+export interface IntegrationRecord {
+ decision: IntegrationDecision
+ owner: IntegrationOwner
+ desktopId: string | null
+ status: IntegrationStatus
+ // Dependent sub-consent for native-messaging host installation (Layer 3a).
+ // Only meaningful once `decision === 'accepted'`; `declined` means no NM
+ // writes ever happen.
+ nmConsent: NmConsent
+ // The scheme/mime default handlers recorded before we overrode them, so a
+ // later removal can restore what the user had.
+ previousSchemeHandler: string | null
+ previousMagnetHandler: string | null
+ // Random per-install id embedded in our desktop entry as an ownership proof.
+ // A copyable marker key alone cannot prove WE wrote a file (a foreign file
+ // can carry the same marker); the id, generated once and known only from our
+ // own persisted record, distinguishes our entry from another AppImage
+ // install writing the same fixed filename, and gates every overwrite/delete.
+ installId: string | null
+ // sha256 of the icon bytes we last wrote, so removal only deletes an icon
+ // that still matches what we installed (an icon file carries no marker).
+ iconSha256: string | null
+}
+
+export const DEFAULT_INTEGRATION_RECORD: IntegrationRecord = {
+ decision: 'unset',
+ owner: null,
+ desktopId: null,
+ status: null,
+ nmConsent: 'unset',
+ previousSchemeHandler: null,
+ previousMagnetHandler: null,
+ installId: null,
+ iconSha256: null,
+}
+
+const integrationRecordSchema = z
+ .object({
+ decision: z
+ .enum(['unset', 'accepted', 'declined'])
+ .catch(DEFAULT_INTEGRATION_RECORD.decision),
+ owner: z
+ .enum(['self', 'external'])
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.owner),
+ desktopId: z
+ .string()
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.desktopId),
+ status: z
+ .enum(['healthy', 'failed'])
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.status),
+ nmConsent: z
+ .enum(['unset', 'accepted', 'declined'])
+ .catch(DEFAULT_INTEGRATION_RECORD.nmConsent),
+ previousSchemeHandler: z
+ .string()
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.previousSchemeHandler),
+ previousMagnetHandler: z
+ .string()
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.previousMagnetHandler),
+ installId: z
+ .string()
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.installId),
+ iconSha256: z
+ .string()
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.iconSha256),
+ })
+ .catch(DEFAULT_INTEGRATION_RECORD)
+
+export function parseIntegrationRecord(value: unknown): IntegrationRecord {
+ return integrationRecordSchema.parse(value)
+}
+
+// ── Identity / paths ────────────────────────────────────
+
+// Deliberately unique names so removal never touches a `motrix.desktop` or icon
+// installed by a deb/rpm/Flatpak alongside this AppImage.
+export const DESKTOP_ENTRY_ID = 'motrix-appimage.desktop'
+export const ICON_NAME = 'motrix-appimage'
+export const OWNERSHIP_MARKER_KEY = 'X-Motrix-Integration'
+export const OWNERSHIP_MARKER_VALUE = 'appimage'
+// Per-install ownership proof embedded alongside the marker (see IntegrationRecord.installId).
+export const OWNERSHIP_ID_KEY = 'X-Motrix-Integration-Id'
+
+export function sha256Hex(data: string | Uint8Array): string {
+ return createHash('sha256').update(data).digest('hex')
+}
+
+// A path is unsafe to serialize into a `.desktop` file if it carries any C0
+// control character — most importantly LF/CR, which would let a crafted
+// $APPIMAGE path inject a second `Exec=` line (a last-key-wins desktop parser
+// would then run the injected command). Reject rather than try to escape.
+// biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting C0 controls is the point
+const CONTROL_CHARS = /[\x00-\x1f\x7f]/
+export function isSafeAppImagePath(value: string): boolean {
+ return value.length > 0 && !CONTROL_CHARS.test(value)
+}
+
+// A desktop id is safe to hand to `xdg-mime` / to resolve on the filesystem
+// only if it is a flat `*.desktop` basename: no path separators, no `..`, no
+// leading `-` (which some `xdg-mime` builds would parse as an option), and no
+// control/whitespace characters.
+export function isSafeDesktopId(id: string): boolean {
+ return (
+ id.length > 0 &&
+ id.endsWith('.desktop') &&
+ !id.includes('/') &&
+ !id.includes('\\') &&
+ !id.includes('..') &&
+ !id.startsWith('-') &&
+ !CONTROL_CHARS.test(id) &&
+ !/\s/.test(id)
+ )
+}
+
+// The install id is embedded verbatim into the desktop file, so it must never
+// carry a newline (which would inject a second key/line) or other control
+// characters. We generate UUIDs, but a tampered persisted record could hold
+// anything — validate before trusting or writing it.
+export function isSafeInstallId(id: string | null): id is string {
+ return (
+ id != null && id.length > 0 && id.length <= 128 && !CONTROL_CHARS.test(id)
+ )
+}
+
+const SCHEME_MIME = 'x-scheme-handler/motrix'
+const MAGNET_MIME = 'x-scheme-handler/magnet'
+const MIME_TYPES =
+ 'application/x-bittorrent;x-scheme-handler/magnet;x-scheme-handler/motrix;'
+
+export function resolveXdgDataHome(
+ env: NodeJS.ProcessEnv,
+ homedir: string
+): string {
+ const configured = env.XDG_DATA_HOME
+ if (configured && path.isAbsolute(configured)) return configured
+ return path.join(homedir, '.local', 'share')
+}
+
+export function applicationsDir(dataHome: string): string {
+ return path.join(dataHome, 'applications')
+}
+
+export function desktopEntryFilePath(dataHome: string): string {
+ return path.join(applicationsDir(dataHome), DESKTOP_ENTRY_ID)
+}
+
+export function iconFilePath(dataHome: string): string {
+ return path.join(
+ dataHome,
+ 'icons',
+ 'hicolor',
+ '256x256',
+ 'apps',
+ `${ICON_NAME}.png`
+ )
+}
+
+// ── Desktop Entry Exec serialization ────────────────────
+//
+// Two escaping layers per the freedesktop.org Desktop Entry spec:
+// 1. Argument quoting: an argument containing a reserved character is wrapped
+// in double quotes, and `"`, backtick, `$`, `\` inside the quotes are each
+// prefixed with a backslash.
+// 2. String-value escaping applied to the whole Exec value: literal `\`
+// becomes `\\` and the field-code introducer `%` becomes `%%`.
+// The spec mandates layer 2 is conceptually applied after layer 1, which is why
+// a literal backslash inside a quoted argument ends up as four backslashes.
+
+const EXEC_RESERVED = /[\s"'\\><~|&;$*?#()`]/
+
+function quoteExecArg(arg: string): string {
+ if (!EXEC_RESERVED.test(arg)) return arg
+ const escaped = arg.replace(/(["`$\\])/g, '\\$1')
+ return `"${escaped}"`
+}
+
+export function serializeExecValue(argv: string[]): string {
+ const quoted = argv.map(quoteExecArg).join(' ')
+ return quoted.replace(/\\/g, '\\\\').replace(/%/g, '%%')
+}
+
+// Reverse of `serializeExecValue`, plus tolerant handling of standalone field
+// codes (`%U`, `%f`, …) so a full `Exec=` line can be tokenized. Field-code
+// tokens are dropped from the returned argv.
+export function parseExecValue(value: string): string[] {
+ // Undo the string-value layer first: collapse `\\`→`\` and `%%`→`%` in a
+ // single left-to-right pass so `\\\\` does not over-collapse.
+ let unescaped = ''
+ for (let i = 0; i < value.length; i++) {
+ const ch = value[i]
+ const next = value[i + 1]
+ if (ch === '\\' && next === '\\') {
+ unescaped += '\\'
+ i++
+ } else if (ch === '%' && next === '%') {
+ unescaped += '%'
+ i++
+ } else {
+ unescaped += ch
+ }
+ }
+
+ const args: string[] = []
+ let current = ''
+ let inQuotes = false
+ let started = false
+ for (let i = 0; i < unescaped.length; i++) {
+ const ch = unescaped[i]
+ if (inQuotes) {
+ if (ch === '\\') {
+ current += unescaped[++i] ?? ''
+ } else if (ch === '"') {
+ inQuotes = false
+ } else {
+ current += ch
+ }
+ continue
+ }
+ if (ch === '"') {
+ inQuotes = true
+ started = true
+ } else if (/\s/.test(ch)) {
+ if (started) {
+ args.push(current)
+ current = ''
+ started = false
+ }
+ } else {
+ current += ch
+ started = true
+ }
+ }
+ if (started) args.push(current)
+
+ return args.filter((arg) => !/^%[a-zA-Z]$/.test(arg))
+}
+
+// ── Desktop entry document ──────────────────────────────
+
+export interface BuildDesktopEntryOptions {
+ appImagePath: string
+ installId: string
+}
+
+export class UnsafeAppImagePathError extends Error {}
+
+export function buildDesktopEntry(opts: BuildDesktopEntryOptions): string {
+ // Defense in depth against Exec-line injection: never emit a desktop file
+ // for a path carrying control characters (LF/CR could inject a second
+ // `Exec=`). Callers gate on `isSafeAppImagePath` first; throwing here means
+ // no code path can serialize an unsafe path.
+ if (!isSafeAppImagePath(opts.appImagePath)) {
+ throw new UnsafeAppImagePathError(
+ 'refusing to build desktop entry for a path with control characters'
+ )
+ }
+ // The install id is written verbatim as its own key; a control character
+ // (e.g. a newline from a tampered state file) would inject another line.
+ if (!isSafeInstallId(opts.installId)) {
+ throw new UnsafeAppImagePathError(
+ 'refusing to build desktop entry for an unsafe install id'
+ )
+ }
+ const exec = `${serializeExecValue([opts.appImagePath])} %U`
+ const lines = [
+ '[Desktop Entry]',
+ 'Type=Application',
+ 'Name=Motrix',
+ 'GenericName=Download Manager',
+ 'Comment=Full-featured download manager',
+ `Exec=${exec}`,
+ `Icon=${ICON_NAME}`,
+ 'Terminal=false',
+ 'Categories=Network;FileTransfer;',
+ 'Keywords=download;bittorrent;magnet;aria2;',
+ `MimeType=${MIME_TYPES}`,
+ 'StartupWMClass=Motrix',
+ 'StartupNotify=true',
+ `${OWNERSHIP_MARKER_KEY}=${OWNERSHIP_MARKER_VALUE}`,
+ `${OWNERSHIP_ID_KEY}=${opts.installId}`,
+ '',
+ ]
+ return lines.join('\n')
+}
+
+// Minimal parser for the `[Desktop Entry]` group. Values are returned raw (still
+// escaped) — callers that need the Exec argv run it through `parseExecValue`.
+export function parseDesktopEntry(content: string): Map<string, string> {
+ const entries = new Map<string, string>()
+ let inGroup = false
+ for (const rawLine of content.split(/\r?\n/)) {
+ const line = rawLine.trim()
+ if (line.startsWith('[') && line.endsWith(']')) {
+ inGroup = line === '[Desktop Entry]'
+ continue
+ }
+ if (!inGroup || line === '' || line.startsWith('#')) continue
+ const eq = line.indexOf('=')
+ if (eq < 0) continue
+ const key = line.slice(0, eq).trim()
+ const value = line.slice(eq + 1).trim()
+ if (!entries.has(key)) entries.set(key, value)
+ }
+ return entries
+}
+
+// Ownership requires BOTH the marker AND the per-install id matching our own
+// persisted record. The marker alone is copyable and proves nothing; the id is
+// only known from our record, so a foreign file (another AppImage install, a
+// user-crafted file, a stale entry) is never treated as ours.
+export function isOwnedBySelf(
+ entry: Map<string, string>,
+ installId: string | null
+): boolean {
+ return (
+ installId != null &&
+ entry.get(OWNERSHIP_MARKER_KEY) === OWNERSHIP_MARKER_VALUE &&
+ entry.get(OWNERSHIP_ID_KEY) === installId
+ )
+}
+
+// The Exec launches THIS AppImage only when the program (argv[0]) IS the
+// AppImage path — not merely when the path appears somewhere in the argv (an
+// `Exec=/usr/bin/echo /path/Motrix.AppImage` handler must not count).
+export function execTargetsAppImage(
+ execValue: string,
+ appImagePath: string
+): boolean {
+ return parseExecValue(execValue)[0] === appImagePath
+}
+
+export type RewriteDecision = 'ok' | 'drift' | 'conflict'
+
+// Decide what to do with the file currently at our desktop path:
+// - `ok` it is ours and already targets the current AppImage.
+// - `drift` it is ours but the Exec points elsewhere (updated/moved
+// AppImage) — safe to rewrite in place.
+// - `conflict` it is NOT ours (missing/mismatched id) — a foreign file we
+// must never overwrite.
+export function classifyDesktopFile(
+ content: string,
+ appImagePath: string,
+ installId: string | null
+): RewriteDecision {
+ const entry = parseDesktopEntry(content)
+ if (!isOwnedBySelf(entry, installId)) return 'conflict'
+ const exec = entry.get('Exec') ?? ''
+ return execTargetsAppImage(exec, appImagePath) ? 'ok' : 'drift'
+}
+
+// ── External-owner classification ───────────────────────
+
+export interface ClassifyDefaultHandlerOptions {
+ handlerId: string | null
+ resolvedEntry: Map<string, string> | null
+ appImagePath: string
+ installId: string | null
+}
+
+// Decide who owns the current `x-scheme-handler/motrix` default. `external` is
+// only reported when the resolved desktop file is a launchable application
+// whose program (argv[0]) actually IS this AppImage — so a stale entry, a deb
+// Motrix (which points elsewhere), a disabled entry, or a handler that merely
+// mentions the path as an argument is never mistaken for a working
+// integration. The handler id must also be a safe flat `*.desktop` name.
+export function classifyDefaultHandler(
+ opts: ClassifyDefaultHandlerOptions
+): 'self' | 'external' | 'none' {
+ const { handlerId, resolvedEntry, appImagePath, installId } = opts
+ if (!handlerId || !resolvedEntry) return 'none'
+ if (!isSafeDesktopId(handlerId)) return 'none'
+ if (!isUsableHandlerEntry(resolvedEntry)) return 'none'
+ const exec = resolvedEntry.get('Exec') ?? ''
+ if (!execTargetsAppImage(exec, appImagePath)) return 'none'
+ if (
+ handlerId === DESKTOP_ENTRY_ID &&
+ isOwnedBySelf(resolvedEntry, installId)
+ ) {
+ return 'self'
+ }
+ return 'external'
+}
+
+// A recorded previous / candidate handler is only worth capturing or restoring
+// to if its desktop file is actually a launchable Application: present, not
+// `Hidden`, of `Type=Application`, and carrying a non-empty `Exec`. Restoring a
+// default to an empty/disabled/corrupt entry would just create a different dead
+// default.
+export function isUsableHandlerEntry(entry: Map<string, string>): boolean {
+ return (
+ entry.get('Type') === 'Application' &&
+ entry.get('Hidden') !== 'true' &&
+ (entry.get('Exec') ?? '').trim().length > 0
+ )
+}
+
+// ── Injected ports ──────────────────────────────────────
+
+export interface IntegrationStore {
+ load(): Promise<IntegrationRecord>
+ save(record: IntegrationRecord): Promise<void>
+}
+
+export interface IntegrationFs {
+ writeText(filePath: string, data: string): Promise<void>
+ readText(filePath: string): Promise<string>
+ // Raw bytes, for content-fingerprinting the icon (which carries no marker).
+ readBytes(filePath: string): Promise<Uint8Array>
+ remove(filePath: string): Promise<void>
+ mkdirp(dirPath: string): Promise<void>
+ copyFile(src: string, dest: string): Promise<void>
+}
+
+export interface CommandResult {
+ code: number
+ stdout: string
+ stderr: string
+}
+
+export type CommandRunner = (
+ command: string,
+ args: string[]
+) => Promise<CommandResult>
+
+export interface IntegrationLogger {
+ info(obj: unknown, msg?: string): void
+ warn(obj: unknown, msg?: string): void
+ error(obj: unknown, msg?: string): void
+}
+
+export interface AppImageIntegrationDeps {
+ appImagePath: string
+ env: NodeJS.ProcessEnv
+ homedir: string
+ iconSourcePath: string
+ store: IntegrationStore
+ fs: IntegrationFs
+ runCommand: CommandRunner
+ getMagnetEnabled: () => boolean
+ prompt: () => Promise<boolean>
+ log: IntegrationLogger
+}
+
+// ── xdg helpers ─────────────────────────────────────────
+
+// Full query result: `ok` distinguishes a successful lookup (even one that
+// returns no handler) from a failed command (non-zero/timeout/missing binary).
+// Callers that must fail safe on an uncertain state check `ok`.
+async function queryDefaultHandlerResult(
+ deps: AppImageIntegrationDeps,
+ mime: string
+): Promise<{ ok: boolean; id: string | null }> {
+ try {
+ const result = await deps.runCommand('xdg-mime', ['query', 'default', mime])
+ if (result.code !== 0) return { ok: false, id: null }
+ const id = result.stdout.trim()
+ return { ok: true, id: id.length > 0 ? id : null }
+ } catch (err) {
+ deps.log.warn({ err, mime }, 'xdg-mime query default failed')
+ return { ok: false, id: null }
+ }
+}
+
+async function queryDefaultHandler(
+ deps: AppImageIntegrationDeps,
+ mime: string
+): Promise<string | null> {
+ return (await queryDefaultHandlerResult(deps, mime)).id
+}
+
+// Set a mime default and confirm it stuck by re-querying — never assume the
+// handler is live just because the set command returned 0.
+// Point `mime`'s default handler at `targetId` and confirm it stuck by
+// re-querying — never assume the handler is live just because the set command
+// returned 0. Shared by claiming our own entry and restoring a prior handler.
+async function setDefaultAndVerify(
+ deps: AppImageIntegrationDeps,
+ mime: string,
+ targetId: string
+): Promise<boolean> {
+ try {
+ const set = await deps.runCommand('xdg-mime', ['default', targetId, mime])
+ if (set.code !== 0) return false
+ } catch (err) {
+ deps.log.warn({ err, mime, targetId }, 'xdg-mime default failed')
+ return false
+ }
+ const current = await queryDefaultHandler(deps, mime)
+ return current === targetId
+}
+
+async function updateDesktopDatabase(
+ deps: AppImageIntegrationDeps,
+ dataHome: string
+): Promise<void> {
+ try {
+ await deps.runCommand('update-desktop-database', [
+ applicationsDir(dataHome),
+ ])
+ } catch (err) {
+ // Non-fatal: the entry is still valid, only its cache lookup lags.
+ deps.log.warn({ err }, 'update-desktop-database failed')
+ }
+}
+
+// Resolve a desktop id to its parsed entry by scanning the standard
+// application directories, most-specific first.
+async function resolveDesktopEntryById(
+ deps: AppImageIntegrationDeps,
+ dataHome: string,
+ handlerId: string
+): Promise<Map<string, string> | null> {
+ // Never resolve an unsafe id: `path.join(dir, '../../x')` would escape the
+ // applications directory. Safe ids are flat `*.desktop` basenames.
+ if (!isSafeDesktopId(handlerId)) return null
+ for (const dir of desktopSearchDirs(deps.env, dataHome)) {
+ try {
+ const content = await deps.fs.readText(path.join(dir, handlerId))
+ return parseDesktopEntry(content)
+ } catch {
+ // try the next directory
+ }
+ }
+ return null
+}
+
+// True only when `handlerId` resolves to a real, launchable Application entry —
+// the guard used before recording it as a previous handler or restoring the
+// default to it.
+async function resolvesToUsableHandler(
+ deps: AppImageIntegrationDeps,
+ dataHome: string,
+ handlerId: string
+): Promise<boolean> {
+ const entry = await resolveDesktopEntryById(deps, dataHome, handlerId)
+ return entry !== null && isUsableHandlerEntry(entry)
+}
+
+function desktopSearchDirs(env: NodeJS.ProcessEnv, dataHome: string): string[] {
+ const dirs = [applicationsDir(dataHome)]
+ const dataDirs = env.XDG_DATA_DIRS?.split(':').filter(Boolean) ?? [
+ '/usr/local/share',
+ '/usr/share',
+ ]
+ for (const base of dataDirs) {
+ if (path.isAbsolute(base)) dirs.push(path.join(base, 'applications'))
+ }
+ return dirs
+}
+
+function isEnoent(err: unknown): boolean {
+ // Trust a structured errno code when present; only fall back to matching the
+ // message for errors that carry no `code` (so an EACCES on a path that merely
+ // contains the substring "ENOENT" is never mistaken for a missing file).
+ if (err && typeof err === 'object' && 'code' in err) {
+ return (err as { code?: unknown }).code === 'ENOENT'
+ }
+ return /ENOENT/.test(String((err as { message?: unknown })?.message ?? err))
+}
+
+// Read a file's bytes and hash them. `present` distinguishes a genuinely
+// absent file (ENOENT → safe to create) from one that exists but cannot be
+// read (any other error → must be treated as a foreign file we must not
+// clobber), so a hash-mismatch and an unreadable file are never conflated.
+async function readIconState(
+ fs: IntegrationFs,
+ filePath: string
+): Promise<{ present: boolean; hash: string | null }> {
+ try {
+ return { present: true, hash: sha256Hex(await fs.readBytes(filePath)) }
+ } catch (err) {
+ if (isEnoent(err)) return { present: false, hash: null }
+ return { present: true, hash: null }
+ }
+}
+
+// ── Install / heal / remove transactions ────────────────
+
+// Write the desktop file + icon and commit the URL-scheme defaults. Returns the
+// next record. On any failure the record is marked `failed` so the next launch
+// retries. Ordering is transactional per the design: (native-messaging host —
+// Layer 3a TODO) → desktop file + icon → default commit.
+async function installSelfIntegration(
+ deps: AppImageIntegrationDeps,
+ record: IntegrationRecord
+): Promise<IntegrationRecord> {
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+
+ // Reject a path that cannot be safely serialized (control chars / injection)
+ // before touching anything. Nothing is written; the run fails closed.
+ if (!isSafeAppImagePath(deps.appImagePath)) {
+ deps.log.error(
+ { appImagePath: JSON.stringify(deps.appImagePath) },
+ 'refusing to integrate: AppImage path contains control characters'
+ )
+ return { ...record, decision: 'accepted', owner: 'self', status: 'failed' }
+ }
+
+ // A stable per-install id, generated once and preserved across drift
+ // rewrites, is our ownership proof (see IntegrationRecord.installId). A
+ // tampered persisted record could hold an unsafe value (e.g. an embedded
+ // newline), so regenerate unless the stored id is safe.
+ const installId = isSafeInstallId(record.installId)
+ ? record.installId
+ : randomUUID()
+
+ // Record the pre-existing defaults BEFORE overriding, so removal can restore
+ // them — but only a handler that resolves to a real desktop file. A default
+ // pointing at a non-existent id (e.g. one a prior Electron
+ // setAsDefaultProtocolClient left behind) must NOT be recorded, or removal
+ // would "restore" to a phantom and leave a dead default. `resolveDesktopEntryById`
+ // also rejects unsafe ids. Only capture on first install.
+ const capturePrevious = async (
+ mime: string,
+ current: string | null
+ ): Promise<{ ok: boolean; value: string | null }> => {
+ const q = await queryDefaultHandlerResult(deps, mime)
+ // If we cannot even read the current default, do NOT proceed to overwrite
+ // it — persisting `null` here would silently lose the user's real handler.
+ if (!q.ok) return { ok: false, value: current }
+ if (!q.id || q.id === DESKTOP_ENTRY_ID) return { ok: true, value: current }
+ const usable = await resolvesToUsableHandler(deps, dataHome, q.id)
+ return { ok: true, value: usable ? q.id : current }
+ }
+ // Both captures are read-only queries on different mimes — run concurrently.
+ // (The later set/restore calls that write the shared mimeapps.list stay
+ // sequential.)
+ const [schemeCap, magnetCap] = await Promise.all([
+ capturePrevious(SCHEME_MIME, record.previousSchemeHandler),
+ capturePrevious(MAGNET_MIME, record.previousMagnetHandler),
+ ])
+ if (!schemeCap.ok || !magnetCap.ok) {
+ deps.log.warn(
+ {},
+ 'cannot query current default handlers; aborting to avoid losing them'
+ )
+ return {
+ ...record,
+ decision: 'accepted',
+ owner: 'self',
+ installId,
+ status: 'failed',
+ }
+ }
+ const previousSchemeHandler = schemeCap.value
+ const previousMagnetHandler = magnetCap.value
+
+ const base: IntegrationRecord = {
+ ...record,
+ decision: 'accepted',
+ owner: 'self',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId,
+ previousSchemeHandler,
+ previousMagnetHandler,
+ }
+
+ // Persist installId + captured previous handlers BEFORE writing any file or
+ // mutating any default. A crash between here and the final save must not (a)
+ // orphan our own file (next launch would see `installId === null`, judge its
+ // own leftover a foreign conflict, and never repair it), nor (b) lose the
+ // user's original default handlers after we have started overriding them.
+ const failed: IntegrationRecord = { ...base, status: 'failed' }
+ if (
+ record.installId !== installId ||
+ record.previousSchemeHandler !== previousSchemeHandler ||
+ record.previousMagnetHandler !== previousMagnetHandler
+ ) {
+ await deps.store.save(failed)
+ }
+
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const icon = iconFilePath(dataHome)
+
+ // No-clobber: if a file already sits at our desktop path and it is NOT ours
+ // (missing/mismatched id), it belongs to someone else (another AppImage
+ // install, a user file) — never overwrite it. `drift` (our own file, stale
+ // Exec) and a missing file are both safe to (re)write.
+ let existing: string | null = null
+ try {
+ existing = await deps.fs.readText(desktopPath)
+ } catch (err) {
+ // Only a genuinely absent file (ENOENT) is safe to create. A file that
+ // exists but cannot be read is a foreign file we must not clobber.
+ if (!isEnoent(err)) {
+ deps.log.warn(
+ { desktopPath },
+ 'existing desktop file is unreadable; not overwriting'
+ )
+ return failed
+ }
+ existing = null
+ }
+ if (existing !== null) {
+ const decision = classifyDesktopFile(existing, deps.appImagePath, installId)
+ if (decision === 'conflict') {
+ deps.log.warn(
+ { desktopPath },
+ 'appimage desktop path occupied by a foreign file; not overwriting'
+ )
+ return failed
+ }
+ }
+
+ let iconSha256: string | null = record.iconSha256
+ try {
+ // TODO(Layer 3a): when `record.nmConsent === 'accepted'`, copy the native
+ // host to a stable path and sync its NM manifests here, before the desktop
+ // file, so the transaction unwinds NM last. Not implemented in Layer 2.
+
+ await deps.fs.mkdirp(applicationsDir(dataHome))
+ await deps.fs.writeText(
+ desktopPath,
+ buildDesktopEntry({ appImagePath: deps.appImagePath, installId })
+ )
+ await deps.fs.mkdirp(path.dirname(icon))
+ const iconBytes = await deps.fs.readBytes(deps.iconSourcePath)
+ const sourceHash = sha256Hex(iconBytes)
+ // No-clobber for the icon too: an icon carries no marker, so only overwrite
+ // when the target is genuinely absent, is our own recorded icon, or is
+ // byte-identical to what we would write. A foreign icon squatting our
+ // (unique) name — including one that exists but cannot be read — is left
+ // untouched.
+ const existingIcon = await readIconState(deps.fs, icon)
+ const iconIsOursOrAbsent =
+ !existingIcon.present ||
+ (existingIcon.hash !== null &&
+ (existingIcon.hash === record.iconSha256 ||
+ existingIcon.hash === sourceHash))
+ if (iconIsOursOrAbsent) {
+ await deps.fs.copyFile(deps.iconSourcePath, icon)
+ iconSha256 = sourceHash
+ } else {
+ deps.log.warn(
+ { icon },
+ 'appimage icon path occupied by a foreign file; not overwriting'
+ )
+ }
+ } catch (err) {
+ deps.log.error({ err }, 'failed to write appimage desktop file or icon')
+ return failed
+ }
+
+ await updateDesktopDatabase(deps, dataHome)
+
+ const schemeOk = await setDefaultAndVerify(
+ deps,
+ SCHEME_MIME,
+ DESKTOP_ENTRY_ID
+ )
+ // Mirror protocol-manager: only claim the magnet default when the setting is
+ // on; otherwise leave whatever the user already had.
+ let magnetOk = true
+ if (deps.getMagnetEnabled()) {
+ magnetOk = await setDefaultAndVerify(deps, MAGNET_MIME, DESKTOP_ENTRY_ID)
+ }
+
+ const status: IntegrationStatus = schemeOk && magnetOk ? 'healthy' : 'failed'
+ if (status === 'failed') {
+ deps.log.warn(
+ { schemeOk, magnetOk },
+ 'appimage default handler verification failed'
+ )
+ }
+ return { ...base, status, iconSha256 }
+}
+
+// Bring the magnet default in line with the current setting: claim it when
+// enabled and not already ours; hand it back to the recorded prior handler
+// when disabled and currently ours. Returns the record, updated if a new
+// previous handler was captured (so a later revert restores the handler the
+// user was actually using, not a stale one). Best-effort — command failures
+// are logged inside the helpers and never block the rest of self-heal.
+async function reconcileMagnetDefault(
+ deps: AppImageIntegrationDeps,
+ record: IntegrationRecord
+): Promise<IntegrationRecord> {
+ const q = await queryDefaultHandlerResult(deps, MAGNET_MIME)
+ if (!q.ok) return record
+ if (deps.getMagnetEnabled()) {
+ if (q.id === DESKTOP_ENTRY_ID) return record
+ // About to overwrite whatever is currently the magnet handler — capture it
+ // as the new previous (if it is a real, resolvable handler) so a later
+ // revert goes back to it rather than an older recorded value.
+ let next = record
+ if (q.id && q.id !== record.previousMagnetHandler) {
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ if (await resolvesToUsableHandler(deps, dataHome, q.id)) {
+ next = { ...record, previousMagnetHandler: q.id }
+ // Persist the new previous BEFORE overriding the default, so a crash
+ // (or a failed save) after the override cannot leave us pointing at
+ // ourselves with a stale recorded previous.
+ await deps.store.save(next)
+ }
+ }
+ await setDefaultAndVerify(deps, MAGNET_MIME, DESKTOP_ENTRY_ID)
+ return next
+ }
+ if (q.id === DESKTOP_ENTRY_ID) {
+ await restoreDefault(deps, MAGNET_MIME, record.previousMagnetHandler)
+ }
+ return record
+}
+
+// Startup maintenance for an already-accepted self integration: silently repair
+// drift (updated/moved AppImage) and retry a prior failure. Never overwrites a
+// foreign file that has taken our desktop path (ownership conflict).
+async function selfHeal(
+ deps: AppImageIntegrationDeps,
+ record: IntegrationRecord
+): Promise<IntegrationRecord> {
+ if (record.status === 'failed') {
+ return installSelfIntegration(deps, record)
+ }
+
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ const desktopPath = desktopEntryFilePath(dataHome)
+ let content: string | null = null
+ try {
+ content = await deps.fs.readText(desktopPath)
+ } catch {
+ content = null
+ }
+
+ if (content === null) {
+ deps.log.info(
+ { desktopPath },
+ 'appimage desktop file missing; reinstalling'
+ )
+ return installSelfIntegration(deps, record)
+ }
+
+ const decision = classifyDesktopFile(
+ content,
+ deps.appImagePath,
+ record.installId
+ )
+ if (decision === 'ok') {
+ // In an AppImage the settings-change path (protocolManager.register) is a
+ // no-op, so this startup pass is the only place a magnet-setting toggle
+ // converges. TODO(follow-up): also reconcile immediately when the setting
+ // changes at runtime, once a settings-change hook is wired here.
+ const reconciled = await reconcileMagnetDefault(deps, record)
+ if (reconciled !== record) await deps.store.save(reconciled)
+ return reconciled
+ }
+ if (decision === 'drift') {
+ deps.log.info({ desktopPath }, 'repairing drifted appimage desktop file')
+ return installSelfIntegration(deps, record)
+ }
+ // conflict: a foreign file occupies our path. Do not overwrite; mark failed
+ // so the state is visible in settings and re-checked next launch.
+ deps.log.warn(
+ { desktopPath },
+ 'appimage desktop path occupied by a foreign file; leaving it untouched'
+ )
+ const next: IntegrationRecord = { ...record, status: 'failed' }
+ return next
+}
+
+// Reverse-order teardown driven from the settings page. NM removal is a Layer 3a
+// TODO. Restores the recorded defaults FIRST and only deletes our files if the
+// restore succeeded — otherwise a deleted desktop would leave a dangling
+// default handler behind.
+export async function removeSystemIntegration(
+ deps: AppImageIntegrationDeps
+): Promise<IntegrationRecord> {
+ const record = await deps.store.load()
+ // An externally-owned integration (deb install, another tool) was never
+ // written by us: there is nothing of ours to delete, and flipping the record
+ // to `declined` would erase the external classification. Leave both alone.
+ if (record.owner === 'external') {
+ deps.log.info(
+ {},
+ 'appimage integration is externally owned; nothing to remove'
+ )
+ return record
+ }
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const icon = iconFilePath(dataHome)
+
+ // TODO(Layer 3a): unregister native-messaging manifests / remove the stable
+ // host copy first, mirroring the install order in reverse.
+
+ const schemeRestored = await restoreDefault(
+ deps,
+ SCHEME_MIME,
+ record.previousSchemeHandler
+ )
+ const magnetRestored = await restoreDefault(
+ deps,
+ MAGNET_MIME,
+ record.previousMagnetHandler
+ )
+ if (!schemeRestored || !magnetRestored) {
+ // Could not safely reclaim the defaults — keep the desktop file so the
+ // default is not left pointing at a deleted entry. Persist `failed` for a
+ // later retry from settings.
+ deps.log.warn(
+ { schemeRestored, magnetRestored },
+ 'aborting appimage removal: could not restore mime defaults'
+ )
+ const stuck: IntegrationRecord = { ...record, status: 'failed' }
+ await deps.store.save(stuck)
+ return stuck
+ }
+
+ // Delete the desktop file only if it is still verifiably ours.
+ try {
+ const content = await deps.fs.readText(desktopPath)
+ if (isOwnedBySelf(parseDesktopEntry(content), record.installId)) {
+ await deps.fs.remove(desktopPath)
+ }
+ } catch {
+ // already gone
+ }
+ // Delete the icon only if its bytes still match what we installed (an icon
+ // carries no marker, so this is its ownership check).
+ if (record.iconSha256) {
+ try {
+ const bytes = await deps.fs.readBytes(icon)
+ if (sha256Hex(bytes) === record.iconSha256) {
+ await deps.fs.remove(icon)
+ }
+ } catch {
+ // already gone / unreadable
+ }
+ }
+ await updateDesktopDatabase(deps, dataHome)
+
+ const next: IntegrationRecord = {
+ ...DEFAULT_INTEGRATION_RECORD,
+ decision: 'declined',
+ }
+ await deps.store.save(next)
+ return next
+}
+
+// Restore a previously-recorded default handler. Returns whether the mime is
+// now in a safe state (either no longer ours, or successfully repointed and
+// re-verified). Returns false — blocking desktop deletion — when the default is
+// still ours but we cannot safely reclaim it (no recorded previous, unsafe
+// previous id, or the set/verify failed).
+async function restoreDefault(
+ deps: AppImageIntegrationDeps,
+ mime: string,
+ previous: string | null
+): Promise<boolean> {
+ const query = await queryDefaultHandlerResult(deps, mime)
+ // If we cannot even read the current default (command missing / timeout /
+ // non-zero), we do not know whether it still points at us — fail safe and
+ // block deletion rather than risk leaving a default pointing at a file we
+ // are about to remove.
+ if (!query.ok) return false
+ if (query.id !== DESKTOP_ENTRY_ID) return true // user re-pointed it; nothing to do
+ // TODO(Layer 3a+): when there was no prior handler we cannot cleanly "unset"
+ // the default via `xdg-mime` (there is no unset verb). Clearing our line from
+ // the user's mimeapps.list is the documented mechanism but is fiddly across
+ // desktops, so for now we fail-safe: keep our desktop file (removal reports
+ // `failed`) rather than delete it and leave a default pointing at nothing.
+ if (!previous) return false // no safe handler to restore to
+ if (!isSafeDesktopId(previous)) {
+ deps.log.warn({ mime, previous }, 'recorded previous handler is unsafe')
+ return false
+ }
+ // The recorded handler may have been uninstalled, disabled, or corrupted
+ // since we captured it. Restoring the default to a missing OR non-launchable
+ // entry would just create a different dead default, so fail safe (block
+ // deletion, keep our own file).
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ if (!(await resolvesToUsableHandler(deps, dataHome, previous))) {
+ deps.log.warn(
+ { mime, previous },
+ 'recorded previous handler is missing or not launchable; not restoring'
+ )
+ return false
+ }
+ return setDefaultAndVerify(deps, mime, previous)
+}
+
+// ── Entry points ────────────────────────────────────────
+
+export async function runStartupIntegration(
+ deps: AppImageIntegrationDeps
+): Promise<IntegrationRecord> {
+ const record = await deps.store.load()
+
+ if (record.decision === 'declined') return record
+
+ if (record.decision === 'accepted') {
+ if (record.owner === 'external') {
+ // Re-verify the external owner every startup — it may have been deleted,
+ // disabled, or repointed since we recorded it. A stale `external` must
+ // not linger as a false `healthy`.
+ const stillExternal = await detectExternalOwner(deps, record.installId)
+ if (stillExternal) {
+ if (stillExternal === record.desktopId) return record
+ const moved: IntegrationRecord = { ...record, desktopId: stillExternal }
+ await deps.store.save(moved)
+ return moved
+ }
+ // External integration is gone — reset to first-run detection/prompt.
+ deps.log.info(
+ { previous: record.desktopId },
+ 'external appimage integration no longer present; re-detecting'
+ )
+ const reset: IntegrationRecord = {
+ ...record,
+ decision: 'unset',
+ owner: null,
+ desktopId: null,
+ status: null,
+ }
+ return runFirstRun(deps, reset)
+ }
+ if (record.owner === 'self') {
+ const next = await selfHeal(deps, record)
+ if (next !== record) await deps.store.save(next)
+ return next
+ }
+ return record
+ }
+
+ // decision === 'unset' — first run.
+ return runFirstRun(deps, record)
+}
+
+// First-run detection + consent. Detect a pre-existing external owner before
+// prompting; otherwise ask and, on acceptance, install.
+async function runFirstRun(
+ deps: AppImageIntegrationDeps,
+ record: IntegrationRecord
+): Promise<IntegrationRecord> {
+ const external = await detectExternalOwner(deps, record.installId)
+ if (external) {
+ const next: IntegrationRecord = {
+ ...record,
+ decision: 'accepted',
+ owner: 'external',
+ desktopId: external,
+ status: 'healthy',
+ }
+ await deps.store.save(next)
+ return next
+ }
+
+ const accepted = await deps.prompt()
+ if (!accepted) {
+ const declined: IntegrationRecord = { ...record, decision: 'declined' }
+ await deps.store.save(declined)
+ return declined
+ }
+
+ const installed = await installSelfIntegration(deps, record)
+ await deps.store.save(installed)
+ return installed
+}
+
+async function detectExternalOwner(
+ deps: AppImageIntegrationDeps,
+ installId: string | null
+): Promise<string | null> {
+ const handlerId = await queryDefaultHandler(deps, SCHEME_MIME)
+ if (!handlerId) return null
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ const resolvedEntry = await resolveDesktopEntryById(deps, dataHome, handlerId)
+ const owner = classifyDefaultHandler({
+ handlerId,
+ resolvedEntry,
+ appImagePath: deps.appImagePath,
+ installId,
+ })
+ return owner === 'external' ? handlerId : null
+}
+
+// Manual "enable system integration" entry point from settings. Runs the full
+// install transaction regardless of the prior decision (including `declined`).
+export async function enableSystemIntegration(
+ deps: AppImageIntegrationDeps
+): Promise<IntegrationRecord> {
+ const record = await deps.store.load()
+ const installed = await installSelfIntegration(deps, record)
+ await deps.store.save(installed)
+ return installed
+}
diff --git a/src/main/platform/protocol-manager.test.ts b/src/main/platform/protocol-manager.test.ts
index 8a7957bb..8561fd40 100644
--- a/src/main/platform/protocol-manager.test.ts
+++ b/src/main/platform/protocol-manager.test.ts
@@ -152,6 +152,30 @@ describe('createProtocolManager', () => {
expect(mockSetAsDefault).not.toHaveBeenCalled()
})
+
+ it('skips Electron scheme registration in an AppImage (integration owns it)', () => {
+ const {
+ getWindow,
+ settingsManager,
+ torrentParser,
+ onOpenAddTask,
+ deliverToAddTask,
+ onOpenPluginDetail,
+ } = makeDeps(true)
+ const pm = createProtocolManager({
+ getWindow,
+ settingsManager,
+ torrentParser,
+ onOpenAddTask,
+ deliverToAddTask,
+ onOpenPluginDetail,
+ isAppImage: true,
+ })
+ pm.register()
+
+ expect(mockSetAsDefault).not.toHaveBeenCalled()
+ expect(mockRemoveDefault).not.toHaveBeenCalled()
+ })
})
describe('handle', () => {
diff --git a/src/main/platform/protocol-manager.ts b/src/main/platform/protocol-manager.ts
index 7803d454..f28acd98 100644
--- a/src/main/platform/protocol-manager.ts
+++ b/src/main/platform/protocol-manager.ts
@@ -13,6 +13,14 @@ export interface ProtocolManagerDeps {
getWindow: () => BrowserWindow | null
settingsManager: SettingsManager
torrentParser: TorrentParser
+ // When running as a packaged Linux AppImage, the AppImage desktop
+ // self-integration (src/main/platform/appimage-integration.ts) owns the
+ // `motrix:`/`magnet:` scheme defaults via a user-scope `.desktop` file. In
+ // that environment we must NOT also call Electron's
+ // `setAsDefaultProtocolClient`, which writes its own competing desktop entry
+ // and mutates the XDG default — that would race the integration's
+ // external-owner detection and corrupt the recorded prior default handler.
+ isAppImage?: boolean
// Open (or focus) the add-task window with URL prefill. Wired in
// main/index.ts to open the window + dispatch SetAddTaskMode once the
// renderer's first paint + useEffect have completed.
@@ -73,6 +81,13 @@ export function createProtocolManager(deps: ProtocolManagerDeps) {
register() {
if (!app.isPackaged) return
+ // In an AppImage, the desktop self-integration owns scheme registration;
+ // calling Electron's registrar here would fight it. See ProtocolManagerDeps.
+ if (deps.isAppImage) {
+ log.info('appimage: scheme registration owned by desktop integration')
+ return
+ }
+
app.setAsDefaultProtocolClient('motrix')
const magnetEnabled = deps.settingsManager.getApp().protocols.magnet
diff --git a/src/renderer/routes/settings/cards/integration/appimage-integration-section.test.tsx b/src/renderer/routes/settings/cards/integration/appimage-integration-section.test.tsx
new file mode 100644
index 00000000..4f654afd
--- /dev/null
+++ b/src/renderer/routes/settings/cards/integration/appimage-integration-section.test.tsx
@@ -0,0 +1,163 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ invoke: vi.fn(),
+ },
+}))
+
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
+import { AppImageIntegrationSection } from './appimage-integration-section'
+
+const invoke = vi.mocked(transport.invoke)
+
+function statusOnly(view: AppImageIntegrationView) {
+ invoke.mockImplementation(async (channel: string) => {
+ if (channel === Queries.GetAppImageIntegrationStatus) return view
+ throw new Error(`unexpected channel: ${channel}`)
+ })
+}
+
+beforeEach(() => {
+ invoke.mockReset()
+})
+
+describe('AppImageIntegrationSection', () => {
+ it('renders nothing outside an AppImage environment', async () => {
+ statusOnly({ supported: false })
+ const { container } = render(<AppImageIntegrationSection />)
+ await waitFor(() =>
+ expect(invoke).toHaveBeenCalledWith(Queries.GetAppImageIntegrationStatus)
+ )
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('renders nothing when the status query fails (web shell)', async () => {
+ invoke.mockRejectedValue(new Error('unknown query'))
+ const { container } = render(<AppImageIntegrationSection />)
+ await waitFor(() => expect(invoke).toHaveBeenCalled())
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('offers enable when not integrated', async () => {
+ statusOnly({
+ supported: true,
+ decision: 'unset',
+ owner: null,
+ status: null,
+ })
+ render(<AppImageIntegrationSection />)
+ expect(
+ await screen.findByRole('button', { name: 'Enable desktop integration' })
+ ).toBeInTheDocument()
+ expect(screen.getByText('Not integrated with this desktop.')).toBeVisible()
+ expect(
+ screen.queryByRole('button', { name: 'Remove desktop integration' })
+ ).not.toBeInTheDocument()
+ })
+
+ it('enables integration and shows the refreshed state', async () => {
+ invoke.mockImplementation(async (channel: string) => {
+ if (channel === Queries.GetAppImageIntegrationStatus) {
+ return {
+ supported: true,
+ decision: 'declined',
+ owner: null,
+ status: null,
+ }
+ }
+ if (channel === Commands.EnableAppImageIntegration) {
+ return {
+ supported: true,
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ }
+ }
+ throw new Error(`unexpected channel: ${channel}`)
+ })
+ render(<AppImageIntegrationSection />)
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Enable desktop integration' })
+ )
+ expect(
+ await screen.findByRole('button', { name: 'Remove desktop integration' })
+ ).toBeInTheDocument()
+ expect(invoke).toHaveBeenCalledWith(Commands.EnableAppImageIntegration)
+ expect(screen.getByText('Integrated with this desktop.')).toBeVisible()
+ })
+
+ it('removes integration and returns to the enable state', async () => {
+ invoke.mockImplementation(async (channel: string) => {
+ if (channel === Queries.GetAppImageIntegrationStatus) {
+ return {
+ supported: true,
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ }
+ }
+ if (channel === Commands.RemoveAppImageIntegration) {
+ return {
+ supported: true,
+ decision: 'declined',
+ owner: null,
+ status: null,
+ }
+ }
+ throw new Error(`unexpected channel: ${channel}`)
+ })
+ render(<AppImageIntegrationSection />)
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Remove desktop integration' })
+ )
+ expect(
+ await screen.findByRole('button', { name: 'Enable desktop integration' })
+ ).toBeInTheDocument()
+ expect(invoke).toHaveBeenCalledWith(Commands.RemoveAppImageIntegration)
+ })
+
+ it('shows the failed state with both retry and remove', async () => {
+ statusOnly({
+ supported: true,
+ decision: 'accepted',
+ owner: 'self',
+ status: 'failed',
+ })
+ render(<AppImageIntegrationSection />)
+ expect(
+ await screen.findByText('Desktop integration incomplete')
+ ).toBeVisible()
+ expect(
+ screen.getByRole('button', { name: 'Enable desktop integration' })
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'Remove desktop integration' })
+ ).toBeInTheDocument()
+ })
+
+ it('blocks removal for an externally-owned integration', async () => {
+ statusOnly({
+ supported: true,
+ decision: 'accepted',
+ owner: 'external',
+ status: 'healthy',
+ })
+ render(<AppImageIntegrationSection />)
+ expect(
+ await screen.findByText(
+ 'Desktop integration is provided by another Motrix install.'
+ )
+ ).toBeVisible()
+ expect(
+ screen.queryByRole('button', { name: 'Remove desktop integration' })
+ ).not.toBeInTheDocument()
+ })
+})
diff --git a/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx b/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx
new file mode 100644
index 00000000..6a6c33a4
--- /dev/null
+++ b/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx
@@ -0,0 +1,146 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from '@renderer/components/ui/alert'
+import { Button } from '@renderer/components/ui/button'
+import { Spinner } from '@renderer/components/ui/spinner'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
+import { CircleAlert } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+type SupportedView = Extract<AppImageIntegrationView, { supported: true }>
+
+// The main process answers { supported: false } outside a packaged Linux
+// AppImage; the web shell has no handler at all and rejects. Both collapse to
+// "render nothing".
+function parseView(value: unknown): SupportedView | null {
+ if (typeof value !== 'object' || value === null) return null
+ const view = value as AppImageIntegrationView
+ return view.supported === true ? view : null
+}
+
+export function AppImageIntegrationSection() {
+ const { t } = useTranslation()
+ const [view, setView] = useState<SupportedView | null>(null)
+ const [busy, setBusy] = useState(false)
+
+ useEffect(() => {
+ let stale = false
+ transport
+ .invoke(Queries.GetAppImageIntegrationStatus)
+ .then((result) => {
+ if (!stale) setView(parseView(result))
+ })
+ .catch(() => {
+ if (!stale) setView(null)
+ })
+ return () => {
+ stale = true
+ }
+ }, [])
+
+ if (!view) return null
+
+ const integratedBySelf = view.decision === 'accepted' && view.owner === 'self'
+ const external = view.owner === 'external'
+ const failed = integratedBySelf && view.status === 'failed'
+ const showEnable = !external && (!integratedBySelf || failed)
+ const showRemove = integratedBySelf && !external
+
+ const runAction = async (
+ channel:
+ | typeof Commands.EnableAppImageIntegration
+ | typeof Commands.RemoveAppImageIntegration
+ ) => {
+ setBusy(true)
+ try {
+ setView(parseView(await transport.invoke(channel)))
+ } catch {
+ // Keep the current view; the main process logs the failure.
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const statusText = external
+ ? t('settings.integration.appimage.status.externalManaged')
+ : integratedBySelf && view.status === 'healthy'
+ ? t('settings.integration.appimage.status.healthy')
+ : integratedBySelf
+ ? null
+ : t('settings.integration.appimage.status.notIntegrated')
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <span className="text-sm font-medium">
+ {t('settings.integration.appimage.title')}
+ </span>
+ <p className="text-xs text-muted-foreground">
+ {t('settings.integration.appimage.desc')}
+ </p>
+ {statusText && (
+ <p className="text-xs text-muted-foreground" role="status">
+ {statusText}
+ </p>
+ )}
+ </div>
+ <div className="flex shrink-0 gap-2">
+ {showEnable && (
+ <Button
+ type="button"
+ variant={integratedBySelf ? 'outline' : 'default'}
+ size="sm"
+ disabled={busy}
+ onClick={() => runAction(Commands.EnableAppImageIntegration)}
+ >
+ {busy && (
+ <Spinner
+ data-icon="inline-start"
+ role="presentation"
+ aria-hidden="true"
+ />
+ )}
+ {t('settings.integration.appimage.enable')}
+ </Button>
+ )}
+ {showRemove && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy}
+ onClick={() => runAction(Commands.RemoveAppImageIntegration)}
+ >
+ {t('settings.integration.appimage.remove')}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {failed && (
+ <Alert variant="destructive">
+ <CircleAlert aria-hidden="true" />
+ <AlertTitle>
+ {t('settings.integration.appimage.status.failedTitle')}
+ </AlertTitle>
+ <AlertDescription>
+ {t('settings.integration.appimage.status.failedDetail')}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {integratedBySelf && view.status === 'healthy' && (
+ <p className="text-xs text-muted-foreground">
+ {t('settings.integration.appimage.movedHint')}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
index 53558f09..276df8fd 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
@@ -22,6 +22,7 @@ import { FormProvider, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod'
import type { SettingsCardDialogProps } from '../card-types'
+import { AppImageIntegrationSection } from './appimage-integration-section'
import { BrowserExtensionsSection } from './browser-extensions-section'
import { CLIClientsSection } from './cli-clients-section'
import { CliToolSection } from './cli-tool-section'
@@ -137,6 +138,7 @@ export function IntegrationDialog({
{t('settings.integration.system.title')}
</h3>
<SystemProtocolsSection />
+ <AppImageIntegrationSection />
</section>
<Separator />
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 164ea789..46bbd37b 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1517,7 +1517,28 @@
"fileMissing": "File does not exist at this path."
}
},
- "pairResolveFailed": "Couldn't submit your decision — try again."
+ "pairResolveFailed": "Couldn't submit your decision — try again.",
+ "appimage": {
+ "title": "Desktop integration",
+ "desc": "Register this Motrix AppImage with your desktop so browsers and magnet links can hand downloads to it.",
+ "enable": "Enable desktop integration",
+ "remove": "Remove desktop integration",
+ "prompt": {
+ "title": "Integrate Motrix with your desktop?",
+ "message": "Let this Motrix AppImage register with your desktop environment?",
+ "detail": "Motrix will add a desktop entry and icon under your user data directory and register itself as the handler for motrix: links, magnet links, and .torrent files. This lets your browser and the Motrix extension launch Motrix and hand it downloads. Nothing is written outside your home directory, and you can undo this from Settings.",
+ "accept": "Integrate",
+ "decline": "Not now"
+ },
+ "status": {
+ "healthy": "Integrated with this desktop.",
+ "notIntegrated": "Not integrated with this desktop.",
+ "failedTitle": "Desktop integration incomplete",
+ "failedDetail": "Motrix couldn't register itself as the handler for its links. Browser hand-off may not work until you re-enable desktop integration.",
+ "externalManaged": "Desktop integration is provided by another Motrix install."
+ },
+ "movedHint": "If you move the AppImage while Motrix is closed, links may fail to launch until you start Motrix once from its new location."
+ }
}
},
"errors": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index cf2f5471..28b6ceb7 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1503,7 +1503,28 @@
"fileMissing": "该路径不存在。"
}
},
- "pairResolveFailed": "提交决定失败,请重试。"
+ "pairResolveFailed": "提交决定失败,请重试。",
+ "appimage": {
+ "title": "桌面集成",
+ "desc": "将此 Motrix AppImage 注册到桌面环境,让浏览器和磁力链接能把下载交给它。",
+ "enable": "启用桌面集成",
+ "remove": "移除桌面集成",
+ "prompt": {
+ "title": "将 Motrix 集成到桌面环境?",
+ "message": "允许此 Motrix AppImage 注册到你的桌面环境吗?",
+ "detail": "Motrix 会在你的用户数据目录下添加桌面入口和图标,并把自己注册为 motrix: 链接、磁力链接和 .torrent 文件的处理程序。这样浏览器和 Motrix 扩展就能唤起 Motrix 并把下载交给它。不会写入 home 目录以外的位置,你可以随时在设置中撤销。",
+ "accept": "集成",
+ "decline": "暂不"
+ },
+ "status": {
+ "healthy": "已与当前桌面集成。",
+ "notIntegrated": "尚未与当前桌面集成。",
+ "failedTitle": "桌面集成未完成",
+ "failedDetail": "Motrix 未能把自己注册为链接处理程序。在你重新启用桌面集成之前,浏览器唤起可能无法工作。",
+ "externalManaged": "桌面集成由另一个 Motrix 安装提供。"
+ },
+ "movedHint": "如果在 Motrix 未运行时移动 AppImage,链接可能无法唤起,直到你从新位置手动启动一次 Motrix。"
+ }
}
},
"menu": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 0d799948..6907b23a 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1503,7 +1503,28 @@
"fileMissing": "此路徑不存在檔案。"
}
},
- "pairResolveFailed": "無法提交您的決定,請再試一次。"
+ "pairResolveFailed": "無法提交您的決定,請再試一次。",
+ "appimage": {
+ "title": "桌面整合",
+ "desc": "將此 Motrix AppImage 註冊到桌面環境,讓瀏覽器和磁力連結能把下載交給它。",
+ "enable": "啟用桌面整合",
+ "remove": "移除桌面整合",
+ "prompt": {
+ "title": "將 Motrix 整合到桌面環境?",
+ "message": "允許此 Motrix AppImage 註冊到您的桌面環境嗎?",
+ "detail": "Motrix 會在您的使用者資料目錄下新增桌面項目和圖示,並把自己註冊為 motrix: 連結、磁力連結和 .torrent 檔案的處理程式。這樣瀏覽器和 Motrix 擴充功能就能喚起 Motrix 並把下載交給它。不會寫入 home 目錄以外的位置,您可以隨時在設定中撤銷。",
+ "accept": "整合",
+ "decline": "暫不"
+ },
+ "status": {
+ "healthy": "已與目前桌面整合。",
+ "notIntegrated": "尚未與目前桌面整合。",
+ "failedTitle": "桌面整合未完成",
+ "failedDetail": "Motrix 未能把自己註冊為連結處理程式。在您重新啟用桌面整合之前,瀏覽器喚起可能無法運作。",
+ "externalManaged": "桌面整合由另一個 Motrix 安裝提供。"
+ },
+ "movedHint": "如果在 Motrix 未執行時移動 AppImage,連結可能無法喚起,直到您從新位置手動啟動一次 Motrix。"
+ }
}
},
"errors": {
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 2b14d49e..343eff2e 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -79,6 +79,10 @@ export const Commands = {
ResizeWindow: 'command:resizeWindow',
OpenExternal: 'command:openExternal',
RequestDefaultTorrentHandler: 'command:requestDefaultTorrentHandler',
+ // Linux AppImage desktop integration (settings-driven enable/remove).
+ // Both return the refreshed `AppImageIntegrationView`.
+ EnableAppImageIntegration: 'command:enableAppImageIntegration',
+ RemoveAppImageIntegration: 'command:removeAppImageIntegration',
RevealInFolder: 'command:revealInFolder',
// Menu
UpdateMenuContext: 'command:updateMenuContext',
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index 0d73ab17..79e327f9 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -71,6 +71,9 @@ export const Queries = {
// GetUnreadNotificationCount returns the unread badge count as a number.
GetUnreadNotificationCount: 'query:getUnreadNotificationCount',
GetCliToolStatus: 'query:getCliToolStatus',
+ // Linux AppImage desktop integration; returns `AppImageIntegrationView`
+ // ({ supported: false } outside a packaged Linux AppImage).
+ GetAppImageIntegrationStatus: 'query:getAppImageIntegrationStatus',
GetApplicationMenu: 'query:getApplicationMenu',
} as const
diff --git a/src/shared/types/appimage-integration.ts b/src/shared/types/appimage-integration.ts
new file mode 100644
index 00000000..d65e0fa2
--- /dev/null
+++ b/src/shared/types/appimage-integration.ts
@@ -0,0 +1,18 @@
+// Renderer-facing view of the Linux AppImage desktop-integration state.
+// The full persisted record (previous handlers, install id, icon hash) stays
+// private to the main-process integration module; the settings UI only needs
+// the decision/ownership/health triple plus whether the environment supports
+// integration at all (packaged Linux AppImage).
+
+export type AppImageIntegrationDecision = 'unset' | 'accepted' | 'declined'
+export type AppImageIntegrationOwner = 'self' | 'external' | null
+export type AppImageIntegrationHealth = 'healthy' | 'failed' | null
+
+export type AppImageIntegrationView =
+ | { supported: false }
+ | {
+ supported: true
+ decision: AppImageIntegrationDecision
+ owner: AppImageIntegrationOwner
+ status: AppImageIntegrationHealth
+ }
diff --git a/tests/scripts/assemble-release-artifacts.test.ts b/tests/scripts/assemble-release-artifacts.test.ts
index ef9db01f..d80178b0 100644
--- a/tests/scripts/assemble-release-artifacts.test.ts
+++ b/tests/scripts/assemble-release-artifacts.test.ts
@@ -46,6 +46,8 @@ describe('assembleReleaseArtifacts', () => {
expect(result.manifests).toHaveLength(8)
expect(await readdir(fixture.output)).toEqual(
expect.arrayContaining([
+ 'Motrix-2.0.0-arm64.AppImage',
+ 'Motrix-2.0.0-x86_64.AppImage',
'Motrix-2.0.0.aarch64.rpm',
'Motrix-2.0.0.x86_64.rpm',
'Motrix-Native-Host-2.0.0-linux-arm64.tar.gz',
@@ -90,8 +92,11 @@ describe('assembleReleaseArtifacts', () => {
const linuxManifest = load(
await readFile(path.join(fixture.output, manifestName), 'utf8')
) as { files: Array<{ url: string }> }
- expect(linuxManifest.files).toHaveLength(2)
- expect(new Set(linuxManifest.files.map((file) => file.url)).size).toBe(2)
+ expect(linuxManifest.files).toHaveLength(3)
+ expect(new Set(linuxManifest.files.map((file) => file.url)).size).toBe(3)
+ expect(
+ linuxManifest.files.some((file) => file.url.endsWith('.AppImage'))
+ ).toBe(true)
}
await expect(
@@ -472,25 +477,34 @@ describe('assembleReleaseArtifacts', () => {
)
})
- it('rejects AppImage inputs from the GitHub release bundle', async () => {
+ it('flattens the AppImage asset and records it in both Linux manifests', async () => {
const fixture = await createFixture()
- await writeFile(
- path.join(
- path.dirname(fixture.paths.linuxArm64Deb),
- 'Motrix-2.0.0-arm64.AppImage'
- ),
- 'AppImage'
- )
- await expect(
- assembleReleaseArtifacts({
- inputDirectory: fixture.input,
- outputDirectory: fixture.output,
- version: VERSION,
- })
- ).rejects.toThrow(
- 'linux-arm64: unexpected release asset Motrix-2.0.0-arm64.AppImage'
+ await assembleReleaseArtifacts({
+ inputDirectory: fixture.input,
+ outputDirectory: fixture.output,
+ version: VERSION,
+ })
+
+ // Both architecture AppImages land in the output alongside deb/rpm.
+ const output = await readdir(fixture.output)
+ expect(output).toEqual(
+ expect.arrayContaining([
+ 'Motrix-2.0.0-x86_64.AppImage',
+ 'Motrix-2.0.0-arm64.AppImage',
+ ])
)
+
+ // Each Linux updater manifest lists its architecture's AppImage.
+ for (const [manifestName, appImage] of [
+ ['latest-linux.yml', 'Motrix-2.0.0-x86_64.AppImage'],
+ ['latest-linux-arm64.yml', 'Motrix-2.0.0-arm64.AppImage'],
+ ] as const) {
+ const manifest = load(
+ await readFile(path.join(fixture.output, manifestName), 'utf8')
+ ) as { files: Array<{ url: string }> }
+ expect(manifest.files.map((file) => file.url)).toContain(appImage)
+ }
})
it('rejects Linux artifacts swapped between x64 and arm64 inputs', async () => {
@@ -576,9 +590,11 @@ async function createFixture(version = VERSION) {
linuxArm64Deb: `Motrix_${version}_arm64.deb`,
linuxArm64Companion: `Motrix-Native-Host-${version}-linux-arm64.tar.gz`,
linuxArm64Rpm: `Motrix-${version}.aarch64.rpm`,
+ linuxArm64AppImage: `Motrix-${version}-arm64.AppImage`,
linuxX64Deb: `Motrix_${version}_amd64.deb`,
linuxX64Companion: `Motrix-Native-Host-${version}-linux-x64.tar.gz`,
linuxX64Rpm: `Motrix-${version}.x86_64.rpm`,
+ linuxX64AppImage: `Motrix-${version}-x86_64.AppImage`,
macArm64Dmg: `Motrix-${version}-arm64.dmg`,
macArm64Zip: `Motrix-${version}-arm64.zip`,
macX64Dmg: `Motrix-${version}-x64.dmg`,
@@ -589,9 +605,11 @@ async function createFixture(version = VERSION) {
linuxArm64Deb: Buffer.from('Linux arm64 deb'),
linuxArm64Companion: Buffer.from('Linux arm64 Flatpak companion'),
linuxArm64Rpm: Buffer.from('Linux arm64 rpm'),
+ linuxArm64AppImage: Buffer.from('Linux arm64 AppImage'),
linuxX64Deb: Buffer.from('Linux x64 deb'),
linuxX64Companion: Buffer.from('Linux x64 Flatpak companion'),
linuxX64Rpm: Buffer.from('Linux x64 rpm'),
+ linuxX64AppImage: Buffer.from('Linux x64 AppImage'),
macArm64Dmg: Buffer.from('macOS arm64 DMG'),
macArm64Zip: Buffer.from('macOS arm64 ZIP'),
macX64Dmg: Buffer.from('macOS x64 DMG'),
@@ -664,6 +682,11 @@ async function createFixture(version = VERSION) {
contents.linuxX64Companion
)
await writeAsset(linuxX64, names.linuxX64Rpm, contents.linuxX64Rpm)
+ const linuxX64AppImage = await writeAsset(
+ linuxX64,
+ names.linuxX64AppImage,
+ contents.linuxX64AppImage
+ )
const linuxX64Manifest = path.join(linuxX64, 'latest-linux.yml')
const linuxX64BetaManifest = path.join(linuxX64, 'beta-linux.yml')
await writeManifest(
@@ -672,6 +695,7 @@ async function createFixture(version = VERSION) {
[
{ name: names.linuxX64Deb, content: contents.linuxX64Deb },
{ name: names.linuxX64Rpm, content: contents.linuxX64Rpm },
+ { name: names.linuxX64AppImage, content: contents.linuxX64AppImage },
{ name: names.linuxX64Rpm, content: contents.linuxX64Rpm },
],
names.linuxX64Deb
@@ -682,6 +706,7 @@ async function createFixture(version = VERSION) {
[
{ name: names.linuxX64Deb, content: contents.linuxX64Deb },
{ name: names.linuxX64Rpm, content: contents.linuxX64Rpm },
+ { name: names.linuxX64AppImage, content: contents.linuxX64AppImage },
{ name: names.linuxX64Rpm, content: contents.linuxX64Rpm },
],
names.linuxX64Deb
@@ -703,6 +728,11 @@ async function createFixture(version = VERSION) {
names.linuxArm64Companion,
contents.linuxArm64Companion
)
+ const linuxArm64AppImage = await writeAsset(
+ linuxArm64,
+ names.linuxArm64AppImage,
+ contents.linuxArm64AppImage
+ )
const linuxArm64Manifest = path.join(linuxArm64, 'latest-linux-arm64.yml')
await writeManifest(
linuxArm64Manifest,
@@ -710,6 +740,7 @@ async function createFixture(version = VERSION) {
[
{ name: names.linuxArm64Deb, content: contents.linuxArm64Deb },
{ name: names.linuxArm64Rpm, content: contents.linuxArm64Rpm },
+ { name: names.linuxArm64AppImage, content: contents.linuxArm64AppImage },
{ name: names.linuxArm64Rpm, content: contents.linuxArm64Rpm },
],
names.linuxArm64Deb
@@ -720,6 +751,7 @@ async function createFixture(version = VERSION) {
[
{ name: names.linuxArm64Deb, content: contents.linuxArm64Deb },
{ name: names.linuxArm64Rpm, content: contents.linuxArm64Rpm },
+ { name: names.linuxArm64AppImage, content: contents.linuxArm64AppImage },
{ name: names.linuxArm64Rpm, content: contents.linuxArm64Rpm },
],
names.linuxArm64Deb
@@ -752,8 +784,10 @@ async function createFixture(version = VERSION) {
linuxArm64Companion: linuxArm64Companion.path,
linuxArm64Manifest,
linuxArm64Rpm: linuxArm64Rpm.path,
+ linuxArm64AppImage: linuxArm64AppImage.path,
linuxX64Deb: linuxX64Deb.path,
linuxX64Companion: linuxX64Companion.path,
+ linuxX64AppImage: linuxX64AppImage.path,
linuxX64BetaManifest,
linuxX64Manifest,
macArm64Manifest,
diff --git a/tests/scripts/verify-appimage-artifact.test.ts b/tests/scripts/verify-appimage-artifact.test.ts
new file mode 100644
index 00000000..a0e6dd08
--- /dev/null
+++ b/tests/scripts/verify-appimage-artifact.test.ts
@@ -0,0 +1,236 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+// @ts-expect-error -- JavaScript release script intentionally has no declarations
+import {
+ assertAppImageHeader,
+ assertDesktopMimeTypes,
+ expectedAppImageName,
+ REQUIRED_MIME_TYPES,
+ verifyAppimageArtifact,
+} from '../../scripts/verify-appimage-artifact.mjs'
+
+const VERSION = '2.0.0'
+const FULL_MIME =
+ 'application/x-bittorrent;x-scheme-handler/magnet;x-scheme-handler/motrix;'
+const tempDirs: string[] = []
+
+// ELF e_machine for the arch, plus the ELF + AppImage type-2 magic bytes.
+const E_MACHINE = { x64: 0x3e, arm64: 0xb7 }
+function makeHead(arch: 'x64' | 'arm64'): Buffer {
+ const head = Buffer.alloc(64)
+ head[0] = 0x7f
+ head[1] = 0x45 // E
+ head[2] = 0x4c // L
+ head[3] = 0x46 // F
+ head[8] = 0x41 // A
+ head[9] = 0x49 // I
+ head[10] = 0x02 // type 2
+ head.writeUInt16LE(E_MACHINE[arch], 18)
+ // plausible section-header table so squashfsOffset() is well-defined
+ head.writeBigUInt64LE(4096n, 0x28)
+ head.writeUInt16LE(64, 0x3a)
+ head.writeUInt16LE(2, 0x3c)
+ return head
+}
+
+const okStat = { isFile: () => true, mode: 0o755 }
+
+// Default injected ports: valid x64 header, executable regular file, full mime.
+function ports(
+ overrides: {
+ head?: Buffer
+ stat?: { isFile: () => boolean; mode: number }
+ mime?: string
+ arch?: 'x64' | 'arm64'
+ } = {}
+) {
+ return {
+ statFile: async () => overrides.stat ?? okStat,
+ readArtifactHead: async () =>
+ overrides.head ?? makeHead(overrides.arch ?? 'x64'),
+ extractMimeType: async () => overrides.mime ?? FULL_MIME,
+ }
+}
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs.splice(0).map((dir) => rm(dir, { recursive: true }))
+ )
+})
+
+async function makeDir(files: string[]) {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'motrix-appimage-'))
+ tempDirs.push(dir)
+ for (const name of files) await writeFile(path.join(dir, name), name)
+ return dir
+}
+
+describe('expectedAppImageName', () => {
+ it('maps x64 to x86_64 and arm64 to arm64', () => {
+ expect(expectedAppImageName(VERSION, 'x64')).toBe(
+ 'Motrix-2.0.0-x86_64.AppImage'
+ )
+ expect(expectedAppImageName(VERSION, 'arm64')).toBe(
+ 'Motrix-2.0.0-arm64.AppImage'
+ )
+ })
+
+ it('rejects an unsupported architecture', () => {
+ expect(() => expectedAppImageName(VERSION, 'armv7l')).toThrow(
+ 'Unsupported AppImage arch'
+ )
+ })
+})
+
+describe('assertDesktopMimeTypes', () => {
+ it('accepts a MimeType value declaring all three handlers', () => {
+ expect(() => assertDesktopMimeTypes(FULL_MIME)).not.toThrow()
+ })
+
+ it('rejects a value missing a handler', () => {
+ expect(() =>
+ assertDesktopMimeTypes(
+ 'application/x-bittorrent;x-scheme-handler/magnet;'
+ )
+ ).toThrow('x-scheme-handler/motrix')
+ })
+
+ it('rejects an empty value', () => {
+ expect(() => assertDesktopMimeTypes('')).toThrow(REQUIRED_MIME_TYPES[0])
+ expect(() => assertDesktopMimeTypes(undefined)).toThrow(
+ REQUIRED_MIME_TYPES[0]
+ )
+ })
+})
+
+describe('assertAppImageHeader', () => {
+ it('accepts a valid ELF + AppImage type-2 header for the arch', () => {
+ expect(() => assertAppImageHeader(makeHead('x64'), 'x64')).not.toThrow()
+ expect(() => assertAppImageHeader(makeHead('arm64'), 'arm64')).not.toThrow()
+ })
+
+ it('rejects a non-ELF file', () => {
+ const notElf = Buffer.alloc(64)
+ expect(() => assertAppImageHeader(notElf, 'x64')).toThrow('not an ELF')
+ })
+
+ it('rejects an ELF without the AppImage type-2 magic', () => {
+ const head = makeHead('x64')
+ head[8] = 0 // clear the AI magic
+ expect(() => assertAppImageHeader(head, 'x64')).toThrow('AppImage type-2')
+ })
+
+ it('rejects a wrong-architecture ELF', () => {
+ // arm64 ELF verified against x64 target
+ expect(() => assertAppImageHeader(makeHead('arm64'), 'x64')).toThrow(
+ 'does not match x64'
+ )
+ })
+})
+
+describe('verifyAppimageArtifact', () => {
+ it('accepts exactly one correctly named, valid AppImage', async () => {
+ const dir = await makeDir([
+ 'Motrix-2.0.0-x86_64.AppImage',
+ 'Motrix-2.0.0-x86_64.AppImage.blockmap',
+ 'Motrix_2.0.0_amd64.deb',
+ ])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports(),
+ })
+ ).resolves.toEqual({ appImage: 'Motrix-2.0.0-x86_64.AppImage' })
+ })
+
+ it('rejects a missing AppImage', async () => {
+ const dir = await makeDir(['Motrix_2.0.0_amd64.deb'])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports(),
+ })
+ ).rejects.toThrow('Expected exactly one AppImage')
+ })
+
+ it('rejects more than one AppImage for a single architecture', async () => {
+ const dir = await makeDir([
+ 'Motrix-2.0.0-x86_64.AppImage',
+ 'Motrix-2.0.0-arm64.AppImage',
+ ])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports(),
+ })
+ ).rejects.toThrow('Expected exactly one AppImage')
+ })
+
+ it('rejects a wrong-arch AppImage name', async () => {
+ const dir = await makeDir(['Motrix-2.0.0-arm64.AppImage'])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports(),
+ })
+ ).rejects.toThrow('Unexpected AppImage name')
+ })
+
+ it('rejects a non-regular file', async () => {
+ const dir = await makeDir(['Motrix-2.0.0-x86_64.AppImage'])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports({ stat: { isFile: () => false, mode: 0o755 } }),
+ })
+ ).rejects.toThrow('not a regular file')
+ })
+
+ it('rejects a non-executable AppImage', async () => {
+ const dir = await makeDir(['Motrix-2.0.0-x86_64.AppImage'])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports({ stat: { isFile: () => true, mode: 0o644 } }),
+ })
+ ).rejects.toThrow('not executable')
+ })
+
+ it('rejects an artifact whose header is not a valid AppImage', async () => {
+ const dir = await makeDir(['Motrix-2.0.0-x86_64.AppImage'])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports({ head: Buffer.alloc(64) }),
+ })
+ ).rejects.toThrow('not an ELF')
+ })
+
+ it('rejects when the embedded desktop entry omits a handler', async () => {
+ const dir = await makeDir(['Motrix-2.0.0-x86_64.AppImage'])
+ await expect(
+ verifyAppimageArtifact({
+ directory: dir,
+ version: VERSION,
+ arch: 'x64',
+ ...ports({ mime: 'application/x-bittorrent;' }),
+ })
+ ).rejects.toThrow('missing MimeType handlers')
+ })
+})
diff --git a/tests/scripts/verify-update-artifacts.test.ts b/tests/scripts/verify-update-artifacts.test.ts
index 5efc2960..6029df9e 100644
--- a/tests/scripts/verify-update-artifacts.test.ts
+++ b/tests/scripts/verify-update-artifacts.test.ts
@@ -30,16 +30,20 @@ describe('verifyUpdateArtifacts', () => {
const fixture = await makeTempDir()
const deb = Buffer.from('signed Linux arm64 deb')
const rpm = Buffer.from('signed Linux arm64 rpm')
+ const appImage = Buffer.from('signed Linux arm64 AppImage')
const debName = 'Motrix_2.0.0_arm64.deb'
const rpmName = 'Motrix-2.0.0.aarch64.rpm'
+ const appImageName = 'Motrix-2.0.0-arm64.AppImage'
await writeFile(path.join(fixture, debName), deb)
await writeFile(path.join(fixture, rpmName), rpm)
+ await writeFile(path.join(fixture, appImageName), appImage)
await writeFile(
path.join(fixture, 'latest-linux-arm64.yml'),
manifest(
[
{ name: debName, content: deb },
{ name: rpmName, content: rpm },
+ { name: appImageName, content: appImage },
],
debName
)
@@ -49,7 +53,7 @@ describe('verifyUpdateArtifacts', () => {
verifyUpdateArtifacts({ directory: fixture, version: '2.0.0' })
).resolves.toEqual({
manifests: ['latest-linux-arm64.yml'],
- assets: [debName, rpmName],
+ assets: [debName, rpmName, appImageName],
})
})
@@ -206,7 +210,7 @@ describe('verifyUpdateArtifacts', () => {
).rejects.toThrow('legacy path/sha512 does not match files[]')
})
- it('requires both deb and rpm entries in Linux update manifests', async () => {
+ it('requires deb, rpm, and AppImage entries in Linux update manifests', async () => {
const fixture = await makeTempDir()
const deb = Buffer.from('deb only')
const debName = 'Motrix_2.0.0_amd64.deb'
@@ -219,6 +223,24 @@ describe('verifyUpdateArtifacts', () => {
await expect(
verifyUpdateArtifacts({ directory: fixture, version: '2.0.0' })
).rejects.toThrow('a .rpm asset is required for auto-update')
+
+ // With deb + rpm but no AppImage, the AppImage requirement is what fails.
+ const rpm = Buffer.from('rpm')
+ const rpmName = 'Motrix-2.0.0.x86_64.rpm'
+ await writeFile(path.join(fixture, rpmName), rpm)
+ await writeFile(
+ path.join(fixture, 'latest-linux.yml'),
+ manifest(
+ [
+ { name: debName, content: deb },
+ { name: rpmName, content: rpm },
+ ],
+ debName
+ )
+ )
+ await expect(
+ verifyUpdateArtifacts({ directory: fixture, version: '2.0.0' })
+ ).rejects.toThrow('a .AppImage asset is required for auto-update')
})
})
diff --git a/tests/scripts/workflow-release-matrix.test.ts b/tests/scripts/workflow-release-matrix.test.ts
index 8a1e6ac3..7b70535c 100644
--- a/tests/scripts/workflow-release-matrix.test.ts
+++ b/tests/scripts/workflow-release-matrix.test.ts
@@ -1314,7 +1314,7 @@ describe('release workflow publication contract', () => {
expect(paths).not.toContain('alpha')
})
- it('builds only deb and rpm Linux release assets', () => {
+ it('builds AppImage, deb, and rpm Linux release assets', () => {
const linuxTargets = targetMatrix(releaseWorkflow).entries.filter(
(entry) => entry.platform === 'linux'
)
@@ -1322,13 +1322,13 @@ describe('release workflow publication contract', () => {
expect(linuxTargets).toHaveLength(2)
for (const entry of linuxTargets) {
const args = stringField(entry, 'electron_builder_args')
+ expect(args).toMatch(/\bAppImage\b/)
expect(args).toMatch(/\bdeb\b/)
expect(args).toMatch(/\brpm\b/)
- expect(args).not.toMatch(/\bAppImage\b/)
expect(args).not.toMatch(/\bsnap\b/i)
}
expect(releaseSource).toContain(`\${{ matrix.electron_builder_args }}`)
- expect(releaseSource).not.toContain('release/*.AppImage')
+ expect(releaseSource).toContain('release/*.AppImage')
const buildJob = targetMatrix(releaseWorkflow).job
const linuxVerification = jobSteps(buildJob).find(
@@ -1341,7 +1341,18 @@ describe('release workflow publication contract', () => {
)
expect(verificationCommand).toContain('release/*.deb')
expect(verificationCommand).toContain('release/*.rpm')
- expect(verificationCommand).not.toContain('AppImage')
+ expect(verificationCommand).toContain('release/*.AppImage')
+
+ const appImageVerification = jobSteps(buildJob).find(
+ (step) => step.name === 'Verify AppImage artifact'
+ )
+ expect(appImageVerification).toBeDefined()
+ expect(stringField(appImageVerification as LooseRecord, 'if')).toContain(
+ "matrix.platform == 'linux'"
+ )
+ expect(stringField(appImageVerification as LooseRecord, 'run')).toContain(
+ 'scripts/verify-appimage-artifact.mjs'
+ )
})
it('publishes required Flatpak companions outside updater manifests', () => {