Skip to content

A full-featured download manager.

feat(platform): add system default app controls (#1957)

Dr_rOotdf1c970605b3
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c5f362d1..b02a607d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -834,7 +834,7 @@ jobs:
EXPECTED_COMMIT: ${{ github.sha }}
EXPECTED_PLATFORM: ${{ matrix.platform }}
# Updated only after reviewing the verifier source itself.
- VERIFIER_SHA256: 26cb8514c972c2f25964a0010167dd9a8375e81adab51298030258fa8b72dfd9
+ VERIFIER_SHA256: fad12bb2744c53a65c0d3197585064ffa240cbdc16e4d4c3902860174569bbdb
run: |
const crypto = require('node:crypto')
const fs = require('node:fs')
diff --git a/build/installer.nsh b/build/installer.nsh
index 2482c462..40a82d94 100644
--- a/build/installer.nsh
+++ b/build/installer.nsh
@@ -1,12 +1,96 @@
+!define MOTRIX_REGISTERED_APP_NAME "Motrix"
+!define MOTRIX_CAPABILITIES_KEY "Software\Motrix\Capabilities"
+!define MOTRIX_TORRENT_PROGID "Motrix.File.Torrent"
+!define MOTRIX_MAGNET_PROGID "Motrix.Url.Magnet"
+!define MOTRIX_PROTOCOL "motrix"
+
+!macro deleteLegacyMotrixProtocolHandlers
+ ; Electron versions before installer-owned registration wrote URL handlers
+ ; into HKCU at runtime. Remove the proprietary scheme unconditionally, then
+ ; remove a legacy magnet command only when it names the Motrix executable.
+ ; This also prevents an old HKCU handler from shadowing a new all-users
+ ; registration during a per-user -> per-machine update.
+ DeleteRegKey HKCU "Software\Classes\${MOTRIX_PROTOCOL}"
+
+ ReadRegStr $0 HKCU "Software\Classes\magnet\shell\open\command" ""
+ ${StrContains} $1 '\${APP_EXECUTABLE_FILENAME}"' $0
+ ${if} $1 != ""
+ DeleteRegKey HKCU "Software\Classes\magnet\shell"
+ ${endif}
+!macroend
+
+!macro registerMotrixDefaultApps
+ ; Advertise Motrix in Windows Settings > Apps > Default apps without
+ ; changing the protected per-user default choice.
+ WriteRegStr SHELL_CONTEXT "${MOTRIX_CAPABILITIES_KEY}" "ApplicationDescription" "${APP_DESCRIPTION}"
+ WriteRegStr SHELL_CONTEXT "${MOTRIX_CAPABILITIES_KEY}" "ApplicationName" "${MOTRIX_REGISTERED_APP_NAME}"
+ WriteRegStr SHELL_CONTEXT "${MOTRIX_CAPABILITIES_KEY}" "ApplicationIcon" '"$appExe",0'
+ WriteRegStr SHELL_CONTEXT "${MOTRIX_CAPABILITIES_KEY}\FileAssociations" ".torrent" "${MOTRIX_TORRENT_PROGID}"
+ WriteRegStr SHELL_CONTEXT "${MOTRIX_CAPABILITIES_KEY}\UrlAssociations" "magnet" "${MOTRIX_MAGNET_PROGID}"
+ WriteRegStr SHELL_CONTEXT "Software\RegisteredApplications" "${MOTRIX_REGISTERED_APP_NAME}" "${MOTRIX_CAPABILITIES_KEY}"
+
+ ; Register application-specific ProgIDs so a Windows user choice always
+ ; resolves to Motrix rather than a generic class another client can replace.
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_TORRENT_PROGID}" "" "Torrent File"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_TORRENT_PROGID}" "Content Type" "application/x-bittorrent"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_TORRENT_PROGID}\DefaultIcon" "" '"$appExe",0'
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_TORRENT_PROGID}\shell" "" "open"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_TORRENT_PROGID}\shell\open\command" "" '"$appExe" "%1"'
+ WriteRegStr SHELL_CONTEXT "Software\Classes\.torrent" "Content Type" "application/x-bittorrent"
+ WriteRegNone SHELL_CONTEXT "Software\Classes\.torrent\OpenWithProgids" "${MOTRIX_TORRENT_PROGID}"
+
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}" "" "Magnet URI"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}" "Content Type" "application/x-magnet"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}" "URL Protocol" ""
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}\DefaultIcon" "" '"$appExe",0'
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}\shell" "" "open"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}\shell\open\command" "" '"$appExe" "%1"'
+ WriteRegStr SHELL_CONTEXT "Software\Classes\magnet" "" "URL:Magnet URI"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\magnet" "Content Type" "application/x-magnet"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\magnet" "URL Protocol" ""
+
+ ; motrix: is proprietary and does not need a Default Apps user choice. Keep
+ ; it installer-owned so deep links work without Electron writing HKCU keys.
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_PROTOCOL}" "" "URL:Motrix Protocol"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_PROTOCOL}" "URL Protocol" ""
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_PROTOCOL}\DefaultIcon" "" '"$appExe",0'
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_PROTOCOL}\shell" "" "open"
+ WriteRegStr SHELL_CONTEXT "Software\Classes\${MOTRIX_PROTOCOL}\shell\open\command" "" '"$appExe" "%1"'
+
+ System::Call 'shell32::SHChangeNotify(i, i, i, i) v (0x08000000, 0, 0, 0)'
+!macroend
+
+!macro deleteMotrixDefaultApps
+ DeleteRegValue SHELL_CONTEXT "Software\RegisteredApplications" "${MOTRIX_REGISTERED_APP_NAME}"
+ DeleteRegKey SHELL_CONTEXT "${MOTRIX_CAPABILITIES_KEY}"
+ DeleteRegValue SHELL_CONTEXT "Software\Classes\.torrent\OpenWithProgids" "${MOTRIX_TORRENT_PROGID}"
+ DeleteRegKey SHELL_CONTEXT "Software\Classes\${MOTRIX_TORRENT_PROGID}"
+ DeleteRegKey SHELL_CONTEXT "Software\Classes\${MOTRIX_MAGNET_PROGID}"
+ DeleteRegKey SHELL_CONTEXT "Software\Classes\${MOTRIX_PROTOCOL}"
+
+ ; Generic .torrent/magnet metadata is shared with other clients, so leave it
+ ; intact and remove only Motrix-owned registration.
+ System::Call 'shell32::SHChangeNotify(i, i, i, i) v (0x08000000, 0, 0, 0)'
+!macroend
+
!macro deleteMotrixNativeMessagingKeys
DeleteRegKey HKCU "SOFTWARE\Google\Chrome\NativeMessagingHosts\app.motrix.bridge"
DeleteRegKey HKCU "SOFTWARE\Microsoft\Edge\NativeMessagingHosts\app.motrix.bridge"
DeleteRegKey HKCU "SOFTWARE\Mozilla\NativeMessagingHosts\app.motrix.bridge"
!macroend
+!macro customInstall
+ !insertmacro deleteLegacyMotrixProtocolHandlers
+ !insertmacro registerMotrixDefaultApps
+!macroend
+
!macro customUnInstall
; electron-builder also runs the previous uninstaller during an update.
- ; Preserve Native Messaging registration unless this is a real uninstall.
+ ; Always remove the old install scope so a per-user registration cannot
+ ; shadow a new per-machine registration. The new installer immediately
+ ; rewrites the selected scope after an update.
+ !insertmacro deleteMotrixDefaultApps
+
${ifNot} ${isUpdated}
!insertmacro deleteMotrixNativeMessagingKeys
diff --git a/electron-builder.json b/electron-builder.json
index 36abec9a..4beb82c9 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -86,14 +86,6 @@
"schemes": ["magnet"]
}
],
- "fileAssociations": [
- {
- "ext": "torrent",
- "mimeType": "application/x-bittorrent",
- "name": "Torrent",
- "role": "Viewer"
- }
- ],
"mac": {
"category": "public.app-category.utilities",
"type": "distribution",
@@ -106,6 +98,14 @@
"entitlements": "build/entitlements.mac.plist",
"entitlementsInherit": "build/entitlements.mac.plist",
"darkModeSupport": true,
+ "fileAssociations": [
+ {
+ "ext": "torrent",
+ "mimeType": "application/x-bittorrent",
+ "name": "Torrent",
+ "role": "Viewer"
+ }
+ ],
"extendInfo": {
"NSLocalNetworkUsageDescription": "Motrix uses the local network for UPnP port mapping and discovering download peers."
},
@@ -171,6 +171,14 @@
"category": "Network",
"synopsis": "Full-featured download manager",
"description": "Motrix is a full-featured download manager that supports HTTP, FTP, BitTorrent and Magnet downloads.",
+ "fileAssociations": [
+ {
+ "ext": "torrent",
+ "mimeType": "application/x-bittorrent",
+ "name": "Torrent",
+ "role": "Viewer"
+ }
+ ],
"mimeTypes": [
"application/x-bittorrent",
"x-scheme-handler/magnet",
diff --git a/electron-builder.signing.json b/electron-builder.signing.json
index abb7f583..5bfe3bda 100644
--- a/electron-builder.signing.json
+++ b/electron-builder.signing.json
@@ -84,14 +84,6 @@
"schemes": ["magnet"]
}
],
- "fileAssociations": [
- {
- "ext": "torrent",
- "mimeType": "application/x-bittorrent",
- "name": "Torrent",
- "role": "Viewer"
- }
- ],
"mac": {
"category": "public.app-category.utilities",
"type": "distribution",
@@ -104,6 +96,14 @@
"entitlements": "signing-build-resources/entitlements.mac.plist",
"entitlementsInherit": "signing-build-resources/entitlements.mac.plist",
"darkModeSupport": true,
+ "fileAssociations": [
+ {
+ "ext": "torrent",
+ "mimeType": "application/x-bittorrent",
+ "name": "Torrent",
+ "role": "Viewer"
+ }
+ ],
"extendInfo": {
"NSLocalNetworkUsageDescription": "Motrix uses the local network for UPnP port mapping and discovering download peers."
},
diff --git a/scripts/release-signing-input.mjs b/scripts/release-signing-input.mjs
index eedbc987..5667b459 100644
--- a/scripts/release-signing-input.mjs
+++ b/scripts/release-signing-input.mjs
@@ -35,7 +35,7 @@ export const SIGNING_ARCHIVE_LIMITS = Object.freeze({
const TRUSTED_INPUT_SHA256 = Object.freeze({
'electron-builder.signing.json':
- '8657e48dd7a1cb2833e0ee3011ee9a0a28549bbe68e9c8ba5b45693612345de3',
+ '2950c8fb4ebe86a46d384efc373c3fb2b7d08389699fe1ab4ecb54e319dd5cd0',
'signing-build-resources/256x256.png':
'044d3b64a14aa512ca41469372d1ad630557daaeb2cb4e709d34f2d3c57d4c3b',
'signing-build-resources/background.tiff':
@@ -51,7 +51,7 @@ const TRUSTED_INPUT_SHA256 = Object.freeze({
'signing-build-resources/torrent.ico':
'7743ad382011e30236e91322164f0ebd20c283e634db44c36f314aa2abf2f5a8',
'signing-policy/installer.nsh':
- '961d33dafec6c6deab622b473217896a6fc64abbcd0cb30dadc5308d026eeeb4',
+ 'b1238c611da39f9cdf8489de01f88f31cb377b67668353aad2d9d3d1e17701f5',
'signing-tool/package.json':
'b8ddd0e1bb90198d99628eb8b5b8c3c2b8cbda4a3aee48f118a36244467fac51',
'signing-tool/package-lock.json':
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 6529377d..35e5e67a 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -6,14 +6,41 @@ import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
+import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
import { CliPackageManager } from '@shared/types/cli-tool'
import { TaskInstancePhase, TaskStatus, TaskType } from '@shared/types/task'
import { directTaskUpdatePublication } from '@test-utils/task-update'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MainProcessWorkCoordinator } from '../main-process-work-coordinator'
+import { WINDOWS_DEFAULT_APPS_SETTINGS_URL } from '../platform/windows-default-apps'
import type { CommandContext } from './commands'
import { buildCommandHandlers, registerCommandHandlers } from './commands'
+const { resolveWindowsDefaultAppsSettingsUrlMock } = vi.hoisted(() => ({
+ resolveWindowsDefaultAppsSettingsUrlMock: vi.fn(
+ async () => 'ms-settings:defaultapps'
+ ),
+}))
+const { reconcileAppImageIntegrationFromSettingsMock } = vi.hoisted(() => ({
+ reconcileAppImageIntegrationFromSettingsMock: vi.fn(
+ async (_options: {
+ getMagnetEnabled: () => boolean
+ }): Promise<AppImageIntegrationView> => ({ supported: false })
+ ),
+}))
+
+vi.mock('../platform/appimage-integration-host', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ reconcileAppImageIntegrationFromSettings:
+ reconcileAppImageIntegrationFromSettingsMock,
+}))
+
+vi.mock('../platform/windows-default-apps', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ resolveWindowsDefaultAppsSettingsUrl:
+ resolveWindowsDefaultAppsSettingsUrlMock,
+}))
+
// Mock electron so BrowserWindow.fromWebContents can be stubbed in the
// Window-bound command tests. ipcMain/dialog are not invoked by buildCommandHandlers,
// but we stub them for safety.
@@ -839,6 +866,42 @@ describe('buildCommandHandlers', () => {
)
})
+ it('opens the compatible Default Apps page on Windows', async () => {
+ const platformDescriptor = Object.getOwnPropertyDescriptor(
+ process,
+ 'platform'
+ )
+ if (!platformDescriptor) throw new Error('process.platform is unavailable')
+
+ openExternalMock.mockReset()
+ openExternalMock.mockResolvedValue(undefined)
+ resolveWindowsDefaultAppsSettingsUrlMock.mockReset()
+ resolveWindowsDefaultAppsSettingsUrlMock.mockResolvedValue(
+ WINDOWS_DEFAULT_APPS_SETTINGS_URL
+ )
+ Object.defineProperty(process, 'platform', {
+ ...platformDescriptor,
+ value: 'win32',
+ })
+
+ try {
+ const handlers = buildCommandHandlers(
+ fakeCtx() as unknown as CommandContext
+ )
+
+ await expect(
+ handlers[Commands.RequestDefaultTorrentHandler]?.()
+ ).resolves.toEqual({ ok: true, action: 'opened-settings' })
+ expect(openExternalMock).toHaveBeenCalledOnce()
+ expect(openExternalMock).toHaveBeenCalledWith(
+ WINDOWS_DEFAULT_APPS_SETTINGS_URL
+ )
+ expect(resolveWindowsDefaultAppsSettingsUrlMock).toHaveBeenCalledOnce()
+ } finally {
+ Object.defineProperty(process, 'platform', platformDescriptor)
+ }
+ })
+
it('forwards add-task prefill only after the window finishes loading', async () => {
let didFinishLoad: (() => void) | undefined
const send = vi.fn()
@@ -1074,6 +1137,116 @@ describe('Commands.UpdateSettings', () => {
}
const PROXY_ON = { ...PROXY_OFF, enabled: true, host: 'p.example', port: 80 }
+ it('applies a saved magnet preference immediately to protocol owners', async () => {
+ reconcileAppImageIntegrationFromSettingsMock.mockClear()
+ const ctx = fakeCtx()
+ const before = makeSettingsLike(PROXY_OFF, {
+ protocols: { magnet: false },
+ })
+ const after = makeSettingsLike(PROXY_OFF, {
+ protocols: { magnet: true },
+ })
+ const settingsManager = {
+ ...ctx.settingsManager,
+ get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),
+ update: vi.fn().mockResolvedValue({
+ ok: true,
+ requiresRestart: false,
+ changedRestartKeys: [],
+ }),
+ }
+ const protocolManager = {
+ register: vi.fn(() => ({ magnetMatchesSetting: true })),
+ }
+ const handlers = buildCommandHandlers({
+ ...ctx,
+ settingsManager,
+ protocolManager,
+ } as unknown as CommandContext)
+
+ const updateResult = await handlers[Commands.UpdateSettings]?.({
+ app: { protocols: { magnet: true } },
+ })
+
+ expect(protocolManager.register).toHaveBeenCalledOnce()
+ expect(reconcileAppImageIntegrationFromSettingsMock).toHaveBeenCalledOnce()
+ const options =
+ reconcileAppImageIntegrationFromSettingsMock.mock.calls[0]?.[0]
+ expect(options?.getMagnetEnabled()).toBe(true)
+ expect(updateResult).toMatchObject({ protocolAssociationApplied: true })
+ })
+
+ it('returns an explicit association failure after saving the preference', async () => {
+ reconcileAppImageIntegrationFromSettingsMock.mockResolvedValueOnce({
+ supported: true,
+ decision: 'accepted',
+ owner: 'self',
+ status: 'failed',
+ })
+ const ctx = fakeCtx()
+ const before = makeSettingsLike(PROXY_OFF, {
+ protocols: { magnet: true },
+ })
+ const after = makeSettingsLike(PROXY_OFF, {
+ protocols: { magnet: false },
+ })
+ const settingsManager = {
+ ...ctx.settingsManager,
+ get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),
+ update: vi.fn().mockResolvedValue({
+ ok: true,
+ requiresRestart: false,
+ changedRestartKeys: [],
+ }),
+ }
+ const handlers = buildCommandHandlers({
+ ...ctx,
+ settingsManager,
+ protocolManager: {
+ register: vi.fn(() => ({ magnetMatchesSetting: null })),
+ },
+ } as unknown as CommandContext)
+
+ await expect(
+ handlers[Commands.UpdateSettings]?.({
+ app: { protocols: { magnet: false } },
+ })
+ ).resolves.toMatchObject({ protocolAssociationApplied: false })
+ expect(settingsManager.update).toHaveBeenCalledOnce()
+ })
+
+ it('retries an explicitly submitted magnet preference even when already saved', async () => {
+ reconcileAppImageIntegrationFromSettingsMock.mockClear()
+ const ctx = fakeCtx()
+ const settings = makeSettingsLike(PROXY_OFF, {
+ protocols: { magnet: false },
+ })
+ const settingsManager = {
+ ...ctx.settingsManager,
+ get: vi.fn().mockReturnValue(settings),
+ update: vi.fn().mockResolvedValue({
+ ok: true,
+ requiresRestart: false,
+ changedRestartKeys: [],
+ }),
+ }
+ const protocolManager = {
+ register: vi.fn(() => ({ magnetMatchesSetting: true })),
+ }
+ const handlers = buildCommandHandlers({
+ ...ctx,
+ settingsManager,
+ protocolManager,
+ } as unknown as CommandContext)
+
+ await handlers[Commands.UpdateSettings]?.({
+ app: { protocols: { magnet: false } },
+ })
+
+ expect(protocolManager.register).toHaveBeenCalledOnce()
+ expect(reconcileAppImageIntegrationFromSettingsMock).toHaveBeenCalled()
+ })
+
it('does not invoke proxyApplier when proxy unchanged', async () => {
const ctx = fakeCtx()
const settings = makeSettingsLike(PROXY_OFF)
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 7195722a..fe6de08d 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -1,7 +1,5 @@
-import { execFile } from 'node:child_process'
-import { access, rm } from 'node:fs/promises'
+import { rm } from 'node:fs/promises'
import path from 'node:path'
-import { promisify } from 'node:util'
import type { AdaptedMux } from '@core/bridge-receiver/submit-download-adapter'
import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'
import { dnsModeToAsyncDns } from '@core/engine/aria2/dns-fallback'
@@ -106,10 +104,13 @@ import type { ContextStore } from '../commands/context-store'
import type { UpdateManager } from '../core/update-manager'
import {
enableAppImageIntegrationFromSettings,
+ reconcileAppImageIntegrationFromSettings,
removeAppImageIntegrationFromSettings,
} from '../platform/appimage-integration-host'
import { syncAutoLaunch } from '../platform/auto-launch'
+import { setLinuxDefaultTorrentHandler } from '../platform/linux-default-apps'
import type { createProtocolManager } from '../platform/protocol-manager'
+import { resolveWindowsDefaultAppsSettingsUrl } from '../platform/windows-default-apps'
import type { createMainProxyApplier } from '../proxy/wiring'
import type { WindowManager } from '../window/window-manager'
import { createRevealInFolderHandler } from './commands/reveal-in-folder'
@@ -119,52 +120,10 @@ import { NatCommandHandlers } from './nat-commands'
import { applyNatPrivacyGate } from './nat-settings-gate'
import { registerTrustedIpcHandler } from './trusted-ipc'
-const execFileAsync = promisify(execFile)
-
-const TORRENT_MIME_TYPE = 'application/x-bittorrent'
const cliInstallRequestSchema = z
.object({ packageManager: z.enum(CLI_INSTALL_PACKAGE_MANAGERS) })
.strict()
-// .desktop ID is non-deterministic across electron-builder versions / linux
-// distros (productName / executableName / appId all map to it differently).
-// Probe a small list of likely names against the standard application
-// directories so we only call xdg-mime with a real handler.
-const LINUX_DESKTOP_CANDIDATES = [
- 'motrix.desktop',
- 'motrix-turbo.desktop',
- 'app.motrix.native.desktop',
-]
-
-async function findInstalledMotrixDesktopFile(): Promise<string | null> {
- const home = process.env.HOME
- const dirs = [
- '/usr/share/applications',
- '/usr/local/share/applications',
- home ? path.join(home, '.local/share/applications') : null,
- ].filter((d): d is string => Boolean(d))
-
- for (const dir of dirs) {
- for (const name of LINUX_DESKTOP_CANDIDATES) {
- try {
- await access(path.join(dir, name))
- return name
- } catch {
- // not in this dir, keep probing
- }
- }
- }
- return null
-}
-
-async function setLinuxDefaultTorrentHandler(): Promise<void> {
- const desktopId = await findInstalledMotrixDesktopFile()
- if (!desktopId) {
- throw new Error('motrix .desktop file not found in known locations')
- }
- await execFileAsync('xdg-mime', ['default', desktopId, TORRENT_MIME_TYPE])
-}
-
export interface CommandContext {
cliToolService: Pick<CliToolService, 'install'>
supervisor: EngineSupervisor
@@ -983,6 +942,11 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
// Build a patched partial that reflects the user's dialog choice.
const partialObj = partial as Record<string, unknown> | null | undefined
+ const appPartial = partialObj?.app as
+ | { protocols?: { magnet?: unknown } }
+ | undefined
+ const magnetPreferenceSubmitted =
+ typeof appPartial?.protocols?.magnet === 'boolean'
const patched = {
...partialObj,
nat: {
@@ -994,6 +958,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
const result = await settingsManager.update(patched)
const newFull = settingsManager.get()
+ let protocolAssociationApplied: boolean | undefined
if (oldFull.app.updateChannel !== newFull.app.updateChannel) {
updateManager.setChannel(newFull.app.updateChannel)
@@ -1007,8 +972,24 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
) {
await bridgeManager.setEnabled(newFull.app.browserBridgeEnabled)
}
- if (oldFull.app.protocols.magnet !== newFull.app.protocols.magnet) {
- protocolManager.register()
+ if (
+ magnetPreferenceSubmitted ||
+ oldFull.app.protocols.magnet !== newFull.app.protocols.magnet
+ ) {
+ const registration = protocolManager.register()
+ if (registration?.magnetMatchesSetting !== null) {
+ protocolAssociationApplied = registration?.magnetMatchesSetting
+ }
+ const appImageView = await reconcileAppImageIntegrationFromSettings({
+ getMagnetEnabled: () => newFull.app.protocols.magnet,
+ })
+ if (
+ appImageView.supported &&
+ appImageView.decision === 'accepted' &&
+ appImageView.owner === 'self'
+ ) {
+ protocolAssociationApplied = appImageView.status === 'healthy'
+ }
}
if (proxyChanged(oldFull.proxy, newFull.proxy)) {
@@ -1052,7 +1033,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
)
}
- return result
+ return protocolAssociationApplied === undefined
+ ? result
+ : { ...result, protocolAssociationApplied }
},
[Commands.RestartEngine]: async () => {
@@ -1210,7 +1193,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
}
if (process.platform === 'win32') {
try {
- await shell.openExternal('ms-settings:defaultapps')
+ await shell.openExternal(await resolveWindowsDefaultAppsSettingsUrl())
return { ok: true, action: 'opened-settings' as const }
} catch {
await shell.openExternal(
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index 706c089e..2be1163e 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -226,6 +226,12 @@ describe('buildQueryHandlers', () => {
expect(handlers[Queries.GetUpdateState]).toBeInstanceOf(Function)
expect(handlers[Queries.GetEngineStatus]).toBeInstanceOf(Function)
expect(handlers[Queries.GetEngineDiagnostics]).toBeInstanceOf(Function)
+ expect(handlers[Queries.GetLinuxDefaultAssociations]).toBeInstanceOf(
+ Function
+ )
+ expect(handlers[Queries.GetWindowsDefaultAssociations]).toBeInstanceOf(
+ Function
+ )
expect(handlers[Queries.GetTaskFiles]).toBeInstanceOf(Function)
expect(handlers[Queries.GetNatStatus]).toBeInstanceOf(Function)
expect(handlers[Queries.GetNatDiagnostic]).toBeInstanceOf(Function)
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 70220ce8..81753d47 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -46,6 +46,8 @@ 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 { getLinuxDefaultAssociations } from '../platform/linux-default-apps'
+import { getWindowsDefaultAssociations } from '../platform/windows-default-apps'
import { makeElectronFfmpegDetect } from '../plugin/ffmpeg-detect-electron'
import { createGetEngineTaskOptionsHandler } from './queries/get-engine-task-options'
import { createGetGeoIPStatusHandler } from './queries/get-geo-ip-status'
@@ -171,7 +173,15 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
},
[Queries.GetAppImageIntegrationStatus]: async () =>
- getAppImageIntegrationView(),
+ getAppImageIntegrationView({
+ getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
+ }),
+
+ [Queries.GetLinuxDefaultAssociations]: async () =>
+ getLinuxDefaultAssociations(),
+
+ [Queries.GetWindowsDefaultAssociations]: async () =>
+ getWindowsDefaultAssociations(),
[Queries.GetEngineStatus]: async () => {
return supervisor.getStatus()
diff --git a/src/main/platform/appimage-integration-host.ts b/src/main/platform/appimage-integration-host.ts
index aa258cb5..6a996d68 100644
--- a/src/main/platform/appimage-integration-host.ts
+++ b/src/main/platform/appimage-integration-host.ts
@@ -15,6 +15,7 @@ import {
type IntegrationFs,
type IntegrationRecord,
type IntegrationStore,
+ inspectSystemIntegration,
parseIntegrationRecord,
removeSystemIntegration,
runStartupIntegration,
@@ -167,11 +168,25 @@ export async function setupAppImageIntegration(
}
}
-// 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 status query (Queries.GetAppImageIntegrationStatus): validates the
+// persisted healthy state without mutating desktop files or defaults.
+export async function getAppImageIntegrationView(
+ opts: SetupAppImageIntegrationOptions
+): Promise<AppImageIntegrationView> {
+ const appImagePath = appImageEnvironmentPath()
+ if (!appImagePath) return { supported: false }
+ const deps = buildDeps(appImagePath, opts, async () => false)
+ try {
+ return toView(await inspectSystemIntegration(deps))
+ } catch (err) {
+ deps.log.warn({ err }, 'appimage integration status validation failed')
+ const record = await deps.store.load()
+ return toView(
+ record.decision === 'accepted' && record.owner === 'self'
+ ? { ...record, status: 'failed' }
+ : record
+ )
+ }
}
// Settings action (Commands.EnableAppImageIntegration). The user clicked the
@@ -208,6 +223,29 @@ export async function removeAppImageIntegrationFromSettings(
}
}
+// Apply a saved magnet preference immediately for an existing self-owned
+// AppImage integration. This deliberately does not prompt or create a new
+// integration: users who declined (or have an externally-owned package) keep
+// that decision, while an accepted integration no longer needs an app restart
+// before its magnet default converges.
+export async function reconcileAppImageIntegrationFromSettings(
+ opts: SetupAppImageIntegrationOptions
+): Promise<AppImageIntegrationView> {
+ const appImagePath = appImageEnvironmentPath()
+ if (!appImagePath) return { supported: false }
+ const deps = buildDeps(appImagePath, opts, async () => false)
+ try {
+ const current = await deps.store.load()
+ if (current.decision !== 'accepted' || current.owner !== 'self') {
+ return toView(current)
+ }
+ return toView(await runStartupIntegration(deps))
+ } catch (err) {
+ deps.log.warn({ err }, 'appimage settings reconciliation 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
diff --git a/src/main/platform/appimage-integration.test.ts b/src/main/platform/appimage-integration.test.ts
index ba5ce231..e7e1466b 100644
--- a/src/main/platform/appimage-integration.test.ts
+++ b/src/main/platform/appimage-integration.test.ts
@@ -13,6 +13,7 @@ import {
type IntegrationRecord,
type IntegrationStore,
iconFilePath,
+ inspectSystemIntegration,
isOwnedBySelf,
isSafeAppImagePath,
isSafeDesktopId,
@@ -22,6 +23,7 @@ import {
parseDesktopEntry,
parseExecValue,
parseIntegrationRecord,
+ removeDesktopIdFromMimeApps,
removeSystemIntegration,
resolveXdgDataHome,
runStartupIntegration,
@@ -68,7 +70,8 @@ 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()
+ unreadable: Set<string> = new Set(),
+ onWrite?: (filePath: string, data: string) => void
): IntegrationFs & {
files: Map<string, string>
} {
@@ -77,6 +80,7 @@ function createFakeFs(
files,
writeText: vi.fn(async (p: string, data: string) => {
files.set(p, data)
+ onWrite?.(p, data)
}),
readText: vi.fn(async (p: string) => {
if (unreadable.has(p))
@@ -104,6 +108,19 @@ function createFakeFs(
}
}
+function syncFakeDefaultsFromMimeApps(xdg: FakeXdg, content: string): void {
+ for (const mime of [
+ 'x-scheme-handler/motrix',
+ 'application/x-bittorrent',
+ 'x-scheme-handler/magnet',
+ ]) {
+ const escaped = mime.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ const value = new RegExp(`^${escaped}=([^;]+);`, 'mu').exec(content)?.[1]
+ if (value) xdg.defaults.set(mime, value)
+ else xdg.defaults.delete(mime)
+ }
+}
+
interface FakeXdg {
runCommand: (
command: string,
@@ -228,6 +245,35 @@ describe('isSafeDesktopId', () => {
})
})
+describe('removeDesktopIdFromMimeApps', () => {
+ it('removes only the owned default and preserves fallback handlers', () => {
+ const source = [
+ '# keep',
+ '[Default Applications]',
+ 'x-scheme-handler/magnet=motrix-appimage.desktop;firefox.desktop;',
+ 'application/pdf=org.pwmt.zathura.desktop;',
+ '',
+ '[Added Associations]',
+ 'x-scheme-handler/magnet=motrix-appimage.desktop;',
+ '',
+ ].join('\n')
+
+ expect(
+ removeDesktopIdFromMimeApps(
+ source,
+ 'x-scheme-handler/magnet',
+ DESKTOP_ENTRY_ID
+ )
+ ).toEqual({
+ changed: true,
+ content: source.replace(
+ 'x-scheme-handler/magnet=motrix-appimage.desktop;firefox.desktop;',
+ 'x-scheme-handler/magnet=firefox.desktop;'
+ ),
+ })
+ })
+})
+
// ── Exec serialization ──────────────────────────────────
describe('serializeExecValue / parseExecValue', () => {
@@ -603,8 +649,13 @@ describe('runStartupIntegration', () => {
// previous default (a phantom id would not be).
[`${dataHome0}/applications/firefox.desktop`]:
'[Desktop Entry]\nType=Application\nExec=/usr/bin/firefox %u\n',
+ [`${dataHome0}/applications/transmission.desktop`]:
+ '[Desktop Entry]\nType=Application\nExec=/usr/bin/transmission %f\n',
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': 'firefox.desktop',
+ 'application/x-bittorrent': 'transmission.desktop',
})
- const xdg = createFakeXdg({ 'x-scheme-handler/motrix': 'firefox.desktop' })
const prompt = vi.fn(async () => true)
await runStartupIntegration(baseDeps({ store, fs, xdg, prompt }))
@@ -618,6 +669,7 @@ describe('runStartupIntegration', () => {
// previous handler recorded before override
expect(store.record.previousSchemeHandler).toBe('firefox.desktop')
+ expect(store.record.previousTorrentHandler).toBe('transmission.desktop')
// final state healthy, self-owned, with a persisted id + icon hash
expect(store.record.decision).toBe('accepted')
expect(store.record.owner).toBe('self')
@@ -645,6 +697,7 @@ describe('runStartupIntegration', () => {
expect(setIndex).toBeGreaterThan(dbIndex)
// default was verified by re-query afterwards
expect(xdg.defaults.get('x-scheme-handler/motrix')).toBe(DESKTOP_ENTRY_ID)
+ expect(xdg.defaults.get('application/x-bittorrent')).toBe(DESKTOP_ENTRY_ID)
})
it('fails closed without writing when the AppImage path has control chars', async () => {
@@ -857,6 +910,74 @@ describe('runStartupIntegration', () => {
expect(xdg.defaults.get('x-scheme-handler/motrix')).toBe(DESKTOP_ENTRY_ID)
})
+ it('clears an owned magnet default when there was no previous handler', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const mimeAppsPath = '/home/u/.config/mimeapps.list'
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID,
+ 'x-scheme-handler/magnet': DESKTOP_ENTRY_ID,
+ })
+ const fs = createFakeFs(
+ {
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [ICON_SOURCE]: 'PNGDATA',
+ [mimeAppsPath]:
+ '[Default Applications]\nx-scheme-handler/magnet=motrix-appimage.desktop;\n',
+ },
+ new Set(),
+ (filePath, content) => {
+ if (filePath === mimeAppsPath) {
+ syncFakeDefaultsFromMimeApps(xdg, content)
+ xdg.defaults.set('x-scheme-handler/motrix', DESKTOP_ENTRY_ID)
+ }
+ }
+ )
+
+ await runStartupIntegration(
+ baseDeps({ store, fs, xdg, getMagnetEnabled: () => false })
+ )
+
+ expect(xdg.defaults.has('x-scheme-handler/magnet')).toBe(false)
+ expect(store.record.status).toBe('healthy')
+ expect(fs.files.get(mimeAppsPath)).not.toContain(
+ 'x-scheme-handler/magnet=motrix-appimage.desktop;'
+ )
+ })
+
+ it('marks reconciliation failed when an owned magnet default cannot be cleared', async () => {
+ const dataHome = '/home/u/.local/share'
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ })
+ const fs = createFakeFs({
+ [desktopEntryFilePath(dataHome)]: ownedEntry(APPIMAGE),
+ [ICON_SOURCE]: 'PNGDATA',
+ })
+ 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(DESKTOP_ENTRY_ID)
+ expect(store.record.status).toBe('failed')
+ })
+
it('persists the install id before writing files (crash recovery)', async () => {
const store = createFakeStore({ decision: 'unset' })
const fs = createFakeFs({ [ICON_SOURCE]: 'PNGDATA' })
@@ -1030,6 +1151,41 @@ describe('enableSystemIntegration', () => {
})
})
+describe('inspectSystemIntegration', () => {
+ it('downgrades a stale persisted healthy state without mutating the store', 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'),
+ })
+ const fs = createFakeFs({
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [iconPath]: 'PNGDATA',
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID,
+ 'application/x-bittorrent': DESKTOP_ENTRY_ID,
+ })
+ const deps = baseDeps({ store, fs, xdg, getMagnetEnabled: () => false })
+
+ await expect(inspectSystemIntegration(deps)).resolves.toMatchObject({
+ status: 'healthy',
+ })
+ fs.files.delete(desktopPath)
+ await expect(inspectSystemIntegration(deps)).resolves.toMatchObject({
+ status: 'failed',
+ })
+ expect(store.record.status).toBe('healthy')
+ expect(store.save).not.toHaveBeenCalled()
+ })
+})
+
describe('removeSystemIntegration', () => {
it('is a no-op for an externally-owned integration', async () => {
const store = createFakeStore({
@@ -1060,6 +1216,7 @@ describe('removeSystemIntegration', () => {
installId: TEST_INSTALL_ID,
iconSha256: sha256Hex('PNGDATA'),
previousSchemeHandler: 'firefox.desktop',
+ previousTorrentHandler: 'transmission.desktop',
})
const fs = createFakeFs({
[desktopPath]: ownedEntry(APPIMAGE),
@@ -1067,16 +1224,70 @@ describe('removeSystemIntegration', () => {
// 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',
+ [`${dataHome}/applications/transmission.desktop`]:
+ '[Desktop Entry]\nType=Application\nExec=/usr/bin/transmission %f\n',
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID,
+ 'application/x-bittorrent': DESKTOP_ENTRY_ID,
})
- 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(xdg.defaults.get('application/x-bittorrent')).toBe(
+ 'transmission.desktop'
+ )
expect(store.record.decision).toBe('declined')
expect(store.record.owner).toBe(null)
})
+ it('removes a first integration when none of the defaults had a prior handler', async () => {
+ const dataHome = '/home/u/.local/share'
+ const desktopPath = desktopEntryFilePath(dataHome)
+ const iconPath = iconFilePath(dataHome)
+ const mimeAppsPath = '/home/u/.config/mimeapps.list'
+ const store = createFakeStore({
+ decision: 'accepted',
+ owner: 'self',
+ status: 'healthy',
+ desktopId: DESKTOP_ENTRY_ID,
+ installId: TEST_INSTALL_ID,
+ iconSha256: sha256Hex('PNGDATA'),
+ })
+ const xdg = createFakeXdg({
+ 'x-scheme-handler/motrix': DESKTOP_ENTRY_ID,
+ 'application/x-bittorrent': DESKTOP_ENTRY_ID,
+ 'x-scheme-handler/magnet': DESKTOP_ENTRY_ID,
+ })
+ const fs = createFakeFs(
+ {
+ [desktopPath]: ownedEntry(APPIMAGE),
+ [iconPath]: 'PNGDATA',
+ [mimeAppsPath]: [
+ '[Default Applications]',
+ 'x-scheme-handler/motrix=motrix-appimage.desktop;',
+ 'application/x-bittorrent=motrix-appimage.desktop;',
+ 'x-scheme-handler/magnet=motrix-appimage.desktop;',
+ '',
+ ].join('\n'),
+ },
+ new Set(),
+ (filePath, content) => {
+ if (filePath === mimeAppsPath) {
+ syncFakeDefaultsFromMimeApps(xdg, content)
+ }
+ }
+ )
+
+ const next = await removeSystemIntegration(baseDeps({ store, fs, xdg }))
+
+ expect(next.decision).toBe('declined')
+ expect(fs.files.has(desktopPath)).toBe(false)
+ expect(fs.files.has(iconPath)).toBe(false)
+ expect([...xdg.defaults.values()]).not.toContain(DESKTOP_ENTRY_ID)
+ })
+
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)
@@ -1230,7 +1441,7 @@ describe('removeSystemIntegration', () => {
expect(next.status).toBe('failed')
})
- it('keeps the desktop file when there is no recorded previous handler to restore', async () => {
+ it('keeps the desktop file when no editable file contains the owned default', async () => {
const dataHome = '/home/u/.local/share'
const desktopPath = desktopEntryFilePath(dataHome)
const store = createFakeStore({
diff --git a/src/main/platform/appimage-integration.ts b/src/main/platform/appimage-integration.ts
index 368407da..100aefd9 100644
--- a/src/main/platform/appimage-integration.ts
+++ b/src/main/platform/appimage-integration.ts
@@ -43,6 +43,7 @@ export interface IntegrationRecord {
// The scheme/mime default handlers recorded before we overrode them, so a
// later removal can restore what the user had.
previousSchemeHandler: string | null
+ previousTorrentHandler: 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
@@ -62,6 +63,7 @@ export const DEFAULT_INTEGRATION_RECORD: IntegrationRecord = {
status: null,
nmConsent: 'unset',
previousSchemeHandler: null,
+ previousTorrentHandler: null,
previousMagnetHandler: null,
installId: null,
iconSha256: null,
@@ -91,6 +93,10 @@ const integrationRecordSchema = z
.string()
.nullable()
.catch(DEFAULT_INTEGRATION_RECORD.previousSchemeHandler),
+ previousTorrentHandler: z
+ .string()
+ .nullable()
+ .catch(DEFAULT_INTEGRATION_RECORD.previousTorrentHandler),
previousMagnetHandler: z
.string()
.nullable()
@@ -163,6 +169,7 @@ export function isSafeInstallId(id: string | null): id is string {
}
const SCHEME_MIME = 'x-scheme-handler/motrix'
+const TORRENT_MIME = 'application/x-bittorrent'
const MAGNET_MIME = 'x-scheme-handler/magnet'
const MIME_TYPES =
'application/x-bittorrent;x-scheme-handler/magnet;x-scheme-handler/motrix;'
@@ -176,6 +183,15 @@ export function resolveXdgDataHome(
return path.join(homedir, '.local', 'share')
}
+export function resolveXdgConfigHome(
+ env: NodeJS.ProcessEnv,
+ homedir: string
+): string {
+ const configured = env.XDG_CONFIG_HOME
+ if (configured && path.isAbsolute(configured)) return configured
+ return path.join(homedir, '.config')
+}
+
export function applicationsDir(dataHome: string): string {
return path.join(dataHome, 'applications')
}
@@ -529,6 +545,114 @@ async function setDefaultAndVerify(
return current === targetId
}
+export interface MimeAppsEditResult {
+ content: string
+ changed: boolean
+}
+
+// Remove only one desktop id from one MIME key in [Default Applications].
+// Other groups, comments, keys, and fallback handlers are preserved byte-for-
+// byte except for the matching value line. This is the missing inverse of
+// `xdg-mime default`, which intentionally has no `unset` verb.
+export function removeDesktopIdFromMimeApps(
+ content: string,
+ mime: string,
+ desktopId: string
+): MimeAppsEditResult {
+ const newline = content.includes('\r\n') ? '\r\n' : '\n'
+ const hadTrailingNewline = content.endsWith('\n')
+ const lines = content.split(/\r?\n/)
+ if (hadTrailingNewline) lines.pop()
+
+ let inDefaults = false
+ let changed = false
+ const next: string[] = []
+ for (const rawLine of lines) {
+ const line = rawLine.trim()
+ if (line.startsWith('[') && line.endsWith(']')) {
+ inDefaults = line === '[Default Applications]'
+ next.push(rawLine)
+ continue
+ }
+ if (!inDefaults || line === '' || line.startsWith('#')) {
+ next.push(rawLine)
+ continue
+ }
+
+ const eq = rawLine.indexOf('=')
+ if (eq < 0 || rawLine.slice(0, eq).trim() !== mime) {
+ next.push(rawLine)
+ continue
+ }
+ const handlers = rawLine
+ .slice(eq + 1)
+ .split(';')
+ .map((value) => value.trim())
+ .filter(Boolean)
+ const remaining = handlers.filter((value) => value !== desktopId)
+ if (remaining.length === handlers.length) {
+ next.push(rawLine)
+ continue
+ }
+
+ changed = true
+ if (remaining.length > 0) {
+ next.push(`${rawLine.slice(0, eq + 1)}${remaining.join(';')};`)
+ }
+ }
+
+ return {
+ content: `${next.join(newline)}${hadTrailingNewline ? newline : ''}`,
+ changed,
+ }
+}
+
+function userMimeAppsPaths(deps: AppImageIntegrationDeps): string[] {
+ const configHome = resolveXdgConfigHome(deps.env, deps.homedir)
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ const desktopNames = (deps.env.XDG_CURRENT_DESKTOP ?? '')
+ .split(':')
+ .map((value) => value.trim().toLowerCase())
+ .filter((value) => /^[a-z0-9_-]+$/.test(value))
+ return [
+ ...desktopNames.map((name) =>
+ path.join(configHome, `${name}-mimeapps.list`)
+ ),
+ path.join(configHome, 'mimeapps.list'),
+ ...desktopNames.map((name) =>
+ path.join(applicationsDir(dataHome), `${name}-mimeapps.list`)
+ ),
+ path.join(applicationsDir(dataHome), 'mimeapps.list'),
+ ].filter((value, index, all) => all.indexOf(value) === index)
+}
+
+async function clearOwnedDefaultAndVerify(
+ deps: AppImageIntegrationDeps,
+ mime: string
+): Promise<boolean> {
+ for (const filePath of userMimeAppsPaths(deps)) {
+ let content: string
+ try {
+ content = await deps.fs.readText(filePath)
+ } catch (err) {
+ if (isEnoent(err)) continue
+ deps.log.warn({ err, filePath, mime }, 'cannot read user mimeapps file')
+ return false
+ }
+ const edit = removeDesktopIdFromMimeApps(content, mime, DESKTOP_ENTRY_ID)
+ if (!edit.changed) continue
+ try {
+ await deps.fs.writeText(filePath, edit.content)
+ } catch (err) {
+ deps.log.warn({ err, filePath, mime }, 'cannot update user mimeapps file')
+ return false
+ }
+ }
+
+ const current = await queryDefaultHandlerResult(deps, mime)
+ return current.ok && current.id !== DESKTOP_ENTRY_ID
+}
+
async function updateDesktopDatabase(
deps: AppImageIntegrationDeps,
dataHome: string
@@ -585,7 +709,13 @@ function desktopSearchDirs(env: NodeJS.ProcessEnv, dataHome: string): string[] {
for (const base of dataDirs) {
if (path.isAbsolute(base)) dirs.push(path.join(base, 'applications'))
}
- return dirs
+ dirs.push(
+ path.join(dataHome, 'flatpak', 'exports', 'share', 'applications'),
+ '/var/lib/flatpak/exports/share/applications',
+ '/var/lib/snapd/desktop/applications',
+ '/app/share/applications'
+ )
+ return dirs.filter((value, index, all) => all.indexOf(value) === index)
}
function isEnoent(err: unknown): boolean {
@@ -662,14 +792,15 @@ async function installSelfIntegration(
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.
+ // All 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([
+ const [schemeCap, torrentCap, magnetCap] = await Promise.all([
capturePrevious(SCHEME_MIME, record.previousSchemeHandler),
+ capturePrevious(TORRENT_MIME, record.previousTorrentHandler),
capturePrevious(MAGNET_MIME, record.previousMagnetHandler),
])
- if (!schemeCap.ok || !magnetCap.ok) {
+ if (!schemeCap.ok || !torrentCap.ok || !magnetCap.ok) {
deps.log.warn(
{},
'cannot query current default handlers; aborting to avoid losing them'
@@ -683,6 +814,7 @@ async function installSelfIntegration(
}
}
const previousSchemeHandler = schemeCap.value
+ const previousTorrentHandler = torrentCap.value
const previousMagnetHandler = magnetCap.value
const base: IntegrationRecord = {
@@ -692,6 +824,7 @@ async function installSelfIntegration(
desktopId: DESKTOP_ENTRY_ID,
installId,
previousSchemeHandler,
+ previousTorrentHandler,
previousMagnetHandler,
}
@@ -704,6 +837,7 @@ async function installSelfIntegration(
if (
record.installId !== installId ||
record.previousSchemeHandler !== previousSchemeHandler ||
+ record.previousTorrentHandler !== previousTorrentHandler ||
record.previousMagnetHandler !== previousMagnetHandler
) {
await deps.store.save(failed)
@@ -788,17 +922,25 @@ async function installSelfIntegration(
SCHEME_MIME,
DESKTOP_ENTRY_ID
)
+ const torrentOk = await setDefaultAndVerify(
+ deps,
+ TORRENT_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)
+ } else {
+ magnetOk = await restoreDefault(deps, MAGNET_MIME, previousMagnetHandler)
}
- const status: IntegrationStatus = schemeOk && magnetOk ? 'healthy' : 'failed'
+ const status: IntegrationStatus =
+ schemeOk && torrentOk && magnetOk ? 'healthy' : 'failed'
if (status === 'failed') {
deps.log.warn(
- { schemeOk, magnetOk },
+ { schemeOk, torrentOk, magnetOk },
'appimage default handler verification failed'
)
}
@@ -809,14 +951,14 @@ async function installSelfIntegration(
// 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.
+// user was actually using, not a stale one). A failed mutation marks the
+// integration failed so settings never claim a preference was applied.
async function reconcileMagnetDefault(
deps: AppImageIntegrationDeps,
record: IntegrationRecord
): Promise<IntegrationRecord> {
const q = await queryDefaultHandlerResult(deps, MAGNET_MIME)
- if (!q.ok) return record
+ if (!q.ok) return { ...record, status: 'failed' }
if (deps.getMagnetEnabled()) {
if (q.id === DESKTOP_ENTRY_ID) return record
// About to overwrite whatever is currently the magnet handler — capture it
@@ -833,11 +975,20 @@ async function reconcileMagnetDefault(
await deps.store.save(next)
}
}
- await setDefaultAndVerify(deps, MAGNET_MIME, DESKTOP_ENTRY_ID)
- return next
+ const applied = await setDefaultAndVerify(
+ deps,
+ MAGNET_MIME,
+ DESKTOP_ENTRY_ID
+ )
+ return applied ? next : { ...next, status: 'failed' }
}
if (q.id === DESKTOP_ENTRY_ID) {
- await restoreDefault(deps, MAGNET_MIME, record.previousMagnetHandler)
+ const restored = await restoreDefault(
+ deps,
+ MAGNET_MIME,
+ record.previousMagnetHandler
+ )
+ if (!restored) return { ...record, status: 'failed' }
}
return record
}
@@ -898,6 +1049,62 @@ async function selfHeal(
return next
}
+// Read-only status validation for the settings query. Persisted `healthy` is
+// only trusted while the owned entry/icon still match and all required
+// defaults reflect the current preference. A previous failed transaction is
+// never silently upgraded here; retry remains an explicit enable/startup step.
+export async function inspectSystemIntegration(
+ deps: AppImageIntegrationDeps
+): Promise<IntegrationRecord> {
+ const record = await deps.store.load()
+ if (
+ record.decision !== 'accepted' ||
+ record.owner !== 'self' ||
+ record.status !== 'healthy'
+ ) {
+ return record
+ }
+
+ const dataHome = resolveXdgDataHome(deps.env, deps.homedir)
+ let desktopOk = false
+ let iconOk = false
+ try {
+ const content = await deps.fs.readText(desktopEntryFilePath(dataHome))
+ desktopOk =
+ classifyDesktopFile(content, deps.appImagePath, record.installId) === 'ok'
+ } catch {
+ desktopOk = false
+ }
+ if (record.iconSha256) {
+ try {
+ iconOk =
+ sha256Hex(await deps.fs.readBytes(iconFilePath(dataHome))) ===
+ record.iconSha256
+ } catch {
+ iconOk = false
+ }
+ }
+
+ const [scheme, torrent, magnet] = await Promise.all([
+ queryDefaultHandlerResult(deps, SCHEME_MIME),
+ queryDefaultHandlerResult(deps, TORRENT_MIME),
+ queryDefaultHandlerResult(deps, MAGNET_MIME),
+ ])
+ const defaultsOk =
+ scheme.ok &&
+ scheme.id === DESKTOP_ENTRY_ID &&
+ torrent.ok &&
+ torrent.id === DESKTOP_ENTRY_ID &&
+ magnet.ok &&
+ (deps.getMagnetEnabled()
+ ? magnet.id === DESKTOP_ENTRY_ID
+ : magnet.id !== DESKTOP_ENTRY_ID)
+
+ return desktopOk && iconOk && defaultsOk
+ ? record
+ : { ...record, status: 'failed' }
+}
+
// 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
@@ -928,17 +1135,22 @@ export async function removeSystemIntegration(
SCHEME_MIME,
record.previousSchemeHandler
)
+ const torrentRestored = await restoreDefault(
+ deps,
+ TORRENT_MIME,
+ record.previousTorrentHandler
+ )
const magnetRestored = await restoreDefault(
deps,
MAGNET_MIME,
record.previousMagnetHandler
)
- if (!schemeRestored || !magnetRestored) {
+ if (!schemeRestored || !torrentRestored || !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 },
+ { schemeRestored, torrentRestored, magnetRestored },
'aborting appimage removal: could not restore mime defaults'
)
const stuck: IntegrationRecord = { ...record, status: 'failed' }
@@ -980,8 +1192,8 @@ export async function removeSystemIntegration(
// 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).
+// still ours but we cannot safely reclaim it (the owned mimeapps entry could
+// not be cleared, the previous id is unsafe, or set/verify failed).
async function restoreDefault(
deps: AppImageIntegrationDeps,
mime: string,
@@ -994,12 +1206,7 @@ async function restoreDefault(
// 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 (!previous) return clearOwnedDefaultAndVerify(deps, mime)
if (!isSafeDesktopId(previous)) {
deps.log.warn({ mime, previous }, 'recorded previous handler is unsafe')
return false
diff --git a/src/main/platform/linux-default-apps.test.ts b/src/main/platform/linux-default-apps.test.ts
new file mode 100644
index 00000000..642c83e2
--- /dev/null
+++ b/src/main/platform/linux-default-apps.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('electron', () => ({
+ app: { isPackaged: false, getPath: () => '/home/u' },
+}))
+
+import {
+ detectLinuxPackageKind,
+ getLinuxDefaultAssociations,
+ setLinuxDefaultTorrentHandler,
+} from './linux-default-apps'
+
+const NATIVE_ENTRY =
+ '[Desktop Entry]\nType=Application\nExec=/opt/Motrix/motrix %U\n'
+const PACKAGE_ENTRY =
+ '[Desktop Entry]\nType=Application\nExec=/app/bin/motrix %U\n'
+
+describe('Linux default app integration', () => {
+ it.each([
+ [{ APPIMAGE: '/apps/Motrix.AppImage' }, true, 'appimage'],
+ [{ FLATPAK_ID: 'app.motrix.native' }, true, 'flatpak'],
+ [{ SNAP: '/snap/motrix/current' }, true, 'snap'],
+ [{}, true, 'native'],
+ [{}, false, 'unknown'],
+ ] as const)('detects package kind', (env, packaged, expected) => {
+ expect(detectLinuxPackageKind(env, packaged)).toBe(expected)
+ })
+
+ it('reports unsupported outside packaged Linux', async () => {
+ await expect(
+ getLinuxDefaultAssociations({ platform: 'darwin', packaged: true })
+ ).resolves.toMatchObject({ supported: false, packageKind: null })
+ await expect(
+ getLinuxDefaultAssociations({ platform: 'linux', packaged: false })
+ ).resolves.toMatchObject({ supported: false, packageKind: null })
+ })
+
+ it('reports native defaults against an installed desktop id', async () => {
+ const queryDefault = vi.fn(async (mime: string) => ({
+ ok: true,
+ id:
+ mime === 'application/x-bittorrent'
+ ? 'motrix.desktop'
+ : 'org.qbittorrent.qBittorrent.desktop',
+ }))
+
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: {},
+ home: '/home/u',
+ currentExecutable: '/opt/Motrix/motrix',
+ readDesktopFile: vi.fn(async (filePath) =>
+ filePath.endsWith('/motrix.desktop') ? NATIVE_ENTRY : null
+ ),
+ queryDefault,
+ })
+ ).resolves.toEqual({
+ supported: true,
+ packageKind: 'native',
+ registered: true,
+ canSetTorrentDefault: true,
+ torrent: true,
+ magnet: false,
+ })
+ })
+
+ it('recognizes AppImage and Flatpak desktop ids', async () => {
+ const readDesktopFile = vi.fn(async () => PACKAGE_ENTRY)
+ const queryDefault = vi.fn(async () => ({
+ ok: true,
+ id: 'motrix-appimage.desktop',
+ }))
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: { APPIMAGE: '/apps/Motrix.AppImage' },
+ home: '/home/u',
+ readDesktopFile,
+ queryDefault,
+ })
+ ).resolves.toMatchObject({
+ packageKind: 'appimage',
+ registered: true,
+ canSetTorrentDefault: false,
+ torrent: true,
+ magnet: true,
+ })
+
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: { FLATPAK_ID: 'app.motrix.native' },
+ home: '/home/u',
+ readDesktopFile,
+ queryDefault: vi.fn(async () => ({
+ ok: true,
+ id: 'app.motrix.native.desktop',
+ })),
+ })
+ ).resolves.toMatchObject({
+ packageKind: 'flatpak',
+ registered: true,
+ canSetTorrentDefault: false,
+ torrent: true,
+ })
+ })
+
+ it('maps a confined Snap desktop source to its host-exported id', async () => {
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: {
+ SNAP: '/snap/motrix/current',
+ SNAP_INSTANCE_NAME: 'motrix',
+ },
+ home: '/home/u',
+ readDesktopFile: vi.fn(async (filePath) =>
+ filePath.endsWith('/meta/gui/motrix.desktop') ? PACKAGE_ENTRY : null
+ ),
+ queryDefault: vi.fn(async () => ({
+ ok: true,
+ id: 'motrix_motrix.desktop',
+ })),
+ })
+ ).resolves.toMatchObject({
+ packageKind: 'snap',
+ registered: true,
+ torrent: true,
+ magnet: true,
+ })
+ })
+
+ it('distinguishes an unreadable default from not being default', async () => {
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: {},
+ home: '/home/u',
+ currentExecutable: '/opt/Motrix/motrix',
+ readDesktopFile: vi.fn(async (filePath) =>
+ filePath.endsWith('/motrix.desktop') ? NATIVE_ENTRY : null
+ ),
+ queryDefault: vi.fn(async () => ({ ok: false, id: null })),
+ })
+ ).resolves.toMatchObject({ torrent: null, magnet: null })
+ })
+
+ it('sets and verifies the native torrent default', async () => {
+ let torrentDefault = 'other.desktop'
+ const deps = {
+ platform: 'linux' as const,
+ packaged: true,
+ env: {},
+ home: '/home/u',
+ currentExecutable: '/opt/Motrix/motrix',
+ readDesktopFile: vi.fn(async (filePath: string) =>
+ filePath.endsWith('/motrix.desktop') ? NATIVE_ENTRY : null
+ ),
+ queryDefault: vi.fn(async (mime: string) => ({
+ ok: true,
+ id:
+ mime === 'application/x-bittorrent'
+ ? torrentDefault
+ : 'other.desktop',
+ })),
+ setDefault: vi.fn(async (desktopId: string) => {
+ torrentDefault = desktopId
+ return true
+ }),
+ }
+
+ await expect(setLinuxDefaultTorrentHandler(deps)).resolves.toMatchObject({
+ torrent: true,
+ })
+ expect(deps.setDefault).toHaveBeenCalledWith(
+ 'motrix.desktop',
+ 'application/x-bittorrent'
+ )
+ })
+
+ it('does not bypass AppImage or sandbox package ownership', async () => {
+ await expect(
+ setLinuxDefaultTorrentHandler({
+ platform: 'linux',
+ packaged: true,
+ env: { APPIMAGE: '/apps/Motrix.AppImage' },
+ home: '/home/u',
+ readDesktopFile: vi.fn(async () => PACKAGE_ENTRY),
+ queryDefault: vi.fn(async () => ({ ok: true, id: null })),
+ })
+ ).rejects.toThrow('does not support direct default selection')
+ })
+
+ it('rejects a stale user desktop entry that shadows the native package', async () => {
+ const readDesktopFile = vi.fn(async (filePath: string) => {
+ if (filePath === '/home/u/.local/share/applications/motrix.desktop') {
+ return '[Desktop Entry]\nType=Application\nExec=/old/Motrix.AppImage %U\n'
+ }
+ if (filePath === '/usr/share/applications/motrix.desktop') {
+ return NATIVE_ENTRY
+ }
+ return null
+ })
+
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: {},
+ home: '/home/u',
+ currentExecutable: '/opt/Motrix/motrix',
+ readDesktopFile,
+ queryDefault: vi.fn(async () => ({
+ ok: true,
+ id: 'motrix.desktop',
+ })),
+ })
+ ).resolves.toMatchObject({
+ registered: false,
+ canSetTorrentDefault: false,
+ torrent: false,
+ magnet: false,
+ })
+ expect(readDesktopFile).not.toHaveBeenCalledWith(
+ '/usr/share/applications/motrix.desktop'
+ )
+ })
+
+ it('does not attribute a concurrent native Motrix default to Snap', async () => {
+ await expect(
+ getLinuxDefaultAssociations({
+ platform: 'linux',
+ packaged: true,
+ env: {
+ SNAP: '/snap/motrix/current',
+ SNAP_INSTANCE_NAME: 'motrix',
+ },
+ home: '/home/u',
+ readDesktopFile: vi.fn(async (filePath) =>
+ filePath.endsWith('/meta/gui/motrix.desktop') ? PACKAGE_ENTRY : null
+ ),
+ queryDefault: vi.fn(async () => ({
+ ok: true,
+ id: 'motrix.desktop',
+ })),
+ })
+ ).resolves.toMatchObject({
+ packageKind: 'snap',
+ registered: true,
+ torrent: false,
+ magnet: false,
+ })
+ })
+})
diff --git a/src/main/platform/linux-default-apps.ts b/src/main/platform/linux-default-apps.ts
new file mode 100644
index 00000000..30092d20
--- /dev/null
+++ b/src/main/platform/linux-default-apps.ts
@@ -0,0 +1,294 @@
+import { execFile } from 'node:child_process'
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import type {
+ LinuxDefaultAssociations,
+ LinuxPackageKind,
+} from '@shared/types/linux-default-apps'
+import { app } from 'electron'
+import {
+ isUsableHandlerEntry,
+ parseDesktopEntry,
+ parseExecValue,
+} from './appimage-integration'
+
+const execFileAsync = promisify(execFile)
+
+const TORRENT_MIME = 'application/x-bittorrent'
+const MAGNET_MIME = 'x-scheme-handler/magnet'
+const COMMAND_TIMEOUT_MS = 5_000
+const NATIVE_DESKTOP_IDS = ['motrix.desktop', 'motrix-turbo.desktop'] as const
+
+interface LinuxDefaultAppsDeps {
+ platform?: NodeJS.Platform
+ packaged?: boolean
+ env?: NodeJS.ProcessEnv
+ home?: string
+ currentExecutable?: string
+ readDesktopFile?: (filePath: string) => Promise<string | null>
+ queryDefault?: (mime: string) => Promise<{ ok: boolean; id: string | null }>
+ setDefault?: (desktopId: string, mime: string) => Promise<boolean>
+}
+
+function safeDesktopId(value: string | undefined): string | null {
+ if (!value || path.basename(value) !== value) return null
+ if (!/^[A-Za-z0-9._-]+\.desktop$/.test(value) || value.startsWith('-')) {
+ return null
+ }
+ return value
+}
+
+export function detectLinuxPackageKind(
+ env: NodeJS.ProcessEnv,
+ packaged: boolean
+): LinuxPackageKind {
+ if (!packaged) return 'unknown'
+ if (env.APPIMAGE) return 'appimage'
+ if (env.FLATPAK_ID) return 'flatpak'
+ if (env.SNAP || env.SNAP_NAME || env.SNAP_INSTANCE_NAME) return 'snap'
+ return 'native'
+}
+
+function desktopCandidates(
+ packageKind: LinuxPackageKind,
+ env: NodeJS.ProcessEnv
+): string[] {
+ if (packageKind === 'appimage') return ['motrix-appimage.desktop']
+ if (packageKind === 'flatpak') {
+ const id = safeDesktopId(
+ env.FLATPAK_ID ? `${env.FLATPAK_ID}.desktop` : undefined
+ )
+ return id ? [id] : []
+ }
+ if (packageKind === 'snap') {
+ const instance = env.SNAP_INSTANCE_NAME ?? env.SNAP_NAME ?? 'motrix'
+ return [
+ `${instance}_motrix.desktop`,
+ `${instance}_motrix-turbo.desktop`,
+ ].flatMap((id) => {
+ const safe = safeDesktopId(id)
+ return safe ? [safe] : []
+ })
+ }
+ if (packageKind === 'native') return [...NATIVE_DESKTOP_IDS]
+ return []
+}
+
+function applicationDirs(env: NodeJS.ProcessEnv, home: string): string[] {
+ const dataHome =
+ env.XDG_DATA_HOME && path.isAbsolute(env.XDG_DATA_HOME)
+ ? env.XDG_DATA_HOME
+ : path.join(home, '.local', 'share')
+ const dataDirs = (env.XDG_DATA_DIRS ?? '/usr/local/share:/usr/share')
+ .split(':')
+ .filter((dir) => path.isAbsolute(dir))
+
+ return [
+ path.join(dataHome, 'applications'),
+ ...dataDirs.map((dir) => path.join(dir, 'applications')),
+ path.join(home, '.local/share/flatpak/exports/share/applications'),
+ '/var/lib/flatpak/exports/share/applications',
+ '/var/lib/snapd/desktop/applications',
+ '/app/share/applications',
+ ...(env.SNAP && path.isAbsolute(env.SNAP)
+ ? [path.join(env.SNAP, 'meta', 'gui')]
+ : []),
+ ]
+}
+
+async function defaultReadDesktopFile(
+ filePath: string
+): Promise<string | null> {
+ try {
+ return await readFile(filePath, 'utf8')
+ } catch {
+ return null
+ }
+}
+
+function desktopEntryTargetsCurrentExecutable(
+ content: string,
+ currentExecutable: string
+): boolean {
+ const entry = parseDesktopEntry(content)
+ if (!isUsableHandlerEntry(entry)) return false
+ const program = parseExecValue(entry.get('Exec') ?? '')[0]
+ if (!program) return false
+ if (path.isAbsolute(program)) {
+ return path.normalize(program) === path.normalize(currentExecutable)
+ }
+ return !program.includes('/') && program === path.basename(currentExecutable)
+}
+
+async function defaultQueryDefault(
+ mime: string
+): Promise<{ ok: boolean; id: string | null }> {
+ try {
+ const { stdout } = await execFileAsync(
+ 'xdg-mime',
+ ['query', 'default', mime],
+ { timeout: COMMAND_TIMEOUT_MS }
+ )
+ const id = stdout.toString().trim()
+ return { ok: true, id: id || null }
+ } catch {
+ return { ok: false, id: null }
+ }
+}
+
+async function defaultSetDefault(
+ desktopId: string,
+ mime: string
+): Promise<boolean> {
+ try {
+ await execFileAsync('xdg-mime', ['default', desktopId, mime], {
+ timeout: COMMAND_TIMEOUT_MS,
+ })
+ return (await defaultQueryDefault(mime)).id === desktopId
+ } catch {
+ return false
+ }
+}
+
+async function resolveInstalledDesktopIds(
+ packageKind: LinuxPackageKind,
+ env: NodeJS.ProcessEnv,
+ home: string,
+ currentExecutable: string,
+ readDesktopFile: (filePath: string) => Promise<string | null>
+): Promise<string[]> {
+ const candidates = desktopCandidates(packageKind, env)
+ const dirs = applicationDirs(env, home)
+ const installed: string[] = []
+ for (const id of candidates) {
+ for (const dir of dirs) {
+ const content = await readDesktopFile(path.join(dir, id))
+ if (content === null) continue
+ const valid =
+ packageKind === 'native'
+ ? desktopEntryTargetsCurrentExecutable(content, currentExecutable)
+ : isUsableHandlerEntry(parseDesktopEntry(content))
+ if (valid) installed.push(id)
+ // Desktop IDs obey XDG directory precedence. A stale/foreign user entry
+ // shadows a system entry with the same id, so never continue past the
+ // first existing file merely because its Exec failed validation.
+ break
+ }
+ }
+
+ // A confined Snap can see its unprefixed source entry but not the host
+ // export. Map each source basename to only its instance-prefixed export id;
+ // native deb/rpm ids must never be attributed to the Snap.
+ if (packageKind === 'snap' && env.SNAP && path.isAbsolute(env.SNAP)) {
+ const sourceToExport = new Map([
+ ['motrix.desktop', candidates[0]],
+ ['motrix-turbo.desktop', candidates[1]],
+ ])
+ for (const [sourceId, exportId] of sourceToExport) {
+ if (!exportId || installed.includes(exportId)) continue
+ const content = await readDesktopFile(
+ path.join(env.SNAP, 'meta', 'gui', sourceId)
+ )
+ if (
+ content !== null &&
+ isUsableHandlerEntry(parseDesktopEntry(content))
+ ) {
+ installed.push(exportId)
+ }
+ }
+ }
+ return installed
+}
+
+function unsupported(): LinuxDefaultAssociations {
+ return {
+ supported: false,
+ packageKind: null,
+ registered: false,
+ canSetTorrentDefault: false,
+ torrent: null,
+ magnet: null,
+ }
+}
+
+export async function getLinuxDefaultAssociations(
+ deps: LinuxDefaultAppsDeps = {}
+): Promise<LinuxDefaultAssociations> {
+ if ((deps.platform ?? process.platform) !== 'linux') return unsupported()
+
+ const packaged = deps.packaged ?? app.isPackaged
+ const env = deps.env ?? process.env
+ const packageKind = detectLinuxPackageKind(env, packaged)
+ if (packageKind === 'unknown') return unsupported()
+
+ const home = deps.home ?? app.getPath('home')
+ const currentExecutable = deps.currentExecutable ?? app.getPath('exe')
+ const desktopIds = await resolveInstalledDesktopIds(
+ packageKind,
+ env,
+ home,
+ currentExecutable,
+ deps.readDesktopFile ?? defaultReadDesktopFile
+ )
+ if (desktopIds.length === 0) {
+ return {
+ supported: true,
+ packageKind,
+ registered: false,
+ canSetTorrentDefault: false,
+ torrent: false,
+ magnet: false,
+ }
+ }
+
+ const queryDefault = deps.queryDefault ?? defaultQueryDefault
+ const [torrent, magnet] = await Promise.all([
+ queryDefault(TORRENT_MIME),
+ queryDefault(MAGNET_MIME),
+ ])
+
+ return {
+ supported: true,
+ packageKind,
+ registered: true,
+ canSetTorrentDefault: packageKind === 'native',
+ torrent: torrent.ok
+ ? torrent.id !== null && desktopIds.includes(torrent.id)
+ : null,
+ magnet: magnet.ok
+ ? magnet.id !== null && desktopIds.includes(magnet.id)
+ : null,
+ }
+}
+
+export async function setLinuxDefaultTorrentHandler(
+ deps: LinuxDefaultAppsDeps = {}
+): Promise<LinuxDefaultAssociations> {
+ const status = await getLinuxDefaultAssociations(deps)
+ if (
+ !status.supported ||
+ status.packageKind !== 'native' ||
+ !status.registered
+ ) {
+ throw new Error('Linux package does not support direct default selection')
+ }
+
+ const env = deps.env ?? process.env
+ const home = deps.home ?? app.getPath('home')
+ const currentExecutable = deps.currentExecutable ?? app.getPath('exe')
+ const [desktopId] = await resolveInstalledDesktopIds(
+ status.packageKind,
+ env,
+ home,
+ currentExecutable,
+ deps.readDesktopFile ?? defaultReadDesktopFile
+ )
+ if (!desktopId) throw new Error('Motrix desktop entry not found')
+
+ const setDefault = deps.setDefault ?? defaultSetDefault
+ if (!(await setDefault(desktopId, TORRENT_MIME))) {
+ throw new Error('Desktop environment rejected the default handler')
+ }
+ return getLinuxDefaultAssociations(deps)
+}
diff --git a/src/main/platform/protocol-manager.test.ts b/src/main/platform/protocol-manager.test.ts
index 8561fd40..6e892a68 100644
--- a/src/main/platform/protocol-manager.test.ts
+++ b/src/main/platform/protocol-manager.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockSetAsDefault,
mockRemoveDefault,
+ mockIsDefault,
mockIsPackaged,
mockSend,
mockReadFile,
@@ -10,6 +11,7 @@ const {
} = vi.hoisted(() => ({
mockSetAsDefault: vi.fn(),
mockRemoveDefault: vi.fn(),
+ mockIsDefault: vi.fn(),
mockIsPackaged: { value: true },
mockSend: vi.fn(),
mockReadFile: vi.fn(),
@@ -20,6 +22,7 @@ vi.mock('electron', () => ({
app: {
setAsDefaultProtocolClient: mockSetAsDefault,
removeAsDefaultProtocolClient: mockRemoveDefault,
+ isDefaultProtocolClient: mockIsDefault,
get isPackaged() {
return mockIsPackaged.value
},
@@ -81,6 +84,12 @@ describe('createProtocolManager', () => {
beforeEach(() => {
vi.clearAllMocks()
mockIsPackaged.value = true
+ mockSetAsDefault.mockReturnValue(true)
+ mockRemoveDefault.mockReturnValue(true)
+ mockIsDefault.mockImplementation((protocol: string) => {
+ if (protocol !== 'magnet') return false
+ return mockSetAsDefault.mock.calls.some(([value]) => value === 'magnet')
+ })
})
describe('register', () => {
@@ -101,7 +110,7 @@ describe('createProtocolManager', () => {
deliverToAddTask,
onOpenPluginDetail,
})
- pm.register()
+ expect(pm.register()).toEqual({ magnetMatchesSetting: true })
expect(mockSetAsDefault).toHaveBeenCalledWith('motrix')
expect(mockSetAsDefault).toHaveBeenCalledWith('magnet')
@@ -124,7 +133,7 @@ describe('createProtocolManager', () => {
deliverToAddTask,
onOpenPluginDetail,
})
- pm.register()
+ expect(pm.register()).toEqual({ magnetMatchesSetting: true })
expect(mockSetAsDefault).toHaveBeenCalledWith('motrix')
expect(mockRemoveDefault).toHaveBeenCalledWith('magnet')
@@ -148,11 +157,35 @@ describe('createProtocolManager', () => {
deliverToAddTask,
onOpenPluginDetail,
})
- pm.register()
+ expect(pm.register()).toEqual({ magnetMatchesSetting: null })
expect(mockSetAsDefault).not.toHaveBeenCalled()
})
+ it('leaves Windows scheme registration to the installer', () => {
+ const {
+ getWindow,
+ settingsManager,
+ torrentParser,
+ onOpenAddTask,
+ deliverToAddTask,
+ onOpenPluginDetail,
+ } = makeDeps(true)
+ const pm = createProtocolManager({
+ getWindow,
+ settingsManager,
+ torrentParser,
+ onOpenAddTask,
+ deliverToAddTask,
+ onOpenPluginDetail,
+ platform: 'win32',
+ })
+ expect(pm.register()).toEqual({ magnetMatchesSetting: null })
+
+ expect(mockSetAsDefault).not.toHaveBeenCalled()
+ expect(mockRemoveDefault).not.toHaveBeenCalled()
+ })
+
it('skips Electron scheme registration in an AppImage (integration owns it)', () => {
const {
getWindow,
@@ -171,11 +204,34 @@ describe('createProtocolManager', () => {
onOpenPluginDetail,
isAppImage: true,
})
- pm.register()
+ expect(pm.register()).toEqual({ magnetMatchesSetting: null })
expect(mockSetAsDefault).not.toHaveBeenCalled()
expect(mockRemoveDefault).not.toHaveBeenCalled()
})
+
+ it('reports when the effective magnet default does not match the setting', () => {
+ const {
+ getWindow,
+ settingsManager,
+ torrentParser,
+ onOpenAddTask,
+ deliverToAddTask,
+ onOpenPluginDetail,
+ } = makeDeps(true)
+ mockSetAsDefault.mockReturnValue(false)
+ mockIsDefault.mockReturnValue(false)
+ const pm = createProtocolManager({
+ getWindow,
+ settingsManager,
+ torrentParser,
+ onOpenAddTask,
+ deliverToAddTask,
+ onOpenPluginDetail,
+ })
+
+ expect(pm.register()).toEqual({ magnetMatchesSetting: false })
+ })
})
describe('handle', () => {
diff --git a/src/main/platform/protocol-manager.ts b/src/main/platform/protocol-manager.ts
index f28acd98..33a6bb69 100644
--- a/src/main/platform/protocol-manager.ts
+++ b/src/main/platform/protocol-manager.ts
@@ -21,6 +21,9 @@ export interface ProtocolManagerDeps {
// and mutates the XDG default — that would race the integration's
// external-owner detection and corrupt the recorded prior default handler.
isAppImage?: boolean
+ // Windows associations are installer-owned so they can participate in the
+ // protected Default Apps UI and be removed reliably on uninstall/update.
+ platform?: NodeJS.Platform
// 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.
@@ -35,6 +38,10 @@ export interface ProtocolManagerDeps {
onOpenPluginDetail: (pluginId: string) => void
}
+export interface ProtocolRegistrationResult {
+ magnetMatchesSetting: boolean | null
+}
+
interface TorrentPayload {
name: string
dataBase64: string
@@ -79,25 +86,42 @@ export function createProtocolManager(deps: ProtocolManagerDeps) {
return {
register() {
- if (!app.isPackaged) return
+ if (!app.isPackaged) return { magnetMatchesSetting: null }
+
+ if ((deps.platform ?? process.platform) === 'win32') {
+ log.info('windows: scheme registration owned by installer')
+ return { magnetMatchesSetting: null }
+ }
// 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
+ return { magnetMatchesSetting: null }
}
- app.setAsDefaultProtocolClient('motrix')
-
const magnetEnabled = deps.settingsManager.getApp().protocols.magnet
- if (magnetEnabled) {
- app.setAsDefaultProtocolClient('magnet')
- } else {
- app.removeAsDefaultProtocolClient('magnet')
- }
+ try {
+ app.setAsDefaultProtocolClient('motrix')
+ if (magnetEnabled) {
+ app.setAsDefaultProtocolClient('magnet')
+ } else {
+ app.removeAsDefaultProtocolClient('magnet')
+ }
- log.info({ magnetEnabled }, 'protocols registered')
+ const magnetIsDefault = app.isDefaultProtocolClient('magnet')
+ const magnetMatchesSetting = magnetEnabled
+ ? magnetIsDefault
+ : !magnetIsDefault
+ log.info(
+ { magnetEnabled, magnetMatchesSetting },
+ 'protocols registered'
+ )
+ return { magnetMatchesSetting }
+ } catch (err) {
+ log.warn({ err, magnetEnabled }, 'protocol registration failed')
+ return { magnetMatchesSetting: false }
+ }
},
handle(url: string) {
diff --git a/src/main/platform/windows-default-apps.test.ts b/src/main/platform/windows-default-apps.test.ts
new file mode 100644
index 00000000..634113a4
--- /dev/null
+++ b/src/main/platform/windows-default-apps.test.ts
@@ -0,0 +1,179 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ buildWindowsDefaultAppsSettingsUrl,
+ getWindowsDefaultAssociations,
+ resolveWindowsDefaultAppsSettingsUrl,
+ supportsRegisteredAppDefaultAppsQuery,
+ WINDOWS_DEFAULT_APPS_SETTINGS_URL,
+ WINDOWS_REGISTERED_APP_NAME,
+} from './windows-default-apps'
+
+describe('Windows Default Apps settings', () => {
+ it('builds scope-correct registered-app URLs', () => {
+ expect(WINDOWS_REGISTERED_APP_NAME).toBe('Motrix')
+ expect(buildWindowsDefaultAppsSettingsUrl('user')).toBe(
+ 'ms-settings:defaultapps?registeredAppUser=Motrix'
+ )
+ expect(buildWindowsDefaultAppsSettingsUrl('machine')).toBe(
+ 'ms-settings:defaultapps?registeredAppMachine=Motrix'
+ )
+ expect(buildWindowsDefaultAppsSettingsUrl(null)).toBe(
+ WINDOWS_DEFAULT_APPS_SETTINGS_URL
+ )
+ })
+
+ it.each([
+ ['10.0.19045.5737', false],
+ ['10.0.22000.1816', false],
+ ['10.0.22000.1817', true],
+ ['10.0.22621.1554', false],
+ ['10.0.22621.1555', true],
+ ['10.0.22631.0', true],
+ ['10.0.26100.1', true],
+ ['invalid', false],
+ ])('detects registered-app query support for %s', (version, expected) => {
+ expect(supportsRegisteredAppDefaultAppsQuery(version)).toBe(expected)
+ })
+
+ it('prefers a per-user registration because HKCU shadows HKLM', async () => {
+ const hasRegistration = vi.fn().mockResolvedValue(true)
+
+ await expect(
+ resolveWindowsDefaultAppsSettingsUrl({
+ osRelease: '10.0.22631.0',
+ hasRegistration,
+ })
+ ).resolves.toBe('ms-settings:defaultapps?registeredAppUser=Motrix')
+ expect(hasRegistration).toHaveBeenCalledOnce()
+ expect(hasRegistration).toHaveBeenCalledWith('user')
+ })
+
+ it('uses the machine query for an all-users installation', async () => {
+ const hasRegistration = vi
+ .fn()
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true)
+
+ await expect(
+ resolveWindowsDefaultAppsSettingsUrl({
+ osRelease: '10.0.22631.0',
+ hasRegistration,
+ })
+ ).resolves.toBe('ms-settings:defaultapps?registeredAppMachine=Motrix')
+ expect(hasRegistration.mock.calls).toEqual([['user'], ['machine']])
+ })
+
+ it('uses the generic page on Windows 10 without probing the registry', async () => {
+ const hasRegistration = vi.fn()
+
+ await expect(
+ resolveWindowsDefaultAppsSettingsUrl({
+ osRelease: '10.0.19045.5737',
+ hasRegistration,
+ })
+ ).resolves.toBe(WINDOWS_DEFAULT_APPS_SETTINGS_URL)
+ expect(hasRegistration).not.toHaveBeenCalled()
+ })
+
+ it('uses the generic page when the portable ZIP has no registration', async () => {
+ const hasRegistration = vi.fn().mockResolvedValue(false)
+
+ await expect(
+ resolveWindowsDefaultAppsSettingsUrl({
+ osRelease: '10.0.26100.1',
+ hasRegistration,
+ })
+ ).resolves.toBe(WINDOWS_DEFAULT_APPS_SETTINGS_URL)
+ expect(hasRegistration).toHaveBeenCalledTimes(2)
+ })
+
+ it('reports unsupported association status outside Windows', async () => {
+ const hasRegistration = vi.fn()
+ const readUserChoice = vi.fn()
+
+ await expect(
+ getWindowsDefaultAssociations({
+ platform: 'linux',
+ hasRegistration,
+ readUserChoice,
+ })
+ ).resolves.toEqual({
+ supported: false,
+ registered: false,
+ scope: null,
+ torrent: false,
+ magnet: false,
+ })
+ expect(hasRegistration).not.toHaveBeenCalled()
+ expect(readUserChoice).not.toHaveBeenCalled()
+ })
+
+ it('reports current defaults for an all-users installation', async () => {
+ const hasRegistration = vi
+ .fn()
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true)
+ const readUserChoice = vi.fn(async (association: string) => ({
+ ok: true,
+ progId:
+ association === 'torrent' ? 'motrix.file.torrent' : 'Other.Url.Handler',
+ }))
+
+ await expect(
+ getWindowsDefaultAssociations({
+ platform: 'win32',
+ hasRegistration,
+ readUserChoice,
+ })
+ ).resolves.toEqual({
+ supported: true,
+ registered: true,
+ scope: 'machine',
+ torrent: true,
+ magnet: false,
+ })
+ expect(hasRegistration.mock.calls).toEqual([['user'], ['machine']])
+ expect(readUserChoice.mock.calls).toEqual([['torrent'], ['magnet']])
+ })
+
+ it('does not probe the machine scope when HKCU owns registration', async () => {
+ const hasRegistration = vi.fn().mockResolvedValue(true)
+ const readUserChoice = vi.fn().mockResolvedValue({
+ ok: true,
+ progId: 'Motrix.Url.Magnet',
+ })
+
+ await expect(
+ getWindowsDefaultAssociations({
+ platform: 'win32',
+ hasRegistration,
+ readUserChoice,
+ })
+ ).resolves.toMatchObject({
+ registered: true,
+ scope: 'user',
+ torrent: false,
+ magnet: true,
+ })
+ expect(hasRegistration).toHaveBeenCalledOnce()
+ })
+
+ it('reports registry query failures as unverifiable', async () => {
+ await expect(
+ getWindowsDefaultAssociations({
+ platform: 'win32',
+ hasRegistration: vi.fn().mockResolvedValue(null),
+ readUserChoice: vi.fn().mockResolvedValue({
+ ok: false,
+ progId: null,
+ }),
+ })
+ ).resolves.toEqual({
+ supported: true,
+ registered: null,
+ scope: null,
+ torrent: null,
+ magnet: null,
+ })
+ })
+})
diff --git a/src/main/platform/windows-default-apps.ts b/src/main/platform/windows-default-apps.ts
new file mode 100644
index 00000000..6d843254
--- /dev/null
+++ b/src/main/platform/windows-default-apps.ts
@@ -0,0 +1,185 @@
+import { execFile } from 'node:child_process'
+import { release } from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import type { WindowsDefaultAssociations } from '@shared/types/windows-default-apps'
+
+const execFileAsync = promisify(execFile)
+
+export const WINDOWS_REGISTERED_APP_NAME = 'Motrix'
+export const WINDOWS_DEFAULT_APPS_SETTINGS_URL = 'ms-settings:defaultapps'
+const WINDOWS_CAPABILITIES_REGISTRY_PATH = 'Software\\Motrix\\Capabilities'
+const WINDOWS_TORRENT_PROGID = 'Motrix.File.Torrent'
+const WINDOWS_MAGNET_PROGID = 'Motrix.Url.Magnet'
+const WINDOWS_USER_CHOICE_KEYS = {
+ torrent:
+ 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.torrent\\UserChoice',
+ magnet:
+ 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\magnet\\UserChoice',
+} as const
+
+export type WindowsRegistrationScope = 'user' | 'machine'
+
+interface ResolveWindowsDefaultAppsSettingsUrlDeps {
+ osRelease?: string
+ hasRegistration?: (scope: WindowsRegistrationScope) => Promise<boolean | null>
+}
+
+interface GetWindowsDefaultAssociationsDeps {
+ platform?: NodeJS.Platform
+ hasRegistration?: (scope: WindowsRegistrationScope) => Promise<boolean | null>
+ readUserChoice?: (
+ association: 'torrent' | 'magnet'
+ ) => Promise<{ ok: boolean; progId: string | null }>
+}
+
+/**
+ * The registered-app query was backported to specific Windows 11 cumulative
+ * updates. Windows 10 and earlier Windows 11 builds only support the generic
+ * Default Apps page.
+ */
+export function supportsRegisteredAppDefaultAppsQuery(
+ osRelease: string
+): boolean {
+ const [major, minor, build, revision = 0] = osRelease
+ .split('.')
+ .map((part) => Number.parseInt(part, 10))
+
+ if (major !== 10 || minor !== 0) return false
+ if (build === 22000) return revision >= 1817
+ if (build === 22621) return revision >= 1555
+ return build >= 22631
+}
+
+export function buildWindowsDefaultAppsSettingsUrl(
+ scope: WindowsRegistrationScope | null
+): string {
+ if (!scope) return WINDOWS_DEFAULT_APPS_SETTINGS_URL
+ const query = scope === 'user' ? 'registeredAppUser' : 'registeredAppMachine'
+ return `${WINDOWS_DEFAULT_APPS_SETTINGS_URL}?${query}=${encodeURIComponent(WINDOWS_REGISTERED_APP_NAME)}`
+}
+
+async function hasWindowsRegistration(
+ scope: WindowsRegistrationScope
+): Promise<boolean | null> {
+ const root = scope === 'user' ? 'HKCU' : 'HKLM'
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows'
+ const regExe = path.win32.join(systemRoot, 'System32', 'reg.exe')
+
+ try {
+ const { stdout } = await execFileAsync(
+ regExe,
+ ['query', `${root}\\Software\\RegisteredApplications`, '/reg:64'],
+ { timeout: 2_000, windowsHide: true }
+ )
+ const registration = new RegExp(
+ `^\\s*${WINDOWS_REGISTERED_APP_NAME}\\s+REG_\\w+\\s+(.+?)\\s*$`,
+ 'imu'
+ ).exec(stdout.toString())?.[1]
+ return (
+ registration?.toLowerCase() ===
+ WINDOWS_CAPABILITIES_REGISTRY_PATH.toLowerCase()
+ )
+ } catch {
+ return null
+ }
+}
+
+async function readWindowsUserChoice(
+ association: 'torrent' | 'magnet'
+): Promise<{ ok: boolean; progId: string | null }> {
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows'
+ const regExe = path.win32.join(systemRoot, 'System32', 'reg.exe')
+
+ try {
+ const { stdout } = await execFileAsync(
+ regExe,
+ [
+ 'query',
+ `HKCU\\${WINDOWS_USER_CHOICE_KEYS[association]}`,
+ '/v',
+ 'ProgId',
+ '/reg:64',
+ ],
+ { timeout: 2_000, windowsHide: true }
+ )
+ const progId =
+ /^\s*ProgId\s+REG_\w+\s+(.+?)\s*$/imu.exec(stdout.toString())?.[1] ?? null
+ return { ok: progId !== null, progId }
+ } catch {
+ return { ok: false, progId: null }
+ }
+}
+
+export async function getWindowsDefaultAssociations(
+ deps: GetWindowsDefaultAssociationsDeps = {}
+): Promise<WindowsDefaultAssociations> {
+ if ((deps.platform ?? process.platform) !== 'win32') {
+ return {
+ supported: false,
+ registered: false,
+ scope: null,
+ torrent: false,
+ magnet: false,
+ }
+ }
+
+ const hasRegistration = deps.hasRegistration ?? hasWindowsRegistration
+ const readUserChoice = deps.readUserChoice ?? readWindowsUserChoice
+ const [userRegistered, torrentChoice, magnetChoice] = await Promise.all([
+ hasRegistration('user'),
+ readUserChoice('torrent'),
+ readUserChoice('magnet'),
+ ])
+ const machineRegistered =
+ userRegistered === true ? false : await hasRegistration('machine')
+ const registered =
+ userRegistered === true || machineRegistered === true
+ ? true
+ : userRegistered === false && machineRegistered === false
+ ? false
+ : null
+
+ return {
+ supported: true,
+ registered,
+ scope:
+ userRegistered === true
+ ? 'user'
+ : userRegistered === false && machineRegistered === true
+ ? 'machine'
+ : null,
+ torrent: torrentChoice.ok
+ ? torrentChoice.progId?.toLowerCase() ===
+ WINDOWS_TORRENT_PROGID.toLowerCase()
+ : null,
+ magnet: magnetChoice.ok
+ ? magnetChoice.progId?.toLowerCase() ===
+ WINDOWS_MAGNET_PROGID.toLowerCase()
+ : null,
+ }
+}
+
+export async function resolveWindowsDefaultAppsSettingsUrl(
+ deps: ResolveWindowsDefaultAppsSettingsUrlDeps = {}
+): Promise<string> {
+ if (!supportsRegisteredAppDefaultAppsQuery(deps.osRelease ?? release())) {
+ return WINDOWS_DEFAULT_APPS_SETTINGS_URL
+ }
+
+ const hasRegistration = deps.hasRegistration ?? hasWindowsRegistration
+ const userRegistration = await hasRegistration('user')
+ if (userRegistration === true) {
+ return buildWindowsDefaultAppsSettingsUrl('user')
+ }
+ // An unreadable HKCU registration could shadow HKLM. Avoid a scope-specific
+ // deep link when the effective scope cannot be established.
+ if (userRegistration === null) return WINDOWS_DEFAULT_APPS_SETTINGS_URL
+ if ((await hasRegistration('machine')) === true) {
+ return buildWindowsDefaultAppsSettingsUrl('machine')
+ }
+
+ // The portable ZIP never runs the NSIS registration. Keep its button useful
+ // by opening the generic page instead of deep-linking to a nonexistent app.
+ return WINDOWS_DEFAULT_APPS_SETTINGS_URL
+}
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
index 4f654afd..3d095351 100644
--- a/src/renderer/routes/settings/cards/integration/appimage-integration-section.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/appimage-integration-section.test.tsx
@@ -143,6 +143,35 @@ describe('AppImageIntegrationSection', () => {
).toBeInTheDocument()
})
+ it('explains why a safe removal was blocked', 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: 'accepted',
+ owner: 'self',
+ status: 'failed',
+ }
+ }
+ throw new Error(`unexpected channel: ${channel}`)
+ })
+ render(<AppImageIntegrationSection />)
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Remove desktop integration' })
+ )
+ expect(
+ await screen.findByText(/kept its desktop entry to avoid leaving/u)
+ ).toBeVisible()
+ })
+
it('blocks removal for an externally-owned integration', async () => {
statusOnly({
supported: true,
diff --git a/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx b/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx
index 6a6c33a4..f6418996 100644
--- a/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/appimage-integration-section.tsx
@@ -24,10 +24,17 @@ function parseView(value: unknown): SupportedView | null {
return view.supported === true ? view : null
}
-export function AppImageIntegrationSection() {
+export interface AppImageIntegrationSectionProps {
+ onIntegrationChange?: () => void
+}
+
+export function AppImageIntegrationSection({
+ onIntegrationChange,
+}: AppImageIntegrationSectionProps = {}) {
const { t } = useTranslation()
const [view, setView] = useState<SupportedView | null>(null)
const [busy, setBusy] = useState(false)
+ const [lastAction, setLastAction] = useState<'enable' | 'remove' | null>(null)
useEffect(() => {
let stale = false
@@ -57,9 +64,15 @@ export function AppImageIntegrationSection() {
| typeof Commands.EnableAppImageIntegration
| typeof Commands.RemoveAppImageIntegration
) => {
+ const action =
+ channel === Commands.RemoveAppImageIntegration ? 'remove' : 'enable'
setBusy(true)
+ setLastAction(null)
try {
- setView(parseView(await transport.invoke(channel)))
+ const next = parseView(await transport.invoke(channel))
+ setView(next)
+ setLastAction(action)
+ onIntegrationChange?.()
} catch {
// Keep the current view; the main process logs the failure.
} finally {
@@ -131,7 +144,11 @@ export function AppImageIntegrationSection() {
{t('settings.integration.appimage.status.failedTitle')}
</AlertTitle>
<AlertDescription>
- {t('settings.integration.appimage.status.failedDetail')}
+ {t(
+ lastAction === 'remove'
+ ? 'settings.integration.appimage.status.removeBlockedDetail'
+ : 'settings.integration.appimage.status.failedDetail'
+ )}
</AlertDescription>
</Alert>
)}
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx
index 544a1415..89ebdb00 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx
@@ -7,6 +7,7 @@ import {
CliToolReason,
} from '@shared/types/cli-tool'
import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
vi.mock('@renderer/lib/transport', () => ({
@@ -79,6 +80,7 @@ if (typeof globalThis.ResizeObserver === 'undefined') {
} as unknown as typeof ResizeObserver
}
+import { transport } from '@renderer/lib/transport'
import { IntegrationDialog } from './integration-dialog'
describe('IntegrationDialog scaffold', () => {
@@ -143,4 +145,61 @@ describe('IntegrationDialog scaffold', () => {
/only in the desktop app/i
)
})
+
+ it('keeps the dialog open when the saved magnet association was rejected', async () => {
+ const onClose = vi.fn()
+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
+ if (channel === 'query:getSettings') {
+ return {
+ app: {
+ browserBridgeEnabled: false,
+ protocols: { magnet: false },
+ },
+ media: {
+ ffmpegBinaryPath: '',
+ ffmpegStagingMB: 1024,
+ ffmpegOpTimeoutSec: 300,
+ },
+ }
+ }
+ if (channel === 'command:updateSettings') {
+ return { ok: true, protocolAssociationApplied: false }
+ }
+ if (
+ channel === 'bridge:listPaired' ||
+ channel === 'bridge:listTrusted' ||
+ channel === 'bridge:listPendingPairRequests'
+ ) {
+ return []
+ }
+ if (channel === 'query:getFfmpegDetection') {
+ return { active: null, candidates: [] }
+ }
+ if (channel === 'query:getAppImageIntegrationStatus') {
+ return { supported: false }
+ }
+ return {}
+ })
+ const user = userEvent.setup()
+ render(
+ <IntegrationDialog
+ open={true}
+ onClose={onClose}
+ labelKey="settings.cards.integration.title"
+ descKey="settings.cards.integration.desc"
+ />
+ )
+
+ await user.click(
+ await screen.findByRole('switch', {
+ name: 'Open magnet links with Motrix',
+ })
+ )
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+
+ expect(
+ await screen.findByText(/desktop association could not be changed/i)
+ ).toBeVisible()
+ expect(onClose).not.toHaveBeenCalled()
+ })
})
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
index 7907334c..95a380e0 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { Alert, AlertDescription } from '@renderer/components/ui/alert'
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
@@ -15,7 +16,8 @@ import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
import { DEFAULT_APP_SETTINGS, DEFAULT_MEDIA_SETTINGS } from '@shared/schemas'
import type { AppSettings } from '@shared/types/settings'
-import { useEffect } from 'react'
+import { CircleAlert } from 'lucide-react'
+import { useEffect, useState } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod'
@@ -59,6 +61,8 @@ export function IntegrationDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
+ const [protocolRevision, setProtocolRevision] = useState(0)
+ const [saveError, setSaveError] = useState<string | null>(null)
const form = useForm<IntegrationFormValues>({
resolver: zodResolver(integrationFormSchema),
defaultValues: DEFAULTS,
@@ -90,6 +94,7 @@ export function IntegrationDialog({
}, [open])
const onSubmit = form.handleSubmit(async (values) => {
+ setSaveError(null)
const dirty = pickDirty(values, form.formState.dirtyFields) as
| Partial<{
app: Partial<IntegrationFormValues['app']>
@@ -101,7 +106,13 @@ export function IntegrationDialog({
return
}
const patch = dirty as Partial<AppSettings>
- await transport.invoke(Commands.UpdateSettings, patch)
+ const result = (await transport.invoke(Commands.UpdateSettings, patch)) as {
+ protocolAssociationApplied?: boolean
+ }
+ if (result.protocolAssociationApplied === false) {
+ setSaveError(t('settings.integration.system.protocolMagnetApplyFailed'))
+ return
+ }
onClose()
})
@@ -129,8 +140,12 @@ export function IntegrationDialog({
>
{t('settings.integration.system.title')}
</h3>
- <SystemProtocolsSection />
- <AppImageIntegrationSection />
+ <SystemProtocolsSection refreshRevision={protocolRevision} />
+ <AppImageIntegrationSection
+ onIntegrationChange={() =>
+ setProtocolRevision((revision) => revision + 1)
+ }
+ />
</section>
<Separator />
@@ -185,6 +200,12 @@ export function IntegrationDialog({
</div>
<DialogFooter className="shrink-0 border-t border-border px-6 py-4">
+ {saveError && (
+ <Alert variant="destructive" className="mr-auto">
+ <CircleAlert aria-hidden="true" />
+ <AlertDescription>{saveError}</AlertDescription>
+ </Alert>
+ )}
<Button type="button" variant="outline" size="sm" onClick={onClose}>
{t('common.cancel')}
</Button>
diff --git a/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx b/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
new file mode 100644
index 00000000..8ef937c2
--- /dev/null
+++ b/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
@@ -0,0 +1,223 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { LinuxDefaultAssociations } from '@shared/types/linux-default-apps'
+import type { WindowsDefaultAssociations } from '@shared/types/windows-default-apps'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { FormProvider, useForm } from 'react-hook-form'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { IntegrationFormValues } from './integration-dialog'
+import { SystemProtocolsSection } from './system-protocols-section'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { invoke: vi.fn(), off: vi.fn(), on: vi.fn(), platform: 'win32' },
+}))
+
+let windowsStatus: WindowsDefaultAssociations
+let linuxStatus: LinuxDefaultAssociations
+
+function renderSection(platform: typeof transport.platform) {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: platform,
+ })
+
+ function Harness() {
+ const form = useForm<IntegrationFormValues>({
+ defaultValues: {
+ app: {
+ browserBridgeEnabled: true,
+ protocols: { magnet: true },
+ },
+ media: {
+ ffmpegBinaryPath: '',
+ ffmpegStagingMB: 512,
+ ffmpegOpTimeoutSec: 300,
+ },
+ },
+ })
+ return (
+ <FormProvider {...form}>
+ <SystemProtocolsSection />
+ </FormProvider>
+ )
+ }
+
+ return render(<Harness />)
+}
+
+describe('<SystemProtocolsSection>', () => {
+ beforeEach(() => {
+ windowsStatus = {
+ supported: true,
+ registered: true,
+ scope: 'user',
+ torrent: true,
+ magnet: false,
+ }
+ linuxStatus = {
+ supported: true,
+ packageKind: 'native',
+ registered: true,
+ canSetTorrentDefault: true,
+ torrent: false,
+ magnet: true,
+ }
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetWindowsDefaultAssociations) {
+ return windowsStatus
+ }
+ if (channel === Queries.GetLinuxDefaultAssociations) {
+ return linuxStatus
+ }
+ if (channel === Commands.RequestDefaultTorrentHandler) {
+ return { ok: true, action: 'set' }
+ }
+ if (channel === Commands.EnableAppImageIntegration) {
+ return { supported: true, status: 'healthy' }
+ }
+ return { ok: true }
+ })
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('shows current Windows status and opens the system settings', async () => {
+ renderSection('win32')
+
+ expect(
+ screen.queryByText('Open magnet links with Motrix')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByText('Default app for torrents and magnet links')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText(
+ /Motrix appears there after installation with Motrix Setup/u
+ )
+ ).toBeInTheDocument()
+ expect(await screen.findByText('Default')).toBeInTheDocument()
+ expect(screen.getByText('Not default')).toBeInTheDocument()
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Open Windows settings' })
+ )
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.RequestDefaultTorrentHandler
+ )
+ )
+ })
+
+ it('refreshes association status when the window regains focus', async () => {
+ windowsStatus = { ...windowsStatus, torrent: false }
+ renderSection('win32')
+ expect(await screen.findAllByText('Not default')).toHaveLength(2)
+
+ windowsStatus = { ...windowsStatus, torrent: true, magnet: true }
+ act(() => window.dispatchEvent(new Event('focus')))
+
+ await waitFor(() => {
+ expect(screen.getAllByText('Default')).toHaveLength(2)
+ })
+ })
+
+ it('explains when the portable ZIP has no installer registration', async () => {
+ windowsStatus = { ...windowsStatus, registered: false, scope: null }
+ renderSection('win32')
+
+ expect(await screen.findAllByText('Setup required')).toHaveLength(2)
+ })
+
+ it('shows live native Linux defaults and offers a verified one-click action', async () => {
+ renderSection('linux')
+
+ expect(
+ screen.getByText('Open magnet links with Motrix')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText('Linux file and link associations')
+ ).toBeInTheDocument()
+ expect(await screen.findByText('Package: deb / rpm')).toBeVisible()
+ expect(screen.getByText('Not default')).toBeVisible()
+ expect(screen.getByText('Default')).toBeVisible()
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Set .torrent default' })
+ )
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.RequestDefaultTorrentHandler
+ )
+ )
+ expect(
+ await screen.findByText('Motrix is now the default for .torrent files.')
+ ).toBeVisible()
+ })
+
+ it('routes AppImage users to the dedicated desktop integration controls', async () => {
+ linuxStatus = {
+ ...linuxStatus,
+ packageKind: 'appimage',
+ canSetTorrentDefault: false,
+ torrent: true,
+ }
+ renderSection('linux')
+
+ expect(await screen.findByText('Package: AppImage')).toBeVisible()
+ expect(screen.getByText(/Use Desktop integration below/u)).toBeVisible()
+ expect(
+ screen.queryByRole('button', { name: 'Set .torrent default' })
+ ).not.toBeInTheDocument()
+ expect(screen.getByText(/Applied immediately after saving/u)).toBeVisible()
+ })
+
+ it('offers a transaction-safe repair for a legacy AppImage association', async () => {
+ linuxStatus = {
+ ...linuxStatus,
+ packageKind: 'appimage',
+ registered: true,
+ canSetTorrentDefault: false,
+ torrent: false,
+ }
+ renderSection('linux')
+
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Repair associations' })
+ )
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.EnableAppImageIntegration
+ )
+ )
+ })
+
+ it('explains sandbox ownership and distinguishes an unreadable default', async () => {
+ linuxStatus = {
+ ...linuxStatus,
+ packageKind: 'flatpak',
+ canSetTorrentDefault: false,
+ torrent: null,
+ magnet: null,
+ }
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetLinuxDefaultAssociations) return linuxStatus
+ if (channel === Commands.RequestDefaultTorrentHandler) {
+ return { ok: true, action: 'opened-fallback' }
+ }
+ return { ok: true }
+ })
+ renderSection('linux')
+
+ expect(await screen.findByText('Package: Flatpak')).toBeVisible()
+ expect(screen.getAllByText("Couldn't verify")).toHaveLength(2)
+ fireEvent.click(screen.getByRole('button', { name: 'View setup steps' }))
+ expect(
+ await screen.findByText(/Setup instructions were opened instead/u)
+ ).toBeVisible()
+ })
+})
diff --git a/src/renderer/routes/settings/cards/integration/system-protocols-section.tsx b/src/renderer/routes/settings/cards/integration/system-protocols-section.tsx
index 64248b42..5b381c00 100644
--- a/src/renderer/routes/settings/cards/integration/system-protocols-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/system-protocols-section.tsx
@@ -7,48 +7,232 @@ import {
FormLabel,
} from '@renderer/components/ui/form'
import { Switch } from '@renderer/components/ui/switch'
+import { useTransportMirror } from '@renderer/hooks/use-transport-mirror'
import { transport } from '@renderer/lib/transport'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { LinuxDefaultAssociations } from '@shared/types/linux-default-apps'
+import type { WindowsDefaultAssociations } from '@shared/types/windows-default-apps'
import { CircleQuestionMark } from 'lucide-react'
+import { useEffect, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import type { IntegrationFormValues } from './integration-dialog'
-export function SystemProtocolsSection() {
+type AssociationDisplayState =
+ | 'checking'
+ | 'setupRequired'
+ | 'default'
+ | 'notDefault'
+ | 'unavailable'
+
+const ASSOCIATION_STATUS_CLASS: Record<AssociationDisplayState, string> = {
+ checking: 'bg-muted-foreground/50',
+ setupRequired: 'bg-amber-500',
+ default: 'bg-emerald-500',
+ notDefault: 'bg-muted-foreground/50',
+ unavailable: 'bg-amber-500',
+}
+
+const ASSOCIATION_STATUS_KEY = {
+ checking: 'settings.integration.system.associationChecking',
+ setupRequired: 'settings.integration.system.associationSetupRequired',
+ default: 'settings.integration.system.associationDefault',
+ notDefault: 'settings.integration.system.associationNotDefault',
+ unavailable: 'settings.integration.system.associationUnavailable',
+} as const
+
+function associationDisplayState(
+ status: WindowsDefaultAssociations | LinuxDefaultAssociations | null,
+ isDefault: boolean | null
+): AssociationDisplayState {
+ if (!status) return 'checking'
+ if (!status.supported) return 'unavailable'
+ if (status.registered === null) return 'unavailable'
+ if (!status.registered) return 'setupRequired'
+ if (isDefault === null) return 'unavailable'
+ return isDefault ? 'default' : 'notDefault'
+}
+
+export interface SystemProtocolsSectionProps {
+ refreshRevision?: number
+}
+
+export function SystemProtocolsSection({
+ refreshRevision = 0,
+}: SystemProtocolsSectionProps) {
const { t } = useTranslation()
const form = useFormContext<IntegrationFormValues>()
+ const isWindows = transport.platform === 'win32'
+ const isLinux = transport.platform === 'linux'
+ const [windowsAssociations, setWindowsAssociations] =
+ useState<WindowsDefaultAssociations | null>(null)
+ const [linuxAssociations, setLinuxAssociations] =
+ useState<LinuxDefaultAssociations | null>(null)
+ const [linuxAction, setLinuxAction] = useState<
+ 'idle' | 'running' | 'set' | 'fallback' | 'failed'
+ >('idle')
+ const { refresh: refreshWindowsAssociations } = useTransportMirror({
+ events: [],
+ refetchOnFocus: isWindows,
+ retryOnce: true,
+ load: async (stale) => {
+ if (!isWindows) return
+ const status = (await transport.invoke(
+ Queries.GetWindowsDefaultAssociations
+ )) as WindowsDefaultAssociations
+ if (!stale()) setWindowsAssociations(status)
+ },
+ })
+ const { refresh: refreshLinuxAssociations } = useTransportMirror({
+ events: [],
+ refetchOnFocus: isLinux,
+ retryOnce: true,
+ load: async (stale) => {
+ if (!isLinux) return
+ const status = (await transport.invoke(
+ Queries.GetLinuxDefaultAssociations
+ )) as LinuxDefaultAssociations
+ if (!stale()) setLinuxAssociations(status)
+ },
+ })
+
+ useEffect(() => {
+ if (refreshRevision > 0 && isLinux) void refreshLinuxAssociations()
+ }, [isLinux, refreshLinuxAssociations, refreshRevision])
+
+ const associationLabel =
+ isWindows || isLinux
+ ? t(
+ isWindows
+ ? 'settings.integration.system.defaultAssociationsWindows'
+ : 'settings.integration.system.defaultAssociationsLinux'
+ )
+ : t('settings.integration.system.torrentAssociation')
+ let associationDescription = t(
+ 'settings.integration.system.torrentAssociationDesc'
+ )
+ if (transport.platform === 'darwin') {
+ associationDescription = t(
+ 'settings.integration.system.torrentAssociationMacDesc'
+ )
+ } else if (isWindows) {
+ associationDescription = t(
+ 'settings.integration.system.defaultAssociationsWindowsDesc'
+ )
+ } else if (isLinux) {
+ const kind = linuxAssociations?.packageKind
+ associationDescription = t(
+ linuxAssociations === null
+ ? 'settings.integration.system.defaultAssociationsLinuxCheckingDesc'
+ : !linuxAssociations.supported
+ ? 'settings.integration.system.defaultAssociationsLinuxUnavailableDesc'
+ : kind === 'appimage'
+ ? 'settings.integration.system.defaultAssociationsLinuxAppImageDesc'
+ : kind === 'flatpak' || kind === 'snap'
+ ? 'settings.integration.system.defaultAssociationsLinuxSandboxDesc'
+ : 'settings.integration.system.defaultAssociationsLinuxDesc'
+ )
+ }
const handleOpenSystemSettings = async () => {
- await transport.invoke(Commands.RequestDefaultTorrentHandler)
+ if (isLinux) setLinuxAction('running')
+ try {
+ const channel =
+ isLinux && linuxAssociations?.packageKind === 'appimage'
+ ? Commands.EnableAppImageIntegration
+ : Commands.RequestDefaultTorrentHandler
+ const result = (await transport.invoke(channel)) as {
+ action?: string
+ supported?: boolean
+ status?: string | null
+ }
+ if (isWindows) await refreshWindowsAssociations()
+ if (isLinux) {
+ await refreshLinuxAssociations()
+ if (channel === Commands.EnableAppImageIntegration) {
+ setLinuxAction(
+ result.supported === true && result.status === 'healthy'
+ ? 'set'
+ : 'failed'
+ )
+ } else {
+ setLinuxAction(result.action === 'set' ? 'set' : 'fallback')
+ }
+ }
+ } catch {
+ if (isLinux) setLinuxAction('failed')
+ }
}
+ const associations = isWindows ? windowsAssociations : linuxAssociations
+ const associationRows = [
+ {
+ id: 'torrent',
+ label: t('settings.integration.system.torrentFiles'),
+ isDefault: associations?.torrent ?? null,
+ },
+ {
+ id: 'magnet',
+ label: t('settings.integration.system.magnetLinks'),
+ isDefault: associations?.magnet ?? null,
+ },
+ ] as const
+
+ const linuxPackageLabel = linuxAssociations?.packageKind
+ ? t(
+ `settings.integration.system.linuxPackage.${linuxAssociations.packageKind}`
+ )
+ : null
+ const showLinuxButton =
+ isLinux &&
+ linuxAssociations !== null &&
+ (linuxAssociations.packageKind !== 'appimage' ||
+ (linuxAssociations.registered && linuxAssociations.torrent !== true))
+ const isAppImageRepair =
+ linuxAssociations?.packageKind === 'appimage' && showLinuxButton
+ const linuxCanSet = linuxAssociations?.canSetTorrentDefault === true
+
return (
<div className="space-y-4">
- <FormField
- control={form.control}
- name="app.protocols.magnet"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.integration.system.protocolMagnet')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.integration.system.protocolMagnetDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch checked={field.value} onCheckedChange={field.onChange} />
- </FormControl>
- </FormItem>
- )}
- />
+ {!isWindows && (
+ <FormField
+ control={form.control}
+ name="app.protocols.magnet"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.integration.system.protocolMagnet')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t(
+ isLinux && linuxAssociations?.packageKind === 'appimage'
+ ? 'settings.integration.system.protocolMagnetAppImageDesc'
+ : isLinux &&
+ (linuxAssociations?.packageKind === 'flatpak' ||
+ linuxAssociations?.packageKind === 'snap')
+ ? 'settings.integration.system.protocolMagnetSandboxDesc'
+ : 'settings.integration.system.protocolMagnetDesc'
+ )}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ )}
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<span className="inline-flex items-center gap-1.5 text-sm font-medium">
- {t('settings.integration.system.torrentAssociation')}
+ {associationLabel}
<a
href={EXTERNAL_URLS.motrix.manual.defaultApplication}
target="_blank"
@@ -60,19 +244,92 @@ export function SystemProtocolsSection() {
</a>
</span>
<p className="text-xs text-muted-foreground">
- {transport.platform === 'darwin'
- ? t('settings.integration.system.torrentAssociationMacDesc')
- : t('settings.integration.system.torrentAssociationDesc')}
+ {associationDescription}
</p>
+ {(isWindows || isLinux) && (
+ <div
+ className="mt-2 grid gap-1.5"
+ role="status"
+ aria-live="polite"
+ aria-label={t(
+ isWindows
+ ? 'settings.integration.system.associationStatusLabel'
+ : 'settings.integration.system.associationStatusLabelLinux'
+ )}
+ >
+ {linuxPackageLabel && (
+ <p className="mb-0.5 text-xs text-muted-foreground">
+ {t('settings.integration.system.linuxPackageDetected', {
+ package: linuxPackageLabel,
+ })}
+ </p>
+ )}
+ {associationRows.map((row) => {
+ const state = associationDisplayState(
+ associations,
+ row.isDefault
+ )
+ return (
+ <div
+ key={row.id}
+ className="flex items-center justify-between gap-6 text-xs"
+ >
+ <span className="text-muted-foreground">{row.label}</span>
+ <span className="inline-flex items-center gap-1.5 font-medium">
+ <span
+ className={`size-1.5 rounded-full ${ASSOCIATION_STATUS_CLASS[state]}`}
+ aria-hidden="true"
+ />
+ {t(
+ state === 'setupRequired' && isLinux
+ ? 'settings.integration.system.associationNotRegistered'
+ : ASSOCIATION_STATUS_KEY[state]
+ )}
+ </span>
+ </div>
+ )
+ })}
+ {isLinux &&
+ linuxAction !== 'idle' &&
+ linuxAction !== 'running' && (
+ <p
+ className={`pt-1 text-xs ${
+ linuxAction === 'set'
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : linuxAction === 'failed'
+ ? 'text-destructive'
+ : 'text-muted-foreground'
+ }`}
+ >
+ {t(
+ linuxAction === 'set'
+ ? 'settings.integration.system.linuxActionSet'
+ : linuxAction === 'failed'
+ ? 'settings.integration.system.linuxActionFailed'
+ : 'settings.integration.system.linuxActionFallback'
+ )}
+ </p>
+ )}
+ </div>
+ )}
</div>
- {transport.platform !== 'darwin' && (
+ {(isWindows || showLinuxButton) && (
<Button
type="button"
variant="outline"
size="sm"
+ disabled={isLinux && linuxAction === 'running'}
onClick={handleOpenSystemSettings}
>
- {t('settings.common.setAsDefault')}
+ {isWindows
+ ? t('settings.integration.system.openWindowsSettings')
+ : t(
+ isAppImageRepair
+ ? 'settings.integration.system.repairLinuxAssociations'
+ : linuxCanSet
+ ? 'settings.integration.system.setTorrentDefaultLinux'
+ : 'settings.integration.system.viewLinuxInstructions'
+ )}
</Button>
)}
</div>
diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.ts
index 105b13bb..95d49780 100644
--- a/src/server/ipc/queries.test.ts
+++ b/src/server/ipc/queries.test.ts
@@ -139,6 +139,35 @@ function makeCtx(over: Record<string, unknown> = {}) {
}
describe('buildServerQueryHandlers — allowed save directories', () => {
+ it('reports Linux associations as unsupported on the web server', async () => {
+ const handlers = buildServerQueryHandlers(makeCtx() as never)
+
+ await expect(
+ handlers[Queries.GetLinuxDefaultAssociations]?.()
+ ).resolves.toEqual({
+ supported: false,
+ packageKind: null,
+ registered: false,
+ canSetTorrentDefault: false,
+ torrent: null,
+ magnet: null,
+ })
+ })
+
+ it('reports Windows associations as unsupported on the web server', async () => {
+ const handlers = buildServerQueryHandlers(makeCtx() as never)
+
+ await expect(
+ handlers[Queries.GetWindowsDefaultAssociations]?.()
+ ).resolves.toEqual({
+ supported: false,
+ registered: false,
+ scope: null,
+ torrent: false,
+ magnet: false,
+ })
+ })
+
it('publishes the validated path policy instead of reparsing the environment', async () => {
const handlers = buildServerQueryHandlers(
makeCtx({
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index f1f031f3..c37397df 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -179,6 +179,23 @@ export function buildServerQueryHandlers(
[Queries.GetSystemProxy]: async () => null,
+ [Queries.GetLinuxDefaultAssociations]: async () => ({
+ supported: false,
+ packageKind: null,
+ registered: false,
+ canSetTorrentDefault: false,
+ torrent: null,
+ magnet: null,
+ }),
+
+ [Queries.GetWindowsDefaultAssociations]: async () => ({
+ supported: false,
+ registered: false,
+ scope: null,
+ torrent: false,
+ magnet: false,
+ }),
+
[Queries.GetTrackerList]: async () => trackerManager.getCuratedList(),
[Queries.GetTrackerSources]: async () =>
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index ddc1f99e..5af8358a 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1402,7 +1402,43 @@
"protocolMagnetDesc": "Open magnet links from your browser in Motrix.",
"torrentAssociation": "Open .torrent files with Motrix",
"torrentAssociationDesc": "Once set, double-clicking a .torrent file will open it in Motrix.",
- "torrentAssociationMacDesc": "In Finder, right-click any .torrent file → Get Info → Open with → choose Motrix → Change All…"
+ "torrentAssociationMacDesc": "In Finder, right-click any .torrent file → Get Info → Open with → choose Motrix → Change All…",
+ "defaultAssociationsWindows": "Default app for torrents and magnet links",
+ "defaultAssociationsWindowsDesc": "Choose Motrix for .torrent files and magnet links in Windows Default Apps. Motrix appears there after installation with Motrix Setup.",
+ "torrentFiles": ".torrent files",
+ "magnetLinks": "Magnet links",
+ "associationStatusLabel": "Current Windows default app status",
+ "associationChecking": "Checking…",
+ "associationSetupRequired": "Setup required",
+ "associationDefault": "Default",
+ "associationNotDefault": "Not default",
+ "associationUnavailable": "Couldn't verify",
+ "associationNotRegistered": "Not registered",
+ "openWindowsSettings": "Open Windows settings",
+ "defaultAssociationsLinux": "Linux file and link associations",
+ "defaultAssociationsLinuxCheckingDesc": "Checking this Linux package and its current desktop associations…",
+ "defaultAssociationsLinuxUnavailableDesc": "Desktop association status isn't available from this app environment.",
+ "defaultAssociationsLinuxDesc": "Motrix can set itself as the .torrent default for an installed deb or rpm package. Magnet changes take effect when you apply this dialog.",
+ "defaultAssociationsLinuxAppImageDesc": "Use Desktop integration below to register or remove this AppImage safely. Motrix restores verified previous handlers before deleting its desktop entry.",
+ "defaultAssociationsLinuxSandboxDesc": "This package publishes Motrix as a handler, but your desktop environment chooses the default app. Removing the package may not restore the previous default automatically.",
+ "associationStatusLabelLinux": "Current Linux file and link association status",
+ "linuxPackageDetected": "Package: {{package}}",
+ "linuxPackage": {
+ "appimage": "AppImage",
+ "native": "deb / rpm",
+ "flatpak": "Flatpak",
+ "snap": "Snap",
+ "unknown": "Unknown package"
+ },
+ "protocolMagnetAppImageDesc": "Applied immediately after saving when Desktop integration is enabled.",
+ "protocolMagnetSandboxDesc": "Motrix will request the change when you save, but the sandbox or desktop environment may require you to choose the default app manually.",
+ "protocolMagnetApplyFailed": "The preference was saved, but the desktop association could not be changed. Choose the default app in your system settings.",
+ "setTorrentDefaultLinux": "Set .torrent default",
+ "repairLinuxAssociations": "Repair associations",
+ "viewLinuxInstructions": "View setup steps",
+ "linuxActionSet": "Motrix is now the default for .torrent files.",
+ "linuxActionFallback": "Automatic setup isn't available for this package. Setup instructions were opened instead.",
+ "linuxActionFailed": "Couldn't update the Linux default. Check your desktop environment settings."
},
"browser": {
"title": "Browser extensions",
@@ -1589,6 +1625,7 @@
"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.",
+ "removeBlockedDetail": "Motrix couldn't safely restore a verified previous handler, so it kept its desktop entry to avoid leaving a broken default. Choose another default app in your desktop settings, then try removing the integration again.",
"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."
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 1ea91d36..379565da 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1389,7 +1389,43 @@
"protocolMagnetDesc": "在浏览器里点击磁力链接时,用 Motrix 打开。",
"torrentAssociation": "用 Motrix 打开种子文件",
"torrentAssociationDesc": "设置好之后,双击种子文件 (.torrent) 会自动用 Motrix 打开。",
- "torrentAssociationMacDesc": "在 Finder 中右键任意 .torrent 文件 → 显示简介 → 打开方式 → 选择 Motrix → 全部更改…"
+ "torrentAssociationMacDesc": "在 Finder 中右键任意 .torrent 文件 → 显示简介 → 打开方式 → 选择 Motrix → 全部更改…",
+ "defaultAssociationsWindows": "种子文件和磁力链接的默认应用",
+ "defaultAssociationsWindowsDesc": "在 Windows 默认应用中为 .torrent 文件和磁力链接选择 Motrix。使用 Motrix 安装程序安装后,Motrix 才会出现在列表中。",
+ "torrentFiles": ".torrent 文件",
+ "magnetLinks": "磁力链接",
+ "associationStatusLabel": "当前 Windows 默认应用状态",
+ "associationChecking": "正在检查…",
+ "associationSetupRequired": "需要安装程序",
+ "associationDefault": "当前默认",
+ "associationNotDefault": "不是默认",
+ "associationUnavailable": "无法确认",
+ "associationNotRegistered": "尚未注册",
+ "openWindowsSettings": "打开 Windows 设置",
+ "defaultAssociationsLinux": "Linux 文件与链接关联",
+ "defaultAssociationsLinuxCheckingDesc": "正在识别当前 Linux 软件包并读取桌面关联…",
+ "defaultAssociationsLinuxUnavailableDesc": "当前应用环境无法读取桌面关联状态。",
+ "defaultAssociationsLinuxDesc": "通过 deb 或 rpm 安装时,Motrix 可以一键设为 .torrent 默认应用;磁力链接开关会在应用此对话框后生效。",
+ "defaultAssociationsLinuxAppImageDesc": "通过下方的桌面集成安全注册或移除此 AppImage。删除桌面入口前,Motrix 会先恢复经过验证的原默认程序。",
+ "defaultAssociationsLinuxSandboxDesc": "当前软件包会把 Motrix 注册为候选处理程序,但默认应用由桌面环境决定。卸载软件包后,之前的默认程序可能不会自动恢复。",
+ "associationStatusLabelLinux": "当前 Linux 文件与链接关联状态",
+ "linuxPackageDetected": "软件包:{{package}}",
+ "linuxPackage": {
+ "appimage": "AppImage",
+ "native": "deb / rpm",
+ "flatpak": "Flatpak",
+ "snap": "Snap",
+ "unknown": "未知软件包"
+ },
+ "protocolMagnetAppImageDesc": "启用桌面集成后,保存设置会立即同步磁力链接关联。",
+ "protocolMagnetSandboxDesc": "保存时 Motrix 会请求更改,但沙箱或桌面环境可能仍要求你手动选择默认应用。",
+ "protocolMagnetApplyFailed": "设置已保存,但无法更改桌面关联。请在系统设置中选择默认应用。",
+ "setTorrentDefaultLinux": "设为 .torrent 默认",
+ "repairLinuxAssociations": "修复关联",
+ "viewLinuxInstructions": "查看设置方法",
+ "linuxActionSet": "Motrix 已成为 .torrent 文件的默认应用。",
+ "linuxActionFallback": "当前软件包无法自动设置,已改为打开设置说明。",
+ "linuxActionFailed": "无法更新 Linux 默认应用,请检查桌面环境设置。"
},
"browser": {
"title": "浏览器扩展",
@@ -1575,6 +1611,7 @@
"notIntegrated": "尚未与当前桌面集成。",
"failedTitle": "桌面集成未完成",
"failedDetail": "Motrix 未能把自己注册为链接处理程序。在你重新启用桌面集成之前,浏览器唤起可能无法工作。",
+ "removeBlockedDetail": "Motrix 无法安全恢复经过验证的原处理程序,因此保留了桌面入口,避免留下失效的默认关联。请先在桌面环境中选择其他默认应用,再重试移除集成。",
"externalManaged": "桌面集成由另一个 Motrix 安装提供。"
},
"movedHint": "如果在 Motrix 未运行时移动 AppImage,链接可能无法唤起,直到你从新位置手动启动一次 Motrix。"
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 65545249..68645e4d 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1389,7 +1389,43 @@
"protocolMagnetDesc": "從瀏覽器在 Motrix 開啟 Magnet 連結。",
"torrentAssociation": "使用 Motrix 開啟 .torrent 檔案",
"torrentAssociationDesc": "設定後,按兩下 .torrent 檔案即可在 Motrix 開啟。",
- "torrentAssociationMacDesc": "在 Finder 中,以右鍵按一下任一 .torrent 檔案 → 取得資訊 → 打開檔案的應用程式 → 選擇 Motrix → 全部更改..."
+ "torrentAssociationMacDesc": "在 Finder 中,以右鍵按一下任一 .torrent 檔案 → 取得資訊 → 打開檔案的應用程式 → 選擇 Motrix → 全部更改...",
+ "defaultAssociationsWindows": "種子檔案和 Magnet 連結的預設應用程式",
+ "defaultAssociationsWindowsDesc": "在 Windows 預設應用程式中為 .torrent 檔案和 Magnet 連結選擇 Motrix。使用 Motrix 安裝程式安裝後,Motrix 才會顯示在清單中。",
+ "torrentFiles": ".torrent 檔案",
+ "magnetLinks": "Magnet 連結",
+ "associationStatusLabel": "目前的 Windows 預設應用程式狀態",
+ "associationChecking": "正在檢查…",
+ "associationSetupRequired": "需要安裝程式",
+ "associationDefault": "目前預設",
+ "associationNotDefault": "不是預設",
+ "associationUnavailable": "無法確認",
+ "associationNotRegistered": "尚未註冊",
+ "openWindowsSettings": "開啟 Windows 設定",
+ "defaultAssociationsLinux": "Linux 檔案與連結關聯",
+ "defaultAssociationsLinuxCheckingDesc": "正在識別目前的 Linux 套件並讀取桌面關聯…",
+ "defaultAssociationsLinuxUnavailableDesc": "目前的應用程式環境無法讀取桌面關聯狀態。",
+ "defaultAssociationsLinuxDesc": "透過 deb 或 rpm 安裝時,Motrix 可以一鍵設為 .torrent 預設應用程式;Magnet 連結開關會在套用此對話框後生效。",
+ "defaultAssociationsLinuxAppImageDesc": "透過下方的桌面整合安全註冊或移除此 AppImage。刪除桌面項目前,Motrix 會先還原經過驗證的原預設程式。",
+ "defaultAssociationsLinuxSandboxDesc": "目前的套件會將 Motrix 註冊為候選處理程式,但預設應用程式由桌面環境決定。移除套件後,之前的預設程式可能不會自動還原。",
+ "associationStatusLabelLinux": "目前的 Linux 檔案與連結關聯狀態",
+ "linuxPackageDetected": "套件:{{package}}",
+ "linuxPackage": {
+ "appimage": "AppImage",
+ "native": "deb / rpm",
+ "flatpak": "Flatpak",
+ "snap": "Snap",
+ "unknown": "未知套件"
+ },
+ "protocolMagnetAppImageDesc": "啟用桌面整合後,儲存設定會立即同步 Magnet 連結關聯。",
+ "protocolMagnetSandboxDesc": "儲存時 Motrix 會要求變更,但沙箱或桌面環境可能仍要求您手動選擇預設應用程式。",
+ "protocolMagnetApplyFailed": "設定已儲存,但無法變更桌面關聯。請在系統設定中選擇預設應用程式。",
+ "setTorrentDefaultLinux": "設為 .torrent 預設",
+ "repairLinuxAssociations": "修復關聯",
+ "viewLinuxInstructions": "檢視設定方式",
+ "linuxActionSet": "Motrix 已成為 .torrent 檔案的預設應用程式。",
+ "linuxActionFallback": "目前的套件無法自動設定,已改為開啟設定說明。",
+ "linuxActionFailed": "無法更新 Linux 預設應用程式,請檢查桌面環境設定。"
},
"browser": {
"title": "瀏覽器擴充功能",
@@ -1575,6 +1611,7 @@
"notIntegrated": "尚未與目前桌面整合。",
"failedTitle": "桌面整合未完成",
"failedDetail": "Motrix 未能把自己註冊為連結處理程式。在您重新啟用桌面整合之前,瀏覽器喚起可能無法運作。",
+ "removeBlockedDetail": "Motrix 無法安全還原經過驗證的原處理程式,因此保留了桌面項目,避免留下失效的預設關聯。請先在桌面環境中選擇其他預設應用程式,再重試移除整合。",
"externalManaged": "桌面整合由另一個 Motrix 安裝提供。"
},
"movedHint": "如果在 Motrix 未執行時移動 AppImage,連結可能無法喚起,直到您從新位置手動啟動一次 Motrix。"
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index 79e327f9..a69b8523 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -74,6 +74,8 @@ export const Queries = {
// Linux AppImage desktop integration; returns `AppImageIntegrationView`
// ({ supported: false } outside a packaged Linux AppImage).
GetAppImageIntegrationStatus: 'query:getAppImageIntegrationStatus',
+ GetLinuxDefaultAssociations: 'query:getLinuxDefaultAssociations',
+ GetWindowsDefaultAssociations: 'query:getWindowsDefaultAssociations',
GetApplicationMenu: 'query:getApplicationMenu',
} as const
diff --git a/src/shared/types/linux-default-apps.ts b/src/shared/types/linux-default-apps.ts
new file mode 100644
index 00000000..3c7abab9
--- /dev/null
+++ b/src/shared/types/linux-default-apps.ts
@@ -0,0 +1,15 @@
+export type LinuxPackageKind =
+ | 'appimage'
+ | 'native'
+ | 'flatpak'
+ | 'snap'
+ | 'unknown'
+
+export interface LinuxDefaultAssociations {
+ supported: boolean
+ packageKind: LinuxPackageKind | null
+ registered: boolean
+ canSetTorrentDefault: boolean
+ torrent: boolean | null
+ magnet: boolean | null
+}
diff --git a/src/shared/types/windows-default-apps.ts b/src/shared/types/windows-default-apps.ts
new file mode 100644
index 00000000..b83fca94
--- /dev/null
+++ b/src/shared/types/windows-default-apps.ts
@@ -0,0 +1,7 @@
+export interface WindowsDefaultAssociations {
+ supported: boolean
+ registered: boolean | null
+ scope: 'user' | 'machine' | null
+ torrent: boolean | null
+ magnet: boolean | null
+}
diff --git a/tests/scripts/windows-default-apps-registration.test.ts b/tests/scripts/windows-default-apps-registration.test.ts
new file mode 100644
index 00000000..ec0e9cab
--- /dev/null
+++ b/tests/scripts/windows-default-apps-registration.test.ts
@@ -0,0 +1,176 @@
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { describe, expect, it } from 'vitest'
+import {
+ WINDOWS_DEFAULT_APPS_SETTINGS_URL,
+ WINDOWS_REGISTERED_APP_NAME,
+} from '../../src/main/platform/windows-default-apps'
+
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../..'
+)
+
+const TORRENT_ASSOCIATION = {
+ ext: 'torrent',
+ mimeType: 'application/x-bittorrent',
+ name: 'Torrent',
+ role: 'Viewer',
+}
+
+interface BuilderConfig {
+ fileAssociations?: unknown
+ linux?: { fileAssociations?: unknown }
+ mac?: { fileAssociations?: unknown }
+ nsis?: {
+ allowToChangeInstallationDirectory?: boolean
+ include?: string
+ perMachine?: boolean
+ }
+ win?: { fileAssociations?: unknown }
+}
+
+async function readJson(relativePath: string): Promise<BuilderConfig> {
+ return JSON.parse(
+ await readFile(path.join(REPOSITORY_ROOT, relativePath), 'utf8')
+ ) as BuilderConfig
+}
+
+async function readText(relativePath: string): Promise<string> {
+ return readFile(path.join(REPOSITORY_ROOT, relativePath), 'utf8')
+}
+
+function nsisDefine(source: string, name: string): string | undefined {
+ return new RegExp(`^!define ${name} "([^"]+)"$`, 'm').exec(source)?.[1]
+}
+
+function nsisMacro(source: string, name: string): string {
+ const body = new RegExp(`!macro ${name}\\n([\\s\\S]*?)!macroend`).exec(
+ source
+ )?.[1]
+ if (!body) throw new Error(`missing NSIS macro: ${name}`)
+ return body
+}
+
+describe('Windows Default Apps registration', () => {
+ it('keeps Windows associations installer-owned and other platforms unchanged', async () => {
+ const config = await readJson('electron-builder.json')
+ const signingConfig = await readJson('electron-builder.signing.json')
+
+ expect(config.fileAssociations).toBeUndefined()
+ expect(config.win?.fileAssociations).toBeUndefined()
+ expect(config.mac?.fileAssociations).toEqual([TORRENT_ASSOCIATION])
+ expect(config.linux?.fileAssociations).toEqual([TORRENT_ASSOCIATION])
+ expect(config.nsis).toMatchObject({
+ allowToChangeInstallationDirectory: true,
+ include: 'build/installer.nsh',
+ perMachine: false,
+ })
+
+ expect(signingConfig.fileAssociations).toBeUndefined()
+ expect(signingConfig.win?.fileAssociations).toBeUndefined()
+ expect(signingConfig.mac?.fileAssociations).toEqual([TORRENT_ASSOCIATION])
+ expect(signingConfig.nsis).toMatchObject({
+ allowToChangeInstallationDirectory: true,
+ include: 'trusted/installer.nsh',
+ perMachine: false,
+ })
+ })
+
+ it('advertises app-specific torrent and magnet ProgIDs without changing UserChoice', async () => {
+ const installer = await readText('build/installer.nsh')
+ const register = nsisMacro(installer, 'registerMotrixDefaultApps')
+
+ expect(nsisDefine(installer, 'MOTRIX_REGISTERED_APP_NAME')).toBe(
+ WINDOWS_REGISTERED_APP_NAME
+ )
+ expect(nsisDefine(installer, 'MOTRIX_CAPABILITIES_KEY')).toBe(
+ 'Software\\Motrix\\Capabilities'
+ )
+ expect(nsisDefine(installer, 'MOTRIX_TORRENT_PROGID')).toBe(
+ 'Motrix.File.Torrent'
+ )
+ expect(nsisDefine(installer, 'MOTRIX_MAGNET_PROGID')).toBe(
+ 'Motrix.Url.Magnet'
+ )
+ expect(nsisDefine(installer, 'MOTRIX_PROTOCOL')).toBe('motrix')
+
+ expect(register).toContain(
+ 'WriteRegStr SHELL_CONTEXT "Software\\RegisteredApplications"'
+ )
+ expect(register).toContain(
+ `"\${MOTRIX_CAPABILITIES_KEY}" "ApplicationDescription" "\${APP_DESCRIPTION}"`
+ )
+ expect(register).toContain(
+ `"\${MOTRIX_CAPABILITIES_KEY}" "ApplicationName" "\${MOTRIX_REGISTERED_APP_NAME}"`
+ )
+ expect(register).toContain(
+ `"\${MOTRIX_CAPABILITIES_KEY}\\FileAssociations" ".torrent" "\${MOTRIX_TORRENT_PROGID}"`
+ )
+ expect(register).toContain(
+ `"\${MOTRIX_CAPABILITIES_KEY}\\UrlAssociations" "magnet" "\${MOTRIX_MAGNET_PROGID}"`
+ )
+ expect(register).toContain(
+ `"Software\\Classes\\\${MOTRIX_TORRENT_PROGID}\\shell\\open\\command"`
+ )
+ expect(register).toContain(
+ `"Software\\Classes\\\${MOTRIX_MAGNET_PROGID}\\shell\\open\\command"`
+ )
+ expect(register).toContain(
+ `"Software\\Classes\\\${MOTRIX_PROTOCOL}\\shell\\open\\command"`
+ )
+ expect(register.match(/'"\$appExe" "%1"'/gu)).toHaveLength(3)
+ expect(register).toContain(
+ `"Software\\Classes\\.torrent\\OpenWithProgids" "\${MOTRIX_TORRENT_PROGID}"`
+ )
+ expect(register).toContain('shell32::SHChangeNotify')
+ expect(installer).not.toContain('UserChoice')
+ })
+
+ it('cleans the old scope on updates and only Motrix-owned keys', async () => {
+ const installer = await readText('build/installer.nsh')
+ const install = nsisMacro(installer, 'customInstall')
+ const uninstall = nsisMacro(installer, 'customUnInstall')
+ const remove = nsisMacro(installer, 'deleteMotrixDefaultApps')
+ const legacyCleanup = nsisMacro(
+ installer,
+ 'deleteLegacyMotrixProtocolHandlers'
+ )
+
+ expect(install).toContain('!insertmacro deleteLegacyMotrixProtocolHandlers')
+ expect(install).toContain('!insertmacro registerMotrixDefaultApps')
+ expect(
+ uninstall.indexOf('!insertmacro deleteMotrixDefaultApps')
+ ).toBeLessThan(uninstall.search(/\$\{ifNot\} \$\{isUpdated\}/u))
+ expect(legacyCleanup).toContain(
+ String.raw`DeleteRegKey HKCU "Software\Classes\${MOTRIX_PROTOCOL}"`
+ )
+ expect(legacyCleanup).toContain(
+ 'ReadRegStr $0 HKCU "Software\\Classes\\magnet\\shell\\open\\command"'
+ )
+ expect(legacyCleanup).toContain(String.raw`'\${APP_EXECUTABLE_FILENAME}"'`)
+ expect(remove).toContain(
+ 'DeleteRegValue SHELL_CONTEXT "Software\\RegisteredApplications"'
+ )
+ expect(remove).toContain(
+ `DeleteRegKey SHELL_CONTEXT "Software\\Classes\\\${MOTRIX_TORRENT_PROGID}"`
+ )
+ expect(remove).toContain(
+ `DeleteRegKey SHELL_CONTEXT "Software\\Classes\\\${MOTRIX_MAGNET_PROGID}"`
+ )
+ expect(remove).toContain(
+ `DeleteRegKey SHELL_CONTEXT "Software\\Classes\\\${MOTRIX_PROTOCOL}"`
+ )
+ expect(remove).not.toContain(
+ 'DeleteRegKey SHELL_CONTEXT "Software\\Classes\\.torrent"'
+ )
+ expect(remove).not.toContain(
+ 'DeleteRegKey SHELL_CONTEXT "Software\\Classes\\magnet"'
+ )
+ })
+
+ it('keeps a generic settings fallback for Windows 10 and portable ZIPs', () => {
+ expect(WINDOWS_DEFAULT_APPS_SETTINGS_URL).toBe('ms-settings:defaultapps')
+ })
+})