Skip to content

A full-featured download manager.

fix: persist settings and align desktop window controls (#1906)

Dr_rOotadca4810c8cb
diff --git a/README.md b/README.md
index 87e0ba80..df3811de 100644
--- a/README.md
+++ b/README.md
@@ -220,9 +220,12 @@ flag enabled:
MOTRIX_PREVIEW_MAC_MENU=1 pnpm start
```
-The flag hides the main window's macOS traffic-light buttons and enables the
-renderer dropdown menu. Restart the development process after changing the
-flag because both Electron and Vite read it at startup.
+The flag hides the main window's macOS traffic-light buttons, enables the
+renderer dropdown menu, and shows the custom window controls used on Windows
+and Linux. Collapse the sidebar in this mode to check the application menu,
+attached actions, drag region, and caption-control safe areas together.
+Restart the development process after changing the flag because both Electron
+and Vite read it at startup.
This mode is intended for layout and command-item debugging. Electron routes
macOS role items through AppKit's native menu, so role-backed actions such as
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9f785dd2..0137301b 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -207,8 +207,10 @@ Windows 和 Linux 会在 Motrix 窗口内渲染应用菜单。在 macOS 开发
MOTRIX_PREVIEW_MAC_MENU=1 pnpm start
```
-该开关会隐藏主窗口的 macOS 红绿灯按钮,并启用 renderer dropdown menu。Electron
-和 Vite 都会在启动时读取此开关,因此修改后需要重启开发进程。
+该开关会隐藏主窗口的 macOS 红绿灯按钮,启用 renderer dropdown menu,并显示
+Windows/Linux 使用的自绘窗体按钮。可在这个模式下收起 Sidebar,联合检查应用菜单、
+附加 actions、拖拽区域和窗体按钮的安全间距。Electron 和 Vite 都会在启动时读取此
+开关,因此修改后需要重启开发进程。
此模式用于调试布局和 command 菜单项。Electron 会通过 AppKit 原生菜单处理 macOS
role 菜单项,因此 **Window → Minimize** 等 role action 从预览 dropdown 调用时,行为
diff --git a/e2e/dashboard.spec.ts b/e2e/dashboard.spec.ts
index 3664616d..e58b6225 100644
--- a/e2e/dashboard.spec.ts
+++ b/e2e/dashboard.spec.ts
@@ -11,7 +11,7 @@
import { expect, test } from './fixtures/electron-app'
test.describe('Dashboard v1', () => {
- test('cold launch renders seven tile labels and task views within 800ms', async ({
+ test('cold launch renders seven default tile labels within 800ms', async ({
mainWindow,
}) => {
// Navigate to dashboard (hash router — '#/' is the dashboard route)
@@ -55,21 +55,14 @@ test.describe('Dashboard v1', () => {
).toBeVisible({ timeout: 800 }),
expect(
mainWindow
- .getByTestId('dashboard-tile-tasks')
- .getByText('Tasks', { exact: true })
+ .getByTestId('dashboard-tile-activity')
+ .getByText('Activity', { exact: true })
).toBeVisible({ timeout: 800 }),
expect(
mainWindow
.getByTestId('dashboard-tile-transfer')
.getByText('Transfer', { exact: true })
).toBeVisible({ timeout: 800 }),
- expect(
- mainWindow
- .getByTestId('dashboard-tile-tasks')
- .getByRole('radiogroup', { name: 'Task view' })
- ).toBeVisible({
- timeout: 800,
- }),
])
})
diff --git a/e2e/media-settings.spec.ts b/e2e/media-settings.spec.ts
index 3eb6071e..fa837254 100644
--- a/e2e/media-settings.spec.ts
+++ b/e2e/media-settings.spec.ts
@@ -1,21 +1,23 @@
import { expect, test } from './fixtures/electron-app'
test.describe('media settings', () => {
- test('shows detection status and saves manual path with restart hint', async ({
+ test('shows detection status and saves a manual path', async ({
mainWindow,
}) => {
// 1. Open Settings page from the main sidebar.
- await mainWindow.getByRole('link', { name: 'Settings' }).click()
+ await mainWindow
+ .getByRole('link', { name: 'Settings', exact: true })
+ .click()
- // 2. Click the Media card. Card titles come from
- // settings.cards.media.title — match the exact text.
- await mainWindow.getByText('Media', { exact: true }).first().click()
+ // 2. Media tools live in the Integration card.
+ await mainWindow.getByText('Integration', { exact: true }).first().click()
- // 3. Detection status card visible — at least the manual candidate
- // row always renders (state='unconfigured' when path is empty).
- await expect(
- mainWindow.locator('[data-testid="candidate-row-manual"]')
- ).toBeVisible()
+ // 3. The media section is lower in the scrollable Integration dialog.
+ const detectionCard = mainWindow.locator(
+ '[data-testid="media-detection-card"]'
+ )
+ await detectionCard.scrollIntoViewIfNeeded()
+ await expect(detectionCard).toBeVisible()
// 4. Change the binary path input.
const pathInput = mainWindow.locator(
@@ -24,14 +26,8 @@ test.describe('media settings', () => {
await pathInput.fill('/tmp/custom-ffmpeg')
await expect(pathInput).toHaveValue('/tmp/custom-ffmpeg')
- // 5. Click Apply.
- await mainWindow.getByRole('button', { name: 'Apply' }).click()
-
- // 6. Restart hint surfaces inline. Text source:
- // settings.media.restartHint — "Saved. Restart Motrix for active
- // plugins to detect changes."
- const hint = mainWindow.locator('[data-testid="media-restart-hint"]')
- await expect(hint).toBeVisible()
- await expect(hint).toContainText(/restart/i)
+ // 5. Save and verify that the dialog closes.
+ await mainWindow.getByRole('button', { name: 'Save' }).click()
+ await expect(pathInput).not.toBeVisible()
})
})
diff --git a/e2e/settings-persistence.spec.ts b/e2e/settings-persistence.spec.ts
index ee58c748..fc2d06f9 100644
--- a/e2e/settings-persistence.spec.ts
+++ b/e2e/settings-persistence.spec.ts
@@ -4,7 +4,7 @@ import { expect, launchMotrix, test } from './fixtures/electron-app'
const SWITCH_LABEL = 'Notify when download completes'
async function openGeneralSettings(page: Page): Promise<void> {
- await page.getByRole('link', { name: 'Settings' }).click()
+ await page.getByRole('link', { name: 'Settings', exact: true }).click()
// Settings cards are clickable tiles. The "General" card's title comes
// from settings.cards.general.title. Match the text that's also the
// accessible heading inside the card.
@@ -43,7 +43,7 @@ test.describe('settings persistence', () => {
// Apply: handler awaits transport.invoke(UpdateSettings),
// which awaits SettingsManager.update -> writeFile.
// Dialog closes after success → switch leaves the DOM.
- await main.getByRole('button', { name: 'Apply' }).click()
+ await main.getByRole('button', { name: 'Save' }).click()
await expect(switch1).toBeHidden()
await app.close()
diff --git a/e2e/task-recovery.spec.ts b/e2e/task-recovery.spec.ts
index bc90de55..5e82b75c 100644
--- a/e2e/task-recovery.spec.ts
+++ b/e2e/task-recovery.spec.ts
@@ -73,7 +73,7 @@ test.describe('task recovery', () => {
let main = await openMain(app)
await waitForEngineReady(main)
- await main.getByRole('button', { name: '+ New task' }).click()
+ await main.getByRole('button', { name: 'New task' }).click()
const addTaskPage = await findAddTaskWindow(app)
await addTaskPage.getByRole('textbox', { name: 'URLs' }).fill(fx.fileUrl)
await addTaskPage.getByRole('button', { name: 'Download' }).click()
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index 7c3703d7..14cde3c5 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -24,33 +24,6 @@ import type { Aria2RpcClient } from './aria2/aria2-rpc-client'
import { EngineSupervisor } from './engine-supervisor'
import { checkPort } from './port-check'
-vi.mock('../probe/disk-probe', () => ({
- probePrecise: vi.fn().mockResolvedValue({
- platform: 'darwin',
- mountPoint: '/',
- fsType: 'apfs',
- diskType: 'ssd',
- isInternal: true,
- isNetworkFs: false,
- freeBytes: 250000000000,
- confidence: 'high',
- }),
- invalidateProbeCache: vi.fn(),
-}))
-
-vi.mock('./aria2/aria2-tuning', () => ({
- recommend: vi.fn().mockReturnValue({
- fileAllocation: 'none',
- diskCache: 16777216,
- split: 5,
- minSplitSize: 20971520,
- reasons: [],
- confidence: 'high',
- alternatives: [],
- detectedEnv: {},
- }),
-}))
-
// checkPort uses node:net I/O which doesn't fire under fake timers, and
// a live aria2 on the dev port would make it return false. Mock the
// port-check module so the supervisor always sees the port as available.
@@ -227,6 +200,11 @@ describe('EngineSupervisor', () => {
await supervisor.start('/usr/bin/aria2c')
expect(adapter.setFeatureReport).toHaveBeenCalledWith(FEATURE_REPORT)
})
+
+ it('does not overwrite persisted tuning settings during engine start', async () => {
+ await supervisor.start('/usr/bin/aria2c')
+ expect(settings.update).not.toHaveBeenCalled()
+ })
})
describe('start — probe failure', () => {
@@ -490,6 +468,18 @@ describe('EngineSupervisor', () => {
expect(payloads).toHaveLength(0)
})
+ it('suppresses a process exit as soon as app shutdown is prepared', async () => {
+ await supervisor.start('/usr/bin/aria2c')
+ const payloads = collectFailures()
+
+ supervisor.prepareForShutdown()
+ processManager.onExit?.(1, null)
+
+ expect(payloads).toHaveLength(0)
+ expect(supervisor.getState()).toBe(EngineState.Ready)
+ await supervisor.stop()
+ })
+
it('restart() emits no EngineFailureOccurred on a successful manual restart', async () => {
await supervisor.start('/usr/bin/aria2c')
const payloads = collectFailures()
@@ -798,6 +788,40 @@ describe('EngineSupervisor', () => {
})
})
+ describe('applyEngineSettings', () => {
+ it('is a no-op unless Ready', async () => {
+ const previous = settings.getEngine()
+ await supervisor.applyEngineSettings(previous, {
+ ...previous,
+ split: 32,
+ })
+ expect(rpcClient.changeGlobalOption).not.toHaveBeenCalled()
+ })
+
+ it('maps changed runtime settings and excludes startup-only settings', async () => {
+ await supervisor.start('/usr/bin/aria2c')
+ vi.mocked(rpcClient.changeGlobalOption).mockClear()
+ const previous = settings.getEngine()
+
+ await supervisor.applyEngineSettings(previous, {
+ ...previous,
+ split: 32,
+ userAgent: 'Motrix/Test',
+ btEnableLpd: false,
+ sessionSaveInterval: 30,
+ fileAllocation: 'prealloc',
+ diskCache: 32 * 1024 * 1024,
+ })
+
+ expect(rpcClient.changeGlobalOption).toHaveBeenCalledWith({
+ split: '32',
+ 'user-agent': 'Motrix/Test',
+ 'bt-enable-lpd': 'false',
+ 'save-session-interval': '30',
+ })
+ })
+ })
+
describe('applyProxyChange', () => {
it('is no-op when state is not Ready', async () => {
// supervisor starts in Stopped — never started
diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.ts
index e05ea1f6..a22fc579 100644
--- a/src/core/engine/engine-supervisor.ts
+++ b/src/core/engine/engine-supervisor.ts
@@ -17,14 +17,13 @@ import {
EngineState,
type EngineStatusSnapshot,
} from '@shared/types/engine'
+import type { EngineSettings } from '@shared/types/settings'
import type { EventBus } from '../events/event-bus'
-import { probePrecise } from '../probe/disk-probe'
import type { SettingsManager } from '../settings/settings-manager'
import type { Aria2Adapter } from './aria2/aria2-adapter'
import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'
import type { Aria2ProcessManager } from './aria2/aria2-process-manager'
import type { Aria2RpcClient } from './aria2/aria2-rpc-client'
-import { recommend } from './aria2/aria2-tuning'
import { checkPort, findAvailablePort } from './port-check'
const log = getLogger('engine')
@@ -40,6 +39,24 @@ const MAX_RESTARTS = 5
const HEALTH_CHECK_INTERVAL = 30_000
const MAX_CONSECUTIVE_FAILURES = 3
+const HOT_ENGINE_OPTIONS = {
+ maxConcurrentDownloads: 'max-concurrent-downloads',
+ maxConnectionPerServer: 'max-connection-per-server',
+ split: 'split',
+ minSplitSize: 'min-split-size',
+ userAgent: 'user-agent',
+ connectTimeout: 'connect-timeout',
+ socketTimeout: 'timeout',
+ maxTries: 'max-tries',
+ retryWait: 'retry-wait',
+ lowestSpeedLimit: 'lowest-speed-limit',
+ btMaxPeers: 'bt-max-peers',
+ btEnableLpd: 'bt-enable-lpd',
+ seedRatio: 'seed-ratio',
+ seedTime: 'seed-time',
+ sessionSaveInterval: 'save-session-interval',
+} as const satisfies Partial<Record<keyof EngineSettings, string>>
+
function getBackoffDelay(attempt: number): number {
return Math.min(BACKOFF_BASE * 2 ** attempt, BACKOFF_MAX)
}
@@ -158,6 +175,25 @@ export class EngineSupervisor {
})
}
+ /** HOT-update changed runtime engine settings without restarting aria2. */
+ async applyEngineSettings(
+ previous: EngineSettings,
+ next: EngineSettings
+ ): Promise<void> {
+ if (this.state !== EngineState.Ready) return
+
+ const params: Record<string, string> = {}
+ for (const [key, option] of Object.entries(HOT_ENGINE_OPTIONS) as Array<
+ [keyof typeof HOT_ENGINE_OPTIONS, string]
+ >) {
+ if (previous[key] !== next[key]) {
+ params[option] = String(next[key])
+ }
+ }
+ if (Object.keys(params).length === 0) return
+ await this.rpcClient.changeGlobalOption(params)
+ }
+
/**
* HOT-update the aria2 proxy via `aria2.changeGlobalOption`. No-op when
* the engine is not Ready (cold start picks up proxy via `buildArgs`).
@@ -174,10 +210,20 @@ export class EngineSupervisor {
await this.rpcClient.changeGlobalOption(params)
}
- async stop(): Promise<void> {
+ /**
+ * Synchronously fence process-exit handling before asynchronous app cleanup.
+ * Windows can terminate child processes as soon as session end begins, so
+ * waiting until stop() reaches gracefulStop() can misclassify that expected
+ * exit as an engine crash.
+ */
+ prepareForShutdown(): void {
this.stopping = true
this.stopHealthCheck()
this.clearRestartTimer()
+ }
+
+ async stop(): Promise<void> {
+ this.prepareForShutdown()
if (this.processManager.isRunning()) {
// SIGTERM aria2 directly. Its signal handler sets
@@ -214,11 +260,7 @@ export class EngineSupervisor {
let phase: 'probe' | 'config' | 'spawn' | 'rpc' = 'probe'
try {
- const defaultSaveDir = this.settingsManager.getApp().defaultSaveDir || '.'
- const [featureReport, probeResult] = await Promise.all([
- this.processManager.probe(this.binaryPath),
- probePrecise(defaultSaveDir),
- ])
+ const featureReport = await this.processManager.probe(this.binaryPath)
if (this.stopping) return
this.featureReport = featureReport
@@ -227,26 +269,6 @@ export class EngineSupervisor {
// we just probed so the gate reflects the real engine version.
this.adapter.setFeatureReport(featureReport)
- const tuning = recommend(probeResult, null)
-
- const currentEngine = this.settingsManager.getEngine()
- if (
- currentEngine.fileAllocation !== tuning.fileAllocation ||
- currentEngine.diskCache !== tuning.diskCache ||
- currentEngine.split !== tuning.split ||
- currentEngine.minSplitSize !== tuning.minSplitSize
- ) {
- await this.settingsManager.update({
- engine: {
- fileAllocation: tuning.fileAllocation,
- diskCache: tuning.diskCache,
- split: tuning.split,
- minSplitSize: tuning.minSplitSize,
- },
- })
- this.eventBus.emit(Events.TuningUpdated, tuning)
- }
-
// Step 2: Ensure config and build args
phase = 'config'
await this.configBuilder.ensureUserConfig()
diff --git a/src/core/notifications/engine-failure-subscriber.test.ts b/src/core/notifications/engine-failure-subscriber.test.ts
index 4cb4056e..eb02fec5 100644
--- a/src/core/notifications/engine-failure-subscriber.test.ts
+++ b/src/core/notifications/engine-failure-subscriber.test.ts
@@ -4,6 +4,7 @@ import { Events } from '@shared/protocol/events'
import type { EngineFailurePayload } from '@shared/types/engine'
import {
EngineFailureReason,
+ EngineState,
engineFailureReasonKey,
} from '@shared/types/engine'
import { NotificationKinds } from '@shared/types/notification'
@@ -62,7 +63,7 @@ describe('registerEngineFailureSubscriber', () => {
log: makeLog(),
})
- expect(order).toEqual(['cleanup', 'subscribe'])
+ expect(order).toEqual(['cleanup', 'subscribe', 'subscribe'])
expect(motrixDb.deleteEngineNotificationLedgerBefore).toHaveBeenCalledWith(
5000
)
@@ -96,6 +97,93 @@ describe('registerEngineFailureSubscriber', () => {
})
})
+ it('discards a transient unexpected-exit incident after automatic recovery', () => {
+ const motrixDb = {
+ deleteEngineNotificationLedgerBefore: vi.fn(() => 0),
+ } as unknown as MotrixDatabase
+ const eventBus = new EventBus()
+ const notify = vi.fn()
+
+ registerEngineFailureSubscriber({
+ motrixDb,
+ eventBus,
+ notificationCenter: { notify },
+ log: makeLog(),
+ })
+
+ eventBus.emit(
+ Events.EngineFailureOccurred,
+ makePayload({ reason: EngineFailureReason.UnexpectedExit })
+ )
+ eventBus.emit(Events.EngineStateChanged, EngineState.Restarting)
+ expect(notify).not.toHaveBeenCalled()
+
+ eventBus.emit(Events.EngineStateChanged, EngineState.Ready)
+ expect(notify).not.toHaveBeenCalled()
+ })
+
+ it('publishes a recoverable incident if automatic recovery becomes terminal', () => {
+ const motrixDb = {
+ deleteEngineNotificationLedgerBefore: vi.fn(() => 0),
+ } as unknown as MotrixDatabase
+ const eventBus = new EventBus()
+ const notify = vi.fn()
+ const payload = makePayload({
+ reason: EngineFailureReason.HealthCheckFailed,
+ })
+
+ registerEngineFailureSubscriber({
+ motrixDb,
+ eventBus,
+ notificationCenter: { notify },
+ log: makeLog(),
+ })
+
+ eventBus.emit(Events.EngineFailureOccurred, payload)
+ eventBus.emit(Events.EngineStateChanged, EngineState.Failed)
+
+ expect(notify).toHaveBeenCalledOnce()
+ expect(notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sourceKey: payload.incidentId,
+ bodyKey:
+ 'panel.dashboard.engine.diagnostics.reason.health_check_failed',
+ })
+ )
+ })
+
+ it('reports only a terminal restart cause after a transient exit', () => {
+ const motrixDb = {
+ deleteEngineNotificationLedgerBefore: vi.fn(() => 0),
+ } as unknown as MotrixDatabase
+ const eventBus = new EventBus()
+ const notify = vi.fn()
+
+ registerEngineFailureSubscriber({
+ motrixDb,
+ eventBus,
+ notificationCenter: { notify },
+ log: makeLog(),
+ })
+
+ eventBus.emit(
+ Events.EngineFailureOccurred,
+ makePayload({ reason: EngineFailureReason.UnexpectedExit })
+ )
+ const terminal = makePayload({
+ incidentId: 'engine:1001:1',
+ occurredAt: 1001,
+ reason: EngineFailureReason.SpawnFailed,
+ })
+ eventBus.emit(Events.EngineFailureOccurred, terminal)
+ eventBus.emit(Events.EngineStateChanged, EngineState.Failed)
+
+ expect(notify).toHaveBeenCalledOnce()
+ expect(notify).toHaveBeenCalledWith(
+ expect.objectContaining({ sourceKey: terminal.incidentId })
+ )
+ })
+
it('a notify() throw (e.g. a full store) is swallowed and logged via log.warn, never re-thrown into the EventBus dispatch', () => {
const motrixDb = {
deleteEngineNotificationLedgerBefore: vi.fn(() => 0),
diff --git a/src/core/notifications/engine-failure-subscriber.ts b/src/core/notifications/engine-failure-subscriber.ts
index 8852a477..41f4239e 100644
--- a/src/core/notifications/engine-failure-subscriber.ts
+++ b/src/core/notifications/engine-failure-subscriber.ts
@@ -3,7 +3,11 @@ import type { Logger } from '@core/logger'
import type { MotrixDatabase } from '@core/session/motrix-database'
import { Events } from '@shared/protocol/events'
import type { EngineFailurePayload } from '@shared/types/engine'
-import { engineFailureReasonKey } from '@shared/types/engine'
+import {
+ EngineFailureReason,
+ EngineState,
+ engineFailureReasonKey,
+} from '@shared/types/engine'
import { NotificationKinds } from '@shared/types/notification'
import type { NotificationCenter } from './notification-center'
@@ -15,6 +19,11 @@ export interface EngineFailureSubscriberDeps {
log: Pick<Logger, 'warn'>
}
+const AUTO_RECOVERABLE_REASONS = new Set<EngineFailureReason>([
+ EngineFailureReason.UnexpectedExit,
+ EngineFailureReason.HealthCheckFailed,
+])
+
/**
* Startup wiring for engine-incident notifications (Task 13):
*
@@ -23,8 +32,13 @@ export interface EngineFailureSubscriberDeps {
* produced it (the per-instance `seq` resets on restart), so there is no
* replay source for these rows across a boot and they must be cleared
* before subscribing, not after.
- * 2. Subscribe to `Events.EngineFailureOccurred` and turn each payload into
- * a notification-center row. Delivery idempotency for any payload
+ * 2. Subscribe to `Events.EngineFailureOccurred` and turn terminal payloads
+ * into notification-center rows. Unexpected exits and health-check misses
+ * are held while the supervisor performs its automatic recovery: reaching
+ * Ready discards the transient incident, while reaching Failed publishes
+ * it. This prevents a recovered login-start race from leaving a durable
+ * "engine failed" notification next to a Ready status.
+ * 3. Delivery idempotency for any payload
* re-emitted within the same boot is the ledger's job (`sourceKey =
* incidentId` inside `NotificationCenter.notify`) — this subscriber
* holds no dedup state of its own.
@@ -37,8 +51,9 @@ export function registerEngineFailureSubscriber(
const now = deps.now ?? Date.now
deps.motrixDb.deleteEngineNotificationLedgerBefore(now())
- deps.eventBus.on(Events.EngineFailureOccurred, (...args: unknown[]) => {
- const payload = args[0] as EngineFailurePayload
+ let pendingRecoverableFailure: EngineFailurePayload | null = null
+
+ const notify = (payload: EngineFailurePayload) => {
// notify()'s store write (insertNotificationWithLedger) can throw
// (e.g. SQLITE_FULL). This listener runs synchronously inside
// EventBus.emit, which has no per-listener isolation, and that emit
@@ -62,5 +77,32 @@ export function registerEngineFailureSubscriber(
'engineFailureSubscriber: notify() threw'
)
}
+ }
+
+ deps.eventBus.on(Events.EngineFailureOccurred, (...args: unknown[]) => {
+ const payload = args[0] as EngineFailurePayload
+ if (AUTO_RECOVERABLE_REASONS.has(payload.reason)) {
+ pendingRecoverableFailure = payload
+ return
+ }
+
+ // A concrete startup/restart failure supersedes the earlier transient
+ // exit that led into this recovery attempt; report only the terminal
+ // cause instead of creating two rows for one incident.
+ pendingRecoverableFailure = null
+ notify(payload)
+ })
+
+ deps.eventBus.on(Events.EngineStateChanged, (...args: unknown[]) => {
+ const state = args[0] as EngineState
+ if (state === EngineState.Ready) {
+ pendingRecoverableFailure = null
+ return
+ }
+ if (state === EngineState.Failed && pendingRecoverableFailure) {
+ const payload = pendingRecoverableFailure
+ pendingRecoverableFailure = null
+ notify(payload)
+ }
})
}
diff --git a/src/core/notifications/engine-restart-required.test.ts b/src/core/notifications/engine-restart-required.test.ts
new file mode 100644
index 00000000..10ea843f
--- /dev/null
+++ b/src/core/notifications/engine-restart-required.test.ts
@@ -0,0 +1,49 @@
+import { Events } from '@shared/protocol/events'
+import { NotificationKinds } from '@shared/types/notification'
+import { describe, expect, it, vi } from 'vitest'
+import {
+ type PublishEngineRestartRequiredDeps,
+ publishEngineRestartRequired,
+} from './engine-restart-required'
+
+function makeDeps(): PublishEngineRestartRequiredDeps {
+ return {
+ eventBus: { emit: vi.fn() } as never,
+ notificationCenter: { notify: vi.fn(() => ({ fresh: true })) },
+ log: { warn: vi.fn() } as never,
+ }
+}
+
+describe('publishEngineRestartRequired', () => {
+ it('writes a durable warning and emits the action-toast event', () => {
+ const deps = makeDeps()
+
+ publishEngineRestartRequired(deps, ['rpcPort', 'diskCache'])
+
+ expect(deps.notificationCenter.notify).toHaveBeenCalledWith({
+ sourceKey: expect.stringMatching(/^engine-restart-required:/),
+ kind: NotificationKinds.EngineRestartRequired,
+ severity: 'warning',
+ titleKey: 'notification.engineRestartRequired.title',
+ bodyKey: 'notification.engineRestartRequired.body',
+ })
+ expect(deps.eventBus.emit).toHaveBeenCalledWith(
+ Events.EngineRestartRequired,
+ { changedKeys: ['rpcPort', 'diskCache'] }
+ )
+ })
+
+ it('still emits the toast event when the notification store fails', () => {
+ const deps = makeDeps()
+ vi.mocked(deps.notificationCenter.notify).mockImplementation(() => {
+ throw new Error('disk full')
+ })
+
+ expect(() => publishEngineRestartRequired(deps, ['rpcPort'])).not.toThrow()
+ expect(deps.log.warn).toHaveBeenCalledOnce()
+ expect(deps.eventBus.emit).toHaveBeenCalledWith(
+ Events.EngineRestartRequired,
+ { changedKeys: ['rpcPort'] }
+ )
+ })
+})
diff --git a/src/core/notifications/engine-restart-required.ts b/src/core/notifications/engine-restart-required.ts
new file mode 100644
index 00000000..71e2be22
--- /dev/null
+++ b/src/core/notifications/engine-restart-required.ts
@@ -0,0 +1,44 @@
+import { randomUUID } from 'node:crypto'
+import type { EventBus } from '@core/events/event-bus'
+import type { Logger } from '@core/logger'
+import { Events } from '@shared/protocol/events'
+import type { EngineRestartRequiredPayload } from '@shared/types/engine'
+import { NotificationKinds } from '@shared/types/notification'
+import type { NotificationCenter } from './notification-center'
+
+export interface PublishEngineRestartRequiredDeps {
+ eventBus: EventBus
+ notificationCenter: Pick<NotificationCenter, 'notify'>
+ log: Pick<Logger, 'warn'>
+}
+
+/**
+ * Publish one durable notification-center row plus the transient renderer
+ * event that owns the action-bearing toast. A notification write failure
+ * must not turn an already-durable settings save into a failed command.
+ */
+export function publishEngineRestartRequired(
+ deps: PublishEngineRestartRequiredDeps,
+ changedKeys: readonly string[]
+): void {
+ const payload: EngineRestartRequiredPayload = {
+ changedKeys: [...changedKeys],
+ }
+
+ try {
+ deps.notificationCenter.notify({
+ sourceKey: `engine-restart-required:${randomUUID()}`,
+ kind: NotificationKinds.EngineRestartRequired,
+ severity: 'warning',
+ titleKey: 'notification.engineRestartRequired.title',
+ bodyKey: 'notification.engineRestartRequired.body',
+ })
+ } catch (error) {
+ deps.log.warn(
+ { err: error, changedKeys: payload.changedKeys },
+ 'engine restart notification write failed'
+ )
+ }
+
+ deps.eventBus.emit(Events.EngineRestartRequired, payload)
+}
diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.ts
index ff09bb00..9f0c5ef6 100644
--- a/src/core/settings/settings-manager.test.ts
+++ b/src/core/settings/settings-manager.test.ts
@@ -389,6 +389,34 @@ describe('SettingsManager', () => {
expect(mockedFs.writeFile).toHaveBeenCalled()
})
+ it('persists explicit split and disk tuning values unchanged', async () => {
+ await manager.update({
+ engine: {
+ split: 32,
+ fileAllocation: 'prealloc',
+ diskCache: 32 * 1024 * 1024,
+ },
+ })
+
+ expect(manager.getEngine()).toEqual(
+ expect.objectContaining({
+ split: 32,
+ fileAllocation: 'prealloc',
+ diskCache: 32 * 1024 * 1024,
+ })
+ )
+ const persisted = JSON.parse(
+ mockedFs.writeFile.mock.calls.at(-1)?.[1] as string
+ ) as AppSettings
+ expect(persisted.engine).toEqual(
+ expect.objectContaining({
+ split: 32,
+ fileAllocation: 'prealloc',
+ diskCache: 32 * 1024 * 1024,
+ })
+ )
+ })
+
it('updates app settings and persists', async () => {
const before = manager.get()
const result = await manager.update({
diff --git a/src/main/index.ts b/src/main/index.ts
index 852d2650..08f53c4e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -410,6 +410,10 @@ let resolvedApplicationLocale: SupportedLocale = DEFAULT_LOCALE
let cleanupPromise: Promise<void> | null = null
function performCleanup(): Promise<void> {
+ // Fence engine exit handling before the first await. Windows may terminate
+ // aria2 as soon as session end begins, before graceful cleanup reaches it.
+ supervisor?.prepareForShutdown()
+
// Release a first-run bootstrap waiting for legal consent before asking the
// work coordinator to drain that bootstrap. This must happen synchronously
// or declining/closing the disclaimer can deadlock shutdown.
@@ -1373,13 +1377,11 @@ async function initializeMainProcess(): Promise<void> {
!gate.isAccepted() && requested !== 'onboarding'
? 'onboarding'
: requested,
- onSessionEnd: () => quitController.markSessionEnding(),
- })
- // Apply the persisted theme before opening windows, then keep Windows
- // caption symbols synchronized with the resolved app/system theme.
- setupNativeThemeSync(eventBus, settingsManager, (shouldUseDarkColors) => {
- windowManager.syncWindowControlsTheme(shouldUseDarkColors)
+ onSessionEnd: prepareForSessionEnd,
})
+ // Apply the persisted theme before opening windows. Renderer-drawn Windows
+ // controls inherit the same theme through CSS without native overlay sync.
+ setupNativeThemeSync(eventBus, settingsManager)
// Install forwarding before the onboarding window becomes interactive.
// SetDisclaimerLanguage persists before its asynchronous locale transaction
// completes; an immediate AcceptDisclaimer can open the main window in that
@@ -1408,7 +1410,7 @@ async function initializeMainProcess(): Promise<void> {
})
// OS logout/shutdown: skip the quit dialog so session end is never blocked.
- powerMonitor.on('shutdown', () => quitController.markSessionEnding())
+ powerMonitor.on('shutdown', prepareForSessionEnd)
if (gate.isAccepted()) {
const runMode = settingsManager.getApp().runMode
@@ -1703,6 +1705,7 @@ async function initializeMainProcess(): Promise<void> {
const natStack = createNatManager({
eventBus,
settingsManager,
+ isEngineReady: () => supervisor.getState() === EngineState.Ready,
})
natManager = natStack.manager
log.info('NatManager constructed')
@@ -2200,6 +2203,7 @@ async function initializeMainProcess(): Promise<void> {
torrentMetaStore,
fileCleanupService,
eventBus,
+ notificationCenter,
motrixDatabase: motrixDb,
geoipManager,
proxyApplier,
@@ -2379,6 +2383,7 @@ function beginShutdown(): void {
// quitController.phase is already 'shutting-down' (set synchronously before
// this call). app.quit() below re-fires before-quit synchronously; the guard
// there relies on the phase already being terminal.
+ supervisor?.prepareForShutdown()
// Drain a pending coalesced TaskUpdated while consumers are still attached.
taskUpdatePublisher.flush()
windowManager?.setWillQuit(true) // FIRST — never before/during the dialog
@@ -2396,6 +2401,14 @@ function beginShutdown(): void {
.finally(() => app.quit())
}
+function prepareForSessionEnd(): void {
+ // This callback runs from Windows query-session-end/session-end and the
+ // cross-platform powerMonitor shutdown event. Mark the child exit expected
+ // synchronously; the ordinary quit flow performs the graceful stop later.
+ supervisor?.prepareForShutdown()
+ quitController.markSessionEnding()
+}
+
const quitController = new QuitController({
getWarnBeforeQuit: () => settingsManager.getApp().warnBeforeQuit,
getActiveCount: () => countActiveDownloads(taskManager.getAll()),
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 26dfc4d4..563c964a 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -81,6 +81,8 @@ function fakeCtx() {
},
supervisor: {
restart: vi.fn(),
+ applyEngineSettings: vi.fn().mockResolvedValue(undefined),
+ applyAsyncDns: vi.fn().mockResolvedValue(undefined),
recover: vi.fn(),
start: vi.fn(),
stop: vi.fn(),
@@ -176,6 +178,9 @@ function fakeCtx() {
off: vi.fn(),
removeAll: vi.fn(),
},
+ notificationCenter: {
+ notify: vi.fn(() => ({ fresh: true })),
+ },
proxyApplier: {
apply: vi.fn().mockResolvedValue(undefined),
applyAll: vi.fn().mockResolvedValue(undefined),
@@ -670,6 +675,42 @@ describe('buildCommandHandlers', () => {
expect(minimize).toHaveBeenCalledOnce()
})
+ it('ToggleMaximizeCurrentWindow maximizes and restores only its sender window', async () => {
+ const maximize = vi.fn()
+ const unmaximize = vi.fn()
+ const fakeSender = {} as never
+ fromWebContentsMock
+ .mockReturnValueOnce({
+ isDestroyed: vi.fn(() => false),
+ isMaximizable: vi.fn(() => true),
+ isMaximized: vi.fn(() => false),
+ maximize,
+ unmaximize,
+ })
+ .mockReturnValueOnce({
+ isDestroyed: vi.fn(() => false),
+ isMaximizable: vi.fn(() => true),
+ isMaximized: vi.fn(() => true),
+ maximize,
+ unmaximize,
+ })
+ const ctx = fakeCtx()
+ // @ts-expect-error partial ctx
+ const handlers = buildCommandHandlers(ctx)
+
+ await expect(
+ handlers[Commands.ToggleMaximizeCurrentWindow]?.(fakeSender)
+ ).resolves.toEqual({ ok: true })
+ await expect(
+ handlers[Commands.ToggleMaximizeCurrentWindow]?.(fakeSender)
+ ).resolves.toEqual({ ok: true })
+
+ expect(fromWebContentsMock).toHaveBeenNthCalledWith(1, fakeSender)
+ expect(fromWebContentsMock).toHaveBeenNthCalledWith(2, fakeSender)
+ expect(maximize).toHaveBeenCalledOnce()
+ expect(unmaximize).toHaveBeenCalledOnce()
+ })
+
it('routes direct shell commands to their owning collaborators', async () => {
const ctx = fakeCtx()
// @ts-expect-error partial ctx
@@ -821,6 +862,9 @@ describe('buildCommandHandlers', () => {
const minimizeRegistration = ipcHandleMock.mock.calls.find(
([channel]) => channel === Commands.MinimizeCurrentWindow
)
+ const toggleMaximizeRegistration = ipcHandleMock.mock.calls.find(
+ ([channel]) => channel === Commands.ToggleMaximizeCurrentWindow
+ )
const menuContextRegistration = ipcHandleMock.mock.calls.find(
([channel]) => channel === Commands.UpdateMenuContext
)
@@ -829,6 +873,7 @@ describe('buildCommandHandlers', () => {
)
expect(closeRegistration).toBeDefined()
expect(minimizeRegistration).toBeDefined()
+ expect(toggleMaximizeRegistration).toBeDefined()
expect(menuContextRegistration).toBeDefined()
expect(restartRegistration).toBeDefined()
@@ -839,6 +884,13 @@ describe('buildCommandHandlers', () => {
minimize: vi.fn(),
})
await minimizeRegistration?.[1]({ sender })
+ fromWebContentsMock.mockReturnValueOnce({
+ isDestroyed: () => false,
+ isMaximizable: () => true,
+ isMaximized: () => false,
+ maximize: vi.fn(),
+ })
+ await toggleMaximizeRegistration?.[1]({ sender })
await menuContextRegistration?.[1]({ sender }, { currentRoute: '/tasks' })
await restartRegistration?.[1]({})
@@ -857,6 +909,9 @@ describe('buildCommandHandlers', () => {
expect(ipcRemoveHandlerMock).toHaveBeenCalledWith(
Commands.MinimizeCurrentWindow
)
+ expect(ipcRemoveHandlerMock).toHaveBeenCalledWith(
+ Commands.ToggleMaximizeCurrentWindow
+ )
expect(ipcRemoveHandlerMock).toHaveBeenCalledWith(Commands.RestartEngine)
})
@@ -946,7 +1001,8 @@ describe('Commands.UpdateSettings', () => {
proxy: object,
app: object = {},
nat: object = {},
- tracker: object = {}
+ tracker: object = {},
+ engine: object = {}
) {
return {
app: {
@@ -960,7 +1016,7 @@ describe('Commands.UpdateSettings', () => {
...nat,
},
proxy,
- engine: {},
+ engine,
tracker: {
sourcesEnabled: true,
blacklistEnabled: true,
@@ -1029,7 +1085,7 @@ describe('Commands.UpdateSettings', () => {
expect(ctx.supervisor.restart).not.toHaveBeenCalled()
})
- it('invokes supervisor.restart when result.requiresRestart is true', async () => {
+ it('saves restart-required settings and publishes a reminder without restarting', async () => {
const ctx = fakeCtx()
const settings = makeSettingsLike(PROXY_OFF)
const settingsManager = {
@@ -1047,10 +1103,48 @@ describe('Commands.UpdateSettings', () => {
protocolManager: { register: vi.fn() },
} as unknown as CommandContext)
await handlers[Commands.UpdateSettings]?.({ engine: { rpcPort: 9000 } })
- expect(ctx.supervisor.restart).toHaveBeenCalledOnce()
+ expect(ctx.supervisor.restart).not.toHaveBeenCalled()
+ expect(ctx.notificationCenter.notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ kind: 'engine-restart-required',
+ severity: 'warning',
+ })
+ )
+ expect(ctx.eventBus.emit).toHaveBeenCalledWith(
+ Events.EngineRestartRequired,
+ { changedKeys: ['rpcPort'] }
+ )
expect(ctx.proxyApplier.apply).not.toHaveBeenCalled()
})
+ it('hot-applies runtime engine settings without a restart reminder', async () => {
+ const ctx = fakeCtx()
+ const before = makeSettingsLike(PROXY_OFF, {}, {}, {}, { split: 16 })
+ const after = makeSettingsLike(PROXY_OFF, {}, {}, {}, { split: 32 })
+ const settingsManager = {
+ ...ctx.settingsManager,
+ get: vi.fn().mockReturnValueOnce(before).mockReturnValueOnce(after),
+ update: vi.fn().mockResolvedValue({
+ ok: true,
+ requiresRestart: false,
+ changedRestartKeys: [],
+ }),
+ }
+ const handlers = buildCommandHandlers({
+ ...ctx,
+ settingsManager,
+ protocolManager: { register: vi.fn() },
+ } as unknown as CommandContext)
+
+ await handlers[Commands.UpdateSettings]?.({ engine: { split: 32 } })
+
+ expect(ctx.supervisor.applyEngineSettings).toHaveBeenCalledWith(
+ before.engine,
+ after.engine
+ )
+ expect(ctx.notificationCenter.notify).not.toHaveBeenCalled()
+ })
+
it('calls trackerManager.applySourcesChange when sourcesEnabled changes', async () => {
const ctx = fakeCtx()
const before = makeSettingsLike(
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 39763c1c..35703274 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -11,6 +11,8 @@ import { ENGINE_READY_TIMEOUT_MS } from '@core/engine/engine-supervisor'
import type { EventBus } from '@core/events/event-bus'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { getLogger } from '@core/logger'
+import { publishEngineRestartRequired } from '@core/notifications/engine-restart-required'
+import type { NotificationCenter } from '@core/notifications/notification-center'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
import type { GrantsManager } from '@core/plugin/grants/grants-manager'
import { HookAuditLog } from '@core/plugin/hooks/audit-log'
@@ -185,6 +187,7 @@ export interface CommandContext {
torrentMetaStore: TorrentMetaStore
fileCleanupService: FileCleanupService
eventBus: EventBus
+ notificationCenter: Pick<NotificationCenter, 'notify'>
motrixDatabase: MotrixDatabase
geoipManager: GeoIPManager
proxyApplier: ReturnType<typeof createMainProxyApplier>
@@ -270,6 +273,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
torrentMetaStore,
fileCleanupService,
eventBus,
+ notificationCenter,
motrixDatabase,
geoipManager,
proxyApplier,
@@ -922,6 +926,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
trackerManager.applySyncScheduleChange()
}
+ await supervisor.applyEngineSettings(oldFull.engine, newFull.engine)
+
if (oldFull.engine.dnsMode !== newFull.engine.dnsMode) {
await supervisor.applyAsyncDns(
dnsModeToAsyncDns(newFull.engine.dnsMode)
@@ -932,7 +938,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
}
if (result.requiresRestart) {
- await supervisor.restart()
+ publishEngineRestartRequired(
+ { eventBus, notificationCenter, log },
+ result.changedRestartKeys
+ )
}
return result
@@ -989,8 +998,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return { ok: true }
},
- // Minimize only the trusted window that originated the request. This is
- // the Linux frameless-window replacement for a native caption button.
+ // Operate only on the trusted window that originated each custom caption
+ // control request. No renderer can target a different BrowserWindow.
[Commands.MinimizeCurrentWindow]: async (sender: WebContents) => {
const win = BrowserWindow.fromWebContents(sender)
if (win && !win.isDestroyed() && win.isMinimizable()) {
@@ -999,6 +1008,18 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return { ok: true }
},
+ [Commands.ToggleMaximizeCurrentWindow]: async (sender: WebContents) => {
+ const win = BrowserWindow.fromWebContents(sender)
+ if (win && !win.isDestroyed() && win.isMaximizable()) {
+ if (win.isMaximized()) {
+ win.unmaximize()
+ } else {
+ win.maximize()
+ }
+ }
+ return { ok: true }
+ },
+
[Commands.PickSaveDir]: async (params: { defaultPath?: string }) => {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
@@ -1457,6 +1478,7 @@ export function registerCommandHandlers(ctx: CommandContext): () => void {
if (
channel === Commands.CloseCurrentWindow ||
channel === Commands.MinimizeCurrentWindow ||
+ channel === Commands.ToggleMaximizeCurrentWindow ||
channel === Commands.ResizeWindow ||
channel === Commands.UpdateMenuContext
) {
diff --git a/src/main/main-process-work-coordinator.test.ts b/src/main/main-process-work-coordinator.test.ts
index 6ba9f6c3..2630870f 100644
--- a/src/main/main-process-work-coordinator.test.ts
+++ b/src/main/main-process-work-coordinator.test.ts
@@ -173,6 +173,10 @@ describe('MainProcessWorkCoordinator', () => {
performCleanup
)
const beginShutdown = source.indexOf('function beginShutdown()')
+ const prepareEngine = source.indexOf(
+ 'supervisor?.prepareForShutdown()',
+ beginShutdown
+ )
const destroyRenderers = source.indexOf(
'windowManager?.destroyAll()',
beginShutdown
@@ -185,6 +189,8 @@ describe('MainProcessWorkCoordinator', () => {
expect(performCleanup).toBeGreaterThan(-1)
expect(removeHandlers).toBeGreaterThan(performCleanup)
expect(beginShutdown).toBeGreaterThan(-1)
+ expect(prepareEngine).toBeGreaterThan(beginShutdown)
+ expect(prepareEngine).toBeLessThan(destroyRenderers)
expect(destroyRenderers).toBeGreaterThan(beginShutdown)
expect(callCleanup).toBeGreaterThan(destroyRenderers)
})
diff --git a/src/main/nat/motrix-nat-manager.test.ts b/src/main/nat/motrix-nat-manager.test.ts
new file mode 100644
index 00000000..a62d4bfa
--- /dev/null
+++ b/src/main/nat/motrix-nat-manager.test.ts
@@ -0,0 +1,164 @@
+import { type NatEvent, type NatManagerDeps, NatState } from '@motrix/nat'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { MotrixNatManager } from './motrix-nat-manager'
+
+function makeHarness() {
+ let engineReady = true
+ let mappingSucceeds = true
+ const readyListeners: Array<() => void> = []
+ const offConfig = vi.fn()
+ const offReady = vi.fn()
+ const offNetwork = vi.fn()
+ const events: NatEvent[] = []
+ const pcpMap = vi.fn(async () =>
+ mappingSucceeds
+ ? { ok: true, value: { externalPort: 6881, ttl: 3600 } }
+ : { ok: false }
+ )
+ const natPmpMap = vi.fn(async () =>
+ mappingSucceeds ? { ok: true } : { ok: false }
+ )
+ const upnpMap = vi.fn(async () =>
+ mappingSucceeds ? { ok: true } : { ok: false }
+ )
+ const networkMonitor = {
+ start: vi.fn(),
+ stop: vi.fn(),
+ onChange: vi.fn(() => offNetwork),
+ snapshot: vi.fn(() => ({
+ gatewayIp: '192.168.1.1',
+ internalIp: '192.168.1.20',
+ hash: 'network-1',
+ })),
+ }
+ const deps: NatManagerDeps = {
+ hooks: {
+ onReady: vi.fn((listener) => {
+ readyListeners.push(listener)
+ return offReady
+ }),
+ onConfigChanged: vi.fn(() => offConfig),
+ },
+ onEvent: (event) => events.push(event),
+ settingsProvider: {
+ getEngine: () => ({ listenPort: 6881, dhtListenPort: 6882 }),
+ getNat: () => ({
+ enabled: true,
+ preferredProtocol: 'auto',
+ mappingTtl: 3600,
+ natTypeDetectionEnabled: false,
+ stunServers: [],
+ portReachabilityCheckEnabled: false,
+ portCheckerEndpoints: [],
+ }),
+ },
+ upnpClient: {
+ discover: vi.fn(async () => ({
+ ok: true,
+ value: {
+ gatewayIp: '192.168.1.1',
+ controlUrl: '/upnp/control',
+ controlHost: '192.168.1.1',
+ controlPort: 1900,
+ serviceType: 'urn:schemas-upnp-org:service:WANIPConnection:1',
+ manufacturer: 'Router',
+ modelName: 'Test',
+ },
+ })),
+ mapPort: upnpMap,
+ unmapPort: vi.fn(async () => ({ ok: true })),
+ getExternalIp: vi.fn(async () => ({ ok: true, value: '203.0.113.1' })),
+ },
+ pmpPcpClient: {
+ natPmpGetExternalIp: vi.fn(async () => ({ ok: false })),
+ natPmpMap,
+ pcpMap,
+ setGatewayIp: vi.fn(),
+ close: vi.fn(async () => {}),
+ },
+ stunClient: {
+ detectNatType: vi.fn(async () => ({ ok: false })),
+ },
+ portChecker: {
+ checkPortReachable: vi.fn(async () => ({ ok: false })),
+ },
+ networkMonitor,
+ }
+ const manager = new MotrixNatManager(deps, () => engineReady)
+
+ return {
+ events,
+ manager,
+ networkMonitor,
+ offConfig,
+ offNetwork,
+ offReady,
+ pcpMap,
+ readyListeners,
+ setEngineReady(value: boolean) {
+ engineReady = value
+ },
+ setMappingSucceeds(value: boolean) {
+ mappingSucceeds = value
+ },
+ }
+}
+
+describe('MotrixNatManager', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('maps immediately after discovery when the engine is already ready', async () => {
+ const harness = makeHarness()
+
+ await harness.manager.start()
+
+ expect(harness.manager.getStatus()).toMatchObject({
+ state: NatState.Active,
+ retryAttempt: 0,
+ })
+ expect(harness.manager.getStatus().activeMappings).toHaveLength(2)
+ expect(harness.pcpMap).toHaveBeenCalledTimes(2)
+ await harness.manager.stop()
+ })
+
+ it('finishes an automatic retry by rebuilding mappings, not by staying Ready', async () => {
+ vi.useFakeTimers()
+ const harness = makeHarness()
+ harness.setMappingSucceeds(false)
+
+ await harness.manager.start()
+ expect(harness.manager.getStatus()).toMatchObject({
+ state: NatState.Failed,
+ retryAttempt: 1,
+ })
+
+ harness.setMappingSucceeds(true)
+ await vi.advanceTimersByTimeAsync(5_000)
+
+ expect(harness.manager.getStatus()).toMatchObject({
+ state: NatState.Active,
+ retryAttempt: 0,
+ })
+ expect(harness.manager.getStatus().activeMappings).toHaveLength(2)
+ await harness.manager.stop()
+ })
+
+ it('cleans up failed-run subscriptions before a manual enable retry', async () => {
+ const harness = makeHarness()
+ harness.setMappingSucceeds(false)
+ await harness.manager.start()
+ expect(harness.manager.getStatus().state).toBe(NatState.Failed)
+
+ harness.setMappingSucceeds(true)
+ await harness.manager.enable()
+
+ expect(harness.offConfig).toHaveBeenCalledOnce()
+ expect(harness.offReady).toHaveBeenCalledOnce()
+ expect(harness.offNetwork).toHaveBeenCalledOnce()
+ expect(harness.networkMonitor.stop).toHaveBeenCalledOnce()
+ expect(harness.manager.getStatus().state).toBe(NatState.Active)
+ await harness.manager.stop()
+ })
+})
diff --git a/src/main/nat/motrix-nat-manager.ts b/src/main/nat/motrix-nat-manager.ts
new file mode 100644
index 00000000..3460ccce
--- /dev/null
+++ b/src/main/nat/motrix-nat-manager.ts
@@ -0,0 +1,47 @@
+import { NatManager, type NatManagerDeps, NatState } from '@motrix/nat'
+
+/**
+ * App lifecycle fixes layered over the reusable NAT package.
+ *
+ * The package waits for an engine-ready event before mapping. During an
+ * automatic NAT retry, however, aria2 is usually already Ready, so no new
+ * engine event follows rediscovery and the manager can remain in Ready with
+ * zero mappings. Re-checking the current engine snapshot after every
+ * discovery closes that race for startup, network changes, and retries.
+ */
+export class MotrixNatManager extends NatManager {
+ constructor(
+ deps: NatManagerDeps,
+ private readonly isEngineReady: () => boolean
+ ) {
+ super(deps)
+ }
+
+ protected override async runDiscovery(): Promise<void> {
+ await super.runDiscovery()
+ if (this.isEngineReady() && this.getStatus().state === NatState.Ready) {
+ await this.mapConfiguredPorts()
+ }
+ }
+
+ /**
+ * A dormant failure still owns its subscriptions and stale mappings.
+ * Restart it cleanly so repeated Enable clicks do not accumulate duplicate
+ * EventBus/network-monitor listeners, then let discovery build fresh maps.
+ */
+ override async enable(): Promise<void> {
+ const { state } = this.getStatus()
+ if (state !== NatState.Idle && state !== NatState.Stopped) {
+ await this.stop()
+ }
+ await this.start()
+ }
+
+ override async forceRemap(): Promise<void> {
+ if (this.getStatus().state === NatState.Failed) {
+ await this.enable()
+ return
+ }
+ await super.forceRemap()
+ }
+}
diff --git a/src/main/nat/nat-manager-factory.test.ts b/src/main/nat/nat-manager-factory.test.ts
index 056e5e9d..06cce840 100644
--- a/src/main/nat/nat-manager-factory.test.ts
+++ b/src/main/nat/nat-manager-factory.test.ts
@@ -132,6 +132,7 @@ describe('createNatManager', () => {
const result = createNatManager({
eventBus: eventBus as never,
settingsManager: settingsManager as never,
+ isEngineReady: () => false,
})
const options = state.natOptions as CapturedNatOptions
const pmpOptions = state.pmpOptions as {
@@ -170,6 +171,7 @@ describe('createNatManager', () => {
createNatManager({
eventBus: eventBus as never,
settingsManager: {} as never,
+ isEngineReady: () => false,
})
const options = state.natOptions as CapturedNatOptions
const onReady = vi.fn()
@@ -243,6 +245,7 @@ describe('createNatManager', () => {
createNatManager({
eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } as never,
settingsManager: {} as never,
+ isEngineReady: () => false,
})
const pmpOptions = state.pmpOptions as {
gatewayIp: string
diff --git a/src/main/nat/nat-manager-factory.ts b/src/main/nat/nat-manager-factory.ts
index cee7eb51..cdae83d9 100644
--- a/src/main/nat/nat-manager-factory.ts
+++ b/src/main/nat/nat-manager-factory.ts
@@ -6,7 +6,7 @@ import type { SettingsManager } from '@core/settings/settings-manager'
import {
NatErrorCode,
type NatEvent,
- NatManager,
+ type NatManager,
type NatManagerHooks,
NetworkMonitor,
nodeHttpClient,
@@ -20,6 +20,7 @@ import {
import { ErrorCode } from '@shared/errors'
import { Events } from '@shared/protocol/events'
import { EngineState } from '@shared/types/engine'
+import { MotrixNatManager } from './motrix-nat-manager'
const NAT_ERROR_CODE_MAP = {
[NatErrorCode.DiscoveryFailed]: ErrorCode.NatDiscoveryFailed,
@@ -42,8 +43,9 @@ export interface NatStack {
export function createNatManager(args: {
eventBus: EventBus
settingsManager: SettingsManager
+ isEngineReady: () => boolean
}): NatStack {
- const { eventBus, settingsManager } = args
+ const { eventBus, isEngineReady, settingsManager } = args
setNatLogger(getLogger('nat'))
// Derive client internal IP (16-byte v4-mapped IPv6) for PCP requests.
@@ -111,16 +113,19 @@ export function createNatManager(args: {
}
}
- const manager = new NatManager({
- hooks,
- onEvent,
- settingsProvider: new SettingsNatProvider(settingsManager),
- upnpClient,
- pmpPcpClient,
- stunClient,
- portChecker,
- networkMonitor,
- })
+ const manager = new MotrixNatManager(
+ {
+ hooks,
+ onEvent,
+ settingsProvider: new SettingsNatProvider(settingsManager),
+ upnpClient,
+ pmpPcpClient,
+ stunClient,
+ portChecker,
+ networkMonitor,
+ },
+ isEngineReady
+ )
return { manager, networkMonitor }
}
diff --git a/src/main/platform/native-theme-sync.ts b/src/main/platform/native-theme-sync.ts
index a787a943..3e56b519 100644
--- a/src/main/platform/native-theme-sync.ts
+++ b/src/main/platform/native-theme-sync.ts
@@ -11,7 +11,7 @@ export interface NativeThemeSyncHandle {
// Bridges the persisted `app.theme` setting to Electron's `nativeTheme`.
// This is what makes the user's choice flow into:
// - macOS vibrancy material + traffic-light/titlebar tint
-// - Windows 11 titlebar overlay color
+// - Windows custom-title-bar colors through `prefers-color-scheme`
// - the OS-reported `prefers-color-scheme` (and thus the renderer's
// own dark-class application via next-themes when in `system` mode)
// - the Linux tray icon picker (reads `nativeTheme.shouldUseDarkColors`)
diff --git a/src/main/window/platform-options.test.ts b/src/main/window/platform-options.test.ts
index b56a8902..328a2a12 100644
--- a/src/main/window/platform-options.test.ts
+++ b/src/main/window/platform-options.test.ts
@@ -10,28 +10,10 @@ describe('buildPlatformOptions', () => {
expect(opts.trafficLightPosition).toEqual({ x: 20, y: 20 })
})
- it('uses dark title-bar symbols for the light Windows theme', () => {
+ it('hides the Windows title bar without enabling native caption controls', () => {
const opts = buildPlatformOptions('win32')
expect(opts.titleBarStyle).toBe('hidden')
- expect(opts.titleBarOverlay).toEqual({
- color: '#00000000',
- symbolColor: '#1d1d1f',
- height: 54,
- })
- })
-
- it('uses light title-bar symbols for the dark Windows theme', () => {
- const opts = buildPlatformOptions('win32', {
- shouldUseDarkColors: true,
- })
- expect(opts.titleBarOverlay).toMatchObject({ symbolColor: '#f5f5f5' })
- })
-
- it('uses a configured Windows title-bar symbol color', () => {
- const opts = buildPlatformOptions('win32', {
- windowControlsSymbolColor: '#1d1d1f',
- })
- expect(opts.titleBarOverlay).toMatchObject({ symbolColor: '#1d1d1f' })
+ expect(opts.titleBarOverlay).toBeUndefined()
})
it('returns hidden titleBarStyle for Linux', () => {
diff --git a/src/main/window/platform-options.ts b/src/main/window/platform-options.ts
index bc73c7c3..c7694885 100644
--- a/src/main/window/platform-options.ts
+++ b/src/main/window/platform-options.ts
@@ -3,26 +3,11 @@ import type { BrowserWindowConstructorOptions } from 'electron'
export interface PlatformOptionsInput {
vibrancy?: boolean
liquidGlass?: boolean
- shouldUseDarkColors?: boolean
- windowControlsSymbolColor?: string
-}
-
-export const WINDOWS_TITLE_BAR_OVERLAY_HEIGHT = 54
-
-export function getWindowsWindowControlsSymbolColor(
- shouldUseDarkColors: boolean
-): string {
- return shouldUseDarkColors ? '#f5f5f5' : '#1d1d1f'
}
export function buildPlatformOptions(
platform: string = process.platform,
- {
- vibrancy = true,
- liquidGlass = false,
- shouldUseDarkColors = false,
- windowControlsSymbolColor,
- }: PlatformOptionsInput = {}
+ { vibrancy = true, liquidGlass = false }: PlatformOptionsInput = {}
): BrowserWindowConstructorOptions {
switch (platform) {
case 'darwin':
@@ -50,15 +35,6 @@ export function buildPlatformOptions(
case 'win32':
return {
titleBarStyle: 'hidden',
- titleBarOverlay: {
- color: '#00000000',
- symbolColor:
- windowControlsSymbolColor ??
- getWindowsWindowControlsSymbolColor(shouldUseDarkColors),
- // The renderer's 28 px header actions are centered at y=27.
- // Matching that center keeps native caption buttons on their baseline.
- height: WINDOWS_TITLE_BAR_OVERLAY_HEIGHT,
- },
}
default:
return {
diff --git a/src/main/window/window-configs.ts b/src/main/window/window-configs.ts
index 3895bfa6..cba35fad 100644
--- a/src/main/window/window-configs.ts
+++ b/src/main/window/window-configs.ts
@@ -18,7 +18,6 @@ export interface WindowConfig {
vibrancy: boolean
liquidGlass: boolean
transparent?: boolean
- windowControlsSymbolColor?: string
}
export const WINDOW_CONFIGS: Record<WindowId, WindowConfig> = {
@@ -65,6 +64,5 @@ export const WINDOW_CONFIGS: Record<WindowId, WindowConfig> = {
vibrancy: false,
liquidGlass: true,
transparent: false,
- windowControlsSymbolColor: '#1d1d1f',
},
}
diff --git a/src/main/window/window-manager.test.ts b/src/main/window/window-manager.test.ts
index f023a850..2b0d348e 100644
--- a/src/main/window/window-manager.test.ts
+++ b/src/main/window/window-manager.test.ts
@@ -93,14 +93,13 @@ vi.mock('electron', () => {
return {
BrowserWindow: MockBrowserWindow,
- nativeTheme: { shouldUseDarkColors: false },
screen: mockScreen,
shell: { openExternal: vi.fn() },
}
})
import type { SettingsManager } from '@core/settings/settings-manager'
-import { BrowserWindow, nativeTheme } from 'electron'
+import { BrowserWindow } from 'electron'
import type { LiquidGlassController } from './liquid-glass'
import { initializeRendererUrlPolicy } from './renderer-url-policy'
import { WINDOW_CONFIGS } from './window-configs'
@@ -124,9 +123,6 @@ function createMockSettingsManager(
describe('WindowManager', () => {
beforeEach(() => {
;(BrowserWindow as unknown as { instances: unknown[] }).instances.length = 0
- ;(
- nativeTheme as unknown as { shouldUseDarkColors: boolean }
- ).shouldUseDarkColors = false
vi.clearAllMocks()
})
@@ -143,7 +139,7 @@ describe('WindowManager', () => {
expect(wm.get('main')).toBe(win)
})
- it('creates aligned Windows caption controls for the light theme', () => {
+ it('creates a hidden Windows title bar for renderer-drawn controls', () => {
const wm = new WindowManager({
settingsManager: createMockSettingsManager(),
preloadPath: '/fake/preload.cjs',
@@ -154,46 +150,8 @@ describe('WindowManager', () => {
const win = wm.open('main')
const options = (win as unknown as { options: Record<string, unknown> })
.options
- expect(options.titleBarOverlay).toEqual({
- color: '#00000000',
- symbolColor: '#1d1d1f',
- height: 54,
- })
- })
-
- it('creates and refreshes Windows caption controls for the dark theme', () => {
- ;(
- nativeTheme as unknown as { shouldUseDarkColors: boolean }
- ).shouldUseDarkColors = true
- const wm = new WindowManager({
- settingsManager: createMockSettingsManager(),
- preloadPath: '/fake/preload.cjs',
- loadUrl: vi.fn(),
- platform: 'win32',
- })
-
- const main = wm.open('main')
- const onboarding = wm.open('onboarding')
- const mainOptions = (
- main as unknown as { options: Record<string, unknown> }
- ).options
- expect(mainOptions.titleBarOverlay).toMatchObject({
- symbolColor: '#f5f5f5',
- height: 54,
- })
-
- wm.syncWindowControlsTheme(true)
-
- expect(main.setTitleBarOverlay).toHaveBeenCalledWith({
- color: '#00000000',
- symbolColor: '#f5f5f5',
- height: 54,
- })
- expect(onboarding.setTitleBarOverlay).toHaveBeenCalledWith({
- color: '#00000000',
- symbolColor: '#1d1d1f',
- height: 54,
- })
+ expect(options.titleBarStyle).toBe('hidden')
+ expect(options.titleBarOverlay).toBeUndefined()
})
it('uses the explicit secure Electron renderer defaults', () => {
@@ -506,6 +464,29 @@ describe('WindowManager', () => {
expect(win.hide).not.toHaveBeenCalled()
})
+ it('reports both early and terminal Windows session-end signals', () => {
+ const onSessionEnd = vi.fn()
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ onSessionEnd,
+ })
+ const win = wm.open('main')
+ const listeners = (win.on as unknown as ReturnType<typeof vi.fn>).mock.calls
+ const querySessionEnd = listeners.find(
+ ([event]) => event === 'query-session-end'
+ )?.[1] as (() => void) | undefined
+ const sessionEnd = listeners.find(
+ ([event]) => event === 'session-end'
+ )?.[1] as (() => void) | undefined
+
+ querySessionEnd?.()
+ sessionEnd?.()
+
+ expect(onSessionEnd).toHaveBeenCalledTimes(2)
+ })
+
it('close destroys add-task window', () => {
const sm = createMockSettingsManager()
const wm = new WindowManager({
diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.ts
index cc4c67ac..97b27ce9 100644
--- a/src/main/window/window-manager.ts
+++ b/src/main/window/window-manager.ts
@@ -3,7 +3,7 @@ import type { SettingsManager } from '@core/settings/settings-manager'
import { Events } from '@shared/protocol/events'
import type { AddTaskUrlParams } from '@shared/schemas/add-task'
import type { WindowBounds } from '@shared/types/settings'
-import { BrowserWindow, nativeTheme, screen, shell } from 'electron'
+import { BrowserWindow, screen, shell } from 'electron'
import type { LiquidGlassController } from './liquid-glass'
import { buildPlatformOptions } from './platform-options'
import {
@@ -29,7 +29,7 @@ export interface WindowManagerDeps {
previewMacMenu?: boolean
/** Central legal/startup gate for every window-opening entry point. */
resolveOpenTarget?: (requested: WindowId) => WindowId
- /** Invoked when the OS signals session end (Windows window 'session-end'). */
+ /** Invoked when Windows first queries or confirms that the session will end. */
onSessionEnd?: () => void
/** Frozen renderer trust policy shared with IPC sender validation. */
rendererUrlPolicy?: RendererUrlPolicy
@@ -236,22 +236,6 @@ export class WindowManager {
}
}
- syncWindowControlsTheme(shouldUseDarkColors: boolean): void {
- const platform = this.deps.platform ?? process.platform
- if (platform !== 'win32') return
-
- for (const [id, win] of this.windows.entries()) {
- if (!win || win.isDestroyed()) continue
- const config = WINDOW_CONFIGS[id]
- const titleBarOverlay = buildPlatformOptions('win32', {
- shouldUseDarkColors,
- windowControlsSymbolColor: config.windowControlsSymbolColor,
- }).titleBarOverlay
- if (!titleBarOverlay || typeof titleBarOverlay === 'boolean') continue
- win.setTitleBarOverlay(titleBarOverlay)
- }
- }
-
setWillQuit(value: boolean): void {
this.willQuit = value
}
@@ -331,8 +315,6 @@ export class WindowManager {
const platformOpts = buildPlatformOptions(platform, {
vibrancy: config.vibrancy && !liquidGlass,
liquidGlass,
- shouldUseDarkColors: nativeTheme.shouldUseDarkColors,
- windowControlsSymbolColor: config.windowControlsSymbolColor,
})
const win = new BrowserWindow({
@@ -463,6 +445,7 @@ export class WindowManager {
})
if (id === 'main') {
+ win.on('query-session-end', () => this.deps.onSessionEnd?.())
win.on('session-end', () => this.deps.onSessionEnd?.())
}
}
diff --git a/src/renderer/components/desktop-kit/panel/header-action-button.test.tsx b/src/renderer/components/desktop-kit/panel/header-action-button.test.tsx
index 854ce17f..c226cf68 100644
--- a/src/renderer/components/desktop-kit/panel/header-action-button.test.tsx
+++ b/src/renderer/components/desktop-kit/panel/header-action-button.test.tsx
@@ -78,7 +78,7 @@ describe('HeaderActionButton', () => {
expect(button).toHaveTextContent('Add')
})
- it('renders icon-only on the 28px row in the compact header', () => {
+ it('keeps a 16px icon in a 28px target on the collapsed header centerline', () => {
stubCompactEnvironment()
render(
<SidebarProvider defaultOpen={false}>
@@ -89,7 +89,14 @@ describe('HeaderActionButton', () => {
)
const button = screen.getByRole('button', { name: 'Install' })
- expect(button).toHaveClass('h-7')
+ expect(button).toHaveClass(
+ 'size-7',
+ 'p-0',
+ '[&>svg]:size-4',
+ '[&>svg]:opacity-50',
+ 'hover:[&>svg]:opacity-75'
+ )
+ expect(button).not.toHaveClass('[&>svg]:translate-y-0.5')
expect(button).not.toHaveTextContent('Install')
})
})
diff --git a/src/renderer/components/desktop-kit/panel/header-action-button.tsx b/src/renderer/components/desktop-kit/panel/header-action-button.tsx
index d6920f8f..9fcdde7d 100644
--- a/src/renderer/components/desktop-kit/panel/header-action-button.tsx
+++ b/src/renderer/components/desktop-kit/panel/header-action-button.tsx
@@ -8,10 +8,11 @@ import {
import type React from 'react'
import { useCompactHeader } from '../hooks/use-compact-header'
-// Compact buttons mirror the 28px window-chrome row (AddTaskTriggerButton
-// is size-[28px] with a size-4 icon) so hit targets stay comfortable in
-// the short header. Icons keep Button's default size-4.
-export const COMPACT_ACTION_CLASS = 'h-7 px-1.5'
+// Compact panel actions share the window chrome controls' 28px hit target.
+// Keep the glyph geometrically centered inside that target; the complete
+// button stays on the shared WindowChrome centerline.
+export const COMPACT_ACTION_CLASS =
+ 'size-7 p-0 [&>svg]:size-4 [&>svg]:opacity-50 hover:[&>svg]:opacity-75 focus-visible:[&>svg]:opacity-75'
/**
* A PanelShell header action that adapts to the compact header: full mode
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
index 23df641a..272bb613 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
@@ -54,8 +54,8 @@ describe('PanelShell', () => {
</PanelShell>
)
expect(container.querySelector('header')).toHaveClass(
- 'compact-header:pl-[var(--window-chrome-safe-area-leading)]',
- 'compact-header:pr-[var(--window-chrome-safe-area-trailing)]'
+ 'compact-header:ps-[var(--window-chrome-safe-area-leading)]',
+ 'compact-header:pe-[var(--window-chrome-safe-area-trailing)]'
)
})
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
index 45f37fe4..65be454f 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
@@ -37,14 +37,14 @@ export function PanelShell({
{/* PanelShell header */}
<header
className={cn(
- 'flex shrink-0 items-start justify-between gap-4 px-6 pt-8 pb-4 transition-[padding] duration-200',
+ 'flex shrink-0 items-start justify-between gap-4 px-6 pt-9 pb-4 transition-[padding] duration-200',
// Compact rows center on the window-chrome icon line: the overlay
// strip renders its 28px buttons at window y 13..41 (pt-[14px]
// wrapper in AppLayout), i.e. centerline y=27. The inset sits 8px
// down (m-2), so 5px top padding centers a 28px row at
// 8 + 5 + 14 = 27 — same line as the traffic lights ({x:20,y:20}).
'compact-header:py-[5px]',
- 'compact-header:pl-[var(--window-chrome-safe-area-leading)] compact-header:pr-[var(--window-chrome-safe-area-trailing)]',
+ 'compact-header:ps-[var(--window-chrome-safe-area-leading)] compact-header:pe-[var(--window-chrome-safe-area-trailing)]',
headerClassName
)}
>
@@ -56,6 +56,7 @@ export function PanelShell({
title
)}
<div
+ data-slot="panel-shell-actions"
// Keep actions above the z-30 WindowChrome drag strip but below the
// z-50 modal layer so dialogs always cover background controls.
className="app-no-drag relative z-40 flex shrink-0 items-center gap-2"
diff --git a/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx b/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx
index f3f6b3b3..983d73c2 100644
--- a/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx
+++ b/src/renderer/components/desktop-kit/sidebar/app-sidebar.test.tsx
@@ -99,6 +99,35 @@ describe('AppSidebar', () => {
}
})
+ it('matches footer item sizing and horizontal inset to the main navigation', () => {
+ render(wrap(<AppSidebar />))
+
+ const dashboard = screen
+ .getByText('Dashboard')
+ .closest('[data-slot="sidebar-menu-button"]')
+ const notifications = screen
+ .getByText('Notifications')
+ .closest('[data-slot="sidebar-menu-button"]')
+ const settings = screen
+ .getByText('Settings')
+ .closest('[data-slot="sidebar-menu-button"]')
+ const mainGroup = dashboard?.closest('[data-slot="sidebar-group"]')
+ const footer = settings?.closest('[data-slot="sidebar-footer"]')
+
+ expect(mainGroup).toHaveClass('p-[2px]')
+ expect(footer).toHaveClass('px-0.5')
+ for (const item of [dashboard, notifications, settings]) {
+ expect(item).toHaveAttribute('data-size', 'default')
+ expect(item).toHaveClass(
+ 'h-[38px]',
+ 'px-2.5',
+ 'py-3',
+ 'gap-2',
+ '[&>svg]:size-4'
+ )
+ }
+ })
+
it('renders the Notifications entry before a separator before Settings in the footer', () => {
render(wrap(<AppSidebar />))
@@ -133,9 +162,11 @@ describe('AppSidebar', () => {
.closest('[data-sidebar="menu"]')
const separator = footerMenu?.querySelector('[data-sidebar="separator"]')
expect(separator).not.toBeNull()
+ expect(separator).toHaveClass('mx-0', 'w-auto')
const wrapper = separator?.parentElement
expect(wrapper?.tagName).toBe('LI')
+ expect(wrapper).toHaveClass('relative')
expect(wrapper).toHaveAttribute('aria-hidden', 'true')
})
diff --git a/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx b/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx
index c33a7475..3c67d1ce 100644
--- a/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx
+++ b/src/renderer/components/desktop-kit/sidebar/app-sidebar.tsx
@@ -80,11 +80,11 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
- <SidebarFooter>
+ <SidebarFooter className="px-0.5">
<SidebarMenu>
<NotificationsNavItem />
<SidebarMenuItem aria-hidden="true">
- <SidebarSeparator />
+ <SidebarSeparator className="mx-0" />
</SidebarMenuItem>
{FOOTER_NAV_ITEMS.map((item) => {
const Icon = item.icon
diff --git a/src/renderer/components/settings-kit/restart-confirm-dialog.tsx b/src/renderer/components/settings-kit/restart-confirm-dialog.tsx
deleted file mode 100644
index aab3f568..00000000
--- a/src/renderer/components/settings-kit/restart-confirm-dialog.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { Button } from '@renderer/components/ui/button'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@renderer/components/ui/dialog'
-import { useTranslation } from 'react-i18next'
-
-export interface RestartConfirmDialogProps {
- open: boolean
- onResolve: (confirmed: boolean) => void
-}
-
-export function RestartConfirmDialog({
- open,
- onResolve,
-}: RestartConfirmDialogProps) {
- const { t } = useTranslation()
- return (
- <Dialog open={open} onOpenChange={(v) => !v && onResolve(false)}>
- <DialogContent className="sm:max-w-[420px]">
- <DialogHeader>
- <DialogTitle>{t('settings.common.restartConfirm.title')}</DialogTitle>
- <DialogDescription>
- {t('settings.common.restartConfirm.body')}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => onResolve(false)}
- >
- {t('common.cancel')}
- </Button>
- <Button type="button" size="sm" onClick={() => onResolve(true)}>
- {t('settings.common.restartConfirm.confirm')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/src/renderer/components/settings-kit/use-restart-confirm-dialog.test.tsx b/src/renderer/components/settings-kit/use-restart-confirm-dialog.test.tsx
deleted file mode 100644
index 01732126..00000000
--- a/src/renderer/components/settings-kit/use-restart-confirm-dialog.test.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { act, renderHook } from '@testing-library/react'
-import { describe, expect, it } from 'vitest'
-import { useRestartConfirmDialog } from './use-restart-confirm-dialog'
-
-describe('useRestartConfirmDialog', () => {
- it('opens on confirm() and resolves true on handleResolve(true)', async () => {
- const { result } = renderHook(() => useRestartConfirmDialog())
- expect(result.current.open).toBe(false)
-
- let promise!: Promise<boolean>
- act(() => {
- promise = result.current.confirm()
- })
- expect(result.current.open).toBe(true)
-
- act(() => {
- result.current.handleResolve(true)
- })
- await expect(promise).resolves.toBe(true)
- expect(result.current.open).toBe(false)
- })
-
- it('resolves false on handleResolve(false)', async () => {
- const { result } = renderHook(() => useRestartConfirmDialog())
- let promise!: Promise<boolean>
- act(() => {
- promise = result.current.confirm()
- })
- act(() => {
- result.current.handleResolve(false)
- })
- await expect(promise).resolves.toBe(false)
- })
-})
diff --git a/src/renderer/components/settings-kit/use-restart-confirm-dialog.ts b/src/renderer/components/settings-kit/use-restart-confirm-dialog.ts
deleted file mode 100644
index e4e68c2a..00000000
--- a/src/renderer/components/settings-kit/use-restart-confirm-dialog.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useCallback, useRef, useState } from 'react'
-
-export function useRestartConfirmDialog() {
- const [open, setOpen] = useState(false)
- const resolverRef = useRef<((v: boolean) => void) | null>(null)
-
- const confirm = useCallback(
- () =>
- new Promise<boolean>((resolve) => {
- resolverRef.current = resolve
- setOpen(true)
- }),
- []
- )
-
- const handleResolve = useCallback((confirmed: boolean) => {
- resolverRef.current?.(confirmed)
- resolverRef.current = null
- setOpen(false)
- }, [])
-
- return { confirm, open, handleResolve }
-}
diff --git a/src/renderer/components/ui/toast.test.tsx b/src/renderer/components/ui/toast.test.tsx
index cb9360ed..dc58b1ee 100644
--- a/src/renderer/components/ui/toast.test.tsx
+++ b/src/renderer/components/ui/toast.test.tsx
@@ -90,8 +90,35 @@ describe('toast', () => {
const viewport = baseElement.querySelector('[class*="z-[100]"]')
expect(viewport).not.toBeNull()
expect(viewport?.className).toContain('max-w-[calc(100vw-2rem)]')
+ expect(viewport).toHaveClass('end-4')
+ expect(viewport).not.toHaveClass('right-4')
})
+ it.each(['win32', 'linux'] as const)(
+ 'positions %s toasts below the custom caption controls',
+ async (platform) => {
+ Object.defineProperty(window, 'motrix', {
+ value: { ...window.motrix, platform },
+ configurable: true,
+ })
+ try {
+ const { baseElement } = render(<Toaster />)
+ add({ title: 'safe area probe' })
+ await screen.findByText('safe area probe')
+ const viewport = baseElement.querySelector(
+ '[aria-label="Notifications"]'
+ ) as HTMLElement | null
+ expect(viewport).toHaveStyle({ top: '56px' })
+ expect(viewport).not.toHaveClass('top-4')
+ } finally {
+ Object.defineProperty(window, 'motrix', {
+ value: { ...window.motrix, platform: 'darwin' },
+ configurable: true,
+ })
+ }
+ }
+ )
+
it('labels the viewport region for screen readers, translated with the locale', async () => {
const { baseElement } = render(<Toaster />)
add({ title: 'probe region' })
diff --git a/src/renderer/components/ui/toast.tsx b/src/renderer/components/ui/toast.tsx
index 59188df4..d0fb1b61 100644
--- a/src/renderer/components/ui/toast.tsx
+++ b/src/renderer/components/ui/toast.tsx
@@ -1,7 +1,12 @@
import { Toast } from '@base-ui/react/toast'
import { Button } from '@renderer/components/ui/button'
import { SEVERITY_ICONS } from '@renderer/components/ui/severity-icons'
+import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
+import {
+ DESKTOP_WINDOW_CHROME_HEIGHT,
+ WINDOW_CHROME_EDGE_GAP,
+} from '@shared/constants/window-chrome'
import type { PairRequestPayload } from '@shared/protocol/bridge'
import { XIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
@@ -147,6 +152,11 @@ function ToastList() {
export function Toaster() {
const { t } = useTranslation()
+ const avoidDesktopChrome =
+ __MOTRIX_TARGET__ === 'electron' &&
+ (transport.platform === 'win32' ||
+ transport.platform === 'linux' ||
+ (transport.platform === 'darwin' && __MOTRIX_PREVIEW_MAC_MENU__))
return (
// Base UI defaults `limit` to 3; the 4th-oldest toast onward gets
// `data-limited` (styled below as invisible + unclickable). A live
@@ -159,7 +169,17 @@ export function Toaster() {
<Toast.Portal>
<Toast.Viewport
aria-label={t('notification.center.toastRegionAria')}
- className="pointer-events-none fixed top-4 right-4 z-[100] flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2 outline-none"
+ className={cn(
+ 'pointer-events-none fixed end-4 z-[100] flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2 outline-none',
+ !avoidDesktopChrome && 'top-4'
+ )}
+ style={
+ avoidDesktopChrome
+ ? {
+ top: DESKTOP_WINDOW_CHROME_HEIGHT + WINDOW_CHROME_EDGE_GAP,
+ }
+ : undefined
+ }
>
<ToastList />
</Toast.Viewport>
diff --git a/src/renderer/components/window-chrome/add-task-trigger-button.test.tsx b/src/renderer/components/window-chrome/add-task-trigger-button.test.tsx
index 531587bf..a9e56665 100644
--- a/src/renderer/components/window-chrome/add-task-trigger-button.test.tsx
+++ b/src/renderer/components/window-chrome/add-task-trigger-button.test.tsx
@@ -56,4 +56,13 @@ describe('AddTaskTriggerButton', () => {
})
expect(openMock).not.toHaveBeenCalled()
})
+
+ it('shares the window-chrome icon opacity treatment', () => {
+ renderWithProviders()
+ expect(screen.getByRole('button', { name: /new task/i })).toHaveClass(
+ '[&>svg]:opacity-50',
+ 'hover:[&>svg]:opacity-75',
+ 'focus-visible:[&>svg]:opacity-75'
+ )
+ })
})
diff --git a/src/renderer/components/window-chrome/add-task-trigger-button.tsx b/src/renderer/components/window-chrome/add-task-trigger-button.tsx
index 90632284..a56b0285 100644
--- a/src/renderer/components/window-chrome/add-task-trigger-button.tsx
+++ b/src/renderer/components/window-chrome/add-task-trigger-button.tsx
@@ -26,7 +26,7 @@ export function AddTaskTriggerButton({
size="icon"
aria-label={t('chrome.newTask')}
className={cn(
- 'app-no-drag size-7 opacity-50 bg-transparent hover:opacity-75 hover:bg-accent focus-visible:opacity-75',
+ 'app-no-drag size-7 bg-transparent [&>svg]:opacity-50 hover:bg-accent hover:[&>svg]:opacity-75 focus-visible:[&>svg]:opacity-75',
className
)}
onClick={onClick}
diff --git a/src/renderer/components/window-chrome/window-chrome.test.tsx b/src/renderer/components/window-chrome/window-chrome.test.tsx
index 40554f02..00fecfd1 100644
--- a/src/renderer/components/window-chrome/window-chrome.test.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.test.tsx
@@ -3,7 +3,7 @@ import '@testing-library/jest-dom/vitest'
import { Commands } from '@shared/protocol/commands'
import { fireEvent, render, screen } from '@testing-library/react'
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
-import { WindowChrome } from './window-chrome'
+import { shouldShowDesktopWindowControls, WindowChrome } from './window-chrome'
beforeAll(() => {
// stub the preload bridge read by the module on import
@@ -33,6 +33,13 @@ beforeEach(() => {
})
describe('WindowChrome', () => {
+ it('uses the macOS menu-preview env branch to expose custom controls', () => {
+ expect(shouldShowDesktopWindowControls('darwin', false)).toBe(false)
+ expect(shouldShowDesktopWindowControls('darwin', true)).toBe(true)
+ expect(shouldShowDesktopWindowControls('win32', false)).toBe(true)
+ expect(shouldShowDesktopWindowControls('linux', false)).toBe(true)
+ })
+
it('renders no title text in overlay variant', () => {
render(<WindowChrome variant="overlay" title="ignored" />)
expect(screen.queryByText('ignored')).toBeNull()
@@ -47,6 +54,12 @@ describe('WindowChrome', () => {
expect(el.style.right).toBe('0px')
})
+ it('offsets macOS actions 94 px from the left edge', () => {
+ const { container } = render(<WindowChrome variant="overlay" />)
+
+ expect((container.firstChild as HTMLElement).style.paddingLeft).toBe('94px')
+ })
+
it('renders the title text in titled variant', () => {
render(<WindowChrome variant="titled" title="My Window" />)
expect(screen.getByText('My Window')).toBeInTheDocument()
@@ -74,21 +87,42 @@ describe('WindowChrome', () => {
</WindowChrome>
)
- expect(
- container.querySelector('[data-slot="window-chrome-actions"]')
- ).not.toHaveClass('ml-auto')
+ const actions = container.querySelector(
+ '[data-slot="window-chrome-actions"]'
+ )
+ const dragRegion = container.querySelector(
+ '[data-slot="window-chrome-drag-region"]'
+ )
+ expect(actions?.compareDocumentPosition(dragRegion as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
})
- it('supports explicitly right-aligned child actions', () => {
+ it('places end actions after the drag region and separates caption controls', () => {
+ setPlatform('win32')
const { container } = render(
<WindowChrome variant="titled" actionsPosition="end">
<button type="button">Trigger</button>
</WindowChrome>
)
- expect(
- container.querySelector('[data-slot="window-chrome-actions"]')
- ).toHaveClass('ml-auto')
+ const dragRegion = container.querySelector(
+ '[data-slot="window-chrome-drag-region"]'
+ )
+ const actions = container.querySelector(
+ '[data-slot="window-chrome-actions"]'
+ )
+ const controls = container.querySelector(
+ '[data-slot="desktop-window-controls"]'
+ )
+ expect(dragRegion).toHaveClass('min-w-16', 'flex-1')
+ expect(dragRegion?.compareDocumentPosition(actions as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
+ expect(actions?.compareDocumentPosition(controls as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
+ expect(controls).toHaveClass('ms-4')
})
it('renders a vertically aligned no-drag leading slot before actions', () => {
@@ -107,67 +141,176 @@ describe('WindowChrome', () => {
const actions = container.querySelector(
'[data-slot="window-chrome-actions"]'
)
- expect(leading).toHaveClass('app-no-drag', 'pt-3.5', 'mr-1.5')
+ expect(leading).toHaveClass('app-no-drag', 'pt-3.5', 'me-1.5')
expect(leading?.compareDocumentPosition(actions as Node)).toBe(
Node.DOCUMENT_POSITION_FOLLOWING
)
})
- it('keeps Linux controls trailing for start-positioned actions', () => {
- setPlatform('linux')
- const { container } = render(
- <WindowChrome variant="overlay">
- <button type="button">Action</button>
- </WindowChrome>
- )
+ it.each(['linux', 'win32'] as const)(
+ 'aligns the %s menu-state sidebar toggle 94 px from the left edge',
+ (platform) => {
+ setPlatform(platform)
+ const { container } = render(
+ <WindowChrome
+ variant="overlay"
+ leading={<div className="w-[72px]">Menu</div>}
+ >
+ <button type="button">Toggle sidebar</button>
+ </WindowChrome>
+ )
- const actions = container.querySelector(
- '[data-slot="window-chrome-actions"]'
- )
- const controls = container.querySelector('.window-controls')
- expect(controls).toHaveClass('ml-auto')
- expect(controls).toHaveStyle({ paddingTop: '14px' })
- expect((container.firstChild as HTMLElement).style.paddingRight).toBe(
- '16px'
- )
- expect(actions?.compareDocumentPosition(controls as Node)).toBe(
- Node.DOCUMENT_POSITION_FOLLOWING
- )
- })
+ const chrome = container.firstChild as HTMLElement
+ const leading = container.querySelector(
+ '[data-slot="window-chrome-leading"]'
+ )
+ const actions = container.querySelector(
+ '[data-slot="window-chrome-actions"]'
+ )
+ expect(chrome.style.paddingInlineStart).toBe('12px')
+ expect(leading).toHaveClass('me-1.5')
+ expect(actions).toHaveClass('ms-1')
+ }
+ )
- it('uses the theme foreground color for Linux caption controls', () => {
- setPlatform('linux')
+ it.each(['linux', 'win32'] as const)(
+ 'keeps %s controls at the logical end for start-positioned actions',
+ (platform) => {
+ setPlatform(platform)
+ const { container } = render(
+ <WindowChrome variant="overlay">
+ <button type="button">Action</button>
+ </WindowChrome>
+ )
+
+ const actions = container.querySelector(
+ '[data-slot="window-chrome-actions"]'
+ )
+ const controls = container.querySelector(
+ '[data-slot="desktop-window-controls"]'
+ )
+ const dragRegion = container.querySelector(
+ '[data-slot="window-chrome-drag-region"]'
+ )
+ expect(dragRegion).toHaveClass('min-w-16', 'flex-1')
+ expect(controls).toHaveClass('pe-3.5', 'pt-3.5')
+ expect(controls).not.toHaveClass('ms-4')
+ expect((container.firstChild as HTMLElement).style.paddingInlineEnd).toBe(
+ '0px'
+ )
+ expect(actions?.compareDocumentPosition(dragRegion as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
+ expect(dragRegion?.compareDocumentPosition(controls as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
+ }
+ )
+
+ it.each(['linux', 'win32'] as const)(
+ 'renders aligned 28 px %s caption hit targets with 16 px icons',
+ (platform) => {
+ setPlatform(platform)
+ const { container } = render(<WindowChrome variant="overlay" />)
+ const chrome = container.firstChild as HTMLElement
+ const controls = container.querySelector(
+ '[data-slot="desktop-window-controls"]'
+ )
+ expect(chrome.style.height).toBe('40px')
+ expect(controls).toHaveClass('gap-2', 'pe-3.5', 'pt-3.5')
+ const buttons = [
+ screen.getByRole('button', { name: 'Minimize' }),
+ screen.getByRole('button', { name: 'Maximize or restore' }),
+ screen.getByRole('button', { name: 'Close' }),
+ ]
+ for (const button of buttons) {
+ expect(button).toHaveClass('size-7')
+ expect(button.querySelector('svg')).toHaveClass('size-4')
+ }
+ }
+ )
+
+ it('uses theme-aware caption colors with a readable destructive hover', () => {
+ setPlatform('win32')
render(<WindowChrome variant="overlay" />)
const minimize = screen.getByRole('button', { name: 'Minimize' })
const close = screen.getByRole('button', { name: 'Close' })
- expect(minimize).toHaveStyle({ color: 'var(--color-foreground)' })
- expect(close).toHaveStyle({ color: 'var(--color-foreground)' })
+ expect(minimize).toHaveClass(
+ 'text-foreground',
+ '[&>svg]:opacity-50',
+ 'hover:bg-accent',
+ 'hover:text-accent-foreground',
+ 'hover:[&>svg]:opacity-75',
+ 'dark:hover:bg-accent/50'
+ )
+ expect(close).toHaveClass(
+ 'text-foreground',
+ '[&>svg]:opacity-50',
+ 'hover:bg-destructive',
+ 'hover:text-white',
+ 'hover:[&>svg]:opacity-100',
+ 'dark:hover:bg-destructive/80'
+ )
+ expect(close).not.toHaveClass('hover:text-destructive-foreground')
})
- it('routes Linux caption controls to sender-bound window commands', () => {
- setPlatform('linux')
- render(<WindowChrome variant="overlay" />)
+ it.each(['linux', 'win32'] as const)(
+ 'routes %s caption controls to sender-bound window commands',
+ (platform) => {
+ setPlatform(platform)
+ render(<WindowChrome variant="overlay" />)
- fireEvent.click(screen.getByRole('button', { name: 'Minimize' }))
- fireEvent.click(screen.getByRole('button', { name: 'Close' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Minimize' }))
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Maximize or restore' })
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))
- expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
- 1,
- Commands.MinimizeCurrentWindow
- )
- expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
- 2,
- Commands.CloseCurrentWindow
- )
+ expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
+ 1,
+ Commands.MinimizeCurrentWindow
+ )
+ expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
+ 2,
+ Commands.ToggleMaximizeCurrentWindow
+ )
+ expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
+ 3,
+ Commands.CloseCurrentWindow
+ )
+ }
+ )
+
+ it('disables maximize for fixed-size windows', () => {
+ setPlatform('win32')
+ render(<WindowChrome variant="titled" maximizable={false} />)
+
+ expect(
+ screen.getByRole('button', { name: 'Maximize or restore' })
+ ).toBeDisabled()
})
- it('reserves the Windows caption-button area with a visual gap', () => {
+ it('aligns app and caption controls on the shared compact baseline', () => {
setPlatform('win32')
- const { container } = render(<WindowChrome variant="overlay" />)
- expect((container.firstChild as HTMLElement).style.paddingRight).toBe(
- '154px'
+ const { container } = render(
+ <WindowChrome
+ variant="overlay"
+ leading={<button type="button">Menu</button>}
+ >
+ <button type="button">Action</button>
+ </WindowChrome>
)
+
+ expect(
+ container.querySelector('[data-slot="window-chrome-leading"]')
+ ).toHaveClass('pt-3.5')
+ expect(
+ container.querySelector('[data-slot="window-chrome-actions"]')
+ ).toHaveClass('pt-3.5')
+ expect(
+ container.querySelector('[data-slot="desktop-window-controls"]')
+ ).toHaveClass('pt-3.5')
})
})
diff --git a/src/renderer/components/window-chrome/window-chrome.tsx b/src/renderer/components/window-chrome/window-chrome.tsx
index 271f5fd4..1d130955 100644
--- a/src/renderer/components/window-chrome/window-chrome.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.tsx
@@ -1,98 +1,130 @@
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
+import { DESKTOP_WINDOW_CHROME_HEIGHT } from '@shared/constants/window-chrome'
import { Commands } from '@shared/protocol/commands'
+import { MinusIcon, SquareIcon, XIcon } from 'lucide-react'
import type React from 'react'
import { useTranslation } from 'react-i18next'
-const WINDOWS_CAPTION_CONTROLS_WIDTH = 138
-const CAPTION_CONTROLS_EDGE_GAP = 16
-const CAPTION_CONTROLS_TOP_PADDING = 14
-
-function LinuxWindowControls({ pushToEnd }: { pushToEnd: boolean }) {
+function DesktopWindowControls({
+ maximizable,
+ separateFromActions,
+}: {
+ maximizable: boolean
+ separateFromActions: boolean
+}) {
const { t } = useTranslation()
const minimize = () => {
void transport.invoke(Commands.MinimizeCurrentWindow)
}
+ const toggleMaximize = () => {
+ void transport.invoke(Commands.ToggleMaximizeCurrentWindow)
+ }
const close = () => {
void transport.invoke(Commands.CloseCurrentWindow)
}
+ const buttonClassName =
+ 'app-no-drag flex size-7 shrink-0 items-center justify-center rounded-md border-0 bg-transparent text-foreground outline-none transition-colors [&>svg]:opacity-50 hover:[&>svg]:opacity-75 focus-visible:[&>svg]:opacity-75 focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-30'
+ const standardButtonClassName = cn(
+ buttonClassName,
+ 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50'
+ )
+
return (
<div
- className={cn('window-controls app-no-drag', pushToEnd && 'ml-auto')}
- style={{
- display: 'flex',
- gap: 8,
- paddingTop: CAPTION_CONTROLS_TOP_PADDING,
- }}
+ data-slot="desktop-window-controls"
+ className={cn(
+ 'flex shrink-0 items-center gap-2 pe-3.5 pt-3.5',
+ separateFromActions && 'ms-4'
+ )}
>
<button
type="button"
+ className={standardButtonClassName}
onClick={minimize}
- style={controlButtonStyle}
aria-label={t('chrome.minimize')}
+ title={t('chrome.minimize')}
+ >
+ <MinusIcon aria-hidden className="size-4" strokeWidth={1.5} />
+ </button>
+ <button
+ type="button"
+ className={standardButtonClassName}
+ disabled={!maximizable}
+ onClick={toggleMaximize}
+ aria-label={t('chrome.toggleMaximize')}
+ title={t('chrome.toggleMaximize')}
>
- &#x2013;
+ <SquareIcon aria-hidden className="size-4" strokeWidth={1.5} />
</button>
<button
type="button"
+ className={cn(
+ buttonClassName,
+ 'hover:bg-destructive hover:text-white hover:[&>svg]:opacity-100 dark:hover:bg-destructive/80'
+ )}
onClick={close}
- style={controlButtonStyle}
aria-label={t('chrome.close')}
+ title={t('chrome.close')}
>
- &#x2715;
+ <XIcon aria-hidden className="size-4" strokeWidth={1.5} />
</button>
</div>
)
}
-const controlButtonStyle: React.CSSProperties = {
- background: 'transparent',
- border: 'none',
- color: 'var(--color-foreground)',
- cursor: 'pointer',
- fontSize: 14,
- padding: '4px 8px',
- borderRadius: 4,
- lineHeight: 1,
-}
-
interface WindowChromeProps {
actionsPosition?: 'start' | 'end'
compact?: boolean
+ maximizable?: boolean
+ previewDesktopControls?: boolean
title?: string
variant?: 'overlay' | 'titled'
leading?: React.ReactNode
children?: React.ReactNode
}
+export function shouldShowDesktopWindowControls(
+ platform: NodeJS.Platform | 'web',
+ previewMacMenu: boolean
+): boolean {
+ return (
+ platform === 'linux' ||
+ platform === 'win32' ||
+ (platform === 'darwin' && previewMacMenu)
+ )
+}
+
export function WindowChrome({
actionsPosition = 'start',
compact: _compact,
+ maximizable = true,
+ previewDesktopControls = false,
title,
variant = 'titled',
leading,
children,
}: WindowChromeProps) {
const platform = transport.platform
- const height = 40
- const showLinuxControls = platform === 'linux'
+ const showDesktopControls = shouldShowDesktopWindowControls(
+ platform,
+ previewDesktopControls
+ )
const isOverlay = variant === 'overlay'
const isMac = platform === 'darwin'
const showTrafficLight =
- __MOTRIX_TARGET__ === 'electron' && isMac && !__MOTRIX_PREVIEW_MAC_MENU__
+ __MOTRIX_TARGET__ === 'electron' && isMac && !previewDesktopControls
+ const offsetStartActionsForDesktopMenu =
+ showDesktopControls && leading != null && actionsPosition === 'start'
const containerStyle: React.CSSProperties = {
- height,
+ height: DESKTOP_WINDOW_CHROME_HEIGHT,
display: 'flex',
alignItems: 'center',
- paddingLeft: showTrafficLight ? 93 : 12,
- paddingRight:
- platform === 'win32'
- ? WINDOWS_CAPTION_CONTROLS_WIDTH + CAPTION_CONTROLS_EDGE_GAP
- : platform === 'linux'
- ? CAPTION_CONTROLS_EDGE_GAP
- : 20,
+ paddingLeft: showTrafficLight ? 94 : undefined,
+ paddingInlineStart: showTrafficLight ? undefined : 12,
+ paddingInlineEnd: showDesktopControls ? 0 : 20,
flexShrink: 0,
userSelect: 'none',
...(isOverlay && {
@@ -105,30 +137,43 @@ export function WindowChrome({
}),
} as React.CSSProperties
+ const actionSlot = (
+ <div
+ data-slot="window-chrome-actions"
+ className={cn(
+ 'app-no-drag relative z-[60] flex shrink-0 items-center gap-2 pt-3.5 empty:hidden',
+ offsetStartActionsForDesktopMenu && 'ms-1'
+ )}
+ >
+ {children}
+ </div>
+ )
+
return (
<div className="window-chrome app-drag" style={containerStyle}>
{!isOverlay && title && (
- <div className="text-[13px] font-[600] pt-[14px]">{title}</div>
+ <div className="pt-[14px] text-[13px] font-[600]">{title}</div>
)}
{leading && (
<div
data-slot="window-chrome-leading"
- className="app-no-drag relative z-[60] mr-1.5 flex shrink-0 items-center pt-3.5 empty:hidden"
+ className="app-no-drag relative z-[60] me-1.5 flex shrink-0 items-center pt-3.5 empty:hidden"
>
{leading}
</div>
)}
+ {actionsPosition === 'start' && actionSlot}
<div
- data-slot="window-chrome-actions"
- className={cn(
- 'app-no-drag relative z-[60] flex shrink-0 items-center gap-2',
- actionsPosition === 'end' && 'ml-auto'
- )}
- >
- {children}
- </div>
- {showLinuxControls && (
- <LinuxWindowControls pushToEnd={actionsPosition === 'start'} />
+ aria-hidden
+ data-slot="window-chrome-drag-region"
+ className="min-w-16 flex-1"
+ />
+ {actionsPosition === 'end' && actionSlot}
+ {showDesktopControls && (
+ <DesktopWindowControls
+ maximizable={maximizable}
+ separateFromActions={actionsPosition === 'end'}
+ />
)}
</div>
)
diff --git a/src/renderer/hooks/use-engine-restart-required-toast.test.tsx b/src/renderer/hooks/use-engine-restart-required-toast.test.tsx
new file mode 100644
index 00000000..38b4e3bc
--- /dev/null
+++ b/src/renderer/hooks/use-engine-restart-required-toast.test.tsx
@@ -0,0 +1,88 @@
+import '@renderer/lib/i18n'
+import { toast } from '@renderer/components/ui/toast'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { EngineState } from '@shared/types/engine'
+import { act, renderHook } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ ENGINE_RESTART_REQUIRED_TOAST_ID,
+ useEngineRestartRequiredToast,
+} from './use-engine-restart-required-toast'
+
+const listeners = new Map<string, (...args: unknown[]) => void>()
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ platform: 'darwin',
+ invoke: vi.fn().mockResolvedValue({ ok: true }),
+ on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
+ listeners.set(event, listener)
+ }),
+ off: vi.fn((event: string) => {
+ listeners.delete(event)
+ }),
+ },
+}))
+
+vi.mock('@renderer/components/ui/toast', () => ({
+ toast: {
+ add: vi.fn(() => 'engine-restart-required'),
+ close: vi.fn(),
+ },
+}))
+
+describe('useEngineRestartRequiredToast', () => {
+ beforeEach(() => {
+ listeners.clear()
+ vi.mocked(transport.invoke).mockClear()
+ vi.mocked(toast.add).mockClear()
+ vi.mocked(toast.close).mockClear()
+ })
+
+ it('shows one sticky warning whose action restarts the engine', () => {
+ renderHook(() => useEngineRestartRequiredToast())
+
+ act(() => {
+ listeners.get(Events.EngineRestartRequired)?.({
+ changedKeys: ['rpcPort'],
+ })
+ })
+
+ expect(toast.add).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: ENGINE_RESTART_REQUIRED_TOAST_ID,
+ title: 'Restart the download engine to apply settings',
+ description:
+ 'Your settings are saved. Restart the download engine when convenient.',
+ type: 'warning',
+ timeout: 0,
+ })
+ )
+ const options = vi.mocked(toast.add).mock.calls[0]?.[0]
+ act(() => {
+ options?.actionProps?.onClick?.({} as never)
+ })
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RestartEngine)
+ })
+
+ it('closes the reminder when the engine becomes Ready and unsubscribes', () => {
+ const { unmount } = renderHook(() => useEngineRestartRequiredToast())
+
+ act(() => {
+ listeners.get(Events.EngineStateChanged)?.(EngineState.Ready)
+ })
+ expect(toast.close).toHaveBeenCalledWith(ENGINE_RESTART_REQUIRED_TOAST_ID)
+
+ unmount()
+ expect(transport.off).toHaveBeenCalledWith(
+ Events.EngineRestartRequired,
+ expect.any(Function)
+ )
+ expect(transport.off).toHaveBeenCalledWith(
+ Events.EngineStateChanged,
+ expect.any(Function)
+ )
+ })
+})
diff --git a/src/renderer/hooks/use-engine-restart-required-toast.ts b/src/renderer/hooks/use-engine-restart-required-toast.ts
new file mode 100644
index 00000000..86fa99a6
--- /dev/null
+++ b/src/renderer/hooks/use-engine-restart-required-toast.ts
@@ -0,0 +1,46 @@
+import { toast } from '@renderer/components/ui/toast'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { EngineState } from '@shared/types/engine'
+import { useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export const ENGINE_RESTART_REQUIRED_TOAST_ID = 'engine-restart-required'
+
+/** Show one coalesced, action-bearing reminder until the engine is Ready again. */
+export function useEngineRestartRequiredToast(): void {
+ const { t } = useTranslation()
+
+ useEffect(() => {
+ const onRestartRequired = () => {
+ toast.close(ENGINE_RESTART_REQUIRED_TOAST_ID)
+ toast.add({
+ id: ENGINE_RESTART_REQUIRED_TOAST_ID,
+ title: t('notification.engineRestartRequired.title'),
+ description: t('notification.engineRestartRequired.body'),
+ type: 'warning',
+ timeout: 0,
+ actionProps: {
+ children: t('notification.engineRestartRequired.restartNow'),
+ onClick: () => {
+ void transport.invoke(Commands.RestartEngine).catch(() => {})
+ },
+ },
+ })
+ }
+
+ const onEngineStateChanged = (...args: unknown[]) => {
+ if (args[0] === EngineState.Ready) {
+ toast.close(ENGINE_RESTART_REQUIRED_TOAST_ID)
+ }
+ }
+
+ transport.on(Events.EngineRestartRequired, onRestartRequired)
+ transport.on(Events.EngineStateChanged, onEngineStateChanged)
+ return () => {
+ transport.off(Events.EngineRestartRequired, onRestartRequired)
+ transport.off(Events.EngineStateChanged, onEngineStateChanged)
+ }
+ }, [t])
+}
diff --git a/src/renderer/layouts/app-layout.test.tsx b/src/renderer/layouts/app-layout.test.tsx
index 817d4fba..24648109 100644
--- a/src/renderer/layouts/app-layout.test.tsx
+++ b/src/renderer/layouts/app-layout.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
-import { act, render, screen } from '@testing-library/react'
+import { act, fireEvent, render, screen } from '@testing-library/react'
import { createMemoryRouter, RouterProvider } from 'react-router'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { AppLayout } from './app-layout'
@@ -98,6 +98,12 @@ describe('AppLayout', () => {
expect(document.querySelector('[data-slot="sidebar-wrapper"]')).toHaveClass(
'electron-window-chrome'
)
+ expect(
+ document.querySelector('[data-slot="desktop-window-controls"]')
+ ).not.toBeNull()
+ expect(
+ document.querySelector('[data-slot="sidebar-inset"]')
+ ).not.toHaveAttribute('style')
})
it('keeps Electron chrome safe-area overrides out of the web target', () => {
@@ -111,6 +117,36 @@ describe('AppLayout', () => {
vi.stubGlobal('__MOTRIX_TARGET__', 'electron')
})
+ it('keeps chrome actions and the drag region available after collapsing the sidebar', async () => {
+ Object.defineProperty(window.motrix, 'platform', {
+ value: 'win32',
+ configurable: true,
+ })
+ await act(async () => {
+ renderAppLayout()
+ await Promise.resolve()
+ })
+
+ const wrapper = document.querySelector('[data-slot="sidebar-wrapper"]')
+ expect(wrapper).toHaveAttribute('data-state', 'expanded')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Toggle sidebar' }))
+
+ expect(wrapper).toHaveAttribute('data-state', 'collapsed')
+ expect(
+ document.querySelector('[data-slot="window-chrome-leading"]')
+ ).not.toBeNull()
+ expect(
+ document.querySelector('[data-slot="window-chrome-actions"]')
+ ).not.toBeNull()
+ expect(
+ document.querySelector('[data-slot="window-chrome-drag-region"]')
+ ).toHaveClass('min-w-16', 'flex-1')
+ expect(
+ document.querySelector('[data-slot="desktop-window-controls"]')
+ ).not.toBeNull()
+ })
+
it('keeps the sidebar-wrapper background in mobile mode', () => {
// Below the 768px breakpoint the Sidebar renders as a portaled Sheet
// without data-variant="inset", so the wrapper's conditional
diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsx
index 1dee4176..ca358cb7 100644
--- a/src/renderer/layouts/app-layout.tsx
+++ b/src/renderer/layouts/app-layout.tsx
@@ -8,6 +8,7 @@ import { MotrixMenuButton } from '@renderer/components/window-chrome/motrix-menu
import { SidebarTriggerButton } from '@renderer/components/window-chrome/sidebar-trigger-button'
import { WindowChrome } from '@renderer/components/window-chrome/window-chrome'
import { EngineDiagnosticsDialogHost } from '@renderer/features/engine-diagnostics/engine-diagnostics-dialog'
+import { useEngineRestartRequiredToast } from '@renderer/hooks/use-engine-restart-required-toast'
import { useIpcEvent } from '@renderer/hooks/use-ipc-event'
import { useMenuContextSync } from '@renderer/hooks/use-menu-context-sync'
import { useNotificationToasts } from '@renderer/hooks/use-notification-toasts'
@@ -30,6 +31,7 @@ export function AppLayout() {
useShortcuts()
useToastEvents()
usePairRequestPrompts()
+ useEngineRestartRequiredToast()
useNotificationToasts()
const navigate = useNavigate()
@@ -37,7 +39,6 @@ export function AppLayout() {
const transparentInset = matches.some(
(m) => (m.handle as RouteHandle | undefined)?.transparentInset
)
-
useIpcEvent(Events.NavigateTo, (...args) => {
const path = args[0]
if (typeof path === 'string' && path) navigate(path)
@@ -54,11 +55,18 @@ export function AppLayout() {
<SidebarProvider
className={cn(
'h-svh overflow-hidden bg-sidebar',
- __MOTRIX_TARGET__ === 'electron' && 'electron-window-chrome'
+ __MOTRIX_TARGET__ === 'electron' && 'electron-window-chrome',
+ __MOTRIX_TARGET__ === 'electron' &&
+ __MOTRIX_PREVIEW_MAC_MENU__ &&
+ 'preview-desktop-window-controls'
)}
>
- <WindowChrome variant="overlay" leading={<MotrixMenuButton />}>
- <div className="pt-3.5 flex items-center gap-1.5">
+ <WindowChrome
+ variant="overlay"
+ leading={<MotrixMenuButton />}
+ previewDesktopControls={__MOTRIX_PREVIEW_MAC_MENU__}
+ >
+ <div className="flex items-center gap-1.5">
<SidebarTriggerButton />
<AddTaskTriggerButton />
</div>
diff --git a/src/renderer/lib/form-utils.test.ts b/src/renderer/lib/form-utils.test.ts
index 829e3c76..f13a5f85 100644
--- a/src/renderer/lib/form-utils.test.ts
+++ b/src/renderer/lib/form-utils.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { patchHasRestartKeys, pickDirty } from './form-utils'
+import { pickDirty } from './form-utils'
describe('pickDirty', () => {
it('returns undefined for fully clean tree', () => {
@@ -38,46 +38,3 @@ describe('pickDirty', () => {
).toEqual({ proxy: { scopes: { download: true, updateApp: false } } })
})
})
-
-describe('patchHasRestartKeys', () => {
- it('returns false for non-engine patch', () => {
- expect(patchHasRestartKeys({ app: { theme: 'dark' } } as never)).toBe(false)
- })
-
- it('returns true when engine patch contains a RESTART key', () => {
- expect(patchHasRestartKeys({ engine: { rpcPort: 17000 } } as never)).toBe(
- true
- )
- })
-
- it('returns false for non-RESTART engine key', () => {
- expect(patchHasRestartKeys({ engine: { btMaxPeers: 100 } } as never)).toBe(
- false
- )
- })
-
- it('returns false for empty patch', () => {
- expect(patchHasRestartKeys({} as never)).toBe(false)
- })
-
- it('returns false when app patch contains browserBridgeEnabled (hot-applied via BridgeManager)', () => {
- expect(
- patchHasRestartKeys({ app: { browserBridgeEnabled: true } } as never)
- ).toBe(false)
- })
-
- it('returns false when app patch contains launchAtStartup (hot-applied via syncAutoLaunch)', () => {
- expect(
- patchHasRestartKeys({ app: { launchAtStartup: false } } as never)
- ).toBe(false)
- })
-
- it('returns false for mixed patch with non-restart app key and non-restart engine key', () => {
- expect(
- patchHasRestartKeys({
- engine: { btMaxPeers: 100 },
- app: { browserBridgeEnabled: false },
- } as never)
- ).toBe(false)
- })
-})
diff --git a/src/renderer/lib/form-utils.ts b/src/renderer/lib/form-utils.ts
index 019a135c..580c8da3 100644
--- a/src/renderer/lib/form-utils.ts
+++ b/src/renderer/lib/form-utils.ts
@@ -1,13 +1,3 @@
-import {
- APP_RESTART_REQUIRED_KEYS,
- ENGINE_RESTART_REQUIRED_KEYS,
-} from '@shared/constants/restart-keys'
-import type {
- AppSettings,
- EngineSettings,
- MotrixAppSettings,
-} from '@shared/types/settings'
-
type DirtyTree = boolean | { [key: string]: DirtyTree | undefined }
export function pickDirty<T>(
@@ -32,25 +22,3 @@ export function pickDirty<T>(
}
return hasAny ? (out as Partial<T>) : undefined
}
-
-export function patchHasRestartKeys(patch: Partial<AppSettings>): boolean {
- const enginePatch = patch.engine
- if (
- enginePatch &&
- Object.keys(enginePatch).some((k) =>
- ENGINE_RESTART_REQUIRED_KEYS.has(k as keyof EngineSettings)
- )
- ) {
- return true
- }
- const appPatch = patch.app
- if (
- appPatch &&
- Object.keys(appPatch).some((k) =>
- APP_RESTART_REQUIRED_KEYS.has(k as keyof MotrixAppSettings)
- )
- ) {
- return true
- }
- return false
-}
diff --git a/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx b/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx
index 7714e5ec..ce5bf542 100644
--- a/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx
@@ -463,20 +463,44 @@ describe('DashboardGrid', () => {
])
})
- it('renders icon-only h-7 actions when the header is compact', () => {
+ it('renders icon-only 28px actions on the collapsed header centerline', () => {
renderCollapsedGrid()
const configure = screen.getByRole('button', { name: /Configure|配置/i })
- expect(configure).toHaveClass('h-7')
+ expect(configure).toHaveClass(
+ 'size-7',
+ 'p-0',
+ 'hover:bg-transparent',
+ 'dark:hover:bg-transparent',
+ 'panel-action-align-visual-end'
+ )
+ expect(configure.querySelector('svg')).toHaveClass('size-4')
+ expect(configure).not.toHaveClass('[&>svg]:translate-y-0.5')
expect(configure).not.toHaveTextContent(/Configure|配置/i)
fireEvent.click(configure)
const cancel = screen.getByRole('button', { name: /Cancel|取消/i })
- expect(cancel).toHaveClass('h-7')
+ expect(cancel).toHaveClass('size-7', 'p-0', '[&>svg]:size-4')
expect(cancel).not.toHaveTextContent(/Cancel|取消/i)
})
+ it('uses a 28px configure action in the expanded panel header', () => {
+ renderDefaultGrid()
+
+ const configure = screen.getByRole('button', { name: /Configure|配置/i })
+ expect(configure).toHaveClass(
+ 'size-7',
+ 'items-center',
+ 'justify-center',
+ 'panel-action-align-visual-end',
+ 'hover:bg-transparent',
+ 'dark:hover:bg-transparent'
+ )
+ expect(configure.querySelector('svg')).toHaveClass('size-4')
+ expect(configure).not.toHaveClass('size-8')
+ })
+
it('shows all presets only while configuring and labels exact or custom drafts', async () => {
renderDefaultGrid()
diff --git a/src/renderer/routes/dashboard/components/dashboard-grid.tsx b/src/renderer/routes/dashboard/components/dashboard-grid.tsx
index fb70133e..43bd35cc 100644
--- a/src/renderer/routes/dashboard/components/dashboard-grid.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-grid.tsx
@@ -1411,15 +1411,18 @@ export function DashboardGrid({
<Button
type="button"
variant="ghost"
- size={compact ? 'icon-sm' : 'sm'}
+ size="icon-xs"
aria-label={label.action}
- className={compact ? COMPACT_ACTION_CLASS : undefined}
+ className={cn(
+ 'panel-action-align-visual-end relative size-7 bg-transparent hover:bg-transparent dark:hover:bg-transparent',
+ compact && COMPACT_ACTION_CLASS
+ )}
disabled={configurationUnavailable}
onClick={startEditing}
/>
}
>
- <SlidersHorizontal aria-hidden />
+ <SlidersHorizontal aria-hidden className="size-4" />
</TooltipTrigger>
{configurationUnavailable ? (
<TooltipContent>{label.expandHint}</TooltipContent>
diff --git a/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx b/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx
index a400051e..7c3e1588 100644
--- a/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx
+++ b/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom/vitest'
import { i18n } from '@renderer/lib/i18n'
import { ErrorCode } from '@shared/errors'
+import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import {
NatPortReachability,
@@ -18,8 +19,9 @@ import {
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { DashboardTileViewport } from '../layout/dashboard-registry'
-const { mockInvoke, toastAddMock } = vi.hoisted(() => ({
+const { mockInvoke, openExternalMock, toastAddMock } = vi.hoisted(() => ({
mockInvoke: vi.fn(),
+ openExternalMock: vi.fn(),
toastAddMock: vi.fn(),
}))
const natState = vi.hoisted(() => ({ status: null as NatStatus | null }))
@@ -57,6 +59,10 @@ vi.mock('@renderer/components/ui/toast', () => ({
toast: { add: toastAddMock, close: vi.fn() },
}))
+vi.mock('@renderer/platform/services', () => ({
+ usePlatformServices: () => ({ openExternal: openExternalMock }),
+}))
+
const { NatTile } = await import('./nat-tile')
const COMPACT = {
@@ -106,6 +112,7 @@ function makeStatus(overrides: Partial<NatStatus> = {}): NatStatus {
describe('NatTile', () => {
beforeEach(() => {
mockInvoke.mockReset().mockResolvedValue({ ok: true })
+ openExternalMock.mockReset()
toastAddMock.mockReset()
natState.status = makeStatus()
})
@@ -380,6 +387,22 @@ describe('NatTile', () => {
expect(mockInvoke).toHaveBeenCalledWith(Commands.EnableNat)
})
+ it('offers the official troubleshooting guide in the terminal failed state', () => {
+ natState.status = makeStatus({
+ state: NatState.Failed,
+ retryAttempt: 3,
+ maxRetries: 3,
+ })
+ render(<NatTile viewport={SQUARE_DETAILED} />)
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'NAT troubleshooting guide' })
+ )
+ expect(openExternalMock).toHaveBeenCalledWith(
+ EXTERNAL_URLS.motrix.manual.natTroubleshooting.en
+ )
+ })
+
it('toasts when a command is rate limited', async () => {
mockInvoke.mockResolvedValue({ ok: false, error: ErrorCode.IpcRateLimited })
render(<NatTile viewport={SQUARE_DETAILED} />)
diff --git a/src/renderer/routes/dashboard/tiles/nat-tile.tsx b/src/renderer/routes/dashboard/tiles/nat-tile.tsx
index ea1e64c8..62c617bb 100644
--- a/src/renderer/routes/dashboard/tiles/nat-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/nat-tile.tsx
@@ -17,9 +17,11 @@ import {
} from '@renderer/lib/nat-status'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
+import { usePlatformServices } from '@renderer/platform/services'
import { ErrorCode } from '@shared/errors'
+import { getNatTroubleshootingUrl } from '@shared/external-urls'
import { type CommandChannel, Commands } from '@shared/protocol/commands'
-import { Activity, Power, RefreshCw, Settings2 } from 'lucide-react'
+import { Activity, BookOpen, Power, RefreshCw, Settings2 } from 'lucide-react'
import type { ComponentType } from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
@@ -62,6 +64,7 @@ interface NatAction {
export function NatTile({ viewport, className }: NatTileProps) {
const { t, i18n } = useTranslation()
+ const services = usePlatformServices()
const status = useNatStatus()
const compact = viewport.contentLevel === 'compact'
const summary = viewport.contentLevel === 'summary'
@@ -70,6 +73,7 @@ export function NatTile({ viewport, className }: NatTileProps) {
const focus = viewport.contentLevel === 'focus'
const { bucket, color } = natBucket(status)
+ const failed = bucket === 'failed'
const stateLabel =
status && isNatRetrying(status)
? t('panel.dashboard.nat.retrying', {
@@ -137,6 +141,18 @@ export function NatTile({ viewport, className }: NatTileProps) {
run: () => void runCommand(Commands.RunNatDiagnostic),
},
]
+ if (failed) {
+ actions.push({
+ key: 'help',
+ Icon: BookOpen,
+ label: t('panel.dashboard.nat.actions.troubleshoot'),
+ shortLabel: t('panel.dashboard.nat.actions.short.help'),
+ run: () =>
+ services.openExternal(
+ getNatTroubleshootingUrl(i18n.resolvedLanguage ?? i18n.language)
+ ),
+ })
+ }
return (
<TileShell
@@ -353,7 +369,8 @@ function NatActions({
data-testid="nat-actions"
aria-label={label}
className={cn(
- 'grid min-w-0 shrink-0 grid-cols-3 gap-0.5 rounded-lg border-0 bg-muted/45 p-1 ring-1 ring-inset ring-foreground/5',
+ 'grid min-w-0 shrink-0 gap-0.5 rounded-lg border-0 bg-muted/45 p-1 ring-1 ring-inset ring-foreground/5',
+ actions.length === 4 ? 'grid-cols-4' : 'grid-cols-3',
summary ? 'w-fit' : 'mt-3 w-full'
)}
>
diff --git a/src/renderer/routes/downloads/downloads-page.test.tsx b/src/renderer/routes/downloads/downloads-page.test.tsx
index 2ad321f0..609de5a4 100644
--- a/src/renderer/routes/downloads/downloads-page.test.tsx
+++ b/src/renderer/routes/downloads/downloads-page.test.tsx
@@ -1,5 +1,9 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
+import {
+ type PlatformServices,
+ PlatformServicesProvider,
+} from '@renderer/platform/services'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
@@ -60,6 +64,15 @@ vi.mock('@renderer/lib/transport', () => ({
},
}))
+const testPlatformServices: PlatformServices = {
+ kind: 'electron',
+ pickSaveDir: vi.fn(async () => null),
+ closeHost: vi.fn(),
+ readClipboard: vi.fn(async () => ''),
+ openExternal: vi.fn(),
+ notify: vi.fn(),
+}
+
function task(
id: string,
status: TaskStatus,
@@ -131,10 +144,15 @@ function TestRouter({ initialPath }: { initialPath: string }) {
}
function renderAt(path: string) {
- const view = render(<TestRouter initialPath={path} />)
+ const renderTree = () => (
+ <PlatformServicesProvider services={testPlatformServices}>
+ <TestRouter initialPath={path} />
+ </PlatformServicesProvider>
+ )
+ const view = render(renderTree())
return {
...view,
- refresh: () => view.rerender(<TestRouter initialPath={path} />),
+ refresh: () => view.rerender(renderTree()),
}
}
@@ -155,9 +173,17 @@ describe('DownloadsPage', () => {
expect(
screen.getByRole('heading', { name: /downloads/i })
).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: /search downloads/i })
- ).toBeInTheDocument()
+ const search = screen.getByRole('button', { name: /search downloads/i })
+ expect(search).toHaveClass(
+ 'size-7',
+ 'items-center',
+ 'justify-center',
+ 'hover:bg-transparent',
+ 'dark:hover:bg-transparent',
+ 'panel-action-align-visual-end'
+ )
+ expect(search.querySelector('svg')).toHaveClass('size-4')
+ expect(search).not.toHaveClass('size-8')
})
it.each([
diff --git a/src/renderer/routes/downloads/downloads-page.tsx b/src/renderer/routes/downloads/downloads-page.tsx
index eaa25e8f..1dc6a52b 100644
--- a/src/renderer/routes/downloads/downloads-page.tsx
+++ b/src/renderer/routes/downloads/downloads-page.tsx
@@ -303,7 +303,7 @@ export function DownloadsPage() {
/>
}
actionsPosition="end"
- footer={<GlobalStatsBar />}
+ footer={<GlobalStatsBar counts={counts} />}
contentClassName="px-6"
>
{status === 'error' && hasReadySnapshot ? (
diff --git a/src/renderer/routes/downloads/filter-search-command.tsx b/src/renderer/routes/downloads/filter-search-command.tsx
index 1c876190..76d78055 100644
--- a/src/renderer/routes/downloads/filter-search-command.tsx
+++ b/src/renderer/routes/downloads/filter-search-command.tsx
@@ -33,15 +33,13 @@ export function FilterSearchCommand({
variant="ghost"
size="icon"
aria-label={t('panel.downloads.search.placeholder')}
- // In the collapsed (40px) header the button keeps its 32px visual
- // size — icon position and hover circle stay identical to the
- // expanded state — but -my-2 cancels the extra layout height so
- // the row stays 16px tall like the title trigger.
- className="app-no-drag relative size-8 rounded-full compact-header:-my-0.5"
+ // Match the 28px window-chrome targets so compact panel actions
+ // stay on the Toggle Sidebar and Add Task centerline.
+ className="panel-action-align-visual-end app-no-drag relative size-7 rounded-full bg-transparent hover:bg-transparent dark:hover:bg-transparent [&>svg]:opacity-50 hover:[&>svg]:opacity-75 focus-visible:[&>svg]:opacity-75"
/>
}
>
- <Search className="size-4 text-muted-foreground" />
+ <Search className="size-4" />
{active && (
<span className="absolute -right-0.5 -top-0.5 size-2 rounded-full bg-primary ring-2 ring-background" />
)}
diff --git a/src/renderer/routes/downloads/filter.test.ts b/src/renderer/routes/downloads/filter.test.ts
index c1c3c75e..e95b70e0 100644
--- a/src/renderer/routes/downloads/filter.test.ts
+++ b/src/renderer/routes/downloads/filter.test.ts
@@ -4,6 +4,7 @@ import { makeDownloadTask } from '@test-utils/task'
import { describe, expect, it } from 'vitest'
import {
applyFilter,
+ countTasksByTab,
countTasksByType,
DOWNLOADS_TABS,
isValidTab,
@@ -99,6 +100,19 @@ describe('applyFilter (tab + types)', () => {
})
})
+describe('countTasksByTab', () => {
+ it('uses Motrix task statuses for all footer and title counts', () => {
+ expect(
+ countTasksByTab([
+ fake({ id: 'paused', status: TaskStatus.Paused }),
+ fake({ id: 'completed', status: TaskStatus.Completed }),
+ fake({ id: 'error', status: TaskStatus.Error }),
+ fake({ id: 'removed', status: TaskStatus.Removed }),
+ ])
+ ).toEqual({ all: 3, active: 1, completed: 1, error: 1 })
+ })
+})
+
describe('countTasksByType', () => {
it('counts per type ignoring Removed', () => {
const counts = countTasksByType([
diff --git a/src/renderer/routes/downloads/global-stats-bar.test.tsx b/src/renderer/routes/downloads/global-stats-bar.test.tsx
index 61f98521..b48fbb48 100644
--- a/src/renderer/routes/downloads/global-stats-bar.test.tsx
+++ b/src/renderer/routes/downloads/global-stats-bar.test.tsx
@@ -1,5 +1,9 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
+import {
+ type PlatformServices,
+ PlatformServicesProvider,
+} from '@renderer/platform/services'
import { Queries } from '@shared/protocol/queries'
import { NatState } from '@shared/types/nat'
import { render, screen } from '@testing-library/react'
@@ -45,12 +49,40 @@ vi.mock('@renderer/lib/transport', () => ({
import { GlobalStatsBar } from './global-stats-bar'
+const motrixCounts = { all: 7, active: 2, completed: 3, error: 2 }
+
+const testPlatformServices: PlatformServices = {
+ kind: 'electron',
+ pickSaveDir: vi.fn(async () => null),
+ closeHost: vi.fn(),
+ readClipboard: vi.fn(async () => ''),
+ openExternal: vi.fn(),
+ notify: vi.fn(),
+}
+
describe('GlobalStatsBar', () => {
it('renders formatted speeds with engine and nat badges', async () => {
- render(<GlobalStatsBar />)
+ render(
+ <PlatformServicesProvider services={testPlatformServices}>
+ <GlobalStatsBar counts={motrixCounts} />
+ </PlatformServicesProvider>
+ )
// formatBytes(16_500_000) = "15.7 MB" (1024-base, value.toFixed(1))
expect(screen.getByText(/15\.7 MB\/s/)).toBeInTheDocument()
expect(await screen.findByText(/Engine ready/)).toBeInTheDocument()
expect(await screen.findByText(/NAT active/)).toBeInTheDocument()
})
+
+ it('uses Motrix task counts instead of aria2 runtime counts', () => {
+ render(
+ <PlatformServicesProvider services={testPlatformServices}>
+ <GlobalStatsBar counts={motrixCounts} />
+ </PlatformServicesProvider>
+ )
+
+ expect(
+ screen.getByText('Active 2 · Completed 3 · Error 2')
+ ).toBeInTheDocument()
+ expect(screen.queryByText(/Completed 42/)).not.toBeInTheDocument()
+ })
})
diff --git a/src/renderer/routes/downloads/global-stats-bar.tsx b/src/renderer/routes/downloads/global-stats-bar.tsx
index 4c2b06bc..464ac9cb 100644
--- a/src/renderer/routes/downloads/global-stats-bar.tsx
+++ b/src/renderer/routes/downloads/global-stats-bar.tsx
@@ -2,9 +2,14 @@ import { useGlobalStats } from '@renderer/hooks/use-global-stats'
import { formatBytes } from '@renderer/lib/format'
import { useTranslation } from 'react-i18next'
import { EngineBadge } from './engine-badge'
+import type { DownloadsTab } from './filter'
import { NatBadge } from './nat-badge'
-export function GlobalStatsBar() {
+interface GlobalStatsBarProps {
+ counts: Record<DownloadsTab, number>
+}
+
+export function GlobalStatsBar({ counts }: GlobalStatsBarProps) {
const { t } = useTranslation()
const { stats } = useGlobalStats()
@@ -25,9 +30,9 @@ export function GlobalStatsBar() {
</span>
<span className="tabular-nums">
{t('panel.downloads.stats.counts', {
- active: stats?.activeTasks ?? 0,
- completed: stats?.stoppedTasks ?? 0,
- error: 0,
+ active: counts.active,
+ completed: counts.completed,
+ error: counts.error,
})}
</span>
</div>
diff --git a/src/renderer/routes/downloads/nat-badge.test.tsx b/src/renderer/routes/downloads/nat-badge.test.tsx
new file mode 100644
index 00000000..891c8694
--- /dev/null
+++ b/src/renderer/routes/downloads/nat-badge.test.tsx
@@ -0,0 +1,61 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { EXTERNAL_URLS } from '@shared/external-urls'
+import { NatState, type NatStatus } from '@shared/types/nat'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { invoke, openExternal } = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ openExternal: vi.fn(),
+}))
+const natState = vi.hoisted(() => ({ status: null as NatStatus | null }))
+
+vi.mock('@renderer/hooks/use-nat-status', () => ({
+ useNatStatus: () => natState.status,
+}))
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ invoke,
+ on: vi.fn(),
+ off: vi.fn(),
+ platform: 'darwin',
+ },
+}))
+
+vi.mock('@renderer/platform/services', () => ({
+ usePlatformServices: () => ({ openExternal }),
+}))
+
+const { NatBadge } = await import('./nat-badge')
+
+describe('NatBadge', () => {
+ beforeEach(() => {
+ invoke.mockReset().mockResolvedValue({ ok: true })
+ openExternal.mockReset()
+ natState.status = {
+ state: NatState.Failed,
+ enabled: true,
+ activeMappings: [],
+ gatewayInfo: null,
+ lastError: null,
+ lastDiagnostic: null,
+ retryAttempt: 3,
+ maxRetries: 3,
+ }
+ })
+
+ it('offers the official troubleshooting guide in the failed menu', async () => {
+ render(<NatBadge />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'NAT failed' }))
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'Troubleshoot NAT' })
+ )
+
+ expect(openExternal).toHaveBeenCalledWith(
+ EXTERNAL_URLS.motrix.manual.natTroubleshooting.en
+ )
+ })
+})
diff --git a/src/renderer/routes/downloads/nat-badge.tsx b/src/renderer/routes/downloads/nat-badge.tsx
index c5811ed7..f3d23e04 100644
--- a/src/renderer/routes/downloads/nat-badge.tsx
+++ b/src/renderer/routes/downloads/nat-badge.tsx
@@ -17,6 +17,8 @@ import {
} from '@renderer/lib/nat-status'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
+import { usePlatformServices } from '@renderer/platform/services'
+import { getNatTroubleshootingUrl } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
@@ -29,7 +31,8 @@ const TEXT_KEY: Record<NatBucket, string> = {
}
export function NatBadge() {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
+ const services = usePlatformServices()
const status = useNatStatus()
const { bucket, color } = natBucket(status)
const badgeText = t(TEXT_KEY[bucket])
@@ -48,6 +51,12 @@ export function NatBadge() {
const handleDisable = useCallback(() => {
void transport.invoke(Commands.DisableNat)
}, [])
+ const troubleshootingUrl = getNatTroubleshootingUrl(
+ i18n.resolvedLanguage ?? i18n.language
+ )
+ const handleHelp = useCallback(() => {
+ void services.openExternal(troubleshootingUrl)
+ }, [services, troubleshootingUrl])
return (
<DropdownMenu>
@@ -80,6 +89,11 @@ export function NatBadge() {
{t('panel.downloads.stats.natEnable')}
</DropdownMenuItem>
)}
+ {bucket === 'failed' ? (
+ <DropdownMenuItem onClick={handleHelp}>
+ {t('panel.downloads.stats.natHelp')}
+ </DropdownMenuItem>
+ ) : null}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/src/renderer/routes/notifications/notifications-page.test.tsx b/src/renderer/routes/notifications/notifications-page.test.tsx
index 81b65389..7090abc5 100644
--- a/src/renderer/routes/notifications/notifications-page.test.tsx
+++ b/src/renderer/routes/notifications/notifications-page.test.tsx
@@ -78,7 +78,9 @@ describe('<NotificationsPage>', () => {
renderPage()
expect(await screen.findByText('No notifications')).toBeInTheDocument()
expect(
- screen.getByText('Download failures and completions will show up here')
+ screen.getByText(
+ 'Download activity and important app notices will show up here'
+ )
).toBeInTheDocument()
// The Empty state isn't a list — the row container must not claim
// role="list" over zero list items.
diff --git a/src/renderer/routes/settings/cards/about-dialog.test.tsx b/src/renderer/routes/settings/cards/about-dialog.test.tsx
index 0276e516..f67556ce 100644
--- a/src/renderer/routes/settings/cards/about-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.test.tsx
@@ -371,9 +371,13 @@ describe('<AboutDialog>', () => {
'This build of Motrix doesn’t support automatic updates. Download the latest release from the official website.'
)
).toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'Check for updates' })
- ).not.toBeInTheDocument()
+ const checkButton = screen.getByRole('button', {
+ name: 'Check for updates',
+ })
+ expect(checkButton).toBeDisabled()
+ expect(checkButton).toHaveTextContent('Check')
+ expect(checkButton).toHaveClass('disabled:opacity-50')
+ expect(checkButton).not.toHaveClass('disabled:opacity-100')
})
it('persists the automatic launch check setting from the footer', async () => {
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
index 21e29e50..fe0d24bb 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
@@ -71,7 +71,7 @@ describe('<AdvancedDialog>', () => {
)
await waitFor(() => screen.getByDisplayValue('16800'))
const user = userEvent.setup()
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).not.toHaveBeenCalledWith(
Commands.UpdateSettings,
expect.anything()
@@ -79,11 +79,12 @@ describe('<AdvancedDialog>', () => {
expect(onClose).toHaveBeenCalled()
})
- it('shows restart confirm when RESTART field is dirty', async () => {
+ it('saves a restart-required field without a pre-save confirmation', async () => {
+ const onClose = vi.fn()
render(
<AdvancedDialog
open
- onClose={vi.fn()}
+ onClose={onClose}
labelKey="settings.cards.advanced.title"
descKey="settings.cards.advanced.desc"
/>
@@ -97,60 +98,12 @@ describe('<AdvancedDialog>', () => {
// rather than the intended final number. fireEvent fires one change event
// with the full target value, matching real-user paste/blur semantics.
fireEvent.change(portInput, { target: { value: '17000' } })
- await user.click(screen.getByRole('button', { name: /apply/i }))
- expect(
- await screen.findByText(/restart to apply changes/i)
- ).toBeInTheDocument()
- })
-
- it('cancel restart keeps form dirty and does not call UpdateSettings', async () => {
- const onClose = vi.fn()
- render(
- <AdvancedDialog
- open
- onClose={onClose}
- labelKey="settings.cards.advanced.title"
- descKey="settings.cards.advanced.desc"
- />
- )
- await waitFor(() => screen.getByDisplayValue('16800'))
- const user = userEvent.setup()
- const portInput = screen.getByDisplayValue('16800')
- fireEvent.change(portInput, { target: { value: '17000' } })
- await user.click(screen.getByRole('button', { name: /apply/i }))
- await screen.findByText(/restart to apply changes/i)
-
- // The first Cancel button is the dialog cancel; restart confirm has its own.
- // Find the confirm dialog scope
- const cancelButtons = screen.getAllByRole('button', { name: /cancel/i })
- await user.click(cancelButtons[cancelButtons.length - 1])
-
- expect(transport.invoke).not.toHaveBeenCalledWith(
- Commands.UpdateSettings,
- expect.anything()
- )
- expect(onClose).not.toHaveBeenCalled()
- })
-
- it('confirm restart sends UpdateSettings with engine patch', async () => {
- render(
- <AdvancedDialog
- open
- onClose={vi.fn()}
- labelKey="settings.cards.advanced.title"
- descKey="settings.cards.advanced.desc"
- />
- )
- await waitFor(() => screen.getByDisplayValue('16800'))
- const user = userEvent.setup()
- const portInput = screen.getByDisplayValue('16800')
- fireEvent.change(portInput, { target: { value: '17000' } })
- await user.click(screen.getByRole('button', { name: /apply/i }))
- await screen.findByText(/restart to apply changes/i)
- await user.click(screen.getByRole('button', { name: /save and restart/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
engine: { rpcPort: 17000 },
})
+ expect(onClose).toHaveBeenCalled()
+ expect(screen.queryByText(/restart to apply changes/i)).toBeNull()
})
it('Generate button populates rpcSecret', async () => {
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.tsx b/src/renderer/routes/settings/cards/advanced-dialog.tsx
index 606a216d..61c3e44f 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.tsx
@@ -1,5 +1,3 @@
-import { RestartConfirmDialog } from '@renderer/components/settings-kit/restart-confirm-dialog'
-import { useRestartConfirmDialog } from '@renderer/components/settings-kit/use-restart-confirm-dialog'
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
@@ -21,7 +19,7 @@ import { Input } from '@renderer/components/ui/input'
import { PasswordInput } from '@renderer/components/ui/password-input'
import { Separator } from '@renderer/components/ui/separator'
import { Switch } from '@renderer/components/ui/switch'
-import { patchHasRestartKeys, pickDirty } from '@renderer/lib/form-utils'
+import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
@@ -58,7 +56,6 @@ export function AdvancedDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
- const restartDialog = useRestartConfirmDialog()
const form = useForm<AdvancedFields>({ defaultValues: DEFAULTS })
// biome-ignore lint/correctness/useExhaustiveDependencies: form is stable
@@ -94,10 +91,6 @@ export function AdvancedDialog({
return
}
const patch = { engine: dirty }
- if (patchHasRestartKeys(patch as Partial<AppSettings>)) {
- const ok = await restartDialog.confirm()
- if (!ok) return
- }
await transport.invoke(Commands.UpdateSettings, patch)
onClose()
})
@@ -105,208 +98,197 @@ export function AdvancedDialog({
const persistenceOn = form.watch('sqlite3Persistence')
return (
- <>
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogContent
- className="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>
- </DialogHeader>
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent
+ className="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>
+ </DialogHeader>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
+ <Form {...form}>
+ <form className="space-y-4">
+ <h3 className="text-sm font-semibold text-foreground">
+ {t('settings.advanced.rpc.title')}
+ </h3>
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
- <Form {...form}>
- <form className="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 }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={1024}
+ max={65535}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) => {
+ const n = Number.parseInt(e.target.value, 10)
+ field.onChange(
+ Number.isFinite(n)
+ ? Math.min(65535, Math.max(1024, n))
+ : DEFAULT_ENGINE_SETTINGS.rpcPort
+ )
+ }}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="rpcPort"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>{t('settings.advanced.rpc.port')}</FormLabel>
- <FormDescription className="text-xs">
- {t('settings.advanced.rpc.portDesc')}
- </FormDescription>
- </div>
+ <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>
- <Input
- type="number"
- min={1024}
- max={65535}
- className="w-24 h-8"
+ <PasswordInput
value={field.value}
- onChange={(e) => {
- const n = Number.parseInt(e.target.value, 10)
- field.onChange(
- Number.isFinite(n)
- ? Math.min(65535, Math.max(1024, n))
- : DEFAULT_ENGINE_SETTINGS.rpcPort
- )
- }}
+ onChange={field.onChange}
+ onBlur={field.onBlur}
+ showPasswordLabel={t('settings.common.showSecret')}
+ hidePasswordLabel={t('settings.common.hideSecret')}
+ className="flex-1"
/>
</FormControl>
- </FormItem>
- )}
- />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label={t('settings.common.generate')}
+ onClick={() => field.onChange(generateRpcSecret())}
+ >
+ <Dices className="h-3 w-3" />
+ </Button>
+ </div>
+ </FormItem>
+ )}
+ />
- <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
- 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())}
- >
- <Dices className="h-3 w-3" />
- </Button>
- </div>
- </FormItem>
- )}
- />
+ <Separator className="my-4" />
- <Separator className="my-4" />
+ <h3 className="text-sm font-semibold text-foreground">
+ {t('settings.advanced.persistence.title')}
+ </h3>
- <h3 className="text-sm font-semibold text-foreground">
- {t('settings.advanced.persistence.title')}
- </h3>
+ <FormField
+ control={form.control}
+ name="sqlite3Persistence"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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>
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="sqlite3Persistence"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="sqlite3DbPath"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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
- className="w-56 h-8"
- placeholder={t(
- 'settings.advanced.persistence.dbPathPlaceholder'
- )}
- disabled={!persistenceOn}
- value={field.value}
- onChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="sqlite3HistoryLimit"
- render={({ field }) => (
- <FormItem 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>
- <FormControl>
- <Input
- type="number"
- min={-1}
- className="w-24 h-8"
- disabled={!persistenceOn}
- value={field.value}
- onChange={(e) => {
- const parsed = Number.parseInt(e.target.value, 10)
- field.onChange(
- Number.isFinite(parsed)
- ? Math.max(-1, parsed)
- : -1
- )
- }}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </form>
- </Form>
- </div>
+ <FormField
+ control={form.control}
+ name="sqlite3DbPath"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ className="w-56 h-8"
+ placeholder={t(
+ 'settings.advanced.persistence.dbPathPlaceholder'
+ )}
+ disabled={!persistenceOn}
+ value={field.value}
+ onChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- size="sm"
- onClick={onSubmit}
- disabled={form.formState.isSubmitting}
- >
- {t('common.apply')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <FormField
+ control={form.control}
+ name="sqlite3HistoryLimit"
+ render={({ field }) => (
+ <FormItem 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>
+ <FormControl>
+ <Input
+ type="number"
+ min={-1}
+ className="w-24 h-8"
+ disabled={!persistenceOn}
+ value={field.value}
+ onChange={(e) => {
+ const parsed = Number.parseInt(e.target.value, 10)
+ field.onChange(
+ Number.isFinite(parsed) ? Math.max(-1, parsed) : -1
+ )
+ }}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </form>
+ </Form>
+ </div>
- <RestartConfirmDialog
- open={restartDialog.open}
- onResolve={restartDialog.handleResolve}
- />
- </>
+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={onSubmit}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/src/renderer/routes/settings/cards/app-update-section.tsx b/src/renderer/routes/settings/cards/app-update-section.tsx
index 7251ff2d..e2b3c1a4 100644
--- a/src/renderer/routes/settings/cards/app-update-section.tsx
+++ b/src/renderer/routes/settings/cards/app-update-section.tsx
@@ -1,6 +1,7 @@
import { Alert } from '@renderer/components/ui/alert'
import { Button } from '@renderer/components/ui/button'
import { Spinner } from '@renderer/components/ui/spinner'
+import { cn } from '@renderer/lib/utils'
import type { AppUpdateState } from '@shared/types/app-update'
import type { AppUpdateChannel } from '@shared/types/settings'
import { DownloadIcon, RefreshCwIcon, RotateCwIcon } from 'lucide-react'
@@ -118,7 +119,10 @@ function UpdateActionButton({
type="button"
size="sm"
variant={action.variant}
- className="h-7! gap-1.5 rounded-md! px-2 text-xs shadow-none disabled:opacity-100 [&_svg]:size-3.5!"
+ className={cn(
+ 'h-7! gap-1.5 rounded-md! px-2 text-xs shadow-none [&_svg]:size-3.5!',
+ state.phase !== 'unsupported' && 'disabled:opacity-100'
+ )}
aria-label={action.accessibleLabel}
aria-busy={
state.phase === 'checking' || state.phase === 'downloading'
@@ -146,7 +150,13 @@ function updateAction(
): UpdateAction | null {
switch (state.phase) {
case 'unsupported':
- return null
+ return {
+ label: t('settings.about.update.checkAction'),
+ accessibleLabel: t('settings.about.update.check'),
+ icon: <RefreshCwIcon data-icon="inline-start" aria-hidden="true" />,
+ disabled: true,
+ variant: 'default',
+ }
case 'checking':
return {
label: t('settings.about.update.checking'),
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
index e70d89ad..06e7058a 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
@@ -107,7 +107,7 @@ describe('<AppearanceDialog>', () => {
await user.click(themeTrigger)
const darkOption = await screen.findByRole('option', { name: /dark/i })
await user.click(darkOption)
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
app: { theme: 'dark' },
})
@@ -129,7 +129,7 @@ describe('<AppearanceDialog>', () => {
await user.click(languageTrigger)
await user.click(await screen.findByRole('option', { name: '简体中文' }))
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
app: { language: 'zh-CN' },
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.tsx b/src/renderer/routes/settings/cards/appearance-dialog.tsx
index cda449bf..c1e39d61 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.tsx
@@ -328,7 +328,7 @@ export function AppearanceDialog({
onClick={onSubmit}
disabled={form.formState.isSubmitting}
>
- {t('common.apply')}
+ {t('common.save')}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx b/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
index 0c65bcbf..3fd0959b 100644
--- a/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
@@ -1,11 +1,12 @@
// src/renderer/routes/settings/cards/bit-torrent-dialog.test.tsx
import '@testing-library/jest-dom/vitest'
-import { 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'
import '@renderer/lib/i18n'
import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
import { BitTorrentDialog } from './bit-torrent-dialog'
@@ -80,7 +81,7 @@ describe('<BitTorrentDialog>', () => {
})
})
- it('shows restart confirm when listen port changes', async () => {
+ it('saves a listen-port change without a pre-save confirmation', async () => {
render(
<BitTorrentDialog
open
@@ -92,12 +93,12 @@ describe('<BitTorrentDialog>', () => {
await waitFor(() => screen.getAllByDisplayValue('6881'))
const user = userEvent.setup()
const listenInput = screen.getAllByDisplayValue('6881')[0]
- await user.clear(listenInput)
- await user.type(listenInput, '6882')
- await user.click(screen.getByRole('button', { name: /apply/i }))
- expect(
- await screen.findByText(/restart to apply changes/i)
- ).toBeInTheDocument()
+ fireEvent.change(listenInput, { target: { value: '6882' } })
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ engine: { listenPort: 6882 },
+ })
+ expect(screen.queryByText(/restart to apply changes/i)).toBeNull()
})
it('shows hint paragraph pointing users to the Trackers page Blacklist tab', async () => {
diff --git a/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx b/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
index 4d885f70..e2b45ab0 100644
--- a/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
+++ b/src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
@@ -1,8 +1,6 @@
// src/renderer/routes/settings/cards/bit-torrent-dialog.tsx
import { PresetChips } from '@renderer/components/settings-kit/preset-chips'
-import { RestartConfirmDialog } from '@renderer/components/settings-kit/restart-confirm-dialog'
-import { useRestartConfirmDialog } from '@renderer/components/settings-kit/use-restart-confirm-dialog'
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
@@ -23,7 +21,7 @@ import {
import { Input } from '@renderer/components/ui/input'
import { Separator } from '@renderer/components/ui/separator'
import { Switch } from '@renderer/components/ui/switch'
-import { patchHasRestartKeys, pickDirty } from '@renderer/lib/form-utils'
+import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
@@ -90,7 +88,6 @@ export function BitTorrentDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
- const restartDialog = useRestartConfirmDialog()
const form = useForm<BtFields>({ defaultValues: DEFAULTS })
// biome-ignore lint/correctness/useExhaustiveDependencies: form is stable
@@ -138,549 +135,532 @@ export function BitTorrentDialog({
onClose()
return
}
- if (patchHasRestartKeys(dirty as Partial<AppSettings>)) {
- const ok = await restartDialog.confirm()
- if (!ok) return
- }
await transport.invoke(Commands.UpdateSettings, dirty)
onClose()
})
return (
- <>
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogContent
- className="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>
- </DialogHeader>
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent
+ className="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>
+ </DialogHeader>
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
- <Form {...form}>
- <form className="space-y-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 }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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
- type="number"
- min={1024}
- max={65535}
- className="w-24 h-8"
- value={field.value}
- onChange={(e) => {
- const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 6881)
- }}
- />
- </FormControl>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="engine.dhtListenPort"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
+ <Form {...form}>
+ <form className="space-y-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 }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={1024}
+ max={65535}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) => {
+ const n = Number.parseInt(e.target.value, 10)
+ field.onChange(Number.isFinite(n) ? n : 6881)
+ }}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="engine.dhtListenPort"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={1024}
+ max={65535}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) => {
+ const n = Number.parseInt(e.target.value, 10)
+ field.onChange(Number.isFinite(n) ? n : 6881)
+ }}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="engine.dhtEnabled"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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>
+ </FormItem>
+ )}
+ />
+
+ <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 }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={1}
+ max={1000}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) => {
+ const n = Number.parseInt(e.target.value, 10)
+ field.onChange(Number.isFinite(n) ? n : 128)
+ }}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="engine.btEnableLpd"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="app.magnetFileSelection"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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>
+ </FormItem>
+ )}
+ />
+
+ <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 }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={0}
+ max={100}
+ step={0.1}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) =>
+ field.onChange(Number.parseFloat(e.target.value) || 0)
+ }
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="engine.seedTime"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={0}
+ max={525600}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) => {
+ const n = Number.parseInt(e.target.value, 10)
+ field.onChange(Number.isFinite(n) ? n : 0)
+ }}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <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 }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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>
+ </FormItem>
+ )}
+ />
+
+ <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.listen.dhtListenPort')}
+ {t('settings.bittorrent.trackers.syncInterval')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.bittorrent.listen.dhtListenPortDesc')}
+ {t('settings.bittorrent.trackers.syncIntervalDesc')}
</FormDescription>
</div>
<FormControl>
<Input
type="number"
- min={1024}
- max={65535}
+ min={1}
+ max={168}
className="w-24 h-8"
value={field.value}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 6881)
+ field.onChange(Number.isFinite(n) ? n : 24)
}}
/>
</FormControl>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="engine.dhtEnabled"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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>
- </FormItem>
- )}
- />
+ </div>
+ <PresetChips
+ name="tracker.syncIntervalHours"
+ options={[
+ { label: '6h', value: 6 },
+ { label: '12h', value: 12 },
+ { label: '24h', value: 24 },
+ ]}
+ />
+ </FormItem>
+ )}
+ />
- <Separator className="my-4" />
+ <FormField
+ control={form.control}
+ name="tracker.probeEnabled"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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>
+ </FormItem>
+ )}
+ />
- {/* Peers */}
- <h3 className="text-sm font-semibold text-foreground">
- {t('settings.bittorrent.peers.title')}
- </h3>
- <FormField
- control={form.control}
- name="engine.btMaxPeers"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
+ <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.peers.btMaxPeers')}
+ {t('settings.bittorrent.trackers.probeTimeout')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.bittorrent.peers.btMaxPeersDesc')}
+ {t('settings.bittorrent.trackers.probeTimeoutDesc')}
</FormDescription>
</div>
<FormControl>
<Input
type="number"
- min={1}
- max={1000}
- className="w-24 h-8"
+ min={1000}
+ max={30000}
+ step={500}
+ className="w-28 h-8"
value={field.value}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 128)
+ field.onChange(Number.isFinite(n) ? n : 5000)
}}
/>
</FormControl>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="engine.btEnableLpd"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="app.magnetFileSelection"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
+ </div>
+ <PresetChips
+ name="tracker.probeTimeoutMs"
+ options={[
+ { label: '3s', value: 3000 },
+ { label: '5s', value: 5000 },
+ { label: '10s', value: 10000 },
+ ]}
+ />
+ </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.peers.magnetFileSelection')}
+ {t('settings.bittorrent.trackers.healthyThreshold')}
</FormLabel>
<FormDescription className="text-xs">
{t(
- 'settings.bittorrent.peers.magnetFileSelectionDesc'
+ 'settings.bittorrent.trackers.healthyThresholdDesc'
)}
</FormDescription>
</div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <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 }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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
- type="number"
- min={0}
- max={100}
- step={0.1}
- className="w-24 h-8"
- value={field.value}
- onChange={(e) =>
- field.onChange(
- Number.parseFloat(e.target.value) || 0
- )
- }
- />
- </FormControl>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="engine.seedTime"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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
type="number"
- min={0}
- max={525600}
+ min={500}
+ max={10000}
+ step={100}
className="w-24 h-8"
value={field.value}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 0)
+ field.onChange(Number.isFinite(n) ? n : 2000)
}}
/>
</FormControl>
- </FormItem>
- )}
- />
-
- <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>
+ </div>
+ <PresetChips
+ name="tracker.healthyThresholdMs"
+ options={[
+ { label: '1s', value: 1000 },
+ { label: '2s', value: 2000 },
+ { label: '5s', value: 5000 },
+ ]}
+ />
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="tracker.autoSync"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <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>
- </FormItem>
- )}
- />
-
- <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
- type="number"
- min={1}
- max={168}
- className="w-24 h-8"
- value={field.value}
- onChange={(e) => {
- const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 24)
- }}
- />
- </FormControl>
- </div>
- <PresetChips
- name="tracker.syncIntervalHours"
- options={[
- { label: '6h', value: 6 },
- { label: '12h', value: 12 },
- { label: '24h', value: 24 },
- ]}
+ <FormField
+ control={form.control}
+ name="tracker.minSuccessRate"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <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
+ type="number"
+ min={0}
+ max={1}
+ step={0.05}
+ className="w-24 h-8"
+ value={field.value}
+ onChange={(e) =>
+ field.onChange(Number.parseFloat(e.target.value) || 0)
+ }
/>
- </FormItem>
- )}
- />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="tracker.probeEnabled"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
+ <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.enableProbe')}
+ {t('settings.bittorrent.trackers.maxTrackerCount')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.bittorrent.trackers.enableProbeDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <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
- type="number"
- min={1000}
- max={30000}
- step={500}
- className="w-28 h-8"
- value={field.value}
- onChange={(e) => {
- const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 5000)
- }}
- />
- </FormControl>
- </div>
- <PresetChips
- name="tracker.probeTimeoutMs"
- options={[
- { label: '3s', value: 3000 },
- { label: '5s', value: 5000 },
- { label: '10s', value: 10000 },
- ]}
- />
- </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
- type="number"
- min={500}
- max={10000}
- step={100}
- className="w-24 h-8"
- value={field.value}
- onChange={(e) => {
- const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 2000)
- }}
- />
- </FormControl>
- </div>
- <PresetChips
- name="tracker.healthyThresholdMs"
- options={[
- { label: '1s', value: 1000 },
- { label: '2s', value: 2000 },
- { label: '5s', value: 5000 },
- ]}
- />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="tracker.minSuccessRate"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.bittorrent.trackers.minSuccessRate')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.bittorrent.trackers.minSuccessRateDesc')}
+ {t(
+ 'settings.bittorrent.trackers.maxTrackerCountDesc'
+ )}
</FormDescription>
</div>
<FormControl>
<Input
type="number"
- min={0}
- max={1}
- step={0.05}
+ min={5}
+ max={200}
className="w-24 h-8"
value={field.value}
- onChange={(e) =>
- field.onChange(
- Number.parseFloat(e.target.value) || 0
- )
- }
+ onChange={(e) => {
+ const n = Number.parseInt(e.target.value, 10)
+ field.onChange(Number.isFinite(n) ? n : 50)
+ }}
/>
</FormControl>
- </FormItem>
- )}
- />
+ </div>
+ <PresetChips
+ name="tracker.maxTrackerCount"
+ options={[
+ { label: '20', value: 20 },
+ { label: '50', value: 50 },
+ { label: '100', value: 100 },
+ ]}
+ />
+ </FormItem>
+ )}
+ />
- <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
- type="number"
- min={5}
- max={200}
- className="w-24 h-8"
- value={field.value}
- onChange={(e) => {
- const n = Number.parseInt(e.target.value, 10)
- field.onChange(Number.isFinite(n) ? n : 50)
- }}
- />
- </FormControl>
- </div>
- <PresetChips
- name="tracker.maxTrackerCount"
- options={[
- { label: '20', value: 20 },
- { label: '50', value: 50 },
- { label: '100', value: 100 },
- ]}
- />
- </FormItem>
- )}
- />
-
- <p className="text-xs text-muted-foreground">
- {t('settings.bittorrent.trackers.blacklistMovedInfo')}
- </p>
- </form>
- </Form>
+ <p className="text-xs text-muted-foreground">
+ {t('settings.bittorrent.trackers.blacklistMovedInfo')}
+ </p>
+ </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 />
- </div>
+ {/* Peer geo — self-contained form; rendered outside BT form to avoid nested <form> */}
+ <div className="mt-4 border-t border-border pt-4">
+ <BtPeerGeoSection />
</div>
+ </div>
- <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- size="sm"
- onClick={onSubmit}
- disabled={form.formState.isSubmitting}
- >
- {t('common.apply')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- <RestartConfirmDialog
- open={restartDialog.open}
- onResolve={restartDialog.handleResolve}
- />
- </>
+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={onSubmit}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
index 24e857b6..cda13337 100644
--- a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
@@ -96,13 +96,49 @@ describe('<DownloadsDialog>', () => {
.find((el) => el.getAttribute('min') === '1') as HTMLInputElement
fireEvent.change(concurrent, { target: { value: '10' } })
const user = userEvent.setup()
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
engine: { maxConcurrentDownloads: 10 },
})
expect(onClose).toHaveBeenCalled()
})
+ it('saves split, file allocation, and disk cache as explicit user values', async () => {
+ render(
+ <DownloadsDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )
+ await waitFor(() => {
+ expect(screen.getByLabelText(/split connections per file/i)).toHaveValue(
+ 16
+ )
+ })
+
+ fireEvent.change(screen.getByLabelText(/split connections per file/i), {
+ target: { value: '32' },
+ })
+ fireEvent.change(screen.getByLabelText(/disk cache/i), {
+ target: { value: '32' },
+ })
+ const user = userEvent.setup()
+ 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('button', { name: /save/i }))
+
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ engine: {
+ split: 32,
+ fileAllocation: 'prealloc',
+ diskCache: 32 * 1024 * 1024,
+ },
+ })
+ expect(screen.queryByText(/restart to apply changes/i)).toBeNull()
+ })
+
it('renders the speed modes with user-facing names', async () => {
render(
<DownloadsDialog
@@ -151,7 +187,7 @@ describe('<DownloadsDialog>', () => {
) as HTMLInputElement
// 1024 KB/s → bytes/sec: 1024 * 1024 = 1_048_576.
fireEvent.change(baseDown, { target: { value: '1024' } })
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
speedLimit: { base: { download: 1024 * 1024 } },
})
@@ -176,7 +212,7 @@ describe('<DownloadsDialog>', () => {
})
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: /^automatic$/i }))
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
speedLimit: { turtle: 'auto' },
})
@@ -273,7 +309,7 @@ describe('<DownloadsDialog>', () => {
expect(reserved).toHaveValue(20)
fireEvent.change(reserved, { target: { value: '30' } })
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
speedLimit: {
turtle: 'auto',
diff --git a/src/renderer/routes/settings/cards/downloads-dialog.tsx b/src/renderer/routes/settings/cards/downloads-dialog.tsx
index e0851d52..5161b5c3 100644
--- a/src/renderer/routes/settings/cards/downloads-dialog.tsx
+++ b/src/renderer/routes/settings/cards/downloads-dialog.tsx
@@ -1,5 +1,3 @@
-import { RestartConfirmDialog } from '@renderer/components/settings-kit/restart-confirm-dialog'
-import { useRestartConfirmDialog } from '@renderer/components/settings-kit/use-restart-confirm-dialog'
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
@@ -11,7 +9,7 @@ import {
} from '@renderer/components/ui/dialog'
import { Form } from '@renderer/components/ui/form'
import { Separator } from '@renderer/components/ui/separator'
-import { patchHasRestartKeys, pickDirty } from '@renderer/lib/form-utils'
+import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
@@ -40,7 +38,6 @@ export function DownloadsDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
- const restartDialog = useRestartConfirmDialog()
const form = useForm<DownloadsFields>({ defaultValues: DOWNLOADS_DEFAULTS })
// biome-ignore lint/correctness/useExhaustiveDependencies: form is stable across renders; this is a mount-only fetch
@@ -79,61 +76,45 @@ export function DownloadsDialog({
onClose()
return
}
- // If engine fields are dirty, check for restart-requiring keys.
- const enginePatch = (dirty as Partial<DownloadsFields>).engine
- if (enginePatch) {
- const patch = { engine: enginePatch }
- if (patchHasRestartKeys(patch as Partial<AppSettings>)) {
- const ok = await restartDialog.confirm()
- if (!ok) return
- }
- }
await transport.invoke(Commands.UpdateSettings, dirty)
onClose()
})
return (
- <>
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogContent
- className="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>
- </DialogHeader>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
- <Form {...form}>
- <form className="space-y-4">
- <EngineTuningSection form={form} />
- <Separator className="my-4" />
- <SpeedLimitSection form={form} />
- </form>
- </Form>
- </div>
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent
+ className="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>
+ </DialogHeader>
- <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- size="sm"
- onClick={onSubmit}
- disabled={form.formState.isSubmitting}
- >
- {t('common.apply')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
+ <Form {...form}>
+ <form className="space-y-4">
+ <EngineTuningSection form={form} />
+ <Separator className="my-4" />
+ <SpeedLimitSection form={form} />
+ </form>
+ </Form>
+ </div>
- <RestartConfirmDialog
- open={restartDialog.open}
- onResolve={restartDialog.handleResolve}
- />
- </>
+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={onSubmit}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsx
index e98aaf73..10e01bc8 100644
--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx
@@ -82,7 +82,7 @@ describe('<GeneralDialog>', () => {
name: /confirm before quitting/i,
})
await userEvent.click(toggle)
- await userEvent.click(screen.getByRole('button', { name: /apply/i }))
+ await userEvent.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
@@ -98,7 +98,7 @@ describe('<GeneralDialog>', () => {
name: /notify on failure/i,
})
await userEvent.click(toggle)
- await userEvent.click(screen.getByRole('button', { name: /apply/i }))
+ await userEvent.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
@@ -114,7 +114,7 @@ describe('<GeneralDialog>', () => {
name: /autofill link from clipboard/i,
})
await userEvent.click(toggle)
- await userEvent.click(screen.getByRole('button', { name: /apply/i }))
+ await userEvent.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
@@ -137,7 +137,7 @@ describe('<GeneralDialog>', () => {
const user = userEvent.setup()
const switches = screen.getAllByRole('switch')
await user.click(switches[0]) // toggle launchAtStartup
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
app: { launchAtStartup: true },
})
diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsx
index 86a566ca..b1e02253 100644
--- a/src/renderer/routes/settings/cards/general-dialog.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.tsx
@@ -1,6 +1,4 @@
import { DirectoryPicker } from '@renderer/components/desktop-kit/directory-picker'
-import { RestartConfirmDialog } from '@renderer/components/settings-kit/restart-confirm-dialog'
-import { useRestartConfirmDialog } from '@renderer/components/settings-kit/use-restart-confirm-dialog'
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
@@ -19,7 +17,7 @@ import {
FormLabel,
} from '@renderer/components/ui/form'
import { Switch } from '@renderer/components/ui/switch'
-import { patchHasRestartKeys, pickDirty } from '@renderer/lib/form-utils'
+import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
@@ -59,7 +57,6 @@ export function GeneralDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
- const restartDialog = useRestartConfirmDialog()
const form = useForm<GeneralFields>({ defaultValues: DEFAULTS })
// biome-ignore lint/correctness/useExhaustiveDependencies: form is stable across renders; this is a mount-only fetch
@@ -96,185 +93,174 @@ export function GeneralDialog({
return
}
const patch = { app: dirty }
- if (patchHasRestartKeys(patch as Partial<AppSettings>)) {
- const ok = await restartDialog.confirm()
- if (!ok) return
- }
await transport.invoke(Commands.UpdateSettings, patch)
onClose()
})
return (
- <>
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogContent
- className="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>
- </DialogHeader>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
- <Form {...form}>
- <form className="space-y-4">
- <FormField
- control={form.control}
- name="launchAtStartup"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.launchAtStartup')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.launchAtStartupDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent
+ className="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>
+ </DialogHeader>
- <FormField
- control={form.control}
- name="defaultSaveDir"
- render={() => (
- <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>
- <DirectoryPicker name="defaultSaveDir" />
- </FormItem>
- )}
- />
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
+ <Form {...form}>
+ <form className="space-y-4">
+ <FormField
+ control={form.control}
+ name="launchAtStartup"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.launchAtStartup')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.launchAtStartupDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="autofillClipboardLinks"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.autofillClipboardLinks')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.autofillClipboardLinksDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
+ <FormField
+ control={form.control}
+ name="defaultSaveDir"
+ render={() => (
+ <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>
+ <DirectoryPicker name="defaultSaveDir" />
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="notifyOnComplete"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.notifyOnComplete')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.notifyOnCompleteDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
+ <FormField
+ control={form.control}
+ name="autofillClipboardLinks"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.autofillClipboardLinks')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.autofillClipboardLinksDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="notifyOnError"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.notifyOnError')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.notifyOnErrorDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
+ <FormField
+ control={form.control}
+ name="notifyOnComplete"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.notifyOnComplete')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.notifyOnCompleteDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <FormField
- control={form.control}
- name="warnBeforeQuit"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.warnBeforeQuit')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.warnBeforeQuitDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </form>
- </Form>
- </div>
+ <FormField
+ control={form.control}
+ name="notifyOnError"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.notifyOnError')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.notifyOnErrorDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
- <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- size="sm"
- onClick={onSubmit}
- disabled={form.formState.isSubmitting}
- >
- {t('common.apply')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <FormField
+ control={form.control}
+ name="warnBeforeQuit"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.warnBeforeQuit')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.warnBeforeQuitDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </form>
+ </Form>
+ </div>
- <RestartConfirmDialog
- open={restartDialog.open}
- onResolve={restartDialog.handleResolve}
- />
- </>
+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={onSubmit}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
index 276df8fd..7907334c 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
@@ -1,6 +1,4 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import { RestartConfirmDialog } from '@renderer/components/settings-kit/restart-confirm-dialog'
-import { useRestartConfirmDialog } from '@renderer/components/settings-kit/use-restart-confirm-dialog'
import { Button } from '@renderer/components/ui/button'
import {
Dialog,
@@ -11,7 +9,7 @@ import {
DialogTitle,
} from '@renderer/components/ui/dialog'
import { Separator } from '@renderer/components/ui/separator'
-import { patchHasRestartKeys, pickDirty } from '@renderer/lib/form-utils'
+import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
@@ -61,7 +59,6 @@ export function IntegrationDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
- const restartDialog = useRestartConfirmDialog()
const form = useForm<IntegrationFormValues>({
resolver: zodResolver(integrationFormSchema),
defaultValues: DEFAULTS,
@@ -104,114 +101,103 @@ export function IntegrationDialog({
return
}
const patch = dirty as Partial<AppSettings>
- if (patchHasRestartKeys(patch)) {
- const ok = await restartDialog.confirm()
- if (!ok) return
- }
await transport.invoke(Commands.UpdateSettings, patch)
onClose()
})
return (
- <>
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogContent
- className="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>
- </DialogHeader>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
- <FormProvider {...form}>
- <div className="flex flex-col gap-6">
- <section
- aria-labelledby="integration-system"
- className="flex flex-col gap-3"
+ <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <DialogContent
+ className="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>
+ </DialogHeader>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
+ <FormProvider {...form}>
+ <div className="flex flex-col gap-6">
+ <section
+ aria-labelledby="integration-system"
+ className="flex flex-col gap-3"
+ >
+ <h3
+ id="integration-system"
+ className="text-sm font-semibold text-foreground"
>
- <h3
- id="integration-system"
- className="text-sm font-semibold text-foreground"
- >
- {t('settings.integration.system.title')}
- </h3>
- <SystemProtocolsSection />
- <AppImageIntegrationSection />
- </section>
-
- <Separator />
-
- <section
- aria-labelledby="integration-browser"
- className="flex flex-col gap-3"
+ {t('settings.integration.system.title')}
+ </h3>
+ <SystemProtocolsSection />
+ <AppImageIntegrationSection />
+ </section>
+
+ <Separator />
+
+ <section
+ aria-labelledby="integration-browser"
+ className="flex flex-col gap-3"
+ >
+ <h3
+ id="integration-browser"
+ className="text-sm font-semibold text-foreground"
>
- <h3
- id="integration-browser"
- className="text-sm font-semibold text-foreground"
- >
- {t('settings.integration.browser.title')}
- </h3>
- <BrowserExtensionsSection />
- </section>
-
- <Separator />
-
- <section
- aria-labelledby="integration-cli"
- className="flex flex-col gap-4"
+ {t('settings.integration.browser.title')}
+ </h3>
+ <BrowserExtensionsSection />
+ </section>
+
+ <Separator />
+
+ <section
+ aria-labelledby="integration-cli"
+ className="flex flex-col gap-4"
+ >
+ <h3
+ id="integration-cli"
+ className="text-sm font-semibold text-foreground"
>
- <h3
- id="integration-cli"
- className="text-sm font-semibold text-foreground"
- >
- {t('settings.integration.cli.title')}
- </h3>
- <CliToolSection />
- <Separator />
- <CLIClientsSection />
- <PendingApprovalsSection />
- </section>
-
+ {t('settings.integration.cli.title')}
+ </h3>
+ <CliToolSection />
<Separator />
-
- <section
- aria-labelledby="integration-media"
- className="flex flex-col gap-3"
+ <CLIClientsSection />
+ <PendingApprovalsSection />
+ </section>
+
+ <Separator />
+
+ <section
+ aria-labelledby="integration-media"
+ className="flex flex-col gap-3"
+ >
+ <h3
+ id="integration-media"
+ className="text-sm font-semibold text-foreground"
>
- <h3
- id="integration-media"
- className="text-sm font-semibold text-foreground"
- >
- {t('settings.integration.media.title')}
- </h3>
- <MediaToolsSection />
- </section>
- </div>
- </FormProvider>
- </div>
-
- <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- size="sm"
- onClick={onSubmit}
- disabled={form.formState.isSubmitting}
- >
- {t('common.apply')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- <RestartConfirmDialog
- open={restartDialog.open}
- onResolve={restartDialog.handleResolve}
- />
- </>
+ {t('settings.integration.media.title')}
+ </h3>
+ <MediaToolsSection />
+ </section>
+ </div>
+ </FormProvider>
+ </div>
+
+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={onSubmit}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/src/renderer/routes/settings/cards/network-dialog.test.tsx b/src/renderer/routes/settings/cards/network-dialog.test.tsx
index b044f2a1..7497ced1 100644
--- a/src/renderer/routes/settings/cards/network-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/network-dialog.test.tsx
@@ -85,7 +85,7 @@ describe('<NetworkDialog>', () => {
const user = userEvent.setup()
const switches = screen.getAllByRole('switch')
await user.click(switches[0])
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
expect(transport.invoke).toHaveBeenCalledWith(
Commands.UpdateSettings,
@@ -115,7 +115,7 @@ describe('<NetworkDialog>', () => {
const user = userEvent.setup()
await user.click(screen.getByRole('combobox', { name: /dns lookup/i }))
await user.click(await screen.findByRole('option', { name: /system dns/i }))
- await user.click(screen.getByRole('button', { name: /apply/i }))
+ await user.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
engine: { dnsMode: 'system' },
diff --git a/src/renderer/routes/settings/cards/network-dialog.tsx b/src/renderer/routes/settings/cards/network-dialog.tsx
index 96f5640e..cd99c21a 100644
--- a/src/renderer/routes/settings/cards/network-dialog.tsx
+++ b/src/renderer/routes/settings/cards/network-dialog.tsx
@@ -449,7 +449,7 @@ export function NetworkDialog({
onClick={onSubmit}
disabled={form.formState.isSubmitting}
>
- {t('common.apply')}
+ {t('common.save')}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/src/renderer/styles/globals.css b/src/renderer/styles/globals.css
index d6d9ef55..58316fe2 100644
--- a/src/renderer/styles/globals.css
+++ b/src/renderer/styles/globals.css
@@ -147,12 +147,20 @@
--window-chrome-safe-area-leading: 160px;
}
+.platform-darwin.window-main
+ .electron-window-chrome.preview-desktop-window-controls,
+.platform-linux.window-main .electron-window-chrome,
.platform-win32.window-main .electron-window-chrome {
- --window-chrome-safe-area-trailing: 148px;
+ --window-chrome-safe-area-trailing: 112px;
}
-.platform-linux.window-main .electron-window-chrome {
- --window-chrome-safe-area-trailing: 88px;
+@media (width >= 48rem) {
+ .electron-window-chrome.group\/sidebar-wrapper[data-state="expanded"]
+ .panel-action-align-visual-end {
+ /* Keep the 16px glyph centered inside its 28px target while preserving
+ the existing glyph-end visual line. */
+ inset-inline-end: -0.125rem;
+ }
}
.dark {
diff --git a/src/renderer/windows/add-task-window.tsx b/src/renderer/windows/add-task-window.tsx
index c3e58554..8b847e98 100644
--- a/src/renderer/windows/add-task-window.tsx
+++ b/src/renderer/windows/add-task-window.tsx
@@ -32,7 +32,12 @@ export function AddTaskWindow() {
return (
<div className="flex h-screen flex-col">
- <WindowChrome variant="titled" compact title={t('task.add.title')} />
+ <WindowChrome
+ variant="titled"
+ compact
+ maximizable={false}
+ title={t('task.add.title')}
+ />
<PlatformServicesProvider services={electronServices}>
<AddTaskForm
defaultValues={defaultValues}
diff --git a/src/renderer/windows/onboarding-window.tsx b/src/renderer/windows/onboarding-window.tsx
index f2e1ac27..6440e643 100644
--- a/src/renderer/windows/onboarding-window.tsx
+++ b/src/renderer/windows/onboarding-window.tsx
@@ -10,6 +10,7 @@ export function OnboardingWindow() {
title="Motrix"
variant="titled"
compact
+ maximizable={false}
actionsPosition="end"
>
<OnboardingLanguageSelect />
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index c3f424d3..b16d67b3 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -44,6 +44,7 @@ function makeFakeCtx() {
supervisor: {
stop: vi.fn().mockResolvedValue(undefined),
start: vi.fn().mockResolvedValue(undefined),
+ applyEngineSettings: vi.fn().mockResolvedValue(undefined),
applyAsyncDns: vi.fn().mockResolvedValue(undefined),
} as unknown as EngineSupervisor,
dnsFallback: { reset: vi.fn() },
@@ -78,6 +79,7 @@ function makeFakeCtx() {
deleteMetadata: vi.fn(),
} as unknown as MotrixDatabase,
notificationCenter: {
+ notify: vi.fn(() => ({ fresh: true })),
markRead: vi.fn(() => true),
markAllRead: vi.fn(() => 0),
delete: vi.fn(() => true),
@@ -145,7 +147,7 @@ function makeFakeCtx() {
function makeSettings(
proxy: typeof PROXY_OFF,
tracker: { sourcesEnabled?: boolean; blacklistEnabled?: boolean } = {},
- engine: { dnsMode?: 'auto' | 'system' | 'engine' } = {}
+ engine: { dnsMode?: 'auto' | 'system' | 'engine'; split?: number } = {}
) {
return {
proxy,
@@ -227,7 +229,7 @@ describe('server Commands.UpdateSettings', () => {
expect(ctx.dnsFallback.reset).not.toHaveBeenCalled()
})
- it('restarts engine via stop+start when requiresRestart is true', async () => {
+ it('publishes a restart reminder without stopping the engine', async () => {
const ctx = makeFakeCtx()
;(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockReturnValue(
makeSettings(PROXY_OFF)
@@ -239,8 +241,41 @@ describe('server Commands.UpdateSettings', () => {
ctx as Parameters<typeof buildServerCommandHandlers>[0]
)
await handlers[Commands.UpdateSettings]?.({ engine: { rpcPort: 9000 } })
- expect(ctx.supervisor.stop).toHaveBeenCalledOnce()
- expect(ctx.supervisor.start).toHaveBeenCalledWith('/usr/bin/aria2c')
+ expect(ctx.supervisor.stop).not.toHaveBeenCalled()
+ expect(ctx.supervisor.start).not.toHaveBeenCalled()
+ expect(ctx.notificationCenter.notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ kind: 'engine-restart-required',
+ severity: 'warning',
+ })
+ )
+ expect(ctx.eventBus.emit).toHaveBeenCalledWith(
+ Events.EngineRestartRequired,
+ { changedKeys: ['rpcPort'] }
+ )
+ })
+
+ it('hot-applies runtime engine settings without a restart reminder', async () => {
+ const ctx = makeFakeCtx()
+ const before = makeSettings(PROXY_OFF, {}, { dnsMode: 'auto', split: 16 })
+ const after = makeSettings(PROXY_OFF, {}, { dnsMode: 'auto', split: 32 })
+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)
+ .mockReturnValueOnce(before)
+ .mockReturnValueOnce(after)
+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(
+ { ok: true, requiresRestart: false, changedRestartKeys: [] }
+ )
+ const handlers = buildServerCommandHandlers(
+ ctx as Parameters<typeof buildServerCommandHandlers>[0]
+ )
+
+ await handlers[Commands.UpdateSettings]?.({ engine: { split: 32 } })
+
+ expect(ctx.supervisor.applyEngineSettings).toHaveBeenCalledWith(
+ before.engine,
+ after.engine
+ )
+ expect(ctx.notificationCenter.notify).not.toHaveBeenCalled()
})
it('calls trackerManager.applySourcesChange when sourcesEnabled changes', async () => {
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 8916939b..5f09257b 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -7,6 +7,7 @@ import type { EngineSupervisor } from '@core/engine/engine-supervisor'
import { ENGINE_READY_TIMEOUT_MS } from '@core/engine/engine-supervisor'
import type { EventBus } from '@core/events/event-bus'
import { getLogger } from '@core/logger'
+import { publishEngineRestartRequired } from '@core/notifications/engine-restart-required'
import type { NotificationCenter } from '@core/notifications/notification-center'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
import { pluginSecretFields } from '@core/plugin/configuration-schema'
@@ -135,7 +136,6 @@ export function buildServerCommandHandlers(
bindTaskRetry,
adapter,
trackerManager,
- aria2BinaryPath,
finalNamePicker,
torrentMetaStore,
taskManager,
@@ -536,6 +536,8 @@ export function buildServerCommandHandlers(
)
}
+ await supervisor.applyEngineSettings(oldFull.engine, newFull.engine)
+
if (oldFull.engine.dnsMode !== newFull.engine.dnsMode) {
await supervisor.applyAsyncDns(
dnsModeToAsyncDns(newFull.engine.dnsMode)
@@ -545,11 +547,11 @@ export function buildServerCommandHandlers(
dnsFallback?.reset()
}
- // Server uses explicit stop+start (mirrors Commands.RestartEngine
- // handler in this file); main runtime uses supervisor.restart().
if (result.requiresRestart) {
- await supervisor.stop()
- await supervisor.start(aria2BinaryPath)
+ publishEngineRestartRequired(
+ { eventBus, notificationCenter, log },
+ result.changedRestartKeys
+ )
}
return result
diff --git a/src/shared/constants/restart-keys.ts b/src/shared/constants/restart-keys.ts
index 5458ee2f..f327a312 100644
--- a/src/shared/constants/restart-keys.ts
+++ b/src/shared/constants/restart-keys.ts
@@ -17,10 +17,9 @@ export const ENGINE_RESTART_REQUIRED_KEYS: ReadonlySet<keyof EngineSettings> =
'sqlite3HistoryLimit',
])
-// Consumed by:
-// - renderer's patchHasRestartKeys() — shows RestartConfirmDialog before saving
-// - SettingsManager.update() — sets requiresAppRestart in UpdateResult
-// - Commands.UpdateSettings handler — calls app.relaunch() + app.exit(0)
+// Consumed by SettingsManager.update(), which reports requiresAppRestart to
+// shell command handlers. Settings forms always save first; shells own any
+// follow-up restart notice or action.
//
// Currently empty: launchAtStartup is hot-applied via syncAutoLaunch();
// browserBridgeEnabled is hot-applied via BridgeManager.setEnabled().
diff --git a/src/shared/constants/window-chrome.ts b/src/shared/constants/window-chrome.ts
new file mode 100644
index 00000000..cc9a8aaa
--- /dev/null
+++ b/src/shared/constants/window-chrome.ts
@@ -0,0 +1,3 @@
+/** Custom Windows/Linux title-bar geometry shared across renderer surfaces. */
+export const DESKTOP_WINDOW_CHROME_HEIGHT = 40
+export const WINDOW_CHROME_EDGE_GAP = 16
diff --git a/src/shared/external-urls.test.ts b/src/shared/external-urls.test.ts
new file mode 100644
index 00000000..160c86a1
--- /dev/null
+++ b/src/shared/external-urls.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest'
+import { EXTERNAL_URLS, getNatTroubleshootingUrl } from './external-urls'
+
+describe('getNatTroubleshootingUrl', () => {
+ it('uses the Chinese manual for Chinese locales', () => {
+ expect(getNatTroubleshootingUrl('zh-CN')).toBe(
+ EXTERNAL_URLS.motrix.manual.natTroubleshooting.zh
+ )
+ expect(getNatTroubleshootingUrl('zh-Hant-TW')).toBe(
+ EXTERNAL_URLS.motrix.manual.natTroubleshooting.zh
+ )
+ })
+
+ it('uses the English manual for other locales', () => {
+ expect(getNatTroubleshootingUrl('en-US')).toBe(
+ EXTERNAL_URLS.motrix.manual.natTroubleshooting.en
+ )
+ })
+})
diff --git a/src/shared/external-urls.ts b/src/shared/external-urls.ts
index a162004e..cead8ba8 100644
--- a/src/shared/external-urls.ts
+++ b/src/shared/external-urls.ts
@@ -18,8 +18,17 @@ export const EXTERNAL_URLS = {
releaseNotes: 'https://motrix.app/release-notes/',
manual: {
home: 'https://motrix.app/manual/',
+ natTroubleshooting: {
+ en: 'https://motrix.app/manual/port-mapping/',
+ zh: 'https://motrix.app/zh/manual/port-mapping/',
+ },
advancedProxy: 'https://motrix.app/manual/advanced-proxy',
defaultApplication: 'https://motrix.app/manual/default-application',
},
},
} as const
+
+export function getNatTroubleshootingUrl(language: string): string {
+ const locale = language.toLowerCase().startsWith('zh') ? 'zh' : 'en'
+ return EXTERNAL_URLS.motrix.manual.natTroubleshooting[locale]
+}
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 46bbd37b..57d19c4a 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -96,6 +96,7 @@
},
"chrome": {
"minimize": "Minimize",
+ "toggleMaximize": "Maximize or restore",
"close": "Close",
"toggleSidebar": "Toggle sidebar",
"newTask": "New task"
@@ -448,11 +449,13 @@
"disable": "Disable NAT",
"remap": "Force remap",
"diagnose": "Run diagnostic",
+ "troubleshoot": "NAT troubleshooting guide",
"short": {
"enable": "Enable",
"disable": "Disable",
"remap": "Remap",
- "diagnose": "Diagnose"
+ "diagnose": "Diagnose",
+ "help": "Help"
},
"settings": "NAT settings"
},
@@ -529,7 +532,8 @@
"natFailed": "NAT failed",
"natOff": "NAT off",
"natEnable": "Enable NAT",
- "natDisable": "Disable NAT"
+ "natDisable": "Disable NAT",
+ "natHelp": "Troubleshoot NAT"
},
"tab": {
"all": "All",
@@ -1323,11 +1327,6 @@
}
},
"common": {
- "restartConfirm": {
- "title": "Restart to apply changes?",
- "body": "Some changes require a restart to take effect. Active downloads pause and resume in a few seconds.",
- "confirm": "Save and restart"
- },
"browse": "Browse…",
"add": "Add",
"remove": "Remove",
@@ -2100,6 +2099,11 @@
"engineFailure": {
"title": "Download engine failed"
},
+ "engineRestartRequired": {
+ "title": "Restart the download engine to apply settings",
+ "body": "Your settings are saved. Restart the download engine when convenient.",
+ "restartNow": "Restart now"
+ },
"dnsFallback": {
"title": "{{name}} retried with system DNS",
"body": "Motrix couldn't reach a DNS server, so it switched to system DNS for this session."
@@ -2109,7 +2113,7 @@
"markAllRead": "Mark all read",
"clearAll": "Clear",
"empty": "No notifications",
- "emptyDesc": "Download failures and completions will show up here",
+ "emptyDesc": "Download activity and important app notices will show up here",
"unreadBadgeAria_one": "{{count}} unread notification",
"unreadBadgeAria_other": "{{count}} unread notifications",
"rowUnreadAria": "{{title}} (unread)",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 28b6ceb7..92c23a09 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -95,6 +95,7 @@
},
"chrome": {
"minimize": "最小化",
+ "toggleMaximize": "最大化或还原",
"close": "关闭",
"toggleSidebar": "切换边栏",
"newTask": "新建任务"
@@ -446,11 +447,13 @@
"disable": "禁用 NAT",
"remap": "强制重映射",
"diagnose": "运行诊断",
+ "troubleshoot": "查看 NAT 排障手册",
"short": {
"enable": "启用",
"disable": "禁用",
"remap": "重映射",
- "diagnose": "诊断"
+ "diagnose": "诊断",
+ "help": "帮助"
},
"settings": "NAT 设置"
},
@@ -527,7 +530,8 @@
"natOff": "NAT 已关闭",
"natRetrying": "NAT 重试中 ({{attempt}}/{{max}})",
"natEnable": "启用 NAT",
- "natDisable": "关闭 NAT"
+ "natDisable": "关闭 NAT",
+ "natHelp": "查看 NAT 排障手册"
},
"tab": {
"all": "全部",
@@ -1310,11 +1314,6 @@
}
},
"common": {
- "restartConfirm": {
- "title": "重启以应用更改?",
- "body": "部分更改需要重启才能生效。当前下载会暂停后自动恢复。",
- "confirm": "保存并重启"
- },
"browse": "浏览…",
"add": "添加",
"remove": "移除",
@@ -2080,6 +2079,11 @@
"engineFailure": {
"title": "下载引擎故障"
},
+ "engineRestartRequired": {
+ "title": "重启下载引擎以应用设置",
+ "body": "设置已保存,可在方便时重启下载引擎。",
+ "restartNow": "立即重启"
+ },
"dnsFallback": {
"title": "{{name}} 已改用系统 DNS 重试",
"body": "引擎无法联系任何 DNS 服务器,本次会话已切换到系统解析器。"
@@ -2089,7 +2093,7 @@
"markAllRead": "全部标为已读",
"clearAll": "清空",
"empty": "暂无通知",
- "emptyDesc": "下载失败和完成会显示在这里",
+ "emptyDesc": "下载活动和重要应用提醒会显示在这里",
"unreadBadgeAria_other": "{{count}} 条未读通知",
"rowUnreadAria": "{{title}}(未读)",
"toastRegionAria": "通知"
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 6907b23a..68be1da8 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -95,6 +95,7 @@
},
"chrome": {
"minimize": "最小化",
+ "toggleMaximize": "最大化或還原",
"close": "關閉",
"toggleSidebar": "切換側邊欄",
"newTask": "新增任務"
@@ -446,11 +447,13 @@
"disable": "停用 NAT",
"remap": "強制重新對應",
"diagnose": "執行診斷",
+ "troubleshoot": "查看 NAT 疑難排解手冊",
"short": {
"enable": "啟用",
"disable": "停用",
"remap": "重新對應",
- "diagnose": "診斷"
+ "diagnose": "診斷",
+ "help": "說明"
},
"settings": "NAT 設定"
},
@@ -527,7 +530,8 @@
"natFailed": "NAT 失敗",
"natOff": "NAT 已關閉",
"natEnable": "啟用 NAT",
- "natDisable": "停用 NAT"
+ "natDisable": "停用 NAT",
+ "natHelp": "查看 NAT 疑難排解手冊"
},
"tab": {
"all": "全部",
@@ -1310,11 +1314,6 @@
}
},
"common": {
- "restartConfirm": {
- "title": "要重新啟動以套用變更嗎?",
- "body": "部分變更需要重新啟動才會生效。進行中的下載將會暫停,並在幾秒後繼續。",
- "confirm": "儲存並重新啟動"
- },
"browse": "瀏覽...",
"add": "新增",
"remove": "移除",
@@ -1701,6 +1700,11 @@
"engineFailure": {
"title": "下載引擎失敗"
},
+ "engineRestartRequired": {
+ "title": "重新啟動下載引擎以套用設定",
+ "body": "設定已儲存,您可以在方便時重新啟動下載引擎。",
+ "restartNow": "立即重新啟動"
+ },
"dnsFallback": {
"title": "{{name}} 已改用系統 DNS 重試",
"body": "引擎無法聯繫任何 DNS 伺服器,本次工作階段已切換至系統解析器。"
@@ -1710,7 +1714,7 @@
"markAllRead": "全部標示為已讀",
"clearAll": "清除",
"empty": "沒有通知",
- "emptyDesc": "下載失敗和完成時會顯示在這裡",
+ "emptyDesc": "下載活動和重要應用程式通知會顯示在這裡",
"unreadBadgeAria_other": "{{count}} 則未讀通知",
"rowUnreadAria": "{{title}} (未讀)",
"toastRegionAria": "通知"
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 343eff2e..8e0db035 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -50,6 +50,7 @@ export const Commands = {
DownloadAllTorrents: 'command:downloadAllTorrents',
CloseCurrentWindow: 'command:closeCurrentWindow',
MinimizeCurrentWindow: 'command:minimizeCurrentWindow',
+ ToggleMaximizeCurrentWindow: 'command:toggleMaximizeCurrentWindow',
ShowMainWindow: 'command:showMainWindow',
ShowAddTaskWindow: 'command:showAddTaskWindow',
// Torrent
diff --git a/src/shared/types/engine.ts b/src/shared/types/engine.ts
index 1c20e695..c8f14b2e 100644
--- a/src/shared/types/engine.ts
+++ b/src/shared/types/engine.ts
@@ -74,6 +74,11 @@ export interface EngineFailurePayload {
technicalMessage: string | null
}
+/** Payload emitted after settings save while startup-only engine keys differ. */
+export interface EngineRestartRequiredPayload {
+ changedKeys: string[]
+}
+
export interface EngineProcessInfo {
pid: number
name: string
diff --git a/src/shared/types/notification.ts b/src/shared/types/notification.ts
index 7266a515..e7edaae7 100644
--- a/src/shared/types/notification.ts
+++ b/src/shared/types/notification.ts
@@ -5,6 +5,7 @@ export const NotificationKinds = {
TaskError: 'task-error',
TaskComplete: 'task-complete',
EngineFailure: 'engine-failure',
+ EngineRestartRequired: 'engine-restart-required',
DnsFallback: 'dns-fallback',
} as const
export type NotificationKind = string