A full-featured download manager.
feat(settings): refine preferences and desktop notifications (#2210)
Dr_rOot694bb29e802f
diff --git a/.github/pr-assets/settings-general.png b/.github/pr-assets/settings-general.pngnew file mode 100644index 00000000..75f33085Binary files /dev/null and b/.github/pr-assets/settings-general.png differdiff --git a/e2e/settings-layout.spec.ts b/e2e/settings-layout.spec.tsnew file mode 100644index 00000000..c8e5b6b7--- /dev/null+++ b/e2e/settings-layout.spec.ts@@ -0,0 +1,117 @@+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import type { AppSettings } from '@shared/types/settings'+import { expect, test, waitForEngineReady } from './fixtures/electron-app'++test('moved settings preserve draft, cancel and save behavior in the desktop host', async ({+ mainWindow: page,+}, testInfo) => {+ await waitForEngineReady(page)+ const read = () =>+ page.evaluate(+ async (channel) => (await window.motrix.invoke(channel)) as AppSettings,+ Queries.GetSettings+ )+ const before = await read()+ const open = async (card: string) => {+ await page.getByRole('link', { name: 'Settings', exact: true }).click()+ await page+ .getByRole('button', {+ name: new RegExp(`^${card.toLowerCase()} ${card} `),+ })+ .click()+ await expect(+ page.getByRole('button', { name: 'Save', exact: true })+ ).toBeEnabled()+ }+ await open('Downloads')+ await expect(+ page.getByRole('heading', { name: 'Save folders' })+ ).toBeVisible()+ await expect(page.getByRole('textbox', { name: 'User-Agent' })).toHaveValue(+ before.engine.userAgent+ )+ const clipboard = page.getByRole('switch', {+ name: 'Autofill links from clipboard',+ })+ await clipboard.click()+ await page+ .getByRole('spinbutton', { name: 'Upload — Standard limits' })+ .fill('123')+ expect((await read()).app.autofillClipboardLinks).toBe(+ before.app.autofillClipboardLinks+ )+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()+ await open('Downloads')+ await expect(clipboard).toBeChecked({+ checked: before.app.autofillClipboardLinks,+ })+ await clipboard.click()+ await page+ .getByRole('spinbutton', { name: 'Upload — Standard limits' })+ .fill('123')+ await page.screenshot({+ path: testInfo.outputPath('downloads-production.png'),+ })+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(page.getByRole('dialog')).toHaveCount(0)+ const saved = await read()+ expect(saved.app.autofillClipboardLinks).toBe(+ !before.app.autofillClipboardLinks+ )+ expect(saved.speedLimit.base.upload).toBe(+ 123 * (before.app.byteUnitSystem === 'binary' ? 1024 : 1000)+ )+ expect(saved.speedLimit.base.download).toBe(before.speedLimit.base.download)+ expect(saved.app.directoryPreferences).toEqual(+ before.app.directoryPreferences+ )+ await open('BitTorrent')+ const location = page.getByRole('switch', { name: 'Show country or region' })+ await location.click()+ expect((await read()).geoip.enabled).toBe(before.geoip.enabled)+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()+ await open('BitTorrent')+ await expect(location).toBeChecked({ checked: before.geoip.enabled })+ await location.click()+ await page+ .getByRole('spinbutton', { name: 'Magnet loading timeout (s)' })+ .fill('900')+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(page.getByRole('dialog')).toHaveCount(0)+ expect((await read()).geoip.enabled).toBe(!before.geoip.enabled)+ expect((await read()).engine.magnetResolveTimeout).toBe(900)+ await open('Advanced')+ const retention = page.getByRole('combobox', {+ name: 'Completed recovery records',+ })+ await retention.click()+ await page.getByRole('option', { name: 'Latest records…' }).click()+ const count = page.getByRole('spinbutton', { name: 'Records to keep' })+ await count.fill('0')+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(page.getByText('Enter a number greater than 0.')).toBeVisible()+ await count.fill('731')+ await retention.click()+ await page.getByRole('option', { name: 'Do not retain' }).click()+ await retention.click()+ await page.getByRole('option', { name: 'Latest records…' }).click()+ await expect(count).toHaveValue('731')+ await page.screenshot({+ path: testInfo.outputPath('advanced-production.png'),+ })+ await page.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(+ page.getByRole('dialog', { name: 'Advanced', exact: true })+ ).toHaveCount(0)+ expect((await read()).engine.sqlite3HistoryLimit).toBe(731)+ await open('Advanced')+ await expect(count).toHaveValue('731')+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()+ await page.evaluate(+ async ({ channel, language }) => {+ await window.motrix.invoke(channel, { app: { language } })+ },+ { channel: Commands.UpdateSettings, language: 'zh-CN' }+ )+})diff --git a/e2e/settings-persistence.spec.ts b/e2e/settings-persistence.spec.tsindex 3641c392..7d94a2a2 100644--- a/e2e/settings-persistence.spec.ts+++ b/e2e/settings-persistence.spec.ts@@ -1,12 +1,20 @@import type { ElectronApplication, Page } from '@playwright/test'import {expect,+ findAddTaskWindow,launchMotrix,test,waitForEngineReady,} from './fixtures/electron-app'-const SWITCH_LABEL = 'Notify when download completes'+const NOTIFICATION_LABEL = 'Download completed'++async function chooseNotification(page: Page, label: string, option: string) {+ await page.getByRole('combobox', { name: label }).click()+ await page.getByRole('option', { name: option, exact: true }).click()+ await expect(page.getByRole('combobox', { name: label })).toHaveText(option)+ await expect(page.getByRole('option')).toHaveCount(0)+}async function openGeneralSettings(page: Page): Promise<void> {await page.getByRole('link', { name: 'Settings', exact: true }).click()@@ -14,8 +22,13 @@ async function openGeneralSettings(page: Page): Promise<void> {// from settings.cards.general.title. Match the text that's also the// accessible heading inside the card.await page.getByText('General', { exact: true }).first().click()- // Dialog opens — wait for the switch to be present before interacting.- await expect(page.getByRole('switch', { name: SWITCH_LABEL })).toBeVisible()+ // Wait for the authoritative settings baseline before editing.+ await expect(+ page.getByRole('combobox', { name: NOTIFICATION_LABEL })+ ).toBeVisible()+ await expect(+ page.getByRole('button', { name: 'Save', exact: true })+ ).toBeEnabled()}async function openMain(app: ElectronApplication): Promise<Page> {@@ -25,6 +38,118 @@ async function openMain(app: ElectronApplication): Promise<Page> {}test.describe('settings persistence', () => {+ test('desktop notification choices filter existing history, refresh badges, and survive restart', async ({+ userDataDir,+ rpcPort,+ httpFixture,+ }, testInfo) => {+ let app = await launchMotrix({ userDataDir, rpcPort })+ try {+ let main = await openMain(app)+ await waitForEngineReady(main)+ await main.getByRole('button', { name: 'New task' }).click()+ const addTask = await findAddTaskWindow(app)+ await addTask+ .getByRole('textbox', { name: 'URLs' })+ .fill(httpFixture.fileUrl)+ await addTask.getByRole('button', { name: 'Download' }).click()+ const badge = main.getByTestId('notification-badge')+ await expect(badge).toHaveText('1', { timeout: 20_000 })+ // Task creation also queues navigation to its inspector. Let that+ // navigation settle before opening a settings dialog on another route.+ await expect(+ main.getByRole('dialog', { name: 'Task Inspector' })+ ).toBeVisible()++ await openGeneralSettings(main)+ await chooseNotification(+ main,+ 'Download completed',+ 'System notifications'+ )+ await main.getByRole('button', { name: 'Cancel', exact: true }).click()+ await expect(badge).toHaveText('1')+ await openGeneralSettings(main)+ await expect(+ main.getByRole('combobox', { name: 'Download completed' })+ ).toHaveText('Both')+ await chooseNotification(+ main,+ 'Download completed',+ 'System notifications'+ )+ await chooseNotification(main, 'Download failed', 'System notifications')+ await main.getByRole('combobox', { name: 'Unread badge' }).click()+ await main.getByRole('option', { name: 'Dot', exact: true }).click()+ await main.screenshot({+ path: testInfo.outputPath('notification-preferences.png'),+ })+ await main.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(badge).toHaveCount(0)+ await expect(main.getByTestId('notification-badge-dot')).toHaveCount(0)+ await main+ .getByRole('link', { name: 'Notifications', exact: true })+ .click()+ await expect(+ main.getByText('No notifications', { exact: true })+ ).toBeVisible()++ await openGeneralSettings(main)+ await chooseNotification(main, 'Download completed', 'Both')+ await main.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(main.getByTestId('notification-badge-dot')).toBeVisible()+ await expect(main.getByTestId('notification-badge-dot')).toHaveAttribute(+ 'aria-label',+ 'Unread notifications'+ )+ await expect(badge).toHaveCount(0)+ await main.screenshot({+ path: testInfo.outputPath('notification-dot.png'),+ })+ await main.getByRole('button', { name: 'Toggle sidebar' }).click()+ // The desktop sidebar slides off-canvas rather than becoming an icon rail.+ await expect(+ main.getByTestId('notification-badge-dot')+ ).not.toBeInViewport()+ await main.screenshot({+ path: testInfo.outputPath('notification-dot-collapsed.png'),+ })+ await main.getByRole('button', { name: 'Toggle sidebar' }).click()+ await expect(main.getByTestId('notification-badge-dot')).toBeInViewport()++ await openGeneralSettings(main)+ await main.getByRole('combobox', { name: 'Unread badge' }).click()+ await main.getByRole('option', { name: 'Hidden', exact: true }).click()+ await main.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(main.getByTestId('notification-badge-dot')).toHaveCount(0)+ await app.close()++ app = await launchMotrix({ userDataDir, rpcPort })+ main = await openMain(app)+ await openGeneralSettings(main)+ await expect(+ main.getByRole('combobox', { name: 'Download completed' })+ ).toHaveText('Both')+ await expect(+ main.getByRole('combobox', { name: 'Download failed' })+ ).toHaveText('System notifications')+ await expect(+ main.getByRole('combobox', { name: 'Unread badge' })+ ).toHaveText('Hidden')+ await main.getByRole('button', { name: 'Cancel', exact: true }).click()+ await expect(main.getByTestId('notification-badge')).toHaveCount(0)+ await expect(main.getByTestId('notification-badge-dot')).toHaveCount(0)+ await main+ .getByRole('link', { name: 'Notifications', exact: true })+ .click()+ await expect(+ main.getByText('test.bin finished downloading', { exact: true })+ ).toBeVisible()+ } finally {+ await app.close().catch(() => {})+ }+ })+test('task file deletion defaults to trash and persists an explicit permanent choice', async ({userDataDir,rpcPort,@@ -50,9 +175,7 @@ test.describe('settings persistence', () => {await deletion.click()await main.getByRole('option', { name: 'Delete permanently' }).click()await expect(- main.getByText(- 'Files are deleted directly and cannot be restored from the trash.'- )+ main.getByText('Deleted files cannot be restored from the trash.')).toBeVisible()await main.screenshot({path: testInfo.outputPath('file-deletion-settings.png'),@@ -86,17 +209,20 @@ test.describe('settings persistence', () => {await expect(() => waitForEngineReady(main)).toPass({ timeout: 15000 })await main.getByRole('link', { name: 'Settings', exact: true }).click()await main.getByText('BitTorrent', { exact: true }).first().click()+ await expect(+ main.getByRole('button', { name: 'Save', exact: true })+ ).toBeEnabled()return main}try {let main = await openBitTorrentSettings()const toggle = main.getByRole('switch', {- name: 'Download all files when selection times out',+ name: 'Download all if no selection is made',})await expect(toggle).not.toBeChecked()await toggle.click()const timeout = main.getByRole('spinbutton', {- name: 'File selection timeout (seconds)',+ name: 'Time to choose files (s)',})await expect(timeout).toHaveValue('60')await timeout.fill('120')@@ -107,12 +233,12 @@ test.describe('settings persistence', () => {main = await openBitTorrentSettings()await expect(main.getByRole('switch', {- name: 'Download all files when selection times out',+ name: 'Download all if no selection is made',})).toBeChecked()await expect(main.getByRole('spinbutton', {- name: 'File selection timeout (seconds)',+ name: 'Time to choose files (s)',})).toHaveValue('120')} finally {@@ -178,43 +304,29 @@ test.describe('settings persistence', () => {}})- test('notifyOnComplete switch survives an app restart', async ({+ test('notification channel selection survives an app restart', async ({userDataDir,rpcPort,}) => {- // ─── Run 1: toggle the switch and Apply ──────────────────────let app = await launchMotrix({ userDataDir, rpcPort })- let main = await openMain(app)- await openGeneralSettings(main)-- const switch1 = main.getByRole('switch', { name: SWITCH_LABEL })- const before = await switch1.getAttribute('aria-checked')- expect(before).not.toBeNull()-- await switch1.click()- // Toggle is local to react-hook-form until Apply commits.- // Waiting on aria-checked flipping confirms the click registered- // before we click Apply.- const expectedAfter = before === 'true' ? 'false' : 'true'- await expect(switch1).toHaveAttribute('aria-checked', expectedAfter)-- // Apply: handler awaits transport.invoke(UpdateSettings),- // which awaits SettingsManager.update -> writeFile.- // Dialog closes after success → switch leaves the DOM.- await main.getByRole('button', { name: 'Save' }).click()- await expect(switch1).toBeHidden()-- await app.close()-- // ─── Run 2: reopen, navigate back, assert persisted state ────- app = await launchMotrix({ userDataDir, rpcPort })- main = await openMain(app)- await openGeneralSettings(main)-- const switch2 = main.getByRole('switch', { name: SWITCH_LABEL })- await expect(switch2).toHaveAttribute('aria-checked', expectedAfter)-- await app.close()+ try {+ let main = await openMain(app)+ await openGeneralSettings(main)+ await chooseNotification(main, NOTIFICATION_LABEL, 'Off')+ await main.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(+ main.getByRole('combobox', { name: NOTIFICATION_LABEL })+ ).toBeHidden()+ await app.close()+ app = await launchMotrix({ userDataDir, rpcPort })+ main = await openMain(app)+ await openGeneralSettings(main)+ await expect(+ main.getByRole('combobox', { name: NOTIFICATION_LABEL })+ ).toHaveText('Off')+ } finally {+ await app.close().catch(() => {})+ }})})diff --git a/src/core/nat/diagnostic-scheduler.test.ts b/src/core/nat/diagnostic-scheduler.test.tsnew file mode 100644index 00000000..8f466184--- /dev/null+++ b/src/core/nat/diagnostic-scheduler.test.ts@@ -0,0 +1,80 @@+import { DEFAULT_NAT_SETTINGS } from '@shared/schemas/nat-settings'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { DiagnosticScheduler } from './diagnostic-scheduler'++afterEach(() => vi.useRealTimers())+function fixture() {+ vi.useFakeTimers()+ const settings = {+ ...DEFAULT_NAT_SETTINGS,+ autoDiagnostic: true,+ natTypeDetectionEnabled: true,+ stunServers: ['stun.example.com:3478'],+ diagnosticIntervalSec: 300,+ }+ const run = vi.fn(async (_signal: AbortSignal) => {})+ const error = vi.fn()+ const scheduler = new DiagnosticScheduler(() => settings, run, error)+ return { settings, run, error, scheduler }+}+describe('Network diagnostic scheduling', () => {+ it('runs at the saved interval and stops all future checks', async () => {+ const { scheduler, run } = fixture()+ scheduler.start()+ await vi.advanceTimersByTimeAsync(299999)+ expect(run).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(run).toHaveBeenCalledOnce()+ await scheduler.stop()+ await vi.advanceTimersByTimeAsync(600000)+ expect(run).toHaveBeenCalledOnce()+ })+ it('does not run when automatic checks or both diagnostic types are off', async () => {+ const { scheduler, run, settings } = fixture()+ settings.autoDiagnostic = false+ scheduler.start()+ await vi.advanceTimersByTimeAsync(300000)+ expect(run).not.toHaveBeenCalled()+ settings.autoDiagnostic = true+ settings.natTypeDetectionEnabled = false+ settings.portReachabilityCheckEnabled = false+ scheduler.refresh()+ await vi.advanceTimersByTimeAsync(300000)+ expect(run).not.toHaveBeenCalled()+ await scheduler.stop()+ })+ it('aborts an in-flight check on changes and never overlaps its replacement', async () => {+ const { scheduler, run, settings } = fixture()+ let finish!: () => void+ run.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve+ })+ )+ scheduler.start()+ await vi.advanceTimersByTimeAsync(300000)+ const signal = run.mock.calls[0][0]+ settings.diagnosticIntervalSec = 600+ scheduler.refresh()+ expect(signal.aborted).toBe(true)+ await vi.advanceTimersByTimeAsync(600000)+ expect(run).toHaveBeenCalledOnce()+ finish()+ await vi.advanceTimersByTimeAsync(0)+ expect(run).toHaveBeenCalledTimes(2)+ await scheduler.stop()+ })+ it('does not reset the timer for unrelated settings events and recovers after errors', async () => {+ const { scheduler, run, error } = fixture()+ run.mockRejectedValueOnce(Error('offline'))+ scheduler.start()+ await vi.advanceTimersByTimeAsync(150000)+ scheduler.refresh()+ await vi.advanceTimersByTimeAsync(150000)+ expect(error).toHaveBeenCalledOnce()+ await vi.advanceTimersByTimeAsync(300000)+ expect(run).toHaveBeenCalledTimes(2)+ await scheduler.stop()+ })+})diff --git a/src/core/nat/diagnostic-scheduler.ts b/src/core/nat/diagnostic-scheduler.tsnew file mode 100644index 00000000..d8e76134--- /dev/null+++ b/src/core/nat/diagnostic-scheduler.ts@@ -0,0 +1,82 @@+import type { NatSettings } from '@shared/types/settings'++/** App-owned scheduling; the NAT library continues to own protocol operations. */+export class DiagnosticScheduler {+ private timer?: ReturnType<typeof setTimeout>+ private controller?: AbortController+ private running?: Promise<void>+ private active = false+ private revision = 0+ private fingerprint = ''++ constructor(+ private readonly read: () => NatSettings,+ private readonly run: (signal: AbortSignal) => Promise<void>,+ private readonly onError: (error: unknown) => void+ ) {}++ start() {+ this.active = true+ this.refresh()+ }+ refresh() {+ if (!this.active) return+ const settings = this.read()+ const key = JSON.stringify([+ settings.autoDiagnostic,+ settings.diagnosticIntervalSec,+ settings.natTypeDetectionEnabled,+ settings.stunServers,+ settings.portReachabilityCheckEnabled,+ settings.portCheckerEndpoints,+ ])+ if (key === this.fingerprint) return+ this.fingerprint = key+ this.revision+++ clearTimeout(this.timer)+ this.controller?.abort()+ this.schedule()+ }+ private enabled() {+ const settings = this.read()+ return (+ this.active &&+ settings.autoDiagnostic &&+ ((settings.natTypeDetectionEnabled && settings.stunServers.length > 0) ||+ (settings.portReachabilityCheckEnabled &&+ settings.portCheckerEndpoints.length > 0))+ )+ }+ private schedule() {+ if (!this.enabled()) return+ const revision = this.revision+ this.timer = setTimeout(() => {+ if (revision !== this.revision || !this.enabled()) return+ this.running = this.tick(revision)+ }, this.read().diagnosticIntervalSec * 1000)+ this.timer.unref?.()+ }+ private async tick(revision: number) {+ // A changed schedule waits for the prior (aborted) check before starting.+ const previous = this.running+ await previous+ if (revision !== this.revision || !this.enabled()) return+ const controller = new AbortController()+ this.controller = controller+ try {+ await this.run(controller.signal)+ } catch (error) {+ if (!controller.signal.aborted) this.onError(error)+ } finally {+ if (revision === this.revision && this.active) this.schedule()+ }+ }+ async stop() {+ this.active = false+ this.revision+++ this.fingerprint = ''+ clearTimeout(this.timer)+ this.controller?.abort()+ await this.running+ }+}diff --git a/src/core/notifications/notification-center.test.ts b/src/core/notifications/notification-center.test.tsindex 00e6c17c..306d18a4 100644--- a/src/core/notifications/notification-center.test.ts+++ b/src/core/notifications/notification-center.test.ts@@ -2,6 +2,10 @@ import { EventBus } from '@core/events/event-bus'import { MotrixDatabase } from '@core/session/motrix-database'import { Events } from '@shared/protocol/events'import type { AppNotification } from '@shared/types/notification'+import {+ getHiddenNotificationKinds,+ NotificationKinds,+} from '@shared/types/notification'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { NotificationCenter, type NotifyInput } from './notification-center'import { makeDiagnosisOccurrence, makeLog } from './notification-test-fixtures'@@ -280,3 +284,90 @@ describe('NotificationCenter read-only passthroughs', () => {expect(center.list(1)).toHaveLength(1)})})++describe('desktop notification visibility', () => {+ it('filters before the list limit, retains hidden rows and ledger, and leaves server views unchanged', () => {+ const preferences = {+ notifyInAppOnComplete: false,+ notifyInAppOnError: true,+ }+ const emit = vi.fn()+ const center = new NotificationCenter({+ store: db,+ emit,+ log: makeLog(),+ getHiddenKinds: () => getHiddenNotificationKinds(preferences),+ })+ center.notify(makeInput({ sourceKey: 'failure', createdAt: 1 }))+ for (let index = 0; index < 120; index++) {+ center.notify(+ makeInput({+ sourceKey: `complete-${index}`,+ kind: NotificationKinds.TaskComplete,+ severity: 'info',+ createdAt: index + 2,+ })+ )+ }+ expect(center.list().map((row) => row.sourceKey)).toEqual(['failure'])+ expect(center.unreadCount()).toBe(1)+ expect(+ emit.mock.calls.filter(+ ([channel]) => channel === Events.NotificationAdded+ )+ ).toHaveLength(121)+ const server = new NotificationCenter({+ store: db,+ emit: vi.fn(),+ log: makeLog(),+ })+ expect(server.list()).toHaveLength(100)+ expect(server.unreadCount()).toBe(121)+ expect(center.markAllRead()).toBe(1)+ expect(server.unreadCount()).toBe(120)+ expect(center.clear()).toBe(1)+ expect(server.list(500)).toHaveLength(120)+ preferences.notifyInAppOnComplete = true+ emit.mockClear()+ expect(center.unreadCount()).toBe(120)+ expect(center.list()).toHaveLength(100)+ expect(emit).not.toHaveBeenCalled()+ expect(center.notify(makeInput({ sourceKey: 'complete-0' }))).toEqual({+ fresh: false,+ })+ })++ it('keeps application alerts visible and upgrades diagnoses while task failures are hidden', () => {+ const preferences = {+ notifyInAppOnComplete: false,+ notifyInAppOnError: false,+ }+ const center = new NotificationCenter({+ store: db,+ emit: vi.fn(),+ log: makeLog(),+ getHiddenKinds: () => getHiddenNotificationKinds(preferences),+ })+ center.notify(makeInput({ sourceKey: 'hidden-error' }))+ const alerts = Object.values(NotificationKinds).filter(+ (kind) =>+ kind !== NotificationKinds.TaskError &&+ kind !== NotificationKinds.TaskComplete+ )+ for (const kind of [...alerts, 'future-alert'])+ center.notify(makeInput({ sourceKey: kind, kind }))+ expect(center.unreadCount()).toBe(alerts.length + 1)+ expect(+ center.list().every((row) => row.kind !== NotificationKinds.TaskError)+ ).toBe(true)+ expect(+ center.applyDiagnosisUpgrade(+ makeDiagnosisOccurrence({ terminalOccurrenceId: 'hidden-error' })+ )+ ).toBe(true)+ preferences.notifyInAppOnError = true+ expect(+ center.list().find((row) => row.sourceKey === 'hidden-error')?.bodyKey+ ).toBe('task.error.reason.diskFull')+ })+})diff --git a/src/core/notifications/notification-center.ts b/src/core/notifications/notification-center.tsindex bb3cf8c5..f5b1ef06 100644--- a/src/core/notifications/notification-center.ts+++ b/src/core/notifications/notification-center.ts@@ -30,6 +30,8 @@ export interface NotificationCenterDeps {// `EventBusOptions.onListenerError`).emit: (channel: EventChannel, payload?: unknown) => voidnow?: () => number+ /** A shell-specific display policy. Omitted by the server to show all kinds. */+ getHiddenKinds?: () => readonly string[]log: Pick<Logger, 'warn' | 'error'>}@@ -104,7 +106,10 @@ export class NotificationCenter {}markAllRead(): number {- const count = this.deps.store.markAllNotificationsRead(this.now())+ const count = this.deps.store.markAllNotificationsRead(+ this.now(),+ this.deps.getHiddenKinds?.()+ )if (count > 0) this.deps.emit(Events.NotificationsChanged)return count}@@ -116,18 +121,23 @@ export class NotificationCenter {}clear(): number {- const count = this.deps.store.clearNotifications()+ const count = this.deps.store.clearNotifications(+ this.deps.getHiddenKinds?.()+ )if (count > 0) this.deps.emit(Events.NotificationsChanged)return count}list(limit?: number): AppNotification[] {- return limit === undefined- ? this.deps.store.listNotifications()- : this.deps.store.listNotifications(limit)+ return this.deps.store.listNotifications(+ limit,+ this.deps.getHiddenKinds?.()+ )}unreadCount(): number {- return this.deps.store.getUnreadNotificationCount()+ return this.deps.store.getUnreadNotificationCount(+ this.deps.getHiddenKinds?.()+ )}}diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.tsindex c5122bbc..09c79ef3 100644--- a/src/core/session/motrix-database.ts+++ b/src/core/session/motrix-database.ts@@ -486,22 +486,25 @@ export class MotrixDatabase {`SELECT id, source_key, kind, severity, title_key, title_params,body_key, body_params, task_id, created_at, read_atFROM notifications+ WHERE kind NOT IN (SELECT value FROM json_each(?))ORDER BY created_at DESC, rowid DESCLIMIT ?`)this.stmtGetUnreadNotificationCount = this.db.prepare(- 'SELECT COUNT(*) AS c FROM notifications WHERE read_at IS NULL'+ 'SELECT COUNT(*) AS c FROM notifications WHERE read_at IS NULL AND kind NOT IN (SELECT value FROM json_each(?))')this.stmtMarkNotificationRead = this.db.prepare('UPDATE notifications SET read_at = ? WHERE id = ?')this.stmtMarkAllNotificationsRead = this.db.prepare(- 'UPDATE notifications SET read_at = ? WHERE read_at IS NULL'+ 'UPDATE notifications SET read_at = ? WHERE read_at IS NULL AND kind NOT IN (SELECT value FROM json_each(?))')this.stmtDeleteNotification = this.db.prepare('DELETE FROM notifications WHERE id = ?')- this.stmtClearNotifications = this.db.prepare('DELETE FROM notifications')+ this.stmtClearNotifications = this.db.prepare(+ 'DELETE FROM notifications WHERE kind NOT IN (SELECT value FROM json_each(?))'+ )this.stmtUpdateNotificationBySourceKey = this.db.prepare('UPDATE notifications SET body_key = ?, body_params = ? WHERE source_key = ?')@@ -1222,13 +1225,21 @@ export class MotrixDatabase {/** Display rows, newest first. Malformed `title_params`/`body_params`* JSON on disk reads back as `null` (validate-on-read) rather than* throwing or trusting an unreadable value. */- listNotifications(limit = NOTIFICATION_LIST_LIMIT): AppNotification[] {- const rows = this.stmtListNotifications.all(limit) as RawNotificationRow[]+ listNotifications(+ limit = NOTIFICATION_LIST_LIMIT,+ hiddenKinds: readonly string[] = []+ ): AppNotification[] {+ const rows = this.stmtListNotifications.all(+ JSON.stringify(hiddenKinds),+ limit+ ) as RawNotificationRow[]return rows.map(mapNotificationRow)}- getUnreadNotificationCount(): number {- const row = this.stmtGetUnreadNotificationCount.get() as { c: number }+ getUnreadNotificationCount(hiddenKinds: readonly string[] = []): number {+ const row = this.stmtGetUnreadNotificationCount.get(+ JSON.stringify(hiddenKinds)+ ) as { c: number }return row.c}@@ -1236,8 +1247,14 @@ export class MotrixDatabase {return this.stmtMarkNotificationRead.run(readAt, id).changes > 0}- markAllNotificationsRead(readAt: number): number {- return this.stmtMarkAllNotificationsRead.run(readAt).changes+ markAllNotificationsRead(+ readAt: number,+ hiddenKinds: readonly string[] = []+ ): number {+ return this.stmtMarkAllNotificationsRead.run(+ readAt,+ JSON.stringify(hiddenKinds)+ ).changes}deleteNotification(id: string): boolean {@@ -1246,8 +1263,8 @@ export class MotrixDatabase {/** Display table only — the ledger (`notification_occurrences`) is* untouched by delete/clear/prune, per the delivery-idempotency spec. */- clearNotifications(): number {- return this.stmtClearNotifications.run().changes+ clearNotifications(hiddenKinds: readonly string[] = []): number {+ return this.stmtClearNotifications.run(JSON.stringify(hiddenKinds)).changes}updateNotificationBySourceKey(diff --git a/src/core/settings/downloads-settings.test.ts b/src/core/settings/downloads-settings.test.tsnew file mode 100644index 00000000..16018b48--- /dev/null+++ b/src/core/settings/downloads-settings.test.ts@@ -0,0 +1,168 @@+import { mkdir, mkdtemp, readFile, realpath, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { createSaveDownloadsSettingsHandler } from './downloads-settings'+import { SettingsManager } from './settings-manager'++const roots: string[] = []+const empty = { addFavorites: [], removeFavorites: [], removeRecent: [] }+afterEach(async () => {+ vi.restoreAllMocks()+ await Promise.all(+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))+ )+})+async function fixture() {+ const root = await realpath(+ await mkdtemp(path.join(tmpdir(), 'motrix-downloads-'))+ )+ roots.push(root)+ const file = path.join(root, 'settings.json')+ const change = vi.fn()+ const manager = new SettingsManager(file, { onChange: change })+ await manager.load()+ change.mockClear()+ const request = () => ({+ expectedRevision: manager.getDownloadsSettingsSnapshot().revision,+ settings: {},+ directories: empty,+ })+ return { root, file, change, manager, request }+}+describe('Downloads atomic settings save', () => {+ it('durably commits folders, clipboard, performance and nested speed edits together', async () => {+ const { root, file, change, manager, request } = await fixture()+ const folder = path.join(root, 'downloads ')+ await mkdir(folder)+ await manager.update({ speedLimit: { base: { upload: 777 } } })+ change.mockClear()+ const apply = vi.fn(async () => {+ const disk = JSON.parse(await readFile(file, 'utf8'))+ expect(disk.app).toMatchObject({+ defaultSaveDir: folder,+ autofillClipboardLinks: false,+ directoryPreferences: { favorites: [folder] },+ })+ expect(disk.engine.maxConcurrentDownloads).toBe(8)+ expect(disk.speedLimit.base).toEqual({ upload: 777, download: 5000 })+ })+ const result = await createSaveDownloadsSettingsHandler(manager, { apply })(+ {+ ...request(),+ settings: {+ app: { defaultSaveDir: folder, autofillClipboardLinks: false },+ engine: { maxConcurrentDownloads: 8 },+ speedLimit: { base: { download: 5000 } },+ },+ directories: { ...empty, addFavorites: [folder] },+ }+ )+ expect(result).toMatchObject({ ok: true, update: { saved: true } })+ expect(change).toHaveBeenCalledOnce()+ expect(apply).toHaveBeenCalledOnce()+ const restored = new SettingsManager(file)+ await restored.load()+ expect(restored.getApp().directoryPreferences.favorites).toEqual([folder])+ expect(restored.get().speedLimit.base).toEqual({+ upload: 777,+ download: 5000,+ })+ })+ it('does not commit any field when a destination is invalid', async () => {+ const { root, manager, request, change } = await fixture()+ const before = structuredClone(manager.get())+ const result = await createSaveDownloadsSettingsHandler(manager)({+ ...request(),+ settings: {+ app: { autofillClipboardLinks: false },+ engine: { maxConcurrentDownloads: 8 },+ },+ directories: { ...empty, addFavorites: [path.join(root, 'missing')] },+ })+ expect(result.ok).toBe(false)+ expect(manager.get()).toEqual(before)+ expect(change).not.toHaveBeenCalled()+ })+ it('rejects stale revisions without losing newer folders or untouched speed leaves', async () => {+ const { manager, request } = await fixture()+ const stale = request()+ await manager.mutateDirectoryPreferences({+ action: 'recordRecent',+ path: '/newer',+ })+ await manager.update({ speedLimit: { base: { upload: 444 } } })+ const save = createSaveDownloadsSettingsHandler(manager)+ const conflict = await save({+ ...stale,+ settings: { speedLimit: { base: { download: 222 } } },+ })+ expect(conflict).toMatchObject({+ ok: false,+ error: { code: 'conflict' },+ snapshot: {+ settings: { speedLimit: { base: { upload: 444 } } },+ directoryPreferences: { recent: ['/newer'] },+ },+ })+ expect(+ await save({+ ...request(),+ settings: { speedLimit: { base: { download: 222 } } },+ })+ ).toMatchObject({ ok: true })+ expect(manager.get().speedLimit.base).toEqual({+ upload: 444,+ download: 222,+ })+ })+ it('fences an older request still resolving a directory with a pristine save', async () => {+ const { manager, request } = await fixture()+ let resolve!: (path: string) => void+ const save = createSaveDownloadsSettingsHandler(manager, {+ resolveDefaultDirectory: () =>+ new Promise((r) => {+ resolve = r+ }),+ })+ const old = save({+ ...request(),+ settings: { app: { defaultSaveDir: '/old' } },+ })+ expect(await save(request())).toMatchObject({ ok: true })+ resolve('/old')+ expect(await old).toMatchObject({ ok: false, error: { code: 'conflict' } })+ expect(manager.getApp().defaultSaveDir).not.toBe('/old')+ })+ it('reports committed success plus an apply warning when runtime application fails', async () => {+ const { manager, request } = await fixture()+ const result = await createSaveDownloadsSettingsHandler(manager, {+ apply: async () => {+ throw Error('unavailable')+ },+ })({ ...request(), settings: { engine: { maxConcurrentDownloads: 8 } } })+ expect(result).toMatchObject({+ ok: true,+ update: { applicationFailed: true },+ value: { settings: { engine: { maxConcurrentDownloads: 8 } } },+ })+ })+ it.each([+ { engine: { split: undefined } },+ { speedLimit: { base: { download: undefined } } },+ { app: { runMode: 2 } },+ { engine: { split: 129 } },+ ])(+ 'rejects invalid or out-of-scope patches without changing state: %j',+ async (settings) => {+ const { manager, request, change } = await fixture()+ expect(+ await createSaveDownloadsSettingsHandler(manager)({+ ...request(),+ settings,+ })+ ).toMatchObject({ ok: false })+ expect(change).not.toHaveBeenCalled()+ }+ )+})diff --git a/src/core/settings/downloads-settings.ts b/src/core/settings/downloads-settings.tsnew file mode 100644index 00000000..2c3ed062--- /dev/null+++ b/src/core/settings/downloads-settings.ts@@ -0,0 +1,86 @@+import { constants } from 'node:fs'+import { access } from 'node:fs/promises'+import { AppError } from '@shared/errors'+import {+ type DownloadsSettingsResult,+ saveDownloadsSettingsRequestSchema,+} from '@shared/schemas/downloads-settings'+import { GetGeneralSettingsDraftRequestSchema } from '@shared/schemas/general-settings'+import type { SettingsUpdateResult } from '@shared/schemas/settings-update'+import type { EngineSettings } from '@shared/types/settings'+import {+ directoryPreferenceFailure,+ resolveDesktopDirectory,+} from './directory-preferences'+import type { SettingsManager } from './settings-manager'++export function createGetDownloadsSettingsDraftHandler(+ settings: SettingsManager+) {+ return async (raw: unknown): Promise<DownloadsSettingsResult> => {+ if (!GetGeneralSettingsDraftRequestSchema.safeParse(raw).success)+ return { ok: false, error: { code: 'invalidPath' } }+ return { ok: true, value: settings.getDownloadsSettingsSnapshot() }+ }+}++export function createSaveDownloadsSettingsHandler(+ settings: SettingsManager,+ options: {+ resolveFavorite?: (path: string) => Promise<string>+ resolveDefaultDirectory?: (path: string) => Promise<string>+ apply?: (+ oldEngine: EngineSettings,+ update: SettingsUpdateResult+ ) => Promise<void>+ } = {}+) {+ let tail: Promise<void> = Promise.resolve()+ return async (raw: unknown): Promise<DownloadsSettingsResult> => {+ const parsed = saveDownloadsSettingsRequestSchema.safeParse(raw)+ if (!parsed.success) return { ok: false, error: { code: 'invalidPath' } }+ try {+ const request = parsed.data+ for (const path of request.directories.addFavorites) {+ const resolved = await (+ options.resolveFavorite ?? resolveDesktopDirectory+ )(path)+ if (resolved !== path)+ throw Object.assign(new Error('Noncanonical favorite'), {+ code: 'EINVAL',+ })+ }+ if (request.settings.app?.defaultSaveDir !== undefined) {+ const resolve =+ options.resolveDefaultDirectory ??+ (async (path: string) => {+ const canonical = await resolveDesktopDirectory(path)+ await access(canonical, constants.W_OK | constants.X_OK)+ return canonical+ })+ request.settings.app.defaultSaveDir = await resolve(+ request.settings.app.defaultSaveDir+ )+ }+ const oldEngine = structuredClone(settings.getEngine())+ const result = await settings.saveDownloadsSettings(request)+ if (!result.ok || !result.update) return result+ const update = result.update+ const apply = tail.then(() => options.apply?.(oldEngine, update))+ tail = apply.then(+ () => undefined,+ () => undefined+ )+ try {+ await apply+ } catch {+ update.applicationFailed = true+ }+ return result+ } catch (error) {+ return directoryPreferenceFailure(+ error instanceof AppError && error.cause ? error.cause : error+ )+ }+ }+}diff --git a/src/core/settings/general-settings.test.ts b/src/core/settings/general-settings.test.tsindex 5ea5968b..a656ebce 100644--- a/src/core/settings/general-settings.test.ts+++ b/src/core/settings/general-settings.test.ts@@ -41,6 +41,27 @@ async function fixture() {}describe('General settings save handler', () => {+ it('persists desktop notification preferences independently of native settings', async () => {+ const { manager, file } = await fixture()+ const preferences = {+ notifyInAppOnComplete: false,+ notifyInAppOnError: false,+ notificationBadgeStyle: 'hidden',+ }+ const save = createCurrentSave(manager)+ expect(await save({ app: preferences, directories: empty })).toMatchObject({+ ok: true,+ value: { app: preferences },+ })+ const restored = new SettingsManager(file)+ await restored.load()+ expect(restored.getApp()).toMatchObject({+ ...preferences,+ notifyOnComplete: true,+ notifyOnError: true,+ })+ })+it('validates every addition then atomically persists General fields and exact directory deltas', async () => {const { root, file, manager, change } = await fixture()const destination = path.join(root, 'destination ')diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.tsindex 635c7221..d19cece2 100644--- a/src/core/settings/settings-manager.ts+++ b/src/core/settings/settings-manager.ts@@ -21,6 +21,13 @@ import {type MutateDirectoryPreferencesRequest,MutateDirectoryPreferencesRequestSchema,} from '@shared/schemas/directory-preferences'+import {+ type DownloadsSettingsResult,+ type DownloadsSettingsSnapshot,+ downloadsSettingsSchema,+ type SaveDownloadsSettingsRequest,+ saveDownloadsSettingsRequestSchema,+} from '@shared/schemas/downloads-settings'import {GeneralSettingsAppSchema,type GeneralSettingsResult,@@ -291,6 +298,52 @@ export class SettingsManager {}}+ getDownloadsSettingsSnapshot(): DownloadsSettingsSnapshot {+ return {+ revision: this.generalSettingsRevision,+ settings: downloadsSettingsSchema.parse(this.settings),+ directoryPreferences: structuredClone(+ this.settings.app.directoryPreferences+ ),+ }+ }++ async saveDownloadsSettings(+ raw: SaveDownloadsSettingsRequest+ ): Promise<DownloadsSettingsResult> {+ const parsed = saveDownloadsSettingsRequestSchema.safeParse(raw)+ if (!parsed.success) return { ok: false, error: { code: 'invalidPath' } }+ const { settings, directories, expectedRevision } = parsed.data+ return this.enqueueMutation(async () => {+ if (expectedRevision !== this.generalSettingsRevision)+ return {+ ok: false,+ error: { code: 'conflict' },+ snapshot: this.getDownloadsSettingsSnapshot(),+ }+ const preferences = structuredClone(+ this.settings.app.directoryPreferences+ )+ preferences.favorites = [+ ...new Set([+ ...preferences.favorites.filter(+ (path) => !directories.removeFavorites.includes(path)+ ),+ ...directories.addFavorites,+ ]),+ ]+ if (preferences.favorites.length > DIRECTORY_FAVORITES_LIMIT)+ return { ok: false, error: { code: 'limitReached' } }+ preferences.recent = preferences.recent.filter(+ (path) => !directories.removeRecent.includes(path)+ )+ // One durable write owns directory deltas, the default folder and all+ // download settings. An empty write still fences timed-out predecessors.+ const update = await this.persistUpdate(settings, preferences)+ return { ok: true, value: this.getDownloadsSettingsSnapshot(), update }+ })+ }+private commitSettings(old: AppSettings, next: AppSettings): void {this.settings = nextthis.generalSettingsRevision = randomUUID()@@ -519,10 +572,12 @@ export class SettingsManager {}private async persistUpdate(- partial: DeepPartial<AppSettings>+ partial: DeepPartial<AppSettings>,+ directories?: AppSettings['app']['directoryPreferences']): Promise<UpdateResult> {const old = structuredClone(this.settings)const next = structuredClone(this.settings)+ if (directories) next.app.directoryPreferences = directoriesconst changedRestartKeys: string[] = []const changedAppRestartKeys: string[] = []diff --git a/src/main/index.ts b/src/main/index.tsindex c0ccb065..73fd6b7e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -133,6 +133,7 @@ import {import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'import { EngineState } from '@shared/types/engine'import type { AppNotification } from '@shared/types/notification'+import { getHiddenNotificationKinds } from '@shared/types/notification'import type { AppSettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'import { TaskType } from '@shared/types/task'@@ -345,6 +346,13 @@ const settingsManager = new SettingsManager(settingsPath, {...defaultSaveDirOptions,onChange: (old, updated) => {eventBus.emit(Events.SettingsChanged, { old, updated })+ if (+ old.app.notifyInAppOnComplete !== updated.app.notifyInAppOnComplete ||+ old.app.notifyInAppOnError !== updated.app.notifyInAppOnError ||+ old.app.notificationBadgeStyle !== updated.app.notificationBadgeStyle+ ) {+ eventBus.emit(Events.NotificationsChanged)+ }if (old.app.sidebarColor !== updated.app.sidebarColor) {eventBus.emit(Events.SidebarColorChanged, {sidebarColor: updated.app.sidebarColor,@@ -482,6 +490,7 @@ let recoveryService: TaskRecoveryServiceImpl | undefinedlet dnsFallbackRetry: ((taskId: string) => Promise<unknown>) | undefinedlet trayHandle: ReturnType<typeof setupTray> | null = nulllet natManager: NatManager | null = null+let stopNatDiagnostics: (() => Promise<void>) | null = nulllet trackerManager: TrackerManager | null = nulllet menuManager: MenuManager | null = nulllet osNotificationBridge: { dispose(): void } | null = null@@ -591,7 +600,10 @@ function performCleanup(): Promise<void> {safely('magnet', () => magnetTracker?.stopAndDrain()),safely('speed-limit', () => speedLimitController?.stop()),safely('geoip', () => geoipManager?.stop()),- safely('nat', () => natManager?.stop()),+ safely('nat', async () => {+ await stopNatDiagnostics?.()+ await natManager?.stop()+ }),])// Tracker edits pause active tasks while changing bt-tracker. Drain their// unconditional resume compensation while both Session persistence and@@ -1664,7 +1676,9 @@ async function initializeMainProcess(): Promise<void> {// interval. Early forwarding guarantees the eventual LocaleChanged reaches// either the onboarding window or the newly-opened main window (whose// preload buffers it until React subscribes).- setupEventForwarding(eventBus, windowManager)+ setupEventForwarding(eventBus, windowManager, () =>+ getHiddenNotificationKinds(settingsManager.getApp())+ )// Subscribe before notification-center replay. Resolve task paths on click// so notifications follow any output moves made after download completion.@@ -2082,6 +2096,8 @@ async function initializeMainProcess(): Promise<void> {isEngineReady: () => supervisor.getState() === EngineState.Ready,})natManager = natStack.manager+ stopNatDiagnostics = natStack.stopDiagnostics+ natStack.startDiagnostics()log.info('NatManager constructed')const startupGeoipManager = new GeoIPManager({@@ -2619,6 +2635,7 @@ async function initializeMainProcess(): Promise<void> {notificationCenter = new NotificationCenter({store: motrixDb,emit: eventBus.emit.bind(eventBus),+ getHiddenKinds: () => getHiddenNotificationKinds(settingsManager.getApp()),log,})const disposeNotificationIpc = registerNotificationIpc({diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex d682109a..1db853e8 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -1336,6 +1336,51 @@ describe('SetTaskBtTracker handler', () => {})describe('Commands.UpdateSettings', () => {+ it.each([+ { app: { theme: 'dark' } },+ { nat: { diagnosticIntervalSec: 600 } },+ ])(+ 'does not re-enable external checks from a stale patch: %j',+ async (patch) => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-settings-race-'))+ try {+ const manager = new SettingsManager(path.join(root, 'settings.json'))+ await manager.load()+ await manager.update({+ nat: {+ natTypeDetectionEnabled: true,+ portReachabilityCheckEnabled: true,+ autoDiagnostic: true,+ },+ })+ const update = buildCommandHandlers({+ ...fakeCtx(),+ settingsManager: manager,+ } as unknown as CommandContext)[Commands.UpdateSettings]!++ // Both requests read the enabled baseline before either queued write+ // commits. Unrelated fields must not carry those old NAT flags.+ await Promise.all([+ update({+ nat: {+ natTypeDetectionEnabled: false,+ portReachabilityCheckEnabled: false,+ },+ }),+ update(patch),+ ])++ expect(manager.get().nat).toMatchObject({+ natTypeDetectionEnabled: false,+ portReachabilityCheckEnabled: false,+ })+ expect(manager.get()).toMatchObject(patch)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ }+ )+it('awaits locale application and permits retrying an already saved language', async () => {const base = makeSettingsLike(PROXY_OFF)const current = { ...base, app: { ...base.app, language: 'zh-CN' } }diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex f66982b6..e2a1a3d3 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -44,6 +44,7 @@ import type { MotrixDatabase } from '@core/session/motrix-database'import type { SessionManager } from '@core/session/session-manager'import { applySavedSettings } from '@core/settings/apply-saved-settings'import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'+import { createSaveDownloadsSettingsHandler } from '@core/settings/downloads-settings'import { createSaveGeneralSettingsHandler } from '@core/settings/general-settings'import type { SettingsManager } from '@core/settings/settings-manager'import {@@ -950,6 +951,26 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {[Commands.MutateDirectoryPreferences]: directoryPreferences.mutate,+ [Commands.SaveDownloadsSettings]: createSaveDownloadsSettingsHandler(+ settingsManager,+ {+ apply: async (oldEngine, result) => {+ await supervisor.applyDefaultSaveDir(+ settingsManager.getApp().defaultSaveDir+ )+ await supervisor.applyEngineSettings(+ oldEngine,+ settingsManager.getEngine()+ )+ if (result.requiresRestart)+ publishEngineRestartRequired(+ { eventBus, notificationCenter, log },+ result.changedRestartKeys ?? []+ )+ },+ }+ ),+[Commands.SaveGeneralSettings]: createSaveGeneralSettingsHandler(settingsManager,{@@ -1002,13 +1023,34 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {| undefinedconst magnetPreferenceSubmitted =typeof appPartial?.protocols?.magnet === 'boolean'+ const natPartial = partialObj?.nat as+ | Record<string, unknown>+ | null+ | undefinedconst patched = {...partialObj,- nat: {- ...((partialObj?.nat as object | undefined) ?? {}),- natTypeDetectionEnabled: gated.nat.natTypeDetectionEnabled,- portReachabilityCheckEnabled: gated.nat.portReachabilityCheckEnabled,- },+ // The confirmation snapshot can be stale by the time this write is+ // queued. Only replace submitted toggles; copying untouched flags can+ // re-enable external checks disabled by another window in the meantime.+ ...(natPartial && typeof natPartial === 'object'+ ? {+ nat: {+ ...natPartial,+ ...(Object.hasOwn(natPartial, 'natTypeDetectionEnabled')+ ? {+ natTypeDetectionEnabled:+ gated.nat.natTypeDetectionEnabled,+ }+ : {}),+ ...(Object.hasOwn(natPartial, 'portReachabilityCheckEnabled')+ ? {+ portReachabilityCheckEnabled:+ gated.nat.portReachabilityCheckEnabled,+ }+ : {}),+ },+ }+ : {}),}const result = await settingsManager.update(patched)diff --git a/src/main/ipc/events.test.ts b/src/main/ipc/events.test.tsindex e3cd201f..60a41410 100644--- a/src/main/ipc/events.test.ts+++ b/src/main/ipc/events.test.ts@@ -1,5 +1,9 @@import { EventBus } from '@core/events/event-bus'import { Events } from '@shared/protocol/events'+import {+ getHiddenNotificationKinds,+ NotificationKinds,+} from '@shared/types/notification'import { describe, expect, it, vi } from 'vitest'import type { WindowManager } from '../window/window-manager'import { setupEventForwarding } from './events'@@ -36,6 +40,47 @@ function createWindowManager(}describe('setupEventForwarding', () => {+ it('silences only hidden task events in renderers while preserving native subscribers and live preference changes', () => {+ const eventBus = new EventBus()+ const wm = createWindowManager()+ const preferences = {+ notifyInAppOnComplete: false,+ notifyInAppOnError: false,+ }+ setupEventForwarding(eventBus, wm, () =>+ getHiddenNotificationKinds(preferences)+ )+ const nativeSubscriber = vi.fn()+ eventBus.on(Events.NotificationAdded, nativeSubscriber)+ for (const kind of [+ NotificationKinds.TaskComplete,+ NotificationKinds.TaskError,+ ]) {+ eventBus.emit(Events.NotificationAdded, { kind })+ }+ expect(wm.broadcast).not.toHaveBeenCalled()+ expect(nativeSubscriber).toHaveBeenCalledTimes(2)+ for (const kind of [+ NotificationKinds.EngineFailure,+ NotificationKinds.EngineCompatibility,+ 'unknown-alert',+ ]) {+ eventBus.emit(Events.NotificationAdded, { kind })+ expect(wm.broadcast).toHaveBeenCalledWith(Events.NotificationAdded, {+ kind,+ })+ }+ eventBus.emit(Events.NotificationsChanged)+ expect(wm.broadcast).toHaveBeenCalledWith(Events.NotificationsChanged)+ preferences.notifyInAppOnError = true+ eventBus.emit(Events.NotificationAdded, {+ kind: NotificationKinds.TaskError,+ })+ expect(wm.broadcast).toHaveBeenLastCalledWith(Events.NotificationAdded, {+ kind: NotificationKinds.TaskError,+ })+ })+it('broadcasts locale changes to every managed window', () => {const eventBus = new EventBus()const wm = createWindowManager()diff --git a/src/main/ipc/events.ts b/src/main/ipc/events.tsindex 55d98580..7b8e7e60 100644--- a/src/main/ipc/events.ts+++ b/src/main/ipc/events.ts@@ -1,6 +1,7 @@import type { EventBus } from '@core/events/event-bus'import { subscribeForwardableEvents } from '@core/events/forward-events'import { type EventChannel, Events } from '@shared/protocol/events'+import type { AppNotification } from '@shared/types/notification'import type { WindowId } from '@shared/types/window'import type { WindowManager } from '../window/window-manager'@@ -32,9 +33,18 @@ function sendToWindowWhenReady(export function setupEventForwarding(eventBus: EventBus,- windowManager: WindowManager+ windowManager: WindowManager,+ getHiddenNotificationKinds: () => readonly string[] = () => []): void {subscribeForwardableEvents(eventBus, (channel, args) => {+ // Keep the durable event available to the native OS bridge. Only the+ // Electron renderer's transient presentation is filtered here, using+ // current settings synchronously even before the renderer has loaded.+ if (+ channel === Events.NotificationAdded &&+ getHiddenNotificationKinds().includes((args[0] as AppNotification).kind)+ )+ returnwindowManager.broadcast(channel, ...args)})diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.tsindex 7ffa42c0..2419d4eb 100644--- a/src/main/ipc/queries.ts+++ b/src/main/ipc/queries.ts@@ -19,6 +19,7 @@ import type { RegistryClient } from '@core/plugin/registry/registry-client'import { parseElectronProxyChain } from '@core/proxy/system-proxy'import type { MotrixDatabase } from '@core/session/motrix-database'import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'+import { createGetDownloadsSettingsDraftHandler } from '@core/settings/downloads-settings'import { createGetGeneralSettingsDraftHandler } from '@core/settings/general-settings'import type { SettingsManager } from '@core/settings/settings-manager'import type { SpeedLimitController } from '@core/speed-limit/speed-limit-controller'@@ -166,6 +167,8 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {return taskInspectorActivityRuntime.snapshot(params)},+ [Queries.GetDownloadsSettingsDraft]:+ createGetDownloadsSettingsDraftHandler(settingsManager),[Queries.GetGeneralSettingsDraft]:createGetGeneralSettingsDraftHandler(settingsManager),[Queries.GetDirectoryPreferences]:diff --git a/src/main/nat/motrix-nat-manager.test.ts b/src/main/nat/motrix-nat-manager.test.tsindex a5868c08..77e63be1 100644--- a/src/main/nat/motrix-nat-manager.test.ts+++ b/src/main/nat/motrix-nat-manager.test.ts@@ -1,4 +1,10 @@-import { type NatEvent, type NatManagerDeps, NatState } from '@motrix/nat'+import {+ type NatEvent,+ type NatManagerDeps,+ NatPortReachability,+ NatState,+ NatType,+} from '@motrix/nat'import { afterEach, describe, expect, it, vi } from 'vitest'import { MotrixNatManager } from './motrix-nat-manager'@@ -89,6 +95,7 @@ function makeHarness() {const manager = new MotrixNatManager(deps, () => engineReady)return {+ deps,events,manager,networkMonitor,@@ -169,3 +176,78 @@ describe('MotrixNatManager', () => {await harness.manager.stop()})})++describe('Saved network diagnostic preferences', () => {+ it('makes no outbound checks when both switches are disabled', async () => {+ const { manager, deps } = makeHarness()+ await manager.runDiagnostic()+ expect(deps.stunClient.detectNatType).not.toHaveBeenCalled()+ expect(deps.portChecker.checkPortReachable).not.toHaveBeenCalled()+ })+ it('checks the configured incoming port and does not reuse its TCP result for DHT', async () => {+ const { manager, deps } = makeHarness()+ const nat = deps.settingsProvider.getNat()+ deps.settingsProvider.getNat = () => ({+ ...nat,+ natTypeDetectionEnabled: true,+ stunServers: ['stun.example.com:3478'],+ portReachabilityCheckEnabled: true,+ portCheckerEndpoints: ['https://check.example.com'],+ })+ vi.mocked(deps.stunClient.detectNatType).mockResolvedValue({+ ok: true,+ value: { mappedIp: '203.0.113.2', mappedPort: 40000 },+ })+ vi.mocked(deps.portChecker.checkPortReachable).mockResolvedValue({+ ok: true,+ value: { reachable: true },+ })+ await manager.runDiagnostic()+ expect(deps.portChecker.checkPortReachable).toHaveBeenCalledWith(+ expect.objectContaining({+ externalIp: '203.0.113.2',+ port: 6881,+ endpoints: ['https://check.example.com'],+ })+ )+ expect(manager.getStatus().lastDiagnostic).toMatchObject({+ natType: NatType.Unknown,+ portReachability: {+ btListenPort: NatPortReachability.Reachable,+ dhtListenPort: NatPortReachability.Unknown,+ },+ })+ })+ it('does not submit a port check with an unknown external address', async () => {+ const { manager, deps } = makeHarness()+ const nat = deps.settingsProvider.getNat()+ deps.settingsProvider.getNat = () => ({+ ...nat,+ portReachabilityCheckEnabled: true,+ portCheckerEndpoints: ['https://check.example.com'],+ })+ await manager.runDiagnostic()+ expect(deps.portChecker.checkPortReachable).not.toHaveBeenCalled()+ expect(+ manager.getStatus().lastDiagnostic?.portReachability.btListenPort+ ).toBe(NatPortReachability.Unknown)+ })+ it('does not publish a diagnostic aborted during STUN detection', async () => {+ const { manager, deps, events } = makeHarness()+ const nat = deps.settingsProvider.getNat()+ deps.settingsProvider.getNat = () => ({+ ...nat,+ natTypeDetectionEnabled: true,+ stunServers: ['stun.example.com:3478'],+ })+ const controller = new AbortController()+ vi.mocked(deps.stunClient.detectNatType).mockImplementation(async () => {+ controller.abort()+ return { ok: false }+ })+ await manager.runDiagnostic(controller.signal)+ expect(+ events.filter((event) => event.type === 'diagnostic-completed')+ ).toHaveLength(0)+ })+})diff --git a/src/main/nat/motrix-nat-manager.ts b/src/main/nat/motrix-nat-manager.tsindex 3460ccce..233552b4 100644--- a/src/main/nat/motrix-nat-manager.ts+++ b/src/main/nat/motrix-nat-manager.ts@@ -1,4 +1,12 @@-import { NatManager, type NatManagerDeps, NatState } from '@motrix/nat'+import {+ type NatDiagnosticResult,+ NatManager,+ type NatManagerDeps,+ NatPortReachability,+ NatProtocol,+ NatState,+ NatType,+} from '@motrix/nat'/*** App lifecycle fixes layered over the reusable NAT package.@@ -17,6 +25,106 @@ export class MotrixNatManager extends NatManager {super(deps)}+ private diagnostic: NatDiagnosticResult | null = null+ private diagnosticInFlight: Promise<void> | null = null++ override getStatus() {+ return { ...super.getStatus(), lastDiagnostic: this.diagnostic }+ }++ override async runDiagnostic(signal?: AbortSignal): Promise<void> {+ if (this.diagnosticInFlight) return this.diagnosticInFlight+ this.diagnosticInFlight = this.checkDiagnostics(signal)+ try {+ await this.diagnosticInFlight+ } finally {+ this.diagnosticInFlight = null+ }+ }++ private async checkDiagnostics(signal?: AbortSignal) {+ const nat = this.deps.settingsProvider.getNat()+ const engine = this.deps.settingsProvider.getEngine()+ if (signal?.aborted) return+ const result: NatDiagnosticResult = {+ runAt: this.now(),+ natType: NatType.Unknown,+ gatewayInfo: this.gatewayInfo,+ portReachability: {+ btListenPort: NatPortReachability.Unknown,+ dhtListenPort: NatPortReachability.Unknown,+ },+ protocolAvailability: {+ pcp:+ this.gatewayInfo?.supportedProtocols.includes(NatProtocol.Pcp) ??+ false,+ natpmp:+ this.gatewayInfo?.supportedProtocols.includes(NatProtocol.NatPmp) ??+ false,+ upnp:+ this.gatewayInfo?.supportedProtocols.includes(NatProtocol.Upnp) ??+ false,+ },+ healthScore: 'fair',+ recommendations: [],+ }+ let externalIp = this.gatewayInfo?.externalIp ?? ''+ if (nat.natTypeDetectionEnabled && nat.stunServers.length > 0) {+ const detected = await this.deps.stunClient.detectNatType({+ servers: nat.stunServers,+ timeoutMs: 3000,+ signal,+ })+ if (signal?.aborted) return+ if (+ detected.ok &&+ detected.value &&+ typeof detected.value === 'object' &&+ 'mappedIp' in detected.value &&+ typeof detected.value.mappedIp === 'string'+ ) {+ externalIp = detected.value.mappedIp+ // A binding response alone cannot classify cone/symmetric NAT.+ if (externalIp === this.deps.networkMonitor.snapshot().internalIp)+ result.natType = NatType.Open+ }+ }+ if (+ nat.portReachabilityCheckEnabled &&+ nat.portCheckerEndpoints.length > 0 &&+ externalIp.length > 0+ ) {+ for (const endpoint of nat.portCheckerEndpoints) {+ if (signal?.aborted) return+ const checked = await this.deps.portChecker.checkPortReachable({+ endpoints: [endpoint],+ externalIp,+ port: engine.listenPort,+ timeoutMs: 5000,+ signal,+ })+ if (signal?.aborted) return+ if (+ checked.ok &&+ checked.value &&+ typeof checked.value === 'object' &&+ 'reachable' in checked.value &&+ typeof checked.value.reachable === 'boolean'+ ) {+ result.portReachability.btListenPort = checked.value.reachable+ ? NatPortReachability.Reachable+ : NatPortReachability.Unreachable+ result.healthScore = checked.value.reachable ? 'good' : 'poor'+ break+ }+ }+ // The current service contract does not specify UDP; never describe a+ // TCP result for the DHT port as evidence of UDP reachability.+ }+ this.diagnostic = result+ this.deps.onEvent({ type: 'diagnostic-completed', result })+ }+protected override async runDiscovery(): Promise<void> {await super.runDiscovery()if (this.isEngineReady() && this.getStatus().state === NatState.Ready) {diff --git a/src/main/nat/nat-manager-factory.test.ts b/src/main/nat/nat-manager-factory.test.tsindex 06cce840..8ad31f72 100644--- a/src/main/nat/nat-manager-factory.test.ts+++ b/src/main/nat/nat-manager-factory.test.ts@@ -144,6 +144,8 @@ describe('createNatManager', () => {expect(result).toEqual({manager: state.managerInstance,networkMonitor: state.networkMonitorInstance,+ startDiagnostics: expect.any(Function),+ stopDiagnostics: expect.any(Function),})expect(state.getLogger).toHaveBeenCalledWith('nat')expect(state.setNatLogger).toHaveBeenCalledWith(state.appLogger)diff --git a/src/main/nat/nat-manager-factory.ts b/src/main/nat/nat-manager-factory.tsindex cdae83d9..f7489498 100644--- a/src/main/nat/nat-manager-factory.ts+++ b/src/main/nat/nat-manager-factory.ts@@ -1,6 +1,7 @@import { networkInterfaces } from 'node:os'import type { EventBus } from '@core/events/event-bus'import { getLogger } from '@core/logger'+import { DiagnosticScheduler } from '@core/nat/diagnostic-scheduler'import { SettingsNatProvider } from '@core/nat/settings-nat-provider'import type { SettingsManager } from '@core/settings/settings-manager'import {@@ -38,6 +39,8 @@ const NAT_ERROR_CODE_MAP = {export interface NatStack {manager: NatManagernetworkMonitor: NetworkMonitor+ startDiagnostics: () => void+ stopDiagnostics: () => Promise<void>}export function createNatManager(args: {@@ -127,7 +130,25 @@ export function createNatManager(args: {isEngineReady)- return { manager, networkMonitor }+ const diagnostics = new DiagnosticScheduler(+ () => settingsManager.get().nat,+ (signal) => manager.runDiagnostic(signal),+ (error) =>+ getLogger('nat').warn({ error }, 'automatic network check failed')+ )+ const refresh = () => diagnostics.refresh()+ return {+ manager,+ networkMonitor,+ startDiagnostics: () => {+ eventBus.on(Events.SettingsChanged, refresh)+ diagnostics.start()+ },+ stopDiagnostics: async () => {+ eventBus.off(Events.SettingsChanged, refresh)+ await diagnostics.stop()+ },+ }}function mapNatErrorCode(code: string): ErrorCode | string {diff --git a/src/main/notifications/os-bridge.test.ts b/src/main/notifications/os-bridge.test.tsindex bb520e3f..735f356c 100644--- a/src/main/notifications/os-bridge.test.ts+++ b/src/main/notifications/os-bridge.test.ts@@ -196,6 +196,26 @@ function baseDeps(overrides: {// Full gating matrix: (window state) x (kind) x (toggle on/off)// ---------------------------------------------------------------------------+it.each([NotificationKinds.TaskComplete, NotificationKinds.TaskError])(+ 'still delivers native %s notifications when desktop in-app surfaces are hidden',+ (kind) => {+ const factory = makeNotificationFactory()+ const { deps, deliver } = baseDeps({+ window: makeWindow(false, false),+ settings: makeSettings({+ notifyInAppOnComplete: false,+ notifyInAppOnError: false,+ notificationBadgeStyle: 'hidden',+ }),+ createNotification: factory.createNotification,+ })+ createOsNotificationBridge(deps)+ deliver(makeNotification({ kind }))+ expect(factory.instances).toHaveLength(1)+ expect(factory.instances[0].show).toHaveBeenCalledOnce()+ }+)+const WINDOW_STATES: Array<{label: stringisVisible: booleandiff --git a/src/renderer/components/notification-center/notifications-nav-item.test.tsx b/src/renderer/components/notification-center/notifications-nav-item.test.tsxindex 976513e7..260c8bc1 100644--- a/src/renderer/components/notification-center/notifications-nav-item.test.tsx+++ b/src/renderer/components/notification-center/notifications-nav-item.test.tsx@@ -2,6 +2,7 @@ import '@testing-library/jest-dom/vitest'import '@renderer/lib/i18n'import { SidebarProvider } from '@renderer/components/ui/sidebar'import { TooltipProvider } from '@renderer/components/ui/tooltip'+import { refreshRendererSettings } from '@renderer/lib/settings-refresh'import { transport } from '@renderer/lib/transport'import { Events } from '@shared/protocol/events'import { Queries } from '@shared/protocol/queries'@@ -12,6 +13,7 @@ import { NotificationsNavItem } from './notifications-nav-item'vi.mock('@renderer/lib/transport', () => ({transport: {+ platform: 'darwin',invoke: vi.fn(),on: vi.fn(),off: vi.fn(),@@ -57,8 +59,9 @@ beforeAll(() => {)})-function mockInvoke(count: number) {+function mockInvoke(count: number, notificationBadgeStyle = 'count') {vi.mocked(transport.invoke).mockImplementation(async (ch: string) => {+ if (ch === Queries.GetSettings) return { app: { notificationBadgeStyle } }if (ch === Queries.ListNotifications) return []if (ch === Queries.GetUnreadNotificationCount) return countreturn undefined@@ -79,10 +82,109 @@ function renderNavItem() {describe('<NotificationsNavItem>', () => {afterEach(() => {+ Object.defineProperty(transport, 'platform', {+ value: 'darwin',+ configurable: true,+ })vi.clearAllMocks()vi.useRealTimers()})+ it('shows an accessible dot without announcing a numeric obligation', async () => {+ mockInvoke(7, 'dot')+ renderNavItem()+ const dot = await screen.findByTestId('notification-badge-dot')+ expect(dot).toHaveAttribute('role', 'status')+ expect(dot).toHaveAttribute('aria-label', 'Unread notifications')+ expect(dot).not.toHaveAttribute('aria-hidden')+ expect(screen.queryByTestId('notification-badge')).not.toBeInTheDocument()+ })++ it('hides both badges and live announcements without hiding navigation', async () => {+ mockInvoke(7, 'hidden')+ renderNavItem()+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Queries.GetUnreadNotificationCount+ )+ )+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ expect(+ screen.queryByTestId('notification-badge-dot')+ ).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Notifications' })).toHaveAttribute(+ 'href',+ '/notifications'+ )+ })++ it('applies a saved badge preference without a notification event', async () => {+ mockInvoke(4)+ renderNavItem()+ await screen.findByTestId('notification-badge')+ mockInvoke(4, 'dot')+ await act(() => refreshRendererSettings())+ expect(screen.getByRole('status')).toHaveAttribute(+ 'aria-label',+ 'Unread notifications'+ )+ mockInvoke(4, 'hidden')+ await act(() => refreshRendererSettings())+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ })++ it('does not flash a count while the desktop preference is loading', async () => {+ let resolveSettings!: (value: unknown) => void+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetSettings)+ return new Promise((resolve) => {+ resolveSettings = resolve+ })+ if (channel === Queries.GetUnreadNotificationCount) return 9+ })+ renderNavItem()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ await act(async () =>+ resolveSettings({ app: { notificationBadgeStyle: 'hidden' } })+ )+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ })++ it('ignores an older count response after a newer refresh hides the badge', async () => {+ let resolveCount!: (value: number) => void+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetSettings)+ return { app: { notificationBadgeStyle: 'count' } }+ if (channel === Queries.GetUnreadNotificationCount)+ return new Promise<number>((resolve) => {+ resolveCount = resolve+ })+ })+ renderNavItem()+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Queries.GetUnreadNotificationCount+ )+ )+ mockInvoke(8, 'hidden')+ await act(() => refreshRendererSettings())+ await act(async () => resolveCount(7))+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ })++ it('keeps the Web badge numeric even if desktop settings hide it', async () => {+ Object.defineProperty(transport, 'platform', {+ value: 'web',+ configurable: true,+ })+ mockInvoke(7, 'hidden')+ renderNavItem()+ expect(await screen.findByTestId('notification-badge')).toHaveTextContent(+ '7'+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetSettings)+ })+it('hides the badge when the unread count is zero', async () => {mockInvoke(0)renderNavItem()diff --git a/src/renderer/components/notification-center/notifications-nav-item.tsx b/src/renderer/components/notification-center/notifications-nav-item.tsxindex b8be5781..9e19ff54 100644--- a/src/renderer/components/notification-center/notifications-nav-item.tsx+++ b/src/renderer/components/notification-center/notifications-nav-item.tsx@@ -24,7 +24,7 @@ const UNREAD_DISPLAY_CAP = 99*/export function NotificationsNavItem() {const { t } = useTranslation()- const { unreadCount } = useNotifications({ countOnly: true })+ const { unreadCount, badgeStyle } = useNotifications({ countOnly: true })const badgeLabel =unreadCount > UNREAD_DISPLAY_CAP? `${UNREAD_DISPLAY_CAP}+`@@ -42,7 +42,15 @@ export function NotificationsNavItem() {><NotificationsIcon /><span className="select-none">{t('nav.notifications')}</span>- {unreadCount > 0 && (+ {unreadCount > 0 && badgeStyle === 'dot' && (+ <span+ data-testid="notification-badge-dot"+ role="status"+ aria-label={t('notification.center.unreadDotAria')}+ className="ml-auto size-1.5 shrink-0 rounded-full bg-[#007aff] group-data-[collapsible=icon]:absolute group-data-[collapsible=icon]:top-1 group-data-[collapsible=icon]:right-1"+ />+ )}+ {unreadCount > 0 && badgeStyle === 'count' && (<><spandata-testid="notification-badge"diff --git a/src/renderer/components/notification-center/use-notifications.ts b/src/renderer/components/notification-center/use-notifications.tsindex 6856698d..558df2dd 100644--- a/src/renderer/components/notification-center/use-notifications.ts+++ b/src/renderer/components/notification-center/use-notifications.ts@@ -1,18 +1,22 @@import { useTransportMirror } from '@renderer/hooks/use-transport-mirror'+import type { SettingsReader } from '@renderer/lib/settings-refresh'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import { Queries } from '@shared/protocol/queries'+import {+ type NotificationBadgeStyle,+ notificationBadgeStyleSchema,+} from '@shared/schemas/app-settings'import type { AppNotification } from '@shared/types/notification'+import type { AppSettings } from '@shared/types/settings'import { useCallback, useState } from 'react'export interface UseNotificationsOptions {/*** Skip `Queries.ListNotifications` entirely and leave `items` at `[]`.- * For a consumer that only ever reads `unreadCount` (the sidebar badge,- * always mounted) this halves the per-refresh IPC cost — one query- * instead of two, and the list query alone reads up to 100 rows and runs- * two `JSON.parse` calls per row for `titleParams`/`bodyParams`.+ * The always-mounted sidebar reads the count and, on desktop, its badge+ * preference. It never needs the list's up to 100 rows and their params.** Mount-constant: the mirror captures wiring at mount; flipping this* later does not trigger a refetch.@@ -23,6 +27,7 @@ export interface UseNotificationsOptions {export interface UseNotificationsResult {items: AppNotification[]unreadCount: number+ badgeStyle: NotificationBadgeStylemarkRead: (id: string) => Promise<void>markAllRead: () => Promise<void>remove: (id: string) => Promise<void>@@ -47,7 +52,8 @@ export interface UseNotificationsResult {* `{ countOnly: true }` (e.g. `NotificationsNavItem`, the always-mounted* sidebar badge) skips the `ListNotifications` invoke and leaves `items`* at `[]` — the return shape is unchanged so callers that only destructure- * `unreadCount` need no other change.+ * `unreadCount` need no other change. The desktop badge preference is loaded+ * before publishing the count so a hidden badge never flashes at startup.** Mutations (`markRead`/`markAllRead`/`remove`/`clear`) only invoke the* matching `Commands` and rely on the `NotificationsChanged` broadcast the@@ -66,27 +72,36 @@ export function useNotifications(const { countOnly = false } = optionsconst [items, setItems] = useState<AppNotification[]>([])const [unreadCount, setUnreadCount] = useState(0)+ const [badgeStyle, setBadgeStyle] = useState<NotificationBadgeStyle>('count')const load = useCallback(- async (stale: () => boolean) => {+ async (stale: () => boolean, read: SettingsReader) => {+ let style: NotificationBadgeStyle = 'count'+ if (countOnly && transport.platform !== 'web') {+ const settings = (await read(Queries.GetSettings)) as+ | AppSettings+ | undefined+ if (stale()) return+ style = notificationBadgeStyleSchema+ .catch('count')+ .parse(settings?.app?.notificationBadgeStyle)+ }const list = countOnly? []- : ((await transport.invoke(- Queries.ListNotifications- )) as AppNotification[])+ : ((await read(Queries.ListNotifications)) as AppNotification[])if (stale()) return- const count = (await transport.invoke(- Queries.GetUnreadNotificationCount- )) as number+ const count = (await read(Queries.GetUnreadNotificationCount)) as numberif (stale()) returnsetItems(list)setUnreadCount(count)+ setBadgeStyle(style)},[countOnly])const { refresh } = useTransportMirror({events: [Events.NotificationsChanged],+ refreshOnSettingsSave: transport.platform !== 'web',load,})@@ -106,5 +121,14 @@ export function useNotifications(await transport.invoke(Commands.ClearNotifications)}, [])- return { items, unreadCount, markRead, markAllRead, remove, clear, refresh }+ return {+ items,+ unreadCount,+ badgeStyle,+ markRead,+ markAllRead,+ remove,+ clear,+ refresh,+ }}diff --git a/src/renderer/components/settings-kit/use-settings-load.tsx b/src/renderer/components/settings-kit/use-settings-load.tsxnew file mode 100644index 00000000..60410b86--- /dev/null+++ b/src/renderer/components/settings-kit/use-settings-load.tsx@@ -0,0 +1,65 @@+import { Button } from '@renderer/components/ui/button'+import { transport } from '@renderer/lib/transport'+import { Queries } from '@shared/protocol/queries'+import type { AppSettings } from '@shared/types/settings'+import { useCallback, useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'++/** Drafts cannot be edited or saved until their authoritative baseline loads. */+export function useSettingsLoad(onLoad: (settings: AppSettings) => void) {+ const callback = useRef(onLoad)+ callback.current = onLoad+ const [state, setState] = useState({ ready: false, error: false })+ const generation = useRef(0)+ const retry = useCallback(async () => {+ const revision = ++generation.current+ setState({ ready: false, error: false })+ try {+ const settings = (await transport.invoke(+ Queries.GetSettings+ )) as AppSettings+ if (revision !== generation.current) return+ if (!settings || typeof settings !== 'object')+ throw new Error('Missing settings snapshot')+ callback.current(settings)+ setState({ ready: true, error: false })+ } catch {+ if (revision === generation.current)+ setState({ ready: false, error: true })+ }+ }, [])+ useEffect(() => {+ void retry()+ return () => {+ generation.current+++ }+ }, [retry])+ return { ...state, retry }+}++export function SettingsLoadStatus({+ ready,+ error,+ retry,+}: ReturnType<typeof useSettingsLoad>) {+ const { t } = useTranslation()+ if (ready) return null+ return (+ <div+ className="flex items-center justify-between gap-4 text-xs text-muted-foreground"+ role={error ? 'alert' : 'status'}+ >+ <p>{t(error ? 'settings.validation.loadFailed' : 'common.loading')}</p>+ {error && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => void retry()}+ >+ {t('common.retry')}+ </Button>+ )}+ </div>+ )+}diff --git a/src/renderer/features/directory-preferences/use-directory-preferences-draft.ts b/src/renderer/features/directory-preferences/use-directory-preferences-draft.tsindex 7f011763..f0581a6b 100644--- a/src/renderer/features/directory-preferences/use-directory-preferences-draft.ts+++ b/src/renderer/features/directory-preferences/use-directory-preferences-draft.ts@@ -6,16 +6,16 @@ import {type GeneralSettingsApp,type GeneralSettingsErrorCode,GeneralSettingsResultSchema,- type GeneralSettingsSnapshot,type SaveGeneralSettingsRequest,} from '@shared/schemas/general-settings'+import type { SettingsUpdateResult } from '@shared/schemas/settings-update'import { useCallback, useEffect, useRef, useState } from 'react'+import type { z } from 'zod'export const DIRECTORY_DRAFT_TIMEOUT = 20_000export const GENERAL_SETTINGS_SAVE_ATTEMPTS = 3type AppPatch = SaveGeneralSettingsRequest['app']-type AppKey = keyof GeneralSettingsAppinterface AppDraft {values: GeneralSettingsAppdirty: AppPatch@@ -42,12 +42,15 @@ export function directoryPreferenceEdits(}}-async function request(+export async function requestDirectoryDraft<T>(channel:| typeof Queries.GetGeneralSettingsDraft- | typeof Commands.SaveGeneralSettings,- args: unknown-) {+ | typeof Commands.SaveGeneralSettings+ | typeof Queries.GetDownloadsSettingsDraft+ | typeof Commands.SaveDownloadsSettings,+ args: unknown,+ schema: z.ZodType<T>+): Promise<T> {let timer: ReturnType<typeof setTimeout> | undefinedtry {const value = await Promise.race([@@ -59,28 +62,53 @@ async function request()}),])- return GeneralSettingsResultSchema.parse(value)+ return schema.parse(value)} finally {clearTimeout(timer)}}-type State = {- baseline: GeneralSettingsSnapshot | null+interface DraftSnapshot<Values> {+ revision: string+ app: Values+ directoryPreferences: DirectoryPreferences+}+type DraftResult<Values> =+ | { ok: true; value: DraftSnapshot<Values>; update?: SettingsUpdateResult }+ | {+ ok: false+ error: { code: GeneralSettingsErrorCode }+ snapshot?: DraftSnapshot<Values>+ }+interface RevisionedOptions<Values extends object> {+ getAppDraft?: () => { values: Values; dirty: Partial<Values> }+ onAppRebase?: (baseline: Values, intent: Partial<Values>) => void+ request: (+ channel: 'load' | 'save',+ args: {+ expectedRevision?: string+ app?: Partial<Values>+ directories?: SaveGeneralSettingsRequest['directories']+ }+ ) => Promise<DraftResult<Values>>+ onSaved?: (update: SettingsUpdateResult) => Promise<void>+}+type State<Values> = {+ baseline: DraftSnapshot<Values> | nullpreferences: DirectoryPreferencesloading: booleansaving: booleanerror: GeneralSettingsErrorCode | null}-type Intent = {+type Intent<Values> = {favorites: Map<string, boolean>removeRecent: Set<string>- app: AppPatch+ app: Partial<Values>}-function applyDirectoryIntent(+function applyDirectoryIntent<Values>(authority: DirectoryPreferences,- intent: Intent+ intent: Intent<Values>): DirectoryPreferences {return {favorites: [@@ -98,8 +126,10 @@ function applyDirectoryIntent(}/** A draft owns explicit intent; a queue-checked revision fences uncertain writes. */-export function useDirectoryPreferencesDraft(options: Options = {}) {- const [state, setState] = useState<State>({+export function useRevisionedDirectoryDraft<Values extends object>(+ options: RevisionedOptions<Values>+) {+ const [state, setState] = useState<State<Values>>({baseline: null,preferences: { favorites: [], recent: [] },loading: true,@@ -117,13 +147,13 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {const submitted = useRef({favorites: new Set<string>(),recent: new Set<string>(),- app: new Set<AppKey>(),+ app: new Set<keyof Values>(),})- const update = useCallback((patch: Partial<State>) => {+ const update = useCallback((patch: Partial<State<Values>>) => {latest.current = { ...latest.current, ...patch }setState(latest.current)}, [])- const captureIntent = useCallback((): Intent => {+ const captureIntent = useCallback((): Intent<Values> => {const current = latest.currentconst baseline = current.baseline?.directoryPreferences ?? {favorites: [],@@ -136,7 +166,7 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {...edits.removeFavorites,])const appDraft = callbacks.current.getAppDraft?.()- const app: AppPatch = { ...appDraft?.dirty }+ const app: Partial<Values> = { ...appDraft?.dirty }if (appDraft) {for (const key of submitted.current.app)Object.assign(app, { [key]: appDraft.values[key] })@@ -156,7 +186,7 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {}}, [])const rebase = useCallback(- (authority: GeneralSettingsSnapshot, intent: Intent) => {+ (authority: DraftSnapshot<Values>, intent: Intent<Values>) => {update({baseline: authority,preferences: applyDirectoryIntent(@@ -175,7 +205,7 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {const intent = captureIntent()update({ loading: true, error: null })try {- const result = await request(Queries.GetGeneralSettingsDraft, {})+ const result = await callbacks.current.request('load', {})if (!mounted.current || current !== generation.current) returnif (result.ok) rebase(result.value, intent)else update({ error: result.error.code })@@ -211,7 +241,7 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {for (const path of intent.favorites.keys())submitted.current.favorites.add(path)for (const path of intent.removeRecent) submitted.current.recent.add(path)- for (const key of Object.keys(intent.app) as AppKey[])+ for (const key of Object.keys(intent.app) as (keyof Values)[])submitted.current.app.add(key)const current = ++generation.currentsaving.current = true@@ -224,7 +254,7 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {) {// Never short-circuit an empty delta: it must advance the host revision// before a previously timed-out request is allowed to finish validation.- const result = await request(Commands.SaveGeneralSettings, {+ const result = await callbacks.current.request('save', {expectedRevision: authority.revision,app: intent.app,directories: directoryPreferenceEdits(@@ -244,6 +274,7 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {removeRecent: new Set(),app: {},})+ if (result.update) await callbacks.current.onSaved?.(result.update)return true}if (result.snapshot) {@@ -279,3 +310,18 @@ export function useDirectoryPreferencesDraft(options: Options = {}) {save,}}++/** Legacy directory-only consumers keep their existing wire contract. */+export function useDirectoryPreferencesDraft(options: Options = {}) {+ return useRevisionedDirectoryDraft<GeneralSettingsApp>({+ ...options,+ request: (channel, args) =>+ requestDirectoryDraft(+ channel === 'load'+ ? Queries.GetGeneralSettingsDraft+ : Commands.SaveGeneralSettings,+ args,+ GeneralSettingsResultSchema+ ),+ })+}diff --git a/src/renderer/hooks/use-notification-toasts.ts b/src/renderer/hooks/use-notification-toasts.tsindex bc99e6b3..9579b751 100644--- a/src/renderer/hooks/use-notification-toasts.ts+++ b/src/renderer/hooks/use-notification-toasts.ts@@ -48,8 +48,9 @@ const FOCUSED_ERROR_TOAST_ID = 'notification-error'* foreground (`!(win.isVisible() && win.isFocused())`); this hook toasts* in-app only when the document IS foreground* (`visibilityState === 'visible' && document.hasFocus()`) — the exact- * complement, so a given error surfaces exactly once across the two- * tracks, never zero times or twice.+ * complement when both notification channels are enabled. Desktop event+ * forwarding filters muted task outcomes before they reach this hook;+ * native notification settings remain independent.** 2. `kind === NotificationKinds.EngineFailure` rows toast through the* STICKY `ENGINE_FAILURE_TOAST_ID` instead (`timeout: 0`, with an action@@ -77,7 +78,7 @@ const FOCUSED_ERROR_TOAST_ID = 'notification-error'** Only `severity === 'error'` rows and the engine-compatibility warning toast* at all — `task-complete`/info rows stay silent (they still land in the bell- * badge / `/notifications` page via `useNotifications()`).+ * badge / `/notifications` page via `useNotifications()` when enabled).** Mount exactly once at the top of the app tree (AppLayout), mirroring* `useToastEvents`/`usePairRequestPrompts`: `t` and `i18n` are threadeddiff --git a/src/renderer/lib/form-utils.ts b/src/renderer/lib/form-utils.tsindex 38255ad1..52493733 100644--- a/src/renderer/lib/form-utils.ts+++ b/src/renderer/lib/form-utils.ts@@ -1,4 +1,7 @@-type DirtyTree = boolean | { [key: string]: DirtyTree | undefined }+type DirtyTree =+ | boolean+ | { [key: string]: DirtyTree | undefined }+ | readonly (DirtyTree | undefined)[]export function pickDirty<T>(values: T,diff --git a/src/renderer/lib/settings-save.ts b/src/renderer/lib/settings-save.tsindex 5e4d9b05..96008d7c 100644--- a/src/renderer/lib/settings-save.ts+++ b/src/renderer/lib/settings-save.ts@@ -50,6 +50,13 @@ export async function saveSettings(): Promise<SettingsUpdateResult> {const response = await transport.invoke(Commands.UpdateSettings, patch)const result = settingsUpdateResultSchema.parse(response)+ await notifySettingsSaved(result)+ return result+}++export async function notifySettingsSaved(+ result: SettingsUpdateResult+): Promise<void> {await synchronizeSavedSettings()for (const listener of listeners) listener(result)if (result.applicationFailed) {@@ -68,5 +75,4 @@ export async function saveSettings(timeout: 0,})}- return result}diff --git a/src/renderer/routes/settings/cards/about-dialog.test.tsx b/src/renderer/routes/settings/cards/about-dialog.test.tsxindex e39b1100..c3d21f6a 100644--- a/src/renderer/routes/settings/cards/about-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/about-dialog.test.tsx@@ -370,7 +370,7 @@ describe('<AboutDialog>', () => {).toBeInTheDocument()expect(screen.getByText(- 'This build of Motrix doesn’t support automatic updates. Download the latest release from the official website.'+ 'This version cannot update automatically. Download the latest version from the official website.')).toBeInTheDocument()const checkButton = screen.getByRole('button', {@@ -412,10 +412,8 @@ describe('<AboutDialog>', () => {app: { updateChannel: 'beta' },})expect(channel).toHaveTextContent('Beta')- expect(- screen.getByText(/Beta releases may be less reliable/)- ).toHaveTextContent(- 'Switching back to Stable stops future betas but never installs an older version automatically.'+ expect(screen.getByText(/Beta may be less stable/)).toHaveTextContent(+ 'Switching back stops beta updates without downgrading.')})diff --git a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx b/src/renderer/routes/settings/cards/advanced-dialog.test.tsxindex 969e1190..f57b59fd 100644--- a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx@@ -176,4 +176,102 @@ describe('<AdvancedDialog>', () => {await user.click(screen.getByRole('button', { name: 'Save' }))await waitFor(() => expect(onClose).toHaveBeenCalledOnce())})+ it.each(['0', '-1'])(+ 'does not interpret typed %s as another history mode',+ async (value) => {+ const close = vi.fn()+ render(<AdvancedDialog open onClose={close} labelKey="" descKey="" />)+ await screen.findByDisplayValue('16800')+ const user = userEvent.setup()+ await user.click(+ screen.getByRole('combobox', { name: 'Completed recovery records' })+ )+ await user.click(+ await screen.findByRole('option', { name: 'Latest records…' })+ )+ const count = screen.getByRole('spinbutton', { name: 'Records to keep' })+ fireEvent.change(count, { target: { value } })+ await user.click(screen.getByRole('button', { name: 'Save' }))+ expect(+ await screen.findByText('Enter a number greater than 0.')+ ).toBeVisible()+ expect(count).toHaveValue(Number(value))+ expect(close).not.toHaveBeenCalled()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.UpdateSettings,+ expect.anything()+ )+ }+ )+ it('restores a custom history count across policy and persistence toggles', async () => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetSettings+ ? { engine: { ...SETTINGS_FIXTURE.engine, sqlite3HistoryLimit: 731 } }+ : { saved: true }+ )+ render(<AdvancedDialog open onClose={vi.fn()} labelKey="" descKey="" />)+ const count = await screen.findByRole('spinbutton', {+ name: 'Records to keep',+ })+ expect(count).toHaveValue(731)+ const user = userEvent.setup()+ const mode = screen.getByRole('combobox', {+ name: 'Completed recovery records',+ })+ await user.click(mode)+ await user.click(+ await screen.findByRole('option', { name: 'Do not retain' })+ )+ expect(+ screen.queryByRole('spinbutton', { name: 'Records to keep' })+ ).toBeNull()+ await user.click(mode)+ await user.click(+ await screen.findByRole('option', { name: 'Latest records…' })+ )+ expect(+ screen.getByRole('spinbutton', { name: 'Records to keep' })+ ).toHaveValue(731)+ await user.click(screen.getByRole('switch', { name: 'Save recovery data' }))+ expect(+ screen.getByRole('spinbutton', { name: 'Records to keep' })+ ).toBeDisabled()+ await user.click(screen.getByRole('switch', { name: 'Save recovery data' }))+ expect(+ screen.getByRole('spinbutton', { name: 'Records to keep' })+ ).toHaveValue(731)+ })+ it.each([+ ['All records', -1],+ ['Do not retain', 0],+ ] as const)('saves the %s retention policy', async (label, limit) => {+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>+ channel === Queries.GetSettings+ ? { engine: { ...SETTINGS_FIXTURE.engine, sqlite3HistoryLimit: 731 } }+ : { saved: true }+ )+ render(<AdvancedDialog open onClose={vi.fn()} labelKey="" descKey="" />)+ await screen.findByDisplayValue('16800')+ const user = userEvent.setup()+ await user.click(+ screen.getByRole('combobox', { name: 'Completed recovery records' })+ )+ await user.click(await screen.findByRole('option', { name: label }))+ await user.click(screen.getByRole('button', { name: 'Save' }))+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {+ engine: { sqlite3HistoryLimit: limit },+ })+ })+ it('validates the progress save interval moved from Downloads', async () => {+ render(<AdvancedDialog open onClose={vi.fn()} labelKey="" descKey="" />)+ await screen.findByDisplayValue('16800')+ const input = screen.getByRole('spinbutton', {+ name: 'Progress save interval (s)',+ })+ fireEvent.change(input, { target: { value: '3601' } })+ await userEvent.setup().click(screen.getByRole('button', { name: 'Save' }))+ expect(+ await screen.findByText('Enter a whole number from 10 to 3600.')+ ).toBeVisible()+ })})diff --git a/src/renderer/routes/settings/cards/advanced-dialog.tsx b/src/renderer/routes/settings/cards/advanced-dialog.tsxindex 31c16163..5e7f599b 100644--- a/src/renderer/routes/settings/cards/advanced-dialog.tsx+++ b/src/renderer/routes/settings/cards/advanced-dialog.tsx@@ -1,9 +1,14 @@import { RandomizeIcon } from '@renderer/components/icons'import { SettingsFormRow } from '@renderer/components/settings-kit/settings-form-row'+import { SettingsSelectTrigger } from '@renderer/components/settings-kit/settings-select-trigger'import {useSettingsForm,useSettingsSubmit,} from '@renderer/components/settings-kit/use-settings-form'+import {+ SettingsLoadStatus,+ useSettingsLoad,+} from '@renderer/components/settings-kit/use-settings-load'import { Button } from '@renderer/components/ui/button'import {Dialog,@@ -23,6 +28,7 @@ import {FormMessage,} from '@renderer/components/ui/form'import { Input } from '@renderer/components/ui/input'+import { Label } from '@renderer/components/ui/label'import { PasswordInput } from '@renderer/components/ui/password-input'import {ScrollArea,@@ -30,22 +36,30 @@ import {ScrollAreaViewport,ScrollBar,} from '@renderer/components/ui/scroll-area'+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectValue,+} from '@renderer/components/ui/select'import { Separator } from '@renderer/components/ui/separator'import { Switch } from '@renderer/components/ui/switch'import { pickDirty } from '@renderer/lib/form-utils'import { saveSettings } from '@renderer/lib/settings-save'-import { transport } from '@renderer/lib/transport'-import { Queries } from '@shared/protocol/queries'import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas'-import type { AppSettings, EngineSettings } from '@shared/types/settings'+import type { EngineSettings } from '@shared/types/settings'import { generateRpcSecret } from '@shared/utils/rpc-secret'-import { useEffect } from 'react'+import { useEffect, useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import type { SettingsCardDialogProps } from './card-types'import { advancedFormSchema } from './settings-form-schemas'+type HistoryRetentionMode = 'all' | 'limited' | 'session'+type AdvancedFields = Pick<EngineSettings,+ | 'sessionSaveInterval'| 'rpcPort'| 'rpcSecret'| 'sqlite3Persistence'@@ -54,6 +68,7 @@ type AdvancedFields = Pick<>const DEFAULTS: AdvancedFields = {+ sessionSaveInterval: DEFAULT_ENGINE_SETTINGS.sessionSaveInterval,rpcPort: DEFAULT_ENGINE_SETTINGS.rpcPort,rpcSecret: DEFAULT_ENGINE_SETTINGS.rpcSecret,sqlite3Persistence: DEFAULT_ENGINE_SETTINGS.sqlite3Persistence,@@ -65,38 +80,71 @@ export function AdvancedDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()- const form = useSettingsForm<AdvancedFields>(advancedFormSchema, DEFAULTS)+ const [historyModeOverride, setHistoryModeOverride] =+ useState<HistoryRetentionMode | null>(null)+ const historyModeRef = useRef<HistoryRetentionMode | null>(null)+ const lastHistoryCount = useRef(1000)+ const historyCountId = useId()+ const historyCountHintId = useId()+ const historyErrorId = useId()+ const form = useSettingsForm<AdvancedFields>(+ advancedFormSchema.refine(+ (values) =>+ historyModeRef.current !== 'limited' || values.sqlite3HistoryLimit > 0,+ {+ path: ['sqlite3HistoryLimit'],+ message: t('settings.advanced.persistence.historyCountPositive'),+ }+ ),+ DEFAULTS+ )+ const historyLimit = form.watch('sqlite3HistoryLimit')+ const historyMode =+ historyModeOverride ??+ (historyLimit === -1 ? 'all' : historyLimit === 0 ? 'session' : 'limited')+ const historyModeOptions = [+ { value: 'all', label: t('settings.advanced.persistence.historyKeepAll') },+ {+ value: 'limited',+ label: t('settings.advanced.persistence.historyKeepRecent'),+ },+ {+ value: 'session',+ label: t('settings.advanced.persistence.historySessionOnly'),+ },+ ] as const- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stableuseEffect(() => {- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings- if (all?.engine) {- form.reset({- rpcPort: all.engine.rpcPort,- rpcSecret: all.engine.rpcSecret,- sqlite3Persistence: all.engine.sqlite3Persistence,- sqlite3DbPath: all.engine.sqlite3DbPath,- sqlite3HistoryLimit: all.engine.sqlite3HistoryLimit,- })- }- })- .catch(() => {- /* keep defaults */+ if (+ Number.isInteger(historyLimit) &&+ historyLimit > 0 &&+ historyLimit <= 1000000+ ) {+ lastHistoryCount.current = historyLimit+ }+ }, [historyLimit])++ const load = useSettingsLoad((all) => {+ if (!all?.engine) throw new Error('Missing settings baseline')+ if (all?.engine) {+ historyModeRef.current = null+ setHistoryModeOverride(null)+ form.reset({+ sessionSaveInterval:+ all.engine.sessionSaveInterval ?? DEFAULTS.sessionSaveInterval,+ rpcPort: all.engine.rpcPort,+ rpcSecret: all.engine.rpcSecret,+ sqlite3Persistence: all.engine.sqlite3Persistence,+ sqlite3DbPath: all.engine.sqlite3DbPath,+ sqlite3HistoryLimit: all.engine.sqlite3HistoryLimit,})- return () => {- cancelled = true}- }, [])+ })const onSubmit = useSettingsSubmit(form, async (values) => {+ if (!load.ready) returnconst dirty = pickDirty(values, form.formState.dirtyFields)if (!dirty) {onClose()@@ -110,14 +158,24 @@ export function AdvancedDialog({const persistenceOn = form.watch('sqlite3Persistence')return (- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog+ open={open}+ onOpenChange={(v, details) => {+ if (!v) {+ if (form.formState.isSubmitting) details.cancel()+ else onClose()+ }+ }}+ ><DialogContentclassName="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"initialFocus={false}><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.advanced.description')}+ </DialogDescription></DialogHeader><ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -129,186 +187,311 @@ export function AdvancedDialog({className="px-6 py-4"style={{ minWidth: '100%' }}>+ <SettingsLoadStatus {...load} /><Form {...form}>- <form className="space-y-4" noValidate onSubmit={onSubmit}>- <h3 className="text-sm font-semibold text-foreground">- {t('settings.advanced.rpc.title')}- </h3>+ <form noValidate onSubmit={onSubmit}>+ <fieldset+ inert={!load.ready || form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}+ className="min-w-0 space-y-4"+ >+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.advanced.rpc.title')}+ </h3>- <FormField- control={form.control}- name="rpcPort"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.advanced.rpc.port')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.advanced.rpc.portDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={1024}- max={65535}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="rpcSecret"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="space-y-1">- <FormLabel>- {t('settings.advanced.rpc.secret')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.advanced.rpc.secretDesc')}- </FormDescription>- </div>- <div className="flex gap-2">+ <FormField+ control={form.control}+ name="rpcPort"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.advanced.rpc.port')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.advanced.rpc.portDesc')}+ </FormDescription>+ </div><FormControl>- <PasswordInput+ <Input{...field}- value={field.value}- onChange={field.onChange}- onBlur={field.onBlur}- showPasswordLabel={t(- 'settings.common.showSecret'- )}- hidePasswordLabel={t(- 'settings.common.hideSecret'- )}- className="flex-1"+ type="number"+ min={1024}+ max={65535}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value) ? field.value : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }/></FormControl>- <Button- type="button"- variant="outline"- size="sm"- aria-label={t('settings.common.generate')}- onClick={() => field.onChange(generateRpcSecret())}- >- <RandomizeIcon className="h-3 w-3" />- </Button>- </div>- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />+ </SettingsFormRow>+ )}+ />- <Separator className="my-4" />+ <FormField+ control={form.control}+ name="rpcSecret"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.advanced.rpc.secret')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.advanced.rpc.secretDesc')}+ </FormDescription>+ </div>+ <div className="flex gap-2">+ <FormControl>+ <PasswordInput+ {...field}+ value={field.value}+ onChange={field.onChange}+ onBlur={field.onBlur}+ showPasswordLabel={t(+ 'settings.common.showSecret'+ )}+ hidePasswordLabel={t(+ 'settings.common.hideSecret'+ )}+ className="flex-1"+ />+ </FormControl>+ <Button+ type="button"+ variant="outline"+ size="sm"+ aria-label={t('settings.common.generate')}+ onClick={() =>+ field.onChange(generateRpcSecret())+ }+ >+ <RandomizeIcon className="h-3 w-3" />+ </Button>+ </div>+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />- <h3 className="text-sm font-semibold text-foreground">- {t('settings.advanced.persistence.title')}- </h3>+ <Separator className="my-4" />- <FormField- control={form.control}- name="sqlite3Persistence"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.advanced.persistence.enable')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.advanced.persistence.enableDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.advanced.persistence.title')}+ </h3>- <FormField- control={form.control}- name="sqlite3DbPath"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.advanced.persistence.dbPath')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.advanced.persistence.dbPathDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- className="w-56 h-8"- placeholder={t(- 'settings.advanced.persistence.dbPathPlaceholder'- )}- disabled={- !persistenceOn &&- !form.formState.errors.sqlite3DbPath- }- value={field.value}- onChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />+ <FormField+ control={form.control}+ name="sqlite3Persistence"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.advanced.persistence.enable')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.advanced.persistence.enableDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />- <FormField- control={form.control}- name="sqlite3HistoryLimit"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.advanced.persistence.historyLimit')}- </FormLabel>- <FormDescription className="text-xs">- {t(- 'settings.advanced.persistence.historyLimitDesc'+ <FormField+ control={form.control}+ name="sqlite3DbPath"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.advanced.persistence.dbPath')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.advanced.persistence.dbPathDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ className="w-56 h-8"+ placeholder={t(+ 'settings.advanced.persistence.dbPathPlaceholder'+ )}+ disabled={+ !persistenceOn &&+ !form.formState.errors.sqlite3DbPath+ }+ value={field.value}+ onChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />++ <FormField+ control={form.control}+ name="sqlite3HistoryLimit"+ render={({ field, fieldState }) => {+ const disabled = !persistenceOn && !fieldState.error+ return (+ <FormItem className="space-y-3">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.advanced.persistence.historyLimit'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.advanced.persistence.historyLimitDesc'+ )}+ </FormDescription>+ </div>+ <Select+ items={historyModeOptions}+ value={historyMode}+ disabled={disabled}+ onValueChange={(+ next: HistoryRetentionMode | null+ ) => {+ if (!next) return+ historyModeRef.current = next+ setHistoryModeOverride(next)+ form.setValue(+ 'sqlite3HistoryLimit',+ next === 'all'+ ? -1+ : next === 'session'+ ? 0+ : lastHistoryCount.current,+ {+ shouldDirty: true,+ shouldValidate: true,+ }+ )+ }}+ >+ <FormControl>+ <SettingsSelectTrigger+ ref={+ historyMode === 'limited'+ ? undefined+ : field.ref+ }+ onBlur={field.onBlur}+ className="shrink-0"+ >+ <SelectValue />+ </SettingsSelectTrigger>+ </FormControl>+ <SelectContent position="popper" align="end">+ <SelectGroup>+ {historyModeOptions.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ >+ {option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ {historyMode === 'limited' && (+ <div className="flex items-start justify-between gap-4 border-l border-border/60 pl-4">+ <div className="space-y-1">+ <Label htmlFor={historyCountId}>+ {t(+ 'settings.advanced.persistence.historyCount'+ )}+ </Label>+ <p+ id={historyCountHintId}+ className="text-xs text-muted-foreground"+ >+ {t(+ 'settings.advanced.persistence.historyCountHint'+ )}+ </p>+ </div>+ <Input+ id={historyCountId}+ ref={field.ref}+ name={field.name}+ type="number"+ min={1}+ max={1000000}+ step={1}+ className="w-30 h-8 shrink-0"+ disabled={disabled}+ aria-invalid={Boolean(fieldState.error)}+ aria-describedby={`${historyCountHintId}${fieldState.error ? ` ${historyErrorId}` : ''}`}+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onBlur={field.onBlur}+ onChange={(event) => {+ historyModeRef.current = 'limited'+ setHistoryModeOverride('limited')+ field.onChange(event.target.valueAsNumber)+ }}+ />+ </div>+ )}+ {fieldState.error && (+ <div id={historyErrorId}>+ <FormMessage className="text-xs" />+ </div>)}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={-1}- max={1000000}- className="w-30 h-8"- disabled={- !persistenceOn &&- !form.formState.errors.sqlite3HistoryLimit- }- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />+ </FormItem>+ )+ }}+ />+ <FormField+ control={form.control}+ name="sessionSaveInterval"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.downloads.disk.sessionSaveInterval')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.downloads.disk.sessionSaveIntervalDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={10}+ max={3600}+ className="w-30 h-8"+ onChange={(e) =>+ field.onChange(e.target.valueAsNumber)+ }+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ </fieldset></form></Form></ScrollAreaContent>@@ -322,14 +505,20 @@ export function AdvancedDialog({{form.formState.errors.root.save.message}</p>)}- <Button type="button" variant="outline" size="sm" onClick={onClose}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={form.formState.isSubmitting}+ onClick={onClose}+ >{t('common.cancel')}</Button><Buttontype="button"size="sm"onClick={onSubmit}- disabled={form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}>{t('common.save')}</Button>diff --git a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx b/src/renderer/routes/settings/cards/appearance-dialog.test.tsxindex c0016ae0..cd68fff3 100644--- a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx@@ -173,7 +173,7 @@ describe('<AppearanceDialog>', () => {/>)const toggle = await screen.findByRole('switch', {- name: 'Enable Liquid Glass effect',+ name: 'Liquid Glass',})const user = userEvent.setup()await user.click(toggle)@@ -188,87 +188,6 @@ describe('<AppearanceDialog>', () => {})- it('renders hydrated select labels instead of raw values', async () => {- render(- <AppearanceDialog- open- onClose={vi.fn()}- labelKey="settings.cards.appearance.title"- descKey="settings.cards.appearance.desc"- />- )-- await waitFor(() => {- const [themeTrigger, languageTrigger, byteUnitTrigger, runModeTrigger] =- screen.getAllByRole('combobox')-- expect(themeTrigger).toHaveTextContent(/^System$/)- expect(themeTrigger).not.toHaveTextContent(/^system$/)- expect(languageTrigger).toHaveTextContent(/^English$/)- expect(languageTrigger).not.toHaveTextContent(/^en-US$/)- expect(languageTrigger).toHaveClass('min-w-30', 'max-w-64')- expect(languageTrigger).not.toHaveClass('w-32')- expect(byteUnitTrigger).toHaveTextContent('Follow system (MB, GB)')- expect(runModeTrigger).toHaveTextContent(/^Dock & Menu Bar$/)- expect(runModeTrigger).not.toHaveTextContent(/^1$/)- })-- const user = userEvent.setup({ pointerEventsCheck: 0 })- await user.click(- screen.getByRole('combobox', {- name: 'Show app in',- })- )- expect(- await screen.findByRole('option', { name: 'Dock & Menu Bar' })- ).toBeInTheDocument()- expect(- screen.getByRole('option', { name: 'Menu Bar Only' })- ).toBeInTheDocument()- expect(- screen.getByRole('option', { name: 'Dock Only' })- ).toBeInTheDocument()- })-- it.each(['win32', 'linux'] as const)(- 'uses launch behavior labels on %s',- async (platform) => {- Object.defineProperty(transport, 'platform', {- configurable: true,- value: platform,- })- render(- <AppearanceDialog- open- onClose={vi.fn()}- labelKey="settings.cards.appearance.title"- descKey="settings.cards.appearance.desc"- />- )-- const runModeTrigger = await screen.findByRole('combobox', {- name: 'When opening Motrix',- })- expect(runModeTrigger).toHaveTextContent(/^Open Main Window$/)-- const user = userEvent.setup({ pointerEventsCheck: 0 })- await user.click(runModeTrigger)- expect(- await screen.findByRole('option', { name: 'Open Main Window' })- ).toBeInTheDocument()- expect(- screen.getByRole('option', { name: 'Start in System Tray' })- ).toBeInTheDocument()- expect(screen.queryByRole('option', { name: 'Dock Only' })).toBeNull()-- if (platform === 'linux') {- expect(- screen.getByText(/depend on your desktop environment/i)- ).toBeInTheDocument()- }- }- )-it('does not show desktop run-mode settings on the web', async () => {Object.defineProperty(transport, 'platform', {configurable: true,@@ -320,29 +239,6 @@ describe('<AppearanceDialog>', () => {expect(onClose).toHaveBeenCalled()})- it('hydrates and submits lightweight mode independently', async () => {- render(- <AppearanceDialog- open- onClose={vi.fn()}- labelKey="settings.cards.appearance.title"- descKey="settings.cards.appearance.desc"- />- )- const lightweight = await screen.findByRole('switch', {- name: 'Lightweight mode',- })- const user = userEvent.setup()-- expect(lightweight).not.toBeChecked()- await user.click(lightweight)- await user.click(screen.getByRole('button', { name: /save/i }))-- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- app: { lightweightMode: true },- })- })-it.each(['darwin', 'win32', 'linux', 'web'])('defaults reduce motion to off and saves only its dirty field on %s',async (platform) => {diff --git a/src/renderer/routes/settings/cards/appearance-dialog.tsx b/src/renderer/routes/settings/cards/appearance-dialog.tsxindex 92aa0a56..be0953d1 100644--- a/src/renderer/routes/settings/cards/appearance-dialog.tsx+++ b/src/renderer/routes/settings/cards/appearance-dialog.tsx@@ -4,6 +4,10 @@ import {useSettingsForm,useSettingsSubmit,} from '@renderer/components/settings-kit/use-settings-form'+import {+ SettingsLoadStatus,+ useSettingsLoad,+} from '@renderer/components/settings-kit/use-settings-load'import { Button } from '@renderer/components/ui/button'import {Dialog,@@ -33,17 +37,16 @@ import {SelectItem,SelectValue,} from '@renderer/components/ui/select'+import { Separator } from '@renderer/components/ui/separator'import { Switch } from '@renderer/components/ui/switch'import { pickDirty } from '@renderer/lib/form-utils'import { saveSettings } from '@renderer/lib/settings-save'import { useSidebarColorState } from '@renderer/lib/sidebar-color'import { transport } from '@renderer/lib/transport'-import { RunMode } from '@shared/constants'import { isSupportedLocale, SUPPORTED_LOCALES } from '@shared/constants/locales'-import { Queries } from '@shared/protocol/queries'import { DEFAULT_APP_SETTINGS } from '@shared/schemas'import { resolveByteUnitSystem } from '@shared/schemas/byte-unit-system'-import type { AppSettings, MotrixAppSettings } from '@shared/types/settings'+import type { MotrixAppSettings } from '@shared/types/settings'import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import type { SettingsCardDialogProps } from './card-types'@@ -59,9 +62,7 @@ type AppearanceFields = Pick<| 'byteUnitSystem'| 'traySpeedometer'| 'trayIconColor'- | 'runMode'| 'liquidGlassEffect'- | 'lightweightMode'>// Source of truth: src/shared/schemas/app-settings.ts (DEFAULT_APP_SETTINGS).@@ -75,9 +76,7 @@ const DEFAULTS: AppearanceFields = {byteUnitSystem: DEFAULT_APP_SETTINGS.byteUnitSystem,traySpeedometer: DEFAULT_APP_SETTINGS.traySpeedometer,trayIconColor: DEFAULT_APP_SETTINGS.trayIconColor,- runMode: DEFAULT_APP_SETTINGS.runMode,liquidGlassEffect: DEFAULT_APP_SETTINGS.liquidGlassEffect,- lightweightMode: DEFAULT_APP_SETTINGS.lightweightMode,}const LANGUAGE_OPTIONS = SUPPORTED_LOCALES.map(({ code, nativeName }) => ({@@ -92,45 +91,25 @@ export function AppearanceDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()const form = useSettingsForm<AppearanceFields>(appearanceFormSchema, DEFAULTS)- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable across renders; this is a mount-only fetch- useEffect(() => {- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings- if (all?.app) {- form.reset({- theme: all.app.theme,- sidebarColor: all.app.sidebarColor ?? DEFAULTS.sidebarColor,- reduceMotion: all.app.reduceMotion ?? DEFAULTS.reduceMotion,- language: all.app.language,- byteUnitSystem: all.app.byteUnitSystem ?? DEFAULTS.byteUnitSystem,- traySpeedometer: all.app.traySpeedometer,- trayIconColor: all.app.trayIconColor ?? DEFAULTS.trayIconColor,- runMode:- transport.platform !== 'darwin' &&- all.app.runMode === RunMode.HideTray- ? RunMode.Standard- : all.app.runMode,- liquidGlassEffect: all.app.liquidGlassEffect,- lightweightMode: all.app.lightweightMode,- })- }- })- .catch(() => {- /* keep defaults */+ const load = useSettingsLoad((all) => {+ if (!all?.app) throw new Error('Missing settings baseline')+ if (all?.app) {+ form.reset({+ theme: all.app.theme,+ sidebarColor: all.app.sidebarColor ?? DEFAULTS.sidebarColor,+ reduceMotion: all.app.reduceMotion ?? DEFAULTS.reduceMotion,+ language: all.app.language,+ byteUnitSystem: all.app.byteUnitSystem ?? DEFAULTS.byteUnitSystem,+ traySpeedometer: all.app.traySpeedometer,+ trayIconColor: all.app.trayIconColor ?? DEFAULTS.trayIconColor,+ liquidGlassEffect: all.app.liquidGlassEffect,})- return () => {- cancelled = true}- }, [])+ })const sidebarColor = form.watch('sidebarColor')const colorIsDirty = !!form.formState.dirtyFields.sidebarColor@@ -142,6 +121,7 @@ export function AppearanceDialog({}, [open, colorIsDirty, sidebarColor])const onSubmit = useSettingsSubmit(form, async (values) => {+ if (!load.ready) returnconst dirty = pickDirty(values, form.formState.dirtyFields)if (!dirty) {onClose()@@ -199,42 +179,26 @@ export function AppearanceDialog({{ value: 'light', label: t('settings.appearance.trayIconColorLight') },{ value: 'dark', label: t('settings.appearance.trayIconColorDark') },] satisfies Array<{ value: AppearanceFields['trayIconColor']; label: string }>- const showRunMode = transport.platform !== 'web'- const runModeOptions = isMac- ? [- {- value: String(RunMode.Standard),- label: t('settings.appearance.runModeStandard'),- },- {- value: String(RunMode.TrayOnly),- label: t('settings.appearance.runModeTray'),- },- {- value: String(RunMode.HideTray),- label: t('settings.appearance.runModeHideTray'),- },- ]- : [- {- value: String(RunMode.Standard),- label: t('settings.appearance.runModeStandardDesktop'),- },- {- value: String(RunMode.TrayOnly),- label: t('settings.appearance.runModeTrayDesktop'),- },- ]return (- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog+ open={open}+ onOpenChange={(v, details) => {+ if (!v) {+ if (form.formState.isSubmitting) details.cancel()+ else onClose()+ }+ }}+ ><DialogContentclassName="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"initialFocus={false}><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.appearance.description')}+ </DialogDescription></DialogHeader><ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -246,183 +210,28 @@ export function AppearanceDialog({className="px-6 py-4"style={{ minWidth: '100%' }}>+ <SettingsLoadStatus {...load} /><Form {...form}>- <form className="space-y-4" noValidate onSubmit={onSubmit}>- <FormField- control={form.control}- name="theme"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>{t('settings.appearance.theme')}</FormLabel>- <FormControl>- <Select- items={themeOptions}- value={field.value}- onValueChange={(value) => {- if (value !== null) field.onChange(value)- }}- >- <SettingsSelectTrigger>- <SelectValue />- </SettingsSelectTrigger>- <SelectContent>- <SelectGroup>- {themeOptions.map((option) => (- <SelectItem- key={option.value}- value={option.value}- >- {option.label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="sidebarColor"- render={({ field }) => (- <SettingsFormRow className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">- <FormLabel className="sm:pt-2">- {t('settings.appearance.sidebarColor')}- </FormLabel>- <FormControl>- <SidebarColorPicker- value={field.value}- onChange={field.onChange}- onBlur={field.onBlur}- disabled={form.formState.isSubmitting}- />- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="language"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.appearance.language')}- </FormLabel>- <FormControl>- <Select- items={LANGUAGE_OPTIONS}- value={field.value}- onValueChange={(value) => {- if (isSupportedLocale(value))- field.onChange(value)- }}- >- <SettingsSelectTrigger>- <SelectValue />- </SettingsSelectTrigger>- <SelectContent>- <SelectGroup>- {LANGUAGE_OPTIONS.map((option) => (- <SelectItem- key={option.value}- value={option.value}- >- {option.label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="byteUnitSystem"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.appearance.byteUnitSystem')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.appearance.byteUnitSystemDesc')}- </FormDescription>- </div>- <FormControl>- <Select- items={byteUnitOptions}- value={field.value}- onValueChange={(value) => {- if (value !== null) field.onChange(value)- }}- >- <SettingsSelectTrigger>- <SelectValue />- </SettingsSelectTrigger>- <SelectContent>- <SelectGroup>- {byteUnitOptions.map((option) => (- <SelectItem- key={option.value}- value={option.value}- >- {option.label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="reduceMotion"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.appearance.reduceMotion')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.appearance.reduceMotionDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />-- {isLinux && (+ <form noValidate onSubmit={onSubmit}>+ <fieldset+ inert={!load.ready || form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}+ className="min-w-0 space-y-4"+ >+ <h3 className="text-sm font-semibold">+ {t('settings.appearance.themeAndEffects')}+ </h3><FormFieldcontrol={form.control}- name="trayIconColor"+ name="theme"render={({ field }) => (<SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.appearance.trayIconColor')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.appearance.trayIconColorDesc')}- </FormDescription>- </div>+ <FormLabel>+ {t('settings.appearance.theme')}+ </FormLabel><FormControl><Select- items={trayIconColorOptions}+ items={themeOptions}value={field.value}onValueChange={(value) => {if (value !== null) field.onChange(value)@@ -433,7 +242,7 @@ export function AppearanceDialog({</SettingsSelectTrigger><SelectContent><SelectGroup>- {trayIconColorOptions.map((option) => (+ {themeOptions.map((option) => (<SelectItemkey={option.value}value={option.value}@@ -448,20 +257,38 @@ export function AppearanceDialog({</SettingsFormRow>)}/>- )}-- {isMac && (<FormFieldcontrol={form.control}- name="traySpeedometer"+ name="sidebarColor"+ render={({ field }) => (+ <SettingsFormRow className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">+ <FormLabel className="sm:pt-2">+ {t('settings.appearance.sidebarColor')}+ </FormLabel>+ <FormControl>+ <SidebarColorPicker+ value={field.value}+ onChange={field.onChange}+ onBlur={field.onBlur}+ disabled={+ !load.ready || form.formState.isSubmitting+ }+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="reduceMotion"render={({ field }) => (<SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.appearance.traySpeedometer')}+ {t('settings.appearance.reduceMotion')}</FormLabel><FormDescription className="text-xs">- {t('settings.appearance.traySpeedometerDesc')}+ {t('settings.appearance.reduceMotionDesc')}</FormDescription></div><FormControl>@@ -473,69 +300,57 @@ export function AppearanceDialog({</SettingsFormRow>)}/>- )}-- <FormField- control={form.control}- name="liquidGlassEffect"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.appearance.liquidGlassEffect')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.appearance.liquidGlassEffectDesc')}- {isMac &&- ` ${t('settings.appearance.liquidGlassEffectMacDesc')}`}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />-- {showRunMode && (<FormFieldcontrol={form.control}- name="runMode"+ name="liquidGlassEffect"render={({ field }) => (<SettingsFormRow><div className="space-y-1"><FormLabel>- {t(- isMac- ? 'settings.appearance.runMode'- : 'settings.appearance.runModeLaunch'- )}+ {t('settings.appearance.liquidGlassEffect')}</FormLabel>- {isLinux && (- <FormDescription className="text-xs">- {t('settings.appearance.runModeLinuxDesc')}- </FormDescription>- )}+ <FormDescription className="text-xs">+ {t('settings.appearance.liquidGlassEffectDesc')}+ {isMac &&+ ` ${t('settings.appearance.liquidGlassEffectMacDesc')}`}+ </FormDescription></div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <Separator className="my-4" />+ <h3 className="text-sm font-semibold">+ {t('settings.appearance.languageAndDisplay')}+ </h3>+ <FormField+ control={form.control}+ name="language"+ render={({ field }) => (+ <SettingsFormRow>+ <FormLabel>+ {t('settings.appearance.language')}+ </FormLabel><FormControl><Select- items={runModeOptions}- value={String(field.value)}+ items={LANGUAGE_OPTIONS}+ value={field.value}onValueChange={(value) => {- if (value !== null) {- field.onChange(Number(value))- }+ if (isSupportedLocale(value))+ field.onChange(value)}}>- <SettingsSelectTrigger className="min-w-48">+ <SettingsSelectTrigger><SelectValue /></SettingsSelectTrigger><SelectContent><SelectGroup>- {runModeOptions.map((option) => (+ {LANGUAGE_OPTIONS.map((option) => (<SelectItemkey={option.value}value={option.value}@@ -550,32 +365,119 @@ export function AppearanceDialog({</SettingsFormRow>)}/>- )}-- {transport.platform !== 'web' && (<FormFieldcontrol={form.control}- name="lightweightMode"+ name="byteUnitSystem"render={({ field }) => (<SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.appearance.lightweightMode')}+ {t('settings.appearance.byteUnitSystem')}</FormLabel><FormDescription className="text-xs">- {t('settings.appearance.lightweightModeDesc')}+ {t('settings.appearance.byteUnitSystemDesc')}</FormDescription></div><FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />+ <Select+ items={byteUnitOptions}+ value={field.value}+ onValueChange={(value) => {+ if (value !== null) field.onChange(value)+ }}+ >+ <SettingsSelectTrigger>+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent>+ <SelectGroup>+ {byteUnitOptions.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ >+ {option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select></FormControl></SettingsFormRow>)}/>- )}+ <Separator className="my-4" />+ <h3 className="text-sm font-semibold">+ {t('settings.appearance.menuBar')}+ </h3>+ {isLinux && (+ <FormField+ control={form.control}+ name="trayIconColor"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.appearance.trayIconColor')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.appearance.trayIconColorDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Select+ items={trayIconColorOptions}+ value={field.value}+ onValueChange={(value) => {+ if (value !== null) field.onChange(value)+ }}+ >+ <SettingsSelectTrigger>+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent>+ <SelectGroup>+ {trayIconColorOptions.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ >+ {option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </SettingsFormRow>+ )}+ />+ )}+ {isMac && (+ <FormField+ control={form.control}+ name="traySpeedometer"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.appearance.traySpeedometer')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.appearance.traySpeedometerDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ )}+ </fieldset></form></Form></ScrollAreaContent>@@ -589,14 +491,20 @@ export function AppearanceDialog({{form.formState.errors.root.save.message}</p>)}- <Button type="button" variant="outline" size="sm" onClick={onClose}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={form.formState.isSubmitting}+ onClick={onClose}+ >{t('common.cancel')}</Button><Buttontype="button"size="sm"onClick={onSubmit}- disabled={form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}>{t('common.save')}</Button>diff --git a/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx b/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsxindex 4d624d75..10588bf7 100644--- a/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx@@ -84,17 +84,17 @@ describe('<BitTorrentDialog>', () => {await waitFor(() => screen.getByDisplayValue('128'))expect(screen.queryByRole('spinbutton', {- name: 'File selection timeout (seconds)',+ name: 'Time to choose files (s)',})).toBeNull()const user = userEvent.setup()const toggle = screen.getByRole('switch', {- name: 'Download all files when selection times out',+ name: 'Download all if no selection is made',})expect(toggle).not.toBeChecked()await user.click(toggle)const timeout = screen.getByRole('spinbutton', {- name: 'File selection timeout (seconds)',+ name: 'Time to choose files (s)',})expect(timeout).toHaveValue(60)fireEvent.change(timeout, { target: { value: '120' } })@@ -120,12 +120,12 @@ describe('<BitTorrentDialog>', () => {const user = userEvent.setup()await user.click(screen.getByRole('switch', {- name: 'Download all files when selection times out',+ name: 'Download all if no selection is made',}))fireEvent.change(screen.getByRole('spinbutton', {- name: 'File selection timeout (seconds)',+ name: 'Time to choose files (s)',}),{ target: { value: '0' } })@@ -152,12 +152,12 @@ describe('<BitTorrentDialog>', () => {const user = userEvent.setup()await user.click(screen.getByRole('switch', {- name: 'Open file selection after magnet metadata loads',+ name: 'Choose files before downloading',}))expect(screen.getByRole('switch', {- name: 'Download all files when selection times out',+ name: 'Download all if no selection is made',})).toHaveAttribute('aria-disabled', 'true')})@@ -207,7 +207,7 @@ describe('<BitTorrentDialog>', () => {)await waitFor(() => screen.getByText(/blacklist/i))expect(- screen.getByText(/managed in the sidebar Trackers page/i)+ screen.getByText(/Manage blocked trackers in Trackers/i)).toBeInTheDocument()})@@ -241,4 +241,22 @@ describe('<BitTorrentDialog>', () => {expect.anything())})+ it('accepts a 900-second magnet timeout after moving it from Downloads', async () => {+ render(<BitTorrentDialog open onClose={vi.fn()} labelKey="" descKey="" />)+ const input = await screen.findByRole('spinbutton', {+ name: 'Magnet loading timeout (s)',+ })+ await waitFor(() => expect(input).toBeEnabled())+ fireEvent.change(input, { target: { value: '901' } })+ const user = userEvent.setup()+ await user.click(screen.getByRole('button', { name: 'Save' }))+ expect(+ await screen.findByText('Enter a whole number from 30 to 900.')+ ).toBeVisible()+ fireEvent.change(input, { target: { value: '900' } })+ await user.click(screen.getByRole('button', { name: 'Save' }))+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {+ engine: { magnetResolveTimeout: 900 },+ })+ })})diff --git a/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx b/src/renderer/routes/settings/cards/bit-torrent-dialog.tsxindex a2e92448..068a297e 100644--- a/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx+++ b/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx@@ -1,4 +1,8 @@import { SettingsFormRow } from '@renderer/components/settings-kit/settings-form-row'+import {+ SettingsLoadStatus,+ useSettingsLoad,+} from '@renderer/components/settings-kit/use-settings-load'import {ScrollArea,ScrollAreaContent,@@ -6,7 +10,8 @@ import {ScrollBar,} from '@renderer/components/ui/scroll-area'import { saveSettings } from '@renderer/lib/settings-save'-import { transport } from '@renderer/lib/transport'+import { DEFAULT_GEOIP_SETTINGS } from '@shared/schemas/geoip-settings'+import type { z } from 'zod'// src/renderer/routes/settings/cards/bit-torrent-dialog.tsximport { PresetChips } from '@renderer/components/settings-kit/preset-chips'@@ -36,53 +41,23 @@ import { Input } from '@renderer/components/ui/input'import { Separator } from '@renderer/components/ui/separator'import { Switch } from '@renderer/components/ui/switch'import { pickDirty } from '@renderer/lib/form-utils'-import { Queries } from '@shared/protocol/queries'import { DEFAULT_APP_SETTINGS, DEFAULT_ENGINE_SETTINGS } from '@shared/schemas'import {MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS,MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS,} from '@shared/schemas/app-settings'import { DEFAULT_TRACKER_SETTINGS } from '@shared/schemas/tracker-settings'-import type {- AppSettings,- EngineSettings,- MotrixAppSettings,- TrackerSettings,-} from '@shared/types/settings'-import { useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'-import {- BtPeerGeoSection,- type BtPeerGeoSectionHandle,-} from './bt-peer-geo-section'+import { BtPeerGeoSection } from './bt-peer-geo-section'import type { SettingsCardDialogProps } from './card-types'import { bitTorrentFormSchema } from './settings-form-schemas'-interface BtFields {- engine: Pick<- EngineSettings,- | 'listenPort'- | 'dhtListenPort'- | 'dhtEnabled'- | 'btMaxPeers'- | 'btEnableLpd'- | 'seedRatio'- | 'seedTime'- >- app: Pick<- MotrixAppSettings,- | 'magnetFileSelection'- | 'magnetFileSelectionAutoDownload'- | 'magnetFileSelectionTimeoutSeconds'- >- tracker: Omit<- TrackerSettings,- 'sources' | 'sourcesEnabled' | 'blacklistEnabled' | 'blacklistSources'- >-}+export type BtFields = z.infer<typeof bitTorrentFormSchema>const DEFAULTS: BtFields = {+ geoip: DEFAULT_GEOIP_SETTINGS,engine: {+ magnetResolveTimeout: DEFAULT_ENGINE_SETTINGS.magnetResolveTimeout,listenPort: DEFAULT_ENGINE_SETTINGS.listenPort,dhtListenPort: DEFAULT_ENGINE_SETTINGS.dhtListenPort,dhtEnabled: DEFAULT_ENGINE_SETTINGS.dhtEnabled,@@ -113,60 +88,52 @@ export function BitTorrentDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()const form = useSettingsForm<BtFields>(bitTorrentFormSchema, DEFAULTS)const fileSelectionEnabled = form.watch('app.magnetFileSelection')const autoDownloadEnabled = form.watch('app.magnetFileSelectionAutoDownload')- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable- useEffect(() => {- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings- if (all) {- form.reset({- engine: {- listenPort: all.engine.listenPort,- dhtListenPort: all.engine.dhtListenPort,- dhtEnabled: all.engine.dhtEnabled,- btMaxPeers: all.engine.btMaxPeers,- btEnableLpd: all.engine.btEnableLpd,- seedRatio: all.engine.seedRatio,- seedTime: all.engine.seedTime,- },- app: {- magnetFileSelection: all.app.magnetFileSelection,- magnetFileSelectionAutoDownload:- all.app.magnetFileSelectionAutoDownload,- magnetFileSelectionTimeoutSeconds:- all.app.magnetFileSelectionTimeoutSeconds,- },- tracker: {- autoSync: all.tracker.autoSync,- syncIntervalHours: all.tracker.syncIntervalHours,- probeEnabled: all.tracker.probeEnabled,- probeTimeoutMs: all.tracker.probeTimeoutMs,- healthyThresholdMs: all.tracker.healthyThresholdMs,- minSuccessRate: all.tracker.minSuccessRate,- maxTrackerCount: all.tracker.maxTrackerCount,- },- })- }+ const load = useSettingsLoad((all) => {+ if (!all?.engine || !all.app || !all.tracker)+ throw new Error('Missing settings baseline')+ if (all) {+ form.reset({+ geoip: { ...DEFAULT_GEOIP_SETTINGS, ...all.geoip },+ engine: {+ magnetResolveTimeout:+ all.engine.magnetResolveTimeout ??+ DEFAULT_ENGINE_SETTINGS.magnetResolveTimeout,+ listenPort: all.engine.listenPort,+ dhtListenPort: all.engine.dhtListenPort,+ dhtEnabled: all.engine.dhtEnabled,+ btMaxPeers: all.engine.btMaxPeers,+ btEnableLpd: all.engine.btEnableLpd,+ seedRatio: all.engine.seedRatio,+ seedTime: all.engine.seedTime,+ },+ app: {+ magnetFileSelection: all.app.magnetFileSelection,+ magnetFileSelectionAutoDownload:+ all.app.magnetFileSelectionAutoDownload,+ magnetFileSelectionTimeoutSeconds:+ all.app.magnetFileSelectionTimeoutSeconds,+ },+ tracker: {+ autoSync: all.tracker.autoSync,+ syncIntervalHours: all.tracker.syncIntervalHours,+ probeEnabled: all.tracker.probeEnabled,+ probeTimeoutMs: all.tracker.probeTimeoutMs,+ healthyThresholdMs: all.tracker.healthyThresholdMs,+ minSuccessRate: all.tracker.minSuccessRate,+ maxTrackerCount: all.tracker.maxTrackerCount,+ },})- .catch(() => {})- return () => {- cancelled = true}- }, [])+ })- const geoipRef = useRef<BtPeerGeoSectionHandle>(null)const onSubmit = useSettingsSubmit(form, async (values) => {- if (!(await geoipRef.current?.flush())) return+ if (!load.ready) return// biome-ignore lint/suspicious/noExplicitAny: dirtyFields array items don't fit DirtyTree; cast is safeconst dirty = pickDirty(values, form.formState.dirtyFields as any)if (!dirty) {@@ -178,14 +145,24 @@ export function BitTorrentDialog({})return (- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog+ open={open}+ onOpenChange={(v, details) => {+ if (!v) {+ if (form.formState.isSubmitting) details.cancel()+ else onClose()+ }+ }}+ ><DialogContentclassName="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"initialFocus={false}><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.bittorrent.description')}+ </DialogDescription></DialogHeader><ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -197,242 +174,176 @@ export function BitTorrentDialog({className="px-6 py-4"style={{ minWidth: '100%' }}>+ <SettingsLoadStatus {...load} /><Form {...form}>- <form className="space-y-4" noValidate onSubmit={onSubmit}>- {/* Listen */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.bittorrent.listen.title')}- </h3>- <FormField- control={form.control}- name="engine.listenPort"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.listen.listenPort')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.listen.listenPortDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={1024}- max={65535}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="engine.dhtListenPort"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.listen.dhtListenPort')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.listen.dhtListenPortDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={1024}- max={65535}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="engine.dhtEnabled"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.listen.dhtEnabled')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.listen.dhtEnabledDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />-- <Separator className="my-4" />-- {/* Peers */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.bittorrent.peers.title')}- </h3>- <FormField- control={form.control}- name="engine.btMaxPeers"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.peers.btMaxPeers')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.peers.btMaxPeersDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={1}- max={1000}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="engine.btEnableLpd"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.peers.btEnableLpd')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.peers.btEnableLpdDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="app.magnetFileSelection"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.peers.magnetFileSelection')}- </FormLabel>- <FormDescription className="text-xs">- {t(- 'settings.bittorrent.peers.magnetFileSelectionDesc'- )}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="app.magnetFileSelectionAutoDownload"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t(- 'settings.bittorrent.peers.magnetFileSelectionAutoDownload'- )}- </FormLabel>- <FormDescription className="text-xs">- {t(- 'settings.bittorrent.peers.magnetFileSelectionAutoDownloadDesc'- )}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- disabled={!fileSelectionEnabled}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>+ <form noValidate onSubmit={onSubmit}>+ <fieldset+ inert={!load.ready || form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}+ className="min-w-0 space-y-4"+ >+ <h3 className="text-sm font-semibold">+ {t('settings.bittorrent.newMagnetTasks')}+ </h3>{' '}+ <FormField+ control={form.control}+ name="app.magnetFileSelection"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.bittorrent.peers.magnetFileSelection'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.peers.magnetFileSelectionDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="app.magnetFileSelectionAutoDownload"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.bittorrent.peers.magnetFileSelectionAutoDownload'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.peers.magnetFileSelectionAutoDownloadDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ disabled={!fileSelectionEnabled}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ {(autoDownloadEnabled ||+ form.formState.errors.app+ ?.magnetFileSelectionTimeoutSeconds) && (+ <FormField+ control={form.control}+ name="app.magnetFileSelectionTimeoutSeconds"+ render={({ field }) => (+ <FormItem className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.bittorrent.peers.magnetFileSelectionTimeoutSeconds'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.peers.magnetFileSelectionTimeoutSecondsDesc'+ )}+ </FormDescription>+ <FormMessage />+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS}+ max={MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS}+ step={1}+ className="w-30 h-8"+ disabled={+ !fileSelectionEnabled &&+ !form.formState.errors.app+ ?.magnetFileSelectionTimeoutSeconds+ }+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </FormItem>+ )}+ />)}- />- {(autoDownloadEnabled ||- form.formState.errors.app- ?.magnetFileSelectionTimeoutSeconds) && (<FormFieldcontrol={form.control}- name="app.magnetFileSelectionTimeoutSeconds"+ name="engine.magnetResolveTimeout"render={({ field }) => (- <FormItem className="flex items-start justify-between gap-4">+ <SettingsFormRow><div className="space-y-1"><FormLabel>{t(- 'settings.bittorrent.peers.magnetFileSelectionTimeoutSeconds'+ 'settings.downloads.magnet.magnetResolveTimeout')}</FormLabel><FormDescription className="text-xs">{t(- 'settings.bittorrent.peers.magnetFileSelectionTimeoutSecondsDesc'+ 'settings.downloads.magnet.magnetResolveTimeoutDesc')}</FormDescription>- <FormMessage /></div><FormControl><Input{...field}type="number"- min={MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS}- max={MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS}- step={1}+ min={30}+ max={900}className="w-30 h-8"- disabled={- !fileSelectionEnabled &&- !form.formState.errors.app- ?.magnetFileSelectionTimeoutSeconds+ onChange={(e) =>+ field.onChange(e.target.valueAsNumber)}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <Separator className="my-4" />+ {/* Seeding */}+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.bittorrent.seeding.title')}+ </h3>+ <FormField+ control={form.control}+ name="engine.seedRatio"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.seeding.seedRatio')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.seeding.seedRatioDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={0}+ max={100}+ step={0.1}+ className="w-30 h-8"value={Number.isFinite(field.value) ? field.value : ''}@@ -441,127 +352,248 @@ export function BitTorrentDialog({}/></FormControl>- </FormItem>+ </SettingsFormRow>)}/>- )}-- <Separator className="my-4" />-- {/* Seeding */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.bittorrent.seeding.title')}- </h3>- <FormField- control={form.control}- name="engine.seedRatio"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.seeding.seedRatio')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.seeding.seedRatioDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={0}- max={100}- step={0.1}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }+ <FormField+ control={form.control}+ name="engine.seedTime"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.seeding.seedTime')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.seeding.seedTimeDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={0}+ max={525600}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value) ? field.value : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <Separator className="my-4" />+ {/* Trackers (config) */}+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.bittorrent.trackers.title')}+ </h3>+ <p className="text-xs text-muted-foreground">+ {t('settings.bittorrent.trackers.manageSourcesHint')}+ </p>+ <FormField+ control={form.control}+ name="tracker.autoSync"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.trackers.autoSync')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.trackers.autoSyncDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="tracker.syncIntervalHours"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.trackers.syncInterval')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.trackers.syncIntervalDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={1}+ max={168}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </div>+ <PresetChips+ name="tracker.syncIntervalHours"+ options={[+ { label: '6h', value: 6 },+ { label: '12h', value: 12 },+ { label: '24h', value: 24 },+ ]}/>- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="engine.seedTime"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.seeding.seedTime')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.seeding.seedTimeDesc')}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={0}- max={525600}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="tracker.probeEnabled"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.trackers.enableProbe')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.trackers.enableProbeDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="tracker.probeTimeoutMs"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.trackers.probeTimeout')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.trackers.probeTimeoutDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={1000}+ max={30000}+ step={500}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </div>+ <PresetChips+ name="tracker.probeTimeoutMs"+ options={[+ { label: '3s', value: 3000 },+ { label: '5s', value: 5000 },+ { label: '10s', value: 10000 },+ ]}/>- </FormControl>- </SettingsFormRow>- )}- />-- <Separator className="my-4" />-- {/* Trackers (config) */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.bittorrent.trackers.title')}- </h3>- <p className="text-xs text-muted-foreground">- {t('settings.bittorrent.trackers.manageSourcesHint')}- </p>-- <FormField- control={form.control}- name="tracker.autoSync"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.trackers.autoSync')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.trackers.autoSyncDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="tracker.healthyThresholdMs"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.bittorrent.trackers.healthyThreshold'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.trackers.healthyThresholdDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={500}+ max={10000}+ step={100}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </div>+ <PresetChips+ name="tracker.healthyThresholdMs"+ options={[+ { label: '1s', value: 1000 },+ { label: '2s', value: 2000 },+ { label: '5s', value: 5000 },+ ]}/>- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="tracker.syncIntervalHours"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="flex items-start justify-between gap-4">+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="tracker.minSuccessRate"+ render={({ field }) => (+ <SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.bittorrent.trackers.syncInterval')}+ {t('settings.bittorrent.trackers.minSuccessRate')}</FormLabel><FormDescription className="text-xs">{t(- 'settings.bittorrent.trackers.syncIntervalDesc'+ 'settings.bittorrent.trackers.minSuccessRateDesc')}</FormDescription></div>@@ -569,8 +601,9 @@ export function BitTorrentDialog({<Input{...field}type="number"- min={1}- max={168}+ min={0}+ max={1}+ step={0.05}className="w-30 h-8"value={Number.isFinite(field.value) ? field.value : ''@@ -580,66 +613,84 @@ export function BitTorrentDialog({}/></FormControl>- </div>- <PresetChips- name="tracker.syncIntervalHours"- options={[- { label: '6h', value: 6 },- { label: '12h', value: 12 },- { label: '24h', value: 24 },- ]}- />- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />-- <FormField- control={form.control}- name="tracker.probeEnabled"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.trackers.enableProbe')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.trackers.enableProbeDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="tracker.maxTrackerCount"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.bittorrent.trackers.maxTrackerCount'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.bittorrent.trackers.maxTrackerCountDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={5}+ max={200}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </div>+ <PresetChips+ name="tracker.maxTrackerCount"+ options={[+ { label: '20', value: 20 },+ { label: '50', value: 50 },+ { label: '100', value: 100 },+ ]}/>- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="tracker.probeTimeoutMs"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="flex items-start justify-between gap-4">+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />+ <p className="text-xs text-muted-foreground">+ {t('settings.bittorrent.trackers.blacklistMovedInfo')}+ </p>+ <Separator className="my-4" />+ {/* Listen */}+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.bittorrent.listen.title')}+ </h3>+ <FormField+ control={form.control}+ name="engine.listenPort"+ render={({ field }) => (+ <SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.bittorrent.trackers.probeTimeout')}+ {t('settings.bittorrent.listen.listenPort')}</FormLabel><FormDescription className="text-xs">- {t(- 'settings.bittorrent.trackers.probeTimeoutDesc'- )}+ {t('settings.bittorrent.listen.listenPortDesc')}</FormDescription></div><FormControl><Input{...field}type="number"- min={1000}- max={30000}- step={500}+ min={1024}+ max={65535}className="w-30 h-8"value={Number.isFinite(field.value) ? field.value : ''@@ -649,35 +700,21 @@ export function BitTorrentDialog({}/></FormControl>- </div>- <PresetChips- name="tracker.probeTimeoutMs"- options={[- { label: '3s', value: 3000 },- { label: '5s', value: 5000 },- { label: '10s', value: 10000 },- ]}- />- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />-- <FormField- control={form.control}- name="tracker.healthyThresholdMs"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="flex items-start justify-between gap-4">+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="engine.dhtListenPort"+ render={({ field }) => (+ <SettingsFormRow><div className="space-y-1"><FormLabel>- {t(- 'settings.bittorrent.trackers.healthyThreshold'- )}+ {t('settings.bittorrent.listen.dhtListenPort')}</FormLabel><FormDescription className="text-xs">{t(- 'settings.bittorrent.trackers.healthyThresholdDesc'+ 'settings.bittorrent.listen.dhtListenPortDesc')}</FormDescription></div>@@ -685,9 +722,8 @@ export function BitTorrentDialog({<Input{...field}type="number"- min={500}- max={10000}- step={100}+ min={1024}+ max={65535}className="w-30 h-8"value={Number.isFinite(field.value) ? field.value : ''@@ -697,79 +733,55 @@ export function BitTorrentDialog({}/></FormControl>- </div>- <PresetChips- name="tracker.healthyThresholdMs"- options={[- { label: '1s', value: 1000 },- { label: '2s', value: 2000 },- { label: '5s', value: 5000 },- ]}- />- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />-- <FormField- control={form.control}- name="tracker.minSuccessRate"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.trackers.minSuccessRate')}- </FormLabel>- <FormDescription className="text-xs">- {t(- 'settings.bittorrent.trackers.minSuccessRateDesc'- )}- </FormDescription>- </div>- <FormControl>- <Input- {...field}- type="number"- min={0}- max={1}- step={0.05}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="tracker.maxTrackerCount"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="flex items-start justify-between gap-4">+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="engine.dhtEnabled"+ render={({ field }) => (+ <SettingsFormRow><div className="space-y-1"><FormLabel>- {t(- 'settings.bittorrent.trackers.maxTrackerCount'- )}+ {t('settings.bittorrent.listen.dhtEnabled')}</FormLabel><FormDescription className="text-xs">- {t(- 'settings.bittorrent.trackers.maxTrackerCountDesc'- )}+ {t('settings.bittorrent.listen.dhtEnabledDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <Separator className="my-4" />+ {/* Peers */}+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.bittorrent.peers.title')}+ </h3>+ <FormField+ control={form.control}+ name="engine.btMaxPeers"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.peers.btMaxPeers')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.peers.btMaxPeersDesc')}</FormDescription></div><FormControl><Input{...field}type="number"- min={5}- max={200}+ min={1}+ max={1000}className="w-30 h-8"value={Number.isFinite(field.value) ? field.value : ''@@ -779,30 +791,36 @@ export function BitTorrentDialog({}/></FormControl>- </div>- <PresetChips- name="tracker.maxTrackerCount"- options={[- { label: '20', value: 20 },- { label: '50', value: 50 },- { label: '100', value: 100 },- ]}- />- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />-- <p className="text-xs text-muted-foreground">- {t('settings.bittorrent.trackers.blacklistMovedInfo')}- </p>+ </SettingsFormRow>+ )}+ />+ <FormField+ control={form.control}+ name="engine.btEnableLpd"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.peers.btEnableLpd')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.peers.btEnableLpdDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <Separator className="my-4" />+ <BtPeerGeoSection form={form} ready={load.ready} />+ </fieldset></form></Form>-- {/* Peer geo — self-contained form; rendered outside BT form to avoid nested <form> */}- <div className="mt-4 border-t border-border pt-4">- <BtPeerGeoSection ref={geoipRef} />- </div></ScrollAreaContent></ScrollAreaViewport><ScrollBar />@@ -814,14 +832,20 @@ export function BitTorrentDialog({{form.formState.errors.root.save.message}</p>)}- <Button type="button" variant="outline" size="sm" onClick={onClose}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={form.formState.isSubmitting}+ onClick={onClose}+ >{t('common.cancel')}</Button><Buttontype="button"size="sm"onClick={onSubmit}- disabled={form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}>{t('common.save')}</Button>diff --git a/src/renderer/routes/settings/cards/bt-peer-geo-section.test.tsx b/src/renderer/routes/settings/cards/bt-peer-geo-section.test.tsxindex 771f5fcf..1a21a0e6 100644--- a/src/renderer/routes/settings/cards/bt-peer-geo-section.test.tsx+++ b/src/renderer/routes/settings/cards/bt-peer-geo-section.test.tsx@@ -1,255 +1,91 @@+import '@test-utils/dom-animations'import '@testing-library/jest-dom/vitest'import '@renderer/lib/i18n'+import { useSettingsForm } from '@renderer/components/settings-kit/use-settings-form'+import { Form } from '@renderer/components/ui/form'+import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'-import { DEFAULT_GEOIP_SETTINGS } from '@shared/schemas/geoip-settings'-import type { GeoIPStatus } from '@shared/types/geoip'+import {+ DEFAULT_APP_SETTINGS,+ DEFAULT_ENGINE_SETTINGS,+ DEFAULT_GEOIP_SETTINGS,+ DEFAULT_TRACKER_SETTINGS,+} from '@shared/schemas'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import {- afterEach,- beforeAll,- beforeEach,- describe,- expect,- it,- vi,-} from 'vitest'--const mockInvoke = vi.fn()-const mockOn = vi.fn()-const mockOff = vi.fn()+import { beforeEach, expect, it, vi } from 'vitest'+import { BtPeerGeoSection } from './bt-peer-geo-section'+import { bitTorrentFormSchema } from './settings-form-schemas'vi.mock('@renderer/lib/transport', () => ({transport: {- invoke: (...args: unknown[]) => mockInvoke(...args),- on: (...args: unknown[]) => mockOn(...args),- off: (...args: unknown[]) => mockOff(...args),+ invoke: vi.fn(async () => ({ isDownloading: false })),+ on: vi.fn(),+ off: vi.fn(),platform: 'darwin',},}))--const SAMPLE_STATUS: GeoIPStatus = {- enabled: true,- hasDatabase: true,- loaded: true,- lastUpdatedAt: 1_700_000_000_000,- databaseVersion: 'v1.2026.05',- sizeBytes: 9_400_000,- isDownloading: false,- lastError: null,-}--import { BtPeerGeoSection } from './bt-peer-geo-section'--class MockResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--describe('BtPeerGeoSection', () => {- beforeAll(() => {- // jsdom doesn't implement these; Radix Select needs them.- if (!HTMLElement.prototype.hasPointerCapture) {- HTMLElement.prototype.hasPointerCapture = () => false- }- if (!HTMLElement.prototype.releasePointerCapture) {- HTMLElement.prototype.releasePointerCapture = () => {}- }- if (!HTMLElement.prototype.scrollIntoView) {- HTMLElement.prototype.scrollIntoView = () => {}+beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}}- })-- beforeEach(() => {- vi.stubGlobal('ResizeObserver', MockResizeObserver)- mockInvoke.mockReset()- mockOn.mockReset()- mockOff.mockReset()- mockInvoke.mockImplementation(async (channel: string) => {- if (channel === Commands.UpdateSettings) return { saved: true }- if (channel === 'query:getSettings') {- return {- geoip: {- enabled: false,- source: 'loyalsoldier',- customUrl: '',- maxmindLicenseKey: '',- autoUpdate: true,- autoUpdateIntervalDays: 7,- lastUpdatedAt: 0,- databaseVersion: '',- },- }- }- if (channel === 'query:getGeoIPStatus') {- return { ...SAMPLE_STATUS, enabled: false, hasDatabase: false }- }- return undefined- })- })-- afterEach(() => {- vi.clearAllMocks()- })-- it('renders the section heading and the enable toggle', async () => {- render(<BtPeerGeoSection />)- expect(await screen.findByText(/GeoIP Database/i)).toBeInTheDocument()- expect(screen.getByText(/Enable IP-to-country lookup/i)).toBeInTheDocument()- })-- it('persists the enable toggle via UpdateSettings on click', async () => {- render(<BtPeerGeoSection />)- await waitFor(() =>- expect(mockInvoke).toHaveBeenCalledWith('query:getSettings')- )- const enableSwitch = screen.getByRole('switch', {- name: /Enable IP-to-country lookup/i,- })- fireEvent.click(enableSwitch)- await waitFor(() => {- expect(mockInvoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- geoip: { enabled: true },- })- })- })-- it('reveals the custom URL input when source is switched to custom', async () => {- render(<BtPeerGeoSection />)- await waitFor(() =>- expect(mockInvoke).toHaveBeenCalledWith('query:getSettings')- )- // Radix Select is gated by `disabled={!enabled}`, so flip the toggle first.- const enableSwitch = screen.getByRole('switch', {- name: /Enable IP-to-country lookup/i,- })- fireEvent.click(enableSwitch)- // pointerEventsCheck is disabled because Radix Select sets- // `pointer-events: none` on the body during portaled-content open transitions- // and jsdom doesn't model that reliably.- const user = userEvent.setup({ pointerEventsCheck: 0 })- const trigger = screen.getByRole('combobox')- await user.click(trigger)- const customOption = await screen.findByRole('option', {- name: /Custom URL/i,- })- await user.click(customOption)- expect(- await screen.findByPlaceholderText(/GeoLite2-Country\.mmdb/i)- ).toBeInTheDocument()- })-- it('disables the Update now button when GeoIP is disabled', async () => {- render(<BtPeerGeoSection />)- const button = await screen.findByRole('button', { name: /Update now/i })- expect(button).toBeDisabled()- })-- it('subscribes to status + progress events on mount', async () => {- render(<BtPeerGeoSection />)- await waitFor(() => expect(mockOn).toHaveBeenCalled())- const channels = mockOn.mock.calls.map((call) => call[0])- expect(channels).toContain('event:geoipUpdateProgress')- expect(channels).toContain('event:geoipStatusChanged')- })-- async function selectCustomSource() {- const original = mockInvoke.getMockImplementation()- mockInvoke.mockImplementation(async (channel: string) => {- if (channel === 'query:getSettings')- return { geoip: { ...DEFAULT_GEOIP_SETTINGS, enabled: true } }- return original?.(channel)- })- render(<BtPeerGeoSection />)- const user = userEvent.setup({ pointerEventsCheck: 0 })- await user.click(await screen.findByRole('combobox'))- await user.click(await screen.findByRole('option', { name: /Custom URL/i }))- return {- user,- input: await screen.findByRole('textbox', { name: /custom.*url/i }),- }- }-- it('blocks invalid custom URLs and saves the corrected source and address together before updating', async () => {- const { user, input } = await selectCustomSource()- fireEvent.change(input, { target: { value: 'example.com/country.mmdb' } })- await user.click(screen.getByRole('button', { name: /Update now/i }))- expect(- await screen.findByText(- 'Enter a full address starting with http:// or https://.'- )- ).toBeVisible()- expect(mockInvoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()- )- expect(mockInvoke).not.toHaveBeenCalledWith(Commands.UpdateGeoIPDatabase)- fireEvent.change(input, {- target: { value: 'https://example.com/country.mmdb' },- })- await user.click(screen.getByRole('button', { name: /Update now/i }))- await waitFor(() =>- expect(mockInvoke).toHaveBeenCalledWith(Commands.UpdateGeoIPDatabase)- )- const saveIndex = mockInvoke.mock.calls.findIndex(- ([command]) => command === Commands.UpdateSettings- )- const updateIndex = mockInvoke.mock.calls.findIndex(- ([command]) => command === Commands.UpdateGeoIPDatabase- )- expect(mockInvoke.mock.calls[saveIndex]).toEqual([- Commands.UpdateSettings,- {- geoip: {- source: 'custom',- customUrl: 'https://example.com/country.mmdb',- },- },- ])- expect(saveIndex).toBeLessThan(updateIndex)- })-- it('allows disabling GeoIP with an invalid custom URL without saving that draft', async () => {- const { user, input } = await selectCustomSource()- fireEvent.change(input, { target: { value: 'broken address' } })- await user.click(- screen.getByRole('switch', { name: /Enable IP-to-country lookup/i })- )- await waitFor(() =>- expect(mockInvoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- geoip: { enabled: false },- })- )- const writes = mockInvoke.mock.calls.filter(- ([command]) => command === Commands.UpdateSettings- )- expect(writes).toEqual([- [Commands.UpdateSettings, { geoip: { enabled: false } }],- ])- })-- it('does not update the database after a save failure and retries the same draft', async () => {- const { user, input } = await selectCustomSource()- const original = mockInvoke.getMockImplementation()- let fail = true- mockInvoke.mockImplementation(async (channel: string) => {- if (channel === Commands.UpdateSettings && fail)- throw new Error('internal transport error')- return original?.(channel)- })- fireEvent.change(input, {- target: { value: 'https://example.com/country.mmdb' },+ )+})+function Harness({ enabled = false }: { enabled?: boolean }) {+ const form = useSettingsForm(+ bitTorrentFormSchema,+ bitTorrentFormSchema.parse({+ engine: DEFAULT_ENGINE_SETTINGS,+ app: DEFAULT_APP_SETTINGS,+ tracker: DEFAULT_TRACKER_SETTINGS,+ geoip: { ...DEFAULT_GEOIP_SETTINGS, enabled },})- await user.click(screen.getByRole('button', { name: /Update now/i }))- expect(- await screen.findByText('Couldn’t save your changes. Try again.')- ).toBeVisible()- expect(mockInvoke).not.toHaveBeenCalledWith(Commands.UpdateGeoIPDatabase)- fail = false- await user.click(screen.getByRole('button', { name: /Update now/i }))- await waitFor(() =>- expect(mockInvoke).toHaveBeenCalledWith(Commands.UpdateGeoIPDatabase)- )- })+ )+ return (+ <Form {...form}>+ <BtPeerGeoSection form={form} ready />+ </Form>+ )+}+it('keeps preference changes in the outer draft and blocks Update until saved', async () => {+ render(<Harness />)+ fireEvent.click(+ screen.getByRole('switch', { name: 'Show country or region' })+ )+ expect(screen.getByRole('button', { name: 'Update now' })).toBeDisabled()+ expect(+ screen.getByText('Save changes before updating location data.')+ ).toBeVisible()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.UpdateSettings,+ expect.anything()+ )+ const user = userEvent.setup()+ await user.click(+ screen.getByRole('combobox', { name: 'Location data source' })+ )+ await user.click(screen.getByRole('option', { name: 'Custom URL' }))+ expect(+ screen.getByRole('textbox', { name: 'Custom download URL' })+ ).toBeEnabled()+})+it('runs a database update using saved settings without saving the form', async () => {+ render(<Harness enabled />)+ fireEvent.click(screen.getByRole('button', { name: 'Update now' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateGeoIPDatabase)+ )+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.UpdateSettings,+ expect.anything()+ )+})+it('does not offer a database update when locations are disabled', () => {+ render(<Harness />)+ expect(screen.getByRole('button', { name: 'Update now' })).toBeDisabled()})diff --git a/src/renderer/routes/settings/cards/bt-peer-geo-section.tsx b/src/renderer/routes/settings/cards/bt-peer-geo-section.tsxindex 80ed8ba0..bf756a8a 100644--- a/src/renderer/routes/settings/cards/bt-peer-geo-section.tsx+++ b/src/renderer/routes/settings/cards/bt-peer-geo-section.tsx@@ -1,9 +1,7 @@import { SettingsFormRow } from '@renderer/components/settings-kit/settings-form-row'import { SettingsSelectTrigger } from '@renderer/components/settings-kit/settings-select-trigger'-import { useSettingsForm } from '@renderer/components/settings-kit/use-settings-form'import { Button } from '@renderer/components/ui/button'import {- Form,FormControl,FormDescription,FormField,@@ -21,25 +19,11 @@ import { Spinner } from '@renderer/components/ui/spinner'import { Switch } from '@renderer/components/ui/switch'import { useByteFormat } from '@renderer/hooks/use-byte-format'import { useGeoIPStatus } from '@renderer/hooks/use-geoip-status'-import { saveSettings } from '@renderer/lib/settings-save'-import { transport } from '@renderer/lib/transport'-import { Queries } from '@shared/protocol/queries'-import {- DEFAULT_GEOIP_SETTINGS,- geoIpSettingsInputSchema,-} from '@shared/schemas/geoip-settings'-import type { GeoIPSettings, GeoIPSource } from '@shared/types/geoip'-import type { AppSettings } from '@shared/types/settings'-import {- type Ref,- useEffect,- useImperativeHandle,- useRef,- useState,-} from 'react'+import type { GeoIPSource } from '@shared/types/geoip'+import { useEffect, useRef, useState } from 'react'+import type { UseFormReturn } from 'react-hook-form'import { useTranslation } from 'react-i18next'--const SAVE_DEBOUNCE_MS = 400+import type { BtFields } from './bit-torrent-dialog'const SOURCES: ReadonlyArray<{ key: GeoIPSource; disabled?: boolean }> = [{ key: 'loyalsoldier' },@@ -55,148 +39,52 @@ function formatTimestamp(ts: number): string {return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`}-export interface BtPeerGeoSectionHandle {- flush: () => Promise<boolean>-}-export function BtPeerGeoSection({- ref,+ form,+ ready,}: {- ref?: Ref<BtPeerGeoSectionHandle>+ form: UseFormReturn<BtFields>+ ready: boolean}) {const { formatBytes } = useByteFormat()-const { t } = useTranslation()const { status, progress, triggerUpdate } = useGeoIPStatus()const [updateError, setUpdateError] = useState<string | null>(null)- const form = useSettingsForm<GeoIPSettings>(- geoIpSettingsInputSchema,- DEFAULT_GEOIP_SETTINGS- )- const sourceOptions = SOURCES.map(({ key, disabled }) => ({- value: key,- label: `${t(`settings.bittorrent.geoip.source.${key}`)}${- disabled ? ` (${t('settings.bittorrent.geoip.maxmindUnsupported')})` : ''- }`,- disabled,- }))-- const savedValues = useRef(DEFAULT_GEOIP_SETTINGS)- const revision = useRef(0)+ const [updating, setUpdating] = useState(false)const mounted = useRef(true)- const saveQueue = useRef<Promise<void>>(Promise.resolve())- const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)-- // Initial fetch — settings are the source of truth for source/url/etc.;- // `status` (from the hook) drives the live download/loaded indicators.- useEffect(() => {- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings- if (all?.geoip) {- savedValues.current = all.geoip- form.reset(all.geoip)- }- })- .catch(() => {- /* keep defaults */- })- return () => {- cancelled = true- }- }, [form])-useEffect(() => {mounted.current = truereturn () => {mounted.current = false- revision.current += 1- if (debounceRef.current) clearTimeout(debounceRef.current)}}, [])-- const persist = (expectedRevision: number, disableOnly = false) => {- const pending = saveQueue.current.then(async () => {- if (!mounted.current || revision.current !== expectedRevision)- return false- const valid = disableOnly- ? await form.trigger('enabled')- : await form.trigger()- if (!valid || !mounted.current || revision.current !== expectedRevision)- return false- const values = form.getValues()- const patch: Partial<GeoIPSettings> = disableOnly- ? { enabled: false }- : Object.fromEntries(- (['enabled', 'source', 'customUrl', 'autoUpdate'] as const)- .filter((key) => values[key] !== savedValues.current[key])- .map((key) => [key, values[key]])- )- if (Object.keys(patch).length === 0) {- form.clearErrors('root.save')- return true- }- try {- await saveSettings({ geoip: patch })- savedValues.current = { ...savedValues.current, ...patch }- if (mounted.current) form.clearErrors('root.save')- return true- } catch {- if (mounted.current)- form.setError('root.save', {- type: 'server',- message: t('settings.validation.saveFailed'),- })- return false- }- })- saveQueue.current = pending.then(- () => undefined,- () => undefined- )- return pending- }-- const saveField = <Key extends keyof GeoIPSettings>(- key: Key,- value: GeoIPSettings[Key],- debounce = false- ) => {- const expectedRevision = ++revision.current- if (debounceRef.current) clearTimeout(debounceRef.current)- if (debounce) {- debounceRef.current = setTimeout(() => {- debounceRef.current = null- void persist(expectedRevision)- }, SAVE_DEBOUNCE_MS)- } else {- void persist(expectedRevision, key === 'enabled' && value === false)- }- }-- const flush = () => {- if (debounceRef.current) clearTimeout(debounceRef.current)- return persist(++revision.current)- }- useImperativeHandle(ref, () => ({ flush }))-- const enabled = form.watch('enabled')- const source = form.watch('source')- const isDownloading = status?.isDownloading ?? false+ const sourceOptions = SOURCES.map(({ key, disabled }) => ({+ value: key,+ label: `${t(`settings.bittorrent.geoip.source.${key}`)}${disabled ? ` (${t('settings.bittorrent.geoip.maxmindUnsupported')})` : ''}`,+ disabled,+ }))+ const enabled = form.watch('geoip.enabled')+ const source = form.watch('geoip.source')+ const pendingChanges = Boolean(form.formState.dirtyFields.geoip)+ const isDownloading = updating || (status?.isDownloading ?? false)const handleUpdateNow = async () => {- setUpdateError(null)- if (debounceRef.current) clearTimeout(debounceRef.current)- const expectedRevision = ++revision.current- const saved = await persist(expectedRevision)- if (!saved || !mounted.current || revision.current !== expectedRevision)+ if (+ !ready ||+ pendingChanges ||+ !enabled ||+ isDownloading ||+ form.formState.isSubmitting+ )return+ setUpdateError(null)+ setUpdating(true)try {await triggerUpdate()- } catch (err) {- setUpdateError(err instanceof Error ? err.message : 'update failed')+ } catch {+ if (mounted.current)+ setUpdateError(t('settings.bittorrent.geoip.updateFailed'))+ } finally {+ if (mounted.current) setUpdating(false)}}@@ -210,181 +98,183 @@ export function BtPeerGeoSection({{t('settings.bittorrent.geoip.title')}</h3>- <Form {...form}>- <form- className="space-y-4"- noValidate- onSubmit={(event) => event.preventDefault()}- >- <FormField- control={form.control}- name="enabled"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>{t('settings.bittorrent.geoip.enable')}</FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.geoip.enableDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={(v) => {- const next = Boolean(v)- field.onChange(next)- saveField('enabled', next)- }}- />- </FormControl>- </SettingsFormRow>- )}- />+ <div className="space-y-4">+ <FormField+ control={form.control}+ name="geoip.enabled"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>{t('settings.bittorrent.geoip.enable')}</FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.geoip.enableDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={(v) => {+ const next = Boolean(v)+ field.onChange(next)+ }}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />- <div className="flex items-center justify-between gap-4">- <div className="flex flex-col gap-0.5 text-xs text-muted-foreground">- <span>- {t('settings.bittorrent.geoip.lastUpdated')}: {lastUpdatedLabel}+ <div className="flex items-center justify-between gap-4">+ <div className="flex flex-col gap-0.5 text-xs text-muted-foreground">+ <span>+ {t('settings.bittorrent.geoip.lastUpdated')}: {lastUpdatedLabel}+ </span>+ <span>+ {status?.databaseVersion+ ? `v${status.databaseVersion} · ${formatBytes(status.sizeBytes)}`+ : t('settings.bittorrent.geoip.status.notDownloaded')}+ </span>+ {(status?.lastError || updateError) && (+ <span className="text-destructive" data-testid="geoip-error">+ {updateError ?? status?.lastError}</span>- <span>- {status?.databaseVersion- ? `v${status.databaseVersion} · ${formatBytes(status.sizeBytes)}`- : t('settings.bittorrent.geoip.status.notDownloaded')}- </span>- {(status?.lastError || updateError) && (- <span className="text-destructive" data-testid="geoip-error">- {updateError ?? status?.lastError}- </span>- )}- </div>- <Button- type="button"- size="sm"- variant="outline"- disabled={!enabled || isDownloading}- onClick={handleUpdateNow}- >- {isDownloading ? (- <>- <Spinner className="size-3" />- {progress && progress.percent >= 0- ? `${Math.round(progress.percent * 100)}%`- : t('settings.bittorrent.geoip.updating')}- </>- ) : (- t('settings.bittorrent.geoip.updateNow')- )}- </Button>+ )}</div>-- <FormField- control={form.control}- name="source"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>{t('settings.bittorrent.geoip.source')}</FormLabel>- <FormDescription className="text-xs">- {t('settings.bittorrent.geoip.sourceDesc')}- </FormDescription>- </div>- <FormControl>- <Select- items={sourceOptions}- value={field.value}- onValueChange={(value) => {- if (value === null) return- field.onChange(value)- saveField('source', value)- }}- disabled={!enabled}- >- <SettingsSelectTrigger className="min-w-56 max-w-80">- <SelectValue />- </SettingsSelectTrigger>- <SelectContent>- <SelectGroup>- {sourceOptions.map(({ disabled, label, value }) => (- <SelectItem- key={value}- value={value}- disabled={disabled}- >- {label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </SettingsFormRow>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={+ !ready ||+ !enabled ||+ isDownloading ||+ pendingChanges ||+ form.formState.isSubmitting+ }+ onClick={handleUpdateNow}+ >+ {isDownloading ? (+ <>+ <Spinner className="size-3" />+ {progress && progress.percent >= 0+ ? `${Math.round(progress.percent * 100)}%`+ : t('settings.bittorrent.geoip.updating')}+ </>+ ) : (+ t('settings.bittorrent.geoip.updateNow'))}- />+ </Button>+ </div>- {(source === 'custom' || form.formState.errors.customUrl) && (- <FormField- control={form.control}- name="customUrl"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.bittorrent.geoip.customUrl')}- </FormLabel>- </div>- <FormControl>- <Input- className="w-72 h-8"- disabled={!enabled && !form.formState.errors.customUrl}- placeholder={t(- 'settings.bittorrent.geoip.customUrlPlaceholder'- )}- {...field}- onChange={(e) => {- field.onChange(e)- saveField('customUrl', e.target.value, true)- }}- />- </FormControl>- </SettingsFormRow>- )}- />+ {pendingChanges && (+ <p className="text-xs text-muted-foreground">+ {t('settings.bittorrent.geoip.saveBeforeUpdate')}+ </p>+ )}++ <FormField+ control={form.control}+ name="geoip.source"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>{t('settings.bittorrent.geoip.source')}</FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.geoip.sourceDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Select+ items={sourceOptions}+ value={field.value}+ onValueChange={(value) => {+ if (value === null) return+ field.onChange(value)+ }}+ disabled={!enabled}+ >+ <SettingsSelectTrigger className="min-w-56 max-w-80">+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent>+ <SelectGroup>+ {sourceOptions.map(({ disabled, label, value }) => (+ <SelectItem+ key={value}+ value={value}+ disabled={disabled}+ >+ {label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </SettingsFormRow>)}+ />+ {(source === 'custom' || form.formState.errors.geoip?.customUrl) && (<FormFieldcontrol={form.control}- name="autoUpdate"+ name="geoip.customUrl"render={({ field }) => (<SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.bittorrent.geoip.autoUpdate')}+ {t('settings.bittorrent.geoip.customUrl')}</FormLabel><FormDescription className="text-xs">- {t('settings.bittorrent.geoip.autoUpdateDesc')}+ {t('settings.bittorrent.geoip.customUrlDesc')}</FormDescription></div><FormControl>- <Switch- checked={field.value}- disabled={!enabled}- onCheckedChange={(v) => {- const next = Boolean(v)- field.onChange(next)- saveField('autoUpdate', next)+ <Input+ className="w-72 h-8"+ disabled={+ !enabled && !form.formState.errors.geoip?.customUrl+ }+ placeholder={t(+ 'settings.bittorrent.geoip.customUrlPlaceholder'+ )}+ {...field}+ onChange={(e) => {+ field.onChange(e)}}/></FormControl></SettingsFormRow>)}/>- {form.formState.errors.root?.save && (- <p role="alert" className="text-xs text-destructive">- {form.formState.errors.root.save.message}- </p>+ )}++ <FormField+ control={form.control}+ name="geoip.autoUpdate"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.bittorrent.geoip.autoUpdate')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.bittorrent.geoip.autoUpdateDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ disabled={!enabled}+ onCheckedChange={(v) => {+ const next = Boolean(v)+ field.onChange(next)+ }}+ />+ </FormControl>+ </SettingsFormRow>)}- </form>- </Form>+ />+ </div></section>)}diff --git a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx b/src/renderer/routes/settings/cards/downloads-dialog.test.tsxindex 8a92a092..d285b5d5 100644--- a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx@@ -1,3 +1,7 @@+import {+ downloadsSettingsResult,+ TEST_DOWNLOADS_REVISION,+} from '@test-utils/downloads-settings'import '@test-utils/dom-animations'import { setByteUnitSystem } from '@renderer/hooks/use-byte-format'import '@testing-library/jest-dom/vitest'@@ -30,12 +34,21 @@ const { toastAddMock, runtime } = vi.hoisted(() => ({vi.mock('@renderer/lib/transport', () => ({transport: {invoke: vi.fn(),+ on: vi.fn(),+ off: vi.fn(),get platform() {return runtime.platform},},}))+vi.mock('@renderer/platform/services', () => ({+ usePlatformServices: () => ({+ kind: 'electron',+ pickSaveDir: vi.fn(async () => null),+ }),+}))+vi.mock('@renderer/components/ui/toast', () => ({toast: { add: toastAddMock, close: vi.fn() },}))@@ -98,8 +111,9 @@ describe('<DownloadsDialog>', () => {vi.mocked(transport.invoke).mockReset()toastAddMock.mockReset()vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel === Queries.GetSettings) return FIXTURE- return { saved: true, requiresRestart: false, changedRestartKeys: [] }+ if (channel === Queries.GetDownloadsSettingsDraft)+ return downloadsSettingsResult(FIXTURE)+ return downloadsSettingsResult(FIXTURE)})})@@ -116,7 +130,9 @@ describe('<DownloadsDialog>', () => {name: 'When deleting task files',})await waitFor(() =>- expect(screen.getByLabelText(/magnet resolve timeout/i)).toHaveValue(120)+ expect(screen.getByLabelText(/default download folder/i)).toHaveValue(+ '/downloads'+ ))expect(deletion).toHaveTextContent('Move to trash')const user = userEvent.setup()@@ -125,21 +141,33 @@ describe('<DownloadsDialog>', () => {await screen.findByRole('option', { name: 'Delete permanently' }))expect(- screen.getByText(- 'Files are deleted directly and cannot be restored from the trash.'- )+ screen.getByText('Deleted files cannot be restored from the trash.')).toBeVisible()await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- app: { fileDeletionMode: 'permanent' },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ app: { fileDeletionMode: 'permanent' },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('hydrates a saved deletion mode and can switch back to trash', async () => {vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel === Queries.GetSettings)- return { ...FIXTURE, app: { fileDeletionMode: 'permanent' } }- return { saved: true, requiresRestart: false, changedRestartKeys: [] }+ if (channel === Queries.GetDownloadsSettingsDraft)+ return downloadsSettingsResult({+ ...FIXTURE,+ app: { fileDeletionMode: 'permanent' },+ })+ return downloadsSettingsResult(FIXTURE)})render(<DownloadsDialog@@ -161,9 +189,20 @@ describe('<DownloadsDialog>', () => {await screen.findByRole('option', { name: 'Move to trash' }))await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- app: { fileDeletionMode: 'trash' },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ app: { fileDeletionMode: 'trash' },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('hides the desktop deletion preference in the web client', async () => {@@ -177,7 +216,9 @@ describe('<DownloadsDialog>', () => {/>)await waitFor(() =>- expect(screen.getByLabelText(/magnet resolve timeout/i)).toHaveValue(120)+ expect(screen.getByLabelText(/default download folder/i)).toHaveValue(+ '/downloads'+ ))expect(screen.queryByRole('combobox', { name: 'When deleting task files' })@@ -208,32 +249,21 @@ describe('<DownloadsDialog>', () => {fireEvent.change(concurrent, { target: { value: '10' } })const user = userEvent.setup()await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- engine: { maxConcurrentDownloads: 10 },- })- expect(onClose).toHaveBeenCalled()- })-- it('allows saving a 900-second magnet metadata timeout', async () => {- render(- <DownloadsDialog- open- onClose={vi.fn()}- labelKey="settings.cards.downloads.title"- descKey="settings.cards.downloads.desc"- />+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ engine: { maxConcurrentDownloads: 10 },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ })-- const input = await screen.findByLabelText(/magnet resolve timeout/i)- await waitFor(() => expect(input).toHaveValue(120))- expect(input).toHaveAttribute('max', '900')- fireEvent.change(input, { target: { value: '900' } })-- const user = userEvent.setup()- await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- engine: { magnetResolveTimeout: 900 },- })+ expect(onClose).toHaveBeenCalled()})it.each([@@ -249,11 +279,9 @@ describe('<DownloadsDialog>', () => {['min segment size', '1025', 'Enter a number from 1 to 1024.'],['min segment size', '0.5', 'Enter a number from 1 to 1024.'],['disk cache', '129', 'Enter a number from 0 to 128.'],- ['max concurrent downloads', '101', 'Enter a whole number from 1 to 100.'],- ['connect timeout', '601', 'Enter a whole number from 1 to 600.'],- ['max retries', '-1', 'Enter a whole number from 0 to 100.'],- ['session save interval', '3601', 'Enter a whole number from 10 to 3600.'],- ['magnet resolve timeout', '901', 'Enter a whole number from 30 to 900.'],+ ['simultaneous downloads', '101', 'Enter a whole number from 1 to 100.'],+ ['connection timeout', '601', 'Enter a whole number from 1 to 600.'],+ ['maximum attempts', '-1', 'Enter a whole number from 0 to 100.'],])('blocks saving %s = %s with an inline error',async (label, value, message) => {@@ -268,7 +296,7 @@ describe('<DownloadsDialog>', () => {)const user = userEvent.setup()await user.click(- await screen.findByRole('combobox', { name: /performance profile/i })+ await screen.findByRole('combobox', { name: /download performance/i }))await user.click(await screen.findByRole('option', { name: /^custom$/i }))const input = screen.getByLabelText(new RegExp(label, 'i'))@@ -279,8 +307,8 @@ describe('<DownloadsDialog>', () => {expect(input).toHaveAttribute('aria-invalid', 'true')await waitFor(() => expect(input).toHaveFocus())expect(transport.invoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()+ Commands.SaveDownloadsSettings,+ expect.objectContaining({ settings: expect.anything() }))expect(onClose).not.toHaveBeenCalled()}@@ -296,7 +324,7 @@ describe('<DownloadsDialog>', () => {/>)const user = userEvent.setup()- const input = await screen.findByLabelText(/max concurrent downloads/i)+ const input = await screen.findByLabelText(/simultaneous downloads/i)fireEvent.change(input, { target: { value: '1000' } })await user.click(screen.getByRole('button', { name: /save/i }))expect(@@ -308,9 +336,20 @@ describe('<DownloadsDialog>', () => {await user.click(within(row).getByRole('button', { name: '30' }))await waitFor(() => expect(input).toHaveAttribute('aria-invalid', 'false'))await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- engine: { maxConcurrentDownloads: 30 },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ engine: { maxConcurrentDownloads: 30 },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('rejects a negative speed limit instead of silently making it unlimited', async () => {@@ -322,14 +361,14 @@ describe('<DownloadsDialog>', () => {descKey="settings.cards.downloads.desc"/>)- const input = await screen.findByLabelText(/standard download limit/i)+ const input = await screen.findByLabelText(/download — standard limits/i)fireEvent.change(input, { target: { value: '-1' } })await userEvent.setup().click(screen.getByRole('button', { name: /save/i }))expect(await screen.findByText('Enter 0 or more.')).toBeVisible()expect(input).toHaveAttribute('aria-invalid', 'true')expect(transport.invoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()+ Commands.SaveDownloadsSettings,+ expect.objectContaining({ settings: expect.anything() }))})@@ -345,7 +384,7 @@ describe('<DownloadsDialog>', () => {const user = userEvent.setup()await user.click(- await screen.findByRole('combobox', { name: /performance profile/i })+ await screen.findByRole('combobox', { name: /download performance/i }))await user.click(await screen.findByRole('option', { name: /^custom$/i }))@@ -371,7 +410,7 @@ describe('<DownloadsDialog>', () => {const user = userEvent.setup()await user.click(- await screen.findByRole('combobox', { name: /performance profile/i })+ await screen.findByRole('combobox', { name: /download performance/i }))await user.click(await screen.findByRole('option', { name: /^high speed$/i })@@ -384,15 +423,26 @@ describe('<DownloadsDialog>', () => {)await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- engine: {- performanceProfile: 'high',- maxConnectionPerServer:- ENGINE_PERFORMANCE_PROFILES.high.maxConnectionPerServer,- split: ENGINE_PERFORMANCE_PROFILES.high.split,- diskCache: ENGINE_PERFORMANCE_PROFILES.high.diskCache,- },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ engine: {+ performanceProfile: 'high',+ maxConnectionPerServer:+ ENGINE_PERFORMANCE_PROFILES.high.maxConnectionPerServer,+ split: ENGINE_PERFORMANCE_PROFILES.high.split,+ diskCache: ENGINE_PERFORMANCE_PROFILES.high.diskCache,+ },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('places custom performance parameters before concurrent downloads', async () => {@@ -407,12 +457,12 @@ describe('<DownloadsDialog>', () => {const user = userEvent.setup()await user.click(- await screen.findByRole('combobox', { name: /performance profile/i })+ await screen.findByRole('combobox', { name: /download performance/i }))await user.click(await screen.findByRole('option', { name: /^custom$/i }))const customParameters = screen.getByText(/custom performance parameters/i)- const concurrentDownloads = screen.getByText(/max concurrent downloads/i)+ const concurrentDownloads = screen.getByText(/simultaneous downloads/i)expect(customParameters.compareDocumentPosition(concurrentDownloads) &Node.DOCUMENT_POSITION_FOLLOWING@@ -430,7 +480,7 @@ describe('<DownloadsDialog>', () => {)const user = userEvent.setup()await user.click(- await screen.findByRole('combobox', { name: /performance profile/i })+ await screen.findByRole('combobox', { name: /download performance/i }))await user.click(await screen.findByRole('option', { name: /^custom$/i }))@@ -442,18 +492,33 @@ describe('<DownloadsDialog>', () => {fireEvent.change(screen.getByLabelText(/disk cache/i), {target: { value: '64' },})- await user.click(screen.getByRole('combobox', { name: /file allocation/i }))- await user.click(await screen.findByRole('option', { name: /^prealloc$/i }))+ await user.click(+ screen.getByRole('combobox', { name: /reserve disk space/i })+ )+ await user.click(+ await screen.findByRole('option', { name: /^preallocate$/i })+ )await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- engine: {- performanceProfile: 'custom',- split: 32,- fileAllocation: 'prealloc',- diskCache: 64 * 1024 * 1024,- },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ engine: {+ performanceProfile: 'custom',+ split: 32,+ fileAllocation: 'prealloc',+ diskCache: 64 * 1024 * 1024,+ },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )expect(screen.queryByText(/restart to apply changes/i)).toBeNull()})@@ -471,17 +536,30 @@ describe('<DownloadsDialog>', () => {const modifiedTime = await screen.findByRole('combobox', {name: /file modification time/i,})- expect(modifiedTime).toHaveTextContent(/^local$/i)+ expect(modifiedTime).toHaveTextContent(/^download time$/i)expect(modifiedTime).toHaveClass('min-w-30', 'max-w-64')expect(modifiedTime).not.toHaveClass('w-30')await user.click(modifiedTime)- await user.click(await screen.findByRole('option', { name: /^server$/i }))+ await user.click(+ await screen.findByRole('option', { name: /^time from server$/i })+ )await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- engine: { remoteTime: true },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ engine: { remoteTime: true },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('allows the localized file modification value to size intrinsically', async () => {@@ -498,7 +576,7 @@ describe('<DownloadsDialog>', () => {const modifiedTime = await screen.findByRole('combobox', {name: '文件修改时间',})- expect(modifiedTime).toHaveTextContent('本地修改时间')+ expect(modifiedTime).toHaveTextContent('下载时间')expect(screen.getByRole('link', { name: '了解更多' })).toHaveAttribute('href',EXTERNAL_URLS.motrix.manual.downloadPerformance.zh@@ -547,7 +625,7 @@ describe('<DownloadsDialog>', () => {const performance = screen.getByRole('heading', { name: 'Performance' })const speedLimits = screen.getByRole('heading', { name: 'Speed limits' })const reliability = screen.getByRole('heading', {- name: 'Network reliability',+ name: 'Connections and retries',})const follows = (first: Element, second: Element) =>Boolean(@@ -557,7 +635,7 @@ describe('<DownloadsDialog>', () => {expect(follows(performance, speedLimits)).toBe(true)expect(follows(speedLimits, reliability)).toBe(true)- const modeGroup = screen.getByRole('group', { name: 'Current mode' })+ const modeGroup = screen.getByRole('group', { name: 'Speed mode' })expect(modeGroup).toHaveClass('gap-0','rounded-lg',@@ -587,28 +665,39 @@ describe('<DownloadsDialog>', () => {})const user = userEvent.setup()const baseDown = screen.getByLabelText(- /standard download limit/i+ /download — standard limits/i) as HTMLInputElement// Decimal KB/s → bytes/sec: 1024 * 1000 = 1_024_000.fireEvent.change(baseDown, { target: { value: '1024' } })await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- speedLimit: { base: { download: 1024 * 1000 } },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ speedLimit: { base: { download: 1024 * 1000 } },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )expect(onClose).toHaveBeenCalled()})it('converts an existing limit on unit changes without marking it dirty', async () => {vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel === Queries.GetSettings)- return {+ if (channel === Queries.GetDownloadsSettingsDraft)+ return downloadsSettingsResult({...FIXTURE,speedLimit: {...DEFAULT_SPEED_LIMIT_SETTINGS,base: { download: 1_048_576, upload: 0 },},- }- return { saved: true, requiresRestart: false, changedRestartKeys: [] }+ })+ return downloadsSettingsResult(FIXTURE)})render(<DownloadsDialog@@ -618,15 +707,15 @@ describe('<DownloadsDialog>', () => {descKey="settings.cards.downloads.desc"/>)- const input = screen.getByLabelText(/standard download limit/i)+ const input = screen.getByLabelText(/download — standard limits/i)await waitFor(() => expect(input).toHaveValue(1048.576))act(() => setByteUnitSystem('binary'))expect(input).toHaveValue(1024)expect(input).toHaveAttribute('aria-valuetext', '1024 KiB/s')await userEvent.setup().click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ expect.objectContaining({ settings: {} }))})@@ -641,15 +730,26 @@ describe('<DownloadsDialog>', () => {/>)await waitFor(() =>- expect(screen.getByLabelText(/standard download limit/i)).toBeEnabled()+ expect(screen.getByLabelText(/download — standard limits/i)).toBeEnabled())- fireEvent.change(screen.getByLabelText(/standard download limit/i), {+ fireEvent.change(screen.getByLabelText(/download — standard limits/i), {target: { value: '1024' },})await userEvent.setup().click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- speedLimit: { base: { download: 1_048_576 } },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ speedLimit: { base: { download: 1_048_576 } },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it.each(['decimal', 'binary'] as const)(@@ -664,25 +764,36 @@ describe('<DownloadsDialog>', () => {descKey="settings.cards.downloads.desc"/>)- const input = screen.getByLabelText(/standard download limit/i)+ const input = screen.getByLabelText(/download — standard limits/i)await waitFor(() => expect(input).toBeEnabled())const user = userEvent.setup()await user.clear(input)await user.type(input, '1.1')expect(input).toHaveValue(1.1)await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- speedLimit: {- base: { download: unitSystem === 'binary' ? 1126 : 1100 },- },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ speedLimit: {+ base: { download: unitSystem === 'binary' ? 1126 : 1100 },+ },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('groups compact reset actions with their speed limit inputs', async () => {vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel === Queries.GetSettings) {- return {+ if (channel === Queries.GetDownloadsSettingsDraft) {+ return downloadsSettingsResult({...FIXTURE,speedLimit: {...DEFAULT_SPEED_LIMIT_SETTINGS,@@ -691,9 +802,9 @@ describe('<DownloadsDialog>', () => {download: 1024 * 1024,},},- }+ })}- return { saved: true, requiresRestart: false, changedRestartKeys: [] }+ return downloadsSettingsResult(FIXTURE)})render(@@ -707,10 +818,10 @@ describe('<DownloadsDialog>', () => {const user = userEvent.setup()const baseDown = (await screen.findByLabelText(- /standard download limit/i+ /download — standard limits/i)) as HTMLInputElementconst altDown = screen.getByLabelText(- /low-speed download limit/i+ /download — low speed limits/i) as HTMLInputElementconst setUnlimited = screen.getByRole('button', {name: /set unlimited/i,@@ -732,15 +843,26 @@ describe('<DownloadsDialog>', () => {expect(baseDown).toHaveValue(null)expect(baseDown).toHaveAttribute('placeholder', 'Unlimited')expect(altDown).toHaveValue(null)- expect(altDown).toHaveAttribute('placeholder', 'Standard limit')+ expect(altDown).toHaveAttribute('placeholder', 'Use standard')await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- speedLimit: {- base: { download: 0 },- alt: { download: 0 },- },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ speedLimit: {+ base: { download: 0 },+ alt: { download: 0 },+ },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )})it('switching the turtle state to auto submits a turtle patch', async () => {@@ -762,13 +884,24 @@ describe('<DownloadsDialog>', () => {const user = userEvent.setup()await user.click(screen.getByRole('button', { name: /^automatic$/i }))await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- speedLimit: { turtle: 'auto' },- })+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ speedLimit: { turtle: 'auto' },+ },+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )expect(onClose).toHaveBeenCalled()})- it('explains an automatic mode with no rules and localizes weekdays', async () => {+ it('localizes weekdays and validates 24-hour schedule input', async () => {render(<DownloadsDialogopen@@ -785,13 +918,10 @@ describe('<DownloadsDialog>', () => {const user = userEvent.setup()await user.click(screen.getByRole('button', { name: /^automatic$/i }))- expect(- screen.getByText(/no automatic rules are enabled/i)- ).toBeInTheDocument()await user.click(screen.getByRole('switch', {- name: /use low-speed limits on a schedule/i,+ name: /schedule low speed/i,}))expect(screen.getByRole('button', { name: 'Sunday' })).toHaveTextContent(@@ -806,7 +936,6 @@ describe('<DownloadsDialog>', () => {'aria-pressed','true')- expect(screen.getByText(/24-hour format \(HH:mm\)/i)).toBeInTheDocument()const startTime = screen.getByLabelText(/^start$/i)const endTime = screen.getByLabelText(/^end$/i)@@ -823,14 +952,11 @@ describe('<DownloadsDialog>', () => {).toBeVisible()expect(startTime).toHaveValue('99:99')expect(transport.invoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()+ Commands.SaveDownloadsSettings,+ expect.objectContaining({ settings: expect.anything() }))fireEvent.change(startTime, { target: { value: '2130' } })expect(startTime).toHaveValue('21:30')- expect(- screen.getByText(/use low-speed limits from 21:30 to 07:00/i)- ).toBeInTheDocument()})it('shows reserved bandwidth while storing Motrix usage percent', async () => {@@ -853,13 +979,11 @@ describe('<DownloadsDialog>', () => {await user.click(screen.getByRole('button', { name: /^automatic$/i }))await user.click(screen.getByRole('switch', {- name: /avoid using the entire connection/i,+ name: /reserve bandwidth for other apps/i,}))expect(- screen.getByText(- /reserve 20% of bandwidth for other apps after connection bandwidth is entered/i- )+ screen.getByText(/enter both connection speeds to apply this limit/i)).toBeInTheDocument()const reserved = screen.getByLabelText(@@ -877,33 +1001,45 @@ describe('<DownloadsDialog>', () => {)).toBeVisible()expect(transport.invoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()+ Commands.SaveDownloadsSettings,+ expect.objectContaining({ settings: expect.anything() }))expect(onClose).not.toHaveBeenCalled()}fireEvent.change(reserved, { target: { value: '30' } })await user.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {- speedLimit: {- turtle: 'auto',- auto: {- adaptive: {- enabled: true,- headroomPercent: 70,+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.SaveDownloadsSettings,+ {+ expectedRevision: TEST_DOWNLOADS_REVISION,+ settings: {+ speedLimit: {+ turtle: 'auto',+ auto: {+ adaptive: {+ enabled: true,+ headroomPercent: 70,+ },+ },},},- },- })+ directories: {+ addFavorites: [],+ removeFavorites: [],+ removeRecent: [],+ },+ }+ )expect(onClose).toHaveBeenCalled()})it('reports when recent speed estimation has no data', async () => {vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel === Queries.GetSettings) return FIXTURE+ if (channel === Queries.GetDownloadsSettingsDraft)+ return downloadsSettingsResult(FIXTURE)if (channel === Queries.GetSpeedHistory) return []- return { saved: true, requiresRestart: false, changedRestartKeys: [] }+ return downloadsSettingsResult(FIXTURE)})render(<DownloadsDialog@@ -923,11 +1059,11 @@ describe('<DownloadsDialog>', () => {await user.click(screen.getByRole('button', { name: /^automatic$/i }))await user.click(screen.getByRole('switch', {- name: /avoid using the entire connection/i,+ name: /reserve bandwidth for other apps/i,}))await user.click(- screen.getByRole('button', { name: /estimate from recent speeds/i })+ screen.getByRole('button', { name: /estimate connection speed/i }))await waitFor(() => {diff --git a/src/renderer/routes/settings/cards/downloads-dialog.tsx b/src/renderer/routes/settings/cards/downloads-dialog.tsxindex f3491243..d81f66bf 100644--- a/src/renderer/routes/settings/cards/downloads-dialog.tsx+++ b/src/renderer/routes/settings/cards/downloads-dialog.tsx@@ -1,4 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'+import { DirectoryPicker } from '@renderer/components/desktop-kit/directory-picker'+import { SettingsFormRow } from '@renderer/components/settings-kit/settings-form-row'import { useSettingsSubmit } from '@renderer/components/settings-kit/use-settings-form'import { Button } from '@renderer/components/ui/button'import {@@ -9,7 +11,16 @@ import {DialogHeader,DialogTitle,} from '@renderer/components/ui/dialog'-import { Form } from '@renderer/components/ui/form'+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+ useFormField,+} from '@renderer/components/ui/form'import {ScrollArea,ScrollAreaContent,@@ -17,14 +28,15 @@ import {ScrollBar,} from '@renderer/components/ui/scroll-area'import { Separator } from '@renderer/components/ui/separator'+import { Switch } from '@renderer/components/ui/switch'+import {+ DirectoryPreferencesSection,+ DirectoryPreferencesStatus,+} from '@renderer/features/directory-preferences/directory-preferences-section'import { useByteFormat } from '@renderer/hooks/use-byte-format'-import { pickDirty } from '@renderer/lib/form-utils'-import { saveSettings } from '@renderer/lib/settings-save'-import { transport } from '@renderer/lib/transport'-import { Queries } from '@shared/protocol/queries'import { createDefaultSpeedLimitSettings } from '@shared/schemas/speed-limit'-import type { AppSettings } from '@shared/types/settings'-import { useEffect } from 'react'+import type { ComponentProps } from 'react'+import { useRef, useState } from 'react'import { useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import type { SettingsCardDialogProps } from './card-types'@@ -33,21 +45,20 @@ import {type DownloadsFields,downloadsFormSchema,downloadsValidationError,- ENGINE_DEFAULTS,} from './downloads-form'-import { EngineTuningSection } from './engine-tuning-section'+import { EngineTuningSection, UserAgentSection } from './engine-tuning-section'import { PerformanceSection } from './performance-section'import { SpeedLimitSection } from './speed-limit-section'+import { useDownloadsSettingsDraft } from './use-downloads-settings-draft'// Form shape, defaults, and unit constants live in ./downloads-form.ts. The-// compact sections are ordered by user intent: performance, limits, then-// advanced engine behavior.+// sections follow the task flow: destinations, new tasks, performance and+// speed limits, then connection and file behavior.export function DownloadsDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()const { unitSystem } = useByteFormat()@@ -62,65 +73,45 @@ export function DownloadsDialog({mode: 'onBlur',})- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable across renders; this is a mount-only fetch- useEffect(() => {- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings- form.reset({- app: {- fileDeletionMode:- all?.app?.fileDeletionMode ??- DOWNLOADS_DEFAULTS.app.fileDeletionMode,- },- engine: all?.engine- ? { ...ENGINE_DEFAULTS, ...all.engine }- : ENGINE_DEFAULTS,- speedLimit: all?.speedLimit- ? {- ...createDefaultSpeedLimitSettings(unitSystem),- ...all.speedLimit,- }- : createDefaultSpeedLimitSettings(unitSystem),- })- })- .catch(() => {})- return () => {- cancelled = true- }- }, [])-- const onSubmit = useSettingsSubmit(form, async (values) => {- // pickDirty recurses the dirty-fields tree: if speedLimit.base.download- // is dirty, it returns { speedLimit: { base: { download: <new> } } }.- // SettingsManager deep-merges each top-level namespace, so partial- // patches for app, engine, and speedLimit are safe.- // biome-ignore lint/suspicious/noExplicitAny: dirtyFields shape doesn't fit DirtyTree; cast is safe- const dirty = pickDirty(values, form.formState.dirtyFields as any)- if (!dirty) {- onClose()- return- }- await saveSettings(dirty)- onClose()+ const directories = useDownloadsSettingsDraft(form)+ const contentRef = useRef<HTMLDivElement>(null)+ const [defaultPicking, setDefaultPicking] = useState(false)+ const [favoritePicking, setFavoritePicking] = useState(false)+ const busy = directories.saving || defaultPicking || favoritePicking+ const disabled = busy || directories.loading || !directories.ready+ const close = () => {+ if (!busy) onClose()+ }+ const onSubmit = useSettingsSubmit(form, async () => {+ if (disabled) return+ contentRef.current?.focus({ preventScroll: true })+ if (await directories.save()) onClose()})return (- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog+ open={open}+ onOpenChange={(v, details) => {+ if (!v) {+ if (busy) details.cancel()+ else close()+ }+ }}+ ><DialogContentclassName="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"initialFocus={false}><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.downloads.description')}+ </DialogDescription></DialogHeader><ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col"><ScrollAreaViewport+ ref={contentRef}tabIndex={-1}className="min-h-0 flex-1 overscroll-contain">@@ -128,13 +119,90 @@ export function DownloadsDialog({className="px-6 py-4"style={{ minWidth: '100%' }}>+ <DirectoryPreferencesStatus+ loading={directories.loading}+ error={directories.error}+ disabled={busy}+ onRetry={() => void directories.refresh()}+ /><Form {...form}>- <form className="space-y-4" noValidate onSubmit={onSubmit}>- <PerformanceSection form={form} />- <Separator className="my-4" />- <SpeedLimitSection form={form} />- <Separator className="my-4" />- <EngineTuningSection form={form} />+ <form noValidate onSubmit={onSubmit}>+ <fieldset+ className="min-w-0 space-y-4"+ inert={disabled}+ disabled={disabled}+ >+ <h3 className="text-sm font-semibold">+ {t('settings.downloads.saveFolders')}+ </h3>+ <FormField+ control={form.control}+ name="app.defaultSaveDir"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <FormLabel>+ {t('settings.downloads.defaultDownloadFolder')}+ </FormLabel>+ <SettingsDirectoryPicker+ disabled={disabled}+ recordRecent={false}+ allowFavoriteEditing={false}+ onPickingChange={setDefaultPicking}+ inputProps={{+ ref: field.ref,+ onBlur: field.onBlur,+ }}+ />+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ <p className="text-xs text-muted-foreground">+ {t('directoryPreferences.description')}+ </p>+ <DirectoryPreferencesSection+ preferences={directories.preferences}+ onChange={directories.setPreferences}+ disabled={disabled}+ onPickingChange={setFavoritePicking}+ />+ <Separator className="my-4" />+ <h3 className="text-sm font-semibold">+ {t('settings.downloads.newTasks')}+ </h3>+ <FormField+ control={form.control}+ name="app.autofillClipboardLinks"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.downloads.autofillFromClipboard')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.downloads.fillInLinksWhenOpeningNewTask'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ disabled={disabled}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <UserAgentSection form={form} />+ <Separator className="my-4" />+ <PerformanceSection form={form} />+ <Separator className="my-4" />+ <SpeedLimitSection form={form} />+ <Separator className="my-4" />+ <EngineTuningSection form={form} />+ </fieldset></form></Form></ScrollAreaContent>@@ -148,14 +216,20 @@ export function DownloadsDialog({{form.formState.errors.root.save.message}</p>)}- <Button type="button" variant="outline" size="sm" onClick={onClose}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={close}+ >{t('common.cancel')}</Button><Buttontype="button"size="sm"onClick={onSubmit}- disabled={form.formState.isSubmitting}+ disabled={disabled || form.formState.isSubmitting}>{t('common.save')}</Button>@@ -164,3 +238,22 @@ export function DownloadsDialog({</Dialog>)}++function SettingsDirectoryPicker({+ inputProps,+ ...props+}: Omit<ComponentProps<typeof DirectoryPicker>, 'name'>) {+ const { formItemId, formMessageId, formDescriptionId, error } = useFormField()+ return (+ <DirectoryPicker+ {...props}+ name="app.defaultSaveDir"+ inputProps={{+ ...inputProps,+ id: formItemId,+ 'aria-invalid': Boolean(error),+ 'aria-describedby': `${formDescriptionId} ${formMessageId}`,+ }}+ />+ )+}diff --git a/src/renderer/routes/settings/cards/downloads-form.ts b/src/renderer/routes/settings/cards/downloads-form.tsindex 3ef36326..a435e5b1 100644--- a/src/renderer/routes/settings/cards/downloads-form.ts+++ b/src/renderer/routes/settings/cards/downloads-form.ts@@ -1,42 +1,21 @@import { settingsValidationError } from '@renderer/lib/settings-validation'import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas'-import {- appSettingsInputSchema,- DEFAULT_APP_SETTINGS,-} from '@shared/schemas/app-settings'-import { engineSettingsInputSchema } from '@shared/schemas/engine-settings'-import {- DEFAULT_SPEED_LIMIT_SETTINGS,- speedLimitSettingsInputSchema,-} from '@shared/schemas/speed-limit'+import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'+import { downloadsSettingsSchema } from '@shared/schemas/downloads-settings'+import { DEFAULT_SPEED_LIMIT_SETTINGS } from '@shared/schemas/speed-limit'import type { TFunction } from 'i18next'import { z } from 'zod'// ─── Form shape ────────────────────────────────────────────────────────────────// On submit, pickDirty returns only changed keys across app, engine, and-// speedLimit. UpdateSettings deep-merges each top-level namespace.+// speedLimit. SaveDownloadsSettings commits these with directory edits.-export const downloadsFormSchema = z.object({- app: appSettingsInputSchema.pick({ fileDeletionMode: true }),- engine: engineSettingsInputSchema.pick({- performanceProfile: true,- maxConcurrentDownloads: true,- maxConnectionPerServer: true,- split: true,- minSplitSize: true,- userAgent: true,- connectTimeout: true,- socketTimeout: true,- maxTries: true,- retryWait: true,- lowestSpeedLimit: true,- fileAllocation: true,- remoteTime: true,- diskCache: true,- sessionSaveInterval: true,- magnetResolveTimeout: true,+export const downloadsFormSchema = downloadsSettingsSchema.extend({+ app: downloadsSettingsSchema.shape.app.extend({+ defaultSaveDir: z.string().refine((value) => value.trim().length > 0, {+ message: 'settings.validation.directory',+ }),}),- speedLimit: speedLimitSettingsInputSchema,})export type DownloadsFields = z.infer<typeof downloadsFormSchema>@@ -69,12 +48,14 @@ export const ENGINE_DEFAULTS: EngineFields = {fileAllocation: DEFAULT_ENGINE_SETTINGS.fileAllocation,remoteTime: DEFAULT_ENGINE_SETTINGS.remoteTime,diskCache: DEFAULT_ENGINE_SETTINGS.diskCache,- sessionSaveInterval: DEFAULT_ENGINE_SETTINGS.sessionSaveInterval,- magnetResolveTimeout: DEFAULT_ENGINE_SETTINGS.magnetResolveTimeout,}export const DOWNLOADS_DEFAULTS: DownloadsFields = {- app: { fileDeletionMode: DEFAULT_APP_SETTINGS.fileDeletionMode },+ app: {+ defaultSaveDir: DEFAULT_APP_SETTINGS.defaultSaveDir,+ autofillClipboardLinks: DEFAULT_APP_SETTINGS.autofillClipboardLinks,+ fileDeletionMode: DEFAULT_APP_SETTINGS.fileDeletionMode,+ },engine: ENGINE_DEFAULTS,// Source of truth: src/shared/schemas/speed-limit.ts (DEFAULT_SPEED_LIMIT_SETTINGS).speedLimit: DEFAULT_SPEED_LIMIT_SETTINGS,diff --git a/src/renderer/routes/settings/cards/engine-tuning-section.tsx b/src/renderer/routes/settings/cards/engine-tuning-section.tsxindex bed15aac..7a7d5543 100644--- a/src/renderer/routes/settings/cards/engine-tuning-section.tsx+++ b/src/renderer/routes/settings/cards/engine-tuning-section.tsx@@ -88,32 +88,7 @@ export function EngineTuningSection({<h3 className="text-sm font-semibold text-foreground">{t('settings.downloads.reliability.title')}</h3>- <FormField- control={form.control}- name="engine.userAgent"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="flex items-start justify-between gap-4">- <div className="space-y-1">- <FormLabel>- {t('settings.downloads.reliability.userAgent')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.downloads.reliability.userAgentDesc')}- </FormDescription>- </div>- <FormControl>- <Input {...field} className="w-64 h-8" />- </FormControl>- </div>- <FormMessage className="text-xs" />- <PresetChips- name="engine.userAgent"- options={BUILTIN_USER_AGENTS as never}- />- </FormItem>- )}- />+{numericRow('connectTimeout','settings.downloads.reliability.connectTimeout',@@ -278,22 +253,42 @@ export function EngineTuningSection({</SettingsFormRow>)}/>- {numericRow(- 'sessionSaveInterval',- 'settings.downloads.disk.sessionSaveInterval',- 'settings.downloads.disk.sessionSaveIntervalDesc'- )}-- <Separator className="my-4" />+ </>+ )+}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.downloads.magnet.title')}- </h3>- {numericRow(- 'magnetResolveTimeout',- 'settings.downloads.magnet.magnetResolveTimeout',- 'settings.downloads.magnet.magnetResolveTimeoutDesc'+export function UserAgentSection({+ form,+}: {+ form: UseFormReturn<DownloadsFields>+}) {+ const { t } = useTranslation()+ return (+ <FormField+ control={form.control}+ name="engine.userAgent"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.downloads.reliability.userAgent')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.downloads.reliability.userAgentDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Input {...field} className="w-64 h-8" />+ </FormControl>+ </div>+ <FormMessage className="text-xs" />+ <PresetChips+ name="engine.userAgent"+ options={BUILTIN_USER_AGENTS as never}+ />+ </FormItem>)}- </>+ />)}diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsxindex ac29a55b..48a67bfb 100644--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx@@ -1,240 +1,143 @@import '@test-utils/dom-animations'-import type { SaveGeneralSettingsRequest } from '@shared/schemas/general-settings'+import '@testing-library/jest-dom/vitest'+import '@renderer/lib/i18n'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'import {generalSettingsSnapshot,TEST_GENERAL_REVISION,} from '@test-utils/general-settings'-import '@renderer/lib/i18n'-import '@testing-library/jest-dom/vitest'-import { Commands } from '@shared/protocol/commands'-import { Queries } from '@shared/protocol/queries'-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'--// Hoisted alongside vi.mock so the factory can reference it without TDZ.-const transportMock = vi.hoisted(() => ({- invoke: vi.fn(async () => undefined),- on: vi.fn(),- off: vi.fn(),- platform: 'darwin' as NodeJS.Platform | 'web',- pickSaveDir: vi.fn(),-}))+import { GeneralDialog } from './general-dialog'vi.mock('@renderer/lib/transport', () => ({- transport: transportMock,-}))--const pickSaveDir = transportMock.pickSaveDir-vi.mock('@renderer/platform/services', () => ({- usePlatformServices: () => ({ pickSaveDir: transportMock.pickSaveDir }),+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'darwin' },}))--import { transport } from '@renderer/lib/transport'-import { GeneralDialog } from './general-dialog'--class MockResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--const SETTINGS_FIXTURE = {- app: {- launchAtStartup: false,- showMainWindowAtLogin: false,- defaultSaveDir: '/Users/me/Downloads',- notifyOnComplete: true,- notifyOnError: true,- warnBeforeQuit: true,- autofillClipboardLinks: true,- protocols: { magnet: true },- runMode: 1, // RunMode.Standard — numeric enum- theme: 'system',- language: 'en-US',- traySpeedometer: false,- magnetFileSelection: true,- },-}--const generalResult = (- preferences = { favorites: [] as string[], recent: [] as string[] },- app = SETTINGS_FIXTURE.app-) => ({ ok: true, value: generalSettingsSnapshot(preferences, app) })-+let snapshot = generalSettingsSnapshot()beforeEach(() => {- vi.stubGlobal('ResizeObserver', MockResizeObserver)- transportMock.platform = 'darwin'- transportMock.pickSaveDir.mockReset().mockResolvedValue(null)- vi.mocked(transport.invoke).mockReset()- vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {- if (channel === Queries.GetGeneralSettingsDraft) return generalResult()- return generalResult()- })+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ transport.platform = 'darwin'+ snapshot = generalSettingsSnapshot()+ vi.mocked(transport.invoke)+ .mockReset()+ .mockImplementation(async () => ({ ok: true, value: snapshot }))})--describe('<GeneralDialog>', () => {- it('keeps failed initial settings controls disabled and focuses a stable element before Retry', async () => {- let attempts = 0- let release!: (value: unknown) => void- vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel !== Queries.GetGeneralSettingsDraft) return generalResult()- if (++attempts === 1) throw new Error('offline')- return new Promise((resolve) => {- release = resolve- })- })- render(- <GeneralDialog- open- onClose={vi.fn()}- labelKey="settings.cards.general.title"- descKey="settings.cards.general.desc"- />- )- await screen.findByRole('alert')- const toggle = screen.getByRole('switch', { name: /notify on failure/i })- const original = toggle.getAttribute('aria-checked')- await userEvent.click(toggle)- expect(toggle).toHaveAttribute('aria-checked', original)- const retry = screen.getByRole('button', { name: 'Retry' })- retry.focus()- await userEvent.click(retry)- expect(screen.getByRole('dialog')).toContainElement(- document.activeElement as HTMLElement- )- expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()- await act(async () => release(generalResult()))- await screen.findByDisplayValue('/Users/me/Downloads')- })-- it.each(['Cancel', 'Save'])(- 'keeps directory edits and the default Browse selection in the same %s session',- async (action) => {- const preferences = { favorites: ['/saved '], recent: ['/recent'] }- vi.mocked(transport.invoke).mockImplementation(async (channel) =>- channel === Queries.GetGeneralSettingsDraft- ? generalResult(preferences)- : generalResult(preferences)- )- transportMock.pickSaveDir.mockResolvedValue('/new-default')- const onClose = vi.fn()- render(- <GeneralDialog- open- onClose={onClose}- labelKey="settings.cards.general.title"- descKey="settings.cards.general.desc"- />- )- await screen.findByRole('button', { name: 'Remove favorite /saved' })- fireEvent.click(- screen.getByRole('button', { name: 'Remove favorite /saved' })- )- await userEvent.click(- screen.getByRole('switch', { name: /notify on failure/i })+async function openGeneral(close = vi.fn()) {+ render(+ <GeneralDialog+ open+ onClose={close}+ labelKey="settings.cards.general.title"+ descKey="settings.cards.general.desc"+ />+ )+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()+ )+ return close+}+const saves = () =>+ vi+ .mocked(transport.invoke)+ .mock.calls.filter(([channel]) => channel === Commands.SaveGeneralSettings)++describe('General settings', () => {+ it.each([+ ['Off', false, false],+ ['System notifications', true, false],+ ['In-app notifications', false, true],+ ['Both', true, true],+ ] as const)(+ 'maps %s to independent system and in-app preferences',+ async (label, system, inside) => {+ snapshot.app.notifyOnComplete = false+ snapshot.app.notifyInAppOnComplete = false+ await openGeneral()+ const user = userEvent.setup()+ await user.click(+ screen.getByRole('combobox', { name: 'Download completed' }))- await userEvent.click(screen.getByRole('button', { name: 'Browse…' }))- await screen.findByDisplayValue('/new-default')+ await user.click(await screen.findByRole('option', { name: label }))+ expect(saves()).toHaveLength(0)+ await user.click(screen.getByRole('button', { name: 'Save' }))+ const patch = saves()[0]?.[1] as { app: Record<string, boolean> }+ expect({ ...snapshot.app, ...patch.app }).toMatchObject({+ notifyOnComplete: system,+ notifyInAppOnComplete: inside,+ })expect(- vi- .mocked(transport.invoke)- .mock.calls.every(- ([channel]) => channel === Queries.GetGeneralSettingsDraft- )- ).toBe(true)- await userEvent.click(screen.getByRole('button', { name: action }))- await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))- if (action === 'Save') {- expect(transport.invoke).toHaveBeenCalledWith(- Commands.SaveGeneralSettings,- {- expectedRevision: TEST_GENERAL_REVISION,- app: { defaultSaveDir: '/new-default', notifyOnError: false },- directories: {- addFavorites: [],- removeFavorites: ['/saved '],- removeRecent: [],- },- }+ Object.keys(patch.app).every((key) =>+ ['notifyOnComplete', 'notifyInAppOnComplete'].includes(key))- } else {- expect(vi.mocked(transport.invoke).mock.calls).toHaveLength(1)- }+ ).toBe(true)})-- it('locks Save, Cancel and Escape while default-directory Browse is pending', async () => {- let release!: (path: string | null) => void- transportMock.pickSaveDir.mockImplementation(- () =>- new Promise((resolve) => {- release = resolve- })- )- const onClose = vi.fn()- render(- <GeneralDialog- open- onClose={onClose}- labelKey="settings.cards.general.title"- descKey="settings.cards.general.desc"- />- )- await screen.findByDisplayValue('/Users/me/Downloads')- await userEvent.click(screen.getByRole('button', { name: 'Browse…' }))- expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()- expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })- expect(onClose).not.toHaveBeenCalled()- await act(async () => release(null))- await waitFor(() =>- expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled()- )- await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))- expect(onClose).toHaveBeenCalledTimes(1)+ it('discards notification and badge edits on Cancel', async () => {+ const close = await openGeneral()+ const user = userEvent.setup()+ await user.click(screen.getByRole('combobox', { name: 'Download failed' }))+ await user.click(await screen.findByRole('option', { name: 'Off' }))+ await user.click(screen.getByRole('combobox', { name: 'Unread badge' }))+ await user.click(await screen.findByRole('option', { name: 'Hidden' }))+ await user.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(saves()).toHaveLength(0)+ expect(close).toHaveBeenCalledOnce()})-- it('retains dirty app fields and directory rows after an atomic Save failure', async () => {- vi.mocked(transport.invoke).mockImplementation(async (channel) => {- if (channel === Queries.GetGeneralSettingsDraft)- return generalResult({ favorites: ['/saved'], recent: [] })- return { ok: false, error: { code: 'permissionDenied' } }- })- const onClose = vi.fn()- render(- <GeneralDialog- open- onClose={onClose}- labelKey="settings.cards.general.title"- descKey="settings.cards.general.desc"- />- )- await screen.findByRole('button', { name: 'Remove favorite /saved' })- fireEvent.click(- screen.getByRole('button', { name: 'Remove favorite /saved' })+ it('saves moved lifecycle fields and startup fields without touching directories', async () => {+ await openGeneral()+ const user = userEvent.setup()+ expect(screen.queryByRole('textbox', { name: /folder/i })).toBeNull()+ expect(+ screen.getByRole('switch', { name: 'Show window at login' })+ ).toHaveAttribute('aria-disabled', 'true')+ await user.click(screen.getByRole('switch', { name: 'Open at login' }))+ await user.click(+ screen.getByRole('switch', { name: 'Show window at login' }))- await userEvent.click(- screen.getByRole('switch', { name: /notify on failure/i })+ await user.click(+ screen.getByRole('switch', {+ name: 'Save memory when the window is closed',+ }))- await userEvent.click(screen.getByRole('button', { name: 'Save' }))- await screen.findByRole('alert')- expect(onClose).not.toHaveBeenCalled()- expect(- screen.getByRole('switch', { name: /notify on failure/i })- ).not.toBeChecked()- expect(screen.queryByTitle('/saved')).toBeNull()- await userEvent.click(screen.getByRole('button', { name: 'Save' }))- expect(- vi- .mocked(transport.invoke)- .mock.calls.filter(- ([channel]) => channel === Commands.SaveGeneralSettings- )- ).toHaveLength(2)+ await user.click(screen.getByRole('button', { name: 'Save' }))+ expect(saves()[0]?.[1]).toEqual({+ expectedRevision: TEST_GENERAL_REVISION,+ app: {+ launchAtStartup: true,+ showMainWindowAtLogin: true,+ lightweightMode: true,+ },+ directories: { addFavorites: [], removeFavorites: [], removeRecent: [] },+ })})-- it('hydrates General fields and directories from one snapshot', async () => {+ it.each(['win32', 'linux'])(+ 'keeps desktop-specific run modes on %s',+ async (platform) => {+ transport.platform = platform as typeof transport.platform+ await openGeneral()+ const user = userEvent.setup()+ await user.click(+ screen.getByRole('combobox', { name: 'When opening Motrix' })+ )+ await user.click(+ await screen.findByRole('option', { name: 'Start in System Tray' })+ )+ await user.click(screen.getByRole('button', { name: 'Save' }))+ expect(saves()[0]?.[1]).toMatchObject({ app: { runMode: 2 } })+ }+ )+ it('keeps unsupported desktop controls out of the Web dialog', async () => {+ transport.platform = 'web'render(<GeneralDialogopen@@ -243,260 +146,57 @@ describe('<GeneralDialog>', () => {descKey="settings.cards.general.desc"/>)- await waitFor(() => {- expect(- screen.getByDisplayValue('/Users/me/Downloads')- ).toBeInTheDocument()- })- })-- it('saves warnBeforeQuit when toggled', async () => {- render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)-- const toggle = await screen.findByRole('switch', {- name: /confirm before quitting/i,- })- await userEvent.click(toggle)- await userEvent.click(screen.getByRole('button', { name: /save/i }))-- await waitFor(() => {- expect(transport.invoke).toHaveBeenCalledWith(- Commands.SaveGeneralSettings,- {- expectedRevision: TEST_GENERAL_REVISION,- app: { warnBeforeQuit: false },- directories: {- addFavorites: [],- removeFavorites: [],- removeRecent: [],- },- }- )- })+ expect(screen.queryByRole('switch')).toBeNull()+ expect(screen.queryByRole('combobox')).toBeNull()+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()})-- it('hides host startup and quit controls in the web client', async () => {- transportMock.platform = 'web'- render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)-- await waitFor(() =>- expect(- screen.getByDisplayValue('/Users/me/Downloads')- ).toBeInTheDocument()- )- expect(- screen.queryByRole('switch', { name: /open at login/i })- ).not.toBeInTheDocument()- expect(- screen.queryByRole('switch', { name: /show window at login/i })- ).not.toBeInTheDocument()+ it('disables writes after a failed load and supports retry', async () => {+ vi.mocked(transport.invoke).mockRejectedValueOnce(new Error('offline'))+ render(<GeneralDialog open onClose={vi.fn()} labelKey="" descKey="" />)+ await screen.findByRole('button', { name: 'Retry' })+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()expect(- screen.queryByRole('switch', { name: /confirm before quitting/i })- ).not.toBeInTheDocument()- })-- it('saves notifyOnError when toggled', async () => {- render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)-- const toggle = await screen.findByRole('switch', {- name: /notify on failure/i,- })- await userEvent.click(toggle)- await userEvent.click(screen.getByRole('button', { name: /save/i }))-- await waitFor(() => {- expect(transport.invoke).toHaveBeenCalledWith(- Commands.SaveGeneralSettings,- {- expectedRevision: TEST_GENERAL_REVISION,- app: { notifyOnError: false },- directories: {- addFavorites: [],- removeFavorites: [],- removeRecent: [],- },- }- )- })- })-- it('saves autofillClipboardLinks when toggled', async () => {- render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)-- const toggle = await screen.findByRole('switch', {- name: /autofill link from clipboard/i,- })- await userEvent.click(toggle)- await userEvent.click(screen.getByRole('button', { name: /save/i }))-- await waitFor(() => {- expect(transport.invoke).toHaveBeenCalledWith(- Commands.SaveGeneralSettings,- {- expectedRevision: TEST_GENERAL_REVISION,- app: { autofillClipboardLinks: false },- directories: {- addFavorites: [],- removeFavorites: [],- removeRecent: [],- },- }- )- })- })-- it('saves only dirty fields', async () => {- const onClose = vi.fn()- render(- <GeneralDialog- open- onClose={onClose}- labelKey="settings.cards.general.title"- descKey="settings.cards.general.desc"- />+ screen.getByRole('switch', { name: 'Open at login' })+ ).toHaveAttribute('aria-disabled', 'true')+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled())- await waitFor(() => screen.getByDisplayValue('/Users/me/Downloads'))- const user = userEvent.setup()- const switches = screen.getAllByRole('switch')- await user.click(switches[0]) // toggle launchAtStartup- await user.click(screen.getByRole('button', { name: /save/i }))expect(transport.invoke).toHaveBeenCalledWith(- Commands.SaveGeneralSettings,- {- expectedRevision: TEST_GENERAL_REVISION,- app: { launchAtStartup: true },- directories: {- addFavorites: [],- removeFavorites: [],- removeRecent: [],- },- }+ Queries.GetGeneralSettingsDraft,+ {})- expect(onClose).toHaveBeenCalled()- })-})--it('enables the login window preference with auto-launch and saves both dirty fields', async () => {- render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)- await waitFor(() => screen.getByDisplayValue('/Users/me/Downloads'))- const toggle = screen.getByRole('switch', {- name: /show window at login/i,- })- expect(toggle).toHaveAttribute('aria-disabled', 'true')- expect(toggle).not.toBeChecked()- await userEvent.click(screen.getByRole('switch', { name: /open at login/i }))- expect(toggle).not.toHaveAttribute('aria-disabled', 'true')- await userEvent.click(toggle)- await userEvent.click(screen.getByRole('button', { name: /save/i }))- expect(transport.invoke).toHaveBeenCalledWith(Commands.SaveGeneralSettings, {- expectedRevision: TEST_GENERAL_REVISION,- app: { launchAtStartup: true, showMainWindowAtLogin: true },- directories: { addFavorites: [], removeFavorites: [], removeRecent: [] },- })-})--it('asks for a download folder and clears the error after browsing', async () => {- vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {- if (channel === Queries.GetGeneralSettingsDraft)- return generalResult(undefined, {- ...SETTINGS_FIXTURE.app,- defaultSaveDir: '',- })- return generalResult()})- pickSaveDir.mockResolvedValue('/Downloads')- const onClose = vi.fn()- render(<GeneralDialog open onClose={onClose} labelKey="" descKey="" />)- const user = userEvent.setup()- await user.click(await screen.findByRole('button', { name: 'Save' }))- expect(await screen.findByText('Choose a download folder.')).toBeVisible()- expect(onClose).not.toHaveBeenCalled()- expect(transport.invoke).not.toHaveBeenCalledWith(- Commands.UpdateSettings,- expect.anything()- )- await user.click(screen.getByRole('button', { name: 'Browse…' }))- await screen.findByDisplayValue('/Downloads')- await user.click(screen.getByRole('button', { name: 'Save' }))- await waitFor(() =>- expect(transport.invoke).toHaveBeenCalledWith(- Commands.SaveGeneralSettings,- {- expectedRevision: TEST_GENERAL_REVISION,- app: { defaultSaveDir: '/Downloads' },- directories: {- addFavorites: [],- removeFavorites: [],- removeRecent: [],- },- }- )- )- expect(onClose).toHaveBeenCalledOnce()-})--it.each([false, true])(- 'saves a boolean restored to its original clean value after a lost committed response (refresh=%s)',- async (refresh) => {- let host = generalSettingsSnapshot(undefined, SETTINGS_FIXTURE.app)- let first = true+ it('preserves intent after an uncertain committed save and reversal', async () => {+ let lost = truevi.mocked(transport.invoke).mockImplementation(async (channel, raw) => {if (channel === Queries.GetGeneralSettingsDraft)- return { ok: true, value: structuredClone(host) }- const request = raw as SaveGeneralSettingsRequest- if (request.expectedRevision !== host.revision)- return {- ok: false,- error: { code: 'conflict' },- snapshot: structuredClone(host),+ return { ok: true, value: snapshot }+ const request = raw as { app: object }+ if (lost) {+ lost = false+ snapshot = {+ ...snapshot,+ app: { ...snapshot.app, ...request.app },+ revision: '00000000-0000-4000-8000-000000000002',}- host = {- ...host,- app: { ...host.app, ...request.app },- revision: '00000000-0000-4000-8000-000000000002',+ throw new Error('reply lost')}- if (first) {- first = false- host.app.autofillClipboardLinks = false // An unrelated client's committed edit.- throw new Error('response lost after commit')- }- return { ok: true, value: structuredClone(host) }+ return { ok: true, value: snapshot }})- const close = vi.fn()- render(<GeneralDialog open onClose={close} labelKey="" descKey="" />)- await screen.findByDisplayValue('/Users/me/Downloads')+ await openGeneral()const user = userEvent.setup()- const notification = screen.getByRole('switch', {- name: /notify on failure/i,- })- await user.click(notification)+ await user.click(+ screen.getByRole('switch', { name: 'Confirm before quitting' })+ )await user.click(screen.getByRole('button', { name: 'Save' }))- await screen.findByRole('alert')- expect(host.app.notifyOnError).toBe(false)- expect(close).not.toHaveBeenCalled()- await user.click(notification) // RHF dirty=false against the original true baseline.- if (refresh) {- await user.click(screen.getByRole('button', { name: 'Retry' }))- await waitFor(() =>- expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()- )- }+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()+ )+ await user.click(+ screen.getByRole('switch', { name: 'Confirm before quitting' })+ )await user.click(screen.getByRole('button', { name: 'Save' }))- await waitFor(() => expect(close).toHaveBeenCalledOnce())- expect(host.app.notifyOnError).toBe(true)- expect(host.app.autofillClipboardLinks).toBe(false)- expect(- screen.getByRole('switch', { name: /autofill link from clipboard/i })- ).not.toBeChecked()- const saves = vi- .mocked(transport.invoke)- .mock.calls.filter(- ([channel]) => channel === Commands.SaveGeneralSettings- )- expect(saves.at(-1)?.[1]).toMatchObject({ app: { notifyOnError: true } })- const finalRequest = saves.at(-1)?.[1] as- | SaveGeneralSettingsRequest- | undefined- expect(finalRequest?.app).toEqual({ notifyOnError: true })- }-)+ expect(saves().at(-1)?.[1]).toMatchObject({ app: { warnBeforeQuit: true } })+ })+})diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsxindex ae99ddb8..f71fa10d 100644--- a/src/renderer/routes/settings/cards/general-dialog.tsx+++ b/src/renderer/routes/settings/cards/general-dialog.tsx@@ -1,5 +1,5 @@-import { DirectoryPicker } from '@renderer/components/desktop-kit/directory-picker'import { SettingsFormRow } from '@renderer/components/settings-kit/settings-form-row'+import { SettingsSelectTrigger } from '@renderer/components/settings-kit/settings-select-trigger'import {useSettingsForm,useSettingsSubmit,@@ -18,10 +18,7 @@ import {FormControl,FormDescription,FormField,- FormItem,FormLabel,- FormMessage,- useFormField,} from '@renderer/components/ui/form'import {ScrollArea,@@ -29,82 +26,197 @@ import {ScrollAreaViewport,ScrollBar,} from '@renderer/components/ui/scroll-area'-import { Switch } from '@renderer/components/ui/switch'import {- DirectoryPreferencesSection,- DirectoryPreferencesStatus,-} from '@renderer/features/directory-preferences/directory-preferences-section'+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectValue,+} from '@renderer/components/ui/select'+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 { pickDirty } from '@renderer/lib/form-utils'import { transport } from '@renderer/lib/transport'+import { RunMode } from '@shared/constants'import { DEFAULT_APP_SETTINGS } from '@shared/schemas'-import type { GeneralSettingsApp } from '@shared/schemas/general-settings'-import { type ComponentProps, useRef, useState } from 'react'+import { GeneralSettingsAppSchema } from '@shared/schemas/general-settings'+import { useRef } from 'react'import { useTranslation } from 'react-i18next'import type { SettingsCardDialogProps } from './card-types'import { generalFormSchema } from './settings-form-schemas'-type GeneralFields = GeneralSettingsApp--// Source of truth: src/shared/schemas/app-settings.ts (DEFAULT_APP_SETTINGS).-// Defaults are sourced from the schema; the renderer mirrors the subset of-// fields it edits. Keep this Pick<> in sync if the schema fields change.-const DEFAULTS: GeneralFields = {- launchAtStartup: DEFAULT_APP_SETTINGS.launchAtStartup,- showMainWindowAtLogin: DEFAULT_APP_SETTINGS.showMainWindowAtLogin,- defaultSaveDir: DEFAULT_APP_SETTINGS.defaultSaveDir,- notifyOnComplete: DEFAULT_APP_SETTINGS.notifyOnComplete,- notifyOnError: DEFAULT_APP_SETTINGS.notifyOnError,- autofillClipboardLinks: DEFAULT_APP_SETTINGS.autofillClipboardLinks,- warnBeforeQuit: DEFAULT_APP_SETTINGS.warnBeforeQuit,-}-export function GeneralDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()const isWeb = transport.platform === 'web'- const form = useSettingsForm<GeneralFields>(generalFormSchema, DEFAULTS)+ const isMac = transport.platform === 'darwin'+ const isLinux = transport.platform === 'linux'+ const form = useSettingsForm(+ generalFormSchema,+ generalFormSchema.parse(DEFAULT_APP_SETTINGS)+ )+ const baseline = useRef(GeneralSettingsAppSchema.parse(DEFAULT_APP_SETTINGS))const directories = useDirectoryPreferencesDraft({getAppDraft: () => ({- values: form.getValues(),+ values: { ...baseline.current, ...form.getValues() },dirty: pickDirty(form.getValues(), form.formState.dirtyFields) ?? {},}),- onAppRebase: (baseline, intent) => {- form.reset(baseline)- for (const key of Object.keys(intent) as (keyof GeneralFields)[]) {- const value = intent[key]- if (value !== undefined)- form.setValue(key, value, { shouldDirty: true })- }+ onAppRebase: (authority, intent) => {+ baseline.current = authority+ form.reset(+ generalFormSchema.parse({+ ...authority,+ runMode:+ !isMac && authority.runMode === RunMode.HideTray+ ? RunMode.Standard+ : authority.runMode,+ })+ )+ const edits = generalFormSchema.partial().parse(intent)+ for (const [key, value] of Object.entries(edits))+ form.setValue(key as keyof typeof edits, value as never, {+ shouldDirty: true,+ })},})- const contentRef = useRef<HTMLDivElement>(null)- const [defaultPicking, setDefaultPicking] = useState(false)- const [favoritePicking, setFavoritePicking] = useState(false)- const busy = directories.saving || defaultPicking || favoritePicking- const fieldsDisabled =- directories.saving || directories.loading || !directories.ready- const close = () => {- if (!busy) onClose()- }-+ const busy = form.formState.isSubmitting || directories.saving+ const disabled = !directories.ready || directories.loading || busyconst onSubmit = useSettingsSubmit(form, async () => {- if (busy || directories.loading || !directories.ready) return- contentRef.current?.focus({ preventScroll: true })+ if (!directories.ready || directories.loading || isWeb) returnif (await directories.save()) onClose()})-+ const close = () => {+ if (!busy) onClose()+ }+ const boolRow = (+ name:+ | 'launchAtStartup'+ | 'showMainWindowAtLogin'+ | 'lightweightMode'+ | 'warnBeforeQuit',+ description?: string,+ dependsOn = true+ ) => (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>{t(`settings.general.${name}`)}</FormLabel>+ {description && (+ <FormDescription className="text-xs">+ {t(description)}+ </FormDescription>+ )}+ </div>+ <FormControl>+ <Switch+ disabled={disabled || !dependsOn}+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ )+ const notificationRow = (+ system: 'notifyOnComplete' | 'notifyOnError',+ inside: 'notifyInAppOnComplete' | 'notifyInAppOnError',+ label: string+ ) => {+ const os = form.watch(system),+ app = form.watch(inside)+ const value = os ? (app ? 'both' : 'system') : app ? 'app' : 'none'+ const options = [+ { value: 'none', label: t('settings.general.notificationOff') },+ { value: 'system', label: t('settings.general.notificationSystem') },+ { value: 'app', label: t('settings.general.notificationInApp') },+ { value: 'both', label: t('settings.general.notificationBoth') },+ ]+ return (+ <FormField+ control={form.control}+ name={system}+ render={() => (+ <SettingsFormRow>+ <FormLabel>{t(label)}</FormLabel>+ <FormControl>+ <Select+ items={options}+ value={value}+ disabled={disabled}+ onValueChange={(v) => {+ if (!v) return+ form.setValue(system, v === 'system' || v === 'both', {+ shouldDirty: true,+ })+ form.setValue(inside, v === 'app' || v === 'both', {+ shouldDirty: true,+ })+ }}+ >+ <SettingsSelectTrigger>+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent position="popper" align="end">+ <SelectGroup>+ {options.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </SettingsFormRow>+ )}+ />+ )+ }+ const runModeOptions = isMac+ ? [+ {+ value: RunMode.Standard,+ label: t('settings.general.runModeStandard'),+ },+ { value: RunMode.TrayOnly, label: t('settings.general.runModeTray') },+ {+ value: RunMode.HideTray,+ label: t('settings.general.runModeHideTray'),+ },+ ]+ : [+ {+ value: RunMode.Standard,+ label: t('settings.appearance.runModeStandardDesktop'),+ },+ {+ value: RunMode.TrayOnly,+ label: t('settings.appearance.runModeTrayDesktop'),+ },+ ]+ const badgeOptions = ['count', 'dot', 'hidden'].map((value) => ({+ value,+ label: t(+ `settings.general.notificationBadge${value[0].toUpperCase()}${value.slice(1)}`+ ),+ }))return (<Dialogopen={open}onOpenChange={(v, details) => {- if (v) return- if (busy) details.cancel()- else close()+ if (!v) {+ if (busy) details.cancel()+ else close()+ }}}><DialogContent@@ -113,12 +225,12 @@ export function GeneralDialog({><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.general.description')}+ </DialogDescription></DialogHeader>-<ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col"><ScrollAreaViewport- ref={contentRef}tabIndex={-1}className="min-h-0 flex-1 overscroll-contain">@@ -130,229 +242,146 @@ export function GeneralDialog({loading={directories.loading}error={directories.error}disabled={busy}- onRetry={() => {- contentRef.current?.focus({ preventScroll: true })- void directories.refresh()- }}+ onRetry={() => void directories.refresh()}/>-- <Form {...form}>- <form noValidate onSubmit={onSubmit}>- <fieldset- className="min-w-0 space-y-4"- disabled={fieldsDisabled}- >- {!isWeb && (- <FormField- control={form.control}- name="launchAtStartup"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.general.launchAtStartup')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.general.launchAtStartupDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- disabled={fieldsDisabled}- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />- )}-- {!isWeb && (+ {isWeb ? (+ <p className="text-sm text-muted-foreground">+ {t('settings.general.desktopOnly')}+ </p>+ ) : (+ <Form {...form}>+ <form noValidate onSubmit={onSubmit}>+ <fieldset+ inert={disabled}+ disabled={disabled}+ className="min-w-0 space-y-4"+ >+ <h3 className="text-sm font-semibold">+ {t('settings.general.startupAndQuitting')}+ </h3>+ {boolRow('launchAtStartup')}+ {boolRow(+ 'showMainWindowAtLogin',+ undefined,+ form.watch('launchAtStartup')+ )}<FormFieldcontrol={form.control}- name="showMainWindowAtLogin"+ name="runMode"render={({ field }) => (<SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.general.showMainWindowAtLogin')}- </FormLabel>- <FormDescription className="text-xs">{t(- 'settings.general.showMainWindowAtLoginDesc',- {- mode: t(- transport.platform === 'darwin'- ? 'settings.appearance.runModeTray'- : 'settings.appearance.runModeTrayDesktop'- ),- }+ isMac+ ? 'settings.general.runMode'+ : 'settings.appearance.runModeLaunch')}- </FormDescription>+ </FormLabel>+ {isLinux && (+ <FormDescription className="text-xs">+ {t('settings.appearance.runModeLinuxDesc')}+ </FormDescription>+ )}</div><FormControl>- <Switch- disabled={- fieldsDisabled ||- !form.watch('launchAtStartup')+ <Select+ items={runModeOptions}+ value={field.value}+ disabled={disabled}+ onValueChange={(v) =>+ v !== null && field.onChange(v)}- checked={field.value}- onCheckedChange={field.onChange}- />+ >+ <SettingsSelectTrigger className="min-w-48">+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent position="popper" align="end">+ <SelectGroup>+ {runModeOptions.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select></FormControl></SettingsFormRow>)}/>- )}-- <FormField- control={form.control}- name="defaultSaveDir"- render={({ field }) => (- <FormItem className="space-y-2">- <div className="space-y-1">- <FormLabel>- {t('settings.general.defaultSaveDir')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.general.defaultSaveDirDesc')}- </FormDescription>- </div>- <SettingsDirectoryPicker- inputProps={{- ref: field.ref,- onBlur: field.onBlur,- }}- recordRecent={false}- allowFavoriteEditing={false}- disabled={directories.saving || favoritePicking}- onPickingChange={setDefaultPicking}- />- <FormMessage className="basis-full text-xs" />- </FormItem>+ {boolRow(+ 'lightweightMode',+ 'settings.general.lightweightModeDesc')}- />-- <div className="space-y-3 border-b pb-4">+ {boolRow(+ 'warnBeforeQuit',+ 'settings.general.warnBeforeQuitDesc'+ )}+ <Separator className="my-4" />+ <h3 className="text-sm font-semibold">+ {t('settings.general.notifications')}+ </h3><p className="text-xs text-muted-foreground">- {t('directoryPreferences.sectionDescription')}+ {t('settings.general.notificationsDesc')}</p>- <DirectoryPreferencesSection- preferences={directories.preferences}- onChange={directories.setPreferences}- disabled={- busy || directories.loading || !directories.ready- }- onPickingChange={setFavoritePicking}- />- </div>-- <FormField- control={form.control}- name="autofillClipboardLinks"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.general.autofillClipboardLinks')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.general.autofillClipboardLinksDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- disabled={fieldsDisabled}- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="notifyOnComplete"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.general.notifyOnComplete')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.general.notifyOnCompleteDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- disabled={fieldsDisabled}- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>+ {notificationRow(+ 'notifyOnComplete',+ 'notifyInAppOnComplete',+ 'settings.general.downloadCompleted')}- />-- <FormField- control={form.control}- name="notifyOnError"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.general.notifyOnError')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.general.notifyOnErrorDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- disabled={fieldsDisabled}- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>+ {notificationRow(+ 'notifyOnError',+ 'notifyInAppOnError',+ 'settings.general.downloadFailed')}- />-- {!isWeb && (<FormFieldcontrol={form.control}- name="warnBeforeQuit"+ name="notificationBadgeStyle"render={({ field }) => (<SettingsFormRow><div className="space-y-1"><FormLabel>- {t('settings.general.warnBeforeQuit')}+ {t('settings.general.notificationBadgeStyle')}</FormLabel><FormDescription className="text-xs">- {t('settings.general.warnBeforeQuitDesc')}+ {t('settings.general.notificationBadgeDesc')}</FormDescription></div><FormControl>- <Switch- disabled={fieldsDisabled}- checked={field.value}- onCheckedChange={field.onChange}- />+ <Select+ items={badgeOptions}+ value={field.value}+ disabled={disabled}+ onValueChange={(v) =>+ v !== null && field.onChange(v)+ }+ >+ <SettingsSelectTrigger>+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent position="popper" align="end">+ <SelectGroup>+ {badgeOptions.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select></FormControl></SettingsFormRow>)}/>- )}- </fieldset>- </form>- </Form>+ </fieldset>+ </form>+ </Form>+ )}</ScrollAreaContent></ScrollAreaViewport><ScrollBar /></ScrollArea>-<DialogFooter className="shrink-0 border-t border-border px-6 py-4">{form.formState.errors.root?.save && (<p role="alert" className="mr-auto text-xs text-destructive">@@ -366,42 +395,20 @@ export function GeneralDialog({disabled={busy}onClick={close}>- {t('common.cancel')}- </Button>- <Button- type="button"- size="sm"- onClick={onSubmit}- disabled={- form.formState.isSubmitting ||- busy ||- directories.loading ||- !directories.ready- }- >- {t('common.save')}+ {t(isWeb ? 'common.close' : 'common.cancel')}</Button>+ {!isWeb && (+ <Button+ type="button"+ size="sm"+ onClick={onSubmit}+ disabled={disabled}+ >+ {t('common.save')}+ </Button>+ )}</DialogFooter></DialogContent></Dialog>)}--function SettingsDirectoryPicker({- inputProps,- ...props-}: Omit<ComponentProps<typeof DirectoryPicker>, 'name'>) {- const { formItemId, formMessageId, formDescriptionId, error } = useFormField()- return (- <DirectoryPicker- {...props}- name="defaultSaveDir"- inputProps={{- ...inputProps,- id: formItemId,- 'aria-invalid': Boolean(error),- 'aria-describedby': `${formDescriptionId} ${formMessageId}`,- }}- />- )-}diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsxindex c85ad789..74ab3021 100644--- a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx@@ -1,3 +1,4 @@+import { DEFAULT_APP_SETTINGS, DEFAULT_MEDIA_SETTINGS } from '@shared/schemas'import '@test-utils/dom-animations'import '@renderer/lib/i18n'import '@testing-library/jest-dom/vitest'@@ -41,6 +42,11 @@ vi.mock('@renderer/lib/transport', () => ({if (channel === 'bridge:getStatus') {return Promise.resolve(bridgeStatus.current)}+ if (channel === 'query:getSettings')+ return Promise.resolve({+ app: DEFAULT_APP_SETTINGS,+ media: DEFAULT_MEDIA_SETTINGS,+ })if (channel === 'query:getFfmpegDetection') {return Promise.resolve({ active: null, candidates: [] })}@@ -126,7 +132,7 @@ describe('IntegrationDialog scaffold', () => {/>)expect(- await screen.findByRole('heading', { name: /system protocols/i })+ await screen.findByRole('heading', { name: /default app/i })).toBeTruthy()expect(screen.getByRole('heading', { name: /browser extensions/i })@@ -149,7 +155,7 @@ describe('IntegrationDialog scaffold', () => {)expect(- screen.queryByRole('heading', { name: /system protocols/i })+ screen.queryByRole('heading', { name: /default app/i })).not.toBeInTheDocument()expect(await screen.findByRole('heading', { name: /browser extensions/i })@@ -173,7 +179,9 @@ describe('IntegrationDialog scaffold', () => {expect(local.compareDocumentPosition(remote) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()- expect(screen.getByText(/local CLI connects automatically/i)).toBeTruthy()+ expect(+ screen.getByText(/Run motrix in a terminal to control this app/i)+ ).toBeTruthy()})it('renders the complete manual-only unsupported CLI recovery state', async () => {@@ -291,6 +299,11 @@ describe('IntegrationDialog scaffold', () => {if (channel === 'bridge:getStatus') {return bridgeStatus.current}+ if (channel === 'query:getSettings')+ return Promise.resolve({+ app: DEFAULT_APP_SETTINGS,+ media: DEFAULT_MEDIA_SETTINGS,+ })if (channel === 'query:getFfmpegDetection') {return { active: null, candidates: [] }}diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsxindex 5239115a..7ba81626 100644--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx@@ -3,6 +3,10 @@ import {useSettingsForm,useSettingsSubmit,} from '@renderer/components/settings-kit/use-settings-form'+import {+ SettingsLoadStatus,+ useSettingsLoad,+} from '@renderer/components/settings-kit/use-settings-load'import { Alert, AlertDescription } from '@renderer/components/ui/alert'import { Button } from '@renderer/components/ui/button'import {@@ -24,10 +28,9 @@ import { toast } from '@renderer/components/ui/toast'import { pickDirty } from '@renderer/lib/form-utils'import { saveSettings } from '@renderer/lib/settings-save'import { transport } from '@renderer/lib/transport'-import { Queries } from '@shared/protocol/queries'import { DEFAULT_APP_SETTINGS, DEFAULT_MEDIA_SETTINGS } from '@shared/schemas'import type { AppSettings } from '@shared/types/settings'-import { useEffect, useState } from 'react'+import { useState } from 'react'import { FormProvider } from 'react-hook-form'import { useTranslation } from 'react-i18next'import type { z } from 'zod'@@ -56,7 +59,6 @@ export function IntegrationDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()const isWeb = transport.platform === 'web'@@ -67,32 +69,21 @@ export function IntegrationDialog({DEFAULTS)- // biome-ignore lint/correctness/useExhaustiveDependencies: mount-only fetch- useEffect(() => {- if (!open) return- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings- if (all?.app && all?.media) {- form.reset({- app: {- browserBridgeEnabled: all.app.browserBridgeEnabled,- protocols: all.app.protocols,- },- media: { ...all.media },- })- }+ const load = useSettingsLoad((all) => {+ if (!all?.app || !all.media) throw new Error('Missing settings baseline')+ if (all?.app && all?.media) {+ form.reset({+ app: {+ browserBridgeEnabled: all.app.browserBridgeEnabled,+ protocols: all.app.protocols,+ },+ media: { ...all.media },})- .catch(() => {})- return () => {- cancelled = true}- }, [open])+ })const onSubmit = useSettingsSubmit(form, async (values) => {+ if (!load.ready) returnsetSaveError(null)const dirty = pickDirty(values, form.formState.dirtyFields) as| Partial<{@@ -128,14 +119,24 @@ export function IntegrationDialog({})return (- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog+ open={open}+ onOpenChange={(v, details) => {+ if (!v) {+ if (form.formState.isSubmitting) details.cancel()+ else onClose()+ }+ }}+ ><DialogContentclassName="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"initialFocus={false}><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.integration.description')}+ </DialogDescription></DialogHeader><ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -147,8 +148,29 @@ export function IntegrationDialog({className="px-6 py-4"style={{ minWidth: '100%' }}>+ <SettingsLoadStatus {...load} /><FormProvider {...form}>- <div className="flex flex-col gap-6">+ <fieldset+ inert={!load.ready || form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}+ className="min-w-0 flex flex-col gap-6"+ >+ <section+ aria-labelledby="integration-browser"+ className="flex flex-col gap-3"+ >+ <h3+ id="integration-browser"+ className="text-sm font-semibold text-foreground"+ >+ {t('settings.integration.browser.title')}+ </h3>+ <BrowserExtensionsSection />+ {!isWeb && <AppImageNativeHostSection />}+ </section>++ <Separator />+{!isWeb && (<><section@@ -175,22 +197,6 @@ export function IntegrationDialog({</>)}- <section- aria-labelledby="integration-browser"- className="flex flex-col gap-3"- >- <h3- id="integration-browser"- className="text-sm font-semibold text-foreground"- >- {t('settings.integration.browser.title')}- </h3>- <BrowserExtensionsSection />- {!isWeb && <AppImageNativeHostSection />}- </section>-- <Separator />-<sectionaria-labelledby="integration-cli"className="flex flex-col gap-4"@@ -221,7 +227,7 @@ export function IntegrationDialog({</h3><MediaToolsSection /></section>- </div>+ </fieldset></FormProvider></ScrollAreaContent></ScrollAreaViewport>@@ -240,14 +246,20 @@ export function IntegrationDialog({<AlertDescription>{saveError}</AlertDescription></Alert>)}- <Button type="button" variant="outline" size="sm" onClick={onClose}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={form.formState.isSubmitting}+ onClick={onClose}+ >{t('common.cancel')}</Button><Buttontype="button"size="sm"onClick={onSubmit}- disabled={form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}>{t('common.save')}</Button>diff --git a/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx b/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsxindex 5a5fb07e..1191ee85 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@@ -96,9 +96,7 @@ describe('<SystemProtocolsSection>', () => {screen.getByText('Default app for torrents and magnet links')).toBeInTheDocument()expect(- screen.getByText(- /Motrix appears there after installation with Motrix Setup/u- )+ screen.getByText(/Requires an installed copy of Motrix/u)).toBeInTheDocument()expect(await screen.findByText('Default')).toBeInTheDocument()expect(screen.getByText('Not default')).toBeInTheDocument()diff --git a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsxindex 568c0888..c810778d 100644--- a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx+++ b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx@@ -504,7 +504,7 @@ describe('usePairRequestPrompts', () => {expect(toastAddMock).toHaveBeenCalledWith(expect.objectContaining({title:- 'This pairing request is no longer pending — re-run `motrix pair`.',+ 'This pairing request is no longer pending — re-run motrix pair.',})))diff --git a/src/renderer/routes/settings/cards/network-dialog.test.tsx b/src/renderer/routes/settings/cards/network-dialog.test.tsxindex b5fc6a3c..32e6968a 100644--- a/src/renderer/routes/settings/cards/network-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/network-dialog.test.tsx@@ -154,7 +154,7 @@ describe('<NetworkDialog>', () => {const dnsMode = await screen.findByRole('combobox', {name: 'DNS 解析方式',})- expect(dnsMode).toHaveTextContent('引擎内置解析器')+ expect(dnsMode).toHaveTextContent('内置 DNS')expect(dnsMode).toHaveClass('min-w-30', 'max-w-64')expect(dnsMode).not.toHaveClass('w-35')})@@ -263,21 +263,16 @@ describe('<NetworkDialog>', () => {await screen.findByRole('button', { name: /import from system/i }))- await waitFor(() => {- expect(- screen.getByText(- /BT proxy covers HTTP\(S\) only; peers, DHT, and UDP trackers stay direct/i- )- ).toBeInTheDocument()- expect(screen.getAllByRole('switch')[2]).not.toHaveAttribute(- 'aria-disabled',- 'true'- )- expect(screen.getAllByRole('switch')[2]).toHaveAttribute(- 'aria-checked',- 'true'- )- })+ await waitFor(() =>+ expect(screen.getByDisplayValue('127.0.0.1')).toBeInTheDocument()+ )+ await user.click(screen.getByRole('button', { name: 'Use proxy for' }))+ expect(+ await screen.findByRole('menuitemcheckbox', { name: 'File downloads' })+ ).toHaveAttribute('aria-checked', 'true')+ expect(+ screen.getByText('BT peers, DHT and UDP trackers connect directly.')+ ).toBeVisible()})it('shows an actionable error for an enabled proxy without a server', async () => {diff --git a/src/renderer/routes/settings/cards/network-dialog.tsx b/src/renderer/routes/settings/cards/network-dialog.tsxindex 6639bbca..560ef499 100644--- a/src/renderer/routes/settings/cards/network-dialog.tsx+++ b/src/renderer/routes/settings/cards/network-dialog.tsx@@ -5,6 +5,10 @@ import {useSettingsForm,useSettingsSubmit,} from '@renderer/components/settings-kit/use-settings-form'+import {+ SettingsLoadStatus,+ useSettingsLoad,+} from '@renderer/components/settings-kit/use-settings-load'import { Button } from '@renderer/components/ui/button'import {Dialog,@@ -43,7 +47,6 @@ import { Switch } from '@renderer/components/ui/switch'import { pickDirty } from '@renderer/lib/form-utils'import { saveSettings } from '@renderer/lib/settings-save'import { transport } from '@renderer/lib/transport'-import { Queries } from '@shared/protocol/queries'import {DEFAULT_ENGINE_SETTINGS,DEFAULT_NAT_SETTINGS,@@ -54,12 +57,11 @@ import {stunServerInputSchema,} from '@shared/schemas/nat-settings'import type {- AppSettings,DnsResolutionMode,NatSettings,ProxySettings,} from '@shared/types/settings'-import { useEffect } from 'react'+import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import type { SettingsCardDialogProps } from './card-types'import { ProxySection } from './proxy-section'@@ -83,9 +85,9 @@ const DEFAULTS: NetworkFields = {const NAT_PROTOCOL_OPTIONS = [{ label: 'auto', value: 'auto' },- { label: 'pcp', value: 'pcp' },- { label: 'natpmp', value: 'natpmp' },- { label: 'upnp', value: 'upnp' },+ { label: 'PCP', value: 'pcp' },+ { label: 'NAT-PMP', value: 'natpmp' },+ { label: 'UPnP', value: 'upnp' },] as const satisfies ReadonlyArray<{label: stringvalue: NatSettings['preferredProtocol']@@ -95,10 +97,34 @@ export function NetworkDialog({open,onClose,labelKey,- descKey,}: SettingsCardDialogProps) {const { t } = useTranslation()const form = useSettingsForm<NetworkFields>(networkFormSchema, DEFAULTS)+ const diagnosticSwitches = form.watch([+ 'nat.natTypeDetectionEnabled',+ 'nat.portReachabilityCheckEnabled',+ 'nat.autoDiagnostic',+ ])+ const [revealedDiagnosticFields, setRevealedDiagnosticFields] = useState({+ stun: false,+ ports: false,+ interval: false,+ })+ const natErrors = form.formState.errors.nat+ const stunFieldsInvalid = Boolean(natErrors?.stunServers)+ const portFieldsInvalid = Boolean(natErrors?.portCheckerEndpoints)+ const intervalInvalid = Boolean(natErrors?.diagnosticIntervalSec)++ // Keep invalid dependent fields visible while the user corrects them.+ useEffect(() => {+ if (stunFieldsInvalid || portFieldsInvalid || intervalInvalid) {+ setRevealedDiagnosticFields((previous) => ({+ stun: previous.stun || stunFieldsInvalid,+ ports: previous.ports || portFieldsInvalid,+ interval: previous.interval || intervalInvalid,+ }))+ }+ }, [stunFieldsInvalid, portFieldsInvalid, intervalInvalid])const dnsModeOptions = [{ value: 'auto', label: t('settings.network.dns.modeAuto') },@@ -106,33 +132,21 @@ export function NetworkDialog({{ value: 'engine', label: t('settings.network.dns.modeEngine') },] as const- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable- useEffect(() => {- let cancelled = false- transport- .invoke(Queries.GetSettings)- .then((data) => {- if (cancelled) return- const all = data as AppSettings | undefined- if (all?.proxy && all?.nat) {- form.reset({- proxy: all.proxy,- nat: all.nat,- engine: {- dnsMode: all.engine?.dnsMode ?? DEFAULT_ENGINE_SETTINGS.dnsMode,- },- })- }- })- .catch(() => {- /* keep defaults */+ const load = useSettingsLoad((all) => {+ if (!all?.proxy || !all.nat) throw new Error('Missing settings baseline')+ if (all?.proxy && all?.nat) {+ form.reset({+ proxy: all.proxy,+ nat: all.nat,+ engine: {+ dnsMode: all.engine?.dnsMode ?? DEFAULT_ENGINE_SETTINGS.dnsMode,+ },})- return () => {- cancelled = true}- }, [])+ })const onSubmit = useSettingsSubmit(form, async (values) => {+ if (!load.ready) return// biome-ignore lint/suspicious/noExplicitAny: dirtyFields shape doesn't fit DirtyTree; cast is safeconst dirty = pickDirty(values, form.formState.dirtyFields as any)if (!dirty) {@@ -144,14 +158,24 @@ export function NetworkDialog({})return (- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>+ <Dialog+ open={open}+ onOpenChange={(v, details) => {+ if (!v) {+ if (form.formState.isSubmitting) details.cancel()+ else onClose()+ }+ }}+ ><DialogContentclassName="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"initialFocus={false}><DialogHeader className="shrink-0 px-6 pt-6"><DialogTitle>{t(labelKey)}</DialogTitle>- <DialogDescription>{t(descKey)}</DialogDescription>+ <DialogDescription>+ {t('settings.network.description')}+ </DialogDescription></DialogHeader><ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -163,307 +187,369 @@ export function NetworkDialog({className="px-6 py-4"style={{ minWidth: '100%' }}>+ <SettingsLoadStatus {...load} /><Form {...form}>- <form className="space-y-4" noValidate onSubmit={onSubmit}>- <ProxySection form={form} />+ <form noValidate onSubmit={onSubmit}>+ <fieldset+ inert={!load.ready || form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}+ className="min-w-0 space-y-4"+ >+ <ProxySection form={form} />- <Separator className="my-4" />+ <Separator className="my-4" />- {/* DNS resolution */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.network.dns.title')}- </h3>- <FormField- control={form.control}- name="engine.dnsMode"- render={({ field }) => (- <SettingsFormRow className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">- <div className="min-w-0 flex-1 space-y-1">- <FormLabel>- {t('settings.network.dns.mode')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.network.dns.modeDesc')}- </FormDescription>- </div>- <FormControl>- <Select- items={dnsModeOptions}- value={field.value}- onValueChange={(value) => {- if (value !== null) field.onChange(value)- }}- >- <SettingsSelectTrigger>- <SelectValue />- </SettingsSelectTrigger>- <SelectContent>- <SelectGroup>- {dnsModeOptions.map(({ label, value }) => (- <SelectItem key={value} value={value}>- {label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </SettingsFormRow>- )}- />-- <Separator className="my-4" />-- {/* NAT mapping */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.network.nat.title')}- </h3>-- <FormField- control={form.control}- name="nat.enabled"- render={({ field }) => (- <SettingsFormRow>- <div className="space-y-1">- <FormLabel>- {t('settings.network.nat.enable')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.network.nat.enableDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />+ {/* DNS resolution */}+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.network.dns.title')}+ </h3>+ <FormField+ control={form.control}+ name="engine.dnsMode"+ render={({ field }) => (+ <SettingsFormRow className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">+ <div className="min-w-0 flex-1 space-y-1">+ <FormLabel>+ {t('settings.network.dns.mode')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.network.dns.modeDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Select+ items={dnsModeOptions}+ value={field.value}+ onValueChange={(value) => {+ if (value !== null) field.onChange(value)+ }}+ >+ <SettingsSelectTrigger>+ <SelectValue />+ </SettingsSelectTrigger>+ <SelectContent>+ <SelectGroup>+ {dnsModeOptions.map(({ label, value }) => (+ <SelectItem key={value} value={value}>+ {label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </SettingsFormRow>+ )}+ />- <FormField- control={form.control}- name="nat.preferredProtocol"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.network.nat.preferredProtocol')}- </FormLabel>- <FormControl>- <Select- items={NAT_PROTOCOL_OPTIONS}- value={field.value}- onValueChange={(value) => {- if (value !== null) field.onChange(value)- }}- >- <SelectTrigger className="w-30" size="sm">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectGroup>- {NAT_PROTOCOL_OPTIONS.map((option) => (- <SelectItem- key={option.value}- value={option.value}- >- {option.label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="nat.mappingTtl"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.network.nat.mappingTtl')}- </FormLabel>- <FormControl>- <Input- {...field}- type="number"- min={1200}- max={7200}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>- )}- />+ <Separator className="my-4" />- <p className="text-xs text-muted-foreground">- {t('settings.network.nat.btPortHint')}- </p>+ {/* NAT mapping */}+ {transport.platform !== 'web' && (+ <>+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.network.nat.title')}+ </h3>- <Separator className="my-4" />-- {/* NAT type detection (STUN) */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.network.stun.title')}- </h3>- <p className="text-xs text-muted-foreground">- {t('settings.network.stun.privacyHint')}- </p>-- <FormField- control={form.control}- name="nat.natTypeDetectionEnabled"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.network.stun.enable')}- </FormLabel>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />-- <FormField- control={form.control}- name="nat.stunServers"- render={() => (- <FormItem className="space-y-2">- <FormLabel>- {t('settings.network.stun.servers')}- </FormLabel>- <EndpointList- name="nat.stunServers"- maxItems={10}- itemSchema={stunServerInputSchema}- placeholder="stun.example.com:3478"- i18nKeys={{- addButton: 'settings.network.stun.addServer',- empty: 'settings.network.stun.empty',- }}+ <FormField+ control={form.control}+ name="nat.enabled"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.network.nat.enable')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.network.nat.enableDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}/>- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />- <Separator className="my-4" />-- {/* Port reachability */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.network.reachability.title')}- </h3>- <p className="text-xs text-muted-foreground">- {t('settings.network.reachability.privacyHint')}- </p>-- <FormField- control={form.control}- name="nat.portReachabilityCheckEnabled"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.network.reachability.enable')}- </FormLabel>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />+ <FormField+ control={form.control}+ name="nat.preferredProtocol"+ render={({ field }) => (+ <SettingsFormRow>+ <FormLabel>+ {t('settings.network.nat.preferredProtocol')}+ </FormLabel>+ <FormControl>+ <Select+ items={NAT_PROTOCOL_OPTIONS.map((option) => ({+ ...option,+ label:+ option.value === 'auto'+ ? t('settings.network.nat.automatic')+ : option.label,+ }))}+ value={field.value}+ onValueChange={(value) => {+ if (value !== null) field.onChange(value)+ }}+ >+ <SelectTrigger className="w-30" size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {NAT_PROTOCOL_OPTIONS.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ >+ {option.value === 'auto'+ ? t(+ 'settings.network.nat.automatic'+ )+ : option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </SettingsFormRow>+ )}+ />- <FormField- control={form.control}- name="nat.portCheckerEndpoints"- render={() => (- <FormItem className="space-y-2">- <FormLabel>- {t('settings.network.reachability.endpoints')}- </FormLabel>- <EndpointList- name="nat.portCheckerEndpoints"- maxItems={5}- itemSchema={portCheckerInputSchema}- placeholder="https://example.com/check"- i18nKeys={{- addButton:- 'settings.network.reachability.addEndpoint',- empty: 'settings.network.reachability.empty',- }}+ <FormField+ control={form.control}+ name="nat.mappingTtl"+ render={({ field }) => (+ <SettingsFormRow>+ <FormLabel>+ {t('settings.network.nat.mappingTtl')}+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={1200}+ max={7200}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(event.target.valueAsNumber)+ }+ />+ </FormControl>+ </SettingsFormRow>+ )}/>- <FormMessage className="basis-full text-xs" />- </FormItem>- )}- />- <Separator className="my-4" />+ <Separator className="my-4" />- {/* Auto diagnostic */}- <h3 className="text-sm font-semibold text-foreground">- {t('settings.network.diagnostic.title')}- </h3>+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.network.diagnostics')}+ </h3>+ <div className="space-y-4">+ <div className="space-y-3">+ <FormField+ control={form.control}+ name="nat.natTypeDetectionEnabled"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.network.stun.enable')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.network.stun.privacyHint')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <div+ hidden={+ !diagnosticSwitches[0] &&+ !stunFieldsInvalid &&+ !revealedDiagnosticFields.stun+ }+ className="border-l border-border/60 pl-4"+ >+ <FormField+ control={form.control}+ name="nat.stunServers"+ render={() => (+ <FormItem className="space-y-2">+ <FormLabel>+ {t('settings.network.stun.servers')}+ </FormLabel>+ <EndpointList+ name="nat.stunServers"+ maxItems={10}+ itemSchema={stunServerInputSchema}+ placeholder="stun.example.com:3478"+ i18nKeys={{+ addButton:+ 'settings.network.stun.addServer',+ empty: 'settings.network.stun.empty',+ }}+ />+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />+ </div>+ </div>- <FormField- control={form.control}- name="nat.autoDiagnostic"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.network.diagnostic.enable')}- </FormLabel>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />+ <div className="space-y-3">+ <FormField+ control={form.control}+ name="nat.portReachabilityCheckEnabled"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t(+ 'settings.network.reachability.enable'+ )}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.network.reachability.privacyHint'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <div+ hidden={+ !diagnosticSwitches[1] &&+ !portFieldsInvalid &&+ !revealedDiagnosticFields.ports+ }+ className="border-l border-border/60 pl-4"+ >+ <FormField+ control={form.control}+ name="nat.portCheckerEndpoints"+ render={() => (+ <FormItem className="space-y-2">+ <FormLabel>+ {t(+ 'settings.network.reachability.endpoints'+ )}+ </FormLabel>+ <EndpointList+ name="nat.portCheckerEndpoints"+ maxItems={5}+ itemSchema={portCheckerInputSchema}+ placeholder="https://example.com/check"+ i18nKeys={{+ addButton:+ 'settings.network.reachability.addEndpoint',+ empty:+ 'settings.network.reachability.empty',+ }}+ />+ <FormMessage className="basis-full text-xs" />+ </FormItem>+ )}+ />+ </div>+ </div>++ <Separator />- <FormField- control={form.control}- name="nat.diagnosticIntervalSec"- render={({ field }) => (- <SettingsFormRow>- <FormLabel>- {t('settings.network.diagnostic.interval')}- </FormLabel>- <FormControl>- <Input- {...field}- type="number"- min={300}- max={86400}- className="w-30 h-8"- value={- Number.isFinite(field.value) ? field.value : ''- }- onChange={(event) =>- field.onChange(event.target.valueAsNumber)- }- />- </FormControl>- </SettingsFormRow>+ <div className="space-y-3">+ <FormField+ control={form.control}+ name="nat.autoDiagnostic"+ render={({ field }) => (+ <SettingsFormRow>+ <div className="space-y-1">+ <FormLabel>+ {t('settings.network.diagnostic.enable')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t(+ 'settings.network.diagnostic.enableDesc'+ )}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ <div+ hidden={+ !diagnosticSwitches[2] &&+ !intervalInvalid &&+ !revealedDiagnosticFields.interval+ }+ className="border-l border-border/60 pl-4"+ >+ <FormField+ control={form.control}+ name="nat.diagnosticIntervalSec"+ render={({ field }) => (+ <SettingsFormRow>+ <FormLabel>+ {t(+ 'settings.network.diagnostic.interval'+ )}+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ type="number"+ min={300}+ max={86400}+ className="w-30 h-8"+ value={+ Number.isFinite(field.value)+ ? field.value+ : ''+ }+ onChange={(event) =>+ field.onChange(+ event.target.valueAsNumber+ )+ }+ />+ </FormControl>+ </SettingsFormRow>+ )}+ />+ </div>+ </div>+ </div>+ </>)}- />+ </fieldset></form></Form></ScrollAreaContent>@@ -477,14 +563,20 @@ export function NetworkDialog({{form.formState.errors.root.save.message}</p>)}- <Button type="button" variant="outline" size="sm" onClick={onClose}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={form.formState.isSubmitting}+ onClick={onClose}+ >{t('common.cancel')}</Button><Buttontype="button"size="sm"onClick={onSubmit}- disabled={form.formState.isSubmitting}+ disabled={!load.ready || form.formState.isSubmitting}>{t('common.save')}</Button>diff --git a/src/renderer/routes/settings/cards/proxy-section.tsx b/src/renderer/routes/settings/cards/proxy-section.tsxindex fa97439a..e9bc7aeb 100644--- a/src/renderer/routes/settings/cards/proxy-section.tsx+++ b/src/renderer/routes/settings/cards/proxy-section.tsx@@ -7,9 +7,11 @@ import { SettingsFormRow } from '@renderer/components/settings-kit/settings-formimport { Button } from '@renderer/components/ui/button'import {DropdownMenu,+ DropdownMenuCheckboxItem,DropdownMenuContent,DropdownMenuRadioGroup,DropdownMenuRadioItem,+ DropdownMenuSeparator,DropdownMenuTrigger,} from '@renderer/components/ui/dropdown-menu'import {@@ -40,8 +42,17 @@ import type { UseFormReturn } from 'react-hook-form'import { useTranslation } from 'react-i18next'import type { NetworkFields } from './network-dialog'+type ProxyScope = keyof ProxySettings['scopes']+const PROXY_SCOPES: ProxyScope[] = ['download', 'updateApp', 'updateTrackers']+export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {const { t } = useTranslation()+ const scopes = form.watch('proxy.scopes')+ const scopeLabels: Record<ProxyScope, string> = {+ download: t('settings.network.proxy.scopeDownload'),+ updateApp: t('settings.network.proxy.scopeUpdateApp'),+ updateTrackers: t('settings.network.proxy.scopeUpdateTrackers'),+ }// UI-only state. `showAuth` collapses the user/password rows when the// proxy doesn't need a login (the common case). `revealPassword`@@ -164,9 +175,6 @@ export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {<SettingsFormRow><div className="space-y-1"><FormLabel>{t('settings.network.proxy.enable')}</FormLabel>- <FormDescription className="text-xs">- {t('settings.network.proxy.enableDesc')}- </FormDescription></div><FormControl><Switch checked={field.value} onCheckedChange={field.onChange} />@@ -295,7 +303,11 @@ export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {{t('settings.network.proxy.authDesc')}</p></div>- <Switch checked={showAuth} onCheckedChange={handleAuthToggle} />+ <Switch+ aria-label={t('settings.network.proxy.auth')}+ checked={showAuth}+ onCheckedChange={handleAuthToggle}+ /></div>{(showAuth ||form.formState.errors.proxy?.user ||@@ -360,87 +372,75 @@ export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {)}</div>- {/* Scopes — bg-muted/20 grouped card; each row carries- a description so users understand what the toggle- actually does. */}- <div className="space-y-2">- <div className="space-y-1">- <p className="text-sm font-medium leading-none">- {t('settings.network.proxy.scopes')}- </p>- <p className="text-xs text-muted-foreground">- {t('settings.network.proxy.scopesDesc')}- </p>- </div>- <div className="divide-y divide-border rounded-md border border-border bg-muted/20">- <FormField- control={form.control}- name="proxy.scopes.download"- render={({ field }) => (- <SettingsFormRow className="flex items-center justify-between gap-4 space-y-0 px-3 py-2.5">- <div className="space-y-0.5">- <FormLabel className="font-normal">- {t('settings.network.proxy.scopeDownload')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.network.proxy.scopeDownloadDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="proxy.scopes.updateApp"- render={({ field }) => (- <SettingsFormRow className="flex items-center justify-between gap-4 space-y-0 px-3 py-2.5">- <div className="space-y-0.5">- <FormLabel className="font-normal">- {t('settings.network.proxy.scopeUpdateApp')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.network.proxy.scopeUpdateAppDesc')}- </FormDescription>- </div>- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- </SettingsFormRow>- )}- />- <FormField- control={form.control}- name="proxy.scopes.updateTrackers"- render={({ field }) => (- <SettingsFormRow className="flex items-center justify-between gap-4 space-y-0 px-3 py-2.5">- <div className="space-y-0.5">- <FormLabel className="font-normal">- {t('settings.network.proxy.scopeUpdateTrackers')}- </FormLabel>- <FormDescription className="text-xs">- {t('settings.network.proxy.scopeUpdateTrackersDesc')}- </FormDescription>- </div>+ {/* Keep the selected uses visible; edit them in a persistent checkbox menu. */}+ <FormField+ control={form.control}+ name="proxy.scopes"+ render={({ field }) => {+ const selected = PROXY_SCOPES.filter((scope) => scopes[scope])+ const summary =+ selected.length === 0+ ? t('settings.network.proxy.scopeNone')+ : selected+ .map((scope) => scopeLabels[scope])+ .join(t('settings.network.proxy.scopeSeparator'))+ return (+ <SettingsFormRow>+ <div className="min-w-0 space-y-1">+ <FormLabel>{t('settings.network.proxy.scopes')}</FormLabel>+ <FormDescription className="text-xs">+ {summary}+ </FormDescription>+ </div>+ <DropdownMenu><FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- />+ <DropdownMenuTrigger+ aria-label={t('settings.network.proxy.scopes')}+ ref={field.ref}+ onBlur={field.onBlur}+ render={+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="min-w-30 shrink-0 justify-between gap-2 font-normal"+ />+ }+ >+ {t('settings.network.proxy.scopeChoose')}+ <ChevronDownIcon className="size-4 text-muted-foreground" />+ </DropdownMenuTrigger></FormControl>- </SettingsFormRow>- )}- />- </div>- </div>+ <DropdownMenuContent+ align="end"+ className="w-64 max-w-[calc(100vw-2rem)]"+ >+ {PROXY_SCOPES.map((scope) => (+ <DropdownMenuCheckboxItem+ key={scope}+ checked={scopes[scope]}+ closeOnClick={false}+ onCheckedChange={(checked) =>+ form.setValue(`proxy.scopes.${scope}`, checked, {+ shouldDirty: true,+ shouldValidate: true,+ })+ }+ className="[&>span]:size-4 [&>span]:rounded-[4px] [&>span]:border [&>span]:border-input data-checked:[&>span]:border-primary data-checked:[&>span]:bg-primary data-checked:[&>span]:text-primary-foreground"+ >+ {scopeLabels[scope]}+ </DropdownMenuCheckboxItem>+ ))}+ <DropdownMenuSeparator />+ <p className="px-2 py-1.5 text-xs leading-relaxed text-muted-foreground">+ {t('settings.network.proxy.scopeHint')}+ </p>+ </DropdownMenuContent>+ </DropdownMenu>+ </SettingsFormRow>+ )+ }}+ />{/* Bypass — scope effect inlined in the title row */}<FormField@@ -460,7 +460,7 @@ export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {name={field.name}onBlur={field.onBlur}className="min-h-20 text-xs"- placeholder={'localhost\n127.0.0.1\n*.local'}+ placeholder={t('settings.network.proxy.bypassPlaceholder')}value={(field.value ?? []).join('\n')}onChange={(e) => {const lines = e.target.valuediff --git a/src/renderer/routes/settings/cards/settings-form-schemas.test.ts b/src/renderer/routes/settings/cards/settings-form-schemas.test.tsindex 397a6a50..3e6b5271 100644--- a/src/renderer/routes/settings/cards/settings-form-schemas.test.ts+++ b/src/renderer/routes/settings/cards/settings-form-schemas.test.ts@@ -12,8 +12,10 @@ import {DEFAULT_GEOIP_SETTINGS,geoIpSettingsInputSchema,} from '@shared/schemas/geoip-settings'+import { DEFAULT_SPEED_LIMIT_SETTINGS } from '@shared/schemas/speed-limit'import { describe, expect, it } from 'vitest'import type { z } from 'zod'+import { downloadsFormSchema } from './downloads-form'import {advancedFormSchema,appearanceFormSchema,@@ -24,6 +26,14 @@ import {} from './settings-form-schemas'const forms: Record<string, { schema: z.ZodType; values: object }> = {+ downloads: {+ schema: downloadsFormSchema,+ values: {+ app: { ...DEFAULT_APP_SETTINGS, defaultSaveDir: '/downloads' },+ engine: DEFAULT_ENGINE_SETTINGS,+ speedLimit: DEFAULT_SPEED_LIMIT_SETTINGS,+ },+ },general: {schema: generalFormSchema,values: { ...DEFAULT_APP_SETTINGS, defaultSaveDir: '/Downloads' },@@ -44,6 +54,7 @@ const forms: Record<string, { schema: z.ZodType; values: object }> = {engine: DEFAULT_ENGINE_SETTINGS,app: DEFAULT_APP_SETTINGS,tracker: DEFAULT_TRACKER_SETTINGS,+ geoip: DEFAULT_GEOIP_SETTINGS,},},integration: {@@ -72,11 +83,11 @@ describe('Settings form schemas', () => {)it.each([- ['general', 'defaultSaveDir', ' '],+ ['downloads', 'app.defaultSaveDir', ' '],['general', 'notifyOnComplete', 'yes'],['appearance', 'theme', 'unknown'],['appearance', 'trayIconColor', 'white'],- ['appearance', 'runMode', 999],+ ['general', 'runMode', 999],['advanced', 'rpcPort', 65536],['advanced', 'rpcPort', NaN],['advanced', 'rpcPort', 1234.5],diff --git a/src/renderer/routes/settings/cards/settings-form-schemas.ts b/src/renderer/routes/settings/cards/settings-form-schemas.tsindex 12bcdd47..db53b1cc 100644--- a/src/renderer/routes/settings/cards/settings-form-schemas.ts+++ b/src/renderer/routes/settings/cards/settings-form-schemas.ts@@ -1,5 +1,6 @@import { appSettingsInputSchema } from '@shared/schemas/app-settings'import { engineSettingsInputSchema } from '@shared/schemas/engine-settings'+import { geoIpSettingsInputSchema } from '@shared/schemas/geoip-settings'import { mediaSettingsInputSchema } from '@shared/schemas/media-settings'import { natSettingsInputSchema } from '@shared/schemas/nat-settings'import { proxySettingsInputSchema } from '@shared/schemas/proxy-settings'@@ -9,11 +10,14 @@ import { z } from 'zod'export const generalFormSchema = appSettingsInputSchema.pick({launchAtStartup: true,showMainWindowAtLogin: true,- defaultSaveDir: true,notifyOnComplete: true,notifyOnError: true,- autofillClipboardLinks: true,+ notifyInAppOnComplete: true,+ notifyInAppOnError: true,+ notificationBadgeStyle: true,warnBeforeQuit: true,+ runMode: true,+ lightweightMode: true,})export const appearanceFormSchema = appSettingsInputSchema.pick({@@ -24,12 +28,11 @@ export const appearanceFormSchema = appSettingsInputSchema.pick({byteUnitSystem: true,traySpeedometer: true,trayIconColor: true,- runMode: true,liquidGlassEffect: true,- lightweightMode: true,})export const advancedFormSchema = engineSettingsInputSchema.pick({+ sessionSaveInterval: true,rpcPort: true,rpcSecret: true,sqlite3Persistence: true,@@ -44,7 +47,9 @@ export const networkFormSchema = z.object({})export const bitTorrentFormSchema = z.object({+ geoip: geoIpSettingsInputSchema,engine: engineSettingsInputSchema.pick({+ magnetResolveTimeout: true,listenPort: true,dhtListenPort: true,dhtEnabled: true,diff --git a/src/renderer/routes/settings/cards/speed-limit-section.tsx b/src/renderer/routes/settings/cards/speed-limit-section.tsxindex 99b35f73..7de595c0 100644--- a/src/renderer/routes/settings/cards/speed-limit-section.tsx+++ b/src/renderer/routes/settings/cards/speed-limit-section.tsx@@ -21,7 +21,6 @@ import { useByteFormat } from '@renderer/hooks/use-byte-format'import { transport } from '@renderer/lib/transport'import { Queries } from '@shared/protocol/queries'-import type { SpeedLimitSettings } from '@shared/types/settings'import type { SpeedPoint } from '@shared/types/stats'import { type ComponentProps, forwardRef } from 'react'import type { UseFormReturn } from 'react-hook-form'@@ -35,7 +34,6 @@ const TIME_24_PATTERN = '(?:[01]\\d|2[0-3]):[0-5]\\d'const TURTLE_STATES = ['off', 'on', 'auto'] as constconst WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] as const-type Translate = ReturnType<typeof useTranslation>['t']type KbLimitName =| 'speedLimit.base.download'| 'speedLimit.base.upload'@@ -107,121 +105,10 @@ const Time24Input = forwardRef<HTMLInputElement, Time24InputProps>(})-function minCap(values: number[]): number {- let min = 0- for (const value of values) {- if (value <= 0) continue- if (min === 0 || value < min) min = value- }- return min-}--function crossesMidnight(from: string, to: string): boolean {- return to < from-}--function effectSummary(- settings: SpeedLimitSettings,- t: Translate,- formatSpeed: (value: number) => string-): { primary: string; secondary?: string } {- function formatLimit(value: number, t: Translate): string {- return value <= 0- ? t('settings.downloads.speedLimit.unlimited')- : formatSpeed(value)- }- const regularValues = {- download: formatLimit(settings.base.download, t),- upload: formatLimit(settings.base.upload, t),- }-- if (settings.turtle === 'off') {- return {- primary: t(- 'settings.downloads.speedLimit.effect.standard',- regularValues- ),- }- }-- if (settings.turtle === 'on') {- return {- primary: t('settings.downloads.speedLimit.effect.lowSpeed', {- download: formatLimit(- minCap([settings.base.download, settings.alt.download]),- t- ),- upload: formatLimit(- minCap([settings.base.upload, settings.alt.upload]),- t- ),- }),- }- }-- const rules: string[] = []- if (settings.auto.schedule.enabled) {- rules.push(- t('settings.downloads.speedLimit.effect.scheduleRule', {- from: settings.auto.schedule.from,- to: settings.auto.schedule.to,- nextDay: crossesMidnight(- settings.auto.schedule.from,- settings.auto.schedule.to- )- ? t('settings.downloads.speedLimit.effect.nextDay')- : '',- })- )- }- if (settings.auto.adaptive.enabled) {- const bandwidthReady =- settings.auto.adaptive.linkDown > 0 && settings.auto.adaptive.linkUp > 0- rules.push(- t(- bandwidthReady- ? 'settings.downloads.speedLimit.effect.adaptiveRule'- : 'settings.downloads.speedLimit.effect.adaptiveRulePending',- {- reserved: 100 - settings.auto.adaptive.headroomPercent,- }- )- )- }-- if (rules.length === 0) {- return {- primary: t('settings.downloads.speedLimit.effect.noAutoRules'),- secondary: t(- 'settings.downloads.speedLimit.effect.standardValues',- regularValues- ),- }- }-- return {- primary: t('settings.downloads.speedLimit.effect.autoRules', {- rules: rules.join(- t('settings.downloads.speedLimit.effect.ruleSeparator')- ),- }),- secondary: t('settings.downloads.speedLimit.effect.lowerWins'),- }-}--function SectionIntro({- title,- description,-}: {- title: string- description: string-}) {+function SectionIntro({ title }: { title: string }) {return (<div className="space-y-1">- <h4 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">- {title}- </h4>- <p className="text-xs text-muted-foreground">{description}</p>+ <h4 className="text-xs font-medium text-muted-foreground">{title}</h4></div>)}@@ -231,7 +118,7 @@ export function SpeedLimitSection({}: {form: UseFormReturn<DownloadsFields>}) {- const { formatSpeedLimit, unitSystem } = useByteFormat()+ const { unitSystem } = useByteFormat()const kiloByte = unitSystem === 'binary' ? 1024 : 1000const { t } = useTranslation()@@ -239,12 +126,10 @@ export function SpeedLimitSection({const turtle = settings.turtleconst scheduleEnabled = settings.auto.schedule.enabledconst adaptiveEnabled = settings.auto.adaptive.enabled- const summary = effectSummary(settings, t, formatSpeedLimit)const kbLimitRow = (name: KbLimitName,labelKey: string,- descKey: string,zeroAction: 'unlimited' | 'inherit') => (<FormField@@ -253,8 +138,18 @@ export function SpeedLimitSection({render={({ field }) => (<FormItem className="flex items-start justify-between gap-4"><div className="min-w-0 space-y-1">- <FormLabel>{t(labelKey)}</FormLabel>- <FormDescription className="text-xs">{t(descKey)}</FormDescription>+ <FormLabel>+ {t(labelKey)}+ <span className="sr-only">+ {' '}+ —{' '}+ {t(+ name.includes('.base.')+ ? 'settings.downloads.speedLimit.baseSection'+ : 'settings.downloads.speedLimit.altSection'+ )}+ </span>+ </FormLabel><FormMessage className="text-xs" /></div><FormControl>@@ -285,11 +180,7 @@ export function SpeedLimitSection({/>)- const mbpsLimitRow = (- name: MbpsLimitName,- labelKey: string,- descKey: string- ) => (+ const mbpsLimitRow = (name: MbpsLimitName, labelKey: string) => (<FormFieldcontrol={form.control}name={name}@@ -297,7 +188,6 @@ export function SpeedLimitSection({<FormItem className="flex items-start justify-between gap-4"><div className="min-w-0 space-y-1"><FormLabel>{t(labelKey)}</FormLabel>- <FormDescription className="text-xs">{t(descKey)}</FormDescription><FormMessage className="text-xs" /></div><div className="relative shrink-0">@@ -380,16 +270,8 @@ export function SpeedLimitSection({<h3 className="text-sm font-semibold text-foreground">{t('settings.downloads.speedLimit.title')}</h3>- <p className="text-xs text-muted-foreground">- {t('settings.downloads.speedLimit.titleDesc')}- </p></div>- <SectionIntro- title={t('settings.downloads.speedLimit.modeSection')}- description={t('settings.downloads.speedLimit.modeSectionDesc')}- />-<FormFieldcontrol={form.control}name="speedLimit.turtle"@@ -397,11 +279,6 @@ export function SpeedLimitSection({<SettingsFormRow><div className="min-w-0 space-y-1"><FormLabel>{t('settings.downloads.speedLimit.turtle')}</FormLabel>- <FormDescription className="text-xs">- {t(- `settings.downloads.speedLimit.turtleDesc_${field.value as (typeof TURTLE_STATES)[number]}`- )}- </FormDescription></div><FormControl><ToggleGroup@@ -426,39 +303,29 @@ export function SpeedLimitSection({<Separator className="my-2" />- <SectionIntro- title={t('settings.downloads.speedLimit.baseSection')}- description={t('settings.downloads.speedLimit.baseSectionDesc')}- />+ <SectionIntro title={t('settings.downloads.speedLimit.baseSection')} />{kbLimitRow(- 'speedLimit.base.download',- 'settings.downloads.speedLimit.baseDownload',- 'settings.downloads.speedLimit.baseDownloadDesc',+ 'speedLimit.base.upload',+ 'settings.downloads.speedLimit.baseUpload','unlimited')}{kbLimitRow(- 'speedLimit.base.upload',- 'settings.downloads.speedLimit.baseUpload',- 'settings.downloads.speedLimit.baseUploadDesc',+ 'speedLimit.base.download',+ 'settings.downloads.speedLimit.baseDownload','unlimited')}<Separator className="my-2" />- <SectionIntro- title={t('settings.downloads.speedLimit.altSection')}- description={t('settings.downloads.speedLimit.altSectionDesc')}- />+ <SectionIntro title={t('settings.downloads.speedLimit.altSection')} />{kbLimitRow(- 'speedLimit.alt.download',- 'settings.downloads.speedLimit.altDownload',- 'settings.downloads.speedLimit.altDownloadDesc',+ 'speedLimit.alt.upload',+ 'settings.downloads.speedLimit.altUpload','inherit')}{kbLimitRow(- 'speedLimit.alt.upload',- 'settings.downloads.speedLimit.altUpload',- 'settings.downloads.speedLimit.altUploadDesc',+ 'speedLimit.alt.download',+ 'settings.downloads.speedLimit.altDownload','inherit')}@@ -468,13 +335,8 @@ export function SpeedLimitSection({<SectionIntrotitle={t('settings.downloads.speedLimit.autoSection')}- description={t('settings.downloads.speedLimit.autoSectionDesc')}/>- <h5 className="text-xs font-medium text-foreground">- {t('settings.downloads.speedLimit.autoSchedule')}- </h5>-<FormFieldcontrol={form.control}name="speedLimit.auto.schedule.enabled"@@ -484,9 +346,6 @@ export function SpeedLimitSection({<FormLabel>{t('settings.downloads.speedLimit.scheduleEnabled')}</FormLabel>- <FormDescription className="text-xs">- {t('settings.downloads.speedLimit.scheduleEnabledDesc')}- </FormDescription></div><FormControl><Switch@@ -548,9 +407,6 @@ export function SpeedLimitSection({</SettingsFormRow>)}/>- <span className="text-xs text-muted-foreground">- {t('settings.downloads.speedLimit.scheduleTimeFormat')}- </span></div><FormField@@ -592,7 +448,7 @@ export function SpeedLimitSection({</Toggle>))}</div>- <FormDescription className="text-xs text-muted-foreground">+ <FormDescription className="text-xs">{t('settings.downloads.speedLimit.scheduleDaysHint')}</FormDescription><FormMessage className="basis-full text-xs" />@@ -605,10 +461,6 @@ export function SpeedLimitSection({<Separator className="my-2" />- <h5 className="text-xs font-medium text-foreground">- {t('settings.downloads.speedLimit.autoAdaptive')}- </h5>-<FormFieldcontrol={form.control}name="speedLimit.auto.adaptive.enabled"@@ -636,14 +488,12 @@ export function SpeedLimitSection({form.formState.errors.speedLimit?.auto?.adaptive) && (<>{mbpsLimitRow(- 'speedLimit.auto.adaptive.linkDown',- 'settings.downloads.speedLimit.linkDown',- 'settings.downloads.speedLimit.linkDownDesc'+ 'speedLimit.auto.adaptive.linkUp',+ 'settings.downloads.speedLimit.linkUp')}{mbpsLimitRow(- 'speedLimit.auto.adaptive.linkUp',- 'settings.downloads.speedLimit.linkUp',- 'settings.downloads.speedLimit.linkUpDesc'+ 'speedLimit.auto.adaptive.linkDown',+ 'settings.downloads.speedLimit.linkDown')}<div className="flex items-center gap-2 pl-1">@@ -655,9 +505,6 @@ export function SpeedLimitSection({>{t('settings.downloads.speedLimit.fillFromPeak')}</Button>- <span className="text-xs text-muted-foreground">- {t('settings.downloads.speedLimit.fillFromPeakHint')}- </span></div><FormField@@ -674,11 +521,11 @@ export function SpeedLimitSection({</FormLabel><FormDescription className="text-xs">{t(- 'settings.downloads.speedLimit.headroomPercentDesc',- {- reserved: reservedPercent,- motrix: motrixPercent,- }+ settings.auto.adaptive.linkDown > 0 &&+ settings.auto.adaptive.linkUp > 0+ ? 'settings.downloads.speedLimit.bandwidthUsed'+ : 'settings.downloads.speedLimit.bandwidthPending',+ { motrix: motrixPercent })}</FormDescription><FormMessage className="text-xs" />@@ -719,21 +566,9 @@ export function SpeedLimitSection({</>)}- <div- className="space-y-1 rounded-md border border-border bg-muted/40 px-3 py-2.5"- aria-live="polite"- aria-atomic="true"- >- <p className="text-xs font-medium text-foreground">- {t('settings.downloads.speedLimit.effect.title')}- </p>- <p className="text-xs text-muted-foreground">{summary.primary}</p>- {summary.secondary ? (- <p className="text-[11px] text-muted-foreground/80">- {summary.secondary}- </p>- ) : null}- </div>+ <p className="text-xs text-muted-foreground">+ {t('settings.downloads.speedLimit.effect.lowerWins')}+ </p></>)}diff --git a/src/renderer/routes/settings/cards/use-downloads-settings-draft.test.tsx b/src/renderer/routes/settings/cards/use-downloads-settings-draft.test.tsxnew file mode 100644index 00000000..9cf5d047--- /dev/null+++ b/src/renderer/routes/settings/cards/use-downloads-settings-draft.test.tsx@@ -0,0 +1,110 @@+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import { downloadsSettingsResult } from '@test-utils/downloads-settings'+import { act, renderHook, waitFor } from '@testing-library/react'+import { useForm } from 'react-hook-form'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { DOWNLOADS_DEFAULTS, type DownloadsFields } from './downloads-form'+import { useDownloadsSettingsDraft } from './use-downloads-settings-draft'++vi.mock('@renderer/lib/transport', () => ({+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn() },+}))+vi.mock('@renderer/lib/settings-save', () => ({ notifySettingsSaved: vi.fn() }))+beforeEach(() => vi.mocked(transport.invoke).mockReset())+function openDraft() {+ return renderHook(() => {+ const form = useForm<DownloadsFields>({ defaultValues: DOWNLOADS_DEFAULTS })+ const draft = useDownloadsSettingsDraft(form)+ return { form, draft }+ })+}+describe('Downloads draft rebase', () => {+ it('merges exact nested intent with a newer sibling value and directory history', async () => {+ const base = downloadsSettingsResult()+ const newer = downloadsSettingsResult(+ {+ speedLimit: {+ ...DOWNLOADS_DEFAULTS.speedLimit,+ base: { upload: 700, download: 0 },+ },+ },+ { favorites: [], recent: ['/newer'] }+ )+ newer.value.revision = '00000000-0000-4000-8000-000000000002'+ let saved = 0+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetDownloadsSettingsDraft) return base+ if (++saved === 1)+ return { ok: false, error: { code: 'conflict' }, snapshot: newer.value }+ return newer+ })+ const { result } = openDraft()+ await waitFor(() => expect(result.current.draft.ready).toBe(true))+ act(() =>+ result.current.form.setValue('speedLimit.base.download', 250, {+ shouldDirty: true,+ })+ )+ await act(async () => {+ expect(await result.current.draft.save()).toBe(true)+ })+ const calls = vi+ .mocked(transport.invoke)+ .mock.calls.filter(+ ([channel]) => channel === Commands.SaveDownloadsSettings+ )+ expect(calls).toHaveLength(2)+ expect(calls[1][1]).toEqual({+ expectedRevision: newer.value.revision,+ settings: { speedLimit: { base: { download: 250 } } },+ directories: { addFavorites: [], removeFavorites: [], removeRecent: [] },+ })+ expect(result.current.form.getValues('speedLimit.base.upload')).toBe(700)+ expect(result.current.draft.preferences.recent).toEqual(['/newer'])+ })+ it('keeps an explicit reversal after a committed reply is lost', async () => {+ let authority = downloadsSettingsResult()+ let lost = true+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (channel === Queries.GetDownloadsSettingsDraft) return authority+ if (lost) {+ lost = false+ authority = downloadsSettingsResult({+ speedLimit: {+ ...DOWNLOADS_DEFAULTS.speedLimit,+ base: { upload: 0, download: 250 },+ },+ })+ authority.value.revision = '00000000-0000-4000-8000-000000000002'+ throw Error('lost reply')+ }+ return authority+ })+ const { result } = openDraft()+ await waitFor(() => expect(result.current.draft.ready).toBe(true))+ act(() =>+ result.current.form.setValue('speedLimit.base.download', 250, {+ shouldDirty: true,+ })+ )+ await act(async () => {+ expect(await result.current.draft.save()).toBe(false)+ })+ act(() =>+ result.current.form.setValue('speedLimit.base.download', 0, {+ shouldDirty: true,+ })+ )+ await act(async () => {+ expect(await result.current.draft.save()).toBe(true)+ })+ expect(transport.invoke).toHaveBeenLastCalledWith(+ Commands.SaveDownloadsSettings,+ expect.objectContaining({+ settings: { speedLimit: { base: { download: 0 } } },+ })+ )+ })+})diff --git a/src/renderer/routes/settings/cards/use-downloads-settings-draft.ts b/src/renderer/routes/settings/cards/use-downloads-settings-draft.tsnew file mode 100644index 00000000..053b55c2--- /dev/null+++ b/src/renderer/routes/settings/cards/use-downloads-settings-draft.ts@@ -0,0 +1,87 @@+import {+ requestDirectoryDraft,+ useRevisionedDirectoryDraft,+} from '@renderer/features/directory-preferences/use-directory-preferences-draft'+import { pickDirty } from '@renderer/lib/form-utils'+import { notifySettingsSaved } from '@renderer/lib/settings-save'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ downloadsSettingsResultSchema,+ downloadsSettingsSchema,+} from '@shared/schemas/downloads-settings'+import type { FieldPath, UseFormReturn } from 'react-hook-form'+import type { DownloadsFields } from './downloads-form'++// Leaf paths preserve exact user intent during conflict rebases. Arrays (days,+// process names, providers) are replaced as a whole, just like settings patches.+function flatten(value: object, prefix = ''): Record<string, unknown> {+ const result: Record<string, unknown> = {}+ for (const [key, child] of Object.entries(value)) {+ const path = prefix ? `${prefix}.${key}` : key+ if (child && typeof child === 'object' && !Array.isArray(child))+ Object.assign(result, flatten(child, path))+ else result[path] = child+ }+ return result+}+function expand(values: Record<string, unknown>): Record<string, unknown> {+ const result: Record<string, unknown> = {}+ for (const [path, value] of Object.entries(values)) {+ const keys = path.split('.')+ let target = result+ for (const key of keys.slice(0, -1)) {+ target[key] ??= {}+ target = target[key] as Record<string, unknown>+ }+ target[keys[keys.length - 1]] = value+ }+ return result+}++export function useDownloadsSettingsDraft(+ form: UseFormReturn<DownloadsFields>+) {+ return useRevisionedDirectoryDraft<Record<string, unknown>>({+ getAppDraft: () => ({+ values: flatten(form.getValues()),+ dirty: flatten(+ pickDirty(form.getValues(), form.formState.dirtyFields) ?? {}+ ),+ }),+ onAppRebase: (baseline, intent) => {+ form.reset(downloadsSettingsSchema.parse(expand(baseline)))+ for (const [path, value] of Object.entries(intent))+ form.setValue(path as FieldPath<DownloadsFields>, value as never, {+ shouldDirty: true,+ })+ },+ request: async (channel, args) => {+ const result = await requestDirectoryDraft(+ channel === 'load'+ ? Queries.GetDownloadsSettingsDraft+ : Commands.SaveDownloadsSettings,+ channel === 'load'+ ? {}+ : {+ expectedRevision: args.expectedRevision,+ settings: expand(args.app ?? {}),+ directories: args.directories,+ },+ downloadsSettingsResultSchema+ )+ const adapt = (snapshot: {+ revision: string+ settings: DownloadsFields+ directoryPreferences: { favorites: string[]; recent: string[] }+ }) => ({ ...snapshot, app: flatten(snapshot.settings) })+ return result.ok+ ? { ...result, value: adapt(result.value) }+ : {+ ...result,+ snapshot: result.snapshot ? adapt(result.snapshot) : undefined,+ }+ },+ onSaved: notifySettingsSaved,+ })+}diff --git a/src/server/http/app.ts b/src/server/http/app.tsindex 082fdaf7..6d8c51bf 100644--- a/src/server/http/app.ts+++ b/src/server/http/app.ts@@ -16,6 +16,7 @@ import type {} from '@shared/protocol/handler-types'import { Queries } from '@shared/protocol/queries'import { DirectoryPreferencesResultSchema } from '@shared/schemas/directory-preferences'+import { downloadsSettingsResultSchema } from '@shared/schemas/downloads-settings'import { GeneralSettingsResultSchema } from '@shared/schemas/general-settings'import {CreateServerDirectoryResultSchema,@@ -39,6 +40,8 @@ import {export { RPC_BODY_LIMIT_BYTES } from './torrent-command-routes'const directoryResultSchemas = {+ [Commands.SaveDownloadsSettings]: downloadsSettingsResultSchema,+ [Queries.GetDownloadsSettingsDraft]: downloadsSettingsResultSchema,[Commands.MutateDirectoryPreferences]: DirectoryPreferencesResultSchema,[Commands.SaveGeneralSettings]: GeneralSettingsResultSchema,[Queries.GetGeneralSettingsDraft]: GeneralSettingsResultSchema,@@ -150,7 +153,8 @@ export async function createApp(if (channel === Commands.CreateServerDirectory ||channel === Commands.MutateDirectoryPreferences ||- channel === Commands.SaveGeneralSettings+ channel === Commands.SaveGeneralSettings ||+ channel === Commands.SaveDownloadsSettings) {return directoryRpc(channel, req.body, handler)}@@ -188,6 +192,7 @@ export async function createApp(req.params.channel === Queries.ValidateServerDirectory ||req.params.channel === Queries.GetDirectoryPreferences ||req.params.channel === Queries.GetGeneralSettingsDraft ||+ req.params.channel === Queries.GetDownloadsSettingsDraft ||req.params.channel === Queries.ListServerDirectoryLocations) {return directoryRpc(req.params.channel, req.body, handler)diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 9c82c5ac..5ed01d2e 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -30,6 +30,7 @@ import type { MotrixDatabase } from '@core/session/motrix-database'import type { SessionManager } from '@core/session/session-manager'import { applySavedSettings } from '@core/settings/apply-saved-settings'import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'+import { createSaveDownloadsSettingsHandler } from '@core/settings/downloads-settings'import { createSaveGeneralSettingsHandler } from '@core/settings/general-settings'import type { SettingsManager } from '@core/settings/settings-manager'import {@@ -704,6 +705,32 @@ export function buildServerCommandHandlers([Commands.MutateDirectoryPreferences]: directoryPreferences.mutate,+ [Commands.SaveDownloadsSettings]: createSaveDownloadsSettingsHandler(+ settingsManager,+ {+ resolveFavorite: (value) =>+ ctx.serverDirectoryService.resolvePreferenceDirectory(value),+ resolveDefaultDirectory: async (value) =>+ downloadPathPolicy.prepareSaveDir(+ await ctx.serverDirectoryService.resolvePreferenceDirectory(value)+ ),+ apply: async (oldEngine, result) => {+ await supervisor.applyDefaultSaveDir(+ settingsManager.getApp().defaultSaveDir+ )+ await supervisor.applyEngineSettings(+ oldEngine,+ settingsManager.getEngine()+ )+ if (result.requiresRestart)+ publishEngineRestartRequired(+ { eventBus, notificationCenter, log },+ result.changedRestartKeys ?? []+ )+ },+ }+ ),+[Commands.SaveGeneralSettings]: createSaveGeneralSettingsHandler(settingsManager,{diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.tsindex 3700e841..8d40d7a1 100644--- a/src/server/ipc/queries.ts+++ b/src/server/ipc/queries.ts@@ -21,6 +21,7 @@ import type { RegistryClient } from '@core/plugin/registry/registry-client'import { parseProxyEnvironment } from '@core/proxy/system-proxy'import type { MotrixDatabase } from '@core/session/motrix-database'import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'+import { createGetDownloadsSettingsDraftHandler } from '@core/settings/downloads-settings'import { createGetGeneralSettingsDraftHandler } from '@core/settings/general-settings'import type { SettingsManager } from '@core/settings/settings-manager'import type { SpeedLimitController } from '@core/speed-limit/speed-limit-controller'@@ -250,6 +251,8 @@ export function buildServerQueryHandlers([Queries.GetNatDiagnostic]: async () => null,+ [Queries.GetDownloadsSettingsDraft]:+ createGetDownloadsSettingsDraftHandler(settingsManager),[Queries.GetGeneralSettingsDraft]:createGetGeneralSettingsDraftHandler(settingsManager),[Queries.GetDirectoryPreferences]:diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 0284fc1b..3aa86d23 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1191,6 +1191,15 @@"showMainWindowAtLoginDesc": "Hidden with “{{mode}}”.","defaultSaveDir": "Default download folder","defaultSaveDirDesc": "New downloads land here unless overridden per-task.",+ "inAppNotifications": "In-app notifications",+ "inAppNotificationsDesc": "Choose which download notifications to show. App alerts stay on.",+ "notifyInAppOnComplete": "Show completed downloads",+ "notifyInAppOnError": "Show failed downloads",+ "notificationBadgeStyle": "Unread badge",+ "notificationBadgeCount": "Count",+ "notificationBadgeDot": "Dot",+ "notificationBadgeHidden": "Hidden",+ "systemNotifications": "System notifications","notifyOnComplete": "Notify when download completes","notifyOnCompleteDesc": "Show a system notification when a task finishes.","autofillClipboardLinks": "Autofill link from clipboard",@@ -1198,7 +1207,25 @@"notifyOnError": "Notify on failure","notifyOnErrorDesc": "Show a system notification when a download fails while the window is in the background.","warnBeforeQuit": "Confirm before quitting",- "warnBeforeQuitDesc": "Ask for confirmation when quitting while downloads are still active."+ "warnBeforeQuitDesc": "Ask before quitting if downloads are still running.",+ "notificationBadgeDesc": "Shown on the notification center icon.",+ "notificationOff": "Off",+ "notificationSystem": "System notifications",+ "notificationInApp": "In-app notifications",+ "notificationBoth": "Both",+ "startupAndQuitting": "Startup and quitting",+ "runMode": "Show app in",+ "runModeStandard": "Dock and menu bar",+ "runModeTray": "Menu bar only",+ "runModeHideTray": "Dock only",+ "lightweightMode": "Save memory when the window is closed",+ "lightweightModeDesc": "Downloads continue. Reopening is slower and unsaved input is cleared.",+ "notifications": "Notifications",+ "notificationsDesc": "App error alerts stay on.",+ "downloadCompleted": "Download completed",+ "downloadFailed": "Download failed",+ "description": "Startup, quitting and notifications",+ "desktopOnly": "Startup and notification preferences are available in the desktop app."},"appearance": {"theme": "Theme",@@ -1206,18 +1233,18 @@"themeLight": "Light","themeDark": "Dark","language": "Language",- "traySpeedometer": "Show real-time speed in tray",- "traySpeedometerDesc": "macOS only — display the current speed next to the tray icon.",+ "traySpeedometer": "Show speed in menu bar",+ "traySpeedometerDesc": "See download and upload speeds beside the app icon.","trayIconColor": "Tray icon color",- "trayIconColorDesc": "Your panel may use a different theme from Motrix. Choose a light icon for a dark panel, or a dark icon for a light panel.",+ "trayIconColorDesc": "Choose a color that stands out on your system panel.","trayIconColorAuto": "Follow app theme","trayIconColorLight": "Light icon (dark panel)","trayIconColorDark": "Dark icon (light panel)","reduceMotion": "Reduce motion",- "reduceMotionDesc": "Reduce interface animations, including the glass motion effects on the Downloads page.",- "liquidGlassEffect": "Enable Liquid Glass effect",- "liquidGlassEffectDesc": "Use translucent glass for the Downloads toolbar.",- "liquidGlassEffectMacDesc": "Also uses native window glass on macOS 26+. Changing this recreates the main window.",+ "reduceMotionDesc": "Use fewer animations throughout the app.",+ "liquidGlassEffect": "Liquid Glass",+ "liquidGlassEffectDesc": "Give the download toolbar a translucent glass effect.",+ "liquidGlassEffectMacDesc": "Also applies to the window on macOS 26+. The window reopens when changed.","runMode": "Show app in","runModeStandard": "Dock & Menu Bar","runModeTray": "Menu Bar Only",@@ -1229,11 +1256,11 @@"lightweightMode": "Lightweight mode","lightweightModeDesc": "Save memory when the window is closed. Downloads continue, but reopening takes longer and clears unsaved input.","byteUnitSystem": "Size and speed units",- "byteUnitSystemDesc": "Applies to file sizes and transfer speeds.",+ "byteUnitSystemDesc": "Choose how file sizes and speeds are displayed.","byteUnitDecimal": "Decimal (MB, GB · 1000)","byteUnitBinary": "Binary (MiB, GiB · 1024)","byteUnitSystemDefault": "Follow system ({{units}})",- "sidebarColor": "Color",+ "sidebarColor": "Accent color","sidebarColors": {"blue": "Blue","violet": "Violet",@@ -1244,26 +1271,38 @@"cyan": "Cyan","gray": "Gray","auto": "Auto"- }+ },+ "themeAndEffects": "Theme and effects",+ "languageAndDisplay": "Language and display",+ "menuBar": "Menu bar",+ "description": "Theme, language and display",+ "systemTray": "System tray"},"advanced": {"rpc": {"title": "RPC",- "port": "RPC Port",- "portDesc": "TCP port the aria2 RPC server listens on. Restart required.",- "secret": "RPC Secret",- "secretDesc": "Token clients must send to authenticate. Click Generate for a strong random value."+ "port": "RPC port",+ "portDesc": "Restart required after changing this.",+ "secret": "RPC secret",+ "secretDesc": "Required for RPC connections."},"persistence": {- "title": "SQLite Persistence",- "enable": "Enable SQLite Persistence",- "enableDesc": "Store sessions, progress, and history in a single SQLite database. Disabling reverts to upstream aria2 behavior (text session + .aria2 sidecars).",- "dbPath": "Database Path",- "dbPathDesc": "Leave empty to use the default location next to other engine config files.",- "dbPathPlaceholder": "Default: <config>/aria2.db",- "historyLimit": "History Retention",- "historyLimitDesc": "Maximum rows kept in download history. -1 = unlimited; 0 = memory-only (no DB persistence)."- }+ "title": "Progress and recovery",+ "enable": "Save recovery data",+ "enableDesc": "Keep data used to resume downloads after restarting.",+ "dbPath": "Recovery data file",+ "dbPathDesc": "Leave empty to use the default location.",+ "dbPathPlaceholder": "Default location",+ "historyLimit": "Completed recovery records",+ "historyLimitDesc": "The download list and downloaded files are unaffected.",+ "historyKeepAll": "All records",+ "historyKeepRecent": "Latest records…",+ "historySessionOnly": "Do not retain",+ "historyCount": "Records to keep",+ "historyCountHint": "Older recovery records are removed.",+ "historyCountPositive": "Enter a number greater than 0."+ },+ "description": "RPC, progress and recovery"},"about": {"appIconAlt": "Motrix app icon",@@ -1276,7 +1315,7 @@"idleTitle": "Keep Motrix up to date","idle": "Version {{version}} is installed. Check now, or let Motrix check when it opens.","unsupportedTitle": "Automatic updates unavailable",- "unsupported": "This build of Motrix doesn’t support automatic updates. Download the latest release from the official website.",+ "unsupported": "This version cannot update automatically. Download the latest version from the official website.","check": "Check for updates","checkAction": "Check","checking": "Checking…",@@ -1305,10 +1344,10 @@"automaticChecksDescription": "When Motrix opens","automaticChecksError": "Couldn’t save this setting","channelLabel": "Update channel",- "channelDescription": "Choose which application releases Motrix checks for.",+ "channelDescription": "Choose stable releases or try new features in beta.","channelStable": "Stable","channelBeta": "Beta",- "channelBetaWarning": "Beta releases may be less reliable. You will receive beta and later stable releases. Switching back to Stable stops future betas but never installs an older version automatically.",+ "channelBetaWarning": "Beta may be less stable. You’ll also receive newer stable releases. Switching back stops beta updates without downgrading.","channelSaveError": "Couldn’t save the update channel. Try again."},"details": {@@ -1333,84 +1372,89 @@},"bittorrent": {"trackers": {- "autoSync": "Auto Sync",- "autoSyncDesc": "Automatically sync tracker list on schedule",- "syncInterval": "Sync Interval",- "syncIntervalDesc": "How often to sync trackers (hours, 1–168)",- "enableProbe": "Enable Probe",- "enableProbeDesc": "Test tracker health before adding to torrent",- "probeTimeout": "Probe Timeout",- "probeTimeoutDesc": "Max time to wait for probe response (ms, 1000–30000)",- "healthyThreshold": "Healthy Threshold",- "healthyThresholdDesc": "Max response time to be considered healthy (ms, 500–10000)",- "minSuccessRate": "Min Success Rate",- "minSuccessRateDesc": "Minimum success ratio to keep tracker (0–1)",- "maxTrackerCount": "Max Tracker Count",- "maxTrackerCountDesc": "Maximum trackers to apply per torrent (5–200)",+ "autoSync": "Update tracker list automatically",+ "autoSyncDesc": "Keep the list up to date using your sources.",+ "syncInterval": "Update interval (hours)",+ "syncIntervalDesc": "From 1 to 168 hours.",+ "enableProbe": "Check tracker availability",+ "enableProbeDesc": "Test trackers before using them for downloads.",+ "probeTimeout": "Check timeout (ms)",+ "probeTimeoutDesc": "Wait up to this long for a response. 1,000–30,000 ms.",+ "healthyThreshold": "Slow response threshold (ms)",+ "healthyThresholdDesc": "Longer responses are marked slow. 500–10,000 ms.",+ "minSuccessRate": "Minimum success rate",+ "minSuccessRateDesc": "Use trackers with at least this success rate. 0.5 = 50%.",+ "maxTrackerCount": "Trackers per task",+ "maxTrackerCountDesc": "Use up to this many trackers. 5–200.","title": "Trackers",- "manageSourcesHint": "Manage tracker source list in the Trackers sidebar.",- "blacklistMovedInfo": "Tracker blacklist is now managed in the sidebar Trackers page → Blacklist tab."+ "manageSourcesHint": "Manage sources in the Trackers page.",+ "blacklistMovedInfo": "Manage blocked trackers in Trackers → Blacklist."},"geoip": {- "title": "GeoIP Database",- "enable": "Enable IP-to-country lookup",- "enableDesc": "Resolve peer IP addresses to country codes in the peers tab. The database is downloaded on demand and stored in the user data directory.",+ "title": "Peer locations",+ "enable": "Show country or region",+ "enableDesc": "Show locations in the peer list. Downloads location data when needed.","lastUpdated": "Last updated","neverUpdated": "Never","updateNow": "Update now","updating": "Updating…",- "source": "Source",- "sourceDesc": "Choose where the GeoLite2-Country.mmdb file is downloaded from.",+ "source": "Location data source",+ "sourceDesc": "Choose where to download location data.","source.loyalsoldier": "Loyalsoldier (community)","source.p3terx": "P3TERX (community mirror)","source.maxmind": "MaxMind (official)","source.custom": "Custom URL",- "maxmindUnsupported": "Phase 2.1",- "customUrl": "Custom URL",+ "maxmindUnsupported": "Not supported yet",+ "customUrl": "Custom download URL","customUrlPlaceholder": "https://example.com/GeoLite2-Country.mmdb","autoUpdate": "Update automatically",- "autoUpdateDesc": "Check for a fresh database approximately every week.",- "status.loaded": "Loaded",- "status.notDownloaded": "Database not downloaded",+ "autoUpdateDesc": "Check for new location data about once a week.",+ "status.loaded": "Ready",+ "status.notDownloaded": "Location data not downloaded","status.downloading": "Downloading…",- "status.error": "Update failed"+ "status.error": "Update failed",+ "customUrlDesc": "Link to a country database in .mmdb format.",+ "saveBeforeUpdate": "Save changes before updating location data.",+ "updateFailed": "Couldn’t update location data. Try again."},"listen": {- "title": "Listen",+ "title": "Incoming connections","listenPort": "BT listen port",- "listenPortDesc": "Port aria2 binds for incoming peer connections.",+ "listenPortDesc": "Accept incoming peer connections on this port.","dhtListenPort": "DHT listen port",- "dhtListenPortDesc": "Port aria2 binds for DHT.",+ "dhtListenPortDesc": "Find peers through DHT on this port.","dhtEnabled": "Enable DHT",- "dhtEnabledDesc": "Distributed hash table for trackerless torrents."+ "dhtEnabledDesc": "Find peers without relying on a tracker."},"peers": {"title": "Peers","btMaxPeers": "Max peers per torrent",- "btMaxPeersDesc": "Upper bound on simultaneous peer connections.",+ "btMaxPeersDesc": "The most peers one task can connect to at once.","btEnableLpd": "Local peer discovery",- "btEnableLpdDesc": "Find peers on the local network.",- "magnetFileSelection": "Open file selection after magnet metadata loads",- "magnetFileSelectionDesc": "Show a file picker once magnet metadata arrives.",- "magnetFileSelectionAutoDownload": "Download all files when selection times out",- "magnetFileSelectionAutoDownloadDesc": "If file selection is not confirmed in time, download all files to the task’s save folder, even when the window or WebUI is closed.",- "magnetFileSelectionTimeoutSeconds": "File selection timeout (seconds)",- "magnetFileSelectionTimeoutSecondsDesc": "Count from when metadata is ready. Changing the timeout also applies to tasks already waiting for file selection.",+ "btEnableLpdDesc": "Find peers sharing files on your local network.",+ "magnetFileSelection": "Choose files before downloading",+ "magnetFileSelectionDesc": "Show file selection after a magnet link loads.",+ "magnetFileSelectionAutoDownload": "Download all if no selection is made",+ "magnetFileSelectionAutoDownloadDesc": "Starts after the time below, even if the app window or browser is closed.",+ "magnetFileSelectionTimeoutSeconds": "Time to choose files (s)",+ "magnetFileSelectionTimeoutSecondsDesc": "Starts when the file list is ready. Changes also apply to tasks already waiting.","magnetFileSelectionTimeoutInvalid": "Enter a whole number from {{min}} to {{max}} seconds."},"seeding": {"title": "Seeding",- "seedRatio": "Seed ratio limit",- "seedRatioDesc": "Stop seeding above this ratio. 0 = unlimited.",+ "seedRatio": "Share ratio limit",+ "seedRatioDesc": "Upload ÷ download. Seeding stops at this ratio. 0 = unlimited.","seedTime": "Seed time limit (minutes)",- "seedTimeDesc": "Stop seeding after this many minutes. 0 = unlimited. Applies to new and re-seeded tasks."- }+ "seedTimeDesc": "0 = unlimited. Applies to new tasks and when seeding is restarted."+ },+ "newMagnetTasks": "New magnet tasks",+ "description": "Magnets, seeding and trackers"},"downloads": {"performance": {"title": "Performance",- "profile": "Performance profile",- "profileDesc": "Choose how aggressively Motrix downloads.",+ "profile": "Download performance",+ "profileDesc": "Balance download speed and resource use.","learnMore": "Learn more","metrics": {"connections": "Max connections",@@ -1422,7 +1466,7 @@"profiles": {"auto": {"label": "Automatic",- "desc": "Defaults shown; tuned to your drive and file size."+ "desc": "Adjusts to your drive and file size. Values below are defaults."},"balanced": {"label": "Balanced",@@ -1434,102 +1478,102 @@},"maximum": {"label": "Maximum",- "desc": "Uses maximum parallelism. Some servers may reject it."+ "desc": "Uses more connections. Some servers may limit them."},"custom": {"label": "Custom","desc": "Set connections, segment size, and cache."}},- "maxConcurrentDownloads": "Max concurrent downloads",- "maxConcurrentDownloadsDesc": "Number of tasks downloading in parallel.",+ "maxConcurrentDownloads": "Simultaneous downloads",+ "maxConcurrentDownloadsDesc": "Additional tasks wait in the queue.","maxConnectionPerServer": "Max connections per server","maxConnectionPerServerDesc": "Per-file connection limit for one server.","split": "Max connections per file",- "splitDesc": "Actual connections may be fewer.",+ "splitDesc": "Connections used to download one file.","minSplitSize": "Min segment size (MiB)","minSplitSizeDesc": "Segments below 2× this size won’t split."},"reliability": {- "title": "Network reliability",+ "title": "Connections and retries","userAgent": "User-Agent",- "userAgentDesc": "Sent with HTTP requests.",- "connectTimeout": "Connect timeout (s)",- "connectTimeoutDesc": "How long to wait for a TCP connection.",- "socketTimeout": "Socket timeout (s)",- "socketTimeoutDesc": "How long to wait for socket data.",- "maxTries": "Max retries",- "maxTriesDesc": "0 = no retry.",- "retryWait": "Retry wait (s)",- "retryWaitDesc": "Pause between retries.",- "lowestSpeedLimit": "Slow connection threshold (KiB/s)",- "lowestSpeedLimitDesc": "Drop connections below this speed. 0 = disabled."+ "userAgentDesc": "Identifies the app to websites. Change it if a site requires a different one.",+ "connectTimeout": "Connection timeout (s)",+ "connectTimeoutDesc": "How long to wait for a connection.",+ "socketTimeout": "No-data timeout (s)",+ "socketTimeoutDesc": "How long to wait when no data arrives.",+ "maxTries": "Maximum attempts",+ "maxTriesDesc": "Includes the first attempt. 0 = unlimited.",+ "retryWait": "Retry delay (s)",+ "retryWaitDesc": "Wait this long before trying again.",+ "lowestSpeedLimit": "Minimum connection speed (KiB/s)",+ "lowestSpeedLimitDesc": "Disconnect below this speed. 0 = disabled."},"disk": {- "title": "Disk and session",+ "title": "Disk and files","fileDeletionMode": "When deleting task files","fileDeletionTrash": "Move to trash","fileDeletionPermanent": "Delete permanently",- "fileDeletionTrashDesc": "Applies when removing tasks with their files. Files stay in the trash until it is emptied.",- "fileDeletionPermanentDesc": "Files are deleted directly and cannot be restored from the trash.",- "fileAllocation": "File allocation",- "fileAllocationDesc": "How aria2 reserves disk space for new files.",- "fileAllocationNone": "None",- "fileAllocationPrealloc": "Prealloc",- "fileAllocationTrunc": "Trunc",- "fileAllocationFalloc": "Falloc",+ "fileDeletionTrashDesc": "Space is freed when you empty the trash.",+ "fileDeletionPermanentDesc": "Deleted files cannot be restored from the trash.",+ "fileAllocation": "Reserve disk space",+ "fileAllocationDesc": "Reserve space before downloading a file.",+ "fileAllocationNone": "Do not reserve",+ "fileAllocationPrealloc": "Preallocate",+ "fileAllocationTrunc": "Set file size",+ "fileAllocationFalloc": "System allocation","modifiedTime": "File modification time",- "modifiedTimeDesc": "Choose which modification time completed HTTP and FTP downloads use.",- "modifiedTimeLocal": "Local",- "modifiedTimeServer": "Server",+ "modifiedTimeDesc": "For completed HTTP and FTP downloads.",+ "modifiedTimeLocal": "Download time",+ "modifiedTimeServer": "Time from server","diskCache": "Disk cache (MiB)",- "diskCacheDesc": "In-memory write cache.",- "sessionSaveInterval": "Session save interval (s)",- "sessionSaveIntervalDesc": "How often aria2 persists download state."+ "diskCacheDesc": "Memory used to buffer files before writing to disk.",+ "sessionSaveInterval": "Progress save interval (s)",+ "sessionSaveIntervalDesc": "Save more often to reduce progress lost after a crash."},"magnet": {"title": "Magnet",- "magnetResolveTimeout": "Magnet resolve timeout (s)",- "magnetResolveTimeoutDesc": "How long to wait for metadata before giving up."+ "magnetResolveTimeout": "Magnet loading timeout (s)",+ "magnetResolveTimeoutDesc": "How long to wait for the file list."},"speedLimit": {"title": "Speed limits","titleDesc": "Choose how Motrix uses your connection in Standard, Low speed, and Automatic modes.","modeSection": "Speed mode","modeSectionDesc": "Choose how Motrix should use your connection.",- "turtle": "Current mode",+ "turtle": "Speed mode","turtleDesc_off": "Use the standard speed limits.","turtleDesc_on": "Use the low-speed limits now to leave room for other apps.","turtleDesc_auto": "Adjust speed automatically based on time and connection bandwidth.","turtle_off": "Standard","turtle_on": "Low speed","turtle_auto": "Automatic",- "baseSection": "Standard speed limits",+ "baseSection": "Standard limits","baseSectionDesc": "Used for everyday downloads and respected in every mode.",- "baseDownload": "Standard download limit",+ "baseDownload": "Download","baseDownloadDesc": "The maximum everyday download speed.",- "baseUpload": "Standard upload limit",+ "baseUpload": "Upload","baseUploadDesc": "The maximum everyday upload speed.","unlimited": "Unlimited","setUnlimited": "Set unlimited",- "standardLimit": "Standard limit",+ "standardLimit": "Use standard","useStandardLimit": "Use standard limit",- "altSection": "Low-speed limits",+ "altSection": "Low speed limits","altSectionDesc": "Used in Low speed mode or by scheduled rules. These limits can only reduce the standard limits.",- "altDownload": "Low-speed download limit",+ "altDownload": "Download","altDownloadDesc": "The maximum download speed while Low speed mode is active.",- "altUpload": "Low-speed upload limit",+ "altUpload": "Upload","altUploadDesc": "The maximum upload speed while Low speed mode is active.","autoSection": "Automatic rules","autoSectionDesc": "These rules apply only in Automatic mode.","autoSchedule": "Scheduled slowdown",- "scheduleEnabled": "Use low-speed limits on a schedule",+ "scheduleEnabled": "Schedule low speed","scheduleEnabledDesc": "Switch to the low-speed limits on selected days and times.","scheduleFrom": "Start","scheduleTo": "End","scheduleTimeFormat": "24-hour format (HH:mm)",- "scheduleDays": "Active days",- "scheduleDaysHint": "With no specific days selected, this runs every day. An end time earlier than the start time means the next day.",+ "scheduleDays": "Days",+ "scheduleDaysHint": "An end time before the start continues into the next day.","weekdays": {"sun": {"short": "Sun",@@ -1561,14 +1605,14 @@}},"autoAdaptive": "Leave bandwidth for other apps",- "adaptiveEnabled": "Avoid using the entire connection",- "adaptiveEnabledDesc": "Limit Motrix automatically based on your connection bandwidth.",- "linkDown": "Connection download bandwidth",+ "adaptiveEnabled": "Reserve bandwidth for other apps",+ "adaptiveEnabledDesc": "Enter your connection speeds below to calculate the limit.",+ "linkDown": "Connection download speed","linkDownDesc": "The download speed your internet connection can reach.",- "linkUp": "Connection upload bandwidth",+ "linkUp": "Connection upload speed","linkUpDesc": "The upload speed your internet connection can reach.",- "fillFromPeak": "Estimate from recent speeds",- "fillFromPeakHint": "Uses the fastest speed Motrix observed recently.",+ "fillFromPeak": "Estimate connection speed",+ "fillFromPeakHint": "Based on the fastest recent downloads and uploads.","estimateEmpty": "No speed history is available yet. Complete an unlimited download or enter bandwidth manually.","estimateSuccess": "Connection bandwidth filled from recent speeds.","estimateError": "Could not read recent speed history. Enter bandwidth manually.",@@ -1586,9 +1630,17 @@"adaptiveRulePending": "reserve {{reserved}}% of bandwidth for other apps after connection bandwidth is entered","ruleSeparator": " and ","autoRules": "Motrix will {{rules}}.",- "lowerWins": "When multiple limits apply, Motrix uses the lower value."- }- }+ "lowerWins": "The lowest active limit applies."+ },+ "bandwidthUsed": "Motrix can use up to {{motrix}}%.",+ "bandwidthPending": "Enter both connection speeds to apply this limit."+ },+ "newTasks": "New tasks",+ "defaultDownloadFolder": "Default download folder",+ "autofillFromClipboard": "Autofill links from clipboard",+ "fillInLinksWhenOpeningNewTask": "Paste copied links when opening a new task.",+ "saveFolders": "Save folders",+ "description": "Files, download speed and connections"},"network": {"dns": {@@ -1602,62 +1654,71 @@"proxy": {"title": "Proxy","enable": "Enable proxy",- "enableDesc": "Route traffic through a proxy server.",+ "enableDesc": "Use a proxy for the connections selected below.","server": "Server","protocol": "Protocol",- "host": "Host",+ "host": "Server address","hostPlaceholder": "proxy.example.com","port": "Port",- "auth": "Authentication",- "authDesc": "Required by proxies that need a login.",- "user": "User",+ "auth": "Proxy login",+ "authDesc": "Turn on if your proxy requires a username and password.",+ "user": "Username","password": "Password","showPassword": "Show password","hidePassword": "Hide password",- "bypass": "Bypass list",- "bypassDesc": "One exact host or CIDR per line. Use a leading dot like `.local` for subdomains (not the root domain); `*` wildcards are not supported for downloads.",- "bypassScopeNote": "Downloads + App update only",- "scopes": "Apply to",+ "bypass": "Connect directly to",+ "bypassDesc": "One domain, IP or CIDR per line. Start with . to match subdomains only. File downloads don’t support * wildcards.",+ "bypassScopeNote": "File downloads and app updates only",+ "scopes": "Use proxy for","scopesDesc": "Choose which kinds of traffic go through the proxy.",- "scopeDownload": "Downloads",- "scopeDownloadDesc": "BT proxy covers HTTP(S) only; peers, DHT, and UDP trackers stay direct.",- "scopeUpdateApp": "App update check",- "scopeUpdateAppDesc": "Electron auto-updater HTTPS calls.",- "scopeUpdateTrackers": "Tracker sync",- "scopeUpdateTrackersDesc": "Syncs tracker lists only; it does not proxy BT traffic.",+ "scopeDownload": "File downloads",+ "scopeDownloadDesc": "For BT, only HTTP(S) uses the proxy. Peers, DHT and UDP trackers connect directly.",+ "scopeUpdateApp": "App updates",+ "scopeUpdateAppDesc": "Check for Motrix updates through the proxy.",+ "scopeUpdateTrackers": "Tracker list updates",+ "scopeUpdateTrackersDesc": "Download tracker lists through the proxy; BT traffic is unaffected.","importFromSystem": "Import from system","importedToast": "System proxy imported: {{host}}:{{port}}",- "noSystemProxy": "No system proxy configured."+ "noSystemProxy": "No system proxy configured.",+ "bypassPlaceholder": "localhost\n127.0.0.1\n.local",+ "scopeHint": "BT peers, DHT and UDP trackers connect directly.",+ "scopeNone": "None selected",+ "scopeChoose": "Select…",+ "scopeSeparator": ", "},"nat": {- "title": "NAT mapping",+ "title": "Port mapping (NAT)","enable": "Enable port mapping",- "enableDesc": "Open inbound BT/DHT ports on the router automatically.",+ "enableDesc": "Ask the router to open the ports set in BitTorrent settings.","preferredProtocol": "Preferred protocol",- "mappingTtl": "Mapping TTL (seconds)",- "btPortHint": "Mapping applies to BT/DHT ports configured in BitTorrent."+ "mappingTtl": "Mapping duration (s)",+ "btPortHint": "Mapping applies to BT/DHT ports configured in BitTorrent.",+ "automatic": "Automatic"},"stun": {"title": "NAT type detection",- "privacyHint": "Sends queries to third-party STUN servers.",- "enable": "Enable detection via STUN",+ "privacyHint": "Uses third-party STUN servers.",+ "enable": "Detect NAT type","servers": "STUN servers",- "empty": "No STUN servers configured.",+ "empty": "Add at least one STUN server.","addServer": "Add STUN server"},"reachability": {- "title": "Port reachability",- "privacyHint": "Sends a probe to a third-party HTTPS endpoint.",- "enable": "Probe port from external service",- "endpoints": "Endpoints (HTTPS)",- "empty": "No reachability endpoints.",- "addEndpoint": "Add endpoint"+ "title": "Incoming port check",+ "privacyHint": "Uses a third-party service to check access from the internet.",+ "enable": "Check incoming ports",+ "endpoints": "Check services (HTTPS)",+ "empty": "Add at least one check service.",+ "addEndpoint": "Add check service"},"diagnostic": {- "title": "Auto diagnostic",- "enable": "Run diagnostics on schedule",- "interval": "Interval (seconds)"- }+ "title": "Automatic network checks",+ "enable": "Automatic checks",+ "interval": "Check interval (s)",+ "enableDesc": "Repeat the checks enabled above."+ },+ "description": "Proxy, DNS and connection checks",+ "diagnostics": "Network diagnostics"},"common": {"browse": "Browse…",@@ -1675,14 +1736,14 @@},"integration": {"system": {- "title": "System protocols",+ "title": "Default app","protocolMagnet": "Open magnet links with Motrix","protocolMagnetDesc": "Open magnet links from your browser in Motrix.","torrentAssociation": "Open .torrent files with Motrix",- "torrentAssociationDesc": "Once set, double-clicking a .torrent file will open it in Motrix.",+ "torrentAssociationDesc": "Double-click a .torrent file to open it in Motrix.","torrentAssociationMacDesc": "In Finder, right-click any .torrent file → Get Info → Open with → choose Motrix → Change All…","defaultAssociationsWindows": "Default app for torrents and magnet links",- "defaultAssociationsWindowsDesc": "Choose Motrix for .torrent files and magnet links in Windows Default Apps. Motrix appears there after installation with Motrix Setup.",+ "defaultAssociationsWindowsDesc": "Choose Motrix for .torrent files and magnet links in Windows settings. Requires an installed copy of Motrix.","torrentFiles": ".torrent files","magnetLinks": "Magnet links","associationStatusLabel": "Current Windows default app status",@@ -1720,8 +1781,8 @@},"browser": {"title": "Browser extensions",- "masterSwitch": "Send downloads from browser extensions",- "masterSwitchDesc": "After installing the Motrix browser extension, you can send downloads from any webpage with one click.",+ "masterSwitch": "Connect browser extensions",+ "masterSwitchDesc": "Send webpage downloads to Motrix with the browser extension.","install": {"chrome": "Chrome","edge": "Microsoft Edge",@@ -1762,7 +1823,7 @@"pairUnavailable": "This pairing request is no longer pending — retry pairing from the browser extension.","trustedExtensions": "Trusted extensions","trustedSummary": "{{count}} total",- "trustedGuidance": "If you installed a download extension other than the official Motrix one, paste the extension ID it provided here. You usually don’t need this.",+ "trustedGuidance": "For other trusted extensions, add the ID provided by the developer.","trustedEmpty": "Nothing here yet.","headerId": "Extension ID","headerBrowser": "Browser",@@ -1786,7 +1847,7 @@"title": "Command-line tools","tool": {"title": "Motrix command-line tool",- "description": "Run `motrix` in any terminal to control this Motrix.",+ "description": "Run motrix in a terminal to control this app.","managerLabel": "Package manager","commandLabel": "Install command","copyCommand": "Copy install command",@@ -1819,7 +1880,7 @@"manager": "Installed with","unknown": "unknown"},- "successGuidance": "Open a new terminal, then run `motrix --help`.",+ "successGuidance": "Open a new terminal, then run motrix --help.","diagnostics": {"show": "Show details","hide": "Hide details"@@ -1833,16 +1894,16 @@"permission": "The package manager cannot write to its global install location. Use a Node.js version manager or a user-writable prefix; do not use sudo.","network": "The package manager could not reach the registry. Check your network or registry configuration, then try again.","timeout": "Installation took too long and was stopped. Check your network, then try again.",- "pathMissing": "The package was installed, but `motrix` is not on PATH. Open a new terminal or add the reported install directory to PATH.",- "pathShadowed": "Another `motrix` executable appears earlier on PATH. Remove the older entry or correct PATH, then check again.",- "verifyFailed": "The installer completed, but Motrix could not verify the active `motrix` executable.",- "installFailed": "The package manager could not install `@motrix/cli`. Review the details, then try again or run the command manually.",+ "pathMissing": "The package was installed, but motrix is not on PATH. Open a new terminal or add the reported install directory to PATH.",+ "pathShadowed": "Another motrix executable appears earlier on PATH. Remove the older entry or correct PATH, then check again.",+ "verifyFailed": "The installer completed, but Motrix could not verify the active motrix executable.",+ "installFailed": "The package manager could not install @motrix/cli. Review the details, then try again or run the command manually.","unknown": "Motrix could not check the command-line tool. Try again or run the copied command manually."}},"remote": {"title": "Paired remote tools",- "description": "The local CLI connects automatically and does not need pairing. Run `motrix pair` only for a remote or headless Motrix instance.",+ "description": "Local tools connect automatically. Run motrix pair to connect to another computer or server.","empty": "No remote tools paired.","lastActive": "Last active","neverActive": "Never used",@@ -1861,11 +1922,11 @@"deny": "Deny","expiresIn": "Expires in {{time}}"},- "pairUnavailable": "This pairing request is no longer pending — re-run `motrix pair`."+ "pairUnavailable": "This pairing request is no longer pending — re-run motrix pair."},"media": {"title": "Media tools",- "desc": "Check FFmpeg availability and media plugin limits",+ "desc": "Merge or convert media with FFmpeg.","notDetected": "FFmpeg not detected","refresh": "Refresh","binaryPath": "Custom FFmpeg path",@@ -1906,10 +1967,10 @@"unconfigured": "Not set","version_mismatch": "Unsupported"},- "stagingMB": "Temporary workspace limit (MB)",- "stagingMBDesc": "Per plugin and task. Used while FFmpeg writes intermediate files. Default 4096 MB.",+ "stagingMB": "Temporary file limit (MB)",+ "stagingMBDesc": "Space for intermediate files, per plugin and task.","opTimeoutSec": "FFmpeg timeout (seconds)",- "opTimeoutSecDesc": "Maximum time for one FFmpeg operation. Default 1800 seconds (30 minutes), max 3600.",+ "opTimeoutSecDesc": "Maximum time for one media operation, up to 3,600 seconds.","cleanupStaging": "Clean temporary files","cleanupConfirm": "Remove all FFmpeg temporary directories?","restartHint": "Saved. Restart Motrix for active plugins to detect changes.",@@ -1917,7 +1978,7 @@"validation": {"fileMissing": "File does not exist at this path."},- "applyHint": "Save to apply the custom path. Media downloads use the current FFmpeg path without restarting Motrix; rescan in the browser extension to refresh support.",+ "applyHint": "Save to use this path for new media downloads. Rescan in the browser extension to refresh support.","savedTitle": "FFmpeg settings saved","desktopSavedHint": "New media downloads read the saved path. Restart Motrix for active plugins to detect the change.","pipelineUnavailable": "Media download support is unavailable.",@@ -1964,7 +2025,8 @@"missing": "A required file is missing. Run the AppImage from its current location and repair.","io": "The operation failed. Check disk access and try Repair."}- }+ },+ "description": "Browsers, default apps and tools"},"validation": {"rangeHint": "Range: {{min}}–{{max}}.",@@ -1989,7 +2051,8 @@"address": "Address {{number}}","addressDraft": "New address","required": "Enter an address first.",- "time": "Use a 24-hour time, such as 23:00."+ "time": "Use a 24-hour time, such as 23:00.",+ "loadFailed": "Couldn’t load settings. Try again."},"feedback": {"syncFailedTitle": "Settings saved; interface update failed",@@ -2590,6 +2653,7 @@"clearAll": "Clear","empty": "No notifications","emptyDesc": "Download activity and important app notices will show up here",+ "unreadDotAria": "Unread notifications","unreadBadgeAria_one": "{{count}} unread notification","unreadBadgeAria_other": "{{count}} unread notifications","rowUnreadAria": "{{title}} (unread)",@@ -2676,11 +2740,11 @@}},"directoryPreferences": {- "sectionDescription": "Choose favorite folders and manage recent download locations.",+ "sectionDescription": "Keep frequently used folders handy.","manage": "Manage directories","manageDescription": "Choose favorite folders and manage recent folders.","title": "Manage directories",- "description": "Changes apply when you save. Removing a record does not delete folders or downloads.",+ "description": "Removing a folder from this list won’t delete it or its files.","favorites": "Favorite folders","recent": "Recent folders","addFavorite": "Add favorite",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 2ad0b6ee..d59ce288 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1171,12 +1171,21 @@}},"general": {- "launchAtStartup": "登录时自动启动",+ "launchAtStartup": "登录时启动","launchAtStartupDesc": "登录时自动启动 Motrix。","showMainWindowAtLogin": "登录时显示窗口","showMainWindowAtLoginDesc": "选择“{{mode}}”时不显示。","defaultSaveDir": "默认下载目录","defaultSaveDirDesc": "新建下载默认保存到此目录,可按任务覆盖。",+ "inAppNotifications": "应用内通知",+ "inAppNotificationsDesc": "选择要显示的下载通知。应用故障提醒始终开启。",+ "notifyInAppOnComplete": "显示下载完成通知",+ "notifyInAppOnError": "显示下载失败通知",+ "notificationBadgeStyle": "未读角标",+ "notificationBadgeCount": "数量",+ "notificationBadgeDot": "圆点",+ "notificationBadgeHidden": "隐藏",+ "systemNotifications": "系统通知","notifyOnComplete": "下载完成通知","notifyOnCompleteDesc": "任务完成时弹出系统通知。","autofillClipboardLinks": "新建任务时自动填入剪贴板链接",@@ -1184,7 +1193,25 @@"notifyOnError": "下载失败时通知","notifyOnErrorDesc": "当窗口处于后台时,下载失败会弹出系统通知。","warnBeforeQuit": "退出前确认",- "warnBeforeQuitDesc": "当仍有下载在进行时退出,弹出确认。"+ "warnBeforeQuitDesc": "有下载进行时,退出前提醒。",+ "notificationBadgeDesc": "显示在通知中心图标上。",+ "notificationOff": "不通知",+ "notificationSystem": "系统通知",+ "notificationInApp": "应用内通知",+ "notificationBoth": "两个都通知",+ "startupAndQuitting": "启动与退出",+ "runMode": "应用显示位置",+ "runModeStandard": "程序坞和菜单栏",+ "runModeTray": "仅菜单栏",+ "runModeHideTray": "仅程序坞",+ "lightweightMode": "关闭窗口后节省内存",+ "lightweightModeDesc": "下载会继续;重新打开稍慢,未保存的输入会清除。",+ "notifications": "通知",+ "notificationsDesc": "应用故障提醒始终开启。",+ "downloadCompleted": "下载完成",+ "downloadFailed": "下载失败",+ "description": "启动、退出与通知",+ "desktopOnly": "启动和通知偏好可在桌面应用中设置。"},"appearance": {"theme": "主题",@@ -1192,18 +1219,18 @@"themeLight": "浅色","themeDark": "深色","language": "语言",- "traySpeedometer": "在托盘显示实时速度",- "traySpeedometerDesc": "仅 macOS — 在托盘图标旁显示当前速度。",+ "traySpeedometer": "在菜单栏显示速度",+ "traySpeedometerDesc": "在应用图标旁显示下载和上传速度。","trayIconColor": "托盘图标颜色",- "trayIconColorDesc": "面板主题可能与 Motrix 不同。深色面板请选择浅色图标,浅色面板请选择深色图标。",+ "trayIconColorDesc": "选择在系统面板上容易看清的颜色。","trayIconColorAuto": "跟随应用主题","trayIconColorLight": "浅色图标(深色面板)","trayIconColorDark": "深色图标(浅色面板)","reduceMotion": "减少动画",- "reduceMotionDesc": "减少界面动画,包括下载页的玻璃动态效果。",- "liquidGlassEffect": "启用液态玻璃效果",- "liquidGlassEffectDesc": "为下载页工具栏使用半透明玻璃效果。",- "liquidGlassEffectMacDesc": "macOS 26 及以上同时使用原生窗口玻璃,更改后会重建主窗口。",+ "reduceMotionDesc": "减少界面中的动态效果。",+ "liquidGlassEffect": "液态玻璃",+ "liquidGlassEffectDesc": "让下载工具栏呈现半透明玻璃效果。",+ "liquidGlassEffectMacDesc": "macOS 26 及以上也会应用到窗口;更改后窗口会重新打开。","runMode": "显示位置","runModeStandard": "程序坞与菜单栏","runModeTray": "仅菜单栏",@@ -1215,11 +1242,11 @@"lightweightMode": "轻量模式","lightweightModeDesc": "关闭窗口后节省内存,下载不受影响。重新打开稍慢,未保存的输入会清除。","byteUnitSystem": "大小和速度单位",- "byteUnitSystemDesc": "用于文件大小与传输速度的显示。",+ "byteUnitSystemDesc": "选择文件大小和速度的显示单位。","byteUnitDecimal": "十进制(MB、GB · 1000)","byteUnitBinary": "二进制(MiB、GiB · 1024)","byteUnitSystemDefault": "跟随系统({{units}})",- "sidebarColor": "颜色",+ "sidebarColor": "主题色","sidebarColors": {"blue": "冰蓝","violet": "鸢紫",@@ -1230,7 +1257,12 @@"cyan": "湖青","gray": "淡灰","auto": "自动"- }+ },+ "themeAndEffects": "主题与效果",+ "languageAndDisplay": "语言与显示",+ "menuBar": "菜单栏",+ "description": "主题、语言与显示",+ "systemTray": "系统托盘"},"about": {"appIconAlt": "Motrix 应用图标",@@ -1243,7 +1275,7 @@"idleTitle": "让 Motrix 保持最新","idle": "当前安装的是版本 {{version}}。立即检查,或让 Motrix 在启动时自动检查。","unsupportedTitle": "自动更新不可用",- "unsupported": "当前构建不支持自动更新,请前往官网下载最新版本。",+ "unsupported": "当前版本不支持自动更新,请到官网下载最新版。","check": "检查更新","checkAction": "检查","checking": "正在检查…",@@ -1272,10 +1304,10 @@"automaticChecksDescription": "Motrix 启动时","automaticChecksError": "无法保存此设置","channelLabel": "更新通道",- "channelDescription": "选择 Motrix 要检查的应用 release 类型。",- "channelStable": "Stable",- "channelBeta": "Beta",- "channelBetaWarning": "Beta release 可能不够稳定。你会收到 beta 和后续 stable release;切回 Stable 后将停止接收新 beta,但不会自动安装更旧版本。",+ "channelDescription": "选择稳定版本,或通过测试版本体验新功能。",+ "channelStable": "稳定版",+ "channelBeta": "测试版",+ "channelBetaWarning": "测试版可能不够稳定,也会接收后续稳定版。切回稳定版后不再接收测试版,不会自动降级。","channelSaveError": "无法保存更新通道,请重试。"},"details": {@@ -1302,101 +1334,113 @@"rpc": {"title": "RPC","port": "RPC 端口",- "portDesc": "aria2 RPC 服务监听的 TCP 端口。需重启。",+ "portDesc": "修改后需重启。","secret": "RPC 密钥",- "secretDesc": "客户端用于认证的令牌。点击生成获取随机密钥。"+ "secretDesc": "用于验证 RPC 连接。"},"persistence": {- "title": "SQLite 持久化",- "enable": "启用 SQLite 持久化",- "enableDesc": "将会话、进度与历史保存到单个 SQLite 数据库中。关闭后回退到上游 aria2 行为(文本 session + .aria2 sidecar)。",- "dbPath": "数据库路径",- "dbPathDesc": "留空则使用默认位置(与其他 engine 配置文件相邻)。",- "dbPathPlaceholder": "默认:<config>/aria2.db",- "historyLimit": "历史保留条数",- "historyLimitDesc": "下载历史保留的最大行数。-1 = 无限;0 = 仅内存(不写 DB)。"- }+ "title": "进度与恢复",+ "enable": "保存恢复数据",+ "enableDesc": "保存用于重启后继续下载的数据。",+ "dbPath": "恢复数据文件",+ "dbPathDesc": "留空则使用默认位置。",+ "dbPathPlaceholder": "默认位置",+ "historyLimit": "已完成下载的恢复记录",+ "historyLimitDesc": "不影响下载列表和已下载的文件。",+ "historyKeepAll": "全部保留",+ "historyKeepRecent": "保留最近…",+ "historySessionOnly": "不保留",+ "historyCount": "保留条数",+ "historyCountHint": "较早的恢复记录会被移除。",+ "historyCountPositive": "请输入大于 0 的数量。"+ },+ "description": "RPC、进度与恢复"},"bittorrent": {"trackers": {- "autoSync": "自动同步",- "autoSyncDesc": "按计划自动同步 tracker 列表",- "syncInterval": "同步间隔",- "syncIntervalDesc": "tracker 同步频率(小时,1–168)",- "enableProbe": "启用探测",- "enableProbeDesc": "添加到种子前测试 tracker 健康状态",- "probeTimeout": "探测超时",- "probeTimeoutDesc": "等待探测响应的最长时间(ms,1000–30000)",- "healthyThreshold": "健康阈值",- "healthyThresholdDesc": "视为健康的最大响应时间(ms,500–10000)",+ "autoSync": "自动更新 Tracker 列表",+ "autoSyncDesc": "从已添加的来源获取最新列表。",+ "syncInterval": "更新间隔(小时)",+ "syncIntervalDesc": "可设为 1–168 小时。",+ "enableProbe": "检查 Tracker 可用性",+ "enableProbeDesc": "使用前检查 Tracker 是否能正常响应。",+ "probeTimeout": "检查超时(毫秒)",+ "probeTimeoutDesc": "等待响应的最长时间,1,000–30,000 毫秒。",+ "healthyThreshold": "慢响应判定时间(毫秒)",+ "healthyThresholdDesc": "响应超过此时间会标记为缓慢,500–10,000 毫秒。","minSuccessRate": "最低成功率",- "minSuccessRateDesc": "保留 tracker 的最低成功比例(0–1)",- "maxTrackerCount": "最大 Tracker 数",- "maxTrackerCountDesc": "每个种子应用的最大 tracker 数(5–200)",+ "minSuccessRateDesc": "使用达到此成功率的 Tracker,0.5 表示 50%。",+ "maxTrackerCount": "每个任务的 Tracker 数量",+ "maxTrackerCountDesc": "最多使用的 Tracker 数量,5–200。","title": "Trackers",- "manageSourcesHint": "在侧边栏 Trackers 页管理源列表。",- "blacklistMovedInfo": "Tracker 黑名单已迁移到侧边栏 Trackers 页面 → 黑名单标签页管理。"+ "manageSourcesHint": "在 Tracker 页面管理来源。",+ "blacklistMovedInfo": "在 Tracker → 黑名单中管理屏蔽的地址。"},"geoip": {- "title": "GeoIP 数据库",- "enable": "启用 IP 地理识别",- "enableDesc": "在 peers 列表中根据 IP 解析对端国家。数据库按需下载,存放在用户数据目录。",+ "title": "节点位置",+ "enable": "显示国家或地区",+ "enableDesc": "在节点列表中显示位置,需要时会下载位置数据。","lastUpdated": "最后更新","neverUpdated": "从未更新","updateNow": "现在更新","updating": "更新中…",- "source": "数据源",- "sourceDesc": "选择 GeoLite2-Country.mmdb 文件的下载来源。",+ "source": "位置数据来源",+ "sourceDesc": "选择位置数据的下载来源。","source.loyalsoldier": "Loyalsoldier(社区维护)","source.p3terx": "P3TERX(社区镜像)","source.maxmind": "MaxMind 官方","source.custom": "自定义 URL",- "maxmindUnsupported": "Phase 2.1",- "customUrl": "自定义 URL",+ "maxmindUnsupported": "暂不支持",+ "customUrl": "自定义下载地址","customUrlPlaceholder": "https://example.com/GeoLite2-Country.mmdb","autoUpdate": "自动更新",- "autoUpdateDesc": "大约每周检查一次新数据库。",- "status.loaded": "已加载",- "status.notDownloaded": "数据库未下载",+ "autoUpdateDesc": "大约每周检查一次位置数据更新。",+ "status.loaded": "已就绪",+ "status.notDownloaded": "尚未下载位置数据","status.downloading": "下载中…",- "status.error": "更新失败"+ "status.error": "更新失败",+ "customUrlDesc": "填写 .mmdb 格式国家数据文件的链接。",+ "saveBeforeUpdate": "请先保存设置,再更新位置数据。",+ "updateFailed": "无法更新位置数据,请重试。"},"listen": {- "title": "监听",+ "title": "传入连接","listenPort": "BT 监听端口",- "listenPortDesc": "aria2 用于接收节点连接的端口。",+ "listenPortDesc": "用于接收其他用户的连接。","dhtListenPort": "DHT 监听端口",- "dhtListenPortDesc": "aria2 用于 DHT 的端口。",+ "dhtListenPortDesc": "用于通过 DHT 查找其他用户。","dhtEnabled": "启用 DHT",- "dhtEnabledDesc": "分布式哈希表,用于无 tracker 的种子。"+ "dhtEnabledDesc": "无需依赖 Tracker 也能查找其他用户。"},"peers": {"title": "节点","btMaxPeers": "每种子最大节点数",- "btMaxPeersDesc": "并发节点连接数上限。",+ "btMaxPeersDesc": "单个任务同时连接的节点数量上限。","btEnableLpd": "本地节点发现",- "btEnableLpdDesc": "在本地网络发现节点。",- "magnetFileSelection": "磁链元数据加载后弹出文件选择",- "magnetFileSelectionDesc": "磁链元数据到达后显示文件选择器。",- "magnetFileSelectionAutoDownload": "选择文件超时后自动下载全部文件",- "magnetFileSelectionAutoDownloadDesc": "未在限定时间内确认文件选择,将下载全部文件到任务保存目录;关闭窗口或 WebUI 后仍会生效。",+ "btEnableLpdDesc": "查找局域网内共享文件的设备。",+ "magnetFileSelection": "下载前选择文件",+ "magnetFileSelectionDesc": "磁力链接加载后,选择要下载的文件。",+ "magnetFileSelectionAutoDownload": "超时后下载全部文件",+ "magnetFileSelectionAutoDownloadDesc": "超过下方等待时间后开始下载;关闭窗口或浏览器后仍会生效。","magnetFileSelectionTimeoutSeconds": "选择文件等待时间(秒)",- "magnetFileSelectionTimeoutSecondsDesc": "从元数据解析完成、进入待选文件状态开始计时。修改时长也会应用到已经等待选择的任务。",+ "magnetFileSelectionTimeoutSecondsDesc": "从文件列表加载完成时计时,也适用于正在等待的任务。","magnetFileSelectionTimeoutInvalid": "请输入 {{min}} 至 {{max}} 秒之间的整数。"},"seeding": {"title": "做种",- "seedRatio": "做种比率上限",- "seedRatioDesc": "超过此比率停止做种。0 = 无限制。",+ "seedRatio": "分享率上限",+ "seedRatioDesc": "上传量 ÷ 下载量,达到后停止做种;0 表示不限。","seedTime": "做种时间上限(分钟)",- "seedTimeDesc": "做种达到该分钟数后停止。0 = 无限制。应用于新建或重新做种的任务。"- }+ "seedTimeDesc": "0 表示不限,适用于新任务和重新开始做种的任务。"+ },+ "newMagnetTasks": "新建磁力任务",+ "description": "磁力链接、做种与 Tracker"},"downloads": {"performance": {"title": "性能",- "profile": "性能档位",- "profileDesc": "选择 Motrix 的下载强度。",+ "profile": "下载性能",+ "profileDesc": "平衡下载速度与资源占用。","learnMore": "了解更多","metrics": {"connections": "最大连接数",@@ -1408,7 +1452,7 @@"profiles": {"auto": {"label": "自动",- "desc": "显示默认值,实际随磁盘和文件大小调整。"+ "desc": "按磁盘和文件大小自动调整,下方为默认值。"},"balanced": {"label": "均衡",@@ -1420,102 +1464,102 @@},"maximum": {"label": "极限",- "desc": "使用最大并发;部分服务器可能拒绝。"+ "desc": "使用更多连接,部分服务器可能会限制连接数。"},"custom": {"label": "自定义","desc": "设置连接数、分段大小和缓存。"}},- "maxConcurrentDownloads": "最大同时下载数",- "maxConcurrentDownloadsDesc": "同一时刻并行下载的任务数。",+ "maxConcurrentDownloads": "同时下载任务数",+ "maxConcurrentDownloadsDesc": "超出的任务会排队等待。","maxConnectionPerServer": "单服务器最大连接数","maxConnectionPerServerDesc": "每个文件对同一服务器的连接上限。","split": "单文件最大连接数",- "splitDesc": "实际连接数可能更少。",+ "splitDesc": "下载单个文件时使用的连接数。","minSplitSize": "最小分段大小(MiB)","minSplitSizeDesc": "小于此值两倍的分段不再拆分。"},"reliability": {- "title": "网络可靠性",+ "title": "连接与重试","userAgent": "User-Agent",- "userAgentDesc": "HTTP 请求附带的 User-Agent。",- "connectTimeout": "连接超时 (秒)",- "connectTimeoutDesc": "等待 TCP 建连的最长时间。",- "socketTimeout": "套接字超时 (秒)",- "socketTimeoutDesc": "等待 socket 数据的最长时间。",- "maxTries": "最大重试次数",- "maxTriesDesc": "0 表示不重试。",- "retryWait": "重试间隔 (秒)",- "retryWaitDesc": "两次重试之间的停顿。",- "lowestSpeedLimit": "慢连接阈值 (KiB/s)",- "lowestSpeedLimitDesc": "速度低于此值时断开。0 表示关闭。"+ "userAgentDesc": "向网站标识下载工具,按网站要求修改。",+ "connectTimeout": "连接等待时间(秒)",+ "connectTimeoutDesc": "等待服务器连接的最长时间。",+ "socketTimeout": "数据等待时间(秒)",+ "socketTimeoutDesc": "连接后未收到数据的最长等待时间。",+ "maxTries": "最多尝试次数",+ "maxTriesDesc": "包含首次尝试;0 表示不限次数。",+ "retryWait": "重试间隔(秒)",+ "retryWaitDesc": "失败后等多久再试。",+ "lowestSpeedLimit": "最低连接速度(KiB/s)",+ "lowestSpeedLimitDesc": "低于此速度时断开连接;0 表示关闭。"},"disk": {"fileDeletionMode": "删除任务文件时","fileDeletionTrash": "移到回收站","fileDeletionPermanent": "直接删除",- "fileDeletionTrashDesc": "适用于移除任务时同时删除文件。清空回收站后才会释放磁盘空间。",- "fileDeletionPermanentDesc": "文件将直接删除,无法从回收站恢复。",- "title": "磁盘与会话",- "fileAllocation": "文件预分配",- "fileAllocationDesc": "aria2 如何为新文件预留磁盘空间。",- "fileAllocationNone": "不分配",- "fileAllocationPrealloc": "预分配",- "fileAllocationTrunc": "截断",- "fileAllocationFalloc": "Falloc",+ "fileDeletionTrashDesc": "清空回收站后才会释放磁盘空间。",+ "fileDeletionPermanentDesc": "删除后无法从回收站恢复。",+ "title": "磁盘与文件",+ "fileAllocation": "磁盘空间预留",+ "fileAllocationDesc": "下载开始前,为文件预留空间。",+ "fileAllocationNone": "不预留",+ "fileAllocationPrealloc": "预先分配",+ "fileAllocationTrunc": "设置文件大小",+ "fileAllocationFalloc": "系统分配","modifiedTime": "文件修改时间",- "modifiedTimeDesc": "选择 HTTP 和 FTP 下载完成后使用的文件修改时间。",- "modifiedTimeLocal": "本地修改时间",- "modifiedTimeServer": "服务器修改时间",+ "modifiedTimeDesc": "适用于下载完成的 HTTP 和 FTP 文件。",+ "modifiedTimeLocal": "下载时间",+ "modifiedTimeServer": "服务器提供的时间","diskCache": "磁盘缓存 (MiB)",- "diskCacheDesc": "写入磁盘前的内存缓存上限。",- "sessionSaveInterval": "会话保存间隔 (秒)",- "sessionSaveIntervalDesc": "aria2 持久化下载状态的频率。"+ "diskCacheDesc": "写入磁盘前暂存文件数据的内存。",+ "sessionSaveInterval": "进度保存间隔(秒)",+ "sessionSaveIntervalDesc": "保存越频繁,意外退出时丢失的进度越少。"},"magnet": {"title": "磁力链",- "magnetResolveTimeout": "磁力链解析超时 (秒)",- "magnetResolveTimeoutDesc": "等待元数据的最长时间。"+ "magnetResolveTimeout": "磁力链接加载时限(秒)",+ "magnetResolveTimeoutDesc": "等待文件列表加载的最长时间。"},"speedLimit": {"title": "速度限制","titleDesc": "选择 Motrix 在常规、低速和自动模式下如何使用网络。","modeSection": "速度模式","modeSectionDesc": "选择 Motrix 应当怎样使用你的网络。",- "turtle": "当前模式",+ "turtle": "速度模式","turtleDesc_off": "使用常规速度上限。","turtleDesc_on": "立即使用低速上限,适合临时给其他应用让出网络。","turtleDesc_auto": "根据时间和网络带宽自动调整速度。","turtle_off": "常规","turtle_on": "低速","turtle_auto": "自动",- "baseSection": "常规速度上限",+ "baseSection": "常规限速","baseSectionDesc": "日常下载使用;所有模式都会遵循这里的上限。",- "baseDownload": "常规下载上限",+ "baseDownload": "下载","baseDownloadDesc": "日常下载时允许的最高速度。",- "baseUpload": "常规上传上限",+ "baseUpload": "上传","baseUploadDesc": "日常上传时允许的最高速度。","unlimited": "不限速","setUnlimited": "设为不限速","standardLimit": "沿用常规上限","useStandardLimit": "沿用常规上限",- "altSection": "低速模式上限",+ "altSection": "低速限速","altSectionDesc": "低速模式和定时规则使用;只会在常规上限基础上进一步降速。",- "altDownload": "低速下载上限",+ "altDownload": "下载","altDownloadDesc": "低速模式生效时允许的最高下载速度。",- "altUpload": "低速上传上限",+ "altUpload": "上传","altUploadDesc": "低速模式生效时允许的最高上传速度。",- "autoSection": "自动调整规则",+ "autoSection": "自动规则","autoSectionDesc": "仅在自动模式下生效。","autoSchedule": "按时段降低速度",- "scheduleEnabled": "按计划使用低速模式",+ "scheduleEnabled": "定时启用低速模式","scheduleEnabledDesc": "在指定日期和时段自动切换到低速上限。","scheduleFrom": "开始时间","scheduleTo": "结束时间","scheduleTimeFormat": "24 小时制(HH:mm)",- "scheduleDays": "生效日期",- "scheduleDaysHint": "未指定日期时每天生效。结束时间早于开始时间时,按次日计算。",+ "scheduleDays": "重复日期",+ "scheduleDaysHint": "结束时间早于开始时间时,持续至次日。","weekdays": {"sun": {"short": "日",@@ -1547,14 +1591,14 @@}},"autoAdaptive": "为其他应用留出带宽",- "adaptiveEnabled": "避免 Motrix 占满网络",- "adaptiveEnabledDesc": "根据网络带宽自动限制 Motrix 的最高速度。",- "linkDown": "网络下载带宽",+ "adaptiveEnabled": "为其他应用预留带宽",+ "adaptiveEnabledDesc": "按下方填写的宽带速度计算限速。",+ "linkDown": "宽带下载速度","linkDownDesc": "网络连接能够达到的下载速度。",- "linkUp": "网络上传带宽",+ "linkUp": "宽带上传速度","linkUpDesc": "网络连接能够达到的上传速度。",- "fillFromPeak": "根据近期速度估算",- "fillFromPeakHint": "使用 Motrix 近期观察到的最高速度。",+ "fillFromPeak": "估算宽带速度",+ "fillFromPeakHint": "按近期最高下载和上传速度估算。","estimateEmpty": "暂无可用的速度记录。请先完成一次不限速下载,或手动填写网络带宽。","estimateSuccess": "已根据近期速度填入网络带宽。","estimateError": "无法读取近期速度记录,请手动填写网络带宽。",@@ -1572,78 +1616,95 @@"adaptiveRulePending": "在网络带宽填写完成后为其他应用预留 {{reserved}}% 带宽","ruleSeparator": ",并","autoRules": "Motrix 将{{rules}}。",- "lowerWins": "多个速度上限同时生效时,将采用较低的值。"- }- }+ "lowerWins": "多项限速同时生效时取最低值。"+ },+ "bandwidthUsed": "Motrix 最多使用 {{motrix}}%。",+ "bandwidthPending": "填入下载和上传速度后生效。"+ },+ "newTasks": "新建任务",+ "defaultDownloadFolder": "默认保存位置",+ "autofillFromClipboard": "自动填入剪贴板链接",+ "fillInLinksWhenOpeningNewTask": "新建任务时,自动填入已复制的链接。",+ "saveFolders": "保存位置",+ "description": "文件、下载速度与连接"},"network": {"dns": {"title": "DNS","mode": "DNS 解析方式",- "modeDesc": "下载引擎解析域名的方式。",+ "modeDesc": "下载时查找服务器地址的方式。","modeAuto": "自动",- "modeSystem": "系统解析器",- "modeEngine": "引擎内置解析器"+ "modeSystem": "系统 DNS",+ "modeEngine": "内置 DNS"},"proxy": {"title": "代理","enable": "启用代理",- "enableDesc": "通过代理服务器路由流量。",+ "enableDesc": "让下方选中的连接通过代理。","server": "服务器","protocol": "协议",- "host": "主机",+ "host": "服务器地址","hostPlaceholder": "proxy.example.com","port": "端口",- "auth": "认证",- "authDesc": "代理服务器要求登录时启用。",- "user": "用户",+ "auth": "代理登录",+ "authDesc": "代理需要用户名和密码时开启。",+ "user": "用户名","password": "密码","showPassword": "显示密码","hidePassword": "隐藏密码",- "bypass": "绕过列表",- "bypassDesc": "每行填写一个精确主机或 CIDR。用 `.local` 这样的前导点匹配子域(不含根域);下载代理不支持 `*` 通配符。",- "bypassScopeNote": "仅作用于下载与应用更新",- "scopes": "应用于",+ "bypass": "不使用代理的地址",+ "bypassDesc": "每行填写一个域名、IP 或 CIDR。开头加 . 仅匹配子域名。文件下载不支持 * 通配符。",+ "bypassScopeNote": "仅下载文件和更新应用",+ "scopes": "代理用途","scopesDesc": "选择哪些流量通过代理。",- "scopeDownload": "下载",- "scopeDownloadDesc": "BT 仅代理 HTTP(S);Peer、DHT 和 UDP Tracker 直连。",- "scopeUpdateApp": "应用更新检查",- "scopeUpdateAppDesc": "Electron 自动更新检查的 HTTPS 请求。",- "scopeUpdateTrackers": "Tracker 同步",- "scopeUpdateTrackersDesc": "仅同步 Tracker 列表,不代理 BT 流量。",+ "scopeDownload": "下载文件",+ "scopeDownloadDesc": "BT 仅代理 HTTP(S);节点、DHT 和 UDP Tracker 直接连接。",+ "scopeUpdateApp": "更新应用",+ "scopeUpdateAppDesc": "通过代理检查 Motrix 更新。",+ "scopeUpdateTrackers": "更新 Tracker 列表",+ "scopeUpdateTrackersDesc": "通过代理更新 Tracker 列表,不影响 BT 下载连接。","importFromSystem": "从系统导入","importedToast": "已从系统导入代理:{{host}}:{{port}}",- "noSystemProxy": "未配置系统代理。"+ "noSystemProxy": "未配置系统代理。",+ "bypassPlaceholder": "localhost\n127.0.0.1\n.local",+ "scopeHint": "BT 节点、DHT 和 UDP Tracker 仍直接连接。",+ "scopeNone": "未选择",+ "scopeChoose": "选择…",+ "scopeSeparator": "、"},"nat": {- "title": "NAT 映射",+ "title": "端口映射(NAT)","enable": "启用端口映射",- "enableDesc": "自动在路由器上开放 BT/DHT 入站端口。",+ "enableDesc": "请求路由器开放 BitTorrent 设置中的端口。","preferredProtocol": "首选协议","mappingTtl": "映射有效期(秒)",- "btPortHint": "映射作用于 BitTorrent 设置中配置的 BT/DHT 端口。"+ "btPortHint": "映射作用于 BitTorrent 设置中配置的 BT/DHT 端口。",+ "automatic": "自动"},"stun": {"title": "NAT 类型检测",- "privacyHint": "通过第三方 STUN 服务器发送查询。",- "enable": "启用 STUN 检测",+ "privacyHint": "使用第三方 STUN 服务器。",+ "enable": "检测 NAT 类型","servers": "STUN 服务器",- "empty": "未配置 STUN 服务器。",+ "empty": "至少添加一个 STUN 服务器。","addServer": "添加 STUN 服务器"},"reachability": {- "title": "端口可达性",- "privacyHint": "通过第三方 HTTPS 服务发送探测。",- "enable": "通过外部服务探测端口",- "endpoints": "端点 (HTTPS)",- "empty": "未配置可达性端点。",- "addEndpoint": "添加端点"+ "title": "外网连接检查",+ "privacyHint": "通过第三方服务检查外网能否连接。",+ "enable": "检查入站端口",+ "endpoints": "检查服务地址(HTTPS)",+ "empty": "至少添加一个检查服务。",+ "addEndpoint": "添加检查服务"},"diagnostic": {- "title": "自动诊断",- "enable": "按计划运行诊断",- "interval": "间隔(秒)"- }+ "title": "自动网络检查",+ "enable": "定期检查",+ "interval": "检查间隔(秒)",+ "enableDesc": "定期运行上方已开启的检测。"+ },+ "description": "代理、DNS 与连接检查",+ "diagnostics": "网络诊断"},"common": {"browse": "浏览…",@@ -1661,14 +1722,14 @@},"integration": {"system": {- "title": "系统协议",+ "title": "默认应用","protocolMagnet": "用 Motrix 打开磁力链接","protocolMagnetDesc": "在浏览器里点击磁力链接时,用 Motrix 打开。","torrentAssociation": "用 Motrix 打开种子文件",- "torrentAssociationDesc": "设置好之后,双击种子文件 (.torrent) 会自动用 Motrix 打开。",+ "torrentAssociationDesc": "双击种子文件时,用 Motrix 打开。","torrentAssociationMacDesc": "在 Finder 中右键任意 .torrent 文件 → 显示简介 → 打开方式 → 选择 Motrix → 全部更改…","defaultAssociationsWindows": "种子文件和磁力链接的默认应用",- "defaultAssociationsWindowsDesc": "在 Windows 默认应用中为 .torrent 文件和磁力链接选择 Motrix。使用 Motrix 安装程序安装后,Motrix 才会出现在列表中。",+ "defaultAssociationsWindowsDesc": "在 Windows 设置中选择用 Motrix 打开种子文件和磁力链接。需先安装 Motrix。","torrentFiles": ".torrent 文件","magnetLinks": "磁力链接","associationStatusLabel": "当前 Windows 默认应用状态",@@ -1706,8 +1767,8 @@},"browser": {"title": "浏览器扩展",- "masterSwitch": "用浏览器扩展发送下载到 Motrix",- "masterSwitchDesc": "安装 Motrix 浏览器扩展后,可以在网页上点击下载图标直接发送到 Motrix。",+ "masterSwitch": "连接浏览器扩展",+ "masterSwitchDesc": "安装浏览器扩展后,将网页下载发送到 Motrix。","install": {"chrome": "Chrome","edge": "Microsoft Edge",@@ -1748,7 +1809,7 @@"pairUnavailable": "该配对请求已失效——请在浏览器扩展中重新发起配对。","trustedExtensions": "受信任的扩展","trustedSummary": "共 {{count}} 个",- "trustedGuidance": "如果你安装了 Motrix 官方扩展之外的下载扩展,把扩展提供的 ID 添加到这里。通常不需要使用。",+ "trustedGuidance": "使用其他可信扩展时,添加开发者提供的扩展 ID。","trustedEmpty": "还没有添加。","headerId": "扩展 ID","headerBrowser": "浏览器",@@ -1772,7 +1833,7 @@"title": "命令行工具","tool": {"title": "Motrix 命令行工具",- "description": "在任意终端中运行 `motrix` 来控制此 Motrix。",+ "description": "在终端运行 motrix,即可控制本应用。","managerLabel": "包管理器","commandLabel": "安装命令","copyCommand": "复制安装命令",@@ -1805,7 +1866,7 @@"manager": "安装方式","unknown": "未知"},- "successGuidance": "打开一个新终端,然后运行 `motrix --help`。",+ "successGuidance": "打开一个新终端,然后运行 motrix --help。","diagnostics": {"show": "显示详情","hide": "隐藏详情"@@ -1819,16 +1880,16 @@"permission": "包管理器无法写入全局安装目录。请使用 Node.js 版本管理器或用户可写的 prefix;不要使用 sudo。","network": "包管理器无法访问 registry。请检查网络或 registry 配置后重试。","timeout": "安装时间过长,已停止。请检查网络后重试。",- "pathMissing": "包已安装,但 PATH 中找不到 `motrix`。请打开新终端,或将提示的安装目录加入 PATH。",- "pathShadowed": "PATH 中有另一个 `motrix` 可执行文件排在前面。请移除旧入口或修正 PATH 后重新检查。",- "verifyFailed": "安装程序已经结束,但 Motrix 无法验证当前生效的 `motrix` 可执行文件。",- "installFailed": "包管理器无法安装 `@motrix/cli`。请查看详情后重试,或手动运行安装命令。",+ "pathMissing": "包已安装,但 PATH 中找不到 motrix。请打开新终端,或将提示的安装目录加入 PATH。",+ "pathShadowed": "PATH 中有另一个 motrix 可执行文件排在前面。请移除旧入口或修正 PATH 后重新检查。",+ "verifyFailed": "安装程序已经结束,但 Motrix 无法验证当前生效的 motrix 可执行文件。",+ "installFailed": "包管理器无法安装 @motrix/cli。请查看详情后重试,或手动运行安装命令。","unknown": "Motrix 无法检查命令行工具。请重试,或手动运行已复制的命令。"}},"remote": {"title": "已配对的远程工具",- "description": "本机 CLI 会自动连接,无需配对。仅在连接远程或 headless Motrix 实例时运行 `motrix pair`。",+ "description": "本机工具会自动连接;连接其他电脑或服务器时,运行 motrix pair。","empty": "暂无已配对的远程工具。","lastActive": "最近活跃","neverActive": "从未使用",@@ -1847,11 +1908,11 @@"deny": "拒绝","expiresIn": "{{time}} 后过期"},- "pairUnavailable": "该配对请求已不在待审批 —— 请重跑 `motrix pair`。"+ "pairUnavailable": "该配对请求已不在待审批 —— 请重跑 motrix pair。"},"media": {"title": "媒体工具",- "desc": "检查 FFmpeg 可用性并设置媒体插件限制",+ "desc": "使用 FFmpeg 合并或转换媒体文件。","notDetected": "未探测到 FFmpeg","refresh": "刷新","binaryPath": "自定义 FFmpeg 路径",@@ -1891,18 +1952,18 @@"unconfigured": "未设置","version_mismatch": "不受支持"},- "stagingMB": "临时工作区上限(MB)",- "stagingMBDesc": "按插件和任务分配,用于 FFmpeg 写入中间文件。默认 4096 MB。",+ "stagingMB": "临时文件空间上限(MB)",+ "stagingMBDesc": "每个插件、每个任务处理媒体时可用的临时空间。","opTimeoutSec": "FFmpeg 超时(秒)",- "opTimeoutSecDesc": "单次 FFmpeg 操作的最长执行时间。默认 1800 秒(30 分钟),上限 3600。",- "cleanupStaging": "清理临时文件残留",+ "opTimeoutSecDesc": "单次媒体处理的最长时间,最多 3,600 秒。",+ "cleanupStaging": "清理临时文件","cleanupConfirm": "删除所有 FFmpeg 临时目录?","restartHint": "已保存。重启 Motrix 后,已启用的插件才能检测到更改。","restartNow": "立即重启","validation": {"fileMissing": "该路径不存在。"},- "applyHint": "修改自定义路径后需点击“保存”。媒体下载会读取当前 FFmpeg 路径,无须重启 Motrix;请在浏览器扩展中重新扫描以刷新支持状态。",+ "applyHint": "保存后用于新媒体下载;请在浏览器扩展中重新扫描以更新支持状态。","savedTitle": "FFmpeg 配置已保存","desktopSavedHint": "新媒体下载会读取保存的路径。已启用的插件需要重启 Motrix 才能检测到此次更改。","pipelineUnavailable": "媒体下载功能当前不可用。",@@ -1949,7 +2010,8 @@"missing": "缺少必要文件,请从当前位置运行 AppImage 并修复。","io": "操作失败,请检查磁盘访问权限后重试修复。"}- }+ },+ "description": "浏览器、默认应用与工具"},"validation": {"rangeHint": "范围:{{min}}–{{max}}。",@@ -1974,7 +2036,8 @@"address": "地址 {{number}}","addressDraft": "新地址","required": "请先填写地址。",- "time": "请使用 24 小时制填写,例如 23:00。"+ "time": "请使用 24 小时制填写,例如 23:00。",+ "loadFailed": "无法加载设置,请重试。"},"feedback": {"syncFailedTitle": "设置已保存,但界面更新失败",@@ -2569,6 +2632,7 @@"clearAll": "清空","empty": "暂无通知","emptyDesc": "下载活动和重要应用提醒会显示在这里",+ "unreadDotAria": "有未读通知","unreadBadgeAria_other": "{{count}} 条未读通知","rowUnreadAria": "{{title}}(未读)","toastRegionAria": "通知",@@ -2654,11 +2718,11 @@}},"directoryPreferences": {- "sectionDescription": "设置常用目录并管理最近使用的下载目录。",+ "sectionDescription": "把常用文件夹放在这里,下载时方便选择。","manage": "管理目录","manageDescription": "设置常用目录,管理最近使用的目录。","title": "管理目录",- "description": "更改将在保存后生效。移除记录不会删除文件夹或下载任务。",+ "description": "从列表移除文件夹不会删除文件夹或其中的文件。","favorites": "常用目录","recent": "最近使用","addFavorite": "添加常用目录",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex b2338e64..97c8baad 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1171,12 +1171,21 @@}},"general": {- "launchAtStartup": "登入時開啟",+ "launchAtStartup": "登入時啟動","launchAtStartupDesc": "登入時自動啟動 Motrix。","showMainWindowAtLogin": "登入時顯示視窗","showMainWindowAtLoginDesc": "選擇「{{mode}}」時不顯示。","defaultSaveDir": "預設下載資料夾","defaultSaveDirDesc": "除非個別任務另有指定,新的下載會儲存在這裡。",+ "inAppNotifications": "應用程式內通知",+ "inAppNotificationsDesc": "選擇要顯示的下載通知。應用程式故障提醒一律開啟。",+ "notifyInAppOnComplete": "顯示下載完成通知",+ "notifyInAppOnError": "顯示下載失敗通知",+ "notificationBadgeStyle": "未讀標記",+ "notificationBadgeCount": "數量",+ "notificationBadgeDot": "圓點",+ "notificationBadgeHidden": "隱藏",+ "systemNotifications": "系統通知","notifyOnComplete": "下載完成時通知","notifyOnCompleteDesc": "任務完成時顯示系統通知。","autofillClipboardLinks": "新增任務時自動填入剪貼簿連結",@@ -1184,7 +1193,25 @@"notifyOnError": "失敗時通知","notifyOnErrorDesc": "視窗在背景時,下載失敗會顯示系統通知。","warnBeforeQuit": "結束前確認",- "warnBeforeQuitDesc": "仍有下載進行時,結束前要求確認。"+ "warnBeforeQuitDesc": "有下載進行時,結束前提醒。",+ "notificationBadgeDesc": "顯示在通知中心圖示上。",+ "notificationOff": "不通知",+ "notificationSystem": "系統通知",+ "notificationInApp": "應用程式內通知",+ "notificationBoth": "兩者皆通知",+ "startupAndQuitting": "啟動與結束",+ "runMode": "應用程式顯示位置",+ "runModeStandard": "Dock 和選單列",+ "runModeTray": "僅選單列",+ "runModeHideTray": "僅 Dock",+ "lightweightMode": "關閉視窗後節省記憶體",+ "lightweightModeDesc": "下載會繼續;重新開啟稍慢,未儲存的輸入會清除。",+ "notifications": "通知",+ "notificationsDesc": "應用程式故障提醒始終開啟。",+ "downloadCompleted": "下載完成",+ "downloadFailed": "下載失敗",+ "description": "啟動、結束與通知",+ "desktopOnly": "啟動和通知偏好可在桌面應用程式中設定。"},"appearance": {"theme": "主題",@@ -1192,18 +1219,18 @@"themeLight": "淺色","themeDark": "深色","language": "語言",- "traySpeedometer": "在系統匣顯示即時速度",- "traySpeedometerDesc": "僅限 macOS,在系統匣圖示旁顯示目前速度。",+ "traySpeedometer": "在選單列顯示速度",+ "traySpeedometerDesc": "在應用程式圖示旁顯示下載和上傳速度。","trayIconColor": "系統匣圖示色彩",- "trayIconColorDesc": "面板佈景主題可能與 Motrix 不同。深色面板請選擇淺色圖示,淺色面板請選擇深色圖示。",+ "trayIconColorDesc": "選擇在系統面板上容易看清的顏色。","trayIconColorAuto": "跟隨應用程式主題","trayIconColorLight": "淺色圖示(深色面板)","trayIconColorDark": "深色圖示(淺色面板)","reduceMotion": "減少動畫",- "reduceMotionDesc": "減少介面動畫,包括下載頁的玻璃動態效果。",- "liquidGlassEffect": "啟用液態玻璃效果",- "liquidGlassEffectDesc": "為下載頁工具列使用半透明玻璃效果。",- "liquidGlassEffectMacDesc": "macOS 26 及以上同時使用原生視窗玻璃,變更後會重新建立主視窗。",+ "reduceMotionDesc": "減少介面中的動態效果。",+ "liquidGlassEffect": "液態玻璃",+ "liquidGlassEffectDesc": "讓下載工具列呈現半透明玻璃效果。",+ "liquidGlassEffectMacDesc": "macOS 26 及以上也會套用至視窗;變更後視窗會重新開啟。","runMode": "顯示位置","runModeStandard": "Dock 與選單列","runModeTray": "僅選單列",@@ -1215,11 +1242,11 @@"lightweightMode": "輕量模式","lightweightModeDesc": "關閉視窗後節省記憶體,下載不受影響。重新開啟稍慢,未儲存的輸入會清除。","byteUnitSystem": "大小與速度單位",- "byteUnitSystemDesc": "用於檔案大小與傳輸速度的顯示。",+ "byteUnitSystemDesc": "選擇檔案大小和速度的顯示單位。","byteUnitDecimal": "十進位(MB、GB · 1000)","byteUnitBinary": "二進位(MiB、GiB · 1024)","byteUnitSystemDefault": "跟隨系統({{units}})",- "sidebarColor": "顏色",+ "sidebarColor": "主題色","sidebarColors": {"blue": "冰藍","violet": "鳶紫",@@ -1230,26 +1257,38 @@"cyan": "湖青","gray": "淡灰","auto": "自動"- }+ },+ "themeAndEffects": "主題與效果",+ "languageAndDisplay": "語言與顯示",+ "menuBar": "選單列",+ "description": "主題、語言與顯示",+ "systemTray": "系統匣"},"advanced": {"rpc": {"title": "RPC","port": "RPC 連接埠",- "portDesc": "aria2 RPC 伺服器監聽的 TCP 連接埠。需要重新啟動。",- "secret": "RPC 密鑰",- "secretDesc": "用戶端用於驗證的 Token。點選「產生」可建立高強度隨機值。"+ "portDesc": "修改後需重新啟動。",+ "secret": "RPC 金鑰",+ "secretDesc": "用於驗證 RPC 連線。"},"persistence": {- "title": "SQLite 持續性",- "enable": "啟用 SQLite 持續性",- "enableDesc": "將工作階段、進度與歷程記錄儲存在單一 SQLite 資料庫。停用後會還原為上游 aria2 行為 (文字工作階段與 .aria2 側邊檔案)。",- "dbPath": "資料庫路徑",- "dbPathDesc": "留空可使用其他引擎設定檔旁的預設位置。",- "dbPathPlaceholder": "預設值:<config>/aria2.db",- "historyLimit": "歷程記錄保留數量",- "historyLimitDesc": "下載歷程記錄保留的最大列數。-1 = 無限制;0 = 僅記憶體 (不儲存至資料庫)。"- }+ "title": "進度與恢復",+ "enable": "儲存恢復資料",+ "enableDesc": "儲存用於重新啟動後繼續下載的資料。",+ "dbPath": "恢復資料檔案",+ "dbPathDesc": "留空則使用預設位置。",+ "dbPathPlaceholder": "預設位置",+ "historyLimit": "已完成下載的恢復記錄",+ "historyLimitDesc": "不影響下載清單和已下載的檔案。",+ "historyKeepAll": "全部保留",+ "historyKeepRecent": "保留最近…",+ "historySessionOnly": "不保留",+ "historyCount": "保留筆數",+ "historyCountHint": "較早的恢復記錄會被移除。",+ "historyCountPositive": "請輸入大於 0 的數量。"+ },+ "description": "RPC、進度與恢復"},"about": {"appIconAlt": "Motrix 應用程式圖示",@@ -1262,7 +1301,7 @@"idleTitle": "讓 Motrix 保持最新","idle": "已安裝版本 {{version}}。現在檢查,或讓 Motrix 在開啟時檢查。","unsupportedTitle": "無法自動更新",- "unsupported": "此 Motrix 建置版本不支援自動更新。請從官方網站下載最新版本。",+ "unsupported": "目前版本不支援自動更新,請至官網下載最新版。","check": "檢查更新","checkAction": "檢查","checking": "檢查中…",@@ -1291,10 +1330,10 @@"automaticChecksDescription": "Motrix 開啟時","automaticChecksError": "無法儲存此設定","channelLabel": "更新通道",- "channelDescription": "選擇 Motrix 要檢查哪些應用程式版本。",+ "channelDescription": "選擇穩定版本,或透過測試版本體驗新功能。","channelStable": "穩定版","channelBeta": "測試版",- "channelBetaWarning": "測試版可能較不穩定。您會收到測試版及後續的穩定版。切回穩定版會停止收到後續測試版,但不會自動安裝較舊版本。",+ "channelBetaWarning": "測試版可能不夠穩定,也會接收後續穩定版。切回穩定版後不再接收測試版,不會自動降級。","channelSaveError": "無法儲存更新通道。請再試一次。"},"details": {@@ -1319,84 +1358,89 @@},"bittorrent": {"trackers": {- "autoSync": "自動同步",- "autoSyncDesc": "依排程自動同步 Tracker 清單",- "syncInterval": "同步間隔",- "syncIntervalDesc": "同步 Tracker 的頻率 (小時,1 至 168)",- "enableProbe": "啟用探測",- "enableProbeDesc": "加入 Torrent 前測試 Tracker 健康狀態",- "probeTimeout": "探測逾時",- "probeTimeoutDesc": "等待探測回應的最長時間 (毫秒,1000 至 30000)",- "healthyThreshold": "健康門檻",- "healthyThresholdDesc": "視為健康的最大回應時間 (毫秒,500 至 10000)",+ "autoSync": "自動更新 Tracker 清單",+ "autoSyncDesc": "從已加入的來源取得最新清單。",+ "syncInterval": "更新間隔(小時)",+ "syncIntervalDesc": "可設為 1–168 小時。",+ "enableProbe": "檢查 Tracker 可用性",+ "enableProbeDesc": "使用前檢查 Tracker 是否能正常回應。",+ "probeTimeout": "檢查逾時(毫秒)",+ "probeTimeoutDesc": "等候回應的最長時間,1,000–30,000 毫秒。",+ "healthyThreshold": "慢回應判定時間(毫秒)",+ "healthyThresholdDesc": "回應超過此時間會標記為緩慢,500–10,000 毫秒。","minSuccessRate": "最低成功率",- "minSuccessRateDesc": "保留 Tracker 所需的最低成功比例 (0 至 1)",- "maxTrackerCount": "Tracker 數量上限",- "maxTrackerCountDesc": "每個 Torrent 套用 Tracker 數量上限 (5 至 200)",+ "minSuccessRateDesc": "使用達到此成功率的 Tracker,0.5 表示 50%。",+ "maxTrackerCount": "每個任務的 Tracker 數量",+ "maxTrackerCountDesc": "最多使用的 Tracker 數量,5–200。","title": "Tracker",- "manageSourcesHint": "在側邊欄的「Tracker」管理 Tracker 來源清單。",- "blacklistMovedInfo": "Tracker 封鎖清單現已移至側邊欄的「Tracker」頁面 →「封鎖清單」分頁管理。"+ "manageSourcesHint": "在 Tracker 頁面管理來源。",+ "blacklistMovedInfo": "在 Tracker → 黑名單中管理封鎖的位址。"},"geoip": {- "title": "GeoIP 資料庫",- "enable": "啟用 IP 對應國家查詢",- "enableDesc": "在對等節點分頁將 IP 位址解析為國家代碼。資料庫會依需求下載並儲存在使用者資料目錄。",+ "title": "節點位置",+ "enable": "顯示國家或地區",+ "enableDesc": "在節點清單中顯示位置,需要時會下載位置資料。","lastUpdated": "上次更新","neverUpdated": "從未","updateNow": "立即更新","updating": "更新中…",- "source": "來源",- "sourceDesc": "選擇下載 GeoLite2-Country.mmdb 檔案的來源。",+ "source": "位置資料來源",+ "sourceDesc": "選擇位置資料的下載來源。","source.loyalsoldier": "Loyalsoldier (社群)","source.p3terx": "P3TERX (社群鏡像)","source.maxmind": "MaxMind (官方)","source.custom": "自訂 URL",- "maxmindUnsupported": "第 2.1 階段",- "customUrl": "自訂 URL",+ "maxmindUnsupported": "暫不支援",+ "customUrl": "自訂下載位址","customUrlPlaceholder": "https://example.com/GeoLite2-Country.mmdb","autoUpdate": "自動更新",- "autoUpdateDesc": "約每週檢查一次是否有新的資料庫。",- "status.loaded": "已載入",- "status.notDownloaded": "尚未下載資料庫",+ "autoUpdateDesc": "大約每週檢查一次位置資料更新。",+ "status.loaded": "已就緒",+ "status.notDownloaded": "尚未下載位置資料","status.downloading": "下載中…",- "status.error": "更新失敗"+ "status.error": "更新失敗",+ "customUrlDesc": "填寫 .mmdb 格式國家資料檔案的連結。",+ "saveBeforeUpdate": "請先儲存設定,再更新位置資料。",+ "updateFailed": "無法更新位置資料,請重試。"},"listen": {- "title": "監聽",+ "title": "傳入連線","listenPort": "BT 監聽連接埠",- "listenPortDesc": "aria2 繫結以接收對等節點連線的連接埠。",+ "listenPortDesc": "用於接收其他使用者的連線。","dhtListenPort": "DHT 監聽連接埠",- "dhtListenPortDesc": "aria2 繫結 DHT 使用的連接埠。",+ "dhtListenPortDesc": "用於透過 DHT 尋找其他使用者。","dhtEnabled": "啟用 DHT",- "dhtEnabledDesc": "供無 Tracker Torrent 使用的分散式雜湊表。"+ "dhtEnabledDesc": "無須依賴 Tracker 也能尋找其他使用者。"},"peers": {"title": "對等節點","btMaxPeers": "每個 Torrent 的對等節點數量上限",- "btMaxPeersDesc": "同時連線的對等節點數量上限。",+ "btMaxPeersDesc": "單一任務同時連線的節點數量上限。","btEnableLpd": "區域網路對等節點探索",- "btEnableLpdDesc": "在區域網路尋找對等節點。",- "magnetFileSelection": "Magnet 中繼資料載入後開啟檔案選擇",- "magnetFileSelectionDesc": "收到 Magnet 中繼資料後顯示檔案選擇器。",- "magnetFileSelectionAutoDownload": "選擇檔案逾時後自動下載全部檔案",- "magnetFileSelectionAutoDownloadDesc": "未在限定時間內確認檔案選擇,將下載全部檔案到任務儲存目錄;關閉視窗或 WebUI 後仍會生效。",- "magnetFileSelectionTimeoutSeconds": "選擇檔案等待時間(秒)",- "magnetFileSelectionTimeoutSecondsDesc": "從中繼資料解析完成、進入待選檔案狀態開始計時。修改時長也會套用到已經等待選擇的任務。",+ "btEnableLpdDesc": "尋找區域網路內分享檔案的裝置。",+ "magnetFileSelection": "下載前選擇檔案",+ "magnetFileSelectionDesc": "磁力連結載入後,選擇要下載的檔案。",+ "magnetFileSelectionAutoDownload": "逾時後下載全部檔案",+ "magnetFileSelectionAutoDownloadDesc": "超過下方等候時間後開始下載;關閉視窗或瀏覽器後仍會生效。",+ "magnetFileSelectionTimeoutSeconds": "選擇檔案等候時間(秒)",+ "magnetFileSelectionTimeoutSecondsDesc": "從檔案清單載入完成時計時,也適用於正在等候的任務。","magnetFileSelectionTimeoutInvalid": "請輸入 {{min}} 至 {{max}} 秒之間的整數。"},"seeding": {"title": "做種","seedRatio": "分享率上限",- "seedRatioDesc": "分享率超過此值後停止做種。0 = 無限制。",+ "seedRatioDesc": "上傳量 ÷ 下載量,達到後停止做種;0 表示不限。","seedTime": "做種時間上限 (分鐘)",- "seedTimeDesc": "做種達到此分鐘數後停止。0 = 無限制。套用於新建或重新做種的任務。"- }+ "seedTimeDesc": "0 表示不限,適用於新任務和重新開始做種的任務。"+ },+ "newMagnetTasks": "新增磁力任務",+ "description": "磁力連結、做種與 Tracker"},"downloads": {"performance": {"title": "效能",- "profile": "效能檔位",- "profileDesc": "選擇 Motrix 的下載強度。",+ "profile": "下載效能",+ "profileDesc": "平衡下載速度與資源使用。","learnMore": "瞭解更多","metrics": {"connections": "連線數上限",@@ -1408,7 +1452,7 @@"profiles": {"auto": {"label": "自動",- "desc": "顯示預設值,實際依磁碟和檔案大小調整。"+ "desc": "依磁碟和檔案大小自動調整,下方為預設值。"},"balanced": {"label": "均衡",@@ -1420,102 +1464,102 @@},"maximum": {"label": "極限",- "desc": "使用最大並行;部分伺服器可能拒絕。"+ "desc": "使用更多連線,部分伺服器可能會限制連線數。"},"custom": {"label": "自訂","desc": "設定連線數、分段大小和快取。"}},- "maxConcurrentDownloads": "同時下載數量上限",- "maxConcurrentDownloadsDesc": "可平行下載的任務數量。",+ "maxConcurrentDownloads": "同時下載任務數",+ "maxConcurrentDownloadsDesc": "超出的任務會排隊等候。","maxConnectionPerServer": "每台伺服器的連線數上限","maxConnectionPerServerDesc": "每個檔案對同一伺服器的連線上限。","split": "單一檔案連線數上限",- "splitDesc": "實際連線數可能更少。",+ "splitDesc": "下載單一檔案時使用的連線數。","minSplitSize": "最小分段大小(MiB)","minSplitSizeDesc": "小於此值兩倍的分段不再拆分。"},"reliability": {- "title": "網路可靠性",+ "title": "連線與重試","userAgent": "User-Agent",- "userAgentDesc": "隨 HTTP 要求傳送。",- "connectTimeout": "連線逾時 (秒)",- "connectTimeoutDesc": "等待 TCP 連線的時間。",- "socketTimeout": "Socket 逾時 (秒)",- "socketTimeoutDesc": "等待 Socket 資料的時間。",- "maxTries": "重試次數上限",- "maxTriesDesc": "0 = 不重試。",- "retryWait": "重試等待時間 (秒)",- "retryWaitDesc": "每次重試之間的暫停時間。",- "lowestSpeedLimit": "低速連線門檻 (KiB/s)",- "lowestSpeedLimitDesc": "低於此速度時中斷連線。0 = 停用。"+ "userAgentDesc": "向網站識別下載工具,依網站要求修改。",+ "connectTimeout": "連線等候時間(秒)",+ "connectTimeoutDesc": "等候伺服器連線的最長時間。",+ "socketTimeout": "資料等候時間(秒)",+ "socketTimeoutDesc": "連線後未收到資料的最長等候時間。",+ "maxTries": "最多嘗試次數",+ "maxTriesDesc": "包含首次嘗試;0 表示不限次數。",+ "retryWait": "重試間隔(秒)",+ "retryWaitDesc": "失敗後等多久再試。",+ "lowestSpeedLimit": "最低連線速度(KiB/s)",+ "lowestSpeedLimitDesc": "低於此速度時中斷連線;0 表示關閉。"},"disk": {"fileDeletionMode": "刪除任務檔案時","fileDeletionTrash": "移至資源回收筒","fileDeletionPermanent": "直接刪除",- "fileDeletionTrashDesc": "適用於移除任務時一併刪除檔案。清空資源回收筒後才會釋放磁碟空間。",- "fileDeletionPermanentDesc": "檔案將直接刪除,無法從資源回收筒還原。",- "title": "磁碟與工作階段",- "fileAllocation": "檔案配置",- "fileAllocationDesc": "aria2 為新檔案保留磁碟空間的方式。",- "fileAllocationNone": "無",+ "fileDeletionTrashDesc": "清空垃圾桶後才會釋放磁碟空間。",+ "fileDeletionPermanentDesc": "刪除後無法從垃圾桶復原。",+ "title": "磁碟與檔案",+ "fileAllocation": "磁碟空間預留",+ "fileAllocationDesc": "下載開始前,為檔案預留空間。",+ "fileAllocationNone": "不預留","fileAllocationPrealloc": "預先配置",- "fileAllocationTrunc": "截斷",- "fileAllocationFalloc": "配置",+ "fileAllocationTrunc": "設定檔案大小",+ "fileAllocationFalloc": "系統配置","modifiedTime": "檔案修改時間",- "modifiedTimeDesc": "選擇 HTTP 與 FTP 下載完成後使用的檔案修改時間。",- "modifiedTimeLocal": "本機修改時間",- "modifiedTimeServer": "伺服器修改時間",+ "modifiedTimeDesc": "適用於下載完成的 HTTP 和 FTP 檔案。",+ "modifiedTimeLocal": "下載時間",+ "modifiedTimeServer": "伺服器提供的時間","diskCache": "磁碟快取 (MiB)",- "diskCacheDesc": "記憶體內的寫入快取。",- "sessionSaveInterval": "工作階段儲存間隔 (秒)",- "sessionSaveIntervalDesc": "aria2 儲存下載狀態的頻率。"+ "diskCacheDesc": "寫入磁碟前暫存檔案資料的記憶體。",+ "sessionSaveInterval": "進度儲存間隔(秒)",+ "sessionSaveIntervalDesc": "儲存越頻繁,意外退出時遺失的進度越少。"},"magnet": {"title": "Magnet",- "magnetResolveTimeout": "Magnet 解析逾時 (秒)",- "magnetResolveTimeoutDesc": "放棄前等待中繼資料的時間。"+ "magnetResolveTimeout": "磁力連結載入時限(秒)",+ "magnetResolveTimeoutDesc": "等候檔案清單載入的最長時間。"},"speedLimit": {"title": "速度限制","titleDesc": "選擇 Motrix 在標準、低速與自動模式下使用連線的方式。","modeSection": "速度模式","modeSectionDesc": "選擇 Motrix 應如何使用您的連線。",- "turtle": "目前模式",+ "turtle": "速度模式","turtleDesc_off": "使用標準速度限制。","turtleDesc_on": "立即使用低速限制,為其他應用程式保留頻寬。","turtleDesc_auto": "依時間與連線頻寬自動調整速度。","turtle_off": "標準","turtle_on": "低速","turtle_auto": "自動",- "baseSection": "標準速度限制",+ "baseSection": "一般限速","baseSectionDesc": "用於日常下載,且在每個模式下都會遵守。",- "baseDownload": "標準下載限制",+ "baseDownload": "下載","baseDownloadDesc": "日常下載的最高速度。",- "baseUpload": "標準上傳限制",+ "baseUpload": "上傳","baseUploadDesc": "日常上傳的最高速度。","unlimited": "不限速","setUnlimited": "設為不限速",- "standardLimit": "沿用標準限制",+ "standardLimit": "沿用一般上限","useStandardLimit": "沿用標準限制",- "altSection": "低速限制",+ "altSection": "低速限速","altSectionDesc": "用於低速模式或排程規則。這些限制只能低於標準限制。",- "altDownload": "低速下載限制",+ "altDownload": "下載","altDownloadDesc": "低速模式啟用時的最高下載速度。",- "altUpload": "低速上傳限制",+ "altUpload": "上傳","altUploadDesc": "低速模式啟用時的最高上傳速度。","autoSection": "自動規則","autoSectionDesc": "這些規則只會在自動模式中套用。","autoSchedule": "排程降速",- "scheduleEnabled": "依排程使用低速限制",+ "scheduleEnabled": "定時啟用低速模式","scheduleEnabledDesc": "在選取的日期與時間切換為低速限制。","scheduleFrom": "開始","scheduleTo": "結束","scheduleTimeFormat": "24 小時制 (HH:mm)",- "scheduleDays": "啟用日期",- "scheduleDaysHint": "未選取特定日期時,每天都會執行。結束時間早於開始時間表示隔日結束。",+ "scheduleDays": "重複日期",+ "scheduleDaysHint": "結束時間早於開始時間時,持續至次日。","weekdays": {"sun": {"short": "日",@@ -1547,14 +1591,14 @@}},"autoAdaptive": "為其他應用程式保留頻寬",- "adaptiveEnabled": "避免用盡全部連線頻寬",- "adaptiveEnabledDesc": "依您的連線頻寬自動限制 Motrix。",- "linkDown": "連線下載頻寬",+ "adaptiveEnabled": "為其他應用程式預留頻寬",+ "adaptiveEnabledDesc": "依下方填寫的寬頻速度計算限速。",+ "linkDown": "寬頻下載速度","linkDownDesc": "網際網路連線可達的下載速度。",- "linkUp": "連線上傳頻寬",+ "linkUp": "寬頻上傳速度","linkUpDesc": "網際網路連線可達的上傳速度。",- "fillFromPeak": "依近期速度估算",- "fillFromPeakHint": "使用 Motrix 最近觀察到的最高速度。",+ "fillFromPeak": "估算寬頻速度",+ "fillFromPeakHint": "依近期最高下載和上傳速度估算。","estimateEmpty": "尚無可用的速度歷程記錄。請完成一次不限速下載,或手動輸入頻寬。","estimateSuccess": "已依近期速度填入連線頻寬。","estimateError": "無法讀取近期速度歷程記錄。請手動輸入頻寬。",@@ -1572,78 +1616,95 @@"adaptiveRulePending": "輸入連線頻寬後,為其他應用程式保留 {{reserved}}% 的頻寬","ruleSeparator": ",並且","autoRules": "Motrix 將{{rules}}。",- "lowerWins": "多項限制同時套用時,Motrix 會採用較低的值。"- }- }+ "lowerWins": "多項限速同時生效時取最低值。"+ },+ "bandwidthUsed": "Motrix 最多使用 {{motrix}}%。",+ "bandwidthPending": "填入下載和上傳速度後生效。"+ },+ "newTasks": "新增任務",+ "defaultDownloadFolder": "預設儲存位置",+ "autofillFromClipboard": "自動填入剪貼簿連結",+ "fillInLinksWhenOpeningNewTask": "新增任務時,自動填入已複製的連結。",+ "saveFolders": "儲存位置",+ "description": "檔案、下載速度與連線"},"network": {"dns": {"title": "DNS","mode": "DNS 解析方式",- "modeDesc": "下載引擎解析網域名稱的方式。",+ "modeDesc": "下載時尋找伺服器位址的方式。","modeAuto": "自動",- "modeSystem": "系統解析器",- "modeEngine": "引擎內建解析器"+ "modeSystem": "系統 DNS",+ "modeEngine": "內建 DNS"},"proxy": {"title": "Proxy","enable": "啟用 Proxy",- "enableDesc": "透過 Proxy 伺服器傳送流量。",+ "enableDesc": "讓下方選取的連線透過代理。","server": "伺服器","protocol": "通訊協定",- "host": "主機",+ "host": "伺服器位址","hostPlaceholder": "proxy.example.com","port": "連接埠",- "auth": "驗證",- "authDesc": "需要登入的 Proxy 會要求驗證。",- "user": "使用者",+ "auth": "代理登入",+ "authDesc": "代理需要使用者名稱和密碼時開啟。",+ "user": "使用者名稱","password": "密碼","showPassword": "顯示密碼","hidePassword": "隱藏密碼",- "bypass": "略過清單",- "bypassDesc": "每行填寫一個精確主機或 CIDR。使用 `.local` 這類前導點比對子網域(不含根網域);下載 Proxy 不支援 `*` 萬用字元。",- "bypassScopeNote": "僅下載與應用程式更新",- "scopes": "套用至",+ "bypass": "不使用代理的位址",+ "bypassDesc": "每行填寫一個網域、IP 或 CIDR。開頭加 . 僅比對子網域。檔案下載不支援 * 萬用字元。",+ "bypassScopeNote": "僅下載檔案和更新應用程式",+ "scopes": "代理用途","scopesDesc": "選擇哪些流量要通過 Proxy。",- "scopeDownload": "下載",- "scopeDownloadDesc": "BT 僅代理 HTTP(S);Peer、DHT 與 UDP Tracker 直接連線。",- "scopeUpdateApp": "應用程式更新檢查",- "scopeUpdateAppDesc": "Electron 自動更新程式的 HTTPS 呼叫。",- "scopeUpdateTrackers": "Tracker 同步",- "scopeUpdateTrackersDesc": "僅同步 Tracker 清單,不會代理 BT 流量。",+ "scopeDownload": "下載檔案",+ "scopeDownloadDesc": "BT 僅代理 HTTP(S);節點、DHT 和 UDP Tracker 直接連線。",+ "scopeUpdateApp": "更新應用程式",+ "scopeUpdateAppDesc": "透過代理檢查 Motrix 更新。",+ "scopeUpdateTrackers": "更新 Tracker 清單",+ "scopeUpdateTrackersDesc": "透過代理更新 Tracker 清單,不影響 BT 下載連線。","importFromSystem": "從系統匯入","importedToast": "已匯入系統 Proxy:{{host}}:{{port}}",- "noSystemProxy": "未設定系統 Proxy。"+ "noSystemProxy": "未設定系統 Proxy。",+ "bypassPlaceholder": "localhost\n127.0.0.1\n.local",+ "scopeHint": "BT 節點、DHT 和 UDP Tracker 仍直接連線。",+ "scopeNone": "未選取",+ "scopeChoose": "選擇…",+ "scopeSeparator": "、"},"nat": {- "title": "NAT 連接埠對應",+ "title": "連接埠對映(NAT)","enable": "啟用連接埠對應",- "enableDesc": "自動在路由器開啟傳入的 BT/DHT 連接埠。",+ "enableDesc": "請求路由器開放 BitTorrent 設定中的連接埠。","preferredProtocol": "偏好的通訊協定",- "mappingTtl": "對應 TTL (秒)",- "btPortHint": "對應會套用至 BitTorrent 設定的 BT/DHT 連接埠。"+ "mappingTtl": "對映有效期(秒)",+ "btPortHint": "對應會套用至 BitTorrent 設定的 BT/DHT 連接埠。",+ "automatic": "自動"},"stun": {"title": "NAT 類型偵測",- "privacyHint": "會向第三方 STUN 伺服器傳送查詢。",- "enable": "透過 STUN 啟用偵測",+ "privacyHint": "使用第三方 STUN 伺服器。",+ "enable": "偵測 NAT 類型","servers": "STUN 伺服器",- "empty": "未設定 STUN 伺服器。",+ "empty": "至少新增一個 STUN 伺服器。","addServer": "新增 STUN 伺服器"},"reachability": {- "title": "連接埠可連通性",- "privacyHint": "會向第三方 HTTPS 端點傳送探測。",- "enable": "從外部服務探測連接埠",- "endpoints": "端點 (HTTPS)",- "empty": "沒有可連通性端點。",- "addEndpoint": "新增端點"+ "title": "外部網路連線檢查",+ "privacyHint": "透過第三方服務檢查外部網路能否連線。",+ "enable": "檢查入站連接埠",+ "endpoints": "檢查服務位址(HTTPS)",+ "empty": "至少新增一個檢查服務。",+ "addEndpoint": "新增檢查服務"},"diagnostic": {- "title": "自動診斷",- "enable": "依排程執行診斷",- "interval": "間隔 (秒)"- }+ "title": "自動網路檢查",+ "enable": "定期檢查",+ "interval": "檢查間隔(秒)",+ "enableDesc": "定期執行上方已開啟的偵測。"+ },+ "description": "代理、DNS 與連線檢查",+ "diagnostics": "網路診斷"},"common": {"browse": "瀏覽…",@@ -1661,14 +1722,14 @@},"integration": {"system": {- "title": "系統通訊協定",+ "title": "預設應用程式","protocolMagnet": "使用 Motrix 開啟 Magnet 連結","protocolMagnetDesc": "從瀏覽器在 Motrix 開啟 Magnet 連結。","torrentAssociation": "使用 Motrix 開啟 .torrent 檔案",- "torrentAssociationDesc": "設定後,按兩下 .torrent 檔案即可在 Motrix 開啟。",+ "torrentAssociationDesc": "按兩下種子檔案時,用 Motrix 開啟。","torrentAssociationMacDesc": "在 Finder 中,以右鍵按一下任一 .torrent 檔案 → 取得資訊 → 打開檔案的應用程式 → 選擇 Motrix → 全部更改…","defaultAssociationsWindows": "種子檔案和 Magnet 連結的預設應用程式",- "defaultAssociationsWindowsDesc": "在 Windows 預設應用程式中為 .torrent 檔案和 Magnet 連結選擇 Motrix。使用 Motrix 安裝程式安裝後,Motrix 才會顯示在清單中。",+ "defaultAssociationsWindowsDesc": "在 Windows 設定中選擇用 Motrix 開啟種子檔案和磁力連結。需先安裝 Motrix。","torrentFiles": ".torrent 檔案","magnetLinks": "Magnet 連結","associationStatusLabel": "目前的 Windows 預設應用程式狀態",@@ -1706,8 +1767,8 @@},"browser": {"title": "瀏覽器擴充功能",- "masterSwitch": "從瀏覽器擴充功能傳送下載",- "masterSwitchDesc": "安裝 Motrix 瀏覽器擴充功能後,可一鍵從任何網頁傳送下載。",+ "masterSwitch": "連接瀏覽器擴充功能",+ "masterSwitchDesc": "安裝瀏覽器擴充功能後,將網頁下載傳送至 Motrix。","install": {"chrome": "Chrome","edge": "Microsoft Edge",@@ -1748,7 +1809,7 @@"pairUnavailable": "此配對要求已不再待處理,請從瀏覽器擴充功能重新配對。","trustedExtensions": "受信任的擴充功能","trustedSummary": "共 {{count}} 個",- "trustedGuidance": "若安裝了 Motrix 官方以外的下載擴充功能,請在這裡貼上其提供的擴充功能 ID。通常不需要這麼做。",+ "trustedGuidance": "使用其他可信擴充功能時,新增開發者提供的擴充功能 ID。","trustedEmpty": "尚無內容。","headerId": "擴充功能 ID","headerBrowser": "瀏覽器",@@ -1772,7 +1833,7 @@"title": "命令列工具","tool": {"title": "Motrix 命令列工具",- "description": "在任何終端機執行 `motrix` 以控制此 Motrix。",+ "description": "在終端機執行 motrix,即可控制本應用程式。","managerLabel": "套件管理員","commandLabel": "安裝命令","copyCommand": "複製安裝命令",@@ -1805,7 +1866,7 @@"manager": "安裝來源","unknown": "未知"},- "successGuidance": "開啟新的終端機,然後執行 `motrix --help`。",+ "successGuidance": "開啟新的終端機,然後執行 motrix --help。","diagnostics": {"show": "顯示詳細資料","hide": "隱藏詳細資料"@@ -1819,16 +1880,16 @@"permission": "套件管理員無法寫入全域安裝位置。請使用 Node.js 版本管理工具或使用者可寫入的前綴,請勿使用 sudo。","network": "套件管理員無法連線至 registry。請檢查網路或 registry 設定後再試一次。","timeout": "安裝時間過長,已停止。請檢查網路後再試一次。",- "pathMissing": "套件已安裝,但 PATH 中找不到 `motrix`。請開啟新的終端機或將回報的安裝目錄加入 PATH。",- "pathShadowed": "PATH 中較前面的位置似乎有另一個 `motrix` 執行檔。請移除舊項目或修正 PATH 後再次檢查。",- "verifyFailed": "安裝程式已完成,但 Motrix 無法驗證目前使用的 `motrix` 執行檔。",- "installFailed": "套件管理員無法安裝 `@motrix/cli`。請檢視詳細資料後重試,或手動執行命令。",+ "pathMissing": "套件已安裝,但 PATH 中找不到 motrix。請開啟新的終端機或將回報的安裝目錄加入 PATH。",+ "pathShadowed": "PATH 中較前面的位置似乎有另一個 motrix 執行檔。請移除舊項目或修正 PATH 後再次檢查。",+ "verifyFailed": "安裝程式已完成,但 Motrix 無法驗證目前使用的 motrix 執行檔。",+ "installFailed": "套件管理員無法安裝 @motrix/cli。請檢視詳細資料後重試,或手動執行命令。","unknown": "Motrix 無法檢查命令列工具。請再試一次或手動執行已複製的命令。"}},"remote": {"title": "已配對的遠端工具",- "description": "本機 CLI 會自動連線,不需要配對。只有遠端或無頭 Motrix 執行個體才需執行 `motrix pair`。",+ "description": "本機工具會自動連線;連接其他電腦或伺服器時,執行 motrix pair。","empty": "沒有已配對的遠端工具。","lastActive": "上次使用","neverActive": "從未使用",@@ -1847,11 +1908,11 @@"deny": "拒絕","expiresIn": "將於 {{time}} 後到期"},- "pairUnavailable": "此配對要求已不再待處理,請重新執行 `motrix pair`。"+ "pairUnavailable": "此配對要求已不再待處理,請重新執行 motrix pair。"},"media": {"title": "媒體工具",- "desc": "檢查 FFmpeg 可用性與媒體外掛程式限制",+ "desc": "使用 FFmpeg 合併或轉換媒體檔案。","notDetected": "未偵測到 FFmpeg","refresh": "重新整理","binaryPath": "自訂 FFmpeg 路徑",@@ -1891,10 +1952,10 @@"unconfigured": "未設定","version_mismatch": "不支援"},- "stagingMB": "暫存工作區上限 (MB)",- "stagingMBDesc": "每個外掛程式與任務各自使用。供 FFmpeg 寫入中繼檔案時使用。預設為 4096 MB。",+ "stagingMB": "暫存檔案空間上限(MB)",+ "stagingMBDesc": "每個外掛、每個任務處理媒體時可用的暫存空間。","opTimeoutSec": "FFmpeg 逾時 (秒)",- "opTimeoutSecDesc": "單一 FFmpeg 作業的最長時間。預設為 1800 秒 (30 分鐘),上限為 3600。",+ "opTimeoutSecDesc": "單次媒體處理的最長時間,最多 3,600 秒。","cleanupStaging": "清理暫存檔案","cleanupConfirm": "要移除所有 FFmpeg 暫存目錄嗎?","restartHint": "已儲存。重新啟動 Motrix 後,已啟用的外掛才能偵測到變更。",@@ -1902,7 +1963,7 @@"validation": {"fileMissing": "此路徑不存在檔案。"},- "applyHint": "修改自訂路徑後需點選「儲存」。媒體下載會讀取目前的 FFmpeg 路徑,無須重新啟動 Motrix;請在瀏覽器擴充功能中重新掃描以更新支援狀態。",+ "applyHint": "儲存後用於新的媒體下載;請在瀏覽器擴充功能中重新掃描以更新支援狀態。","savedTitle": "FFmpeg 設定已儲存","desktopSavedHint": "新的媒體下載會讀取儲存的路徑。已啟用的外掛需要重新啟動 Motrix 才能偵測到此次變更。","pipelineUnavailable": "媒體下載功能目前無法使用。",@@ -1949,7 +2010,8 @@"missing": "缺少必要檔案,請從目前位置執行 AppImage 並修復。","io": "操作失敗,請檢查磁碟存取權限後重試修復。"}- }+ },+ "description": "瀏覽器、預設應用程式與工具"},"validation": {"rangeHint": "範圍:{{min}}–{{max}}。",@@ -1974,7 +2036,8 @@"address": "位址 {{number}}","addressDraft": "新位址","required": "請先填寫位址。",- "time": "請使用 24 小時制填寫,例如 23:00。"+ "time": "請使用 24 小時制填寫,例如 23:00。",+ "loadFailed": "無法載入設定,請重試。"},"feedback": {"syncFailedTitle": "設定已儲存,但介面更新失敗",@@ -2191,6 +2254,7 @@"clearAll": "清除","empty": "沒有通知","emptyDesc": "下載活動和重要應用程式通知會顯示在這裡",+ "unreadDotAria": "有未讀通知","unreadBadgeAria_other": "{{count}} 則未讀通知","rowUnreadAria": "{{title}} (未讀)","toastRegionAria": "通知",@@ -2654,11 +2718,11 @@}},"directoryPreferences": {- "sectionDescription": "設定常用資料夾並管理最近使用的下載位置。",+ "sectionDescription": "把常用資料夾放在這裡,下載時方便選擇。","manage": "管理目錄","manageDescription": "設定常用目錄,管理最近使用的目錄。","title": "管理目錄",- "description": "變更將在儲存後生效。移除記錄不會刪除資料夾或下載任務。",+ "description": "從清單移除資料夾不會刪除資料夾或其中的檔案。","favorites": "常用目錄","recent": "最近使用","addFavorite": "新增常用目錄",diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex d79d732f..0130b83e 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -1,4 +1,5 @@export const Commands = {+ SaveDownloadsSettings: 'command:saveDownloadsSettings',PauseTask: 'command:pauseTask',ResumeTask: 'command:resumeTask',RemoveTask: 'command:removeTask',diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.tsindex 0aa7e78e..cb3625fc 100644--- a/src/shared/protocol/queries.ts+++ b/src/shared/protocol/queries.ts@@ -1,4 +1,5 @@export const Queries = {+ GetDownloadsSettingsDraft: 'query:getDownloadsSettingsDraft',GetDisclaimerState: 'query:getDisclaimerState',ListTasks: 'query:listTasks',GetTaskDetail: 'query:getTaskDetail',diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.tsindex 3b6a9693..6fab9239 100644--- a/src/shared/schemas/app-settings.test.ts+++ b/src/shared/schemas/app-settings.test.ts@@ -6,6 +6,41 @@ import {} from './app-settings'describe('appSettingsSchema', () => {+ it('preserves existing notification defaults, loads desktop choices, and rejects malformed writes', () => {+ const defaults = {+ notifyInAppOnComplete: true,+ notifyInAppOnError: true,+ notificationBadgeStyle: 'count',+ }+ expect(appSettingsSchema.parse({})).toMatchObject(defaults)+ expect(+ appSettingsSchema.parse({+ notifyInAppOnComplete: 'false',+ notifyInAppOnError: null,+ notificationBadgeStyle: 'off',+ })+ ).toMatchObject(defaults)+ for (const notificationBadgeStyle of ['count', 'dot', 'hidden']) {+ const choices = {+ notifyInAppOnComplete: false,+ notifyInAppOnError: false,+ notificationBadgeStyle,+ }+ expect(appSettingsSchema.parse(choices)).toMatchObject(choices)+ expect(appSettingsInputSchema.partial().safeParse(choices).success).toBe(+ true+ )+ }+ for (const invalid of [+ { notifyInAppOnComplete: 'false' },+ { notifyInAppOnError: null },+ { notificationBadgeStyle: 'off' },+ ]) {+ expect(appSettingsInputSchema.partial().safeParse(invalid).success).toBe(+ false+ )+ }+ })it('defaults existing and invalid file deletion preferences to trash', () => {expect(DEFAULT_APP_SETTINGS.fileDeletionMode).toBe('trash')for (const fileDeletionMode of [undefined, null, 'delete', false]) {diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.tsindex 4cb863be..72180a65 100644--- a/src/shared/schemas/app-settings.ts+++ b/src/shared/schemas/app-settings.ts@@ -15,6 +15,10 @@ import { DEFAULT_TRAY_ICON_COLOR, trayIconColorSchema } from './tray-icon-color'export const appUpdateChannelSchema = z.enum(['stable', 'beta'])export const fileDeletionModeSchema = z.enum(['trash', 'permanent'])export type FileDeletionMode = z.infer<typeof fileDeletionModeSchema>+export const notificationBadgeStyleSchema = z.enum(['count', 'dot', 'hidden'])+export type NotificationBadgeStyle = z.infer<+ typeof notificationBadgeStyleSchema+>export const MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS = 10export const MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS = 3600@@ -43,6 +47,9 @@ export const appSettingsSchema = z.object({}),notifyOnComplete: z.boolean().catch(true),notifyOnError: z.boolean().catch(true),+ notifyInAppOnComplete: z.boolean().catch(true),+ notifyInAppOnError: z.boolean().catch(true),+ notificationBadgeStyle: notificationBadgeStyleSchema.catch('count'),autofillClipboardLinks: z.boolean().catch(true),protocols: z.object({diff --git a/src/shared/schemas/downloads-settings.ts b/src/shared/schemas/downloads-settings.tsnew file mode 100644index 00000000..2cfb0ea6--- /dev/null+++ b/src/shared/schemas/downloads-settings.ts@@ -0,0 +1,132 @@+import { z } from 'zod'+import { appSettingsInputSchema } from './app-settings'+import {+ DIRECTORY_PREFERENCES_PATH_LIMIT,+ DirectoryPreferencesSchema,+} from './directory-preferences'+import { engineSettingsInputSchema } from './engine-settings'+import {+ GeneralSettingsErrorCodeSchema,+ SaveGeneralSettingsRequestSchema,+} from './general-settings'+import { settingsUpdateResultSchema } from './settings-update'+import { speedLimitSettingsInputSchema } from './speed-limit'++/** The same form and commit-boundary constraints for both hosts. */+export const downloadsSettingsSchema = z.object({+ app: appSettingsInputSchema.pick({+ defaultSaveDir: true,+ autofillClipboardLinks: true,+ fileDeletionMode: true,+ }),+ engine: engineSettingsInputSchema.pick({+ performanceProfile: true,+ maxConcurrentDownloads: true,+ maxConnectionPerServer: true,+ split: true,+ minSplitSize: true,+ userAgent: true,+ connectTimeout: true,+ socketTimeout: true,+ maxTries: true,+ retryWait: true,+ lowestSpeedLimit: true,+ fileAllocation: true,+ remoteTime: true,+ diskCache: true,+ }),+ speedLimit: speedLimitSettingsInputSchema,+})+const speed = speedLimitSettingsInputSchema+const auto = speed.shape.auto+const speedPatch = speed+ .partial()+ .extend({+ base: speed.shape.base.partial().strict().optional(),+ alt: speed.shape.alt.partial().strict().optional(),+ auto: auto+ .partial()+ .extend({+ schedule: auto.shape.schedule.partial().strict().optional(),+ videoApp: auto.shape.videoApp.partial().strict().optional(),+ adaptive: auto.shape.adaptive+ .partial()+ .extend({+ speedTest: auto.shape.adaptive.shape.speedTest+ .partial()+ .strict()+ .optional(),+ })+ .strict()+ .optional(),+ })+ .strict()+ .optional(),+ })+ .strict()+function containsUndefined(value: unknown): boolean {+ return (+ value === undefined ||+ (value !== null &&+ typeof value === 'object' &&+ Object.values(value).some(containsUndefined))+ )+}+export const downloadsSettingsPatchSchema = z+ .object({+ app: downloadsSettingsSchema.shape.app+ .partial()+ .extend({+ defaultSaveDir: z+ .string()+ .min(1)+ .max(DIRECTORY_PREFERENCES_PATH_LIMIT)+ .optional(),+ })+ .strict()+ .optional(),+ engine: downloadsSettingsSchema.shape.engine.partial().strict().optional(),+ speedLimit: speedPatch.optional(),+ })+ .strict()+ .refine((value) => !containsUndefined(value))+export const downloadsSettingsSnapshotSchema = z+ .object({+ revision: z.string().uuid(),+ settings: downloadsSettingsSchema,+ directoryPreferences: DirectoryPreferencesSchema,+ })+ .strict()+export const saveDownloadsSettingsRequestSchema = z+ .object({+ expectedRevision: z.string().uuid(),+ settings: downloadsSettingsPatchSchema,+ directories: SaveGeneralSettingsRequestSchema.shape.directories,+ })+ .strict()+export const downloadsSettingsResultSchema = z.discriminatedUnion('ok', [+ z+ .object({+ ok: z.literal(true),+ value: downloadsSettingsSnapshotSchema,+ update: settingsUpdateResultSchema.optional(),+ })+ .strict(),+ z+ .object({+ ok: z.literal(false),+ error: z.object({ code: GeneralSettingsErrorCodeSchema }).strict(),+ snapshot: downloadsSettingsSnapshotSchema.optional(),+ })+ .strict(),+])+export type DownloadsSettings = z.infer<typeof downloadsSettingsSchema>+export type DownloadsSettingsSnapshot = z.infer<+ typeof downloadsSettingsSnapshotSchema+>+export type DownloadsSettingsResult = z.infer<+ typeof downloadsSettingsResultSchema+>+export type SaveDownloadsSettingsRequest = z.infer<+ typeof saveDownloadsSettingsRequestSchema+>diff --git a/src/shared/schemas/general-settings.test.ts b/src/shared/schemas/general-settings.test.tsindex e8948750..1caf9a0d 100644--- a/src/shared/schemas/general-settings.test.ts+++ b/src/shared/schemas/general-settings.test.ts@@ -8,7 +8,13 @@ describe('SaveGeneralSettingsRequestSchema', () => {it('accepts dirty General fields and exact literal directory deltas', () => {const request = {expectedRevision: TEST_GENERAL_REVISION,- app: { defaultSaveDir: '/saved ', notifyOnError: false },+ app: {+ defaultSaveDir: '/saved ',+ notifyOnError: false,+ notifyInAppOnComplete: false,+ notifyInAppOnError: false,+ notificationBadgeStyle: 'dot',+ },directories: {...directories,addFavorites: ['/favorite '],@@ -36,6 +42,9 @@ describe('SaveGeneralSettingsRequestSchema', () => {directories,},{ app: { notifyOnError: 'false' }, directories },+ { app: { notifyInAppOnComplete: 'false' }, directories },+ { app: { notifyInAppOnError: undefined }, directories },+ { app: { notificationBadgeStyle: 'off' }, directories },{ app: { notifyOnError: undefined }, directories },{ app: { defaultSaveDir: '' }, directories },{ app: {}, directories: { ...directories, clearRecent: true } },diff --git a/src/shared/schemas/general-settings.ts b/src/shared/schemas/general-settings.tsindex 9b7f324a..e6b20425 100644--- a/src/shared/schemas/general-settings.ts+++ b/src/shared/schemas/general-settings.ts@@ -1,4 +1,8 @@import { z } from 'zod'+import {+ appSettingsInputSchema,+ notificationBadgeStyleSchema,+} from './app-settings'import {DIRECTORY_FAVORITES_LIMIT,DIRECTORY_PREFERENCES_PATH_LIMIT,@@ -10,11 +14,16 @@ import {const directoryPath = z.string().min(1).max(DIRECTORY_PREFERENCES_PATH_LIMIT)export const GeneralSettingsAppSchema = z.object({+ runMode: appSettingsInputSchema.shape.runMode,+ lightweightMode: appSettingsInputSchema.shape.lightweightMode,launchAtStartup: z.boolean(),showMainWindowAtLogin: z.boolean(),defaultSaveDir: z.string(),notifyOnComplete: z.boolean(),notifyOnError: z.boolean(),+ notifyInAppOnComplete: z.boolean(),+ notifyInAppOnError: z.boolean(),+ notificationBadgeStyle: notificationBadgeStyleSchema,autofillClipboardLinks: z.boolean(),warnBeforeQuit: z.boolean(),})diff --git a/src/shared/types/notification.ts b/src/shared/types/notification.tsindex 0fcddf0d..48e464af 100644--- a/src/shared/types/notification.ts+++ b/src/shared/types/notification.ts@@ -11,6 +11,18 @@ export const NotificationKinds = {} as constexport type NotificationKind = string+/** Only routine task outcomes can be hidden; application faults always pass. */+export function getHiddenNotificationKinds(preferences: {+ notifyInAppOnComplete: boolean+ notifyInAppOnError: boolean+}): string[] {+ const kinds: string[] = []+ if (!preferences.notifyInAppOnComplete)+ kinds.push(NotificationKinds.TaskComplete)+ if (!preferences.notifyInAppOnError) kinds.push(NotificationKinds.TaskError)+ return kinds+}+export interface AppNotification {id: stringsourceKey: string | nulldiff --git a/src/shared/types/settings.ts b/src/shared/types/settings.tsindex c1f62fd9..0b1abedb 100644--- a/src/shared/types/settings.ts+++ b/src/shared/types/settings.ts@@ -1,4 +1,7 @@-import type { FileDeletionMode } from '@shared/schemas/app-settings'+import type {+ FileDeletionMode,+ NotificationBadgeStyle,+} from '@shared/schemas/app-settings'import type { ByteUnitPreference } from '@shared/schemas/byte-unit-system'import type { SidebarColor } from '@shared/schemas/sidebar-color'import type { TrayIconColor } from '@shared/schemas/tray-icon-color'@@ -231,6 +234,10 @@ export interface MotrixAppSettings {fileDeletionMode: FileDeletionModenotifyOnComplete: booleannotifyOnError: boolean+ /** Desktop in-app surfaces only; independent of native OS notifications. */+ notifyInAppOnComplete: boolean+ notifyInAppOnError: boolean+ notificationBadgeStyle: NotificationBadgeStyle/** When true, opening the New Task dialog reads the clipboard once and* fills the URL field with any link(s) found — only when the field is* empty. One-shot on open; never a background clipboard watcher. */diff --git a/src/test-utils/downloads-settings.ts b/src/test-utils/downloads-settings.tsnew file mode 100644index 00000000..7764eff3--- /dev/null+++ b/src/test-utils/downloads-settings.ts@@ -0,0 +1,27 @@+import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'+import { downloadsSettingsSchema } from '@shared/schemas/downloads-settings'+import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'+import { DEFAULT_SPEED_LIMIT_SETTINGS } from '@shared/schemas/speed-limit'+export const TEST_DOWNLOADS_REVISION = '00000000-0000-4000-8000-000000000001'+export function downloadsSettingsResult(+ settings: { app?: object; engine?: object; speedLimit?: object } = {},+ preferences = { favorites: [] as string[], recent: [] as string[] }+) {+ return {+ ok: true as const,+ value: {+ revision: TEST_DOWNLOADS_REVISION,+ settings: downloadsSettingsSchema.parse({+ app: {+ ...DEFAULT_APP_SETTINGS,+ defaultSaveDir: '/downloads',+ ...settings.app,+ },+ engine: { ...DEFAULT_ENGINE_SETTINGS, ...settings.engine },+ speedLimit: settings.speedLimit ?? DEFAULT_SPEED_LIMIT_SETTINGS,+ }),+ directoryPreferences: preferences,+ },+ update: { saved: true, requiresRestart: false, changedRestartKeys: [] },+ }+}