Skip to content

A full-featured download manager.

feat(app): unify path display and protect configuration recovery (#2382)

Dr_rOotd4f78d8d0a12
diff --git a/docs/window-size.md b/docs/window-size.md
index 980f6d6d..ea89d2da 100644
--- a/docs/window-size.md
+++ b/docs/window-size.md
@@ -6,8 +6,10 @@ Motrix normally keeps its main window at least 914 × 672 logical pixels. For
tiling window managers or compact desktop layouts, you can override these limits
in the `app` object of `settings.json` in your Motrix user data directory.
-1. Fully quit Motrix, including the tray or menu bar process, before editing.
-2. Add or change these two fields inside the existing `app` object, preserving
+1. Open **Settings → Advanced**. The **Configuration file** section shows the
+ active `settings.json` path; click **Open folder** to locate it.
+2. Fully quit Motrix, including the tray or menu bar process, before editing.
+3. Add or change these two fields inside the existing `app` object, preserving
the other settings:
```json
@@ -19,7 +21,7 @@ in the `app` object of `settings.json` in your Motrix user data directory.
}
```
-3. Save the file and start Motrix again. You can now resize the main window to
+4. Save the file and start Motrix again. You can now resize the main window to
the configured limits; changing the limits does not resize it immediately.
Each value is an integer from 0 to 2147483647. `0` removes Motrix’s minimum for
@@ -34,3 +36,10 @@ configured minimums.
Layouts below the default minimum are not fully adapted: some content may be
clipped or controls crowded. Increase the window size when needed.
+
+If an edit makes the file unreadable as a settings object, Motrix saves the
+original file beside it as `settings.json.corrupt-<timestamp>-<id>.bak` before
+creating a default configuration. If the backup cannot be created, Motrix stops
+recovery without replacing the file. Permission and disk read errors also stop
+loading rather than resetting your settings. Invalid individual fields still
+fall back independently without resetting the whole file.
diff --git a/docs/window-size.zh-CN.md b/docs/window-size.zh-CN.md
index 378c941e..8ddd6a1c 100644
--- a/docs/window-size.zh-CN.md
+++ b/docs/window-size.zh-CN.md
@@ -5,8 +5,9 @@
Motrix 主窗口的默认最小尺寸为 914 × 672 逻辑像素。使用平铺窗口管理器或需要紧凑的桌面布局时,
可以在 Motrix 用户数据目录内的 `settings.json` 中,通过 `app` 对象覆盖这两个限制。
-1. 完全退出 Motrix,包括托盘或菜单栏中的后台进程,然后再编辑配置。
-2. 在已有的 `app` 对象中添加或修改以下两个字段,保留其他设置:
+1. 打开**设置 → 高级**,在**配置文件**一栏查看当前使用的 `settings.json` 路径,点击**打开所在目录**找到文件。
+2. 完全退出 Motrix,包括托盘或菜单栏中的后台进程,然后再编辑配置。
+3. 在已有的 `app` 对象中添加或修改以下两个字段,保留其他设置:
```json
{
@@ -17,7 +18,7 @@ Motrix 主窗口的默认最小尺寸为 914 × 672 逻辑像素。使用平铺
}
```
-3. 保存文件并重新启动 Motrix。此时可以将主窗口缩小到配置的尺寸;修改限制本身不会立即改变窗口大小。
+4. 保存文件并重新启动 Motrix。此时可以将主窗口缩小到配置的尺寸;修改限制本身不会立即改变窗口大小。
每个值均为 0 到 2147483647 之间的整数。`0` 表示取消 Motrix 对应方向的最小尺寸限制,
但操作系统或窗口管理器仍可能施加自己的限制。字段缺失或数值非法时,宽度和高度分别回退至 914 和 672。
@@ -27,3 +28,8 @@ Motrix 主窗口的默认最小尺寸为 914 × 672 逻辑像素。使用平铺
新建任务和首次设置窗口维持原有尺寸。恢复主窗口上次保存的大小时,Motrix 会遵循当前配置的最小尺寸。
低于默认最小尺寸的布局尚未全面适配,部分内容可能被截断,控件也可能比较拥挤。遇到这种情况时请适当放大窗口。
+
+如果编辑后文件无法解析为设置对象,Motrix 会先将原文件备份到同一目录,命名为
+`settings.json.corrupt-<timestamp>-<id>.bak`,然后生成默认配置。如果无法创建备份,
+会停止恢复,不覆盖原文件。权限或磁盘读取错误同样会中止加载,而不会重置设置。
+单个字段值非法时仍只回退该字段,不会重置整个配置文件。
diff --git a/e2e/settings-layout.spec.ts b/e2e/settings-layout.spec.ts
index efd7b3ec..7a43ad74 100644
--- a/e2e/settings-layout.spec.ts
+++ b/e2e/settings-layout.spec.ts
@@ -1,3 +1,4 @@
+import path from 'node:path'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
import type { AppSettings } from '@shared/types/settings'
@@ -51,6 +52,7 @@ test('narrow settings keep readable cards and scroll within the panel', async ({
test('moved settings preserve draft, cancel and save behavior in the desktop host', async ({
mainWindow: page,
+ userDataDir,
}, testInfo) => {
await waitForEngineReady(page)
const read = () =>
@@ -128,6 +130,14 @@ test('moved settings preserve draft, cancel and save behavior in the desktop hos
expect((await read()).geoip.enabled).toBe(!before.geoip.enabled)
expect((await read()).engine.magnetResolveTimeout).toBe(900)
await open('Advanced')
+ const settingsFile = page.getByTitle(
+ path.join(userDataDir, 'settings.json'),
+ { exact: true }
+ )
+ await expect(settingsFile).toBeVisible()
+ await expect(settingsFile).toHaveAttribute('data-slot', 'middle-ellipsis')
+ await expect(page.getByRole('button', { name: 'Open folder' })).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Copy path' })).toHaveCount(0)
const retention = page.getByRole('combobox', {
name: 'Completed recovery records',
})
diff --git a/e2e/settings-recovery.spec.ts b/e2e/settings-recovery.spec.ts
new file mode 100644
index 00000000..cf4b84e8
--- /dev/null
+++ b/e2e/settings-recovery.spec.ts
@@ -0,0 +1,49 @@
+import { readdir, readFile, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
+import { expect, launchMotrix, test } from './fixtures/electron-app'
+
+test('startup preserves a corrupt configuration before creating durable defaults', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ const settingsPath = path.join(userDataDir, 'settings.json')
+ const original = '{"app":{"theme":"dark",\n'
+ await writeFile(settingsPath, original)
+ const backups = async () =>
+ (await readdir(userDataDir)).filter(
+ (name) =>
+ name.startsWith('settings.json.corrupt-') && name.endsWith('.bak')
+ )
+ const readSettings = async () =>
+ JSON.parse(await readFile(settingsPath, 'utf8'))
+ let app = await launchMotrix({ userDataDir, rpcPort })
+ try {
+ await app.firstWindow()
+ const files = await backups()
+ expect(files).toHaveLength(1)
+ expect(await readFile(path.join(userDataDir, files[0]!), 'utf8')).toBe(
+ original
+ )
+ const restored = await readSettings()
+ expect(restored).toMatchObject({
+ version: CURRENT_SETTINGS_VERSION,
+ app: {
+ theme: 'system',
+ mainWindowMinWidth: 914,
+ mainWindowMinHeight: 672,
+ },
+ onboarding: { disclaimerAccepted: false },
+ })
+ expect(restored.engine.rpcSecret).toBeTruthy()
+ await app.close()
+ app = await launchMotrix({ userDataDir, rpcPort })
+ await app.firstWindow()
+ expect((await readSettings()).engine.rpcSecret).toBe(
+ restored.engine.rpcSecret
+ )
+ expect(await backups()).toEqual(files)
+ } finally {
+ await app.close().catch(() => {})
+ }
+})
diff --git a/e2e/web-directory-picker/preferences.browser.ts b/e2e/web-directory-picker/preferences.browser.ts
index e5772778..57f84acf 100644
--- a/e2e/web-directory-picker/preferences.browser.ts
+++ b/e2e/web-directory-picker/preferences.browser.ts
@@ -407,7 +407,14 @@ for (const app of [false, true]) {
const literalPath = parent
.getByRole('button', { name: 'Change directory', exact: true })
.locator('span[dir="ltr"]')
- await expect(literalPath).toHaveText('/downloads/Music')
+ await expect(literalPath).toHaveAttribute('title', '/downloads/Music')
+ expect(
+ (
+ await literalPath
+ .locator(':scope > [aria-hidden="true"]')
+ .allTextContents()
+ ).join('')
+ ).toBe('/downloads/Music')
await expect(literalPath).toHaveCSS('direction', 'ltr')
await expect(trigger).toBeFocused()
expect(await parentSubmissions(page)).toHaveLength(0)
@@ -1036,13 +1043,18 @@ test('narrow Downloads directory fields stay compact with centered rows, full pa
.filter((rect) => rect.width > 0 && rect.height > 0)
const centers = children.map((rect) => rect.y + rect.height / 2)
const text = element.querySelector('[title]') as HTMLElement
+ const visiblePath = [
+ ...text.querySelectorAll(':scope > [aria-hidden="true"]'),
+ ]
+ .map((fragment) => fragment.textContent)
+ .join('')
return {
height: element.getBoundingClientRect().height,
right: element.getBoundingClientRect().right,
dialogRight:
element.closest('[role="dialog"]')?.getBoundingClientRect().right ?? 0,
centerSpread: Math.max(...centers) - Math.min(...centers),
- truncated: text.scrollWidth > text.clientWidth,
+ truncated: visiblePath.includes('…') && visiblePath !== text.title,
}
})
await test.info().attach('compact-directory-row-metrics', {
diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.ts
index 6684bc53..54b5326c 100644
--- a/src/core/settings/settings-manager.test.ts
+++ b/src/core/settings/settings-manager.test.ts
@@ -1,3 +1,4 @@
+import { constants } from 'node:fs'
import { resolveByteUnitSystem } from '@shared/schemas/byte-unit-system'
import type { AppSettings, DashboardTileLayout } from '@shared/types/settings'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -13,23 +14,31 @@ import {
dashboardLayoutSettingsSchema,
} from './validators'
-const { mockReadFile, mockWriteFile, mockMkdir, mockWriteFileAtomic } =
- vi.hoisted(() => ({
- mockReadFile: vi.fn(),
- mockWriteFile: vi.fn(),
- mockMkdir: vi.fn(),
- mockWriteFileAtomic: vi.fn(),
- }))
+const {
+ mockReadFile,
+ mockWriteFile,
+ mockMkdir,
+ mockWriteFileAtomic,
+ mockCopyFile,
+} = vi.hoisted(() => ({
+ mockReadFile: vi.fn(),
+ mockWriteFile: vi.fn(),
+ mockMkdir: vi.fn(),
+ mockWriteFileAtomic: vi.fn(),
+ mockCopyFile: vi.fn(),
+}))
vi.mock('node:fs/promises', () => ({
default: {
readFile: mockReadFile,
writeFile: mockWriteFile,
mkdir: mockMkdir,
+ copyFile: mockCopyFile,
},
readFile: mockReadFile,
writeFile: mockWriteFile,
mkdir: mockMkdir,
+ copyFile: mockCopyFile,
}))
// Atomic save lives in write-file-atomic now. Existing tests assert
@@ -64,6 +73,7 @@ describe('SettingsManager', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockCopyFile.mockReset().mockResolvedValue(undefined)
manager = new SettingsManager(TEST_PATH, { onChange })
})
@@ -445,7 +455,9 @@ describe('SettingsManager', () => {
manager = new SettingsManager(TEST_PATH, {
defaultByteUnitSystem: unitSystem,
})
- mockedFs.readFile.mockRejectedValue(new Error('ENOENT'))
+ mockedFs.readFile.mockRejectedValue(
+ Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
+ )
mockedFs.writeFile.mockResolvedValue(undefined)
await manager.load()
expect(manager.get().speedLimit).toMatchObject({
@@ -800,13 +812,56 @@ describe('SettingsManager', () => {
expect(manager.getEngine().magnetResolveTimeout).toBe(900)
})
- it('falls back to defaults on corrupted JSON', async () => {
+ it.each(['EACCES', 'EIO', 'EISDIR'])(
+ 'preserves the file and surfaces read failure %s without recovery writes',
+ async (code) => {
+ const error = Object.assign(new Error(code), { code })
+ mockReadFile.mockRejectedValue(error)
+ await expect(manager.load()).rejects.toBe(error)
+ expect(mockCopyFile).not.toHaveBeenCalled()
+ expect(mockWriteFileAtomic).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['EACCES', 'ENOSPC', 'EEXIST'])(
+ 'does not replace a damaged file if its backup fails with %s',
+ async (code) => {
+ mockReadFile.mockResolvedValue('{broken')
+ const error = Object.assign(new Error(code), { code })
+ mockCopyFile.mockRejectedValueOnce(error)
+ await expect(manager.load()).rejects.toBe(error)
+ expect(mockWriteFileAtomic).not.toHaveBeenCalled()
+ }
+ )
+
+ it('keeps the backup when writing the recovered defaults fails', async () => {
+ mockReadFile.mockResolvedValue('{broken')
+ const error = Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' })
+ mockWriteFileAtomic.mockRejectedValueOnce(error)
+ await expect(manager.load()).rejects.toBe(error)
+ expect(mockCopyFile).toHaveBeenCalledOnce()
+ expect(mockWriteFileAtomic).toHaveBeenCalledOnce()
+ expect(mockCopyFile.mock.invocationCallOrder[0]).toBeLessThan(
+ mockWriteFileAtomic.mock.invocationCallOrder[0]!
+ )
+ })
+
+ it('backs up corrupted JSON before replacing it with defaults', async () => {
mockedFs.readFile.mockResolvedValue('not valid json {{{')
mockedFs.mkdir.mockResolvedValue(undefined)
mockedFs.writeFile.mockResolvedValue(undefined)
await manager.load()
+ expect(mockCopyFile).toHaveBeenCalledWith(
+ TEST_PATH,
+ expect.stringMatching(/test-settings\.json\.corrupt-.+\.bak$/),
+ constants.COPYFILE_EXCL
+ )
+ expect(mockCopyFile.mock.invocationCallOrder[0]).toBeLessThan(
+ mockWriteFileAtomic.mock.invocationCallOrder[0]!
+ )
+
const settings = manager.get()
expect(settings.version).toBe(CURRENT_SETTINGS_VERSION)
expect(settings.engine).toEqual(
diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.ts
index 231b1b32..c246a40e 100644
--- a/src/core/settings/settings-manager.ts
+++ b/src/core/settings/settings-manager.ts
@@ -1,7 +1,9 @@
import { randomUUID } from 'node:crypto'
-import { mkdir, readFile } from 'node:fs/promises'
+import { constants } from 'node:fs'
+import { copyFile, mkdir, readFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
+import { getLogger } from '@core/logger'
import { ENGINE_PERFORMANCE_TUNING_KEYS } from '@shared/constants/engine-performance-profiles'
import {
APP_RESTART_REQUIRED_KEYS,
@@ -206,13 +208,25 @@ export class SettingsManager {
this.onChange = opts?.onChange
}
+ getFilePath(): string {
+ return this.filePath
+ }
+
async load(): Promise<void> {
+ let raw: string
+ try {
+ raw = await readFile(this.filePath, 'utf-8')
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ await this.initializeDefaultFile()
+ return
+ }
+
let parsed: Record<string, unknown>
let seedMissingRpcSecret = true
let seedMissingSpeedLimit = false
try {
- const raw = await readFile(this.filePath, 'utf-8')
const decoded: unknown = JSON.parse(raw)
if (!isPlainObject(decoded)) {
throw new Error('settings root must be an object')
@@ -226,13 +240,16 @@ export class SettingsManager {
seedMissingSpeedLimit = migrated.speedLimit == null
this.settings = this.buildValidSettings(migrated as Partial<AppSettings>)
} catch {
- // File missing, corrupt, or unreadable — use defaults
- this.settings = createDefaultSettings(
- this.liquidGlassEffectDefault,
- this.defaultByteUnitSystem
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
+ const backupPath = `${this.filePath}.corrupt-${timestamp}-${randomUUID()}.bak`
+ // Preserve the original bytes before replacing the active file. A failed
+ // backup must leave the original untouched, including on name collision.
+ await copyFile(this.filePath, backupPath, constants.COPYFILE_EXCL)
+ getLogger('settings').warn(
+ { backupPath },
+ 'invalid settings file backed up; restoring defaults'
)
- this.seedSentinels(true)
- await this.save()
+ await this.initializeDefaultFile()
return
}
@@ -248,6 +265,15 @@ export class SettingsManager {
}
}
+ private async initializeDefaultFile(): Promise<void> {
+ this.settings = createDefaultSettings(
+ this.liquidGlassEffectDefault,
+ this.defaultByteUnitSystem
+ )
+ this.seedSentinels(true)
+ await this.save()
+ }
+
private seedSentinels(seedMissingRpcSecret: boolean): boolean {
let changed = false
if (seedMissingRpcSecret && this.settings.engine.rpcSecret === '') {
diff --git a/src/core/settings/settings-recovery.test.ts b/src/core/settings/settings-recovery.test.ts
new file mode 100644
index 00000000..3cb032bf
--- /dev/null
+++ b/src/core/settings/settings-recovery.test.ts
@@ -0,0 +1,83 @@
+import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { CURRENT_SETTINGS_VERSION } from './migrations'
+import { SettingsManager } from './settings-manager'
+
+const temporary: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporary.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
+ )
+})
+
+async function fixture() {
+ const dir = await mkdtemp(path.join(tmpdir(), 'motrix-settings-recovery-'))
+ temporary.push(dir)
+ return { dir, file: path.join(dir, 'settings.json') }
+}
+
+describe('settings file recovery', () => {
+ it.each(['{bad json', 'null', '[]', '42', '"text"'])(
+ 'preserves the original bytes and restarts from persisted defaults for %s',
+ async (content) => {
+ const { dir, file } = await fixture()
+ const original = Buffer.from(content)
+ await writeFile(file, original)
+ const manager = new SettingsManager(file)
+ await manager.load()
+ const backups = (await readdir(dir)).filter((name) =>
+ name.endsWith('.bak')
+ )
+ expect(backups).toHaveLength(1)
+ expect(await readFile(path.join(dir, backups[0]!))).toEqual(original)
+ const recovered = JSON.parse(await readFile(file, 'utf8'))
+ expect(recovered.version).toBe(CURRENT_SETTINGS_VERSION)
+ expect(recovered.engine.rpcSecret).toBeTruthy()
+ expect(recovered.onboarding.disclaimerAccepted).toBe(false)
+ const restarted = new SettingsManager(file)
+ await restarted.load()
+ expect(restarted.get()).toEqual(manager.get())
+ expect(
+ (await readdir(dir)).filter((name) => name.endsWith('.bak'))
+ ).toEqual(backups)
+ }
+ )
+
+ it('keeps separate backups across repeated recovery attempts', async () => {
+ const { dir, file } = await fixture()
+ for (const content of ['first broken file', 'second broken file']) {
+ await writeFile(file, content)
+ await new SettingsManager(file).load()
+ }
+ const backups = (await readdir(dir)).filter((name) => name.endsWith('.bak'))
+ expect(backups).toHaveLength(2)
+ expect(
+ await Promise.all(
+ backups.map((name) => readFile(path.join(dir, name), 'utf8'))
+ )
+ ).toEqual(
+ expect.arrayContaining(['first broken file', 'second broken file'])
+ )
+ })
+
+ it('does not back up a new profile or discard valid fields for an invalid field value', async () => {
+ const { dir, file } = await fixture()
+ const manager = new SettingsManager(file)
+ await manager.load()
+ expect(await readdir(dir)).toEqual(['settings.json'])
+ const settings = JSON.parse(await readFile(file, 'utf8'))
+ settings.app.theme = 'dark'
+ settings.app.mainWindowMinWidth = -1
+ await writeFile(file, JSON.stringify(settings))
+ await manager.load()
+ expect(manager.getApp()).toMatchObject({
+ theme: 'dark',
+ mainWindowMinWidth: 914,
+ })
+ expect(manager.getEngine().rpcSecret).toBe(settings.engine.rpcSecret)
+ expect(await readdir(dir)).toEqual(['settings.json'])
+ })
+})
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 33b0d1f4..2c8aa4be 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -315,6 +315,26 @@ function fakeCtx() {
}
describe('buildCommandHandlers', () => {
+ it('opens only the active settings directory and reports shell failures', async () => {
+ const ctx = fakeCtx()
+ const handler = buildCommandHandlers({
+ ...ctx,
+ settingsManager: {
+ ...ctx.settingsManager,
+ getFilePath: () => '/custom profile/settings.json',
+ },
+ } as unknown as CommandContext)[Commands.OpenSettingsDirectory]!
+ openPathMock.mockReset().mockResolvedValue('')
+ await expect(handler({ path: '/unrelated' })).rejects.toThrow()
+ expect(openPathMock).not.toHaveBeenCalled()
+ await expect(handler()).resolves.toBe(true)
+ expect(openPathMock).toHaveBeenCalledExactlyOnceWith('/custom profile')
+ openPathMock.mockResolvedValueOnce('No file manager available')
+ await expect(handler()).resolves.toBe(false)
+ openPathMock.mockRejectedValueOnce(new Error('Shell unavailable'))
+ await expect(handler()).rejects.toThrow('Shell unavailable')
+ })
+
it('downloads registry packages through the injected plugin transport and serializes failures', async () => {
const dir = await mkdtemp(path.join(tmpdir(), 'plugin-network-command-'))
try {
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index dbcfaed9..24e7850c 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -1078,6 +1078,14 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
}
),
+ [Commands.OpenSettingsDirectory]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ const error = await shell.openPath(
+ path.dirname(settingsManager.getFilePath())
+ )
+ return error === ''
+ },
+
[Commands.UpdateSettings]: async (partial: unknown) => {
const oldFull = settingsManager.get()
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index 894775a5..846ca95d 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -316,6 +316,20 @@ describe('buildQueryHandlers', () => {
expect(getSyncStatus).toHaveBeenCalledOnce()
})
+ it('returns the active settings file instead of inferring it from the data directory', async () => {
+ const handlers = buildQueryHandlers({
+ userDataDir: '/default/profile',
+ settingsManager: {
+ getFilePath: () => '/custom profile/settings.json',
+ },
+ } as unknown as QueryContext)
+ await expect(
+ handlers[Queries.GetSettingsFileLocation]?.()
+ ).resolves.toEqual({
+ path: '/custom profile/settings.json',
+ })
+ })
+
it('returns the committed locale separately from a saved system preference', async () => {
const settings = { app: { language: 'system' } }
let resolved = 'fr'
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 787366b2..18c2ebfe 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -182,6 +182,9 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
createDirectoryPreferencesHandlers(settingsManager).get,
[Queries.GetSystemAccentColor]: async () => getSystemAccentColor(),
+ [Queries.GetSettingsFileLocation]: async () => ({
+ path: settingsManager.getFilePath(),
+ }),
[Queries.GetSettings]: async () => {
return {
...settingsManager.get(),
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 19578859..af469566 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -42,7 +42,13 @@ import {
type TorrentBatchCreateResult,
type TorrentQueueAdvanceResult,
} from '@shared/schemas/add-task'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react'
import {
type DeepPartial,
FormProvider,
@@ -163,7 +169,8 @@ export function AddTaskForm({
})
const dirty = form.formState.isDirty
- useEffect(() => {
+ // Publish draft protection before the next key can close the host surface.
+ useLayoutEffect(() => {
onDraftStateChange?.(
dirty,
submitting || batchSubmitting || advancingTorrent
diff --git a/src/renderer/components/desktop-kit/directory-history-menu.test.tsx b/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
index babdca90..4c75396c 100644
--- a/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
+++ b/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
@@ -100,7 +100,9 @@ describe('DirectoryHistoryMenu', () => {
expect(mocks.appHook).toHaveBeenCalled()
expect(mocks.serverHook).not.toHaveBeenCalled()
expect(
- screen.getAllByRole('menuitem').map((item) => item.textContent)
+ screen
+ .getAllByRole('menuitem')
+ .map((item) => item.getAttribute('title') ?? item.textContent)
).toEqual(['/favorite', '/recent ', '/current', 'Manage directories'])
expect(screen.getByRole('menuitem', { name: '/current' })).toHaveAttribute(
'aria-current',
diff --git a/src/renderer/components/desktop-kit/directory-history-menu.tsx b/src/renderer/components/desktop-kit/directory-history-menu.tsx
index 97e6626f..88a090ad 100644
--- a/src/renderer/components/desktop-kit/directory-history-menu.tsx
+++ b/src/renderer/components/desktop-kit/directory-history-menu.tsx
@@ -1,3 +1,4 @@
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import {
CheckIcon,
DirectoryPreferencesIcon,
@@ -209,9 +210,11 @@ function HistoryItems({
<span className="size-4 shrink-0">
{path === currentPath && <CheckIcon aria-hidden="true" />}
</span>
- <span className="min-w-0 whitespace-pre-wrap break-all">
- {path}
- </span>
+ <MiddleEllipsis
+ text={path}
+ maxChars={72}
+ className="font-sans!"
+ />
</DropdownMenuItem>
))}
</DropdownMenuGroup>
diff --git a/src/renderer/components/desktop-kit/directory-picker.tsx b/src/renderer/components/desktop-kit/directory-picker.tsx
index 5514dd0b..62e71b7f 100644
--- a/src/renderer/components/desktop-kit/directory-picker.tsx
+++ b/src/renderer/components/desktop-kit/directory-picker.tsx
@@ -1,3 +1,4 @@
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import {
CheckIcon,
ChevronRightIcon,
@@ -274,14 +275,30 @@ export function DirectoryPicker<TFields extends FieldValues>({
dir={current ? 'ltr' : undefined}
className="block truncate text-sm font-medium"
>
- {filename || placeholder || t('directoryPicker.file.choose')}
+ {filename ? (
+ <MiddleEllipsis
+ text={filename}
+ maxChars={64}
+ className="font-sans!"
+ />
+ ) : (
+ placeholder || t('directoryPicker.file.choose')
+ )}
</span>
{description && (save || description !== actionLabel) && (
<span
dir={current ? 'ltr' : undefined}
className="block truncate text-xs leading-5 text-muted-foreground"
>
- {description}
+ {directory ? (
+ <MiddleEllipsis
+ text={directory}
+ maxChars={64}
+ className="font-sans!"
+ />
+ ) : (
+ description
+ )}
</span>
)}
</span>
@@ -316,12 +333,11 @@ export function DirectoryPicker<TFields extends FieldValues>({
</span>
)}
{current ? (
- <span
- dir="ltr"
- className="min-w-0 flex-1 truncate text-start text-xs text-foreground"
- >
- {current}
- </span>
+ <MiddleEllipsis
+ text={current}
+ maxChars={64}
+ className="min-w-0 flex-1 text-start font-sans! text-xs text-foreground"
+ />
) : (
<span className="min-w-0 flex-1 truncate text-xs italic text-muted-foreground">
{placeholder ?? t('settings.common.directoryEmpty')}
diff --git a/src/renderer/components/desktop-kit/middle-ellipsis.test.tsx b/src/renderer/components/desktop-kit/middle-ellipsis.test.tsx
index 1a9d623f..fa1e7b3f 100644
--- a/src/renderer/components/desktop-kit/middle-ellipsis.test.tsx
+++ b/src/renderer/components/desktop-kit/middle-ellipsis.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom/vitest'
-import { render } from '@testing-library/react'
-import { describe, expect, it } from 'vitest'
+import { fireEvent, render } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
import { MiddleEllipsis } from './middle-ellipsis'
describe('MiddleEllipsis', () => {
@@ -12,7 +12,7 @@ describe('MiddleEllipsis', () => {
'\\\\server\\share\\工具\\ffmpeg.exe',
'/data/👩‍💻/e\u0301/ffmpeg',
])('keeps full accessible and tooltip text for %s', (text) => {
- const { container } = render(<MiddleEllipsis text={text} />)
+ const { container } = render(<MiddleEllipsis text={text} maxChars={512} />)
const root = container.querySelector('[data-slot="middle-ellipsis"]')
expect(root).toHaveAttribute('title', text)
expect(root).toHaveAttribute('dir', 'ltr')
@@ -34,4 +34,19 @@ describe('MiddleEllipsis', () => {
expect(fragments[0]).toHaveTextContent('a👩‍💻')
expect(fragments[1]).toHaveTextContent('b')
})
+
+ it('limits visible characters while preserving the full tooltip, accessible text and clipboard', () => {
+ const text = '/one/two/three/file.txt'
+ const { container } = render(<MiddleEllipsis text={text} maxChars={16} />)
+ const root = container.querySelector('[data-slot="middle-ellipsis"]')!
+ const fragments = root.querySelectorAll(':scope > [aria-hidden="true"]')
+ expect(
+ Array.from(fragments, (element) => element.textContent).join('')
+ ).toBe('/one/t…/file.txt')
+ expect(root).toHaveAttribute('title', text)
+ expect(root.querySelector('.sr-only')).toHaveTextContent(text)
+ const setData = vi.fn()
+ fireEvent.copy(root, { clipboardData: { setData } })
+ expect(setData).toHaveBeenCalledWith('text/plain', text)
+ })
})
diff --git a/src/renderer/components/desktop-kit/middle-ellipsis.tsx b/src/renderer/components/desktop-kit/middle-ellipsis.tsx
index 93fe0d5d..9f8f7df7 100644
--- a/src/renderer/components/desktop-kit/middle-ellipsis.tsx
+++ b/src/renderer/components/desktop-kit/middle-ellipsis.tsx
@@ -1,45 +1,54 @@
import { cn } from '@renderer/lib/utils'
-
-const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
+import { getPathDisplayParts } from '@shared/lib/path-display'
/** Keep both ends visible without reversing path text or measuring layout. */
export function MiddleEllipsis({
text,
className,
+ maxChars = 64,
+ dir = 'ltr',
}: {
text: string
className?: string
+ maxChars?: number
+ dir?: 'ltr' | 'rtl' | 'auto'
}) {
- const characters = Array.from(
- segmenter.segment(text),
- ({ segment }) => segment
- )
- const middle = Math.ceil(characters.length / 2)
+ const { start, ellipsis, end } = getPathDisplayParts(text, maxChars)
return (
<span
data-slot="middle-ellipsis"
- dir="ltr"
+ dir={dir}
title={text}
+ onCopy={(event) => {
+ event.clipboardData.setData('text/plain', text)
+ event.preventDefault()
+ }}
className={cn(
- 'inline-flex min-w-0 max-w-full align-bottom font-mono',
+ 'inline-flex min-w-0 max-w-full select-text align-bottom font-mono',
className
)}
>
<span className="sr-only">{text}</span>
<span
aria-hidden="true"
- className="min-w-0 shrink truncate whitespace-pre"
+ className={cn(
+ 'min-w-0 shrink whitespace-pre',
+ ellipsis ? 'overflow-hidden' : 'truncate'
+ )}
>
- {characters.slice(0, middle).join('')}
+ {start}
</span>
+ {ellipsis && (
+ <span aria-hidden="true" className="shrink-0">
+ {ellipsis}
+ </span>
+ )}
<span
aria-hidden="true"
className="flex min-w-0 shrink justify-end overflow-hidden"
>
- <span className="shrink-0 whitespace-pre">
- {characters.slice(middle).join('')}
- </span>
+ <span className="shrink-0 whitespace-pre">{end}</span>
</span>
</span>
)
diff --git a/src/renderer/components/file-list/file-list.test.tsx b/src/renderer/components/file-list/file-list.test.tsx
index 1461efc7..8dd8909e 100644
--- a/src/renderer/components/file-list/file-list.test.tsx
+++ b/src/renderer/components/file-list/file-list.test.tsx
@@ -87,11 +87,8 @@ describe('FileList', () => {
expect(screen.getByText('File type')).toBeInTheDocument()
for (const [path, extension] of cases) {
- const row = screen.getByText(path).parentElement!
- expect(within(row).getByText(extension)).toHaveAttribute(
- 'title',
- extension
- )
+ const row = screen.getByRole('checkbox', { name: path }).parentElement!
+ expect(within(row).getByTitle(extension)).toHaveTextContent(extension)
}
})
@@ -120,7 +117,7 @@ describe('FileList', () => {
/>
)
- const fileName = screen.getByText(path)
+ const fileName = screen.getByTitle(path)
expect(fileName).toHaveAttribute('dir', 'auto')
expect(fileName).not.toHaveClass('[direction:rtl]')
})
diff --git a/src/renderer/components/file-list/file-list.tsx b/src/renderer/components/file-list/file-list.tsx
index 49632022..ec79468f 100644
--- a/src/renderer/components/file-list/file-list.tsx
+++ b/src/renderer/components/file-list/file-list.tsx
@@ -1,3 +1,4 @@
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import { VirtualList } from '@renderer/components/desktop-kit/virtual-list/virtual-list'
import { Checkbox } from '@renderer/components/ui/checkbox'
import { useByteFormat } from '@renderer/hooks/use-byte-format'
@@ -145,13 +146,12 @@ export function FileList<T extends BaseFileRow = BaseFileRow>({
disabled={readOnly}
aria-label={file.path}
/>
- <span
- className="min-w-0 flex-1 truncate text-xs"
+ <MiddleEllipsis
+ text={file.path}
dir="auto"
- title={file.path}
- >
- {file.path}
- </span>
+ maxChars={80}
+ className="min-w-0 flex-1 font-sans! text-xs"
+ />
<span
className="w-14 shrink-0 truncate text-xs text-muted-foreground"
dir="ltr"
diff --git a/src/renderer/features/directory-preferences/directory-preferences-section.tsx b/src/renderer/features/directory-preferences/directory-preferences-section.tsx
index 90536ca5..ae199ff7 100644
--- a/src/renderer/features/directory-preferences/directory-preferences-section.tsx
+++ b/src/renderer/features/directory-preferences/directory-preferences-section.tsx
@@ -1,3 +1,4 @@
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import {
ChevronRightIcon,
FavoriteIcon,
@@ -161,13 +162,11 @@ export function DirectoryPreferencesSection({
return (
<li key={path} className="flex items-center gap-2 px-2 py-1">
<FolderIcon className="size-4 shrink-0 text-muted-foreground" />
- <span
- dir="ltr"
- title={path}
- className="min-w-0 flex-1 truncate text-xs whitespace-pre"
- >
- {path}
- </span>
+ <MiddleEllipsis
+ text={path}
+ maxChars={64}
+ className="min-w-0 flex-1 font-sans! text-xs"
+ />
{recent && (
<Button
type="button"
diff --git a/src/renderer/features/legacy-import/legacy-fresh-download.tsx b/src/renderer/features/legacy-import/legacy-fresh-download.tsx
index 7860e3d3..0ab62184 100644
--- a/src/renderer/features/legacy-import/legacy-fresh-download.tsx
+++ b/src/renderer/features/legacy-import/legacy-fresh-download.tsx
@@ -1,3 +1,4 @@
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import {
AlertDialog,
AlertDialogContent,
@@ -102,8 +103,12 @@ export function LegacyFreshDownload({ task }: { task: DownloadTask }) {
<p className="text-xs leading-5 text-muted-foreground">
{t('legacyImport.verifyDescription')}
</p>
- <p className="break-all text-xs">
- {availability?.directory ?? task.saveDir}
+ <p className="min-w-0 text-xs">
+ <MiddleEllipsis
+ text={availability?.directory ?? task.saveDir}
+ maxChars={64}
+ className="font-sans!"
+ />
</p>
<Button
size="sm"
diff --git a/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
index 451ab8ea..e470c02a 100644
--- a/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
+++ b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
@@ -1,3 +1,4 @@
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import type { VirtualListHandle } from '@renderer/components/desktop-kit/virtual-list/types'
import { VirtualList } from '@renderer/components/desktop-kit/virtual-list/virtual-list'
import {
@@ -45,6 +46,7 @@ import {
__webPathPickerBus,
type PickRequest,
} from '@renderer/platform/web-services'
+import { truncatePath } from '@shared/lib/path-display'
import {
type KeyboardEvent,
memo,
@@ -528,9 +530,17 @@ function PickerSession({ request, controller }: Session) {
) : (
<FolderIcon className="size-4 shrink-0 text-muted-foreground" />
)}
- <span dir="ltr" className="truncate whitespace-pre">
- {entry.name}
- </span>
+ {entry.name === entry.path ? (
+ <MiddleEllipsis
+ text={entry.path}
+ maxChars={48}
+ className="font-sans!"
+ />
+ ) : (
+ <span dir="ltr" className="truncate whitespace-pre">
+ {entry.name}
+ </span>
+ )}
</Button>
))}
</div>
@@ -937,8 +947,12 @@ function PickerSession({ request, controller }: Session) {
key={entry.path}
value={entry.path}
disabled={locationPending(entry.path)}
+ title={entry.path}
+ aria-label={entry.name}
>
- {entry.name}
+ {entry.name === entry.path
+ ? truncatePath(entry.path, 48)
+ : entry.name}
</option>
))}
</optgroup>
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
index 298f8714..17363b10 100644
--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
@@ -9,6 +9,7 @@ import {
DialogTitle,
} from '@renderer/components/ui/dialog'
import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import { truncatePath } from '@shared/lib/path-display'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
import { useEffect, useId, useRef, useState } from 'react'
@@ -30,24 +31,13 @@ const HAS_OUTPUT_STATES: ReadonlySet<TaskStatus> = new Set([
TaskStatus.Downloading,
])
-// Middle ellipsis: keep the head and the tail (so the file extension stays
-// visible) and collapse the middle. A plain end-cut silently dropped the
-// extension, e.g. "...x265-NeoNoir.mkv" became "...x265-NeoNoir.mk".
-function middleEllipsis(s: string, max: number): string {
- if (s.length <= max) return s
- const ellipsis = '…'
- const head = Math.ceil((max - ellipsis.length) / 2)
- const tail = Math.floor((max - ellipsis.length) / 2)
- return s.slice(0, head) + ellipsis + s.slice(s.length - tail)
-}
-
function buildTitle(
selected: readonly DownloadTask[],
t: ReturnType<typeof useTranslation>['t']
): string {
if (selected.length === 1) {
return t('panel.downloads.action.removeSingleTitle', {
- name: middleEllipsis(selected[0].name, 60),
+ name: truncatePath(selected[0].name, 60),
})
}
const statuses = new Set(selected.map((task) => task.status))
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsx
index 8ac1087d..750be5e9 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx
@@ -1,5 +1,6 @@
import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
import { InspectorDrawer } from '@renderer/components/desktop-kit/inspector-drawer'
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
import {
ActivityIcon,
@@ -153,9 +154,11 @@ export function TaskInspectorDrawer({
}
>
<DiskIcon className="me-1 size-3.5 shrink-0 text-muted-foreground" />
- <span className="truncate">
- {single.finalPath || single.diskPath}
- </span>
+ <MiddleEllipsis
+ text={single.finalPath || single.diskPath}
+ maxChars={64}
+ className="font-sans!"
+ />
</Button>
<CopyButton
variant="ghost"
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
index c9d0539c..cc890644 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
@@ -45,6 +45,8 @@ describe('<AdvancedDialog>', () => {
vi.mocked(transport.invoke).mockReset()
vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
if (channel === Queries.GetSettings) return SETTINGS_FIXTURE
+ if (channel === Queries.GetSettingsFileLocation)
+ return { path: '/profile/settings.json' }
return { saved: true, requiresRestart: false, changedRestartKeys: [] }
})
})
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.tsx b/src/renderer/routes/settings/cards/advanced-dialog.tsx
index 422cb40e..ee3fdaa3 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.tsx
@@ -55,6 +55,7 @@ import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router'
import type { SettingsCardDialogProps } from './card-types'
+import { SettingsFileSection } from './settings-file-section'
import { advancedFormSchema } from './settings-form-schemas'
type HistoryRetentionMode = 'all' | 'limited' | 'session'
@@ -497,6 +498,8 @@ export function AdvancedDialog({
</fieldset>
</form>
</Form>
+ <Separator className="my-4" />
+ {open && <SettingsFileSection />}
{__MOTRIX_TARGET__ === 'electron' && (
<>
<Separator className="my-4" />
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 e9a0fc38..aff88aac 100644
--- a/src/renderer/routes/settings/cards/integration/cli-tool-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/cli-tool-section.tsx
@@ -1,4 +1,5 @@
import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
import { ChevronRightIcon, StatusErrorIcon } from '@renderer/components/icons'
import {
Alert,
@@ -293,11 +294,8 @@ export function CliToolSection() {
<dt className="text-muted-foreground">
{t('settings.integration.cli.tool.metadata.path')}
</dt>
- <dd
- className="min-w-0 break-all font-mono"
- title={status.executablePath}
- >
- {status.executablePath}
+ <dd className="min-w-0">
+ <MiddleEllipsis text={status.executablePath} maxChars={64} />
</dd>
</>
)}
diff --git a/src/renderer/routes/settings/cards/settings-file-section.test.tsx b/src/renderer/routes/settings/cards/settings-file-section.test.tsx
new file mode 100644
index 00000000..d67f3194
--- /dev/null
+++ b/src/renderer/routes/settings/cards/settings-file-section.test.tsx
@@ -0,0 +1,128 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { invoke: vi.fn(), platform: 'darwin' },
+}))
+
+import { transport } from '@renderer/lib/transport'
+import { SettingsFileSection } from './settings-file-section'
+
+describe('SettingsFileSection', () => {
+ beforeEach(() => {
+ transport.platform = 'darwin'
+ vi.mocked(transport.invoke)
+ .mockReset()
+ .mockImplementation(async (channel) =>
+ channel === Queries.GetSettingsFileLocation
+ ? { path: '/profile/settings.json' }
+ : true
+ )
+ })
+
+ it('shows a read-only desktop path and opens its directory without sending a path', async () => {
+ const user = userEvent.setup()
+ render(<SettingsFileSection />)
+ const path = await screen.findByTitle('/profile/settings.json')
+ expect(path).toHaveAttribute('data-slot', 'middle-ellipsis')
+ expect(
+ screen.getByRole('group', { name: 'Configuration file' })
+ ).toContainElement(path)
+ expect(screen.queryByRole('textbox')).toBeNull()
+ await user.click(screen.getByRole('button', { name: 'Open folder' }))
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.OpenSettingsDirectory
+ )
+ expect(vi.mocked(transport.invoke).mock.calls).not.toContainEqual([
+ Commands.OpenSettingsDirectory,
+ '/profile/settings.json',
+ ])
+ expect(screen.queryByRole('button', { name: 'Copy path' })).toBeNull()
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.UpdateSettings)
+ })
+
+ it.each([false, new Error('Shell failure')])(
+ 'reports a failed folder action: %s',
+ async (result) => {
+ const user = userEvent.setup()
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetSettingsFileLocation)
+ return { path: '/profile/settings.json' }
+ if (result instanceof Error) throw result
+ return result
+ })
+ render(<SettingsFileSection />)
+ await user.click(
+ await screen.findByRole('button', { name: 'Open folder' })
+ )
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Couldn’t complete the action. Try again.'
+ )
+ expect(screen.getByRole('button', { name: 'Open folder' })).toBeEnabled()
+ }
+ )
+
+ it('copies the server path locally without offering a folder action', async () => {
+ transport.platform = 'web'
+ const user = userEvent.setup()
+ const copy = vi.spyOn(navigator.clipboard, 'writeText')
+ vi.mocked(transport.invoke).mockResolvedValue({
+ path: '/config/settings.json',
+ })
+ render(<SettingsFileSection />)
+ const path = await screen.findByTitle('/config/settings.json')
+ expect(
+ screen.getByRole('group', { name: 'Server configuration file' })
+ ).toContainElement(path)
+ expect(screen.queryByRole('button', { name: 'Open folder' })).toBeNull()
+ await user.click(screen.getByRole('button', { name: 'Copy path' }))
+ expect(copy).toHaveBeenCalledWith('/config/settings.json')
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole('button', { name: 'Copy path' })
+ .querySelector('[aria-live="polite"]')
+ ).toHaveTextContent('Copied')
+ )
+ expect(transport.invoke).toHaveBeenCalledExactlyOnceWith(
+ Queries.GetSettingsFileLocation
+ )
+ })
+
+ it('reports clipboard failures without claiming the path was copied', async () => {
+ transport.platform = 'web'
+ const user = userEvent.setup()
+ vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValue(
+ new Error('Permission denied')
+ )
+ render(<SettingsFileSection />)
+ await user.click(await screen.findByRole('button', { name: 'Copy path' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Couldn’t complete the action. Try again.'
+ )
+ expect(
+ screen
+ .getByRole('button', { name: 'Copy path' })
+ .querySelector('[aria-live="polite"]')
+ ).toHaveTextContent('Copy path')
+ })
+
+ it('keeps actions unavailable until the path loads and allows retrying a failed load', async () => {
+ const user = userEvent.setup()
+ vi.mocked(transport.invoke).mockRejectedValueOnce(new Error('Disconnected'))
+ render(<SettingsFileSection />)
+ await screen.findByRole('alert')
+ expect(screen.queryByRole('textbox')).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Open folder' })).toBeNull()
+ await user.click(screen.getByRole('button', { name: 'Retry' }))
+ await waitFor(() =>
+ expect(screen.getByTitle('/profile/settings.json')).toBeInTheDocument()
+ )
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+})
diff --git a/src/renderer/routes/settings/cards/settings-file-section.tsx b/src/renderer/routes/settings/cards/settings-file-section.tsx
new file mode 100644
index 00000000..dd043535
--- /dev/null
+++ b/src/renderer/routes/settings/cards/settings-file-section.tsx
@@ -0,0 +1,133 @@
+import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
+import { MiddleEllipsis } from '@renderer/components/desktop-kit/middle-ellipsis'
+import { FolderIcon } from '@renderer/components/icons'
+import { SettingsLoadStatus } from '@renderer/components/settings-kit/use-settings-load'
+import { Button } from '@renderer/components/ui/button'
+import {
+ ButtonGroup,
+ ButtonGroupText,
+} from '@renderer/components/ui/button-group'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { settingsFileLocationSchema } from '@shared/schemas/settings-file'
+import { useCallback, useEffect, useId, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export function SettingsFileSection() {
+ const { t } = useTranslation()
+ const titleId = useId()
+ const [filePath, setFilePath] = useState<string | null>(null)
+ const [loadError, setLoadError] = useState(false)
+ const generation = useRef(0)
+ const [opening, setOpening] = useState(false)
+ const [actionError, setActionError] = useState(false)
+ const isWeb = transport.platform === 'web'
+
+ const loadPath = useCallback(async () => {
+ const revision = ++generation.current
+ setFilePath(null)
+ setLoadError(false)
+ try {
+ const { path } = settingsFileLocationSchema.parse(
+ await transport.invoke(Queries.GetSettingsFileLocation)
+ )
+ if (revision === generation.current) setFilePath(path)
+ } catch {
+ if (revision === generation.current) setLoadError(true)
+ }
+ }, [])
+
+ useEffect(() => {
+ void loadPath()
+ return () => {
+ generation.current++
+ }
+ }, [loadPath])
+
+ const openDirectory = async () => {
+ setOpening(true)
+ setActionError(false)
+ try {
+ const opened = await transport.invoke(Commands.OpenSettingsDirectory)
+ setActionError(opened !== true)
+ } catch {
+ setActionError(true)
+ } finally {
+ setOpening(false)
+ }
+ }
+
+ return (
+ <section aria-labelledby={titleId} className="min-w-0 space-y-2">
+ <h3 id={titleId} className="text-sm font-semibold">
+ {t(
+ isWeb
+ ? 'settings.advanced.configFile.serverTitle'
+ : 'settings.advanced.configFile.title'
+ )}
+ </h3>
+ <SettingsLoadStatus
+ ready={filePath !== null}
+ error={loadError}
+ retry={loadPath}
+ />
+ {filePath !== null && (
+ <ButtonGroup
+ dir="ltr"
+ className="w-full min-w-0"
+ aria-labelledby={titleId}
+ >
+ <ButtonGroupText className="h-8 min-w-0 flex-1 overflow-hidden bg-background px-3 font-normal">
+ <MiddleEllipsis
+ text={filePath}
+ maxChars={64}
+ className="w-full text-xs"
+ />
+ </ButtonGroupText>
+ {isWeb ? (
+ <CopyButton
+ variant="outline"
+ size="icon-sm"
+ className="gap-0"
+ aria-label={t('settings.advanced.configFile.copyPath')}
+ title={t('settings.advanced.configFile.copyPath')}
+ content={() => {
+ setActionError(false)
+ return filePath
+ }}
+ copiedLabel={
+ <span className="sr-only">
+ {t('settings.advanced.configFile.copied')}
+ </span>
+ }
+ onCopyError={() => setActionError(true)}
+ >
+ <span className="sr-only">
+ {t('settings.advanced.configFile.copyPath')}
+ </span>
+ </CopyButton>
+ ) : (
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ aria-label={t('settings.advanced.configFile.openDirectory')}
+ title={t('settings.advanced.configFile.openDirectory')}
+ disabled={opening}
+ aria-busy={opening}
+ onClick={() => void openDirectory()}
+ >
+ <FolderIcon />
+ </Button>
+ )}
+ </ButtonGroup>
+ )}
+ {actionError && (
+ <p role="alert" className="text-xs text-destructive">
+ {t('settings.advanced.configFile.actionFailed')}
+ </p>
+ )}
+ </section>
+ )
+}
diff --git a/src/server/http/rpc.test.ts b/src/server/http/rpc.test.ts
index ed5e0003..56b3e075 100644
--- a/src/server/http/rpc.test.ts
+++ b/src/server/http/rpc.test.ts
@@ -49,6 +49,27 @@ describe('rpc routes', () => {
await app.close()
})
+ it('serializes the settings file location as JSON for web clients', async () => {
+ const location = { path: '/custom profile/配置/settings.json' }
+ const app = await createApp({
+ queryHandlers: {
+ [Queries.GetSettingsFileLocation]: async () => location,
+ },
+ })
+ try {
+ const response = await app.inject({
+ method: 'POST',
+ url: `/rpc/query/${encodeURIComponent(Queries.GetSettingsFileLocation)}`,
+ payload: { args: [] },
+ })
+ expect(response.statusCode).toBe(200)
+ expect(response.headers['content-type']).toContain('application/json')
+ expect(response.json()).toEqual(location)
+ } finally {
+ await app.close()
+ }
+ })
+
it('returns the shared bounded envelope for inspector query success', async () => {
const snapshot = makeTaskInspectorActivitySnapshot('task-1', 9)
const app = await createApp({
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index 6eb7c3fc..e009d4f5 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -215,6 +215,18 @@ function makeFakeCtx() {
}
describe('desktop-only FFmpeg installation boundary', () => {
+ it('does not open a server settings directory through web commands', async () => {
+ const handlers = buildServerCommandHandlers(
+ makeFakeCtx() as ServerCommandContext
+ )
+ await expect(handlers[Commands.OpenSettingsDirectory]?.()).resolves.toBe(
+ false
+ )
+ await expect(
+ handlers[Commands.OpenSettingsDirectory]?.({ path: '/tmp' })
+ ).rejects.toThrow()
+ })
+
it('does not install server executables through web commands', async () => {
const handlers = buildServerCommandHandlers(
makeFakeCtx() as ServerCommandContext
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index e3b81dee..705dd5be 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -407,6 +407,10 @@ export function buildServerCommandHandlers(
return {
...(ctx.operationService ? operationHandlers(ctx.operationService) : {}),
...unsupportedLegacyImportCommands(),
+ [Commands.OpenSettingsDirectory]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ return false
+ },
[Commands.InstallFfmpeg]: async (payload: unknown) => {
z.undefined().parse(payload)
return { ok: false, error: 'unsupported' }
diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.ts
index b3853fb7..dc11c163 100644
--- a/src/server/ipc/queries.test.ts
+++ b/src/server/ipc/queries.test.ts
@@ -165,6 +165,20 @@ function makeCtx(over: Record<string, unknown> = {}) {
}
describe('buildServerQueryHandlers — allowed save directories', () => {
+ it('returns the server settings path for custom profiles', async () => {
+ const handlers = buildServerQueryHandlers(
+ makeCtx({
+ userDataDir: '/data',
+ settingsManager: { getFilePath: () => '/config/settings.json' },
+ }) as unknown as ServerQueryContext
+ )
+ await expect(
+ handlers[Queries.GetSettingsFileLocation]?.()
+ ).resolves.toEqual({
+ path: '/config/settings.json',
+ })
+ })
+
it('returns the same committed system locale for settings and onboarding', async () => {
const settings = { app: { language: 'system' } }
const handlers = buildServerQueryHandlers(
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index 1cdfc4f3..f838b6d2 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -285,6 +285,10 @@ export function buildServerQueryHandlers(
// A remote server cannot read the browser user's operating-system accent.
[Queries.GetSystemAccentColor]: async () => null,
+ [Queries.GetSettingsFileLocation]: async () => ({
+ path: settingsManager.getFilePath(),
+ }),
+
[Queries.GetGeoIPStatus]: createGetGeoIPStatusHandler({ geoipManager }),
[Queries.GetSystemProxy]: async () => parseProxyEnvironment(environment),
diff --git a/src/shared/lib/path-display.test.ts b/src/shared/lib/path-display.test.ts
new file mode 100644
index 00000000..52977b28
--- /dev/null
+++ b/src/shared/lib/path-display.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest'
+import { truncatePath } from './path-display'
+
+const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
+const length = (value: string) => [...segmenter.segment(value)].length
+
+describe('truncatePath', () => {
+ it.each([
+ '',
+ '/',
+ 'C:\\',
+ '\\\\nas\\share',
+ ' /path with spaces/file.txt ',
+ ])('leaves fitting paths untouched: %s', (path) =>
+ expect(truncatePath(path, length(path))).toBe(path)
+ )
+
+ it('preserves the last component when it fits beside the path prefix', () => {
+ expect(truncatePath('/one/two/three/file.txt', 16)).toBe('/one/t…/file.txt')
+ expect(truncatePath('C:\\one\\two\\three\\file.txt', 16)).toBe(
+ 'C:\\one…\\file.txt'
+ )
+ })
+
+ it.each([
+ '/Users/alice/Library/Application Support/Motrix/settings.json',
+ 'C:\\Users\\Alice\\AppData\\Roaming\\Motrix\\settings.json',
+ '\\\\server\\share\\directory\\配置\\settings.json',
+ '~/Downloads/a/very/long/directory/',
+ '/目录/👩‍💻/e\u0301/very-long-filename.tar.gz',
+ 'long-file-without-any-directory-name.mkv',
+ ])('respects the grapheme budget and keeps both ends of %s', (path) => {
+ for (const maxChars of [3, 8, 16, 24, 40]) {
+ const result = truncatePath(path, maxChars)
+ expect(length(result)).toBeLessThanOrEqual(maxChars)
+ expect(result[0]).toBe(path[0])
+ expect(result.at(-1)).toBe(path.at(-1))
+ if (length(path) > maxChars) expect(result).toContain('…')
+ }
+ })
+
+ it('does not split emoji sequences or combining characters', () => {
+ expect(truncatePath('a👨‍👩‍👧‍👦bcdef', 4)).toBe('a👨‍👩‍👧‍👦…f')
+ expect(truncatePath('ae\u0301bcdef', 4)).toBe('ae\u0301…f')
+ expect(truncatePath('/long/directory/e\u0301.txt', 12)).toMatch(
+ /e\u0301\.txt$/
+ )
+ })
+
+ it.each([
+ [0, ''],
+ [1, '…'],
+ [2, 'a…'],
+ [3, 'a…f'],
+ [6, 'abcdef'],
+ ] as const)('handles a budget of %s', (maxChars, expected) =>
+ expect(truncatePath('abcdef', maxChars)).toBe(expected)
+ )
+
+ it.each([-1, 1.5, NaN, Infinity])(
+ 'rejects invalid budgets: %s',
+ (maxChars) => {
+ expect(() => truncatePath('/path', maxChars)).toThrow(RangeError)
+ }
+ )
+})
diff --git a/src/shared/lib/path-display.ts b/src/shared/lib/path-display.ts
new file mode 100644
index 00000000..25d2fa59
--- /dev/null
+++ b/src/shared/lib/path-display.ts
@@ -0,0 +1,57 @@
+const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
+
+const isSeparator = (character: string) =>
+ character === '/' || character === '\\'
+
+/** Display-only fragments; maxChars includes the single-character ellipsis. */
+export function getPathDisplayParts(path: string, maxChars: number) {
+ if (!Number.isSafeInteger(maxChars) || maxChars < 0)
+ throw new RangeError('maxChars must be a non-negative safe integer')
+ const characters = Array.from(
+ segmenter.segment(path),
+ ({ segment }) => segment
+ )
+ if (maxChars === 0) return { start: '', ellipsis: '', end: '' }
+ if (characters.length <= maxChars) {
+ const middle = Math.ceil(characters.length / 2)
+ return {
+ start: characters.slice(0, middle).join(''),
+ ellipsis: '',
+ end: characters.slice(middle).join(''),
+ }
+ }
+
+ const available = maxChars - 1
+ let startLength = Math.ceil(available / 2)
+ let endLength = available - startLength
+ let last = characters.length - 1
+ while (last >= 0 && isSeparator(characters[last])) last--
+ while (last >= 0 && !isSeparator(characters[last])) last--
+ const lastSegmentLength = characters.length - last
+ const rootLength = /^[a-z]:[\\/]/i.test(path)
+ ? 3
+ : /^(?:[\\/]{2}|~[\\/])/.test(path)
+ ? 2
+ : 1
+
+ // Prefer the complete last component when the path root still fits.
+ if (
+ last >= 0 &&
+ lastSegmentLength > endLength &&
+ lastSegmentLength <= available - rootLength
+ ) {
+ endLength = lastSegmentLength
+ startLength = available - endLength
+ }
+ return {
+ start: characters.slice(0, startLength).join(''),
+ ellipsis: '…',
+ end: endLength === 0 ? '' : characters.slice(-endLength).join(''),
+ }
+}
+
+/** Limit display text to maxChars graphemes, including …, without normalizing the path. */
+export function truncatePath(path: string, maxChars: number): string {
+ const { start, ellipsis, end } = getPathDisplayParts(path, maxChars)
+ return start + ellipsis + end
+}
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index d9298405..a5315986 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -1900,6 +1900,14 @@
"secret": "رمز RPC السري",
"secretDesc": "مطلوب لاتصالات RPC.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "ملف الإعدادات",
+ "serverTitle": "ملف إعدادات الخادم",
+ "openDirectory": "فتح المجلد",
+ "copyPath": "نسخ المسار",
+ "copied": "تم النسخ",
+ "actionFailed": "تعذّر إكمال العملية. حاول مرة أخرى."
}
},
"appearance": {
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index b0e74624..aec2ac3a 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -1824,6 +1824,14 @@
"secret": "RPC таен код",
"secretDesc": "Необходим за RPC връзки.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Файл с настройки",
+ "serverTitle": "Файл с настройки на сървъра",
+ "openDirectory": "Отваряне на папката",
+ "copyPath": "Копиране на пътя",
+ "copied": "Копирано",
+ "actionFailed": "Действието не бе завършено. Опитайте отново."
}
},
"appearance": {
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 3a4dbd22..d3c5c1ff 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -1843,6 +1843,14 @@
"secret": "Secret RPC",
"secretDesc": "Necessari per a les connexions RPC.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Fitxer de configuració",
+ "serverTitle": "Fitxer de configuració del servidor",
+ "openDirectory": "Obre la carpeta",
+ "copyPath": "Copia el camí",
+ "copied": "Copiat",
+ "actionFailed": "No s’ha pogut completar l’acció. Torneu-ho a provar."
}
},
"appearance": {
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index 0d841d68..eeb80945 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1348,7 +1348,15 @@
"historyCountHint": "Ältere Wiederherstellungsdatensätze werden entfernt.",
"historyCountPositive": "Geben Sie eine Zahl größer als 0 ein."
},
- "description": "RPC, Fortschritt und Wiederherstellung"
+ "description": "RPC, Fortschritt und Wiederherstellung",
+ "configFile": {
+ "title": "Konfigurationsdatei",
+ "serverTitle": "Server-Konfigurationsdatei",
+ "openDirectory": "Ordner öffnen",
+ "copyPath": "Pfad kopieren",
+ "copied": "Kopiert",
+ "actionFailed": "Die Aktion konnte nicht abgeschlossen werden. Versuche es erneut."
+ }
},
"about": {
"appIconAlt": "Motrix-App-Symbol",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index db878d3c..3116ff33 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -1824,6 +1824,14 @@
"secret": "Μυστικό RPC",
"secretDesc": "Απαιτείται για τις συνδέσεις RPC.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Αρχείο ρυθμίσεων",
+ "serverTitle": "Αρχείο ρυθμίσεων διακομιστή",
+ "openDirectory": "Άνοιγμα φακέλου",
+ "copyPath": "Αντιγραφή διαδρομής",
+ "copied": "Αντιγράφηκε",
+ "actionFailed": "Η ενέργεια δεν ολοκληρώθηκε. Δοκιμάστε ξανά."
}
},
"appearance": {
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 254dabf2..a91cc822 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1348,7 +1348,15 @@
"historyCountHint": "Older recovery records are removed.",
"historyCountPositive": "Enter a number greater than 0."
},
- "description": "RPC, progress and recovery"
+ "description": "RPC, progress and recovery",
+ "configFile": {
+ "title": "Configuration file",
+ "serverTitle": "Server configuration file",
+ "openDirectory": "Open folder",
+ "copyPath": "Copy path",
+ "copied": "Copied",
+ "actionFailed": "Couldn’t complete the action. Try again."
+ }
},
"about": {
"appIconAlt": "Motrix app icon",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index e6dfbfd3..e02058c5 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1362,7 +1362,15 @@
"historyCountHint": "Se quitan los registros de recuperación más antiguos.",
"historyCountPositive": "Introduce un número mayor que 0."
},
- "description": "RPC, progreso y recuperación"
+ "description": "RPC, progreso y recuperación",
+ "configFile": {
+ "title": "Archivo de configuración",
+ "serverTitle": "Archivo de configuración del servidor",
+ "openDirectory": "Abrir carpeta",
+ "copyPath": "Copiar ruta",
+ "copied": "Copiado",
+ "actionFailed": "No se pudo completar la acción. Inténtalo de nuevo."
+ }
},
"about": {
"appIconAlt": "Icono de la aplicación Motrix",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 08e9c10c..0f07b8fe 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -1824,6 +1824,14 @@
"secret": "رمز محرمانهٔ RPC",
"secretDesc": "برای اتصال‌های RPC لازم است.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "فایل تنظیمات",
+ "serverTitle": "فایل تنظیمات سرور",
+ "openDirectory": "باز کردن پوشه",
+ "copyPath": "کپی مسیر",
+ "copied": "کپی شد",
+ "actionFailed": "عملیات انجام نشد. دوباره تلاش کنید."
}
},
"appearance": {
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index b2962d81..48e08772 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -1843,6 +1843,14 @@
"secret": "Secret RPC",
"secretDesc": "Requis pour les connexions RPC.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Fichier de configuration",
+ "serverTitle": "Fichier de configuration du serveur",
+ "openDirectory": "Ouvrir le dossier",
+ "copyPath": "Copier le chemin",
+ "copied": "Copié",
+ "actionFailed": "L’action n’a pas pu être effectuée. Réessayez."
}
},
"appearance": {
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 312c5388..00577207 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1348,7 +1348,15 @@
"historyCountHint": "A régebbi helyreállítási bejegyzések törlődnek.",
"historyCountPositive": "Adj meg 0-nál nagyobb számot."
},
- "description": "RPC, előrehaladás és helyreállítás"
+ "description": "RPC, előrehaladás és helyreállítás",
+ "configFile": {
+ "title": "Konfigurációs fájl",
+ "serverTitle": "Szerver konfigurációs fájlja",
+ "openDirectory": "Mappa megnyitása",
+ "copyPath": "Útvonal másolása",
+ "copied": "Másolva",
+ "actionFailed": "A művelet nem sikerült. Próbáld újra."
+ }
},
"about": {
"appIconAlt": "Motrix alkalmazásikon",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index d026f337..6c04c7a3 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1334,7 +1334,15 @@
"historyCountHint": "Catatan pemulihan yang lebih lama akan dihapus.",
"historyCountPositive": "Masukkan angka yang lebih besar dari 0."
},
- "description": "RPC, progres, dan pemulihan"
+ "description": "RPC, progres, dan pemulihan",
+ "configFile": {
+ "title": "File konfigurasi",
+ "serverTitle": "File konfigurasi server",
+ "openDirectory": "Buka folder",
+ "copyPath": "Salin lokasi",
+ "copied": "Disalin",
+ "actionFailed": "Tindakan tidak dapat diselesaikan. Coba lagi."
+ }
},
"about": {
"appIconAlt": "Ikon aplikasi Motrix",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index ce6a9fc3..4910b69b 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1362,7 +1362,15 @@
"historyCountHint": "I record di recupero più vecchi vengono rimossi.",
"historyCountPositive": "Inserisci un numero maggiore di 0."
},
- "description": "RPC, avanzamento e recupero"
+ "description": "RPC, avanzamento e recupero",
+ "configFile": {
+ "title": "File di configurazione",
+ "serverTitle": "File di configurazione del server",
+ "openDirectory": "Apri cartella",
+ "copyPath": "Copia percorso",
+ "copied": "Copiato",
+ "actionFailed": "Impossibile completare l’azione. Riprova."
+ }
},
"about": {
"appIconAlt": "Icona dell’app Motrix",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index f24cb35b..ea9493f2 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1334,7 +1334,15 @@
"historyCountHint": "古い復旧記録は削除されます。",
"historyCountPositive": "0 より大きい数値を入力してください。"
},
- "description": "RPC、進捗と復旧"
+ "description": "RPC、進捗と復旧",
+ "configFile": {
+ "title": "設定ファイル",
+ "serverTitle": "サーバー設定ファイル",
+ "openDirectory": "保存先フォルダーを開く",
+ "copyPath": "パスをコピー",
+ "copied": "コピーしました",
+ "actionFailed": "操作を完了できませんでした。もう一度お試しください。"
+ }
},
"about": {
"appIconAlt": "Motrix アプリのアイコン",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 40174856..af2a2e95 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1334,7 +1334,15 @@
"historyCountHint": "오래된 복구 기록은 제거됩니다.",
"historyCountPositive": "0보다 큰 숫자를 입력하세요."
},
- "description": "RPC, 진행 상황 및 복구"
+ "description": "RPC, 진행 상황 및 복구",
+ "configFile": {
+ "title": "설정 파일",
+ "serverTitle": "서버 설정 파일",
+ "openDirectory": "폴더 열기",
+ "copyPath": "경로 복사",
+ "copied": "복사됨",
+ "actionFailed": "작업을 완료하지 못했습니다. 다시 시도하세요."
+ }
},
"about": {
"appIconAlt": "Motrix 앱 아이콘",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 3245337b..a6696909 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -1824,6 +1824,14 @@
"secret": "RPC-hemmelighet",
"secretDesc": "Kreves for RPC-tilkoblinger.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Konfigurasjonsfil",
+ "serverTitle": "Serverens konfigurasjonsfil",
+ "openDirectory": "Åpne mappe",
+ "copyPath": "Kopier sti",
+ "copied": "Kopiert",
+ "actionFailed": "Handlingen kunne ikke fullføres. Prøv igjen."
}
},
"appearance": {
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index c15cc921..4006e85d 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -1824,6 +1824,14 @@
"secret": "RPC-geheim",
"secretDesc": "Vereist voor RPC-verbindingen.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Configuratiebestand",
+ "serverTitle": "Serverconfiguratiebestand",
+ "openDirectory": "Map openen",
+ "copyPath": "Pad kopiëren",
+ "copied": "Gekopieerd",
+ "actionFailed": "De actie kon niet worden voltooid. Probeer het opnieuw."
}
},
"appearance": {
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index bd80b9c6..7809e2eb 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1376,7 +1376,15 @@
"historyCountHint": "Starsze zapisy odzyskiwania są usuwane.",
"historyCountPositive": "Wpisz liczbę większą od 0."
},
- "description": "RPC, postęp i odzyskiwanie"
+ "description": "RPC, postęp i odzyskiwanie",
+ "configFile": {
+ "title": "Plik konfiguracji",
+ "serverTitle": "Plik konfiguracji serwera",
+ "openDirectory": "Otwórz folder",
+ "copyPath": "Kopiuj ścieżkę",
+ "copied": "Skopiowano",
+ "actionFailed": "Nie udało się wykonać czynności. Spróbuj ponownie."
+ }
},
"about": {
"appIconAlt": "Ikona aplikacji Motrix",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 7fcecd22..05266539 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1362,7 +1362,15 @@
"historyCountHint": "Os registros de recuperação mais antigos são removidos.",
"historyCountPositive": "Digite um número maior que 0."
},
- "description": "RPC, progresso e recuperação"
+ "description": "RPC, progresso e recuperação",
+ "configFile": {
+ "title": "Arquivo de configuração",
+ "serverTitle": "Arquivo de configuração do servidor",
+ "openDirectory": "Abrir pasta",
+ "copyPath": "Copiar caminho",
+ "copied": "Copiado",
+ "actionFailed": "Não foi possível concluir a ação. Tente novamente."
+ }
},
"about": {
"appIconAlt": "Ícone do aplicativo Motrix",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 70225add..7b86df5b 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -1843,6 +1843,14 @@
"secret": "Secret RPC",
"secretDesc": "Necesar pentru conexiunile RPC.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Fișier de configurare",
+ "serverTitle": "Fișier de configurare al serverului",
+ "openDirectory": "Deschide dosarul",
+ "copyPath": "Copiază calea",
+ "copied": "Copiat",
+ "actionFailed": "Acțiunea nu a putut fi finalizată. Încearcă din nou."
}
},
"appearance": {
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index c2a47b46..c48480a1 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1376,7 +1376,15 @@
"historyCountHint": "Более старые записи восстановления удаляются.",
"historyCountPositive": "Введите число больше 0."
},
- "description": "RPC, прогресс и восстановление"
+ "description": "RPC, прогресс и восстановление",
+ "configFile": {
+ "title": "Файл настроек",
+ "serverTitle": "Файл настроек сервера",
+ "openDirectory": "Открыть папку",
+ "copyPath": "Копировать путь",
+ "copied": "Скопировано",
+ "actionFailed": "Не удалось выполнить действие. Повторите попытку."
+ }
},
"about": {
"appIconAlt": "Значок приложения Motrix",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 9a8b57dd..08d8ccfe 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -1805,6 +1805,14 @@
"secret": "ข้อมูลลับ RPC",
"secretDesc": "จำเป็นสำหรับการเชื่อมต่อ RPC",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "ไฟล์การตั้งค่า",
+ "serverTitle": "ไฟล์การตั้งค่าเซิร์ฟเวอร์",
+ "openDirectory": "เปิดโฟลเดอร์",
+ "copyPath": "คัดลอกพาธ",
+ "copied": "คัดลอกแล้ว",
+ "actionFailed": "ดำเนินการไม่สำเร็จ โปรดลองอีกครั้ง"
}
},
"appearance": {
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 359cf510..bec70af6 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1348,7 +1348,15 @@
"historyCountHint": "Daha eski kurtarma kayıtları kaldırılır.",
"historyCountPositive": "0’dan büyük bir sayı girin."
},
- "description": "RPC, ilerleme ve kurtarma"
+ "description": "RPC, ilerleme ve kurtarma",
+ "configFile": {
+ "title": "Yapılandırma dosyası",
+ "serverTitle": "Sunucu yapılandırma dosyası",
+ "openDirectory": "Klasörü aç",
+ "copyPath": "Yolu kopyala",
+ "copied": "Kopyalandı",
+ "actionFailed": "İşlem tamamlanamadı. Tekrar deneyin."
+ }
},
"about": {
"appIconAlt": "Motrix uygulama simgesi",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 9bff664c..e036a0fd 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -1862,6 +1862,14 @@
"secret": "Секрет RPC",
"secretDesc": "Потрібен для RPC-з'єднань.",
"title": "RPC"
+ },
+ "configFile": {
+ "title": "Файл налаштувань",
+ "serverTitle": "Файл налаштувань сервера",
+ "openDirectory": "Відкрити теку",
+ "copyPath": "Копіювати шлях",
+ "copied": "Скопійовано",
+ "actionFailed": "Не вдалося виконати дію. Спробуйте ще раз."
}
},
"appearance": {
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index a575f2a2..8a313029 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1334,7 +1334,15 @@
"historyCountHint": "Các bản ghi khôi phục cũ hơn sẽ bị xóa.",
"historyCountPositive": "Nhập một số lớn hơn 0."
},
- "description": "RPC, tiến độ và khôi phục"
+ "description": "RPC, tiến độ và khôi phục",
+ "configFile": {
+ "title": "Tệp cấu hình",
+ "serverTitle": "Tệp cấu hình máy chủ",
+ "openDirectory": "Mở thư mục",
+ "copyPath": "Sao chép đường dẫn",
+ "copied": "Đã sao chép",
+ "actionFailed": "Không thể hoàn tất thao tác. Vui lòng thử lại."
+ }
},
"about": {
"appIconAlt": "Biểu tượng ứng dụng Motrix",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index f3111328..8f846ccf 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1402,7 +1402,15 @@
"historyCountHint": "较早的恢复记录会被移除。",
"historyCountPositive": "请输入大于 0 的数量。"
},
- "description": "RPC、进度与恢复"
+ "description": "RPC、进度与恢复",
+ "configFile": {
+ "title": "配置文件",
+ "serverTitle": "服务端配置文件",
+ "openDirectory": "打开所在目录",
+ "copyPath": "复制路径",
+ "copied": "已复制",
+ "actionFailed": "操作未完成,请重试。"
+ }
},
"bittorrent": {
"trackers": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index b8dbc506..b3fabe8b 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1334,7 +1334,15 @@
"historyCountHint": "較早的恢復記錄會被移除。",
"historyCountPositive": "請輸入大於 0 的數量。"
},
- "description": "RPC、進度與恢復"
+ "description": "RPC、進度與恢復",
+ "configFile": {
+ "title": "設定檔",
+ "serverTitle": "伺服器設定檔",
+ "openDirectory": "開啟所在資料夾",
+ "copyPath": "複製路徑",
+ "copied": "已複製",
+ "actionFailed": "操作未完成,請重試。"
+ }
},
"about": {
"appIconAlt": "Motrix 應用程式圖示",
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index d4fbd563..430be938 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -55,6 +55,7 @@ export const Commands = {
MutateDirectoryPreferences: 'command:mutateDirectoryPreferences',
SaveGeneralSettings: 'command:saveGeneralSettings',
UpdateSettings: 'command:updateSettings',
+ OpenSettingsDirectory: 'command:openSettingsDirectory',
AcceptDisclaimer: 'command:acceptDisclaimer',
DeclineDisclaimer: 'command:declineDisclaimer',
SetDisclaimerLanguage: 'command:setDisclaimerLanguage',
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index f5d079e6..edd7ccc8 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -17,6 +17,7 @@ export const Queries = {
GetDirectoryPreferences: 'query:getDirectoryPreferences',
ListServerDirectoryLocations: 'query:listServerDirectoryLocations',
GetSettings: 'query:getSettings',
+ GetSettingsFileLocation: 'query:getSettingsFileLocation',
GetSystemAccentColor: 'query:getSystemAccentColor',
GetUpdateState: 'query:getUpdateState',
GetSystemProxy: 'query:getSystemProxy',
diff --git a/src/shared/schemas/settings-file.ts b/src/shared/schemas/settings-file.ts
new file mode 100644
index 00000000..1a03aed4
--- /dev/null
+++ b/src/shared/schemas/settings-file.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod'
+
+export const settingsFileLocationSchema = z.object({
+ path: z.string().min(1),
+})