Skip to content

A full-featured download manager.

feat(windows): add portable profiles beside the executable (#2445)

Dr_rOotab3f4b3f1408
diff --git a/docs/portable-mode.md b/docs/portable-mode.md
new file mode 100644
index 00000000..73a6f496
--- /dev/null
+++ b/docs/portable-mode.md
@@ -0,0 +1,86 @@
+# Windows portable mode
+
+Download and extract the Windows ZIP, then create a `data` directory beside
+`Motrix.exe` before launching it:
+
+```text
+Motrix/
+ Motrix.exe
+ resources/
+ data/
+ portable.json
+ relocations/
+ user-data/
+ work/
+ tmp/
+ Downloads/
+```
+
+Motrix creates the contents of `data` on startup. `Downloads` is the default
+download destination; it is created when needed. The About dialog identifies
+portable mode. Settings provides an action to open the active settings file.
+
+The Windows installer and Microsoft Store packages retain their existing
+behavior. A directory containing `Uninstall Motrix.exe` is treated as an
+installed copy, even when a `data` directory exists. Other platforms and
+development builds do not automatically enable this mode.
+
+## Data and system integration
+
+`data/user-data` contains settings, task history, engine state, installed
+plugins, plugin credentials, Chromium session storage, logs, and crash dumps.
+Task working files, including magnet metadata, live under `data/work`.
+Electron, Node, and child-process temporary files use `data/tmp`.
+
+Portable mode does not register or remove startup entries, file associations,
+or browser Native Messaging hosts. Automatic CLI installation is unavailable.
+The local bridge can still run, but browser launching/discovery through a
+system-registered native host is not installed for the portable copy.
+Existing installed-copy integrations are left untouched.
+
+The portable profile is independent of an installed profile. Motrix does not
+automatically import the host computer's settings or legacy data. Combining
+portable mode with `MOTRIX_USER_DATA` or `MOTRIX_BRIDGE_DATA_DIR` is rejected.
+An unreadable or unwritable `data` directory stops startup instead of falling
+back to AppData.
+
+## Moving the application
+
+Fully exit Motrix before copying the application folder or disconnecting a
+drive. Copy the whole folder, including `data`, `Downloads`, and any other
+download directories stored within it. Preserve `data/portable.json`: it is
+the journal used to recognize the previous location and recover an
+interrupted relocation. Original settings and path records are retained in
+`data/relocations` before a move is applied. A retry uses those originals;
+manual edits made during an interrupted move stop recovery instead of being
+overwritten.
+
+On startup, paths inside the previous application folder are rebased to the
+current folder. Settings, task paths, file lists, and nested recovery records
+are updated before the engine starts. URLs and paths outside the application
+folder are not rewritten. Custom plugin settings, advanced engine configuration, and command scripts remain user-managed. Engine snapshots from an earlier location are not
+replayed; task reconstruction uses the relocated Motrix records and the
+existing recovery checks. Downloads still require their actual partial files,
+checkpoints, and torrent metadata.
+
+After relocation, unfinished tasks targeting external directories stop with
+a location error. They are not silently redirected to another drive. Check
+their original files and destination before retrying or recreating the task.
+Interrupted transition records are preserved, with automatic finalization and
+magnet cleanup held until explicit recovery.
+Interrupted plugin finalization journals are retained in quarantine for
+explicit recovery, since filesystem identity may have changed. Moving a
+profile does not add restart/resume support to media pipelines that already
+require the task to be added again after interruption.
+
+Do not delete the entire Chromium session directory as a cache: it also
+contains persistent browser storage. Plugin credentials travel with the
+profile; protect the portable folder as you would your installed profile.
+
+## Updating
+
+Portable mode can check for updates, but it never downloads or runs the
+Windows installer. Download the new Windows ZIP, fully exit Motrix, and copy
+the complete `data` folder and portable download directories into the new
+extracted folder. Keep a backup until the new version starts successfully.
+Replacing program files must not replace or discard `data`.
diff --git a/docs/portable-mode.zh-CN.md b/docs/portable-mode.zh-CN.md
new file mode 100644
index 00000000..64b91f5f
--- /dev/null
+++ b/docs/portable-mode.zh-CN.md
@@ -0,0 +1,66 @@
+# Windows 便携模式
+
+下载并解压 Windows ZIP,在启动前于 `Motrix.exe` 同级创建 `data` 文件夹:
+
+```text
+Motrix/
+ Motrix.exe
+ resources/
+ data/
+ portable.json
+ relocations/
+ user-data/
+ work/
+ tmp/
+ Downloads/
+```
+
+Motrix 启动时会创建 `data` 内的内容。`Downloads` 是默认下载目录,在需要时创建。
+关于窗口会标明便携模式,设置中可以打开当前使用的设置文件。
+
+Windows 安装版和 Microsoft Store 包保持现有行为。包含 `Uninstall Motrix.exe`
+的目录视为安装版,即使存在 `data` 文件夹也不会切换。其他平台和开发版本不会自动
+启用此模式。
+
+## 数据与系统集成
+
+`data/user-data` 保存设置、任务历史、引擎状态、已安装插件、插件凭据、Chromium
+会话数据、日志和崩溃文件。任务工作文件(包括磁力元数据)位于 `data/work`。
+Electron、Node 和子进程的临时文件使用 `data/tmp`。
+
+便携模式不会注册或删除开机启动项、文件关联和浏览器 Native Messaging host,
+也不支持自动安装 CLI。本地桥接仍可运行,但不会为便携副本安装依赖系统注册的
+浏览器启动与发现组件。已有安装版的系统集成保持不变。
+
+便携资料与安装版资料相互独立,不会自动导入当前电脑的设置或旧版数据。便携模式
+不能同时设置 `MOTRIX_USER_DATA` 或 `MOTRIX_BRIDGE_DATA_DIR`。`data` 无法读取
+或写入时会停止启动,不会回退到 AppData。
+
+## 移动应用
+
+复制应用文件夹或拔出移动硬盘前,请完全退出 Motrix。复制整个文件夹,包括
+`data`、`Downloads` 和其中其他下载目录。请保留 `data/portable.json`,它记录
+应用先前的位置,并用于恢复中断的位置迁移。迁移前的设置和路径记录保存在
+`data/relocations`,重试会从这些原始记录恢复。若在迁移中断期间手动修改了资料,
+恢复会停止,而不会覆盖这些修改。
+
+启动时,原应用目录内的路径会调整到当前目录。设置、任务路径、文件列表及嵌套的
+恢复记录会在引擎启动前完成更新。URL 和应用目录以外的路径保持原样,自定义插件配置、
+高级引擎配置和命令脚本仍需自行管理。旧位置的
+引擎快照不会直接重放;应用会使用重定位后的 Motrix 记录,结合既有恢复检查重建
+任务。续传仍需要实际的未完成文件、检查点和种子元数据。
+
+移动应用后,目标位于外部目录的未完成任务会停止并显示位置错误,不会被静默重定向
+到其他磁盘。请先确认原文件和保存位置,再重试或重新创建任务。中断的文件整理阶段
+会保留,并暂停自动整理及磁力元数据清理,等待显式恢复。文件系统身份可能
+已经变化,因此未完成的插件文件整理日志会被保留并隔离,等待显式恢复。原本中断后
+需要重新添加的媒体任务,不会因启用便携模式而获得额外的续传能力。
+
+请勿将整个 Chromium 会话目录作为缓存删除,其中也包含持久化的浏览器存储。
+插件凭据会随资料一同移动,请像保护安装版资料一样保护便携文件夹。
+
+## 更新
+
+便携模式可以检查更新,但不会下载安装版或运行安装程序。请下载新版 Windows ZIP,
+完全退出 Motrix,将完整的 `data` 文件夹和便携下载目录复制到新解压的应用目录中。
+确认新版正常启动前请保留备份,替换程序文件时不要覆盖或丢弃 `data`。
diff --git a/e2e/portable-mode.spec.ts b/e2e/portable-mode.spec.ts
new file mode 100644
index 00000000..23ffc88a
--- /dev/null
+++ b/e2e/portable-mode.spec.ts
@@ -0,0 +1,130 @@
+import { writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import type { Page } from '@playwright/test'
+import { Queries } from '@shared/protocol/queries'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForQueryHandlers,
+} from './fixtures/electron-app'
+
+async function openCard(page: Page, name: string): Promise<void> {
+ await page.getByRole('link', { name: 'Settings', exact: true }).click()
+ await page.getByText(name, { exact: true }).first().click()
+}
+
+test.beforeEach(async ({ userDataDir }) => {
+ // These tests exercise settings presentation, without registering a host
+ // browser launcher or importing clipboard content on the test machine.
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: {
+ language: 'en-US',
+ browserBridgeEnabled: false,
+ autofillClipboardLinks: false,
+ },
+ tracker: { autoSync: false },
+ onboarding: { disclaimerAccepted: true },
+ })
+ )
+})
+
+test('ordinary desktop runtime retains its existing settings controls', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ const app = await launchMotrix({
+ userDataDir,
+ rpcPort,
+ extraEnv: { MOTRIX_DEV_DISABLE_NATIVE_MESSAGING: '1' },
+ })
+ try {
+ const page = await app.firstWindow()
+ await waitForQueryHandlers(page)
+ expect(
+ await page.evaluate(
+ (channel) => window.motrix.invoke(channel),
+ Queries.GetPortableMode
+ )
+ ).toEqual({ enabled: false })
+ await openCard(page, 'General')
+ if (process.platform !== 'linux')
+ await expect(
+ page.getByRole('switch', { name: 'Open at login', exact: true })
+ ).toBeEnabled()
+ } finally {
+ await app.close()
+ }
+})
+
+test('portable capability presentation disables system integration and offers manual updates', async ({
+ userDataDir,
+ rpcPort,
+}, testInfo) => {
+ const app = await launchMotrix({
+ userDataDir,
+ rpcPort,
+ extraEnv: { MOTRIX_DEV_DISABLE_NATIVE_MESSAGING: '1' },
+ })
+ try {
+ const page = await app.firstWindow()
+ await waitForQueryHandlers(page)
+ // Portable selection and main-process enforcement are covered by platform
+ // tests. Inject the capability snapshot to exercise its real renderer UI
+ // on every desktop CI host without pretending to run a Windows package.
+ await app.evaluate(
+ ({ ipcMain }, channels) => {
+ ipcMain.removeHandler(channels.mode)
+ ipcMain.handle(channels.mode, () => ({
+ enabled: true,
+ dataDirectory: 'E:\\Motrix\\data',
+ }))
+ ipcMain.removeHandler(channels.update)
+ ipcMain.handle(channels.update, () => ({
+ phase: 'available',
+ currentVersion: '2.0.1',
+ availableVersion: '2.0.2',
+ manualInstallReason: 'portable',
+ }))
+ },
+ { mode: Queries.GetPortableMode, update: Queries.GetUpdateState }
+ )
+ await openCard(page, 'General')
+ if (process.platform !== 'linux')
+ await expect(
+ page.getByText(/Portable mode keeps system settings unchanged/)
+ ).toBeVisible()
+ if (process.platform !== 'linux')
+ await expect(
+ page.getByRole('switch', { name: 'Open at login', exact: true })
+ ).toBeDisabled()
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await openCard(page, 'Advanced')
+ await expect(
+ page.getByRole('textbox', { name: 'Recovery data file', exact: true })
+ ).toBeDisabled()
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await openCard(page, 'About')
+ await expect(page.getByText('Portable mode', { exact: true })).toBeVisible()
+ await expect(
+ page.getByText(/Portable mode never runs the installer/)
+ ).toBeVisible()
+ await expect(
+ page.getByRole('link', { name: 'Download manually' })
+ ).toBeVisible()
+ await expect(
+ page.getByRole('button', { name: /restart and install/i })
+ ).toHaveCount(0)
+ await expect(page.getByRole('dialog')).toHaveCSS('opacity', '1')
+ await page.screenshot({
+ path: testInfo.outputPath('portable-about.png'),
+ animations: 'disabled',
+ })
+ } finally {
+ await app.close()
+ }
+})
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.ts
index 1ace1127..e6912b6b 100644
--- a/src/core/engine/aria2/aria2-config-builder.test.ts
+++ b/src/core/engine/aria2/aria2-config-builder.test.ts
@@ -1090,3 +1090,31 @@ describe('Aria2ConfigBuilder', () => {
})
})
})
+
+it('keeps portable engine snapshots in the shell-selected location', () => {
+ const builder = new Aria2ConfigBuilder(
+ '/resources/aria2.conf',
+ '/portable/data/user-data',
+ { persistenceDirectory: '/portable/data/user-data/engine/current-location' }
+ )
+ const settings = makeEngineSettings({
+ sqlite3DbPath: 'E:\\old-location\\aria2.db',
+ })
+ const args = builder.buildArgs(
+ settings,
+ true,
+ null,
+ { download: 0, upload: 0 },
+ '/portable/Downloads'
+ )
+ expect(builder.resolveSqliteDbPath(settings)).toBe(
+ '/portable/data/user-data/engine/current-location/aria2.db'
+ )
+ expect(args).toContain(
+ '--sqlite3-db-path=/portable/data/user-data/engine/current-location/aria2.db'
+ )
+ expect(args).toContain(
+ '--save-session=/portable/data/user-data/engine/current-location/aria2.session'
+ )
+ expect(args).not.toContain('--sqlite3-db-path=E:\\old-location\\aria2.db')
+})
diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.ts
index 812d6c04..559b384a 100644
--- a/src/core/engine/aria2/aria2-config-builder.ts
+++ b/src/core/engine/aria2/aria2-config-builder.ts
@@ -12,6 +12,8 @@ import writeFileAtomic from 'write-file-atomic'
import { dnsModeToAsyncDns } from './dns-fallback'
export interface Aria2ConfigBuilderOptions {
+ /** Shell-owned persistence location, isolated when a portable profile moves. */
+ persistenceDirectory?: string
rpcListenAll?: boolean
/** Server HTTP and engine RPC must use the same torrent upload budget. */
rpcMaxRequestSizeBytes?: number
@@ -31,6 +33,7 @@ export class Aria2ConfigBuilder {
private readonly rpcListenAll: boolean
private readonly rpcMaxRequestSizeBytes?: number
private readonly supervisorPid?: number
+ private readonly persistenceDirectory?: string
private configuredInputFile = false
private runtimeConfPath: string
@@ -41,8 +44,15 @@ export class Aria2ConfigBuilder {
) {
this.userConfPath = path.join(userConfigDir, 'aria2.conf')
this.runtimeConfPath = this.userConfPath
- this.defaultDbPath = path.join(userConfigDir, 'aria2.db')
- this.saveSessionPath = path.join(userConfigDir, 'aria2.session')
+ this.persistenceDirectory = options.persistenceDirectory
+ this.defaultDbPath = path.join(
+ options.persistenceDirectory ?? userConfigDir,
+ 'aria2.db'
+ )
+ this.saveSessionPath = path.join(
+ options.persistenceDirectory ?? userConfigDir,
+ 'aria2.session'
+ )
this.dhtFilePath = path.join(userConfigDir, 'dht.dat')
this.dht6FilePath = path.join(userConfigDir, 'dht6.dat')
this.rpcListenAll = options.rpcListenAll ?? false
@@ -104,7 +114,9 @@ export class Aria2ConfigBuilder {
}
resolveSqliteDbPath(settings: Pick<EngineSettings, 'sqlite3DbPath'>): string {
- return settings.sqlite3DbPath?.trim() || this.defaultDbPath
+ return this.persistenceDirectory
+ ? this.defaultDbPath
+ : settings.sqlite3DbPath?.trim() || this.defaultDbPath
}
/**
@@ -229,7 +241,7 @@ export class Aria2ConfigBuilder {
args.push('--input-file=')
}
if (hasSqlitePersistence) {
- const dbPath = settings.sqlite3DbPath?.trim() || this.defaultDbPath
+ const dbPath = this.resolveSqliteDbPath(settings)
args.push(
`--enable-sqlite3-persistence=${settings.sqlite3Persistence}`,
`--sqlite3-db-path=${dbPath}`,
diff --git a/src/core/session/portable-relocation.test.ts b/src/core/session/portable-relocation.test.ts
new file mode 100644
index 00000000..7c8c78e6
--- /dev/null
+++ b/src/core/session/portable-relocation.test.ts
@@ -0,0 +1,160 @@
+import Database from 'better-sqlite3'
+import { describe, expect, it } from 'vitest'
+import {
+ capturePortableDatabase,
+ relocatePortableDatabase,
+ relocatePortablePath,
+ relocatePortableValue,
+} from './portable-relocation'
+
+describe('portable path relocation', () => {
+ it.each([
+ [
+ 'E:\\Motrix\\Downloads\\片段.bin',
+ 'F:\\Apps\\Motrix\\Downloads\\片段.bin',
+ ],
+ ['e:/motrix/data/work/meta', 'F:\\Apps\\Motrix\\data\\work\\meta'],
+ ['E:\\Motrix-old\\x', 'E:\\Motrix-old\\x'],
+ ['E:\\Motrix\\..\\other\\x', 'E:\\Motrix\\..\\other\\x'],
+ ['D:\\Downloads\\x', 'D:\\Downloads\\x'],
+ ['https://host/E:/Motrix/x', 'https://host/E:/Motrix/x'],
+ ['Movies/part.mkv', 'Movies/part.mkv'],
+ ])('relocates only contained absolute paths: %s', (input, expected) => {
+ expect(
+ relocatePortablePath(input, ['E:\\Motrix'], 'F:\\Apps\\Motrix')
+ ).toBe(expected)
+ })
+ it('handles UNC roots and repeated recovery without applying the move twice', () => {
+ const value = {
+ paths: ['\\\\server\\share\\Motrix\\Downloads\\a'],
+ secret: 'box:abc:def',
+ }
+ const moved = relocatePortableValue(
+ value,
+ ['\\\\server\\share\\Motrix'],
+ 'E:\\Motrix'
+ )
+ expect(moved).toEqual({
+ paths: ['E:\\Motrix\\Downloads\\a'],
+ secret: 'box:abc:def',
+ })
+ expect(
+ relocatePortableValue(moved, ['\\\\server\\share\\Motrix'], 'E:\\Motrix')
+ ).toEqual(moved)
+ })
+ it('relocates HTTP/BT records, nested recovery payloads and composite file keys atomically', () => {
+ const db = new Database(':memory:')
+ db.exec(`CREATE TABLE tasks (motrix_id TEXT PRIMARY KEY, save_dir TEXT, final_path TEXT, torrent_meta_path TEXT);
+ CREATE TABLE task_instances (instance_id TEXT PRIMARY KEY, disk_path TEXT, payload TEXT);
+ CREATE TABLE task_files (motrix_id TEXT, file_index INTEGER, path TEXT, PRIMARY KEY(motrix_id, file_index)) WITHOUT ROWID;`)
+ db.prepare('INSERT INTO tasks VALUES (?, ?, ?, ?)').run(
+ 'task',
+ 'E:\\Motrix\\Downloads',
+ 'E:\\Motrix\\Downloads\\a',
+ 'E:\\Motrix\\data\\user-data\\torrents\\a.torrent'
+ )
+ const payload = {
+ btStorageLayout: {
+ workspacePath: 'E:\\Motrix\\Downloads\\.motrix\\task',
+ },
+ metadataDir: 'E:\\Motrix\\data\\work\\metadata',
+ headers: {
+ Authorization: 'E:\\Motrix\\opaque-credential',
+ path: 'E:\\Motrix\\opaque-header',
+ },
+ config: { path: 'E:\\Motrix\\opaque-plugin-config' },
+ }
+ db.prepare('INSERT INTO task_instances VALUES (?, ?, ?)').run(
+ 'instance',
+ 'E:\\Motrix\\Downloads\\a.aria2',
+ JSON.stringify(payload)
+ )
+ db.prepare('INSERT INTO task_files VALUES (?, ?, ?)').run(
+ 'task',
+ 1,
+ 'E:\\Motrix\\Downloads\\a'
+ )
+ const snapshot = capturePortableDatabase(db)
+ db.exec(
+ "CREATE TRIGGER fail_relocation BEFORE UPDATE ON task_files BEGIN SELECT RAISE(ABORT, 'blocked'); END"
+ )
+ expect(() =>
+ relocatePortableDatabase(db, snapshot, 'E:\\Motrix', 'F:\\Motrix')
+ ).toThrow('blocked')
+ expect(db.prepare('SELECT final_path FROM tasks').get()).toEqual({
+ final_path: 'E:\\Motrix\\Downloads\\a',
+ })
+ db.exec('DROP TRIGGER fail_relocation')
+ relocatePortableDatabase(db, snapshot, 'E:\\Motrix', 'F:\\Motrix')
+ expect(db.prepare('SELECT path FROM task_files').get()).toEqual({
+ path: 'F:\\Motrix\\Downloads\\a',
+ })
+ const row = db.prepare('SELECT payload FROM task_instances').get() as {
+ payload: string
+ }
+ expect(JSON.parse(row.payload)).toEqual({
+ ...payload,
+ btStorageLayout: {
+ workspacePath: 'F:\\Motrix\\Downloads\\.motrix\\task',
+ },
+ metadataDir: 'F:\\Motrix\\data\\work\\metadata',
+ })
+ db.close()
+ })
+})
+
+it.each([
+ ['E:\\Motrix', 'E:\\Motrix\\new'],
+ ['E:\\Motrix\\old', 'E:\\Motrix'],
+])(
+ 'handles moving between nested directories: %s -> %s',
+ (oldRoot, newRoot) => {
+ const expected = `${newRoot}\\Downloads\\a`
+ expect(
+ relocatePortablePath(`${oldRoot}\\Downloads\\a`, [oldRoot], newRoot)
+ ).toBe(expected)
+ // Retry idempotence belongs to snapshot replay, not path-string heuristics.
+ }
+)
+
+it('replays original values when an ancestor move leaves paths inside the old prefix', () => {
+ const db = new Database(':memory:')
+ db.exec('CREATE TABLE tasks (motrix_id TEXT PRIMARY KEY, final_path TEXT)')
+ db.prepare('INSERT INTO tasks VALUES (?, ?)').run(
+ 'task',
+ 'E:\\Motrix\\old\\old\\file'
+ )
+ const snapshot = capturePortableDatabase(db)
+ relocatePortableDatabase(db, snapshot, 'E:\\Motrix\\old', 'E:\\Motrix')
+ relocatePortableDatabase(db, snapshot, 'E:\\Motrix\\old', 'E:\\Motrix', [
+ 'E:\\Motrix',
+ ])
+ expect(db.prepare('SELECT final_path FROM tasks').get()).toEqual({
+ final_path: 'E:\\Motrix\\old\\file',
+ })
+ relocatePortableDatabase(db, snapshot, 'E:\\Motrix\\old', 'G:\\Motrix', [
+ 'E:\\Motrix',
+ ])
+ expect(db.prepare('SELECT final_path FROM tasks').get()).toEqual({
+ final_path: 'G:\\Motrix\\old\\file',
+ })
+ db.close()
+})
+
+it('refuses to overwrite a task path edited after the relocation snapshot', () => {
+ const db = new Database(':memory:')
+ db.exec('CREATE TABLE tasks (motrix_id TEXT PRIMARY KEY, final_path TEXT)')
+ db.prepare('INSERT INTO tasks VALUES (?, ?)').run(
+ 'task',
+ 'E:\\Motrix\\Downloads\\a'
+ )
+ const snapshot = capturePortableDatabase(db)
+ db.prepare('UPDATE tasks SET final_path = ?').run('D:\\User-selected\\a')
+ expect(() =>
+ relocatePortableDatabase(db, snapshot, 'E:\\Motrix', 'F:\\Motrix')
+ ).toThrow('edited during recovery')
+ expect(db.prepare('SELECT final_path FROM tasks').get()).toEqual({
+ final_path: 'D:\\User-selected\\a',
+ })
+ db.close()
+})
diff --git a/src/core/session/portable-relocation.ts b/src/core/session/portable-relocation.ts
new file mode 100644
index 00000000..a90345d7
--- /dev/null
+++ b/src/core/session/portable-relocation.ts
@@ -0,0 +1,278 @@
+import path from 'node:path'
+import { isDeepStrictEqual } from 'node:util'
+import type Database from 'better-sqlite3'
+import { z } from 'zod'
+
+export function isWithinPortableRoot(value: string, root: string): boolean {
+ if (!path.win32.isAbsolute(value)) return false
+ const relative = path.win32.relative(root, value)
+ return (
+ relative === '' ||
+ (relative !== '..' &&
+ !relative.startsWith('..\\') &&
+ !path.win32.isAbsolute(relative))
+ )
+}
+
+/** Input must be an original path from the immutable relocation snapshot. */
+export function relocatePortablePath(
+ value: string,
+ roots: readonly string[],
+ currentRoot: string
+): string {
+ for (const root of roots) {
+ if (isWithinPortableRoot(value, root))
+ return path.win32.join(currentRoot, path.win32.relative(root, value))
+ }
+ return value
+}
+
+/** Only used for settings fields whose entire value is a path or a path list. */
+export function relocatePortableValue(
+ value: unknown,
+ roots: readonly string[],
+ currentRoot: string
+): unknown {
+ if (typeof value === 'string')
+ return relocatePortablePath(value, roots, currentRoot)
+ if (Array.isArray(value))
+ return value.map((item) => relocatePortableValue(item, roots, currentRoot))
+ if (value !== null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ relocatePortableValue(item, roots, currentRoot),
+ ])
+ )
+ }
+ return value
+}
+
+const PAYLOAD_PATH_KEYS = new Set([
+ 'path',
+ 'paths',
+ 'saveDir',
+ 'diskPath',
+ 'finalPath',
+ 'torrentMetaPath',
+ 'metadataDir',
+ 'mediaMetaPath',
+ 'workspacePath',
+ 'sourcePath',
+ 'targetPath',
+ 'privateTargetPath',
+ 'rollbackPath',
+ 'artifactPath',
+ 'quarantinePath',
+ 'directory',
+ 'rootPath',
+ 'dataPath',
+ 'backupRoot',
+ 'snapshotDir',
+ 'controlBackupPath',
+ 'cleanupArtifactPaths',
+ 'artifactPaths',
+ 'outputRoot',
+ 'outputPath',
+])
+const OPAQUE_KEYS = new Set([
+ 'headers',
+ 'requestHeaders',
+ 'cookies',
+ 'config',
+ 'secrets',
+ 'script',
+ 'requestModifiers',
+ 'resourceValidator',
+ 'sourceMeta',
+ 'source_meta',
+])
+
+/** Keep credentials, request metadata and plugin configuration opaque. */
+function mapPayloadPaths(
+ value: unknown,
+ map: (value: string) => string,
+ pathField = false
+): unknown {
+ if (typeof value === 'string') return pathField ? map(value) : value
+ if (Array.isArray(value))
+ return value.map((item) => mapPayloadPaths(item, map, pathField))
+ if (value !== null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ OPAQUE_KEYS.has(key)
+ ? item
+ : mapPayloadPaths(item, map, PAYLOAD_PATH_KEYS.has(key)),
+ ])
+ )
+ }
+ return value
+}
+
+export function portablePayloadPaths(value: unknown): string[] {
+ const paths: string[] = []
+ mapPayloadPaths(value, (candidate) => {
+ if (path.win32.isAbsolute(candidate)) paths.push(candidate)
+ return candidate
+ })
+ return paths
+}
+
+const PATH_COLUMNS: Record<string, readonly string[]> = {
+ tasks: ['save_dir', 'final_path', 'torrent_meta_path'],
+ task_instances: ['disk_path', 'payload'],
+ task_files: ['path'],
+ plugin_finalize_journals: [
+ 'plan_json',
+ 'source_identity_json',
+ 'target_identity_json',
+ ],
+ plugin_post_deliveries: ['payload_json'],
+}
+const EVIDENCE_COLUMNS: Record<string, readonly string[]> = {
+ tasks: ['agg_status'],
+ task_instances: ['motrix_id', 'status', 'transition_phase'],
+}
+const JSON_COLUMNS = new Set([
+ 'error_detail_params',
+ 'payload',
+ 'plan_json',
+ 'source_identity_json',
+ 'target_identity_json',
+ 'payload_json',
+])
+const sqliteValueSchema = z.union([z.string(), z.number(), z.null()])
+export const portableDatabaseSnapshotSchema = z.record(
+ z.string().refine((name) => Object.hasOwn(PATH_COLUMNS, name)),
+ z.array(z.record(z.string(), sqliteValueSchema))
+)
+export type PortableDatabaseSnapshot = z.infer<
+ typeof portableDatabaseSnapshotSchema
+>
+type SqliteValue = z.infer<typeof sqliteValueSchema>
+const quote = (name: string) => `"${name.replaceAll('"', '""')}"`
+
+function tableColumns(db: Database.Database, table: string) {
+ const schema = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{
+ name: string
+ pk: number
+ }>
+ const keys = schema
+ .filter((column) => column.pk > 0)
+ .sort((a, b) => a.pk - b.pk)
+ .map((column) => column.name)
+ const columns = PATH_COLUMNS[table].filter((name) =>
+ schema.some((column) => column.name === name)
+ )
+ const evidence = (EVIDENCE_COLUMNS[table] ?? []).filter((name) =>
+ schema.some((column) => column.name === name)
+ )
+ return { keys, columns, evidence }
+}
+
+export function capturePortableDatabase(
+ db: Database.Database,
+ tables: readonly string[] = Object.keys(PATH_COLUMNS)
+): PortableDatabaseSnapshot {
+ const snapshot: PortableDatabaseSnapshot = {}
+ for (const table of tables) {
+ if (!Object.hasOwn(PATH_COLUMNS, table))
+ throw new Error('Unknown portable snapshot table')
+ const { keys, columns, evidence } = tableColumns(db, table)
+ if (!keys.length || !columns.length) continue
+ const names = [...new Set([...keys, ...columns, ...evidence])]
+ snapshot[table] = db
+ .prepare(`SELECT ${names.map(quote).join(', ')} FROM ${table}`)
+ .all() as Record<string, SqliteValue>[]
+ }
+ return snapshot
+}
+
+function mapColumn(
+ name: string,
+ value: SqliteValue,
+ sourceRoot: string,
+ targetRoot: string
+): SqliteValue {
+ if (typeof value !== 'string') return value
+ if (JSON_COLUMNS.has(name))
+ return JSON.stringify(
+ mapPayloadPaths(JSON.parse(value), (item) =>
+ relocatePortablePath(item, [sourceRoot], targetRoot)
+ )
+ )
+ return relocatePortablePath(value, [sourceRoot], targetRoot)
+}
+function equivalentColumn(
+ name: string,
+ left: SqliteValue,
+ right: SqliteValue
+): boolean {
+ if (
+ JSON_COLUMNS.has(name) &&
+ typeof left === 'string' &&
+ typeof right === 'string'
+ )
+ return isDeepStrictEqual(JSON.parse(left), JSON.parse(right))
+ return left === right
+}
+
+/** Replay from original values, never from already-rebased rows. All tables commit together. */
+export function relocatePortableDatabase(
+ db: Database.Database,
+ snapshot: PortableDatabaseSnapshot,
+ sourceRoot: string,
+ currentRoot: string,
+ attemptedRoots: readonly string[] = []
+): void {
+ db.transaction(() => {
+ for (const table of Object.keys(PATH_COLUMNS)) {
+ const rows = snapshot[table]
+ if (!rows?.length) continue
+ const { keys, columns } = tableColumns(db, table)
+ if (!keys.length || !columns.length)
+ throw new Error('Portable relocation schema changed')
+ const where = keys.map((name) => `${quote(name)} = ?`).join(' AND ')
+ const read = db.prepare(
+ `SELECT ${columns.map(quote).join(', ')} FROM ${table} WHERE ${where}`
+ )
+ for (const row of rows) {
+ const keyValues = keys.map((name) => row[name])
+ const current = read.get(...keyValues) as
+ | Record<string, SqliteValue>
+ | undefined
+ if (!current) throw new Error('Portable relocation record changed')
+ const changes: Array<[string, SqliteValue]> = []
+ for (const name of columns) {
+ const original = row[name]
+ if (original === undefined)
+ throw new Error('Portable relocation snapshot is incomplete')
+ const mapped = mapColumn(name, original, sourceRoot, currentRoot)
+ const allowed = [
+ original,
+ ...attemptedRoots.map((root) =>
+ mapColumn(name, original, sourceRoot, root)
+ ),
+ ]
+ if (allowed.every((value) => equivalentColumn(name, value, mapped)))
+ continue
+ if (
+ !allowed.some((value) =>
+ equivalentColumn(name, value, current[name])
+ )
+ )
+ throw new Error(
+ 'Portable relocation record was edited during recovery'
+ )
+ if (!equivalentColumn(name, current[name], mapped))
+ changes.push([name, mapped])
+ }
+ if (changes.length)
+ db.prepare(
+ `UPDATE ${table} SET ${changes.map(([name]) => `${quote(name)} = ?`).join(', ')} WHERE ${where}`
+ ).run(...changes.map(([, value]) => value), ...keyValues)
+ }
+ }
+ })()
+}
diff --git a/src/core/task/task-recovery-service.test.ts b/src/core/task/task-recovery-service.test.ts
index 068619be..3a1b14bb 100644
--- a/src/core/task/task-recovery-service.test.ts
+++ b/src/core/task/task-recovery-service.test.ts
@@ -1100,3 +1100,23 @@ describe('targeted finalize recovery', () => {
expect(deps.fs.removePathRecursive).not.toHaveBeenCalled()
})
})
+
+it('preserves held transition evidence and permits only explicit recovery', async () => {
+ const task = makeTask({
+ type: TaskType.Http,
+ status: TaskStatus.Error,
+ errorDetailKey: 'task.recovery.startup.portableExternalPath',
+ })
+ const deps = makeDeps({
+ taskManager: { getAll: () => [task], persist: vi.fn() },
+ canRecoverAutomatically: () => false,
+ hasPendingFinalization: async () => true,
+ })
+ const recovery = new TaskRecoveryServiceImpl(deps)
+ expect((await recovery.recoverOnStartup()).totalScanned).toBe(0)
+ expect(deps.fs.pathExists).not.toHaveBeenCalled()
+ expect(deps.finalizeTask).not.toHaveBeenCalled()
+ expect(task.transitionPhase).toBe(TransitionPhase.Renaming)
+ expect((await recovery.recoverTaskById(task.id)).totalScanned).toBe(1)
+ expect(deps.finalizeTask).toHaveBeenCalledExactlyOnceWith(task.id)
+})
diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.ts
index fdd1374e..e18055c0 100644
--- a/src/core/task/task-recovery-service.ts
+++ b/src/core/task/task-recovery-service.ts
@@ -121,6 +121,8 @@ export const defaultRecoveryFs: RecoveryFs = {
}
export interface RecoveryDeps {
+ /** A shell may hold filesystem work until the user confirms a relocated destination. */
+ canRecoverAutomatically?: (task: DownloadTask) => boolean
taskManager: {
getAll(): DownloadTask[]
set?(id: string, task: DownloadTask): void
@@ -208,6 +210,8 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {
const inFlightPublished = publishedTasks.filter(
(t) =>
!hasLegacyImport(t) &&
+ (taskId !== undefined ||
+ this.deps.canRecoverAutomatically?.(t) !== false) &&
(taskId === undefined || t.id === taskId) &&
(t.transitionPhase !== TransitionPhase.Idle ||
t.status === TaskStatus.Finalizing ||
diff --git a/src/core/torrent/magnet-tracker.test.ts b/src/core/torrent/magnet-tracker.test.ts
index 3e9c1f72..aba783bc 100644
--- a/src/core/torrent/magnet-tracker.test.ts
+++ b/src/core/torrent/magnet-tracker.test.ts
@@ -254,6 +254,7 @@ function createMagnetTracker(
torrentParser: TorrentParser,
activityRecorder = NOOP_TASK_ACTIVITY_RECORDER,
lifecycle?: {
+ canRestoreTask?: () => boolean
parentTaskCreated?: (
task: DownloadTask,
persistParent: () => void | Promise<void>
@@ -2872,99 +2873,110 @@ describe('MagnetTracker', () => {
).toBe(false)
})
- it('primeFromDatabase resumes bounded cleanup for a hidden user-delete tombstone', async () => {
- // A hidden row has no UI entry through which the user can retry cleanup.
- // Restart must therefore restore the adoption shield and schedule cleanup
- // instead of freezing the entry at MAX attempts forever.
- db.saveTaskWithInstances({
- task: {
- motrixId: 'm-quarantined',
- name: '[METADATA] xyz',
- kind: TaskKind.Bt,
- taskType: TaskType.Magnet,
- category: null,
- priority: 0,
- tags: null,
- createdAt: 1700000000,
- updatedAt: 1700000001,
- finalPath: '/Downloads',
- finalName: '',
- torrentMetaPath: null,
- infoHash: null,
- totalBytes: 0,
- downloadedBytes: 0,
- sizeWhenDone: 0,
- fileCount: 0,
- isPrivate: false,
- trackers: [],
- pieceLength: 0,
- aggStatus: TaskStatus.Error,
- finishedAt: 1700000001,
- errorMessage: 'quarantined',
- errorCode: null,
- errorDetailKey: null,
- errorDetailParams: null,
- diagnosisRevision: 0,
- uploadedBytesBaseline: 0,
- source: 'user',
- sourceMeta: null,
- },
- instances: [
- {
- instanceId: 'meta:m-quarantined',
+ it.each([true, false])(
+ 'primeFromDatabase honors the cleanup recovery gate: allowed=%s',
+ async (allowed) => {
+ // A hidden row has no UI entry through which the user can retry cleanup.
+ // Restart must therefore restore the adoption shield and schedule cleanup
+ // instead of freezing the entry at MAX attempts forever.
+ db.saveTaskWithInstances({
+ task: {
motrixId: 'm-quarantined',
- gid: 'g-meta-quarantined',
- phase: TaskInstancePhase.MagnetMetadataResolution,
- status: TaskStatus.Error,
- progress: 0,
- totalBytes: 0,
- downloadedBytes: 0,
- uploadedBytes: 0,
- diskPath: '/tmp/motrix-magnet-metadata-x',
- transitionPhase: TransitionPhase.Idle,
- uris: [
- 'magnet:?xt=urn:btih:6ecc2c259036f3099e06e4885d6e82a1ee8202d6',
- ],
- uriHash: null,
- payload: {
- metadataDir: '/tmp/motrix-magnet-metadata-x',
- cleanupQuarantined: true,
- cleanupTombstoneHidden: true,
- },
+ name: '[METADATA] xyz',
+ kind: TaskKind.Bt,
+ taskType: TaskType.Magnet,
+ category: null,
+ priority: 0,
+ tags: null,
createdAt: 1700000000,
updatedAt: 1700000001,
+ finalPath: '/Downloads',
+ finalName: '',
+ torrentMetaPath: null,
+ infoHash: null,
+ totalBytes: 0,
+ downloadedBytes: 0,
+ sizeWhenDone: 0,
+ fileCount: 0,
+ isPrivate: false,
+ trackers: [],
+ pieceLength: 0,
+ aggStatus: TaskStatus.Error,
+ finishedAt: 1700000001,
+ errorMessage: 'quarantined',
+ errorCode: null,
+ errorDetailKey: null,
+ errorDetailParams: null,
+ diagnosisRevision: 0,
+ uploadedBytesBaseline: 0,
+ source: 'user',
+ sourceMeta: null,
},
- ],
- })
+ instances: [
+ {
+ instanceId: 'meta:m-quarantined',
+ motrixId: 'm-quarantined',
+ gid: 'g-meta-quarantined',
+ phase: TaskInstancePhase.MagnetMetadataResolution,
+ status: TaskStatus.Error,
+ progress: 0,
+ totalBytes: 0,
+ downloadedBytes: 0,
+ uploadedBytes: 0,
+ diskPath: '/tmp/motrix-magnet-metadata-x',
+ transitionPhase: TransitionPhase.Idle,
+ uris: [
+ 'magnet:?xt=urn:btih:6ecc2c259036f3099e06e4885d6e82a1ee8202d6',
+ ],
+ uriHash: null,
+ payload: {
+ metadataDir: '/tmp/motrix-magnet-metadata-x',
+ cleanupQuarantined: true,
+ cleanupTombstoneHidden: true,
+ },
+ createdAt: 1700000000,
+ updatedAt: 1700000001,
+ },
+ ],
+ })
- const tracker = createMagnetTracker(
- rpc as never,
- eventBus as never,
- settings as never,
- db,
- taskManager,
- torrentParser
- )
- tracker.primeFromDatabase()
+ const tracker = createMagnetTracker(
+ rpc as never,
+ eventBus as never,
+ settings as never,
+ db,
+ taskManager,
+ torrentParser,
+ NOOP_TASK_ACTIVITY_RECORDER,
+ { canRestoreTask: () => allowed }
+ )
+ tracker.primeFromDatabase()
+ if (!allowed) {
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(rpc.forceRemove).not.toHaveBeenCalled()
+ tracker.dispose()
+ return
+ }
- expect(
- tracker.observe({
- gid: 'g-meta-quarantined',
- status: 'active',
- } as never)
- ).toBe(true)
+ expect(
+ tracker.observe({
+ gid: 'g-meta-quarantined',
+ status: 'active',
+ } as never)
+ ).toBe(true)
- await vi.advanceTimersByTimeAsync(5_000)
+ await vi.advanceTimersByTimeAsync(5_000)
- expect(rpc.forceRemove).toHaveBeenCalledWith('g-meta-quarantined')
- expect(
- tracker.observe({
- gid: 'g-meta-quarantined',
- status: 'active',
- } as never)
- ).toBe(false)
- expect(db.getTask('m-quarantined')).toBeNull()
- })
+ expect(rpc.forceRemove).toHaveBeenCalledWith('g-meta-quarantined')
+ expect(
+ tracker.observe({
+ gid: 'g-meta-quarantined',
+ status: 'active',
+ } as never)
+ ).toBe(false)
+ expect(db.getTask('m-quarantined')).toBeNull()
+ }
+ )
it.each([false, true])(
'recovers a failed swap after restart with directOutput=%s',
diff --git a/src/core/torrent/magnet-tracker.ts b/src/core/torrent/magnet-tracker.ts
index 68e21bab..4c0087fc 100644
--- a/src/core/torrent/magnet-tracker.ts
+++ b/src/core/torrent/magnet-tracker.ts
@@ -81,6 +81,7 @@ const RETRY_METADATA_TIMEOUT_MULTIPLIER = 2
export type CleanupResult = 'removed' | 'quarantined'
export interface MagnetTrackerLifecycle {
+ canRestoreTask?: (task: TaskRow) => boolean
/**
* Coalesced / immediate TaskUpdated publication (TaskUpdatePublisher).
* Metadata-lifecycle progress rides the trailing window; transitions that
@@ -105,6 +106,8 @@ export interface MagnetTrackerLifecycle {
runExclusivePersistence?: <T>(operation: () => T | Promise<T>) => Promise<T>
wallNow?: () => number
monotonicNow?: () => number
+ /** Existing shell-owned directory for metadata work retained across restarts. */
+ metadataWorkDir?: string
/** Trusted application-owned root for persisted `.torrent` metadata.
* Failed-swap cleanup refuses torrent paths outside this directory. */
torrentMetaDir?: string
@@ -236,6 +239,7 @@ export class MagnetTracker {
if (this.stopped) return
const all = this.db.getAllTasks()
for (const pair of all) {
+ if (this.lifecycle.canRestoreTask?.(pair.task) === false) continue
const metaInst = pair.instances.find(
(i) => i.phase === TaskInstancePhase.MagnetMetadataResolution
)
@@ -487,7 +491,12 @@ export class MagnetTracker {
}
}
- const metadataDir = await mkdtemp(join(tmpdir(), 'motrix-magnet-metadata-'))
+ const metadataDir = await mkdtemp(
+ join(
+ this.lifecycle.metadataWorkDir ?? tmpdir(),
+ 'motrix-magnet-metadata-'
+ )
+ )
if (this.stopped) {
await this.cleanupMetadataDir(metadataDir)
return ''
@@ -774,7 +783,12 @@ export class MagnetTracker {
}
}
- const metadataDir = await mkdtemp(join(tmpdir(), 'motrix-magnet-metadata-'))
+ const metadataDir = await mkdtemp(
+ join(
+ this.lifecycle.metadataWorkDir ?? tmpdir(),
+ 'motrix-magnet-metadata-'
+ )
+ )
let reservedGid: string
try {
reservedGid = this.reserveNewEngineGid()
diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.ts
index 1450e0ea..b365c1ac 100644
--- a/src/main/bridge/index.ts
+++ b/src/main/bridge/index.ts
@@ -67,6 +67,7 @@ import { app, ipcMain } from 'electron'
import { CancellationTokenSource } from 'vscode-jsonrpc'
import { registerTrustedIpcHandler } from '../ipc/trusted-ipc'
import { i18n } from '../lib/i18n'
+import { getPortableProfile } from '../platform/portable-profile'
import { getAppImageNativeHost } from './appimage-native-host-electron'
import { isPackagedLinuxFlatpak } from './flatpak-environment'
import { resolveNativeHostBinaryPath } from './native-host-path'
@@ -329,7 +330,13 @@ function createNativeMessagingInstallation(): NativeMessagingInstallation {
...(installationPlatform === 'win32'
? { windowsRoamingAppData: app.getPath('appData') }
: {}),
- ...(flatpak ? { registrationMode: 'external' as const } : {}),
+ ...(getPortableProfile() ||
+ (!app.isPackaged &&
+ process.env.MOTRIX_DEV_DISABLE_NATIVE_MESSAGING === '1')
+ ? { registrationMode: 'disabled' as const }
+ : flatpak
+ ? { registrationMode: 'external' as const }
+ : {}),
}),
snap,
}
diff --git a/src/main/bridge/native-messaging-installer.test.ts b/src/main/bridge/native-messaging-installer.test.ts
index 3f4a4989..d8480687 100644
--- a/src/main/bridge/native-messaging-installer.test.ts
+++ b/src/main/bridge/native-messaging-installer.test.ts
@@ -654,3 +654,39 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {
await installer.unregister()
})
})
+
+it('leaves installed browser manifests and registry entries untouched in portable mode', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'motrix-portable-nm-'))
+ const registryWriter = vi.fn()
+ const registryDeleter = vi.fn()
+ const installer = new NativeMessagingInstaller({
+ platform: 'win32',
+ registrationMode: 'disabled',
+ hostBinaryPath: 'E:\\Motrix\\resources\\bin\\motrix-native-host.exe',
+ manifestRoot: directory,
+ windowsRoamingAppData: directory,
+ registryWriter,
+ registryDeleter,
+ })
+ const sentinel = join(
+ directory,
+ 'Motrix',
+ 'bridge',
+ 'manifests',
+ 'chrome.json'
+ )
+ await mkdir(dirname(sentinel), { recursive: true })
+ await writeFile(sentinel, 'installed profile')
+ try {
+ await installer.syncManifests({
+ chromium: ['extension-id'],
+ firefox: ['id'],
+ })
+ await installer.unregister()
+ expect(registryWriter).not.toHaveBeenCalled()
+ expect(registryDeleter).not.toHaveBeenCalled()
+ expect(await readFile(sentinel, 'utf8')).toBe('installed profile')
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
+})
diff --git a/src/main/bridge/native-messaging-installer.ts b/src/main/bridge/native-messaging-installer.ts
index 31e8a51e..f01badbb 100644
--- a/src/main/bridge/native-messaging-installer.ts
+++ b/src/main/bridge/native-messaging-installer.ts
@@ -268,9 +268,10 @@ export interface InstallerOptions {
/**
* Whether Motrix owns the host browser manifests. Flatpak uses `external`:
* `/app` is not executable by a host browser, and a separate host-side
- * companion must own both the launcher and manifests.
+ * companion must own both the launcher and manifests. Portable profiles use
+ * `disabled` to leave both existing manifests and registration untouched.
*/
- registrationMode?: 'managed' | 'external'
+ registrationMode?: 'managed' | 'external' | 'disabled'
/**
* Development-only bridge directory selected by Electron. When present,
* sync writes an owner-only sidecar beside the development host executable
@@ -326,7 +327,11 @@ export class NativeMessagingInstaller {
await this.opts.appImage.sync(args)
return { failures: [] }
}
- if (this.opts.registrationMode === 'external') return { failures: [] }
+ if (
+ this.opts.registrationMode === 'external' ||
+ this.opts.registrationMode === 'disabled'
+ )
+ return { failures: [] }
await this.writeDevelopmentHostConfig()
@@ -394,7 +399,11 @@ export class NativeMessagingInstaller {
async unregister(): Promise<void> {
if (this.opts.appImage) return this.opts.appImage.suspend()
- if (this.opts.registrationMode === 'external') return
+ if (
+ this.opts.registrationMode === 'external' ||
+ this.opts.registrationMode === 'disabled'
+ )
+ return
const paths = computeManifestPaths(
this.opts.platform,
diff --git a/src/main/core/app-update-service.test.ts b/src/main/core/app-update-service.test.ts
index af9fcaf2..466c74c0 100644
--- a/src/main/core/app-update-service.test.ts
+++ b/src/main/core/app-update-service.test.ts
@@ -110,3 +110,31 @@ describe('createAppUpdateService', () => {
expect(updater.quitAndInstall).not.toHaveBeenCalled()
})
})
+
+it('checks portable updates but never downloads or installs an NSIS package', async () => {
+ const updater = createFakeUpdater()
+ const service = await createAppUpdateService({
+ eventBus: new EventBus(),
+ currentVersion: '2.0.0',
+ channel: 'stable',
+ isWindowsPackage: false,
+ supported: true,
+ loadUpdater: async () => updater,
+ getManagedMessage: () => '',
+ getInstallBlockReason: () => 'portable',
+ })
+ await service.check()
+ updater.fire('update-available', { version: '2.0.1' })
+ expect(service.getState()).toMatchObject({
+ phase: 'available',
+ manualInstallReason: 'portable',
+ })
+ await service.download()
+ updater.fire('update-downloaded', { version: '2.0.1' })
+ service.install()
+ expect(updater.checkForUpdates).toHaveBeenCalledOnce()
+ expect(updater.autoDownload).toBe(false)
+ expect(updater.autoInstallOnAppQuit).toBe(false)
+ expect(updater.downloadUpdate).not.toHaveBeenCalled()
+ expect(updater.quitAndInstall).not.toHaveBeenCalled()
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 29aebf87..e9b2f056 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -138,11 +138,13 @@ import {
resolveTaskRoute,
} from '@shared/lib/task-navigation'
import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
import {
DEFAULT_BYTE_UNIT_PREFERENCE,
resolveByteUnitSystem,
} from '@shared/schemas/byte-unit-system'
import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'
+import { CliToolReason } from '@shared/types/cli-tool'
import { EngineState } from '@shared/types/engine'
import type { AppNotification } from '@shared/types/notification'
import { getHiddenNotificationKinds } from '@shared/types/notification'
@@ -154,6 +156,7 @@ import {
app,
type BrowserWindow,
dialog,
+ ipcMain,
autoUpdater as nativeAutoUpdater,
powerMonitor,
shell,
@@ -183,6 +186,7 @@ import { registerDisclaimerIpc } from './ipc/disclaimer'
import { setupEventForwarding } from './ipc/events'
import { registerNotificationIpc } from './ipc/notifications'
import { registerQueryHandlers } from './ipc/queries'
+import { registerTrustedIpcHandler } from './ipc/trusted-ipc'
import { setupLauncher } from './launcher'
import {
defaultLegacyRoots,
@@ -210,6 +214,14 @@ import { removePathRecursive, renameAtomic } from './platform/fs-helpers'
import { setupGraphicsRecovery } from './platform/graphics-recovery-runtime'
import { getMacUpdateInstallBlockReason } from './platform/mac-update-install-policy'
import { setupNativeThemeSync } from './platform/native-theme-sync'
+import {
+ getPortableProfile,
+ PortableProfileError,
+} from './platform/portable-profile'
+import {
+ portableEngineStateDirectory,
+ relocatePortableProfile,
+} from './platform/portable-relocation'
import { setupPowerManager } from './platform/power-manager'
import { createProtocolManager } from './platform/protocol-manager'
import { isElectronSelfUpdateSupported } from './platform/self-update-policy'
@@ -272,13 +284,35 @@ if (process.platform === 'linux') {
app.commandLine.appendSwitch('password-store', 'basic')
}
-const platform = createElectronPlatformServices(distributionContext)
+const platform = (() => {
+ try {
+ return createElectronPlatformServices(distributionContext)
+ } catch (error) {
+ if (error instanceof PortableProfileError) {
+ dialog.showErrorBox(
+ i18n.t('settings.portable.title'),
+ i18n.t('settings.portable.startupError')
+ )
+ app.exit(1)
+ }
+ throw error
+ }
+})()
+const portableProfile = getPortableProfile()
const rendererUrlPolicy = initializeRendererUrlPolicy({
isPackaged: app.isPackaged,
appPath: app.getAppPath(),
devServerUrl: app.isPackaged ? null : process.env.VITE_DEV_SERVER_URL,
})
+// Immutable startup capability must be available before onboarding or settings
+// windows mount; late service registration can still be waiting on plugin IO.
+registerTrustedIpcHandler(Queries.GetPortableMode, () => ({
+ enabled: Boolean(portableProfile),
+ dataDirectory: portableProfile?.dataDir,
+}))
+app.once('will-quit', () => ipcMain.removeHandler(Queries.GetPortableMode))
+
// ─── Logger ─────────────────────────────────────────────
const logDir = path.join(platform.userDataDir, 'logs')
@@ -350,20 +384,25 @@ const settingsFlatpakEnvironment =
isPackaged: app.isPackaged,
env: process.env,
})
-const defaultSaveDirOptions = resolveDefaultSaveDirOptions({
- snapEnvironment: settingsSnapEnvironment,
- getSystemDownloadsDir: () => app.getPath('downloads'),
- getHomeDir: homedir,
- ensureDirectory: (directory) => mkdirSync(directory, { recursive: true }),
- onSystemDownloadsDirError: (error, fallbackDir) =>
- log.warn(
- { err: error, fallbackDir },
- 'system downloads directory unavailable; using home fallback'
- ),
-})
+const defaultSaveDirOptions = portableProfile
+ ? { defaultSaveDir: portableProfile.downloadsDir }
+ : resolveDefaultSaveDirOptions({
+ snapEnvironment: settingsSnapEnvironment,
+ getSystemDownloadsDir: () => app.getPath('downloads'),
+ getHomeDir: homedir,
+ ensureDirectory: (directory) => mkdirSync(directory, { recursive: true }),
+ onSystemDownloadsDirError: (error, fallbackDir) =>
+ log.warn(
+ { err: error, fallbackDir },
+ 'system downloads directory unavailable; using home fallback'
+ ),
+ })
const cliToolService = new CliToolService({
+ manualOnlyReason: portableProfile ? CliToolReason.Portable : undefined,
directInstallSupported:
- !settingsFlatpakEnvironment && settingsSnapEnvironment === null,
+ !portableProfile &&
+ !settingsFlatpakEnvironment &&
+ settingsSnapEnvironment === null,
})
const settingsManager = new SettingsManager(settingsPath, {
defaultByteUnitSystem: resolveByteUnitSystem(
@@ -467,7 +506,12 @@ log.info({ extraDir: platform.extraResourceDir }, 'resolved extra directory')
const configBuilder = new Aria2ConfigBuilder(
path.join(platform.extraResourceDir, 'aria2.conf'),
platform.userDataDir,
- { supervisorPid: process.pid }
+ {
+ supervisorPid: process.pid,
+ ...(portableProfile
+ ? { persistenceDirectory: portableEngineStateDirectory(portableProfile) }
+ : {}),
+ }
)
const trustStore = new Aria2TrustStore(platform.userDataDir)
@@ -1398,6 +1442,9 @@ async function startEngineAndRestore(
// flowing. See design spec §6.6.
const finalizeDepsFactory = () => buildFinalizeDeps(adapter)
recoveryService = new TaskRecoveryServiceImpl({
+ canRecoverAutomatically: (task) =>
+ !portableProfile ||
+ task.errorDetailKey !== 'task.recovery.startup.portableExternalPath',
hasPendingFinalization: async (taskId) =>
(await durableFinalizeRuntime?.hasPendingFinalization(taskId)) ?? false,
taskManager: {
@@ -1607,6 +1654,16 @@ async function initializeMainProcess(): Promise<void> {
// Only the minimum work needed before the window can open:
// settings (for window bounds/run mode) and WindowManager.
+ if (portableProfile) {
+ if (!app.hasSingleInstanceLock()) return
+ try {
+ await relocatePortableProfile(portableProfile, motrixDb.database)
+ } catch (error) {
+ throw new PortableProfileError('Portable startup recovery failed', {
+ cause: error,
+ })
+ }
+ }
await settingsManager.load()
if (graphicsRuntime?.recovery.recoveredAtStartup) {
await settingsManager.update({ app: { hardwareAcceleration: false } })
@@ -1838,7 +1895,7 @@ async function initializeMainProcess(): Promise<void> {
const legacyNavigation = new LegacyImportNavigation({
hasConsent: () => gate.isAccepted() && mainProcessWork.isAccepting(),
getService: getLegacyImportService,
- roots: defaultLegacyRoots,
+ roots: portableProfile ? () => [] : defaultLegacyRoots,
changed: () => {
const mainWindow = windowManager?.get('main')
if (mainWindow)
@@ -2243,7 +2300,9 @@ async function initializeMainProcess(): Promise<void> {
// here so SessionManager.restore() can skip aria2-restored segment downloads
// (phantom-task guard); the bridge bootstrap reuses the same value for the
// coordinator's tmpRoot and the poll loop's suppression.
- const mediaTmpDir = path.join(app.getPath('temp'), 'motrix-media')
+ const mediaTmpDir = portableProfile
+ ? path.join(portableProfile.workDir, 'media')
+ : path.join(app.getPath('temp'), 'motrix-media')
mediaTmpRoot = mediaTmpDir
sessionManager = new SessionManager(
taskManager,
@@ -2405,6 +2464,10 @@ async function initializeMainProcess(): Promise<void> {
runExclusivePersistence: (operation) =>
sessionManager.runExclusivePersistence(operation),
torrentMetaDir: path.join(platform.userDataDir, 'torrents'),
+ metadataWorkDir: portableProfile?.workDir,
+ canRestoreTask: (task) =>
+ !portableProfile ||
+ task.errorDetailKey !== 'task.recovery.startup.portableExternalPath',
occurrenceDispatcher,
}
)
@@ -2432,7 +2495,8 @@ async function initializeMainProcess(): Promise<void> {
: null
const updatesSupported =
!distributionContext.isWindowsPackage &&
- (updateSimulatorEnabled ||
+ (Boolean(portableProfile) ||
+ updateSimulatorEnabled ||
isElectronSelfUpdateSupported({
hasUpdateMetadata,
isPackaged: app.isPackaged,
@@ -2455,15 +2519,24 @@ async function initializeMainProcess(): Promise<void> {
isWindowsPackage: distributionContext.isWindowsPackage,
supported: updatesSupported,
getInstallBlockReason: () =>
- getMacUpdateInstallBlockReason({
- platform: process.platform,
- isPackaged: app.isPackaged,
- execPath: process.execPath,
- temporaryDirectory: app.getPath('temp'),
- }),
- loadUpdater: async () =>
- developmentUpdateSimulator ??
- (await import('electron-updater')).default.autoUpdater,
+ portableProfile
+ ? 'portable'
+ : getMacUpdateInstallBlockReason({
+ platform: process.platform,
+ isPackaged: app.isPackaged,
+ execPath: process.execPath,
+ temporaryDirectory: app.getPath('temp'),
+ }),
+ loadUpdater: async () => {
+ if (developmentUpdateSimulator) return developmentUpdateSimulator
+ const updater = (await import('electron-updater')).default.autoUpdater
+ if (portableProfile)
+ updater.setFeedURL({
+ provider: 'generic',
+ url: 'https://dl.motrix.app/releases/',
+ })
+ return updater
+ },
getManagedMessage: () => i18n.t('settings.about.update.managedDescription'),
})
if (!mainProcessWork.isAccepting()) return
@@ -2870,7 +2943,10 @@ async function initializeMainProcess(): Promise<void> {
}
bridgeManager = new BridgeManager(
createBridgeRuntime,
- () => nativeMessagingInstaller.unregister(),
+ () =>
+ portableProfile
+ ? Promise.resolve()
+ : nativeMessagingInstaller.unregister(),
!nativeMessagingInstaller.preserveOnStartupFailure
)
@@ -3178,6 +3254,13 @@ app.on('ready', () => {
return
}
log.error({ err }, 'main process initialization failed')
+ if (err instanceof PortableProfileError) {
+ dialog.showErrorBox(
+ i18n.t('settings.portable.title'),
+ i18n.t('settings.portable.recoveryError')
+ )
+ void requestForcedQuit('portable-startup-failed')
+ }
})
})
@@ -3250,7 +3333,7 @@ const quitController = new QuitController({
beginShutdown,
})
-if (!distributionContext.isWindowsPackage) {
+if (!distributionContext.isWindowsPackage && !portableProfile) {
registerUpdateQuitPreparation({
updater: nativeAutoUpdater,
markForceQuit: () => quitController.markForceQuit(),
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 1a41bbdf..1b121c06 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -36,6 +36,7 @@ import { directTaskUpdatePublication } from '@test-utils/task-update'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createAppUpdateService } from '../core/app-update-service'
import { MainProcessWorkCoordinator } from '../main-process-work-coordinator'
+import { setPortableProfile } from '../platform/portable-profile'
import { WINDOWS_DEFAULT_APPS_SETTINGS_URL } from '../platform/windows-default-apps'
import type { CommandContext } from './commands'
import { buildCommandHandlers, registerCommandHandlers } from './commands'
@@ -3183,3 +3184,24 @@ describe('plugin diagnostic mode command', () => {
}
)
})
+
+it('rejects system association commands from a portable profile', async () => {
+ setPortableProfile({
+ root: 'E:\\Motrix',
+ dataDir: '',
+ userDataDir: '',
+ tempDir: '',
+ workDir: '',
+ downloadsDir: '',
+ })
+ try {
+ const handlers = buildCommandHandlers(
+ fakeCtx() as unknown as CommandContext
+ )
+ await expect(
+ handlers[Commands.RequestDefaultTorrentHandler]?.()
+ ).rejects.toMatchObject({ code: ErrorCode.SettingsInvalid })
+ } finally {
+ setPortableProfile(null)
+ }
+})
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index dd1489b1..c147f31a 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -163,6 +163,7 @@ import {
} from '../platform/appimage-integration-host'
import { syncAutoLaunch } from '../platform/auto-launch'
import { setLinuxDefaultTorrentHandler } from '../platform/linux-default-apps'
+import { getPortableProfile } from '../platform/portable-profile'
import type { createProtocolManager } from '../platform/protocol-manager'
import { resolveWindowsDefaultAppsSettingsUrl } from '../platform/windows-default-apps'
import { desktopOperationHandlers } from '../plugin/operation-commands'
@@ -1519,6 +1520,11 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
}),
[Commands.RequestDefaultTorrentHandler]: async () => {
+ if (getPortableProfile())
+ throw new AppError(
+ ErrorCode.SettingsInvalid,
+ i18n.t('settings.portable.integrationUnavailable')
+ )
if (process.platform === 'darwin') {
// macOS has no central default-apps panel. The previous implementation
// opened the General preference pane, which is unrelated to file
diff --git a/src/main/platform/auto-launch.test.ts b/src/main/platform/auto-launch.test.ts
index a848b59b..c8aae550 100644
--- a/src/main/platform/auto-launch.test.ts
+++ b/src/main/platform/auto-launch.test.ts
@@ -12,6 +12,7 @@ vi.mock('electron', () => ({
}))
import { syncAutoLaunch } from './auto-launch'
+import { setPortableProfile } from './portable-profile'
describe('syncAutoLaunch', () => {
beforeEach(() => {
@@ -63,3 +64,22 @@ describe('syncAutoLaunch', () => {
Object.defineProperty(process, 'platform', { value: originalPlatform })
})
})
+
+it('never adds or removes host startup entries from a portable profile', () => {
+ mockSetLoginItemSettings.mockClear()
+ setPortableProfile({
+ root: 'E:\\Motrix',
+ dataDir: '',
+ userDataDir: '',
+ tempDir: '',
+ workDir: '',
+ downloadsDir: '',
+ })
+ try {
+ syncAutoLaunch(true)
+ syncAutoLaunch(false)
+ expect(mockSetLoginItemSettings).not.toHaveBeenCalled()
+ } finally {
+ setPortableProfile(null)
+ }
+})
diff --git a/src/main/platform/auto-launch.ts b/src/main/platform/auto-launch.ts
index bb81b9a5..b0311815 100644
--- a/src/main/platform/auto-launch.ts
+++ b/src/main/platform/auto-launch.ts
@@ -1,6 +1,8 @@
import { app } from 'electron'
+import { getPortableProfile } from './portable-profile'
export function syncAutoLaunch(enabled: boolean): void {
+ if (getPortableProfile()) return
// Linux login startup is managed in the desktop environment; settings link
// to the manual instead of offering an automatic registration switch.
if (process.platform === 'linux') return
diff --git a/src/main/platform/portable-profile.test.ts b/src/main/platform/portable-profile.test.ts
new file mode 100644
index 00000000..532a736b
--- /dev/null
+++ b/src/main/platform/portable-profile.test.ts
@@ -0,0 +1,76 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const fs = vi.hoisted(() => ({
+ existsSync: vi.fn(() => false),
+ statSync: vi.fn((): { isDirectory: () => boolean } => ({
+ isDirectory: () => true,
+ })),
+ mkdirSync: vi.fn(),
+ writeFileSync: vi.fn(),
+ unlinkSync: vi.fn(),
+}))
+vi.mock('node:fs', () => fs)
+
+import {
+ preparePortableProfile,
+ resolvePortableProfile,
+ setPortableProfile,
+} from './portable-profile'
+
+const options = {
+ platform: 'win32' as const,
+ isPackaged: true,
+ isWindowsPackage: false,
+ executablePath: 'E:\\测试 Motrix\\Motrix.exe',
+}
+
+describe('portable profile selection', () => {
+ beforeEach(() => vi.clearAllMocks())
+ afterEach(() => setPortableProfile(null))
+ it('uses the executable location, including spaces and Unicode, independently of cwd', () => {
+ expect(resolvePortableProfile(options)).toMatchObject({
+ root: 'E:\\测试 Motrix',
+ userDataDir: 'E:\\测试 Motrix\\data\\user-data',
+ downloadsDir: 'E:\\测试 Motrix\\Downloads',
+ })
+ })
+ it.each([
+ { platform: 'darwin' as const },
+ { platform: 'linux' as const },
+ { isPackaged: false },
+ { isWindowsPackage: true },
+ ])(
+ 'never inspects a portable directory for excluded runtimes: %o',
+ (override) => {
+ expect(resolvePortableProfile({ ...options, ...override })).toBeNull()
+ expect(fs.statSync).not.toHaveBeenCalled()
+ }
+ )
+ it('leaves installed NSIS apps unchanged even with a data directory', () => {
+ fs.existsSync.mockReturnValueOnce(true)
+ expect(resolvePortableProfile(options)).toBeNull()
+ expect(fs.statSync).not.toHaveBeenCalled()
+ })
+ it('does not enable or create a portable directory when it is absent', () => {
+ fs.statSync.mockImplementationOnce(() => {
+ throw Object.assign(new Error('missing'), { code: 'ENOENT' })
+ })
+ expect(resolvePortableProfile(options)).toBeNull()
+ expect(fs.mkdirSync).not.toHaveBeenCalled()
+ })
+ it('fails closed for an unreadable marker or a file named data', () => {
+ fs.statSync.mockImplementationOnce(() => {
+ throw Object.assign(new Error('denied'), { code: 'EACCES' })
+ })
+ expect(() => resolvePortableProfile(options)).toThrow('unavailable')
+ fs.statSync.mockReturnValueOnce({ isDirectory: () => false })
+ expect(() => resolvePortableProfile(options)).toThrow('unavailable')
+ })
+ it('probes writes and never falls back when the portable device is read-only', () => {
+ const profile = resolvePortableProfile(options)!
+ fs.writeFileSync.mockImplementationOnce(() => {
+ throw new Error('read-only')
+ })
+ expect(() => preparePortableProfile(profile)).toThrow('not writable')
+ })
+})
diff --git a/src/main/platform/portable-profile.ts b/src/main/platform/portable-profile.ts
new file mode 100644
index 00000000..e5b9866b
--- /dev/null
+++ b/src/main/platform/portable-profile.ts
@@ -0,0 +1,92 @@
+import { randomUUID } from 'node:crypto'
+import {
+ existsSync,
+ mkdirSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import path from 'node:path'
+
+export interface PortableProfile {
+ readonly root: string
+ readonly dataDir: string
+ readonly userDataDir: string
+ readonly workDir: string
+ readonly tempDir: string
+ readonly downloadsDir: string
+}
+
+let activeProfile: PortableProfile | null = null
+
+export function getPortableProfile(): PortableProfile | null {
+ return activeProfile
+}
+
+export function setPortableProfile(profile: PortableProfile | null): void {
+ activeProfile = profile
+}
+
+export class PortableProfileError extends Error {}
+
+/** A directory is an explicit opt-in. Installed NSIS and Store apps ignore it. */
+export function resolvePortableProfile(options: {
+ platform: NodeJS.Platform
+ isPackaged: boolean
+ isWindowsPackage: boolean
+ executablePath: string
+}): PortableProfile | null {
+ if (
+ options.platform !== 'win32' ||
+ !options.isPackaged ||
+ options.isWindowsPackage
+ )
+ return null
+ const root = path.win32.dirname(options.executablePath)
+ if (existsSync(path.win32.join(root, 'Uninstall Motrix.exe'))) return null
+ const dataDir = path.win32.join(root, 'data')
+ try {
+ if (!statSync(dataDir).isDirectory())
+ throw new PortableProfileError(
+ 'The portable data path must be a directory'
+ )
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw new PortableProfileError(
+ 'The portable data directory is unavailable',
+ { cause: error }
+ )
+ }
+ return {
+ root,
+ dataDir,
+ userDataDir: path.win32.join(dataDir, 'user-data'),
+ workDir: path.win32.join(dataDir, 'work'),
+ tempDir: path.win32.join(dataDir, 'tmp'),
+ downloadsDir: path.win32.join(root, 'Downloads'),
+ }
+}
+
+/** Probe actual writes; access(W_OK) alone is insufficient on Windows ACLs. */
+export function preparePortableProfile(profile: PortableProfile): void {
+ try {
+ for (const directory of [
+ profile.dataDir,
+ profile.userDataDir,
+ profile.workDir,
+ profile.tempDir,
+ path.win32.join(profile.userDataDir, 'logs'),
+ path.win32.join(profile.userDataDir, 'crashes'),
+ ]) {
+ mkdirSync(directory, { recursive: true })
+ const probe = path.join(directory, `.write-test-${randomUUID()}`)
+ writeFileSync(probe, '', { flag: 'wx' })
+ unlinkSync(probe)
+ }
+ } catch (error) {
+ throw new PortableProfileError(
+ 'The portable data directory is not writable',
+ { cause: error }
+ )
+ }
+}
diff --git a/src/main/platform/portable-relocation.test.ts b/src/main/platform/portable-relocation.test.ts
new file mode 100644
index 00000000..c8cb02d7
--- /dev/null
+++ b/src/main/platform/portable-relocation.test.ts
@@ -0,0 +1,289 @@
+// @vitest-environment node
+import {
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import Database from 'better-sqlite3'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import type { PortableProfile } from './portable-profile'
+import {
+ portableEngineStateDirectory,
+ relocatePortableProfile,
+} from './portable-relocation'
+
+describe('portable startup relocation', () => {
+ let directory: string
+ let profile: PortableProfile
+ let db: Database.Database
+ beforeEach(async () => {
+ directory = await mkdtemp(path.join(tmpdir(), 'motrix-portable-'))
+ profile = {
+ root: 'E:\\Motrix',
+ dataDir: directory,
+ userDataDir: path.join(directory, 'user-data'),
+ workDir: path.join(directory, 'work'),
+ tempDir: path.join(directory, 'tmp'),
+ downloadsDir: 'E:\\Motrix\\Downloads',
+ }
+ await mkdir(profile.userDataDir)
+ db = new Database(':memory:')
+ db.exec(`CREATE TABLE tasks (motrix_id TEXT PRIMARY KEY, save_dir TEXT, final_path TEXT, agg_status TEXT, error_code TEXT, error_detail_key TEXT, error_message TEXT, error_detail_params TEXT);
+ CREATE TABLE task_instances (instance_id TEXT PRIMARY KEY, motrix_id TEXT, disk_path TEXT, payload TEXT, status TEXT, transition_phase TEXT);`)
+ })
+ afterEach(async () => {
+ db.close()
+ await rm(directory, { recursive: true, force: true })
+ })
+
+ it('keeps a fresh profile independent and records the location before task creation', async () => {
+ expect(await relocatePortableProfile(profile, db)).toBe(false)
+ expect(
+ JSON.parse(await readFile(path.join(directory, 'portable.json'), 'utf8'))
+ .roots
+ ).toEqual(['E:\\Motrix'])
+ })
+
+ it('moves settings and tasks, blocks external tasks and retires stale engine state on return', async () => {
+ await relocatePortableProfile(profile, db)
+ const settings = {
+ app: {
+ defaultSaveDir: 'E:\\Motrix\\Downloads',
+ favorites: ['D:\\External'],
+ },
+ plugins: {
+ example: { config: { secret: 'E:\\Motrix\\opaque-credential' } },
+ },
+ media: {
+ ffmpegBinaryPath: 'E:\\Motrix\\data\\user-data\\binaries\\ffmpeg.exe',
+ },
+ }
+ await writeFile(
+ path.join(profile.userDataDir, 'settings.json'),
+ JSON.stringify(settings)
+ )
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run(
+ 'local',
+ 'E:\\Motrix\\Downloads',
+ 'E:\\Motrix\\Downloads\\a',
+ 'paused'
+ )
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run('external', 'D:\\External', 'D:\\External\\b', 'downloading')
+ db.prepare('INSERT INTO task_instances VALUES (?,?,?,?,?,?)').run(
+ 'external-i',
+ 'external',
+ 'D:\\External\\b',
+ '{}',
+ 'downloading',
+ 'renaming'
+ )
+ const oldEngine = portableEngineStateDirectory(profile)
+ await writeFile(path.join(oldEngine, 'aria2.session'), 'old absolute paths')
+ const moved = { ...profile, root: 'F:\\Motrix' }
+ expect(await relocatePortableProfile(moved, db)).toBe(true)
+ expect(
+ db
+ .prepare(
+ "SELECT save_dir, agg_status FROM tasks WHERE motrix_id = 'local'"
+ )
+ .get()
+ ).toEqual({ save_dir: 'F:\\Motrix\\Downloads', agg_status: 'paused' })
+ expect(
+ db
+ .prepare(
+ "SELECT final_path, agg_status, error_detail_key FROM tasks WHERE motrix_id = 'external'"
+ )
+ .get()
+ ).toEqual({
+ final_path: 'D:\\External\\b',
+ agg_status: 'error',
+ error_detail_key: 'task.recovery.startup.portableExternalPath',
+ })
+ const loaded = JSON.parse(
+ await readFile(path.join(profile.userDataDir, 'settings.json'), 'utf8')
+ )
+ expect(loaded.app.defaultSaveDir).toBe('F:\\Motrix\\Downloads')
+ expect(loaded.plugins.example.config.secret).toBe(
+ 'E:\\Motrix\\opaque-credential'
+ )
+ expect(loaded.app.favorites).toEqual(['D:\\External'])
+ await relocatePortableProfile(profile, db)
+ expect(await readdir(oldEngine)).toEqual([])
+ expect(
+ (await readdir(path.dirname(oldEngine))).some((entry) =>
+ entry.includes('.previous-')
+ )
+ ).toBe(true)
+ })
+
+ it('retains a relocation journal after failure and can recover after another move', async () => {
+ await relocatePortableProfile(profile, db)
+ await writeFile(
+ path.join(profile.userDataDir, 'settings.json'),
+ JSON.stringify({ app: { defaultSaveDir: 'E:\\Motrix\\Downloads' } })
+ )
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run(
+ 'local',
+ 'E:\\Motrix\\Downloads',
+ 'E:\\Motrix\\Downloads\\a',
+ 'paused'
+ )
+ db.exec(
+ "CREATE TRIGGER fail_move BEFORE UPDATE ON tasks BEGIN SELECT RAISE(ABORT, 'blocked'); END"
+ )
+ await expect(
+ relocatePortableProfile({ ...profile, root: 'F:\\Motrix' }, db)
+ ).rejects.toThrow('blocked')
+ db.exec('DROP TRIGGER fail_move')
+ await relocatePortableProfile({ ...profile, root: 'G:\\Motrix' }, db)
+ const settings = JSON.parse(
+ await readFile(path.join(profile.userDataDir, 'settings.json'), 'utf8')
+ )
+ expect(settings.app.defaultSaveDir).toBe('G:\\Motrix\\Downloads')
+ expect(db.prepare('SELECT save_dir FROM tasks').get()).toEqual({
+ save_dir: 'G:\\Motrix\\Downloads',
+ })
+ })
+
+ it('retires engine state after a crash between task blocking and cache retirement', async () => {
+ await relocatePortableProfile(profile, db)
+ const engineDir = portableEngineStateDirectory(profile)
+ await writeFile(
+ path.join(engineDir, 'aria2.session'),
+ 'unsafe external path'
+ )
+ await writeFile(
+ path.join(directory, 'portable.json'),
+ JSON.stringify({
+ version: 1,
+ roots: [profile.root],
+ engineResetPending: true,
+ })
+ )
+ await relocatePortableProfile(profile, db)
+ expect(await readdir(engineDir)).toEqual([])
+ expect(
+ JSON.parse(await readFile(path.join(directory, 'portable.json'), 'utf8'))
+ .engineResetPending
+ ).toBe(false)
+ })
+
+ it('holds an external final destination even when saveDir is internal and the destination becomes the new root', async () => {
+ await relocatePortableProfile(profile, db)
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run(
+ 'mixed',
+ 'E:\\Motrix\\Downloads',
+ 'F:\\Motrix\\outside.bin',
+ 'finalizing'
+ )
+ db.prepare('INSERT INTO task_instances VALUES (?,?,?,?,?,?)').run(
+ 'mixed-i',
+ 'mixed',
+ 'E:\\Motrix\\Downloads\\partial',
+ '{}',
+ 'finalizing',
+ 'renaming'
+ )
+ await relocatePortableProfile({ ...profile, root: 'F:\\Motrix' }, db)
+ expect(
+ db.prepare('SELECT agg_status, error_detail_key FROM tasks').get()
+ ).toEqual({
+ agg_status: 'error',
+ error_detail_key: 'task.recovery.startup.portableExternalPath',
+ })
+ expect(
+ db.prepare('SELECT transition_phase FROM task_instances').get()
+ ).toEqual({ transition_phase: 'renaming' })
+ })
+
+ it('recovers an interrupted nested move from original settings and database values', async () => {
+ profile = { ...profile, root: 'E:\\Motrix\\old' }
+ await relocatePortableProfile(profile, db)
+ const original = 'E:\\Motrix\\old\\old\\Downloads'
+ await writeFile(
+ path.join(profile.userDataDir, 'settings.json'),
+ JSON.stringify({ app: { defaultSaveDir: original } })
+ )
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run('local', original, `${original}\\a`, 'paused')
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run('external', 'D:\\External', 'D:\\External\\b', 'downloading')
+ db.prepare('INSERT INTO task_instances VALUES (?,?,?,?,?,?)').run(
+ 'external-i',
+ 'external',
+ 'D:\\External\\b',
+ '{}',
+ 'downloading',
+ 'idle'
+ )
+ db.exec(
+ "CREATE TRIGGER fail_block BEFORE UPDATE OF status ON task_instances BEGIN SELECT RAISE(ABORT, 'blocked'); END"
+ )
+ const moved = { ...profile, root: 'E:\\Motrix' }
+ await expect(relocatePortableProfile(moved, db)).rejects.toThrow('blocked')
+ db.exec('DROP TRIGGER fail_block')
+ await relocatePortableProfile(moved, db)
+ expect(
+ JSON.parse(
+ await readFile(path.join(profile.userDataDir, 'settings.json'), 'utf8')
+ ).app.defaultSaveDir
+ ).toBe('E:\\Motrix\\old\\Downloads')
+ expect(
+ db.prepare("SELECT save_dir FROM tasks WHERE motrix_id='local'").get()
+ ).toEqual({ save_dir: 'E:\\Motrix\\old\\Downloads' })
+ })
+
+ it('preserves user edits made while relocation is interrupted', async () => {
+ await relocatePortableProfile(profile, db)
+ const settingsPath = path.join(profile.userDataDir, 'settings.json')
+ await writeFile(
+ settingsPath,
+ JSON.stringify({ app: { defaultSaveDir: 'E:\\Motrix\\Downloads' } })
+ )
+ db.prepare(
+ 'INSERT INTO tasks (motrix_id,save_dir,final_path,agg_status) VALUES (?,?,?,?)'
+ ).run(
+ 'local',
+ 'E:\\Motrix\\Downloads',
+ 'E:\\Motrix\\Downloads\\a',
+ 'paused'
+ )
+ db.exec(
+ "CREATE TRIGGER fail_move BEFORE UPDATE ON tasks BEGIN SELECT RAISE(ABORT, 'blocked'); END"
+ )
+ await expect(
+ relocatePortableProfile({ ...profile, root: 'F:\\Motrix' }, db)
+ ).rejects.toThrow('blocked')
+ db.exec('DROP TRIGGER fail_move')
+ const edited = JSON.stringify({
+ app: { defaultSaveDir: 'D:\\My selection' },
+ })
+ await writeFile(settingsPath, edited)
+ await expect(
+ relocatePortableProfile({ ...profile, root: 'F:\\Motrix' }, db)
+ ).rejects.toThrow('edited during relocation')
+ expect(await readFile(settingsPath, 'utf8')).toBe(edited)
+ })
+
+ it('fails closed on corrupt location history', async () => {
+ await writeFile(path.join(directory, 'portable.json'), '{broken')
+ await expect(relocatePortableProfile(profile, db)).rejects.toThrow(
+ 'history is invalid'
+ )
+ })
+})
diff --git a/src/main/platform/portable-relocation.ts b/src/main/platform/portable-relocation.ts
new file mode 100644
index 00000000..97111bc1
--- /dev/null
+++ b/src/main/platform/portable-relocation.ts
@@ -0,0 +1,324 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { mkdir, readFile, rename, stat } from 'node:fs/promises'
+import path from 'node:path'
+import { isDeepStrictEqual } from 'node:util'
+import {
+ capturePortableDatabase,
+ isWithinPortableRoot,
+ type PortableDatabaseSnapshot,
+ portableDatabaseSnapshotSchema,
+ portablePayloadPaths,
+ relocatePortableDatabase,
+ relocatePortableValue,
+} from '@core/session/portable-relocation'
+import type Database from 'better-sqlite3'
+import writeFileAtomic from 'write-file-atomic'
+import { z } from 'zod'
+import { type PortableProfile, PortableProfileError } from './portable-profile'
+
+const rootSchema = z
+ .string()
+ .refine(
+ (value) =>
+ path.win32.isAbsolute(value) && path.win32.parse(value).root.length > 1
+ )
+const settingsSchema = z.record(z.string(), z.unknown()).nullable()
+const snapshotSchema = z.object({
+ sourceRoot: rootSchema,
+ settings: settingsSchema,
+ database: portableDatabaseSnapshotSchema,
+})
+const stateSchema = z.object({
+ version: z.literal(1),
+ roots: z.array(rootSchema).min(1),
+ relocationId: z.uuid().optional(),
+ engineResetPending: z.boolean().optional().default(false),
+})
+
+/** Engine snapshots contain absolute paths. A new location gets a fresh cache. */
+export function portableEngineStateDirectory(profile: PortableProfile): string {
+ const location = createHash('sha256')
+ .update(path.win32.normalize(profile.root).toLowerCase())
+ .digest('hex')
+ .slice(0, 20)
+ return path.join(profile.userDataDir, 'engine', location)
+}
+
+async function readSettings(
+ file: string
+): Promise<z.infer<typeof settingsSchema>> {
+ try {
+ return settingsSchema.parse(JSON.parse(await readFile(file, 'utf8')))
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ }
+}
+function mappedSettings(
+ original: z.infer<typeof settingsSchema>,
+ sourceRoot: string,
+ targetRoot: string
+) {
+ const settings = structuredClone(original)
+ if (!settings) return settings
+ // Opaque plugin credentials/scripts are not path configuration.
+ for (const [namespace, fields] of Object.entries({
+ app: ['defaultSaveDir', 'directoryPreferences'],
+ engine: ['sqlite3DbPath'],
+ media: ['ffmpegBinaryPath'],
+ })) {
+ const group = settings[namespace]
+ if (!group || typeof group !== 'object' || Array.isArray(group)) continue
+ const record = group as Record<string, unknown>
+ for (const field of fields)
+ if (field in record)
+ record[field] = relocatePortableValue(
+ record[field],
+ [sourceRoot],
+ targetRoot
+ )
+ }
+ return settings
+}
+
+/** Retries always replay immutable originals, including after another move. */
+export async function relocatePortableProfile(
+ profile: PortableProfile,
+ database: Database.Database
+): Promise<boolean> {
+ const statePath = path.join(profile.dataDir, 'portable.json')
+ const settingsPath = path.join(profile.userDataDir, 'settings.json')
+ let state: z.infer<typeof stateSchema>
+ try {
+ state = stateSchema.parse(JSON.parse(await readFile(statePath, 'utf8')))
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
+ throw new PortableProfileError('Portable location history is invalid', {
+ cause: error,
+ })
+ state = { version: 1, roots: [profile.root], engineResetPending: false }
+ }
+ const moved =
+ Boolean(state.relocationId) ||
+ state.roots.some((root) => path.win32.relative(root, profile.root) !== '')
+ let snapshot: z.infer<typeof snapshotSchema> | undefined
+ let relocationId = state.relocationId
+ if (relocationId) {
+ snapshot = snapshotSchema.parse(
+ JSON.parse(
+ await readFile(
+ path.join(profile.dataDir, 'relocations', `${relocationId}.json`),
+ 'utf8'
+ )
+ )
+ )
+ if (path.win32.relative(snapshot.sourceRoot, state.roots[0]) !== '')
+ throw new PortableProfileError(
+ 'Portable relocation snapshot does not match its journal'
+ )
+ } else if (moved) {
+ if (state.roots.length !== 1)
+ throw new PortableProfileError(
+ 'Portable relocation originals are missing'
+ )
+ snapshot = {
+ sourceRoot: state.roots[0],
+ settings: await readSettings(settingsPath),
+ database: capturePortableDatabase(database),
+ }
+ relocationId = randomUUID()
+ const directory = path.join(profile.dataDir, 'relocations')
+ await mkdir(directory, { recursive: true })
+ // Retain original paths/recovery evidence; never reuse a mutable profile as
+ // a retry source. Mode 0600 matches the sensitivity of the profile data.
+ await writeFileAtomic(
+ path.join(directory, `${relocationId}.json`),
+ JSON.stringify(snapshot),
+ { mode: 0o600 }
+ )
+ }
+ const attemptedRoots = [...new Set([...state.roots, profile.root])]
+ await writeFileAtomic(
+ statePath,
+ JSON.stringify({
+ version: 1,
+ roots: attemptedRoots,
+ relocationId,
+ engineResetPending: true,
+ }),
+ { mode: 0o600 }
+ )
+ if (snapshot) {
+ const current = await readSettings(settingsPath)
+ const allowed = [
+ snapshot.settings,
+ ...attemptedRoots.map((root) =>
+ mappedSettings(snapshot.settings, snapshot.sourceRoot, root)
+ ),
+ ]
+ if (!allowed.some((value) => isDeepStrictEqual(value, current)))
+ throw new PortableProfileError(
+ 'Portable settings were edited during relocation'
+ )
+ const settings = mappedSettings(
+ snapshot.settings,
+ snapshot.sourceRoot,
+ profile.root
+ )
+ if (settings)
+ await writeFileAtomic(settingsPath, JSON.stringify(settings, null, 2), {
+ mode: 0o600,
+ })
+ relocatePortableDatabase(
+ database,
+ snapshot.database,
+ snapshot.sourceRoot,
+ profile.root,
+ attemptedRoots
+ )
+ }
+ const blocked = await blockUnavailablePortableTasks(
+ profile,
+ database,
+ moved,
+ snapshot?.database,
+ snapshot?.sourceRoot
+ )
+ if (moved || blocked || state.engineResetPending) {
+ const engineDir = portableEngineStateDirectory(profile)
+ try {
+ await rename(engineDir, `${engineDir}.previous-${randomUUID()}`)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ }
+ await mkdir(portableEngineStateDirectory(profile), { recursive: true })
+ await writeFileAtomic(
+ statePath,
+ JSON.stringify({
+ version: 1,
+ roots: [profile.root],
+ engineResetPending: false,
+ }),
+ { mode: 0o600 }
+ )
+ return moved
+}
+
+async function blockUnavailablePortableTasks(
+ profile: PortableProfile,
+ db: Database.Database,
+ moved: boolean,
+ original?: PortableDatabaseSnapshot,
+ sourceRoot = profile.root
+): Promise<boolean> {
+ const current = capturePortableDatabase(db, ['tasks', 'task_instances'])
+ const source = original ?? current
+ const originalTasks = new Map(
+ (source.tasks ?? []).map((row) => [row.motrix_id, row])
+ )
+ const groupInstances = (snapshot: PortableDatabaseSnapshot) => {
+ const groups = new Map<
+ string,
+ NonNullable<PortableDatabaseSnapshot['task_instances']>
+ >()
+ for (const instance of snapshot.task_instances ?? []) {
+ const id = String(instance.motrix_id)
+ const group = groups.get(id) ?? []
+ group.push(instance)
+ groups.set(id, group)
+ }
+ return groups
+ }
+ const currentInstances = groupInstances(current)
+ const sourceInstances = original ? groupInstances(source) : currentInstances
+ const blocked: string[] = []
+ const directoryChecks = new Map<string, Promise<boolean>>()
+ for (const row of current.tasks ?? []) {
+ const id = String(row.motrix_id)
+ const instances = currentInstances.get(id) ?? []
+ const pendingTransition = instances.some(
+ (instance) =>
+ instance.transition_phase && instance.transition_phase !== 'idle'
+ )
+ const pendingBtFinalize = instances.some((instance) => {
+ const payload =
+ typeof instance.payload === 'string' ? JSON.parse(instance.payload) : {}
+ return (
+ payload.btStorageLayout?.version === 2 &&
+ payload.btStorageLayout.finalized === false
+ )
+ })
+ if (
+ row.agg_status === 'removed' ||
+ (['completed', 'error'].includes(String(row.agg_status)) &&
+ !pendingTransition &&
+ !pendingBtFinalize)
+ )
+ continue
+ const originalRow = originalTasks.get(row.motrix_id) ?? row
+ const originalInstances = sourceInstances.get(id) ?? []
+ const paths = [
+ originalRow.save_dir,
+ originalRow.final_path,
+ originalRow.torrent_meta_path,
+ ...originalInstances.flatMap((instance) => [
+ instance.disk_path,
+ ...portablePayloadPaths(
+ typeof instance.payload === 'string'
+ ? JSON.parse(instance.payload)
+ : {}
+ ),
+ ]),
+ ].filter(
+ (value): value is string =>
+ typeof value === 'string' && path.win32.isAbsolute(value)
+ )
+ const external = paths.filter(
+ (value) => !isWithinPortableRoot(value, sourceRoot)
+ )
+ let unavailable = moved && external.length > 0
+ for (const value of unavailable ? [] : external) {
+ const directory =
+ value === originalRow.save_dir ? value : path.win32.dirname(value)
+ let check = directoryChecks.get(directory)
+ if (!check) {
+ check = stat(directory).then(
+ (info) => info.isDirectory(),
+ () => false
+ )
+ directoryChecks.set(directory, check)
+ }
+ if (!(await check)) {
+ unavailable = true
+ break
+ }
+ }
+ if (unavailable) blocked.push(id)
+ }
+ db.transaction(() => {
+ for (const id of blocked) {
+ db.prepare(
+ "UPDATE tasks SET agg_status = 'error', error_code = 'DL_FILE_WRITE_ERROR', error_detail_key = 'task.recovery.startup.portableExternalPath', error_message = NULL, error_detail_params = NULL WHERE motrix_id = ?"
+ ).run(id)
+ // Keep the transition and payload intact for explicit recovery. The
+ // startup recovery gate prevents automatic filesystem work on this task.
+ db.prepare(
+ "UPDATE task_instances SET status = 'error' WHERE motrix_id = ?"
+ ).run(id)
+ }
+ const hasJournals = db
+ .prepare(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'plugin_finalize_journals'"
+ )
+ .get()
+ if (hasJournals) {
+ const quarantine = db.prepare(
+ "UPDATE plugin_finalize_journals SET phase = 'quarantined', quarantine_reason = 'portable-profile-relocated' WHERE phase NOT IN ('cleaned', 'quarantined') AND (? OR task_id = ?)"
+ )
+ if (moved) quarantine.run(1, '')
+ else for (const id of blocked) quarantine.run(0, id)
+ }
+ })()
+ return blocked.length > 0
+}
diff --git a/src/main/platform/services.test.ts b/src/main/platform/services.test.ts
index f147803f..33aceacc 100644
--- a/src/main/platform/services.test.ts
+++ b/src/main/platform/services.test.ts
@@ -20,6 +20,12 @@ const mocks = vi.hoisted(() => {
return {
state,
+ existsSync: vi.fn(() => false),
+ statSync: vi.fn(() => {
+ throw Object.assign(new Error('missing'), { code: 'ENOENT' })
+ }),
+ writeFileSync: vi.fn(),
+ unlinkSync: vi.fn(),
mkdirSync: vi.fn((directory: string) => {
state.operations.push(`mkdir:${directory}`)
}),
@@ -34,6 +40,10 @@ const mocks = vi.hoisted(() => {
vi.mock('node:fs', () => ({
default: { mkdirSync: mocks.mkdirSync },
mkdirSync: mocks.mkdirSync,
+ existsSync: mocks.existsSync,
+ statSync: mocks.statSync,
+ writeFileSync: mocks.writeFileSync,
+ unlinkSync: mocks.unlinkSync,
}))
vi.mock('electron', () => ({
@@ -46,11 +56,18 @@ vi.mock('electron', () => ({
},
}))
+import { getPortableProfile } from './portable-profile'
import { createElectronPlatformServices } from './services'
describe('createElectronPlatformServices', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.existsSync.mockReturnValue(false)
+ mocks.statSync.mockImplementation(() => {
+ throw Object.assign(new Error('missing'), { code: 'ENOENT' })
+ })
+ vi.stubEnv('TEMP', process.env.TEMP)
+ vi.stubEnv('TMP', process.env.TMP)
mocks.state.isPackaged = false
mocks.state.paths = { userData: '/fake/Motrix' }
mocks.state.operations = []
@@ -218,6 +235,40 @@ describe('createElectronPlatformServices', () => {
})
})
+ it('ignores a sibling data folder without touching Store temp or portable state', () => {
+ vi.stubEnv('TEMP', 'C:\\SystemTemp')
+ mocks.statSync.mockImplementation(
+ () => ({ isDirectory: () => true }) as never
+ )
+ expect(createElectronPlatformServices().userDataDir).toBe(storeProfile)
+ expect(getPortableProfile()).toBeNull()
+ expect(mocks.statSync).not.toHaveBeenCalled()
+ expect(process.env.TEMP).toBe('C:\\SystemTemp')
+ expect(mocks.setPath.mock.calls.map(([name]) => name)).toEqual([
+ 'userData',
+ 'sessionData',
+ ])
+ })
+
+ it('keeps an NSIS installation on AppData even when a data folder exists', () => {
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: false,
+ })
+ vi.stubEnv('TEMP', 'C:\\SystemTemp')
+ mocks.existsSync.mockReturnValue(true)
+ mocks.statSync.mockImplementation(
+ () => ({ isDirectory: () => true }) as never
+ )
+ expect(createElectronPlatformServices().userDataDir).toBe(
+ `${appData}\\Motrix`
+ )
+ expect(getPortableProfile()).toBeNull()
+ expect(mocks.statSync).not.toHaveBeenCalled()
+ expect(mocks.setPath).not.toHaveBeenCalled()
+ expect(process.env.TEMP).toBe('C:\\SystemTemp')
+ })
+
it('selects a separate root without reading the direct-install profile', () => {
const svc = createElectronPlatformServices()
@@ -380,3 +431,52 @@ describe('createElectronPlatformServices', () => {
})
})
})
+
+describe('portable profile activation', () => {
+ const execDescriptor = Object.getOwnPropertyDescriptor(process, 'execPath')!
+ afterEach(() => {
+ Object.defineProperty(process, 'execPath', execDescriptor)
+ if (originalResourcesPath)
+ Object.defineProperty(process, 'resourcesPath', originalResourcesPath)
+ else Reflect.deleteProperty(process, 'resourcesPath')
+ Object.defineProperty(process, 'platform', originalPlatform)
+ vi.unstubAllEnvs()
+ })
+
+ it('contains Electron, Node and child-process paths before returning services', () => {
+ vi.stubEnv('TEMP', process.env.TEMP)
+ vi.stubEnv('TMP', process.env.TMP)
+ vi.stubEnv('MOTRIX_USER_DATA', undefined)
+ vi.stubEnv('MOTRIX_BRIDGE_DATA_DIR', undefined)
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: 'win32',
+ })
+ Object.defineProperty(process, 'execPath', {
+ configurable: true,
+ value: 'E:\\Motrix\\Motrix.exe',
+ })
+ Object.defineProperty(process, 'resourcesPath', {
+ configurable: true,
+ value: 'E:\\Motrix\\resources',
+ })
+ mocks.state.isPackaged = true
+ mocks.existsSync.mockReturnValue(false)
+ mocks.statSync.mockImplementation(
+ () => ({ isDirectory: () => true }) as never
+ )
+ const result = createElectronPlatformServices({
+ distribution: 'direct',
+ isWindowsPackage: false,
+ })
+ expect(result.userDataDir).toBe('E:\\Motrix\\data\\user-data')
+ expect(mocks.state.paths.sessionData).toBe(result.userDataDir)
+ expect(mocks.state.paths.crashDumps).toBe(`${result.userDataDir}\\crashes`)
+ expect(mocks.state.paths.logs).toBe(`${result.userDataDir}\\logs`)
+ expect(mocks.state.paths.temp).toBe('E:\\Motrix\\data\\tmp')
+ expect(process.env.TEMP).toBe(mocks.state.paths.temp)
+ expect(process.env.TMP).toBe(mocks.state.paths.temp)
+ expect(getPortableProfile()?.root).toBe('E:\\Motrix')
+ expect(mocks.writeFileSync).toHaveBeenCalled()
+ })
+})
diff --git a/src/main/platform/services.ts b/src/main/platform/services.ts
index 1595848a..7310a96a 100644
--- a/src/main/platform/services.ts
+++ b/src/main/platform/services.ts
@@ -7,6 +7,12 @@ import {
type DistributionContext,
resolveDistributionContext,
} from './distribution-context'
+import {
+ PortableProfileError,
+ preparePortableProfile,
+ resolvePortableProfile,
+ setPortableProfile,
+} from './portable-profile'
export function createElectronPlatformServices(
distributionContext: DistributionContext = resolveDistributionContext({
@@ -18,6 +24,7 @@ export function createElectronPlatformServices(
const isDev = !app.isPackaged
const userDataOverride = process.env.MOTRIX_USER_DATA
const { isWindowsPackage } = distributionContext
+ setPortableProfile(null)
const dataPaths = process.platform === 'win32' ? path.win32 : path
if (isWindowsPackage && userDataOverride) {
throw new Error('MOTRIX_USER_DATA is unsupported for Windows packages')
@@ -30,11 +37,29 @@ export function createElectronPlatformServices(
)
}
+ const portable = resolvePortableProfile({
+ platform: process.platform,
+ isPackaged: app.isPackaged,
+ isWindowsPackage,
+ executablePath: process.execPath,
+ })
+ if (portable) {
+ if (userDataOverride || process.env.MOTRIX_BRIDGE_DATA_DIR) {
+ throw new PortableProfileError(
+ 'Portable mode cannot use external profile overrides'
+ )
+ }
+ preparePortableProfile(portable)
+ setPortableProfile(portable)
+ }
+
let userDataDir: string
if (isWindowsPackage) {
// Never consult or migrate the direct-install profile in package mode.
// Resolve AppData through Electron so Windows controls its package mapping.
userDataDir = dataPaths.join(app.getPath('appData'), 'Motrix-Store')
+ } else if (portable) {
+ userDataDir = portable.userDataDir
} else {
const defaultUserDataDir = app.getPath('userData')
userDataDir =
@@ -44,7 +69,7 @@ export function createElectronPlatformServices(
// Resolve this before any persistent service or the single-instance lock.
// Electron requires an existing absolute directory for app.setPath().
- if (isWindowsPackage || userDataOverride || isDev) {
+ if (portable || isWindowsPackage || userDataOverride || isDev) {
if (!dataPaths.isAbsolute(userDataDir)) {
throw new Error(
isWindowsPackage
@@ -57,6 +82,19 @@ export function createElectronPlatformServices(
app.setPath('sessionData', userDataDir)
}
+ if (portable) {
+ const logsDir = dataPaths.join(userDataDir, 'logs')
+ const crashDir = dataPaths.join(userDataDir, 'crashes')
+ mkdirSync(logsDir, { recursive: true })
+ mkdirSync(crashDir, { recursive: true })
+ app.setPath('logs', logsDir)
+ app.setPath('crashDumps', crashDir)
+ app.setPath('temp', portable.tempDir)
+ // Node's tmpdir() and child processes do not consult Electron's path map.
+ process.env.TEMP = portable.tempDir
+ process.env.TMP = portable.tempDir
+ }
+
const projectRoot = isDev ? path.resolve(__dirname, '..', '..') : ''
const extraDir = isDev
? path.join(projectRoot, 'extra')
diff --git a/src/renderer/hooks/use-portable-mode.ts b/src/renderer/hooks/use-portable-mode.ts
new file mode 100644
index 00000000..8938ce7e
--- /dev/null
+++ b/src/renderer/hooks/use-portable-mode.ts
@@ -0,0 +1,21 @@
+import { transport } from '@renderer/lib/transport'
+import { Queries } from '@shared/protocol/queries'
+import { portableModeSchema } from '@shared/schemas/portable-mode'
+import { useState } from 'react'
+import { useTransportMirror } from './use-transport-mirror'
+
+export function usePortableMode(): boolean {
+ const [portable, setPortable] = useState(false)
+ useTransportMirror({
+ events: [],
+ refetchOnFocus: false,
+ load: async (stale) => {
+ if (transport.platform === 'web') return
+ const status = portableModeSchema.parse(
+ await transport.invoke(Queries.GetPortableMode)
+ )
+ if (!stale()) setPortable(status.enabled)
+ },
+ })
+ return portable
+}
diff --git a/src/renderer/routes/settings/cards/about-dialog.test.tsx b/src/renderer/routes/settings/cards/about-dialog.test.tsx
index 5104b77f..28296bf8 100644
--- a/src/renderer/routes/settings/cards/about-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.test.tsx
@@ -14,6 +14,12 @@ import packageJson from '../../../../../package.json'
import { AboutDialog } from './about-dialog'
import * as appUpdateSection from './app-update-section'
+// These lifecycle tests cover the ordinary desktop host. Portable capability
+// presentation is exercised with the real hook in e2e/portable-mode.spec.ts.
+vi.mock('@renderer/hooks/use-portable-mode', () => ({
+ usePortableMode: () => false,
+}))
+
vi.mock('@renderer/lib/transport', () => ({
transport: {
invoke: vi.fn(),
diff --git a/src/renderer/routes/settings/cards/about-dialog.tsx b/src/renderer/routes/settings/cards/about-dialog.tsx
index 51371ead..3e5a9284 100644
--- a/src/renderer/routes/settings/cards/about-dialog.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.tsx
@@ -13,6 +13,7 @@ import {
ScrollAreaViewport,
ScrollBar,
} from '@renderer/components/ui/scroll-area'
+import { usePortableMode } from '@renderer/hooks/use-portable-mode'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
@@ -48,6 +49,7 @@ export function AboutDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
+ const portable = usePortableMode()
const heading = useRef<HTMLHeadingElement>(null)
const metadata = __MOTRIX_APP_METADATA__
const showUpdates = shouldShowAppUpdate(__MOTRIX_TARGET__)
@@ -91,6 +93,11 @@ export function AboutDialog({
version: metadata.version,
})}
</p>
+ {portable && (
+ <span className="rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground">
+ {t('settings.portable.title')}
+ </span>
+ )}
</div>
<p className="mt-1 max-w-md text-xs leading-[1.45] text-muted-foreground">
{t('settings.about.tagline')}
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.tsx b/src/renderer/routes/settings/cards/advanced-dialog.tsx
index 69c5ea42..3117e38a 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.tsx
@@ -45,6 +45,7 @@ import {
} from '@renderer/components/ui/select'
import { Separator } from '@renderer/components/ui/separator'
import { Switch } from '@renderer/components/ui/switch'
+import { usePortableMode } from '@renderer/hooks/use-portable-mode'
import { pickDirty } from '@renderer/lib/form-utils'
import { saveSettings } from '@renderer/lib/settings-save'
import { LEGACY_MIGRATION_SETTINGS_ROUTE } from '@shared/lib/legacy-import-navigation'
@@ -85,6 +86,7 @@ export function AdvancedDialog({
labelKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
+ const portable = usePortableMode()
const navigate = useNavigate()
const [historyModeOverride, setHistoryModeOverride] =
useState<HistoryRetentionMode | null>(null)
@@ -320,7 +322,11 @@ export function AdvancedDialog({
{t('settings.advanced.persistence.dbPath')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.advanced.persistence.dbPathDesc')}
+ {t(
+ portable
+ ? 'settings.portable.enginePathDescription'
+ : 'settings.advanced.persistence.dbPathDesc'
+ )}
</FormDescription>
</div>
<FormControl>
@@ -331,8 +337,9 @@ export function AdvancedDialog({
'settings.advanced.persistence.dbPathPlaceholder'
)}
disabled={
- !persistenceOn &&
- !form.formState.errors.sqlite3DbPath
+ portable ||
+ (!persistenceOn &&
+ !form.formState.errors.sqlite3DbPath)
}
value={field.value}
onChange={field.onChange}
diff --git a/src/renderer/routes/settings/cards/app-update-section.tsx b/src/renderer/routes/settings/cards/app-update-section.tsx
index a8aa1d78..6643aa29 100644
--- a/src/renderer/routes/settings/cards/app-update-section.tsx
+++ b/src/renderer/routes/settings/cards/app-update-section.tsx
@@ -283,6 +283,8 @@ function statusDescription(
state: AppUpdateState,
t: ReturnType<typeof useTranslation>['t']
): string {
+ if (state.manualInstallReason === 'portable')
+ return t('settings.portable.updateDescription')
if (state.manualInstallReason && state.availableVersion) {
return state.manualInstallReason === 'cross-volume'
? t('settings.about.update.manualCrossVolume')
diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsx
index 2aa8a278..01b03871 100644
--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx
@@ -14,6 +14,12 @@ import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { GeneralDialog } from './general-dialog'
+// These lifecycle tests cover the ordinary desktop host. Portable capability
+// presentation is exercised with the real hook in e2e/portable-mode.spec.ts.
+vi.mock('@renderer/hooks/use-portable-mode', () => ({
+ usePortableMode: () => false,
+}))
+
vi.mock('@renderer/lib/transport', () => ({
transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'darwin' },
}))
diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsx
index 601bf360..c8c71c79 100644
--- a/src/renderer/routes/settings/cards/general-dialog.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.tsx
@@ -38,6 +38,7 @@ import { Separator } from '@renderer/components/ui/separator'
import { Switch } from '@renderer/components/ui/switch'
import { DirectoryPreferencesStatus } from '@renderer/features/directory-preferences/directory-preferences-section'
import { useDirectoryPreferencesDraft } from '@renderer/features/directory-preferences/use-directory-preferences-draft'
+import { usePortableMode } from '@renderer/hooks/use-portable-mode'
import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { RunMode } from '@shared/constants'
@@ -55,6 +56,7 @@ export function GeneralDialog({
labelKey,
}: SettingsCardDialogProps) {
const { t, i18n } = useTranslation()
+ const portable = usePortableMode()
const isWeb = transport.platform === 'web'
const isMac = transport.platform === 'darwin'
const isLinux = transport.platform === 'linux'
@@ -286,11 +288,17 @@ export function GeneralDialog({
</div>
) : (
<>
- {boolRow('launchAtStartup')}
+ {boolRow(
+ 'launchAtStartup',
+ portable
+ ? 'settings.portable.integrationUnavailable'
+ : undefined,
+ !portable
+ )}
{boolRow(
'showMainWindowAtLogin',
undefined,
- form.watch('launchAtStartup')
+ !portable && form.watch('launchAtStartup')
)}
</>
)}
diff --git a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx
index 078c0c5a..d8c48275 100644
--- a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx
@@ -13,6 +13,7 @@ import {
FormLabel,
} from '@renderer/components/ui/form'
import { Switch } from '@renderer/components/ui/switch'
+import { usePortableMode } from '@renderer/hooks/use-portable-mode'
import { browserDisplayName } from '@renderer/lib/browser-name'
import { cn } from '@renderer/lib/utils'
import type { PairedClientInfo } from '@shared/protocol/bridge'
@@ -32,6 +33,7 @@ const IDENTITY_LABEL_KEYS = {
export function BrowserExtensionsSection() {
const { t } = useTranslation()
+ const portable = usePortableMode()
const form = useFormContext<IntegrationFormValues>()
const { items: paired, revoke } = usePairedExtensions()
const status = useBridgeStatus()
@@ -55,7 +57,11 @@ export function BrowserExtensionsSection() {
{t('settings.integration.browser.masterSwitch')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.integration.browser.masterSwitchDesc')}
+ {t(
+ portable
+ ? 'settings.portable.browserDescription'
+ : 'settings.integration.browser.masterSwitchDesc'
+ )}
</FormDescription>
</div>
<FormControl>
diff --git a/src/renderer/routes/settings/cards/integration/cli-tool-section.tsx b/src/renderer/routes/settings/cards/integration/cli-tool-section.tsx
index aff88aac..3b2186a9 100644
--- a/src/renderer/routes/settings/cards/integration/cli-tool-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/cli-tool-section.tsx
@@ -88,6 +88,8 @@ function reasonKey(reason: CliToolReason | null): string {
return 'settings.integration.cli.tool.reason.nodeTooOld'
case CliToolReason.ManagerMissing:
return 'settings.integration.cli.tool.reason.managerMissing'
+ case CliToolReason.Portable:
+ return 'settings.portable.integrationUnavailable'
case CliToolReason.Sandboxed:
return 'settings.integration.cli.tool.reason.sandboxed'
case CliToolReason.UnsupportedWeb:
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
index 1191ee85..9df2abe1 100644
--- a/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
@@ -15,6 +15,7 @@ vi.mock('@renderer/lib/transport', () => ({
transport: { invoke: vi.fn(), off: vi.fn(), on: vi.fn(), platform: 'win32' },
}))
+let portable = false
let windowsStatus: WindowsDefaultAssociations
let linuxStatus: LinuxDefaultAssociations
@@ -50,6 +51,7 @@ function renderSection(platform: typeof transport.platform) {
describe('<SystemProtocolsSection>', () => {
beforeEach(() => {
+ portable = false
windowsStatus = {
supported: true,
registered: true,
@@ -66,6 +68,7 @@ describe('<SystemProtocolsSection>', () => {
magnet: true,
}
vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetPortableMode) return { enabled: portable }
if (channel === Queries.GetWindowsDefaultAssociations) {
return windowsStatus
}
@@ -86,6 +89,22 @@ describe('<SystemProtocolsSection>', () => {
vi.clearAllMocks()
})
+ it('explains why system associations are unavailable in portable mode', async () => {
+ portable = true
+ renderSection('win32')
+ await waitFor(() =>
+ expect(
+ screen.getByText(/Portable mode keeps system settings unchanged/)
+ ).toBeVisible()
+ )
+ expect(
+ screen.queryByRole('button', { name: /default/i })
+ ).not.toBeInTheDocument()
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.RequestDefaultTorrentHandler
+ )
+ })
+
it('shows current Windows status and opens the system settings', async () => {
renderSection('win32')
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 c11028da..1926e7d8 100644
--- a/src/renderer/routes/settings/cards/integration/system-protocols-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/system-protocols-section.tsx
@@ -8,6 +8,7 @@ import {
FormLabel,
} from '@renderer/components/ui/form'
import { Switch } from '@renderer/components/ui/switch'
+import { usePortableMode } from '@renderer/hooks/use-portable-mode'
import { useTransportMirror } from '@renderer/hooks/use-transport-mirror'
import { transport } from '@renderer/lib/transport'
import { EXTERNAL_URLS } from '@shared/external-urls'
@@ -63,6 +64,7 @@ export function SystemProtocolsSection({
refreshRevision = 0,
}: SystemProtocolsSectionProps) {
const { t } = useTranslation()
+ const portable = usePortableMode()
const form = useFormContext<IntegrationFormValues>()
const isWindows = transport.platform === 'win32'
const isLinux = transport.platform === 'linux'
@@ -194,6 +196,13 @@ export function SystemProtocolsSection({
linuxAssociations?.packageKind === 'appimage' && showLinuxButton
const linuxCanSet = linuxAssociations?.canSetTorrentDefault === true
+ if (portable)
+ return (
+ <p className="text-xs text-muted-foreground">
+ {t('settings.portable.integrationUnavailable')}
+ </p>
+ )
+
return (
<div className="space-y-4">
{!isWindows && (
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index f838b6d2..5642126a 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -278,6 +278,8 @@ export function buildServerQueryHandlers(
[Queries.GetDirectoryPreferences]:
createDirectoryPreferencesHandlers(settingsManager).get,
+ [Queries.GetPortableMode]: async () => ({ enabled: false }),
+
[Queries.GetSettings]: async () => ({
...settingsManager.get(),
resolvedLanguage: ctx.getResolvedLanguage(),
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 43d2ccf2..64cc8a13 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -2816,6 +2816,15 @@
"textLength": "استخدم عددًا من المحارف لا يتجاوز {{max}}.",
"time": "استخدم تنسيق 24 ساعة، مثل 23:00.",
"wholeBytes": "استخدم منازل عشرية أقل."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2994,7 +3003,8 @@
"resumeRangeUnsupported": "حُفظ الملف الجزئي لأن الخادم لا يدعم الاستئناف الآمن باستخدام نطاقات البايتات.",
"resumeSourceChanged": "حُفظ الملف الجزئي لأن الملف البعيد تغيّر منذ بدء التنزيل.",
"resumeValidationFailed": "حُفظ الملف الجزئي لأن Motrix لم يتمكن من التحقق من أن الملف البعيد لم يتغيّر.",
- "torrentMetaMissing": "تعذّرت استعادة مهمة BitTorrent هذه: ملف البيانات الوصفية .torrent مفقود. أزل المهمة وأضفها من جديد."
+ "torrentMetaMissing": "تعذّرت استعادة مهمة BitTorrent هذه: ملف البيانات الوصفية .torrent مفقود. أزل المهمة وأضفها من جديد.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "المهام التي انقطعت ثم استُعيدت: {{count}}. انقر للمراجعة."
},
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 920d2c3f..826ed9db 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -2736,6 +2736,15 @@
"textLength": "Използвайте най-много {{max}} знака.",
"time": "Използвайте 24-часов формат, например 23:00.",
"wholeBytes": "Използвайте по-малко десетични знаци."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2910,7 +2919,8 @@
"resumeRangeUnsupported": "Частично изтегленият файл е запазен, тъй като сървърът не поддържа безопасно възобновяване от прекъснатата позиция.",
"resumeSourceChanged": "Частично изтегленият файл е запазен, тъй като отдалеченият файл е променен след началото на изтеглянето.",
"resumeValidationFailed": "Частично изтегленият файл е запазен, тъй като Motrix не успя да провери дали отдалеченият файл е непроменен.",
- "torrentMetaMissing": "Тази BitTorrent задача не може да бъде възстановена: файлът с метаданни .torrent липсва. Премахнете задачата и я добавете отново."
+ "torrentMetaMissing": "Тази BitTorrent задача не може да бъде възстановена: файлът с метаданни .torrent липсва. Премахнете задачата и я добавете отново.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Възстановени прекъснати задачи: {{count}}. Щракнете за преглед."
},
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index b393c382..5da81ff9 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -2756,6 +2756,15 @@
"textLength": "Utilitzeu {{max}} caràcters o menys.",
"time": "Utilitzeu el format de 24 hores, com ara 23:00.",
"wholeBytes": "Utilitzeu menys decimals."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2931,7 +2940,8 @@
"resumeRangeUnsupported": "S'ha conservat el fitxer parcial perquè el servidor no admet reprendre la baixada de manera segura per intervals.",
"resumeSourceChanged": "S'ha conservat el fitxer parcial perquè el fitxer remot ha canviat des que va començar la baixada.",
"resumeValidationFailed": "S'ha conservat el fitxer parcial perquè el Motrix no ha pogut verificar que el fitxer remot no hagi canviat.",
- "torrentMetaMissing": "No es pot recuperar aquesta tasca de BitTorrent: falta el fitxer de metadades .torrent. Suprimiu la tasca i torneu-la a afegir."
+ "torrentMetaMissing": "No es pot recuperar aquesta tasca de BitTorrent: falta el fitxer de metadades .torrent. Suprimiu la tasca i torneu-la a afegir.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Tasques interrompudes recuperades: {{count}}. Feu clic per revisar-les."
},
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index eb917409..5dc20c86 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1174,7 +1174,8 @@
"resumeSourceChanged": "Die unvollständige Datei wurde beibehalten, weil die Datei auf dem Server seit Beginn des Downloads geändert wurde.",
"resumeRangeUnsupported": "Die unvollständige Datei wurde beibehalten, weil der Server keine sichere Fortsetzung über Bereichsanfragen unterstützt.",
"resumeValidationFailed": "Die unvollständige Datei wurde beibehalten, weil Motrix nicht bestätigen konnte, dass die Datei auf dem Server unverändert ist.",
- "mediaInterrupted": "Dieser Mediendownload wurde durch einen Neustart der Anwendung unterbrochen und kann nicht fortgesetzt werden. Fügen Sie ihn erneut hinzu, um es noch einmal zu versuchen."
+ "mediaInterrupted": "Dieser Mediendownload wurde durch einen Neustart der Anwendung unterbrochen und kann nicht fortgesetzt werden. Fügen Sie ihn erneut hinzu, um es noch einmal zu versuchen.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2200,6 +2201,15 @@
"originMismatchBody": "Echtzeitaktualisierungen sind nicht verfügbar. Verwenden Sie die konfigurierte Serveradresse oder bitten Sie die Administration um eine Korrektur.",
"disconnectedTitle": "Die Verbindung für Echtzeitaktualisierungen ist unterbrochen.",
"disconnectedBody": "Einige Informationen werden möglicherweise verzögert angezeigt. Prüfen Sie bei anhaltenden Problemen die Serververbindung und Proxy-Konfiguration."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 516fface..a5e881e2 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -2736,6 +2736,15 @@
"textLength": "Χρησιμοποιήστε έως {{max}} χαρακτήρες.",
"time": "Χρησιμοποιήστε 24ωρη μορφή, όπως 23:00.",
"wholeBytes": "Χρησιμοποιήστε λιγότερα δεκαδικά ψηφία."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2910,7 +2919,8 @@
"resumeRangeUnsupported": "Το μερικό αρχείο διατηρήθηκε επειδή ο διακομιστής δεν υποστηρίζει ασφαλή συνέχιση με εύρη δεδομένων.",
"resumeSourceChanged": "Το μερικό αρχείο διατηρήθηκε επειδή το απομακρυσμένο αρχείο άλλαξε μετά την έναρξη της λήψης.",
"resumeValidationFailed": "Το μερικό αρχείο διατηρήθηκε επειδή το Motrix δεν μπόρεσε να επαληθεύσει ότι το απομακρυσμένο αρχείο δεν άλλαξε.",
- "torrentMetaMissing": "Δεν είναι δυνατή η ανάκτηση αυτής της εργασίας BitTorrent: λείπει το αρχείο μεταδεδομένων .torrent. Αφαιρέστε και προσθέστε ξανά την εργασία."
+ "torrentMetaMissing": "Δεν είναι δυνατή η ανάκτηση αυτής της εργασίας BitTorrent: λείπει το αρχείο μεταδεδομένων .torrent. Αφαιρέστε και προσθέστε ξανά την εργασία.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Διακοπείσες εργασίες που ανακτήθηκαν: {{count}}. Κάντε κλικ για έλεγχο."
},
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 1e4bdc0c..b3bc28e4 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1174,7 +1174,8 @@
"resumeSourceChanged": "The partial file was preserved because the remote file changed since the download started.",
"resumeRangeUnsupported": "The partial file was preserved because the server does not support safe range resume.",
"resumeValidationFailed": "The partial file was preserved because Motrix could not verify that the remote file is unchanged.",
- "mediaInterrupted": "This media download was interrupted by an app restart and can’t be resumed. Re-add it to retry."
+ "mediaInterrupted": "This media download was interrupted by an app restart and can’t be resumed. Re-add it to retry.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2200,6 +2201,15 @@
"originMismatchBody": "Real-time updates are unavailable. Use the configured server address or ask the administrator to correct it.",
"disconnectedTitle": "Real-time updates are disconnected.",
"disconnectedBody": "Some information may be delayed. If this persists, check the server connection and proxy configuration."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 8f2270a2..ad7f51bb 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1188,7 +1188,8 @@
"resumeSourceChanged": "Se conservó el archivo parcial porque el archivo remoto cambió desde que comenzó la descarga.",
"resumeRangeUnsupported": "Se conservó el archivo parcial porque el servidor no permite reanudar de forma segura mediante rangos.",
"resumeValidationFailed": "Se conservó el archivo parcial porque Motrix no pudo comprobar que el archivo remoto sigue igual.",
- "mediaInterrupted": "Esta descarga multimedia se interrumpió al reiniciar la aplicación y no se puede reanudar. Añádela de nuevo para reintentar."
+ "mediaInterrupted": "Esta descarga multimedia se interrumpió al reiniciar la aplicación y no se puede reanudar. Añádela de nuevo para reintentar.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2215,6 +2216,15 @@
"originMismatchBody": "Las actualizaciones en tiempo real no están disponibles. Usa la dirección configurada del servidor o pide al administrador que la corrija.",
"disconnectedTitle": "Las actualizaciones en tiempo real están desconectadas.",
"disconnectedBody": "Parte de la información podría llegar con retraso. Si el problema persiste, comprueba la conexión al servidor y la configuración del proxy."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 22cc837a..663e31aa 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -2736,6 +2736,15 @@
"textLength": "حداکثر {{max}} نویسه استفاده کنید.",
"time": "از قالب 24 ساعته، مانند 23:00، استفاده کنید.",
"wholeBytes": "از رقم‌های اعشاری کمتری استفاده کنید."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2910,7 +2919,8 @@
"resumeRangeUnsupported": "فایل ناقص حفظ شد، زیرا سرور از ادامهٔ ایمن دانلود با درخواست محدوده پشتیبانی نمی‌کند.",
"resumeSourceChanged": "فایل ناقص حفظ شد، زیرا فایل روی سرور از زمان شروع دانلود تغییر کرده است.",
"resumeValidationFailed": "فایل ناقص حفظ شد، زیرا Motrix نتوانست تأیید کند فایل روی سرور تغییر نکرده است.",
- "torrentMetaMissing": "بازیابی این کار BitTorrent ممکن نیست: فایل فرادادهٔ .torrent موجود نیست. کار را حذف و دوباره اضافه کنید."
+ "torrentMetaMissing": "بازیابی این کار BitTorrent ممکن نیست: فایل فرادادهٔ .torrent موجود نیست. کار را حذف و دوباره اضافه کنید.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "{{count}} کار قطع‌شده بازیابی شد. برای بررسی کلیک کنید."
},
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index eff6c44e..ea0a3810 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -2756,6 +2756,15 @@
"textLength": "Utilisez au maximum {{max}} caractères.",
"time": "Utilisez le format 24 heures, par exemple 23:00.",
"wholeBytes": "Utilisez moins de décimales."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2931,7 +2940,8 @@
"resumeRangeUnsupported": "Le fichier partiel a été conservé car le serveur ne permet pas une reprise sécurisée par plages d’octets.",
"resumeSourceChanged": "Le fichier partiel a été conservé car le fichier distant a changé depuis le début du téléchargement.",
"resumeValidationFailed": "Le fichier partiel a été conservé car Motrix n’a pas pu vérifier que le fichier distant était inchangé.",
- "torrentMetaMissing": "Impossible de récupérer cette tâche BitTorrent : le fichier de métadonnées .torrent est absent. Supprimez la tâche et ajoutez-la à nouveau."
+ "torrentMetaMissing": "Impossible de récupérer cette tâche BitTorrent : le fichier de métadonnées .torrent est absent. Supprimez la tâche et ajoutez-la à nouveau.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Tâches interrompues récupérées : {{count}}. Cliquez pour les consulter."
},
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index bfea18d8..65533c13 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1174,7 +1174,8 @@
"resumeSourceChanged": "A részleges fájl megmaradt, mert a távoli fájl a letöltés megkezdése óta megváltozott.",
"resumeRangeUnsupported": "A részleges fájl megmaradt, mert a szerver nem támogatja a biztonságos tartományalapú folytatást.",
"resumeValidationFailed": "A részleges fájl megmaradt, mert a Motrix nem tudta ellenőrizni, hogy a távoli fájl változatlan maradt-e.",
- "mediaInterrupted": "Ezt a médialetöltést az alkalmazás újraindítása megszakította, és nem folytatható. Add hozzá újra az újbóli letöltéshez."
+ "mediaInterrupted": "Ezt a médialetöltést az alkalmazás újraindítása megszakította, és nem folytatható. Add hozzá újra az újbóli letöltéshez.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2200,6 +2201,15 @@
"originMismatchBody": "A valós idejű frissítések nem érhetők el. Használd a beállított szervercímet, vagy kérd meg a rendszergazdát a javítására.",
"disconnectedTitle": "A valós idejű frissítések kapcsolata megszakadt.",
"disconnectedBody": "Egyes információk késve jelenhetnek meg. Ha a probléma továbbra is fennáll, ellenőrizd a szerverkapcsolatot és a proxybeállításokat."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index 8ac79837..2af892e5 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1160,7 +1160,8 @@
"resumeSourceChanged": "Berkas parsial tetap disimpan karena berkas di server telah berubah sejak unduhan dimulai.",
"resumeRangeUnsupported": "Berkas parsial tetap disimpan karena server tidak mendukung pelanjutan unduhan berdasarkan rentang byte secara aman.",
"resumeValidationFailed": "Berkas parsial tetap disimpan karena Motrix tidak dapat memastikan bahwa berkas di server belum berubah.",
- "mediaInterrupted": "Unduhan media ini terputus saat aplikasi dimulai ulang dan tidak dapat dilanjutkan. Tambahkan kembali untuk mencoba lagi."
+ "mediaInterrupted": "Unduhan media ini terputus saat aplikasi dimulai ulang dan tidak dapat dilanjutkan. Tambahkan kembali untuk mencoba lagi.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2185,6 +2186,15 @@
"originMismatchBody": "Pembaruan waktu nyata tidak tersedia. Gunakan alamat server yang dikonfigurasi atau minta administrator memperbaikinya.",
"disconnectedTitle": "Koneksi pembaruan waktu nyata terputus.",
"disconnectedBody": "Beberapa informasi mungkin terlambat diperbarui. Jika masalah berlanjut, periksa koneksi server dan konfigurasi proxy."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index 0129407a..b872e8b2 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1188,7 +1188,8 @@
"resumeSourceChanged": "Il file parziale è stato conservato perché il file remoto è cambiato dall’inizio del download.",
"resumeRangeUnsupported": "Il file parziale è stato conservato perché il server non supporta la ripresa sicura tramite intervalli di byte.",
"resumeValidationFailed": "Il file parziale è stato conservato perché Motrix non ha potuto verificare che il file remoto sia rimasto invariato.",
- "mediaInterrupted": "Questo download multimediale è stato interrotto da un riavvio dell’app e non può essere ripreso. Aggiungilo di nuovo per riprovare."
+ "mediaInterrupted": "Questo download multimediale è stato interrotto da un riavvio dell’app e non può essere ripreso. Aggiungilo di nuovo per riprovare.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2215,6 +2216,15 @@
"originMismatchBody": "Gli aggiornamenti in tempo reale non sono disponibili. Usa l’indirizzo configurato del server o chiedi all’amministratore di correggerlo.",
"disconnectedTitle": "La connessione per gli aggiornamenti in tempo reale è interrotta.",
"disconnectedBody": "Alcune informazioni potrebbero arrivare in ritardo. Se il problema persiste, controlla la connessione al server e la configurazione del proxy."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index a0e0a249..7f8e744d 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1160,7 +1160,8 @@
"resumeSourceChanged": "ダウンロード開始後にサーバー上のファイルが変更されたため、ダウンロード途中のファイルをそのまま保持しました。",
"resumeRangeUnsupported": "サーバーが安全な範囲指定による再開に対応していないため、ダウンロード途中のファイルをそのまま保持しました。",
"resumeValidationFailed": "サーバー上のファイルが変更されていないことを確認できなかったため、ダウンロード途中のファイルをそのまま保持しました。",
- "mediaInterrupted": "このメディアのダウンロードはアプリの再起動により中断されたため、再開できません。再度追加してお試しください。"
+ "mediaInterrupted": "このメディアのダウンロードはアプリの再起動により中断されたため、再開できません。再度追加してお試しください。",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2185,6 +2186,15 @@
"originMismatchBody": "リアルタイム更新を利用できません。設定済みのサーバーアドレスを使用するか、管理者に修正を依頼してください。",
"disconnectedTitle": "リアルタイム更新の接続が切れています。",
"disconnectedBody": "一部の情報の表示が遅れる場合があります。解消しない場合は、サーバーへの接続とプロキシ設定を確認してください。"
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 8f76a483..9889d8b4 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1160,7 +1160,8 @@
"resumeSourceChanged": "다운로드를 시작한 이후 원격 파일이 변경되어 일부 다운로드된 파일을 보존했습니다.",
"resumeRangeUnsupported": "서버가 안전한 범위 기반 다운로드 재개를 지원하지 않아 일부 다운로드된 파일을 보존했습니다.",
"resumeValidationFailed": "원격 파일이 변경되지 않았는지 확인할 수 없어 일부 다운로드된 파일을 보존했습니다.",
- "mediaInterrupted": "앱 재시작으로 이 미디어 다운로드가 중단되었으며 재개할 수 없습니다. 다시 시도하려면 작업을 다시 추가하세요."
+ "mediaInterrupted": "앱 재시작으로 이 미디어 다운로드가 중단되었으며 재개할 수 없습니다. 다시 시도하려면 작업을 다시 추가하세요.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2185,6 +2186,15 @@
"originMismatchBody": "실시간 업데이트를 사용할 수 없습니다. 설정된 서버 주소를 사용하거나 관리자에게 수정을 요청하세요.",
"disconnectedTitle": "실시간 업데이트 연결이 끊겼습니다.",
"disconnectedBody": "일부 정보가 늦게 표시될 수 있습니다. 문제가 계속되면 서버 연결과 프록시 설정을 확인하세요."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 6f223c42..33237a5b 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -2736,6 +2736,15 @@
"textLength": "Bruk høyst {{max}} tegn.",
"time": "Bruk 24-timersformat, for eksempel 23:00.",
"wholeBytes": "Bruk færre desimaler."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2910,7 +2919,8 @@
"resumeRangeUnsupported": "Den delvise filen er beholdt fordi serveren ikke støtter trygg gjenopptakelse med byteområder.",
"resumeSourceChanged": "Den delvise filen er beholdt fordi den eksterne filen har blitt endret siden nedlastingen startet.",
"resumeValidationFailed": "Den delvise filen er beholdt fordi Motrix ikke kunne bekrefte at den eksterne filen er uendret.",
- "torrentMetaMissing": "Kan ikke gjenopprette denne BitTorrent-oppgaven: metadatafilen .torrent mangler. Fjern oppgaven og legg den til på nytt."
+ "torrentMetaMissing": "Kan ikke gjenopprette denne BitTorrent-oppgaven: metadatafilen .torrent mangler. Fjern oppgaven og legg den til på nytt.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Gjenopprettede avbrutte oppgaver: {{count}}. Klikk for å se gjennom dem."
},
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index c70e58a9..3a9bbbfa 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -2736,6 +2736,15 @@
"textLength": "Gebruik maximaal {{max}} tekens.",
"time": "Gebruik een tijd in 24-uursnotatie, zoals 23:00.",
"wholeBytes": "Gebruik minder decimalen."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2910,7 +2919,8 @@
"resumeRangeUnsupported": "Het gedeeltelijke bestand is bewaard omdat de server veilig hervatten met bereikverzoeken niet ondersteunt.",
"resumeSourceChanged": "Het gedeeltelijke bestand is bewaard omdat het externe bestand is gewijzigd sinds de download begon.",
"resumeValidationFailed": "Het gedeeltelijke bestand is bewaard omdat Motrix niet kon controleren of het externe bestand ongewijzigd is.",
- "torrentMetaMissing": "Deze BitTorrent-taak kan niet worden hersteld: het .torrent-metadatabestand ontbreekt. Verwijder de taak en voeg deze opnieuw toe."
+ "torrentMetaMissing": "Deze BitTorrent-taak kan niet worden hersteld: het .torrent-metadatabestand ontbreekt. Verwijder de taak en voeg deze opnieuw toe.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Herstelde onderbroken taken: {{count}}. Klik om ze te bekijken."
},
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 92084163..af5495a6 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1202,7 +1202,8 @@
"resumeSourceChanged": "Zachowano częściowy plik, ponieważ plik zdalny zmienił się od rozpoczęcia pobierania.",
"resumeRangeUnsupported": "Zachowano częściowy plik, ponieważ serwer nie obsługuje bezpiecznego wznawiania za pomocą żądań zakresu.",
"resumeValidationFailed": "Zachowano częściowy plik, ponieważ Motrix nie mógł potwierdzić, że plik zdalny pozostał niezmieniony.",
- "mediaInterrupted": "To pobieranie multimediów zostało przerwane przez ponowne uruchomienie aplikacji i nie można go wznowić. Dodaj zadanie ponownie, aby spróbować jeszcze raz."
+ "mediaInterrupted": "To pobieranie multimediów zostało przerwane przez ponowne uruchomienie aplikacji i nie można go wznowić. Dodaj zadanie ponownie, aby spróbować jeszcze raz.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2230,6 +2231,15 @@
"originMismatchBody": "Aktualizacje w czasie rzeczywistym są niedostępne. Użyj skonfigurowanego adresu serwera lub poproś administratora o jego poprawienie.",
"disconnectedTitle": "Połączenie aktualizacji w czasie rzeczywistym zostało przerwane.",
"disconnectedBody": "Niektóre informacje mogą być opóźnione. Jeśli problem się utrzymuje, sprawdź połączenie z serwerem i konfigurację proxy."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 5bafb9a2..b904fef6 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1188,7 +1188,8 @@
"resumeSourceChanged": "O arquivo parcial foi preservado porque o arquivo remoto mudou desde o início do download.",
"resumeRangeUnsupported": "O arquivo parcial foi preservado porque o servidor não oferece suporte à retomada segura por intervalos de bytes.",
"resumeValidationFailed": "O arquivo parcial foi preservado porque o Motrix não conseguiu verificar se o arquivo remoto permanece inalterado.",
- "mediaInterrupted": "Este download de mídia foi interrompido por uma reinicialização do aplicativo e não pode ser retomado. Adicione-o novamente para tentar de novo."
+ "mediaInterrupted": "Este download de mídia foi interrompido por uma reinicialização do aplicativo e não pode ser retomado. Adicione-o novamente para tentar de novo.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2215,6 +2216,15 @@
"originMismatchBody": "As atualizações em tempo real estão indisponíveis. Use o endereço configurado do servidor ou peça ao administrador para corrigi-lo.",
"disconnectedTitle": "As atualizações em tempo real estão desconectadas.",
"disconnectedBody": "Algumas informações podem estar atrasadas. Se isso persistir, verifique a conexão com o servidor e a configuração do proxy."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index ff4e62d7..51eedff1 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -2756,6 +2756,15 @@
"textLength": "Numărul de caractere nu trebuie să depășească {{max}}.",
"time": "Folosește formatul de 24 de ore, de exemplu 23:00.",
"wholeBytes": "Folosește mai puține zecimale."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2931,7 +2940,8 @@
"resumeRangeUnsupported": "Fișierul parțial a fost păstrat deoarece serverul nu acceptă reluarea sigură prin cereri de intervale de octeți.",
"resumeSourceChanged": "Fișierul parțial a fost păstrat deoarece fișierul de pe server s-a modificat de la începutul descărcării.",
"resumeValidationFailed": "Fișierul parțial a fost păstrat deoarece Motrix nu a putut verifica dacă fișierul de pe server a rămas neschimbat.",
- "torrentMetaMissing": "Această sarcină BitTorrent nu poate fi recuperată: lipsește fișierul de metadate .torrent. Elimină sarcina și adaug-o din nou."
+ "torrentMetaMissing": "Această sarcină BitTorrent nu poate fi recuperată: lipsește fișierul de metadate .torrent. Elimină sarcina și adaug-o din nou.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Sarcini întrerupte recuperate: {{count}}. Apasă pentru a le vedea."
},
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index ded14357..cc1e811e 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1202,7 +1202,8 @@
"resumeSourceChanged": "Частично скачанный файл сохранён, поскольку удалённый файл изменился с начала загрузки.",
"resumeRangeUnsupported": "Частично скачанный файл сохранён, поскольку сервер не поддерживает безопасное возобновление с помощью запросов диапазона.",
"resumeValidationFailed": "Частично скачанный файл сохранён, поскольку Motrix не смог подтвердить, что удалённый файл не изменился.",
- "mediaInterrupted": "Эта загрузка мультимедиа прервана перезапуском приложения, и её невозможно возобновить. Добавьте задачу заново, чтобы повторить попытку."
+ "mediaInterrupted": "Эта загрузка мультимедиа прервана перезапуском приложения, и её невозможно возобновить. Добавьте задачу заново, чтобы повторить попытку.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2230,6 +2231,15 @@
"originMismatchBody": "Обновления в реальном времени недоступны. Используйте настроенный адрес сервера или попросите администратора исправить его.",
"disconnectedTitle": "Соединение для обновлений в реальном времени прервано.",
"disconnectedBody": "Некоторая информация может обновляться с задержкой. Если проблема не исчезнет, проверьте подключение к серверу и настройки прокси."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 2517ad02..334fdb61 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -2716,6 +2716,15 @@
"textLength": "ใช้อักขระไม่เกิน {{max}} ตัว",
"time": "ใช้เวลาแบบ 24 ชั่วโมง เช่น 23:00",
"wholeBytes": "ลดจำนวนตำแหน่งทศนิยม"
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2889,7 +2898,8 @@
"resumeRangeUnsupported": "เก็บไฟล์ที่ดาวน์โหลดบางส่วนไว้ เนื่องจากเซิร์ฟเวอร์ไม่รองรับการดาวน์โหลดต่อตามช่วงข้อมูลอย่างปลอดภัย",
"resumeSourceChanged": "เก็บไฟล์ที่ดาวน์โหลดบางส่วนไว้ เนื่องจากไฟล์บนเซิร์ฟเวอร์เปลี่ยนไปหลังจากเริ่มดาวน์โหลด",
"resumeValidationFailed": "เก็บไฟล์ที่ดาวน์โหลดบางส่วนไว้ เนื่องจาก Motrix ยืนยันไม่ได้ว่าไฟล์บนเซิร์ฟเวอร์ยังไม่เปลี่ยนแปลง",
- "torrentMetaMissing": "กู้คืนงาน BitTorrent นี้ไม่ได้: ไฟล์ข้อมูลเมตา .torrent หายไป โปรดนำงานออกแล้วเพิ่มใหม่"
+ "torrentMetaMissing": "กู้คืนงาน BitTorrent นี้ไม่ได้: ไฟล์ข้อมูลเมตา .torrent หายไป โปรดนำงานออกแล้วเพิ่มใหม่",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "กู้คืนงานที่ถูกขัดจังหวะ {{count}} งานแล้ว คลิกเพื่อตรวจสอบ"
},
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 632bed0e..b486119f 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1174,7 +1174,8 @@
"resumeSourceChanged": "İndirme başladıktan sonra uzak dosya değiştiği için kısmen indirilen dosya korundu.",
"resumeRangeUnsupported": "Sunucu, kalan dosya aralığından güvenle devam etmeyi desteklemediği için kısmen indirilen dosya korundu.",
"resumeValidationFailed": "Motrix uzak dosyanın değişmediğini doğrulayamadığı için kısmen indirilen dosya korundu.",
- "mediaInterrupted": "Uygulama yeniden başlatıldığı için bu medya indirmesi kesintiye uğradı ve sürdürülemiyor. Tekrar denemek için yeniden ekleyin."
+ "mediaInterrupted": "Uygulama yeniden başlatıldığı için bu medya indirmesi kesintiye uğradı ve sürdürülemiyor. Tekrar denemek için yeniden ekleyin.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2200,6 +2201,15 @@
"originMismatchBody": "Gerçek zamanlı güncellemeler kullanılamıyor. Yapılandırılmış sunucu adresini kullanın veya yöneticiden adresi düzeltmesini isteyin.",
"disconnectedTitle": "Gerçek zamanlı güncelleme bağlantısı kesildi.",
"disconnectedBody": "Bazı bilgiler gecikebilir. Sorun sürerse sunucu bağlantısını ve vekil sunucu yapılandırmasını kontrol edin."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index a38f0ccf..bfb895db 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -2776,6 +2776,15 @@
"textLength": "Використайте не більше {{max}} символів.",
"time": "Використайте 24-годинний формат часу, наприклад 23:00.",
"wholeBytes": "Використайте менше десяткових знаків."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"task": {
@@ -2952,7 +2961,8 @@
"resumeRangeUnsupported": "Частково завантажений файл збережено, оскільки сервер не підтримує безпечне продовження за діапазоном байтів.",
"resumeSourceChanged": "Частково завантажений файл збережено, оскільки віддалений файл змінився від початку завантаження.",
"resumeValidationFailed": "Частково завантажений файл збережено, оскільки Motrix не вдалося перевірити, що віддалений файл не змінився.",
- "torrentMetaMissing": "Не вдалося відновити це завдання BitTorrent: файл метаданих .torrent відсутній. Приберіть завдання й додайте його знову."
+ "torrentMetaMissing": "Не вдалося відновити це завдання BitTorrent: файл метаданих .torrent відсутній. Приберіть завдання й додайте його знову.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
},
"toast": "Відновлено перерваних завдань: {{count}}. Натисніть, щоб переглянути."
},
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index fad4a263..505be35c 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1160,7 +1160,8 @@
"resumeSourceChanged": "Tệp tải dở được giữ lại vì tệp trên máy chủ đã thay đổi kể từ khi bắt đầu tải xuống.",
"resumeRangeUnsupported": "Tệp tải dở được giữ lại vì máy chủ không hỗ trợ tải tiếp an toàn từ vị trí đã dừng.",
"resumeValidationFailed": "Tệp tải dở được giữ lại vì Motrix không thể xác minh rằng tệp trên máy chủ chưa thay đổi.",
- "mediaInterrupted": "Lượt tải nội dung đa phương tiện này bị gián đoạn khi ứng dụng khởi động lại và không thể tiếp tục. Hãy thêm lại để thử lại."
+ "mediaInterrupted": "Lượt tải nội dung đa phương tiện này bị gián đoạn khi ứng dụng khởi động lại và không thể tiếp tục. Hãy thêm lại để thử lại.",
+ "portableExternalPath": "This task uses a location outside the portable folder. The application moved or the original directory is unavailable. Check the download location before retrying."
}
},
"error": {
@@ -2185,6 +2186,15 @@
"originMismatchBody": "Không có cập nhật theo thời gian thực. Hãy dùng địa chỉ máy chủ đã cấu hình hoặc nhờ quản trị viên sửa địa chỉ.",
"disconnectedTitle": "Kết nối cập nhật theo thời gian thực đã bị ngắt.",
"disconnectedBody": "Một số thông tin có thể bị trễ. Nếu tình trạng này kéo dài, hãy kiểm tra kết nối máy chủ và cấu hình proxy."
+ },
+ "portable": {
+ "title": "Portable mode",
+ "startupError": "Motrix could not open its portable data directory. Check that the data folder beside Motrix.exe is writable and that no external profile override is set. Motrix has not switched to the system profile.",
+ "integrationUnavailable": "Portable mode keeps system settings unchanged. Startup registration, file associations, and system tool installation are unavailable.",
+ "browserDescription": "The local bridge remains available while Motrix is running. Portable mode does not register a browser launcher or change existing browser integration.",
+ "updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.",
+ "recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.",
+ "enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."
}
},
"errors": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 3bd7d634..76609979 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1160,7 +1160,8 @@
"resumeSourceChanged": "远端文件在下载开始后发生变化,已保留部分文件且未继续写入。",
"resumeRangeUnsupported": "服务器不支持安全的范围续传,已保留部分文件且未继续写入。",
"resumeValidationFailed": "Motrix 无法确认远端文件是否未发生变化,已保留部分文件且未继续写入。",
- "mediaInterrupted": "媒体下载因应用重启而中断,无法恢复。请重新添加以重试。"
+ "mediaInterrupted": "媒体下载因应用重启而中断,无法恢复。请重新添加以重试。",
+ "portableExternalPath": "此任务使用便携目录以外的位置。应用位置已变更或原目录不可用,请确认下载文件的位置后重试。"
}
},
"error": {
@@ -2185,6 +2186,15 @@
"originMismatchBody": "实时更新不可用。请使用服务器配置的访问地址,或联系管理员修正配置。",
"disconnectedTitle": "实时更新连接已中断。",
"disconnectedBody": "部分信息可能延迟。如果持续出现,请检查服务器连接和反向代理配置。"
+ },
+ "portable": {
+ "title": "便携模式",
+ "startupError": "无法打开便携数据目录。请检查 Motrix.exe 同级的 data 文件夹是否可写,并确认未设置外部用户数据目录。Motrix 未切换到系统用户数据目录。",
+ "integrationUnavailable": "便携模式保持系统设置不变,不支持开机启动注册、文件关联和系统工具安装。",
+ "browserDescription": "Motrix 运行时仍可使用本地桥接。便携模式不会注册浏览器启动器,也不会修改已有的浏览器集成。",
+ "updateDescription": "请下载 Windows ZIP,退出 Motrix 后将完整的 data 文件夹移到新版本目录。便携模式不会运行安装程序。",
+ "recoveryError": "无法安全恢复便携数据。请保留 data 文件夹,检查日志和目录权限后重试。Motrix 已停止启动,未使用系统用户数据目录。",
+ "enginePathDescription": "便携模式将引擎状态保存在 data 文件夹内,随应用位置自动管理。"
}
},
"menu": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index b5b27a5f..5d74d069 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1160,7 +1160,8 @@
"resumeSourceChanged": "遠端檔案在下載開始後發生變更,已保留部分檔案且未繼續寫入。",
"resumeRangeUnsupported": "伺服器不支援安全的範圍續傳,已保留部分檔案且未繼續寫入。",
"resumeValidationFailed": "Motrix 無法確認遠端檔案是否未發生變更,已保留部分檔案且未繼續寫入。",
- "mediaInterrupted": "此媒體下載因應用程式重新啟動而中斷,無法繼續。請重新新增後再試。"
+ "mediaInterrupted": "此媒體下載因應用程式重新啟動而中斷,無法繼續。請重新新增後再試。",
+ "portableExternalPath": "此任務使用可攜目錄以外的位置。應用程式位置已變更或原目錄無法使用,請確認下載檔案的位置後重試。"
}
},
"error": {
@@ -2185,6 +2186,15 @@
"originMismatchBody": "即時更新無法使用。請使用伺服器設定的存取位址,或聯絡管理員修正設定。",
"disconnectedTitle": "即時更新連線已中斷。",
"disconnectedBody": "部分資訊可能延遲。如果持續出現,請檢查伺服器連線和反向代理設定。"
+ },
+ "portable": {
+ "title": "可攜模式",
+ "startupError": "無法開啟可攜資料目錄。請檢查 Motrix.exe 同層的 data 資料夾是否可寫入,並確認未設定外部使用者資料目錄。Motrix 未切換至系統使用者資料目錄。",
+ "integrationUnavailable": "可攜模式保持系統設定不變,不支援開機啟動註冊、檔案關聯和系統工具安裝。",
+ "browserDescription": "Motrix 執行時仍可使用本機橋接。可攜模式不會註冊瀏覽器啟動器,也不會修改現有的瀏覽器整合。",
+ "updateDescription": "請下載 Windows ZIP,結束 Motrix 後將完整的 data 資料夾移至新版本目錄。可攜模式不會執行安裝程式。",
+ "recoveryError": "無法安全復原可攜資料。請保留 data 資料夾,檢查記錄和目錄權限後重試。Motrix 已停止啟動,未使用系統使用者資料目錄。",
+ "enginePathDescription": "可攜模式將引擎狀態儲存於 data 資料夾內,隨應用程式位置自動管理。"
}
},
"errors": {
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index b56020b6..665060ce 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -1,4 +1,5 @@
export const Queries = {
+ GetPortableMode: 'query:getPortableMode',
GetGraphicsRecoveryNotice: 'query:getGraphicsRecoveryNotice',
GetRendererSession: 'query:getRendererSession',
GetLegacyImportNavigation: 'query:getLegacyImportNavigation',
diff --git a/src/shared/schemas/portable-mode.ts b/src/shared/schemas/portable-mode.ts
new file mode 100644
index 00000000..5dbecfc9
--- /dev/null
+++ b/src/shared/schemas/portable-mode.ts
@@ -0,0 +1,6 @@
+import { z } from 'zod'
+
+export const portableModeSchema = z.object({
+ enabled: z.boolean(),
+ dataDirectory: z.string().optional(),
+})
diff --git a/src/shared/types/app-update.ts b/src/shared/types/app-update.ts
index 42aecd35..88b29569 100644
--- a/src/shared/types/app-update.ts
+++ b/src/shared/types/app-update.ts
@@ -35,6 +35,7 @@ export interface AppUpdateState {
checkedAt?: string
/** The current installer cannot safely complete an automatic installation. */
manualInstallReason?:
+ | 'portable'
| 'cross-volume'
| 'location-unavailable'
| 'install-failed'
diff --git a/src/shared/types/cli-tool.ts b/src/shared/types/cli-tool.ts
index 8b99d392..15c14b46 100644
--- a/src/shared/types/cli-tool.ts
+++ b/src/shared/types/cli-tool.ts
@@ -27,6 +27,7 @@ export enum CliToolReason {
NodeTooOld = 'node-too-old',
ManagerMissing = 'manager-missing',
Sandboxed = 'sandboxed',
+ Portable = 'portable',
UnsupportedWeb = 'unsupported-web',
Permission = 'permission',
Network = 'network',