Skip to content

A full-featured download manager.

feat(ui): refine dashboard controls and engine diagnostics (#2168)

Dr_rOotbade80222ef4
diff --git a/.gitignore b/.gitignore
index dc83e536..b7758ce7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -161,6 +161,7 @@ graphify-out/*
/playwright-report
/test-results
/.playwright
+/output/playwright
.agents/
skills-lock.json
diff --git a/e2e/activity-tile.spec.ts b/e2e/activity-tile.spec.ts
index 1428a1f3..689a093b 100644
--- a/e2e/activity-tile.spec.ts
+++ b/e2e/activity-tile.spec.ts
@@ -94,7 +94,8 @@ const ENFORCE_REFERENCE_BUDGETS =
process.env.MOTRIX_ACTIVITY_PROFILE_GATE === '1'
function expectedWeeks(span: ActivitySpan): 13 | 26 | 53 {
- if (span.w === 1 || (span.w === 2 && span.h === 1)) return 13
+ if (span.w === 1) return 13
+ if (span.w === 2 && span.h === 1) return 26
if (span.w === 3 && span.h === 1) return 26
if (span.w === 2 && span.h === 2) return 26
return 53
@@ -500,11 +501,11 @@ async function readRendererProfile(page: Page): Promise<RendererProfile> {
element.getAttribute('aria-hidden') === 'true'
)
const monthLabels = directLabels
- .filter((element) => element.style.left !== '')
+ .filter((element) => element.dataset.calendarLabel === 'month')
.map((element) => element.textContent?.trim() ?? '')
.filter(Boolean)
const weekdayLabels = directLabels
- .filter((element) => element.style.top !== '')
+ .filter((element) => element.dataset.calendarLabel === 'weekday')
.map((element) => element.textContent?.trim() ?? '')
.filter(Boolean)
@@ -980,20 +981,26 @@ test.describe('Activity Tile production renderer', () => {
expect(profile.canvasCssWidth).toBeLessThanOrEqual(
profile.calendarClientWidth + 1
)
+ await mainWindow.getByTestId('dashboard-tile-activity').screenshot({
+ path: testInfo.outputPath(`activity-${span.w}x${span.h}-light-en.png`),
+ })
if (span.w === 4 && span.h === 2) {
await expect(mainWindow.locator('html')).toHaveClass(/light/)
- expect(profile.weekdayLabels).toEqual(['Mon', 'Wed', 'Fri'])
- if (profile.monthLabels.length > 1) {
- expect(profile.monthLabels.at(-1)).not.toBe(profile.monthLabels.at(0))
- }
- await mainWindow.getByTestId('dashboard-tile-activity').screenshot({
- path: testInfo.outputPath('activity-4x2-light-en.png'),
- })
+ expect(profile.weekdayLabels).toEqual([
+ 'Mon',
+ 'Wed',
+ 'Fri',
+ 'Mon',
+ 'Wed',
+ 'Fri',
+ ])
+ expect(profile.monthLabels.length).toBeGreaterThanOrEqual(12)
}
}
const calendar = mainWindow.getByTestId('activity-calendar')
+ await mainWindow.mouse.move(1, 1)
await calendar.focus()
await expect(mainWindow.getByRole('tooltip')).toBeVisible()
await expect(mainWindow.getByRole('tooltip')).toContainText(
@@ -1115,7 +1122,7 @@ test.describe('Activity Tile production renderer', () => {
await mainWindow
.getByRole('menuitemradio', { name: /2\s*[×x]\s*1/i })
.click()
- await expect(calendar).toHaveAttribute('aria-colcount', '13')
+ await expect(calendar).toHaveAttribute('aria-colcount', '26')
const dragHandle = activityTile.getByRole('button', { name: 'Drag tile' })
const dragBox = await dragHandle.boundingBox()
@@ -1295,7 +1302,14 @@ test.describe('Activity Tile production renderer', () => {
).toBeVisible()
await expect(mainWindow.locator('html')).toHaveClass(/dark/)
const chinese = await readRendererProfile(mainWindow)
- expect(chinese.weekdayLabels).toEqual(['周一', '周三', '周五'])
+ expect(chinese.weekdayLabels).toEqual([
+ '周一',
+ '周三',
+ '周五',
+ '周一',
+ '周三',
+ '周五',
+ ])
await mainWindow.getByTestId('dashboard-tile-activity').screenshot({
path: testInfo.outputPath('activity-4x2-dark-zh.png'),
})
diff --git a/e2e/dashboard.spec.ts b/e2e/dashboard.spec.ts
index e58b6225..f5092682 100644
--- a/e2e/dashboard.spec.ts
+++ b/e2e/dashboard.spec.ts
@@ -9,8 +9,68 @@
// subprocess. No e2e helper exists for this. This test is skipped.
// Both are documented below with test.skip.
import { expect, test } from './fixtures/electron-app'
+import { setTaskInspectorContentSize } from './fixtures/task-inspector-activity'
test.describe('Dashboard v1', () => {
+ test('keeps the compact header aligned with Downloads while configuring tiles', async ({
+ mainWindow,
+ electronApp,
+ }) => {
+ await expect(mainWindow.locator('html')).toHaveClass(/window-main/)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1100, 780)
+ const toggleSidebar = mainWindow.getByRole('button', {
+ name: 'Toggle sidebar',
+ exact: true,
+ })
+ const header = mainWindow.locator('[data-slot="panel-shell-header"]')
+ const headerHeight = () =>
+ header.evaluate((element) => element.getBoundingClientRect().height)
+
+ await mainWindow
+ .getByRole('link', { name: 'Downloads', exact: true })
+ .click()
+ await toggleSidebar.click()
+ await expect(
+ mainWindow.getByRole('toolbar', { name: 'Downloads' })
+ ).toHaveAttribute('data-density', 'compact')
+ await expect.poll(headerHeight).toBe(38)
+ const downloadsHeight = await headerHeight()
+
+ await toggleSidebar.click()
+ await mainWindow
+ .getByRole('link', { name: 'Dashboard', exact: true })
+ .click()
+ await toggleSidebar.click()
+ await expect.poll(headerHeight).toBe(downloadsHeight)
+ const engine = mainWindow.getByTestId('dashboard-tile-engine')
+ const tileTop = await engine.evaluate(
+ (element) => element.getBoundingClientRect().top
+ )
+
+ await mainWindow
+ .getByRole('button', { name: 'Configure', exact: true })
+ .click()
+ const toolbar = mainWindow.getByRole('toolbar', {
+ name: 'Configure',
+ exact: true,
+ })
+ await expect(toolbar).toHaveAttribute('data-density', 'compact')
+ await expect.poll(headerHeight).toBe(downloadsHeight)
+ await expect
+ .poll(() =>
+ engine.evaluate((element) => element.getBoundingClientRect().top)
+ )
+ .toBe(tileTop)
+ await toolbar.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(toolbar).toHaveCount(0)
+ await expect.poll(headerHeight).toBe(downloadsHeight)
+ await expect
+ .poll(() =>
+ engine.evaluate((element) => element.getBoundingClientRect().top)
+ )
+ .toBe(tileTop)
+ })
+
test('cold launch renders seven default tile labels within 800ms', async ({
mainWindow,
}) => {
diff --git a/src/core/engine/aria2/aria2-rpc-client.test.ts b/src/core/engine/aria2/aria2-rpc-client.test.ts
index e414a4ea..3167a35b 100644
--- a/src/core/engine/aria2/aria2-rpc-client.test.ts
+++ b/src/core/engine/aria2/aria2-rpc-client.test.ts
@@ -81,6 +81,17 @@ describe('Aria2RpcClient', () => {
vi.restoreAllMocks()
})
+ it.each([true, false])(
+ 'reports the actual WebSocket connection state: %s',
+ (connected) => {
+ fakeTransport.isConnected.mockReturnValue(connected)
+ expect(client.getConnectionStatus()).toEqual({
+ transport: 'websocket',
+ connected,
+ })
+ }
+ )
+
describe('accepted pause reconciliation', () => {
const active = {
gid: 'gid1',
diff --git a/src/core/engine/aria2/aria2-rpc-client.ts b/src/core/engine/aria2/aria2-rpc-client.ts
index 7e2b6c90..2e87331a 100644
--- a/src/core/engine/aria2/aria2-rpc-client.ts
+++ b/src/core/engine/aria2/aria2-rpc-client.ts
@@ -1,3 +1,4 @@
+import type { EngineConnectionSnapshot } from '@shared/schemas/engine-connection'
import type { DownloadCookie } from '../engine-adapter'
import { Aria2PauseState } from './aria2-pause-state'
import type { JsonRpcProtocol } from './json-rpc-protocol'
@@ -69,6 +70,10 @@ export class Aria2RpcClient {
return this.transport.isConnected()
}
+ getConnectionStatus(): EngineConnectionSnapshot {
+ return { transport: 'websocket', connected: this.transport.isConnected() }
+ }
+
// ─── Secret injection ────────────────────────────────────────
/** Synchronize the credential used for all subsequent RPC calls. */
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index f6da8a02..a05181ed 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -133,6 +133,10 @@ function createMockRpcClient(): Aria2RpcClient {
connect: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn(),
isConnected: vi.fn(() => true),
+ getConnectionStatus: vi.fn(() => ({
+ transport: 'websocket',
+ connected: true,
+ })),
getVersion: vi.fn().mockResolvedValue({
version: '1.37.0',
enabledFeatures: ['SQLite3-Persistence'],
@@ -1370,6 +1374,22 @@ describe('EngineSupervisor', () => {
})
describe('manual recovery', () => {
+ it('includes the current transport state even before lifecycle health checks catch up', async () => {
+ await supervisor.start('/usr/bin/aria2c')
+ vi.mocked(rpcClient.getConnectionStatus).mockReturnValue({
+ transport: 'websocket',
+ connected: false,
+ })
+
+ const report = await supervisor.diagnose()
+
+ expect(report.state).toBe(EngineState.Ready)
+ expect(report.rpc.connection).toEqual({
+ transport: 'websocket',
+ connected: false,
+ })
+ })
+
function useFallbackPort(): { rpcPort: number } {
const engineSettings = {
...settings.getEngine(),
diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.ts
index 8cbb3c9f..01664fa3 100644
--- a/src/core/engine/engine-supervisor.ts
+++ b/src/core/engine/engine-supervisor.ts
@@ -927,6 +927,7 @@ export class EngineSupervisor {
port: engineSettings.rpcPort,
available: portAvailable,
expectedListener,
+ connection: this.rpcClient.getConnectionStatus(),
},
process: processInfo,
defaultRpc: {
diff --git a/src/core/plugin/host/plugin-host.test.ts b/src/core/plugin/host/plugin-host.test.ts
index 107497bd..da6b8d20 100644
--- a/src/core/plugin/host/plugin-host.test.ts
+++ b/src/core/plugin/host/plugin-host.test.ts
@@ -717,9 +717,12 @@ describe('PluginHost', () => {
host.bridgeFor('alice.demo')?.getWorker().postMessage({
type: 'test_clear_timer',
})
- await new Promise((resolve) => setTimeout(resolve, 5))
- host.__sweepIdleForTest()
- await vi.waitFor(() => expect(host.isActive('alice.demo')).toBe(false))
+ // Timer activity arrives asynchronously and resets the idle clock.
+ // Keep sweeping until the cleared timer has also become idle.
+ await vi.waitFor(() => {
+ host.__sweepIdleForTest()
+ expect(host.isActive('alice.demo')).toBe(false)
+ })
await host.shutdown()
})
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index fa077df6..f742d2f5 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -705,7 +705,12 @@ describe('GetEngineDiagnostics handler', () => {
managedPid: null,
featureReport: null,
binary: { name: 'aria2c', available: true, version: '1.37.0' },
- rpc: { port: 16800, available: false, expectedListener: false },
+ rpc: {
+ port: 16800,
+ available: false,
+ expectedListener: false,
+ connection: { transport: 'websocket', connected: false },
+ },
process: null,
defaultRpc: {
port: 16800,
diff --git a/src/renderer/components/desktop-kit/copy-button.tsx b/src/renderer/components/desktop-kit/copy-button.tsx
index dd58bd7d..80858b10 100644
--- a/src/renderer/components/desktop-kit/copy-button.tsx
+++ b/src/renderer/components/desktop-kit/copy-button.tsx
@@ -2,6 +2,7 @@ import { Button } from '@renderer/components/ui/button'
import { Check, Copy } from 'lucide-react'
import {
type ComponentProps,
+ type ReactNode,
useCallback,
useEffect,
useRef,
@@ -16,6 +17,8 @@ type CopyButtonProps = Omit<
iconPosition?: 'start' | 'end'
onClick?: () => void | Promise<void>
resetMs?: number
+ copiedLabel?: ReactNode
+ onCopyError?: (error: unknown) => void
}
export function CopyButton({
@@ -23,6 +26,8 @@ export function CopyButton({
iconPosition = 'start',
onClick,
resetMs = 1500,
+ copiedLabel,
+ onCopyError,
children,
...rest
}: CopyButtonProps) {
@@ -45,7 +50,8 @@ export function CopyButton({
} else {
return
}
- } catch {
+ } catch (error) {
+ onCopyError?.(error)
return
}
@@ -55,14 +61,34 @@ export function CopyButton({
setCopied(false)
timerRef.current = null
}, resetMs)
- }, [content, onClick, resetMs])
+ }, [content, onClick, onCopyError, resetMs])
const Icon = copied ? Check : Copy
return (
<Button type="button" onClick={handleClick} {...rest}>
{iconPosition === 'start' && <Icon />}
- {children}
+ {copiedLabel ? (
+ <span className="grid">
+ <span
+ aria-hidden="true"
+ className="invisible col-start-1 row-start-1"
+ >
+ {children}
+ </span>
+ <span
+ aria-hidden="true"
+ className="invisible col-start-1 row-start-1"
+ >
+ {copiedLabel}
+ </span>
+ <span aria-live="polite" className="col-start-1 row-start-1">
+ {copied ? copiedLabel : children}
+ </span>
+ </span>
+ ) : (
+ children
+ )}
{iconPosition === 'end' && <Icon />}
</Button>
)
diff --git a/src/renderer/components/desktop-kit/cubic-glass/cubic-glass-motion-lab.tsx b/src/renderer/components/desktop-kit/cubic-glass/cubic-glass-motion-lab.tsx
index 3e7fdc1c..083c873d 100644
--- a/src/renderer/components/desktop-kit/cubic-glass/cubic-glass-motion-lab.tsx
+++ b/src/renderer/components/desktop-kit/cubic-glass/cubic-glass-motion-lab.tsx
@@ -70,16 +70,16 @@ export function CubicGlassMotionLab({
}
return (
- <div className="app-no-drag absolute right-3 top-3 z-20">
+ <div className="app-no-drag absolute right-0 top-3 z-20">
<Popover>
<PopoverTrigger
render={
<Button
type="button"
- variant="outline"
+ variant="ghost"
size="icon-sm"
aria-label={t('panel.downloads.empty.motion.open')}
- className="rounded-full bg-background/70 shadow-sm backdrop-blur-md"
+ className="hover:bg-transparent"
/>
}
>
diff --git a/src/renderer/features/engine-diagnostics/diagnostic-report.test.ts b/src/renderer/features/engine-diagnostics/diagnostic-report.test.ts
new file mode 100644
index 00000000..1c7ca049
--- /dev/null
+++ b/src/renderer/features/engine-diagnostics/diagnostic-report.test.ts
@@ -0,0 +1,97 @@
+import {
+ type EngineDiagnosticReport,
+ EngineFailureReason,
+ EngineRecoveryRecommendation,
+ EngineState,
+} from '@shared/types/engine'
+import { describe, expect, it } from 'vitest'
+import { formatEngineDiagnostics } from './diagnostic-report'
+
+const report: EngineDiagnosticReport = {
+ state: EngineState.Failed,
+ managedPid: null,
+ generatedAt: 1,
+ binary: { name: 'aria2c', available: true, version: '1.37.0-motrix.14' },
+ featureReport: null,
+ rpc: {
+ port: 16800,
+ available: true,
+ expectedListener: false,
+ connection: { transport: 'websocket', connected: false },
+ },
+ process: null,
+ defaultRpc: {
+ port: 16800,
+ available: true,
+ isCurrent: true,
+ process: null,
+ canRestore: false,
+ requiresTermination: false,
+ },
+ failure: {
+ reason: EngineFailureReason.RpcUnavailable,
+ occurredAt: 1,
+ technicalMessage: null,
+ },
+ recommendation: EngineRecoveryRecommendation.Retry,
+ canRetry: true,
+ canForceTerminate: false,
+ canSwitchPort: false,
+ suggestedRpcPort: null,
+}
+
+describe('formatEngineDiagnostics', () => {
+ it('exports the full detected version, timestamps and unavailable values without inventing results', () => {
+ const text = formatEngineDiagnostics(report)
+ const parsed = JSON.parse(text)
+ expect(parsed.binary.version).toBe('1.37.0-motrix.14')
+ expect(parsed.generatedAt).toBe('1970-01-01T00:00:00.001Z')
+ expect(parsed.featureReport).toBeNull()
+ expect(parsed.failure.technicalMessage).toBeNull()
+ expect(parsed.managedPid).toBeNull()
+ expect(parsed.canRetry).toBe(true)
+ expect(parsed.rpc.connection).toEqual({
+ transport: 'websocket',
+ connected: false,
+ })
+ expect(parsed.application.version).toBe(__MOTRIX_APP_METADATA__.version)
+ })
+
+ it('omits unknown future transport fields from shared reports', () => {
+ const text = formatEngineDiagnostics({
+ ...report,
+ privateData: 'future-secret',
+ binary: { ...report.binary, privateData: 'binary-secret' },
+ } as EngineDiagnosticReport)
+ expect(text).not.toContain('future-secret')
+ expect(text).not.toContain('binary-secret')
+ })
+
+ it('redacts credential-shaped errors and home paths while retaining diagnostic evidence', () => {
+ const text = formatEngineDiagnostics({
+ ...report,
+ failure: {
+ ...report.failure!,
+ technicalMessage:
+ 'Failed on port 16800: --rpc-secret="secret with spaces" --all-proxy-passwd=proxy-secret Authorization: Bearer bearer-secret https://user:[email protected]/rpc?token=query-secret&port=16800 {"token":"json-secret"} /Users/alice/Downloads C:\\Users\\bob\\Downloads',
+ },
+ })
+ for (const secret of [
+ 'secret with spaces',
+ 'proxy-secret',
+ 'bearer-secret',
+ 'user:pass',
+ 'query-secret',
+ 'json-secret',
+ 'alice',
+ 'bob',
+ ])
+ expect(text).not.toContain(secret)
+ expect(text).toContain('16800')
+ expect(text).toContain('[redacted]')
+ expect(text).toContain('[home]')
+ expect(JSON.parse(text).failure.reason).toBe(
+ EngineFailureReason.RpcUnavailable
+ )
+ })
+})
diff --git a/src/renderer/features/engine-diagnostics/diagnostic-report.ts b/src/renderer/features/engine-diagnostics/diagnostic-report.ts
new file mode 100644
index 00000000..b2bbe42d
--- /dev/null
+++ b/src/renderer/features/engine-diagnostics/diagnostic-report.ts
@@ -0,0 +1,102 @@
+import type {
+ EngineDiagnosticReport,
+ EngineProcessInfo,
+} from '@shared/types/engine'
+
+// Error messages are already sanitized by the engine. Cover credential-shaped
+// text and home directories again when producing a report intended for sharing.
+function redactDiagnosticText(value: string): string {
+ return value
+ .replace(/\b(Bearer\s+|token:)[A-Za-z0-9._~+/=-]+/gi, '$1[redacted]')
+ .replace(
+ /(["']?(?:--)?(?:rpc-secret|all-proxy(?:-user|-passwd)?|password|passwd|token|api[_-]?key|authorization)["']?\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,
+ '$1[redacted]'
+ )
+ .replace(/(https?:\/\/)[^\s/@]+@/gi, '$1[redacted]@')
+ .replace(/\/(?:Users|home)\/[^/\s]+/g, '[home]')
+ .replace(/[A-Z]:\\Users\\[^\\\s]+/gi, '[home]')
+}
+
+function processSnapshot(process: EngineProcessInfo | null) {
+ return process
+ ? {
+ pid: process.pid,
+ name: redactDiagnosticText(process.name),
+ executableName: process.executableName
+ ? redactDiagnosticText(process.executableName)
+ : null,
+ ownership: process.ownership,
+ safeToTerminate: process.safeToTerminate,
+ }
+ : null
+}
+
+export function formatEngineDiagnostics(
+ report: EngineDiagnosticReport
+): string {
+ // Explicit fields keep future transport additions out of clipboard exports.
+ return JSON.stringify(
+ {
+ schemaVersion: 1,
+ application: {
+ name: __MOTRIX_APP_METADATA__.name,
+ version: __MOTRIX_APP_METADATA__.version,
+ target: __MOTRIX_TARGET__,
+ },
+ generatedAt: new Date(report.generatedAt).toISOString(),
+ state: report.state,
+ managedPid: report.managedPid,
+ binary: {
+ name: redactDiagnosticText(report.binary.name),
+ available: report.binary.available,
+ version: report.binary.version,
+ },
+ featureReport: report.featureReport
+ ? {
+ version: report.featureReport.version,
+ features: report.featureReport.features,
+ hasBtSeedUnverified: report.featureReport.hasBtSeedUnverified,
+ hasBtSaveMetadata: report.featureReport.hasBtSaveMetadata,
+ hasMoveStorage: report.featureReport.hasMoveStorage,
+ hasSqlitePersistence: report.featureReport.hasSqlitePersistence,
+ }
+ : null,
+ rpc: {
+ port: report.rpc.port,
+ available: report.rpc.available,
+ expectedListener: report.rpc.expectedListener,
+ connection: report.rpc.connection
+ ? {
+ transport: report.rpc.connection.transport,
+ connected: report.rpc.connection.connected,
+ }
+ : null,
+ },
+ process: processSnapshot(report.process),
+ defaultRpc: {
+ port: report.defaultRpc.port,
+ isCurrent: report.defaultRpc.isCurrent,
+ available: report.defaultRpc.available,
+ process: processSnapshot(report.defaultRpc.process),
+ canRestore: report.defaultRpc.canRestore,
+ requiresTermination: report.defaultRpc.requiresTermination,
+ },
+ failure: report.failure
+ ? {
+ reason: report.failure.reason,
+ occurredAt: new Date(report.failure.occurredAt).toISOString(),
+ technicalMessage: report.failure.technicalMessage
+ ? redactDiagnosticText(report.failure.technicalMessage)
+ : null,
+ }
+ : null,
+ recommendation: report.recommendation,
+ suggestedRpcPort: report.suggestedRpcPort,
+ canRetry: report.canRetry,
+ canForceTerminate: report.canForceTerminate,
+ canSwitchPort: report.canSwitchPort,
+ },
+ null,
+ 2
+ )
+}
diff --git a/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx b/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx
index 0e9d622d..98b1b670 100644
--- a/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx
+++ b/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx
@@ -11,7 +11,7 @@ import {
} from '@shared/types/engine'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { requestEngineDiagnostics } from './controller'
if (typeof globalThis.ResizeObserver === 'undefined') {
@@ -32,7 +32,7 @@ vi.mock('@renderer/lib/transport', () => ({
const REPORT = {
state: EngineState.Failed,
featureReport: {
- version: '1.37.0',
+ version: '1.37.0-motrix.14',
features: ['Async DNS', 'BitTorrent', 'SQLite3-Persistence'],
hasBtSeedUnverified: false,
hasBtSaveMetadata: false,
@@ -46,8 +46,13 @@ const REPORT = {
},
managedPid: null,
generatedAt: 1,
- binary: { name: 'aria2c', available: true, version: '1.37.0' },
- rpc: { port: 16800, available: false, expectedListener: false },
+ binary: { name: 'aria2c', available: true, version: '1.37.0-motrix.14' },
+ rpc: {
+ port: 16800,
+ available: false,
+ expectedListener: false,
+ connection: { transport: 'websocket', connected: false },
+ },
process: {
pid: 4321,
name: 'aria2c',
@@ -74,7 +79,24 @@ const { EngineDiagnosticsDialogHost } = await import(
'./engine-diagnostics-dialog'
)
+function holdClosingAnimation() {
+ const animation = Promise.withResolvers<void>()
+ const observed = vi.fn()
+ vi.spyOn(Element.prototype, 'getAnimations').mockImplementation(function (
+ this: Element
+ ) {
+ if (this.matches('[data-slot="dialog-content"][data-closed]')) {
+ observed()
+ return [{ finished: animation.promise }] as unknown as Animation[]
+ }
+ return []
+ })
+ return { finish: animation.resolve, observed }
+}
+
describe('EngineDiagnosticsDialogHost', () => {
+ afterEach(() => vi.restoreAllMocks())
+
beforeEach(() => {
invoke.mockReset()
invoke.mockImplementation((channel: string) => {
@@ -93,40 +115,38 @@ describe('EngineDiagnosticsDialogHost', () => {
})
})
- it('explains verified ownership before offering force recovery', async () => {
+ it('keeps the full engine build visible and normal checks collapsed', async () => {
+ const user = userEvent.setup()
render(<EngineDiagnosticsDialogHost />)
act(() => requestEngineDiagnostics())
expect(await screen.findByText('Engine diagnostics')).toBeVisible()
expect(
- await screen.findByText(
- 'Motrix’s RPC port is occupied, so aria2 engine could not start.'
- )
+ await screen.findByRole('heading', {
+ name: 'The engine’s control port is occupied',
+ })
).toBeVisible()
expect(
- await screen.findByText(/matches Motrix’s bundled binary/i)
- ).toBeVisible()
+ await screen.findByTestId('engine-version-summary')
+ ).toHaveTextContent('aria2 Motrix 1.37.0-motrix.14')
expect(
screen.getByRole('button', { name: 'Force stop & recover' })
).toBeVisible()
+ expect(
+ screen.queryByText('Async DNS, BitTorrent, SQLite3-Persistence')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: /Diagnostic details/ })
+ ).toHaveAttribute('aria-expanded', 'false')
+
+ await user.click(screen.getByRole('button', { name: /Diagnostic details/ }))
expect(
screen.getByText('Async DNS, BitTorrent, SQLite3-Persistence')
).toBeVisible()
- const recommendation = screen.getByText('Recommended recovery')
- const binaryCheck = screen.getByText('Bundled aria2')
expect(
- recommendation.compareDocumentPosition(binaryCheck) &
- Node.DOCUMENT_POSITION_FOLLOWING
- ).toBeTruthy()
- expect(screen.getByRole('dialog')).toHaveClass(
- 'h-[min(84vh,760px)]',
- 'grid-rows-[auto_minmax(0,1fr)_auto]',
- 'overflow-hidden'
- )
- expect(screen.getByTestId('engine-diagnostics-scroll')).toHaveAttribute(
- 'data-slot',
- 'scroll-area-viewport'
- )
+ screen.getByText(/Verified Motrix leftover; safe to stop/)
+ ).toBeVisible()
+ expect(screen.getByRole('dialog')).not.toHaveClass('h-[min(84vh,760px)]')
expect(
screen.queryByRole('button', {
name: 'Restore Motrix default port 16800',
@@ -138,13 +158,274 @@ describe('EngineDiagnosticsDialogHost', () => {
const user = userEvent.setup()
render(<EngineDiagnosticsDialogHost />)
act(() => requestEngineDiagnostics())
-
- await user.click(await screen.findByText('Technical details'))
-
+ await user.click(
+ await screen.findByRole('button', { name: /Diagnostic details/ })
+ )
expect(screen.getByText('RPC port 16800 is already in use')).toBeVisible()
expect(screen.getByTestId('engine-diagnostics-scroll')).toContainElement(
- screen.getByText('RPC port 16800 is already in use').closest('details')
+ screen.getByText('RPC port 16800 is already in use')
+ )
+ })
+
+ it.each([false, true])(
+ 'preserves closing content until the exit animation finishes (expanded: %s)',
+ async (expanded) => {
+ const user = userEvent.setup()
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ await screen.findByTestId('engine-version-summary')
+ if (expanded) {
+ await user.click(
+ screen.getByRole('button', { name: /Diagnostic details/ })
+ )
+ }
+ const dialog = screen.getByRole('dialog')
+ const content = dialog.textContent
+ const animation = holdClosingAnimation()
+
+ await user.click(screen.getByRole('button', { name: 'Close' }))
+ await waitFor(() => expect(animation.observed).toHaveBeenCalled())
+ expect(dialog).toBeInTheDocument()
+ expect(dialog.textContent).toBe(content)
+ expect(
+ screen.queryByText('Running engine checks…')
+ ).not.toBeInTheDocument()
+
+ await act(async () => animation.finish())
+ await waitFor(() => expect(dialog).not.toBeInTheDocument())
+ const nextReport = Promise.withResolvers<typeof REPORT>()
+ invoke.mockReturnValueOnce(nextReport.promise)
+ act(() => requestEngineDiagnostics())
+ expect(await screen.findByText('Running engine checks…')).toBeVisible()
+ await act(async () => nextReport.resolve(REPORT))
+ expect(
+ screen.getByRole('button', { name: /Diagnostic details/ })
+ ).toHaveAttribute('aria-expanded', 'false')
+ }
+ )
+
+ it('ignores late requests while closing and keeps a rapid reopen intact', async () => {
+ const user = userEvent.setup()
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ await screen.findByTestId('engine-version-summary')
+ const refresh = Promise.withResolvers<typeof REPORT>()
+ invoke.mockReturnValueOnce(refresh.promise)
+ await user.click(screen.getByRole('button', { name: 'Run again' }))
+ const dialog = screen.getByRole('dialog')
+ const content = dialog.textContent
+ const animation = holdClosingAnimation()
+ await user.click(screen.getByRole('button', { name: 'Close' }))
+ await waitFor(() => expect(animation.observed).toHaveBeenCalled())
+
+ await act(async () =>
+ refresh.resolve({
+ ...REPORT,
+ binary: { ...REPORT.binary, version: 'late-result' },
+ })
+ )
+ expect(dialog.textContent).toBe(content)
+
+ invoke.mockResolvedValueOnce({
+ ...REPORT,
+ binary: { ...REPORT.binary, version: '1.37.0-motrix.15' },
+ })
+ act(() => requestEngineDiagnostics())
+ await waitFor(() =>
+ expect(screen.getByTestId('engine-version-summary')).toHaveTextContent(
+ '1.37.0-motrix.15'
+ )
+ )
+ await act(async () => animation.finish())
+ expect(screen.getByTestId('engine-version-summary')).toHaveTextContent(
+ '1.37.0-motrix.15'
)
+ expect(screen.getByRole('dialog')).toBeVisible()
+ })
+
+ it('copies the complete report while details are collapsed', async () => {
+ const user = userEvent.setup()
+ const writeText = vi
+ .spyOn(navigator.clipboard, 'writeText')
+ .mockResolvedValue()
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ await screen.findByTestId('engine-version-summary')
+ const copy = screen.getByRole('button', { name: 'Copy diagnostics' })
+ await waitFor(() => expect(copy).toBeEnabled())
+ await user.click(copy)
+ expect(await screen.findByRole('button', { name: 'Copied' })).toBeVisible()
+ const copied = JSON.parse(writeText.mock.calls[0][0])
+ expect(copied.binary.version).toBe('1.37.0-motrix.14')
+ expect(copied.featureReport.features).toContain('SQLite3-Persistence')
+ expect(copied.process.pid).toBe(4321)
+ expect(copied.rpc.connection).toEqual({
+ transport: 'websocket',
+ connected: false,
+ })
+ expect(copied.defaultRpc.port).toBe(16800)
+ expect(copied.failure.technicalMessage).toBe(
+ 'RPC port 16800 is already in use'
+ )
+ expect(
+ screen.getByRole('button', { name: /Diagnostic details/ })
+ ).toHaveAttribute('aria-expanded', 'false')
+ writeText.mockRestore()
+ })
+
+ it('does not show copied feedback when the clipboard fails', async () => {
+ const user = userEvent.setup()
+ const writeText = vi
+ .spyOn(navigator.clipboard, 'writeText')
+ .mockRejectedValue(new Error('Denied'))
+ const { toast } = await import('@renderer/components/ui/toast')
+ const addToast = vi.spyOn(toast, 'add')
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ await screen.findByTestId('engine-version-summary')
+ const copy = screen.getByRole('button', { name: 'Copy diagnostics' })
+ await waitFor(() => expect(copy).toBeEnabled())
+ await user.click(copy)
+ await waitFor(() =>
+ expect(addToast).toHaveBeenCalledWith({
+ title: 'Could not copy diagnostics. Please try again.',
+ type: 'error',
+ })
+ )
+ expect(
+ screen.queryByRole('button', { name: 'Copied' })
+ ).not.toBeInTheDocument()
+ writeText.mockRestore()
+ addToast.mockRestore()
+ })
+
+ it('does not substitute a cached or pinned version when the binary probe fails', async () => {
+ invoke.mockResolvedValue({
+ ...REPORT,
+ binary: { name: 'aria2c', available: false, version: null },
+ })
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ expect(
+ await screen.findByTestId('engine-version-summary')
+ ).toHaveTextContent('aria2c Version unavailable')
+ expect(screen.getByTestId('engine-version-summary')).not.toHaveTextContent(
+ '1.37.0'
+ )
+ })
+
+ it.each([
+ EngineState.Starting,
+ EngineState.Restarting,
+ EngineState.Stopped,
+ EngineState.Ready,
+ ])('uses the current %s state instead of a stale failure', async (state) => {
+ invoke.mockResolvedValue({
+ ...REPORT,
+ state,
+ rpc: {
+ ...REPORT.rpc,
+ connection: {
+ transport: 'websocket',
+ connected: state === EngineState.Ready,
+ },
+ },
+ canForceTerminate: false,
+ canRetry: false,
+ recommendation: EngineRecoveryRecommendation.None,
+ })
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ await screen.findByTestId('engine-version-summary')
+ expect(
+ screen.queryByText('The engine’s control port is occupied')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByText(
+ 'Download controls are unavailable. Task status may be out of date.'
+ )
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'Force stop & recover' })
+ ).not.toBeInTheDocument()
+ })
+
+ it.each([
+ [true, 'WebSocket (Connected)'],
+ [false, 'WebSocket (Not connected)'],
+ ])(
+ 'shows the actual transport when connected is %s',
+ async (connected, label) => {
+ const user = userEvent.setup()
+ invoke.mockResolvedValue({
+ ...REPORT,
+ state: EngineState.Ready,
+ failure: null,
+ rpc: {
+ ...REPORT.rpc,
+ expectedListener: true,
+ connection: { transport: 'websocket', connected },
+ },
+ recommendation: EngineRecoveryRecommendation.None,
+ canForceTerminate: false,
+ })
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ expect(await screen.findByText(label)).toBeVisible()
+ await user.click(
+ screen.getByRole('button', { name: /Diagnostic details/ })
+ )
+ expect(screen.getAllByText(label)).toHaveLength(2)
+ if (!connected) {
+ expect(
+ screen.queryByText('The download engine is running normally')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByText('The engine’s control connection is unavailable')
+ ).toBeVisible()
+ }
+ }
+ )
+
+ it('does not guess a transport for reports from an older backend', async () => {
+ invoke.mockResolvedValue({
+ ...REPORT,
+ state: EngineState.Ready,
+ rpc: { ...REPORT.rpc, connection: undefined },
+ })
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ expect(await screen.findByText('Connected')).toBeVisible()
+ expect(screen.queryByText(/WebSocket/)).not.toBeInTheDocument()
+ })
+
+ it('keeps an initial load failure actionable without an empty diagnostics screen', async () => {
+ invoke.mockRejectedValue(new Error('Offline'))
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Could not run engine diagnostics.'
+ )
+ expect(
+ screen.getByRole('button', { name: 'Copy diagnostics' })
+ ).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Run again' })).toBeEnabled()
+ })
+
+ it('marks the retained report stale and disables recovery after a refresh failure', async () => {
+ const user = userEvent.setup()
+ render(<EngineDiagnosticsDialogHost />)
+ act(() => requestEngineDiagnostics())
+ await screen.findByTestId('engine-version-summary')
+ invoke.mockRejectedValueOnce(new Error('Offline'))
+ await user.click(screen.getByRole('button', { name: 'Run again' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'The last successful report is shown below.'
+ )
+ expect(
+ screen.getByRole('button', { name: 'Force stop & recover' })
+ ).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Run again' })).toBeEnabled()
})
it('revalidates and submits the displayed pid after confirmation', async () => {
@@ -158,6 +439,7 @@ describe('EngineDiagnosticsDialogHost', () => {
expect(
await screen.findByText('Force stop the leftover aria2 process?')
).toBeVisible()
+ expect(screen.getByText(/matches Motrix’s bundled binary/i)).toBeVisible()
const actions = screen.getAllByRole('button', {
name: 'Force stop & recover',
})
diff --git a/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.tsx b/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.tsx
index 36714a39..4d4edb84 100644
--- a/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.tsx
+++ b/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.tsx
@@ -1,3 +1,4 @@
+import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
import {
AlertDialog,
AlertDialogAction,
@@ -8,8 +9,12 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from '@renderer/components/ui/alert-dialog'
-import { Badge } from '@renderer/components/ui/badge'
import { Button, buttonVariants } from '@renderer/components/ui/button'
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@renderer/components/ui/collapsible'
import {
Dialog,
DialogClose,
@@ -36,61 +41,69 @@ import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
+import { EngineConnectionSchema } from '@shared/schemas/engine-connection'
import {
type EngineDiagnosticReport,
EngineProcessOwnership,
EngineRecoveryAction,
+ EngineRecoveryRecommendation,
type EngineRecoveryResult,
EngineState,
} from '@shared/types/engine'
import {
- AlertTriangle,
CheckCircle2,
+ ChevronRight,
CircleX,
+ FileText,
LoaderCircle,
- RefreshCw,
RotateCcw,
- ShieldCheck,
+ X,
} from 'lucide-react'
-import { type ReactNode, useCallback, useEffect, useState } from 'react'
+import { type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
consumeEngineDiagnosticsRequest,
ENGINE_FAILURE_TOAST_ID,
subscribeEngineDiagnostics,
} from './controller'
+import { formatEngineDiagnostics } from './diagnostic-report'
+
+const key = 'panel.dashboard.engine.diagnostics'
+
+type CheckState = 'pass' | 'warn' | 'fail' | 'neutral'
-interface CheckRowProps {
+function CheckRow({
+ label,
+ value,
+ state = 'neutral',
+ action,
+ testId,
+}: {
label: string
value: string
- state: 'pass' | 'warn' | 'fail'
+ state?: CheckState
action?: ReactNode
testId?: string
-}
-
-function CheckRow({ label, value, state, action, testId }: CheckRowProps) {
- const Icon =
- state === 'pass' ? CheckCircle2 : state === 'warn' ? AlertTriangle : CircleX
+}) {
return (
<div
data-testid={testId}
- className="flex items-start gap-3 rounded-md border border-border/70 px-3 py-2.5"
+ className="grid grid-cols-[6rem_minmax(0,1fr)] items-baseline gap-x-4 gap-y-1 py-1.5 text-xs leading-5"
>
- <Icon
- className={cn(
- 'mt-0.5 size-4 shrink-0',
- state === 'pass' && 'text-emerald-500',
- state === 'warn' && 'text-amber-500',
- state === 'fail' && 'text-destructive'
- )}
- />
- <div className="min-w-0 flex-1">
- <div className="flex min-w-0 items-start justify-between gap-2">
- <div className="min-w-0 text-sm font-medium">{label}</div>
- {action && <div className="-mt-1 shrink-0">{action}</div>}
- </div>
- <div className="mt-0.5 text-xs text-muted-foreground">{value}</div>
- </div>
+ <dt className="whitespace-nowrap text-muted-foreground">{label}</dt>
+ <dd className="flex min-w-0 items-start justify-between gap-2">
+ <span
+ className={cn(
+ 'min-w-0 break-words',
+ state === 'pass' && 'text-muted-foreground',
+ state === 'warn' && 'text-amber-600 dark:text-amber-400',
+ state === 'fail' && 'text-destructive'
+ )}
+ >
+ {value}
+ </span>
+ {action}
+ </dd>
</div>
)
}
@@ -99,17 +112,29 @@ function processDescription(
report: EngineDiagnosticReport,
t: ReturnType<typeof useTranslation>['t']
): string {
- if (report.rpc.available) {
- return t('panel.dashboard.engine.diagnostics.process.none')
- }
- const processInfo = report.process
- if (!processInfo) {
- return t('panel.dashboard.engine.diagnostics.process.unidentified')
- }
- return t(
- `panel.dashboard.engine.diagnostics.process.${processInfo.ownership}`,
- { pid: processInfo.pid, name: processInfo.name }
+ if (report.rpc.available) return t(`${key}.process.none`)
+ if (!report.process) return t(`${key}.process.unidentified`)
+ return t(`${key}.process.${report.process.ownership}`, {
+ pid: report.process.pid,
+ name: report.process.name,
+ })
+}
+
+function recoveryAction(
+ report: EngineDiagnosticReport | null
+): EngineRecoveryAction | null {
+ if (
+ !report ||
+ report.state === EngineState.Starting ||
+ report.state === EngineState.Restarting
)
+ return null
+ if (report.canForceTerminate) return EngineRecoveryAction.ForceTerminate
+ if (report.canSwitchPort && report.suggestedRpcPort)
+ return EngineRecoveryAction.SwitchPort
+ if (report.canRetry || report.state === EngineState.Ready)
+ return EngineRecoveryAction.Retry
+ return null
}
export function EngineDiagnosticsDialogHost() {
@@ -117,34 +142,41 @@ export function EngineDiagnosticsDialogHost() {
const [open, setOpen] = useState(() => consumeEngineDiagnosticsRequest())
const [report, setReport] = useState<EngineDiagnosticReport | null>(null)
const [loading, setLoading] = useState(false)
+ const [loadFailed, setLoadFailed] = useState(false)
const [recovering, setRecovering] = useState(false)
+ const [detailsOpen, setDetailsOpen] = useState(false)
const [confirmForce, setConfirmForce] = useState(false)
const [confirmRestoreDefault, setConfirmRestoreDefault] = useState(false)
+ const requestId = useRef(0)
const load = useCallback(async () => {
+ const current = ++requestId.current
setLoading(true)
+ setLoadFailed(false)
try {
const next = (await transport.invoke(
Queries.GetEngineDiagnostics
)) as EngineDiagnosticReport
- setReport(next)
+ if (current === requestId.current) setReport(next)
} catch {
- toast.add({
- title: t('panel.dashboard.engine.diagnostics.loadFailed'),
- type: 'error',
- })
+ if (current === requestId.current) {
+ setLoadFailed(true)
+ toast.add({ title: t(`${key}.loadFailed`), type: 'error' })
+ }
} finally {
- setLoading(false)
+ if (current === requestId.current) setLoading(false)
}
}, [t])
useEffect(() => subscribeEngineDiagnostics(() => setOpen(true)), [])
-
useEffect(() => {
if (open) {
toast.close(ENGINE_FAILURE_TOAST_ID)
void load()
}
+ return () => {
+ requestId.current++
+ }
}, [load, open])
const recover = async (action: EngineRecoveryAction) => {
@@ -159,385 +191,463 @@ export function EngineDiagnosticsDialogHost() {
? { expectedPid: report.defaultRpc.process.pid }
: {}),
})) as EngineRecoveryResult
- if (result.ok) {
- toast.add({
- title:
- action === EngineRecoveryAction.RestoreDefaultPort
- ? t(
- 'panel.dashboard.engine.diagnostics.fallback.restoredDefault',
- { port: result.rpcPort }
- )
- : action === EngineRecoveryAction.SwitchPort
- ? t('panel.dashboard.engine.diagnostics.recoveredOnPort', {
- port: result.rpcPort,
- })
- : t('panel.dashboard.engine.diagnostics.recovered'),
- type: 'success',
- })
- } else {
- toast.add({
- title: t('panel.dashboard.engine.diagnostics.recoveryFailed'),
- type: 'error',
- })
- }
- await load()
- } catch {
toast.add({
- title: t('panel.dashboard.engine.diagnostics.recoveryFailed'),
- type: 'error',
+ title: result.ok
+ ? action === EngineRecoveryAction.RestoreDefaultPort
+ ? t(`${key}.fallback.restoredDefault`, { port: result.rpcPort })
+ : action === EngineRecoveryAction.SwitchPort
+ ? t(`${key}.recoveredOnPort`, { port: result.rpcPort })
+ : t(`${key}.recovered`)
+ : t(`${key}.recoveryFailed`),
+ type: result.ok ? 'success' : 'error',
})
- await load()
+ } catch {
+ toast.add({ title: t(`${key}.recoveryFailed`), type: 'error' })
} finally {
+ await load()
setRecovering(false)
setConfirmForce(false)
setConfirmRestoreDefault(false)
}
}
- const processState: CheckRowProps['state'] = report?.rpc.available
- ? 'pass'
- : report?.process?.ownership === EngineProcessOwnership.CurrentApp
+ const busy = loading || recovering
+ const ready = report?.state === EngineState.Ready
+ const connectionResult = EngineConnectionSchema.safeParse(
+ report?.rpc.connection
+ )
+ const rpcConnection = connectionResult.success ? connectionResult.data : null
+ const connectionLost = ready && rpcConnection?.connected === false
+ const healthy = ready && !connectionLost
+ const transitioning =
+ report?.state === EngineState.Starting ||
+ report?.state === EngineState.Restarting
+ const action = recoveryAction(report)
+ const reason = report?.failure?.reason ?? 'unknown'
+ const summary = connectionLost
+ ? 'rpc_unavailable'
+ : report?.state === EngineState.Failed
+ ? reason
+ : (report?.state ?? 'unknown')
+ const engineFeatures = report?.featureReport?.features ?? []
+ const processState: CheckState =
+ report?.rpc.available ||
+ report?.process?.ownership === EngineProcessOwnership.CurrentApp
? 'pass'
: report?.process?.safeToTerminate
? 'warn'
: 'fail'
- const engineFeatures = report?.featureReport?.features ?? []
-
- const defaultPortTooltip = report
- ? recovering
- ? t('panel.dashboard.engine.diagnostics.fallback.restoring', {
- port: report.defaultRpc.port,
- })
+ const connection = connectionLost
+ ? 'disconnected'
+ : ready
+ ? 'connected'
+ : transitioning
+ ? 'connecting'
+ : report?.state === EngineState.Stopped
+ ? 'disconnected'
+ : 'unavailable'
+ const connectionValue = rpcConnection
+ ? t(`${key}.runtime.connectionStatus`, {
+ transport: t(`${key}.transport.${rpcConnection.transport}`),
+ status: t(`${key}.runtime.${connection}`),
+ })
+ : t(`${key}.runtime.${connection}`)
+ const StatusIcon = healthy
+ ? CheckCircle2
+ : transitioning
+ ? LoaderCircle
+ : CircleX
+ const version = report?.binary.version
+ const engineName = version?.includes('-motrix.')
+ ? t(`${key}.motrixEngine`)
+ : report?.binary.name
+ const actionLabel =
+ action === EngineRecoveryAction.ForceTerminate
+ ? t(`${key}.forceRecover`)
+ : action === EngineRecoveryAction.SwitchPort
+ ? t(`${key}.switchPort`, { port: report?.suggestedRpcPort })
+ : t(`${key}.${ready ? 'restart' : 'retry'}`)
+ const defaultPortTooltip = !report
+ ? ''
+ : recovering
+ ? t(`${key}.fallback.restoring`, { port: report.defaultRpc.port })
: report.defaultRpc.available
- ? t('panel.dashboard.engine.diagnostics.fallback.available', {
- port: report.defaultRpc.port,
- })
+ ? t(`${key}.fallback.available`, { port: report.defaultRpc.port })
: report.defaultRpc.requiresTermination
- ? t('panel.dashboard.engine.diagnostics.fallback.verifiedOrphan', {
+ ? t(`${key}.fallback.verifiedOrphan`, {
port: report.defaultRpc.port,
pid: report.defaultRpc.process?.pid ?? '',
})
: report.defaultRpc.process
- ? t('panel.dashboard.engine.diagnostics.fallback.blocked', {
+ ? t(`${key}.fallback.blocked`, {
port: report.defaultRpc.port,
pid: report.defaultRpc.process.pid,
name: report.defaultRpc.process.name,
})
- : t('panel.dashboard.engine.diagnostics.fallback.unidentified', {
+ : t(`${key}.fallback.unidentified`, {
port: report.defaultRpc.port,
})
- : ''
+ const restoreDefault =
+ report && !report.defaultRpc.isCurrent ? (
+ <TooltipProvider delay={300}>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className="inline-flex shrink-0"
+ tabIndex={
+ busy || loadFailed || !report.defaultRpc.canRestore
+ ? 0
+ : undefined
+ }
+ >
+ <Button
+ variant="outline"
+ size="icon-xs"
+ aria-label={t(`${key}.fallback.restore`, {
+ port: report.defaultRpc.port,
+ })}
+ disabled={busy || loadFailed || !report.defaultRpc.canRestore}
+ onClick={() =>
+ report.defaultRpc.requiresTermination
+ ? setConfirmRestoreDefault(true)
+ : void recover(EngineRecoveryAction.RestoreDefaultPort)
+ }
+ >
+ <RotateCcw aria-hidden="true" />
+ </Button>
+ </span>
+ }
+ />
+ <TooltipContent side="left" className="max-w-80">
+ {defaultPortTooltip}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : undefined
return (
<>
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent className="h-[min(84vh,760px)] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden p-0 sm:max-w-2xl">
- <DialogHeader className="px-5 pt-5">
- <DialogTitle className="flex items-center gap-2">
- {t('panel.dashboard.engine.diagnostics.title')}
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (recovering) return
+ if (!next) requestId.current++
+ setOpen(next)
+ }}
+ onOpenChangeComplete={(next) => {
+ if (next || open) return
+ // Keep the closing content intact until the popup is unmounted.
+ setReport(null)
+ setDetailsOpen(false)
+ setLoadFailed(false)
+ setLoading(false)
+ }}
+ >
+ <DialogContent
+ showCloseButton={false}
+ className="max-h-[min(85dvh,720px)] grid-rows-[auto_minmax(0,1fr)_auto] gap-0 overflow-hidden p-0 sm:max-w-[560px]"
+ >
+ <DialogHeader className="flex-row items-center justify-between gap-3 px-5 pt-4 pb-3">
+ <DialogTitle className="shrink-0 text-sm">
+ {t(`${key}.title`)}
</DialogTitle>
- <DialogDescription>
- {t('panel.dashboard.engine.diagnostics.description')}
+ <DialogDescription className="sr-only">
+ {t(`${key}.description`)}
</DialogDescription>
+ <div className="flex min-w-0 items-center gap-2">
+ {report && (
+ <span className="truncate text-xs tabular-nums text-muted-foreground">
+ {t(`${key}.lastChecked`, {
+ time: new Date(report.generatedAt).toLocaleTimeString(),
+ })}
+ </span>
+ )}
+ <DialogClose
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={recovering}
+ aria-label={t('common.close')}
+ />
+ }
+ >
+ <X aria-hidden="true" />
+ </DialogClose>
+ </div>
</DialogHeader>
-
- <ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <ScrollArea className="flex min-h-0 flex-col">
<ScrollAreaViewport
data-testid="engine-diagnostics-scroll"
tabIndex={-1}
className="min-h-0 flex-1 overscroll-contain"
>
- <ScrollAreaContent
- className="space-y-4 px-5 pb-1"
- style={{ minWidth: '100%' }}
- >
- {loading && !report ? (
- <div className="flex items-center justify-center gap-2 py-12 text-sm text-muted-foreground">
- <LoaderCircle className="size-4 animate-spin" />
- {t('panel.dashboard.engine.diagnostics.checking')}
+ <ScrollAreaContent className="px-5" style={{ minWidth: '100%' }}>
+ {loadFailed && (
+ <p
+ role="alert"
+ className="pb-4 text-xs leading-5 text-destructive"
+ >
+ {t(`${key}.${report ? 'refreshFailed' : 'loadFailed'}`)}
+ </p>
+ )}
+ {!report && !loadFailed && (
+ <div
+ role="status"
+ className="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground"
+ >
+ <LoaderCircle
+ aria-hidden="true"
+ className="size-4 animate-spin"
+ />
+ {t(`${key}.checking`)}
</div>
- ) : report ? (
+ )}
+ {report && (
<>
- <div className="flex items-center justify-between gap-3">
- <div>
- <div className="text-sm font-medium">
- {t(
- 'panel.dashboard.engine.diagnostics.currentStatus'
- )}
- </div>
- <div className="mt-0.5 text-xs text-muted-foreground">
- {t('panel.dashboard.engine.diagnostics.lastChecked', {
- time: new Date(
- report.generatedAt
- ).toLocaleTimeString(),
- })}
- </div>
- </div>
- <Badge
- variant={
- report.state === EngineState.Ready
- ? 'secondary'
- : 'destructive'
- }
- >
- {t(
- `panel.dashboard.engine.state.${
- report.state === EngineState.Restarting
- ? 'reconnecting'
- : report.state
- }`
+ <div
+ className="flex items-start gap-3 pt-1 pb-4"
+ aria-live="polite"
+ >
+ <StatusIcon
+ aria-hidden="true"
+ className={cn(
+ 'mt-0.5 size-5 shrink-0',
+ healthy
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : report.state === EngineState.Failed ||
+ connectionLost
+ ? 'text-destructive'
+ : 'text-muted-foreground',
+ transitioning && 'animate-spin'
)}
- </Badge>
- </div>
-
- {report.recommendation !== 'none' && (
- <div className="flex gap-3 rounded-md bg-muted/60 p-3">
- <ShieldCheck className="mt-0.5 size-4 shrink-0 text-primary" />
- <div>
- <div className="text-sm font-medium">
- {t(
- 'panel.dashboard.engine.diagnostics.recommendation.title'
- )}
- </div>
- <div className="mt-0.5 text-xs text-muted-foreground">
- {t(
- `panel.dashboard.engine.diagnostics.recommendation.${report.recommendation}`,
- {
- port: report.suggestedRpcPort ?? '',
- rpcPort: report.rpc.port,
- pid: report.process?.pid ?? '',
- }
- )}
- </div>
- </div>
+ />
+ <div className="min-w-0 space-y-1">
+ <h2 className="text-sm font-medium leading-5">
+ {t(`${key}.summary.${summary}`)}
+ </h2>
+ <p className="text-xs leading-5 text-muted-foreground">
+ {healthy
+ ? t(`${key}.communication.ready`)
+ : t(
+ `${key}.impact.${transitioning ? 'connecting' : report.state === EngineState.Stopped ? 'stopped' : 'failed'}`
+ )}
+ </p>
</div>
- )}
-
- <div className="grid gap-2">
+ </div>
+ <dl className="rounded-md bg-muted/50 px-3 py-1.5">
<CheckRow
- label={t(
- 'panel.dashboard.engine.diagnostics.checks.binary'
- )}
+ label={t(`${key}.runtime.process`)}
value={
- report.binary.available
- ? t(
- 'panel.dashboard.engine.diagnostics.binary.available',
- {
- name: report.binary.name,
- version: report.binary.version ?? '?',
- }
- )
- : t(
- 'panel.dashboard.engine.diagnostics.binary.unavailable',
- { name: report.binary.name }
- )
+ report.managedPid !== null
+ ? t(`${key}.runtime.running`, {
+ pid: report.managedPid,
+ })
+ : t(`${key}.runtime.notRunning`)
}
- state={report.binary.available ? 'pass' : 'fail'}
/>
<CheckRow
- label={t(
- 'panel.dashboard.engine.diagnostics.checks.features'
- )}
- value={
- engineFeatures.length > 0
- ? engineFeatures.join(', ')
- : report.binary.available
- ? t(
- 'panel.dashboard.engine.diagnostics.features.none'
- )
- : t(
- 'panel.dashboard.engine.diagnostics.features.unavailable'
- )
- }
+ label={t(`${key}.runtime.connection`)}
+ value={connectionValue}
state={
- !report.binary.available
+ report.state === EngineState.Failed || connectionLost
? 'fail'
- : engineFeatures.length > 0
- ? 'pass'
- : 'warn'
+ : 'neutral'
}
/>
- <CheckRow
- testId="engine-check-rpc"
- label={t(
- 'panel.dashboard.engine.diagnostics.checks.rpc'
- )}
- value={
- report.rpc.expectedListener
- ? t(
- 'panel.dashboard.engine.diagnostics.rpc.listening',
+ {((!report.rpc.available &&
+ !report.rpc.expectedListener) ||
+ !report.defaultRpc.isCurrent) && (
+ <CheckRow
+ testId="engine-check-rpc"
+ label={t('panel.dashboard.engine.rpcPort')}
+ value={t(
+ `${key}.port.${report.rpc.expectedListener ? 'listening' : report.rpc.available ? 'available' : 'occupied'}`,
+ { port: report.rpc.port }
+ )}
+ state={
+ report.rpc.expectedListener || report.rpc.available
+ ? 'neutral'
+ : 'fail'
+ }
+ action={restoreDefault}
+ />
+ )}
+ </dl>
+ {!transitioning &&
+ report.recommendation !==
+ EngineRecoveryRecommendation.None && (
+ <p className="pt-3 text-xs leading-5 text-muted-foreground">
+ {t(`${key}.recommendation.${report.recommendation}`, {
+ port: report.suggestedRpcPort ?? '',
+ rpcPort: report.rpc.port,
+ pid: report.process?.pid ?? '',
+ })}
+ </p>
+ )}
+ <Collapsible
+ open={detailsOpen}
+ onOpenChange={setDetailsOpen}
+ className="mt-3 mb-2"
+ >
+ <CollapsibleTrigger className="group -mx-3 flex min-h-12 w-[calc(100%+1.5rem)] items-center gap-3 rounded-lg px-3 py-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <FileText
+ aria-hidden="true"
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-0.5">
+ <span className="text-sm">{t(`${key}.details`)}</span>
+ <span
+ className="text-xs text-muted-foreground"
+ data-testid="engine-version-summary"
+ >
+ {engineName} {version ?? t(`${key}.versionUnknown`)}
+ </span>
+ </span>
+ <ChevronRight
+ aria-hidden="true"
+ className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 group-data-panel-open:rotate-90 motion-reduce:transition-none"
+ />
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="border-t pb-4 pt-2">
+ <dl className="divide-y divide-border/50">
+ <CheckRow
+ label={t(`${key}.checks.binary`)}
+ value={
+ report.binary.available
+ ? t(`${key}.binary.available`, {
+ name: report.binary.name,
+ version:
+ version ?? t(`${key}.versionUnknown`),
+ })
+ : t(`${key}.binary.unavailable`, {
+ name: report.binary.name,
+ })
+ }
+ state={report.binary.available ? 'pass' : 'fail'}
+ />
+ <CheckRow
+ label={t(`${key}.checks.features`)}
+ value={
+ engineFeatures.length
+ ? engineFeatures.join(', ')
+ : t(
+ `${key}.features.${report.binary.available ? 'none' : 'unavailable'}`
+ )
+ }
+ state={
+ !report.binary.available
+ ? 'neutral'
+ : engineFeatures.length
+ ? 'pass'
+ : 'warn'
+ }
+ />
+ <CheckRow
+ label={t(`${key}.checks.rpc`)}
+ value={t(
+ `${key}.rpc.${report.rpc.expectedListener ? 'listening' : report.rpc.available ? 'available' : 'occupied'}`,
{ port: report.rpc.port }
- )
- : report.rpc.available
- ? t(
- 'panel.dashboard.engine.diagnostics.rpc.available',
- { port: report.rpc.port }
- )
- : t(
- 'panel.dashboard.engine.diagnostics.rpc.occupied',
- { port: report.rpc.port }
- )
- }
- state={
- report.rpc.available || report.rpc.expectedListener
- ? 'pass'
- : 'fail'
- }
- action={
- !report.defaultRpc.isCurrent ? (
- <TooltipProvider delay={300}>
- <Tooltip>
- <TooltipTrigger
- render={
- <span
- className="inline-flex"
- tabIndex={
- recovering ||
- !report.defaultRpc.canRestore
- ? 0
- : undefined
- }
- >
- <Button
- variant="outline"
- size="icon-xs"
- aria-label={t(
- 'panel.dashboard.engine.diagnostics.fallback.restore',
- { port: report.defaultRpc.port }
- )}
- disabled={
- recovering ||
- !report.defaultRpc.canRestore
- }
- onClick={() => {
- if (
- report.defaultRpc
- .requiresTermination
- ) {
- setConfirmRestoreDefault(true)
- } else {
- void recover(
- EngineRecoveryAction.RestoreDefaultPort
- )
- }
- }}
- >
- {recovering ? (
- <LoaderCircle className="animate-spin" />
- ) : (
- <RotateCcw />
- )}
- </Button>
- </span>
- }
- />
- <TooltipContent
- side="left"
- className="max-w-80"
- >
- {defaultPortTooltip}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : undefined
- }
- />
- <CheckRow
- label={t(
- 'panel.dashboard.engine.diagnostics.checks.process'
- )}
- value={processDescription(report, t)}
- state={processState}
- />
- <CheckRow
- label={t(
- 'panel.dashboard.engine.diagnostics.checks.communication'
- )}
- value={
- report.state === EngineState.Ready
- ? t(
- 'panel.dashboard.engine.diagnostics.communication.ready'
- )
- : t(
- `panel.dashboard.engine.diagnostics.reason.${report.failure?.reason ?? 'unknown'}`
- )
- }
- state={
- report.state === EngineState.Ready ? 'pass' : 'fail'
- }
- />
- </div>
-
- {report.failure?.technicalMessage && (
- <details className="text-xs text-muted-foreground">
- <summary className="cursor-pointer select-none">
- {t(
- 'panel.dashboard.engine.diagnostics.technicalDetails'
+ )}
+ state={
+ report.rpc.available ||
+ report.rpc.expectedListener
+ ? 'pass'
+ : 'fail'
+ }
+ />
+ <CheckRow
+ label={t(`${key}.checks.process`)}
+ value={processDescription(report, t)}
+ state={processState}
+ />
+ <CheckRow
+ label={t(`${key}.checks.communication`)}
+ value={connectionValue}
+ state={
+ healthy
+ ? 'pass'
+ : report.state === EngineState.Failed ||
+ connectionLost
+ ? 'fail'
+ : 'neutral'
+ }
+ />
+ </dl>
+ {report.failure?.technicalMessage && (
+ <div className="mt-3 space-y-1.5">
+ <p className="text-xs text-muted-foreground">
+ {t(`${key}.technicalDetails`)}
+ </p>
+ <pre className="max-w-full whitespace-pre-wrap break-all rounded-md bg-muted/60 p-2.5 font-mono text-xs leading-5">
+ {report.failure.technicalMessage}
+ </pre>
+ </div>
)}
- </summary>
- <code className="mt-2 block break-all rounded bg-muted p-2">
- {report.failure.technicalMessage}
- </code>
- </details>
- )}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
</>
- ) : null}
+ )}
</ScrollAreaContent>
</ScrollAreaViewport>
<ScrollBar />
</ScrollArea>
-
- <DialogFooter className="border-t px-5 py-4">
- <DialogClose
- render={
- <Button variant="outline" size="sm" disabled={recovering} />
- }
- >
- {t('common.close')}
- </DialogClose>
- <Button
- variant="outline"
+ <DialogFooter className="flex-row flex-wrap items-center justify-between gap-2 border-t px-5 py-3 sm:justify-between">
+ <CopyButton
+ key={report?.generatedAt ?? 'empty'}
+ variant="ghost"
size="sm"
- disabled={loading || recovering}
- onClick={load}
+ className="-ml-2 text-xs text-muted-foreground"
+ disabled={!report || busy}
+ content={report ? formatEngineDiagnostics(report) : ''}
+ copiedLabel={t(`${key}.copied`)}
+ onCopyError={() =>
+ toast.add({ title: t(`${key}.copyFailed`), type: 'error' })
+ }
>
- <RefreshCw className={cn(loading && 'animate-spin')} />
- {t('panel.dashboard.engine.diagnostics.runAgain')}
- </Button>
- {report?.canSwitchPort && report.suggestedRpcPort && (
+ {t(`${key}.copy`)}
+ </CopyButton>
+ <div className="ml-auto flex flex-wrap justify-end gap-2">
<Button
variant="outline"
size="sm"
- disabled={recovering}
- onClick={() => recover(EngineRecoveryAction.SwitchPort)}
- >
- {t('panel.dashboard.engine.diagnostics.switchPort', {
- port: report.suggestedRpcPort,
- })}
- </Button>
- )}
- {(report?.canRetry || report?.state === EngineState.Ready) && (
- <Button
- size="sm"
- disabled={recovering}
- onClick={() => recover(EngineRecoveryAction.Retry)}
+ className="text-xs"
+ disabled={busy}
+ onClick={load}
>
- {recovering && <LoaderCircle className="animate-spin" />}
- {report.state === EngineState.Ready
- ? t('panel.dashboard.engine.diagnostics.restart')
- : t('panel.dashboard.engine.diagnostics.retry')}
+ {loading && (
+ <LoaderCircle aria-hidden="true" className="animate-spin" />
+ )}
+ {t(`${key}.runAgain`)}
</Button>
- )}
- {report?.canForceTerminate && (
- <Button
- variant="destructive"
- size="sm"
- disabled={recovering}
- onClick={() => setConfirmForce(true)}
- >
- {t('panel.dashboard.engine.diagnostics.forceRecover')}
- </Button>
- )}
+ {action && (
+ <Button
+ size="sm"
+ className="text-xs"
+ variant={
+ action === EngineRecoveryAction.ForceTerminate
+ ? 'destructive'
+ : ready
+ ? 'outline'
+ : 'default'
+ }
+ disabled={busy || loadFailed}
+ onClick={() =>
+ action === EngineRecoveryAction.ForceTerminate
+ ? setConfirmForce(true)
+ : void recover(action)
+ }
+ >
+ {recovering && (
+ <LoaderCircle aria-hidden="true" className="animate-spin" />
+ )}
+ {actionLabel}
+ </Button>
+ )}
+ </div>
</DialogFooter>
</DialogContent>
</Dialog>
diff --git a/src/renderer/features/nat/nat-status-menu.tsx b/src/renderer/features/nat/nat-status-menu.tsx
new file mode 100644
index 00000000..5db2c44f
--- /dev/null
+++ b/src/renderer/features/nat/nat-status-menu.tsx
@@ -0,0 +1,145 @@
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+} from '@renderer/components/ui/dropdown-menu'
+import { Spinner } from '@renderer/components/ui/spinner'
+import { toast } from '@renderer/components/ui/toast'
+import { NAT_STATUS_TEXT_KEY, natBucket } 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 { Commands } from '@shared/protocol/commands'
+import type { NatStatus } from '@shared/types/nat'
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+
+export function NatStatusIndicator({
+ status,
+ className,
+}: {
+ status: NatStatus | null
+ className?: string
+}) {
+ const { bucket, color } = natBucket(status)
+ return bucket === 'settingUp' ? (
+ <Spinner
+ data-slot="nat-status-indicator"
+ data-bucket={bucket}
+ aria-hidden="true"
+ className={cn(
+ 'size-3 shrink-0 text-muted-foreground motion-reduce:animate-none',
+ className
+ )}
+ />
+ ) : (
+ <span
+ data-slot="nat-status-indicator"
+ data-bucket={bucket}
+ aria-hidden="true"
+ className={cn('size-2 shrink-0 rounded-full', color, className)}
+ />
+ )
+}
+
+/** Both NAT surfaces use the same status explanation and explicit commands. */
+export function NatStatusMenu({
+ status,
+ children,
+}: {
+ status: NatStatus | null
+ children: ReactNode
+}) {
+ const { t, i18n } = useTranslation()
+ const services = usePlatformServices()
+ const { bucket } = natBucket(status)
+ const detailText = t(
+ bucket === 'failed'
+ ? 'panel.downloads.stats.natUnavailable'
+ : NAT_STATUS_TEXT_KEY[bucket]
+ )
+
+ async function runCommand(
+ channel: typeof Commands.EnableNat | typeof Commands.DisableNat
+ ) {
+ const result = (await transport.invoke(channel)) as
+ | { ok?: boolean; error?: string }
+ | undefined
+ if (result?.ok === false && result.error === ErrorCode.IpcRateLimited) {
+ toast.add({ title: t('panel.dashboard.nat.rateLimited'), type: 'error' })
+ }
+ }
+
+ return (
+ <DropdownMenu>
+ {children}
+ <DropdownMenuContent
+ align="end"
+ className="w-52 max-w-[calc(100vw-2rem)]"
+ >
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="space-y-1 whitespace-normal text-xs font-normal">
+ <p className="font-medium text-foreground">{detailText}</p>
+ {bucket === 'active' || bucket === 'failed' ? (
+ <p className="leading-relaxed text-muted-foreground">
+ {t(
+ bucket === 'active'
+ ? 'panel.downloads.stats.natActiveDesc'
+ : 'panel.downloads.stats.natUnavailableDesc'
+ )}
+ </p>
+ ) : null}
+ {status?.enabled && bucket !== 'off' && status.retryAttempt > 0 ? (
+ <p className="text-muted-foreground">
+ {t('panel.downloads.stats.natRetrying', {
+ attempt: status.retryAttempt,
+ max: status.maxRetries,
+ })}
+ </p>
+ ) : null}
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ {status && (bucket === 'failed' || bucket === 'off') ? (
+ <DropdownMenuItem
+ onClick={() => void runCommand(Commands.EnableNat)}
+ >
+ {t(
+ bucket === 'failed'
+ ? 'panel.downloads.stats.natRetry'
+ : 'panel.dashboard.nat.actions.enable'
+ )}
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem render={<Link to="/settings/network" />}>
+ {t('panel.downloads.stats.natSettings')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ void services.openExternal(
+ getNatTroubleshootingUrl(i18n.resolvedLanguage ?? i18n.language)
+ )
+ }
+ >
+ {t('panel.downloads.stats.natHelp')}
+ </DropdownMenuItem>
+ {status?.enabled ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => void runCommand(Commands.DisableNat)}
+ >
+ {t('panel.downloads.stats.natDisable')}
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/src/renderer/hooks/use-engine-display-status.test.tsx b/src/renderer/hooks/use-engine-display-status.test.tsx
index ea15b3b1..6bb4a1ae 100644
--- a/src/renderer/hooks/use-engine-display-status.test.tsx
+++ b/src/renderer/hooks/use-engine-display-status.test.tsx
@@ -1,5 +1,6 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
+import { subscribeEngineDiagnostics } from '@renderer/features/engine-diagnostics/controller'
import { useOperatorSession } from '@renderer/lib/operator-auth'
import { transport } from '@renderer/lib/transport'
import { dashboardTileViewport } from '@renderer/routes/dashboard/layout/dashboard-registry'
@@ -14,6 +15,7 @@ import {
screen,
waitFor,
} from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, expect, it, vi } from 'vitest'
import { useEngineDisplayStatus } from './use-engine-display-status'
@@ -99,6 +101,30 @@ it('distinguishes server unavailability and a confirmed origin mismatch from eng
expect(screen.queryByText('Engine offline')).not.toBeInTheDocument()
})
+it('keeps the diagnostics action available while the badge reports connection health', async () => {
+ const requested = vi.fn()
+ const unsubscribe = subscribeEngineDiagnostics(requested)
+ try {
+ const user = userEvent.setup()
+ const { rerender } = render(<EngineBadge />)
+ await screen.findByRole('button', { name: 'Engine ready' })
+ health.realtimeConnected = false
+ rerender(<EngineBadge />)
+
+ const badge = screen.getByRole('button', { name: 'Periodic updates' })
+ expect(badge).toHaveAttribute('aria-haspopup', 'dialog')
+ expect(badge).toHaveAttribute(
+ 'title',
+ 'Engine diagnostics: Engine ready, Periodic updates'
+ )
+ expect(screen.getByRole('status')).toHaveTextContent('Periodic updates')
+ await user.click(badge)
+ expect(requested).toHaveBeenCalledOnce()
+ } finally {
+ unsubscribe()
+ }
+})
+
it('shows a confirmed engine failure without waiting for unrelated settings', async () => {
let finishSettings!: (value: unknown) => void
let engineState = 'ready'
diff --git a/src/renderer/lib/nat-status.test.ts b/src/renderer/lib/nat-status.test.ts
index 6b23c99d..f4dacd7f 100644
--- a/src/renderer/lib/nat-status.test.ts
+++ b/src/renderer/lib/nat-status.test.ts
@@ -18,7 +18,17 @@ function makeStatus(overrides: Partial<NatStatus> = {}): NatStatus {
describe('natBucket', () => {
it('maps a null status to the off bucket', () => {
- expect(natBucket(null)).toEqual({ bucket: 'off', color: 'bg-gray-500' })
+ expect(natBucket(null)).toEqual({
+ bucket: 'off',
+ color: 'bg-muted-foreground',
+ })
+ })
+
+ it('treats a disabled setting as off even if the last lifecycle state was active', () => {
+ expect(natBucket(makeStatus({ enabled: false }))).toEqual({
+ bucket: 'off',
+ color: 'bg-muted-foreground',
+ })
})
it('maps Active to the active bucket (green)', () => {
@@ -28,7 +38,7 @@ describe('natBucket', () => {
})
})
- it('maps Discovering/Mapping/Ready to the settingUp bucket (blue)', () => {
+ it('maps Discovering/Mapping/Ready to the settingUp bucket with a neutral indicator', () => {
for (const state of [
NatState.Discovering,
NatState.Mapping,
@@ -36,7 +46,7 @@ describe('natBucket', () => {
]) {
expect(natBucket(makeStatus({ state }))).toEqual({
bucket: 'settingUp',
- color: 'bg-blue-500',
+ color: 'bg-muted-foreground',
})
}
})
@@ -46,15 +56,15 @@ describe('natBucket', () => {
natBucket(
makeStatus({ state: NatState.Failed, retryAttempt: 1, maxRetries: 3 })
)
- ).toEqual({ bucket: 'settingUp', color: 'bg-blue-500' })
+ ).toEqual({ bucket: 'settingUp', color: 'bg-muted-foreground' })
})
- it('maps dormant Failed (budget exhausted) to the failed bucket (red)', () => {
+ it('maps dormant Failed (budget exhausted) to the failed bucket with a neutral indicator', () => {
expect(
natBucket(
makeStatus({ state: NatState.Failed, retryAttempt: 3, maxRetries: 3 })
)
- ).toEqual({ bucket: 'failed', color: 'bg-red-500' })
+ ).toEqual({ bucket: 'failed', color: 'bg-muted-foreground' })
})
it('maps Idle/Stopped/Stopping to the off bucket', () => {
diff --git a/src/renderer/lib/nat-status.ts b/src/renderer/lib/nat-status.ts
index 848a7e93..eaba43aa 100644
--- a/src/renderer/lib/nat-status.ts
+++ b/src/renderer/lib/nat-status.ts
@@ -1,11 +1,17 @@
import { NatState, type NatStatus } from '@shared/types/nat'
// Shared NAT status semantics for the renderer. Both NatBadge (downloads
-// stats bar) and NatTile (dashboard) classify a NatStatus the same way;
-// each surface chooses its wording and visual emphasis.
+// stats bar) and NatTile (dashboard) share wording and visual emphasis.
export type NatBucket = 'active' | 'settingUp' | 'failed' | 'off'
+export const NAT_STATUS_TEXT_KEY: Record<NatBucket, string> = {
+ active: 'panel.downloads.stats.natActive',
+ settingUp: 'panel.downloads.stats.natSettingUp',
+ failed: 'panel.downloads.stats.natMapping',
+ off: 'panel.dashboard.nat.state.off',
+}
+
export interface NatBucketDescriptor {
bucket: NatBucket
/** Tailwind background class for the status dot. */
@@ -16,12 +22,12 @@ export interface NatBucketDescriptor {
* Classify a NatStatus into a coarse display bucket + dot color.
*
* Failed-with-retry-budget is deliberately reported as `settingUp` so the UI
- * does not flicker red↔blue between scheduled retry attempts; the retry
- * counter is surfaced separately via {@link isNatRetrying}.
+ * does not alternate between settled and busy between retry attempts; the retry
+ * counter is shown separately in the shared status menu.
*/
export function natBucket(status: NatStatus | null): NatBucketDescriptor {
- if (!status) {
- return { bucket: 'off', color: 'bg-gray-500' }
+ if (!status?.enabled) {
+ return { bucket: 'off', color: 'bg-muted-foreground' }
}
switch (status.state) {
case NatState.Active:
@@ -29,13 +35,13 @@ export function natBucket(status: NatStatus | null): NatBucketDescriptor {
case NatState.Discovering:
case NatState.Mapping:
case NatState.Ready:
- return { bucket: 'settingUp', color: 'bg-blue-500' }
+ return { bucket: 'settingUp', color: 'bg-muted-foreground' }
case NatState.Failed:
return status.retryAttempt < status.maxRetries
- ? { bucket: 'settingUp', color: 'bg-blue-500' }
- : { bucket: 'failed', color: 'bg-red-500' }
+ ? { bucket: 'settingUp', color: 'bg-muted-foreground' }
+ : { bucket: 'failed', color: 'bg-muted-foreground' }
default:
- return { bucket: 'off', color: 'bg-gray-500' }
+ return { bucket: 'off', color: 'bg-muted-foreground' }
}
}
diff --git a/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts b/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts
index fe16835c..2a72d372 100644
--- a/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts
+++ b/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts
@@ -1,6 +1,7 @@
import type { TaskActivitySnapshot } from '@shared/types/task-activity'
import { afterEach, describe, expect, it } from 'vitest'
import {
+ activityCellPosition,
activityDepth,
activityMonthLabels,
buildActivityCells,
@@ -167,7 +168,7 @@ describe('activity calendar day model', () => {
describe('activity calendar geometry', () => {
it('maps tile content levels to presentation maximums', () => {
expect(maxActivityWeeks('compact')).toBe(13)
- expect(maxActivityWeeks('summary')).toBe(13)
+ expect(maxActivityWeeks('summary')).toBe(26)
expect(maxActivityWeeks('detailed')).toBe(26)
expect(maxActivityWeeks('focus')).toBe(53)
})
@@ -377,6 +378,56 @@ describe('activity calendar geometry', () => {
).toBeLessThanOrEqual(48)
})
+ it.each([
+ { width: 397, contentLevel: 'detailed' as const, weeks: 26 },
+ { width: 619, contentLevel: 'focus' as const, weeks: 53 },
+ { width: 842, contentLevel: 'focus' as const, weeks: 53 },
+ ])(
+ 'uses both rows of a tall $width px calendar without losing dates',
+ ({ width, contentLevel, weeks }) => {
+ const geometry = selectActivityGeometry({
+ width,
+ height: 361,
+ contentLevel,
+ })
+ if (!geometry) throw new Error('Missing banded geometry')
+ expect(geometry.bands).toBe(2)
+ expect(geometry.weeks).toBe(weeks)
+ expect(geometry.cellSize).toBeGreaterThan(12)
+ const cells = projectActivityCells(
+ buildActivityCells(snapshot(), new Date(2026, 8, 19)),
+ weeks
+ )
+ for (const [index] of cells.entries()) {
+ const position = activityCellPosition(geometry, index)
+ expect(position.left).toBeGreaterThanOrEqual(0)
+ expect(position.top).toBeGreaterThanOrEqual(0)
+ expect(position.left + geometry.cellSize).toBeLessThanOrEqual(width)
+ expect(position.top + geometry.cellSize).toBeLessThanOrEqual(361)
+ expect(
+ hitTestActivityCell(
+ geometry,
+ cells,
+ position.left + 1,
+ position.top + 1
+ )
+ ).toBe(index)
+ }
+ expect(
+ hitTestActivityCell(
+ geometry,
+ cells,
+ geometry.gridLeft + 1,
+ geometry.gridTop + geometry.bandHeight + 1
+ )
+ ).toBeNull()
+ const labels = activityMonthLabels(cells, geometry.weeksPerBand)
+ expect(
+ labels.some((label) => label.cellIndex >= geometry.weeksPerBand * 7)
+ ).toBe(true)
+ }
+ )
+
it('returns no geometry until the measured box can contain one week', () => {
expect(
selectActivityGeometry({
diff --git a/src/renderer/routes/dashboard/activity/activity-calendar-model.ts b/src/renderer/routes/dashboard/activity/activity-calendar-model.ts
index 4182948b..f35334ea 100644
--- a/src/renderer/routes/dashboard/activity/activity-calendar-model.ts
+++ b/src/renderer/routes/dashboard/activity/activity-calendar-model.ts
@@ -11,6 +11,8 @@ const PREFERRED_CELL_SIZE = 9
const STANDARD_MIN_CELL_SIZE = 7
const EMERGENCY_MIN_CELL_SIZE = 5
const MAX_CELL_SIZE = 12
+const MAX_BANDED_CELL_SIZE = 18
+const BAND_GAP = 24
const WEEKDAY_LABEL_WIDTH = 24
const MONTH_LABEL_HEIGHT = 14
const LEGEND_HEIGHT = 18
@@ -52,6 +54,10 @@ export interface ActivityCalendarGeometry extends ActivityCalendarChrome {
gridTop: number
gridWidth: number
gridHeight: number
+ bands: number
+ weeksPerBand: number
+ bandHeight: number
+ bandStride: number
}
export interface ActivityGeometryInput {
@@ -180,8 +186,8 @@ export function maxActivityWeeks(
): 13 | 26 | 53 {
switch (contentLevel) {
case 'compact':
- case 'summary':
return 13
+ case 'summary':
case 'detailed':
return 26
case 'focus':
@@ -209,8 +215,8 @@ function maximumChrome(
}
case 'summary':
return {
- showMonthLabels: false,
- showWeekdayLabels: true,
+ showMonthLabels: true,
+ showWeekdayLabels: false,
showLegend: false,
}
case 'detailed':
@@ -286,22 +292,34 @@ function fitGeometry(
weeks: number,
gap: 1 | 2 | 3,
minimumCellSize: number,
- chrome: ActivityCalendarChrome
+ chrome: ActivityCalendarChrome,
+ bands = 1
): ActivityCalendarGeometry | null {
const labelWidth = chrome.showWeekdayLabels ? WEEKDAY_LABEL_WIDTH : 0
const labelHeight = chrome.showMonthLabels ? MONTH_LABEL_HEIGHT : 0
const legendHeight = chrome.showLegend ? LEGEND_HEIGHT : 0
const availableWidth = width - labelWidth
- const availableHeight = height - labelHeight - legendHeight
- const widthCellSize = Math.floor((availableWidth - (weeks - 1) * gap) / weeks)
+ const availableHeight =
+ (height - bands * labelHeight - legendHeight - (bands - 1) * BAND_GAP) /
+ bands
+ const weeksPerBand = Math.ceil(weeks / bands)
+ const widthCellSize = Math.floor(
+ (availableWidth - (weeksPerBand - 1) * gap) / weeksPerBand
+ )
const heightCellSize = Math.floor((availableHeight - 6 * gap) / 7)
- const cellSize = Math.min(MAX_CELL_SIZE, widthCellSize, heightCellSize)
+ const cellSize = Math.min(
+ bands > 1 ? MAX_BANDED_CELL_SIZE : MAX_CELL_SIZE,
+ widthCellSize,
+ heightCellSize
+ )
if (cellSize < minimumCellSize) return null
const stride = cellSize + gap
- const gridWidth = weeks * cellSize + (weeks - 1) * gap
- const gridHeight = 7 * cellSize + 6 * gap
+ const gridWidth = weeksPerBand * cellSize + (weeksPerBand - 1) * gap
+ const bandHeight = 7 * cellSize + 6 * gap
+ const bandStride = bandHeight + labelHeight + BAND_GAP
+ const gridHeight = bandHeight + (bands - 1) * bandStride
const gridAreaHeight = height - labelHeight - legendHeight
return {
@@ -318,6 +336,10 @@ function fitGeometry(
labelHeight + Math.max(0, Math.floor((gridAreaHeight - gridHeight) / 2)),
gridWidth,
gridHeight,
+ bands,
+ weeksPerBand,
+ bandHeight,
+ bandStride,
}
}
@@ -331,23 +353,30 @@ export function selectActivityGeometry({
const maxWeeks = maxActivityWeeks(contentLevel)
const requestedWeeks = [53, 26, 13].filter((weeks) => weeks <= maxWeeks)
const plans = chromePlans(contentLevel)
+ const bandOptions =
+ height >= 220 && (contentLevel === 'detailed' || contentLevel === 'focus')
+ ? [2, 1]
+ : [1]
for (const weeks of requestedWeeks) {
let best: ActivityCalendarGeometry | null = null
for (const chrome of plans) {
- for (const gap of GAP_PREFERENCES) {
- const candidate = fitGeometry(
- width,
- height,
- weeks,
- gap,
- STANDARD_MIN_CELL_SIZE,
- chrome
- )
- if (!candidate) continue
-
- if (isBetterStandardGeometry(candidate, best)) {
- best = candidate
+ for (const bands of bandOptions) {
+ for (const gap of GAP_PREFERENCES) {
+ const candidate = fitGeometry(
+ width,
+ height,
+ weeks,
+ gap,
+ STANDARD_MIN_CELL_SIZE,
+ chrome,
+ bands
+ )
+ if (!candidate) continue
+
+ if (isBetterStandardGeometry(candidate, best)) {
+ best = candidate
+ }
}
}
}
@@ -386,6 +415,22 @@ export function selectActivityGeometry({
return best
}
+/** Calendar coordinates stay chronological when the week columns wrap. */
+export function activityCellPosition(
+ geometry: ActivityCalendarGeometry,
+ index: number
+): { left: number; top: number } {
+ const week = Math.floor(index / 7)
+ const band = Math.floor(week / geometry.weeksPerBand)
+ return {
+ left: geometry.gridLeft + (week % geometry.weeksPerBand) * geometry.stride,
+ top:
+ geometry.gridTop +
+ band * geometry.bandStride +
+ (index % 7) * geometry.stride,
+ }
+}
+
export function hitTestActivityCell(
geometry: ActivityCalendarGeometry,
cells: readonly ActivityCalendarCell[],
@@ -397,16 +442,25 @@ export function hitTestActivityCell(
if (localX < 0 || localY < 0) return null
const column = Math.floor(localX / geometry.stride)
- const row = Math.floor(localY / geometry.stride)
- if (column >= geometry.weeks || row >= 7) return null
+ const band = Math.floor(localY / geometry.bandStride)
+ const bandY = localY - band * geometry.bandStride
+ const row = Math.floor(bandY / geometry.stride)
+ const week = band * geometry.weeksPerBand + column
+ if (
+ band >= geometry.bands ||
+ column >= geometry.weeksPerBand ||
+ week >= geometry.weeks ||
+ row >= 7
+ )
+ return null
if (
localX - column * geometry.stride >= geometry.cellSize ||
- localY - row * geometry.stride >= geometry.cellSize
+ bandY - row * geometry.stride >= geometry.cellSize
) {
return null
}
- const index = column * 7 + row
+ const index = week * 7 + row
return cells[index]?.tracking === 'future' ? null : index
}
@@ -486,8 +540,20 @@ export function moveActivityActiveIndex(
}
export function activityMonthLabels(
- cells: readonly ActivityCalendarCell[]
+ cells: readonly ActivityCalendarCell[],
+ weeksPerBand = cells.length / 7
): ActivityMonthLabel[] {
+ if (weeksPerBand > 0 && weeksPerBand * 7 < cells.length) {
+ const labels: ActivityMonthLabel[] = []
+ for (let start = 0; start < cells.length; start += weeksPerBand * 7) {
+ labels.push(
+ ...activityMonthLabels(
+ cells.slice(start, start + weeksPerBand * 7)
+ ).map((label) => ({ ...label, cellIndex: label.cellIndex + start }))
+ )
+ }
+ return labels
+ }
const labels: ActivityMonthLabel[] = []
for (let column = 0; column < cells.length / 7; column += 1) {
diff --git a/src/renderer/routes/dashboard/activity/activity-calendar.tsx b/src/renderer/routes/dashboard/activity/activity-calendar.tsx
index e94739c2..cfa587b8 100644
--- a/src/renderer/routes/dashboard/activity/activity-calendar.tsx
+++ b/src/renderer/routes/dashboard/activity/activity-calendar.tsx
@@ -27,6 +27,7 @@ import {
type ActivityNavigationKey,
activityMonthLabels,
buildActivityCells,
+ activityCellPosition as cellPosition,
defaultActivityActiveIndex,
hitTestActivityCell,
maxActivityWeeks,
@@ -123,16 +124,6 @@ function readPalette(
return palette
}
-function cellPosition(
- geometry: ActivityCalendarGeometry,
- index: number
-): { left: number; top: number } {
- return {
- left: geometry.gridLeft + Math.floor(index / 7) * geometry.stride,
- top: geometry.gridTop + (index % 7) * geometry.stride,
- }
-}
-
function isActivityCellGap(
geometry: ActivityCalendarGeometry,
x: number,
@@ -150,16 +141,18 @@ function isActivityCellGap(
}
const column = Math.floor(relativeX / geometry.stride)
- const row = Math.floor(relativeY / geometry.stride)
- if (column < 0 || column >= geometry.weeks || row < 0 || row >= 7) {
+ const band = Math.floor(relativeY / geometry.bandStride)
+ const bandY = relativeY - band * geometry.bandStride
+ const row = Math.floor(bandY / geometry.stride)
+ const week = band * geometry.weeksPerBand + column
+ if (column >= geometry.weeksPerBand || week >= geometry.weeks || row >= 7) {
return false
}
const horizontalGap =
relativeX % geometry.stride >= geometry.cellSize &&
- column < geometry.weeks - 1
- const verticalGap =
- relativeY % geometry.stride >= geometry.cellSize && row < 6
+ column < geometry.weeksPerBand - 1
+ const verticalGap = bandY % geometry.stride >= geometry.cellSize && row < 6
return horizontalGap || verticalGap
}
@@ -226,6 +219,8 @@ function geometryEqual(
left.gap === right.gap &&
left.gridLeft === right.gridLeft &&
left.gridTop === right.gridTop &&
+ left.weeksPerBand === right.weeksPerBand &&
+ left.bandStride === right.bandStride &&
left.showLegend === right.showLegend &&
left.showMonthLabels === right.showMonthLabels &&
left.showWeekdayLabels === right.showWeekdayLabels
@@ -978,7 +973,10 @@ export function ActivityCalendar({
tooltipAnchorRef.current?.getBoundingClientRect() ?? new DOMRect(),
}
: null
- const monthLabels = useMemo(() => activityMonthLabels(cells), [cells])
+ const monthLabels = useMemo(
+ () => activityMonthLabels(cells, geometry?.weeksPerBand),
+ [cells, geometry?.weeksPerBand]
+ )
const tooltipDetails = tooltipCell
? [
tooltipCell.tracking !== 'untracked' && tooltipCell.submitted > 0
@@ -1022,6 +1020,7 @@ export function ActivityCalendar({
<div
ref={containerRef}
data-testid="activity-calendar"
+ data-bands={geometry?.bands}
dir="ltr"
role="grid"
tabIndex={interactive ? 0 : -1}
@@ -1055,14 +1054,16 @@ export function ActivityCalendar({
{geometry?.showMonthLabels
? monthLabels.map((label) => {
- const column = Math.floor(label.cellIndex / 7)
+ const position = cellPosition(geometry, label.cellIndex)
return (
<span
key={label.cellIndex}
aria-hidden="true"
- className="pointer-events-none absolute top-0 truncate text-[10px] leading-3 text-muted-foreground"
+ data-calendar-label="month"
+ className="pointer-events-none absolute truncate text-[10px] leading-3 text-muted-foreground"
style={{
- left: geometry.gridLeft + column * geometry.stride,
+ left: position.left,
+ top: position.top - 14,
maxWidth: Math.max(geometry.stride * 4, geometry.cellSize),
}}
>
@@ -1073,24 +1074,30 @@ export function ActivityCalendar({
: null}
{geometry?.showWeekdayLabels
- ? weekdayLabels.map(({ key, index }) => (
- <span
- key={key}
- aria-hidden="true"
- className="pointer-events-none absolute start-0 w-6 truncate text-[10px] leading-none text-muted-foreground"
- style={{
- top:
- geometry.gridTop +
- index * geometry.stride +
- Math.max(
- 0,
- Math.floor((geometry.cellSize - LABEL_FONT_SIZE) / 2)
- ),
- }}
- >
- {t(`${KEY_ROOT}.weekday.${key}`)}
- </span>
- ))
+ ? Array.from({ length: geometry.bands }, (_, band) => {
+ const bandStart = cells[band * geometry.weeksPerBand * 7]
+ return weekdayLabels.map(({ key, index }) => (
+ <span
+ key={`${bandStart?.dateKey}-${key}`}
+ aria-hidden="true"
+ data-calendar-label="weekday"
+ className="pointer-events-none absolute start-0 w-6 truncate text-[10px] leading-none text-muted-foreground"
+ style={{
+ left: geometry.gridLeft - 24,
+ top:
+ geometry.gridTop +
+ band * geometry.bandStride +
+ index * geometry.stride +
+ Math.max(
+ 0,
+ Math.floor((geometry.cellSize - LABEL_FONT_SIZE) / 2)
+ ),
+ }}
+ >
+ {t(`${KEY_ROOT}.weekday.${key}`)}
+ </span>
+ ))
+ })
: null}
{geometry?.showLegend ? (
@@ -1106,8 +1113,8 @@ export function ActivityCalendar({
aria-hidden="true"
className="rounded-[2px]"
style={{
- width: geometry.cellSize,
- height: geometry.cellSize,
+ width: Math.min(12, geometry.cellSize),
+ height: Math.min(12, geometry.cellSize),
backgroundColor:
depth === 0
? 'var(--muted)'
@@ -1208,7 +1215,7 @@ export function ActivityCalendar({
</div>
{tooltipDetails.length > 0 ? (
<div className="text-primary-foreground/70">
- {tooltipDetails.join(' · ')}
+ {tooltipDetails.join(', ')}
</div>
) : null}
</div>
diff --git a/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx b/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx
index 6e494a0f..f83d5090 100644
--- a/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-grid.test.tsx
@@ -18,6 +18,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import type { DashboardTileViewport } from '../layout/dashboard-registry'
import { DashboardGrid } from './dashboard-grid'
+vi.mock('@renderer/hooks/use-liquid-glass', () => ({
+ useLiquidGlass: () => false,
+}))
+
const renderCounts = new Map<string, number>()
function renderTile(
@@ -165,15 +169,15 @@ async function selectPreset(name: RegExp) {
}
const COMPACT_PRESET_TILES: DashboardTileLayout[] = [
- { id: 'engine', enabled: true, x: 0, y: 0, w: 2, h: 1 },
- { id: 'speedLimit', enabled: true, x: 2, y: 0, w: 2, h: 1 },
- { id: 'speedUp', enabled: true, x: 0, y: 1, w: 1, h: 1 },
- { id: 'speedDown', enabled: true, x: 1, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'tasks', enabled: true, x: 0, y: 2, w: 2, h: 1 },
- { id: 'nat', enabled: true, x: 2, y: 2, w: 2, h: 1 },
- { id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'engine', enabled: true, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'nat', enabled: true, x: 1, y: 0, w: 1, h: 1 },
+ { id: 'speedUp', enabled: true, x: 2, y: 0, w: 1, h: 1 },
+ { id: 'speedDown', enabled: true, x: 3, y: 0, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 0, y: 1, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 1, y: 1, w: 1, h: 1 },
+ { id: 'tasks', enabled: true, x: 2, y: 1, w: 2, h: 1 },
+ { id: 'active', enabled: true, x: 0, y: 2, w: 2, h: 1 },
+ { id: 'activity', enabled: true, x: 2, y: 2, w: 2, h: 1 },
]
describe('DashboardGrid', () => {
@@ -391,22 +395,13 @@ describe('DashboardGrid', () => {
expect(releaseOnUnmount).toHaveBeenCalledWith(8)
})
- it('groups the configure actions with visible labels', () => {
+ it('exposes configure actions in a keyboard-accessible toolbar', async () => {
+ const user = userEvent.setup()
renderDefaultGrid()
fireEvent.click(screen.getByRole('button', { name: /Configure|配置/i }))
- // Actions render as nested button groups — an edit cluster
- // (cancel/reset/apply) and a gapped preset/Add cluster. The outer group is
- // the one wrapping all five buttons.
- const group = screen
- .getAllByRole('group')
- .find(
- (candidate) => within(candidate).queryAllByRole('button').length === 5
- )
- if (!group) {
- throw new Error('no outer group with all five configure actions')
- }
+ const group = screen.getByRole('toolbar', { name: /Configure|配置/i })
const cancel = within(group).getByRole('button', { name: /Cancel|取消/i })
const reset = within(group).getByRole('button', {
@@ -417,9 +412,8 @@ describe('DashboardGrid', () => {
name: /Presets|预设/i,
})
const add = within(group).getByRole('button', { name: /Add|添加/i })
- // Full mode shows the label text inline (not icon-only).
- expect(cancel).toHaveTextContent(/Cancel|取消/i)
- expect(reset).toHaveTextContent(/^(Reset|重置)$/i)
+ // Keep the primary action and current preset readable; secondary actions
+ // use the same icon buttons and accessible names as the Downloads toolbar.
expect(apply).toHaveTextContent(/Apply|应用/i)
// Add sits at the trailing edge so its end-aligned dropdown hangs
// under the toolbar's right corner.
@@ -430,6 +424,19 @@ describe('DashboardGrid', () => {
presets,
add,
])
+
+ await user.tab()
+ expect(cancel).toHaveFocus()
+ await user.keyboard('{ArrowRight}')
+ expect(reset).toHaveFocus()
+ await user.keyboard('{ArrowRight}')
+ expect(apply).toHaveFocus()
+ await user.keyboard('{ArrowRight}')
+ expect(presets).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(await screen.findByRole('menu')).toBeVisible()
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(presets).toHaveFocus())
})
it('shows all presets only while configuring and labels exact or custom drafts', async () => {
@@ -490,29 +497,21 @@ describe('DashboardGrid', () => {
await selectPreset(/Compact|紧凑/i)
expect(onApply).not.toHaveBeenCalled()
+ expect(screen.getAllByTestId(/^dashboard-tile-/)).toHaveLength(9)
expect(
- screen.getByText('engine-0,0-2x1-summary-wide-viewport:2x1')
- ).toBeInTheDocument()
- expect(
- screen.getByText('speedLimit-2,0-2x1-summary-wide-viewport:2x1')
- ).toBeInTheDocument()
- expect(
- screen.getByText('speedUp-0,1-1x1-compact-square-viewport:1x1')
- ).toBeInTheDocument()
- expect(
- screen.getByText('speedDown-1,1-1x1-compact-square-viewport:1x1')
+ screen.getByText('engine-0,0-1x1-compact-square-viewport:1x1')
).toBeInTheDocument()
expect(
- screen.getByText('active-2,1-1x1-compact-square-viewport:1x1')
+ screen.getByText('nat-1,0-1x1-compact-square-viewport:1x1')
).toBeInTheDocument()
expect(
- screen.getByText('transfer-3,1-1x1-compact-square-viewport:1x1')
+ screen.getByText('speedDown-3,0-1x1-compact-square-viewport:1x1')
).toBeInTheDocument()
expect(
- screen.getByText('tasks-0,2-2x1-summary-wide-viewport:2x1')
+ screen.getByText('tasks-2,1-2x1-summary-wide-viewport:2x1')
).toBeInTheDocument()
expect(
- screen.getByText('nat-2,2-2x1-summary-wide-viewport:2x1')
+ screen.getByText('activity-2,2-2x1-summary-wide-viewport:2x1')
).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /Apply|应用/i }))
@@ -537,7 +536,7 @@ describe('DashboardGrid', () => {
expect(screen.queryByTestId('dashboard-tile-nat')).not.toBeInTheDocument()
expect(
- screen.getByText('tasks-0,0-2x3-focus-tall-viewport:2x3')
+ screen.getByText('tasks-1,1-3x2-focus-wide-viewport:3x2')
).toBeInTheDocument()
expect(
screen.getByRole('button', {
@@ -597,7 +596,7 @@ describe('DashboardGrid', () => {
})
if (operation === 'resize') {
- await selectTileSize('engine', '1x1')
+ await selectTileSize('active', '1x1')
} else if (operation === 'remove') {
fireEvent.click(
within(screen.getByTestId('dashboard-tile-engine')).getByRole(
@@ -645,7 +644,10 @@ describe('DashboardGrid', () => {
name: /2\s*[×x]\s*1/i,
})
expect(expansion).toHaveAttribute('aria-disabled', 'true')
- expect(expansion).toHaveTextContent(/Not enough space|空间不足/i)
+ expect(expansion).not.toHaveTextContent(/Not enough space|空间不足/i)
+ expect(expansion).toHaveAccessibleDescription(
+ /Shrink or remove|缩小或移除/i
+ )
})
it('enters configure mode and cancels draft resize changes', async () => {
@@ -824,7 +826,10 @@ describe('DashboardGrid', () => {
name: /NAT.*(?:Not enough space|空间不足)/i,
})
expect(blockedNat).toHaveAttribute('aria-disabled', 'true')
- expect(blockedNat).toHaveTextContent(/Not enough space|空间不足/i)
+ expect(blockedNat).not.toHaveTextContent(/Not enough space|空间不足/i)
+ expect(blockedNat).toHaveAccessibleDescription(
+ /Shrink or remove|缩小或移除/i
+ )
expect(screen.getByTestId('dashboard-tile-speedUp')).toHaveAttribute(
'data-enabled',
'true'
diff --git a/src/renderer/routes/dashboard/components/dashboard-grid.tsx b/src/renderer/routes/dashboard/components/dashboard-grid.tsx
index 6a4036b2..c8525bc0 100644
--- a/src/renderer/routes/dashboard/components/dashboard-grid.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-grid.tsx
@@ -1,10 +1,9 @@
import { useCompactHeader } from '@renderer/components/desktop-kit/hooks/use-compact-header'
-import {
- COMPACT_ACTION_CLASS,
- HeaderActionButton,
-} from '@renderer/components/desktop-kit/panel/header-action-button'
+import { COMPACT_ACTION_CLASS } from '@renderer/components/desktop-kit/panel/header-action-button'
+import { Toolbar } from '@renderer/components/desktop-kit/toolbar/toolbar'
+import { ToolbarButton } from '@renderer/components/desktop-kit/toolbar/toolbar-button'
+import { ToolbarGroup } from '@renderer/components/desktop-kit/toolbar/toolbar-group'
import { Button } from '@renderer/components/ui/button'
-import { ButtonGroup } from '@renderer/components/ui/button-group'
import {
DropdownMenu,
DropdownMenuContent,
@@ -42,7 +41,7 @@ import {
X,
} from 'lucide-react'
import type React from 'react'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { flushSync } from 'react-dom'
import { useTranslation } from 'react-i18next'
import {
@@ -62,12 +61,18 @@ import {
} from '../layout/dashboard-presets'
import {
type DashboardTileViewport,
- dashboardTileSizeLabel,
dashboardTileSpanKey,
dashboardTileViewport,
getDashboardTileDefinition,
nearestDashboardTilePresentation,
} from '../layout/dashboard-registry'
+import {
+ DASHBOARD_LAYOUT_MENU_CLASS,
+ DASHBOARD_LAYOUT_OPTION_CLASS,
+ DashboardLayoutHint,
+ DashboardLayoutPreview,
+ DashboardPresetPreview,
+} from './dashboard-layout-menu'
import {
DashboardResizeGhost,
type DashboardResizeGhostViewportRect,
@@ -668,7 +673,7 @@ function toLayout(
/**
* Header action that adds removed tiles back to the board. Lives in the
- * editing ButtonGroup so the picker never takes vertical space away from the
+ * editing toolbar so the picker never takes vertical space away from the
* 1fr grid rows; the menu stays open across selections so several tiles can
* be re-added in one pass, and the last pick falls through to the default
* close so an empty menu never shows.
@@ -687,41 +692,84 @@ function AddTileMenu({
onAdd: (id: DashboardTileId) => void
}) {
const { t } = useTranslation()
+ const hintId = useId()
+ const [hintReason, setHintReason] =
+ useState<DashboardLayoutFailureReason | null>(null)
+ const unavailableReason = tiles.find(
+ (option) => !option.available
+ )?.failureReason
const availableCount = tiles.filter((option) => option.available).length
return (
- <DropdownMenu>
- <HeaderActionButton
+ <DropdownMenu onOpenChange={() => setHintReason(null)}>
+ <ToolbarButton
label={label}
- variant="outline"
disabled={disabled}
- wrapTrigger={(button) => <DropdownMenuTrigger render={button} />}
+ render={<DropdownMenuTrigger />}
>
<Plus aria-hidden />
- </HeaderActionButton>
- <DropdownMenuContent align="end">
- {tiles.map(({ tile, available, failureReason }) => {
- const title = t(getDashboardTileDefinition(tile.id).titleKey)
- const reason = failureReason ? unavailable(failureReason) : undefined
- return (
- <DropdownMenuItem
- key={tile.id}
- disabled={!available}
- closeOnClick={availableCount <= 1}
- aria-label={reason ? `${title} ${reason}` : title}
- onClick={() => {
- if (!available) return
- onAdd(tile.id)
- }}
- >
- <span className="min-w-0 flex-1 truncate">{title}</span>
- {reason ? (
- <span className="ml-4 text-[10px] text-muted-foreground">
- {reason}
+ </ToolbarButton>
+ <DropdownMenuContent
+ align="end"
+ sideOffset={8}
+ className={DASHBOARD_LAYOUT_MENU_CLASS}
+ >
+ <div className="shrink-0 px-2 pt-1 pb-1.5 text-[11px] font-medium">
+ {t('panel.dashboard.configure.addTitle')}
+ </div>
+ <div className="min-h-0 overflow-y-auto overscroll-contain">
+ {tiles.map(({ tile, available, failureReason }) => {
+ const title = t(getDashboardTileDefinition(tile.id).titleKey)
+ const reason = failureReason
+ ? unavailable(failureReason)
+ : undefined
+ return (
+ <DropdownMenuItem
+ key={tile.id}
+ disabled={!available}
+ closeOnClick={availableCount <= 1}
+ aria-label={reason ? `${title} ${reason}` : title}
+ aria-describedby={!available ? hintId : undefined}
+ onMouseEnter={() => setHintReason(failureReason ?? null)}
+ onFocus={() => setHintReason(failureReason ?? null)}
+ className={DASHBOARD_LAYOUT_OPTION_CLASS}
+ onClick={() => {
+ if (!available) return
+ onAdd(tile.id)
+ }}
+ >
+ <DashboardLayoutPreview
+ span={tile}
+ className={cn('text-foreground', !available && 'opacity-35')}
+ />
+ <span
+ className={cn('min-w-0 flex-1', !available && 'opacity-60')}
+ >
+ <span className="block truncate text-xs leading-4 font-medium">
+ {title}
+ </span>
+ <span className="block text-[10px] leading-3.5 tabular-nums text-muted-foreground">
+ {t('panel.dashboard.configure.size', {
+ width: tile.w,
+ height: tile.h,
+ })}
+ </span>
</span>
- ) : null}
- </DropdownMenuItem>
- )
- })}
+ {available ? (
+ <Plus
+ aria-hidden
+ className="size-3.5 text-muted-foreground opacity-0 group-data-highlighted/layout-option:opacity-100"
+ />
+ ) : null}
+ </DropdownMenuItem>
+ )
+ })}
+ </div>
+ {unavailableReason ? (
+ <DashboardLayoutHint
+ id={hintId}
+ reason={hintReason ?? unavailableReason}
+ />
+ ) : null}
</DropdownMenuContent>
</DropdownMenu>
)
@@ -754,37 +802,40 @@ function PresetMenu({
return (
<DropdownMenu>
- <HeaderActionButton
+ <ToolbarButton
label={`${label}: ${currentLabel}`}
- visibleLabel={currentLabel}
- variant="outline"
disabled={disabled}
- wrapTrigger={(button) => <DropdownMenuTrigger render={button} />}
+ className="w-auto gap-1.5 px-2.5 compact-header:size-6 compact-header:p-0"
+ render={<DropdownMenuTrigger />}
>
<LayoutTemplate aria-hidden />
- </HeaderActionButton>
- <DropdownMenuContent align="end" className="w-64">
+ <span className="max-w-32 truncate compact-header:hidden">
+ {currentLabel}
+ </span>
+ </ToolbarButton>
+ <DropdownMenuContent align="end" className={DASHBOARD_LAYOUT_MENU_CLASS}>
{DASHBOARD_LAYOUT_PRESETS.map((preset) => (
<DropdownMenuItem
key={preset.id}
- className="items-start gap-2"
+ className={cn(
+ DASHBOARD_LAYOUT_OPTION_CLASS,
+ currentPresetId === preset.id && 'bg-muted/60'
+ )}
onClick={() => onSelect(preset.id)}
>
- <div className="min-w-0 flex-1">
- <div className="text-sm">{t(preset.titleKey)}</div>
- <div className="text-[11px] text-muted-foreground">
- {t(preset.descriptionKey)}
- </div>
- </div>
+ <DashboardPresetPreview tiles={preset.layout.tiles} />
+ <span className="min-w-0 flex-1 truncate text-sm">
+ {t(preset.titleKey)}
+ </span>
{currentPresetId === preset.id ? (
- <Check className="mt-0.5 size-4 shrink-0" aria-hidden />
+ <Check className="size-3.5 shrink-0" aria-hidden />
) : null}
</DropdownMenuItem>
))}
{canUndo ? (
<>
<DropdownMenuSeparator />
- <DropdownMenuItem onClick={onUndo}>
+ <DropdownMenuItem className="rounded-lg text-xs" onClick={onUndo}>
<Undo2 aria-hidden />
{undoLabel}
</DropdownMenuItem>
@@ -1356,33 +1407,33 @@ export function DashboardGrid({
const actions = useMemo(
() =>
editing ? (
- <ButtonGroup>
- <ButtonGroup>
- <HeaderActionButton
+ <Toolbar label={label.action} data-slot="dashboard-configure-toolbar">
+ <ToolbarGroup>
+ <ToolbarButton
label={label.cancel}
- variant="outline"
onClick={cancelEditing}
disabled={saving}
>
<X aria-hidden />
- </HeaderActionButton>
- <HeaderActionButton
+ </ToolbarButton>
+ <ToolbarButton
label={label.reset}
- variant="outline"
onClick={resetDraft}
disabled={saving}
>
<RotateCcw aria-hidden />
- </HeaderActionButton>
- <HeaderActionButton
+ </ToolbarButton>
+ <ToolbarButton
label={label.apply}
+ className="w-auto gap-1.5 bg-primary! px-2.5 text-primary-foreground! enabled:hover:bg-primary/90! enabled:active:bg-primary/80! compact-header:size-6 compact-header:p-0"
onClick={() => void applyDraft()}
disabled={saving}
>
<Check aria-hidden />
- </HeaderActionButton>
- </ButtonGroup>
- <ButtonGroup>
+ <span className="compact-header:hidden">{label.apply}</span>
+ </ToolbarButton>
+ </ToolbarGroup>
+ <ToolbarGroup>
<PresetMenu
disabled={saving}
label={label.presets}
@@ -1400,8 +1451,8 @@ export function DashboardGrid({
unavailable={(reason) => label.unavailable[reason]}
onAdd={addTile}
/>
- </ButtonGroup>
- </ButtonGroup>
+ </ToolbarGroup>
+ </Toolbar>
) : (
<Tooltip>
<TooltipTrigger
@@ -1527,17 +1578,6 @@ export function DashboardGrid({
resize: label.resize,
remove: label.remove,
sizeGroup: label.sizeGroup,
- size: (_size, presentation) => {
- const sizeLabel = t(
- `panel.dashboard.configure.sizeLabels.${dashboardTileSizeLabel(presentation)}`
- )
- const dimensions = t('panel.dashboard.configure.size', {
- width: presentation.span.w,
- height: presentation.span.h,
- defaultValue: `${presentation.span.w} × ${presentation.span.h}`,
- })
- return `${sizeLabel} · ${dimensions}`
- },
unavailable: (reason) => label.unavailable[reason],
}}
onResize={(id, span) => {
diff --git a/src/renderer/routes/dashboard/components/dashboard-layout-menu.tsx b/src/renderer/routes/dashboard/components/dashboard-layout-menu.tsx
new file mode 100644
index 00000000..a0df4cfa
--- /dev/null
+++ b/src/renderer/routes/dashboard/components/dashboard-layout-menu.tsx
@@ -0,0 +1,123 @@
+import { cn } from '@renderer/lib/utils'
+import {
+ DASHBOARD_COLUMNS,
+ DASHBOARD_ROWS,
+} from '@shared/schemas/dashboard-layout'
+import type {
+ DashboardTileLayout,
+ DashboardTileSpan,
+} from '@shared/types/settings'
+import { Info } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import type { DashboardLayoutFailureReason } from '../layout/dashboard-layout'
+
+export const DASHBOARD_LAYOUT_MENU_CLASS =
+ 'flex w-52 flex-col overflow-hidden rounded-xl border-border/70 p-1 shadow-lg'
+
+export const DASHBOARD_LAYOUT_OPTION_CLASS =
+ 'group/layout-option min-h-10 gap-2 rounded-lg px-2 py-1 data-disabled:pointer-events-auto data-disabled:opacity-100 data-disabled:text-muted-foreground data-disabled:data-highlighted:bg-muted/40 data-disabled:data-highlighted:text-muted-foreground'
+
+const PREVIEW_CELLS = Array.from(
+ { length: DASHBOARD_COLUMNS * DASHBOARD_ROWS },
+ (_, index) => ({
+ x: (index % DASHBOARD_COLUMNS) * 14 + 1,
+ y: Math.floor(index / DASHBOARD_COLUMNS) * 14 + 1,
+ })
+)
+
+/** A miniature of the fixed canvas, with the chosen footprint drawn to scale. */
+export function DashboardLayoutPreview({
+ span,
+ className,
+}: {
+ span: DashboardTileSpan
+ className?: string
+}) {
+ return (
+ <svg
+ viewBox="0 0 56 42"
+ aria-hidden="true"
+ className={cn('size-auto h-6 w-8 shrink-0', className)}
+ >
+ {PREVIEW_CELLS.map(({ x, y }) => (
+ <rect
+ key={`${x}:${y}`}
+ x={x}
+ y={y}
+ width="11"
+ height="11"
+ rx="2.5"
+ fill="currentColor"
+ opacity="0.08"
+ />
+ ))}
+ <rect
+ x="1"
+ y="1"
+ width={span.w * 14 - 3}
+ height={span.h * 14 - 3}
+ rx="2.5"
+ fill="currentColor"
+ fillOpacity="0.16"
+ stroke="currentColor"
+ strokeOpacity="0.65"
+ />
+ </svg>
+ )
+}
+
+/** The preset's actual tile arrangement, sharing the size menu's canvas scale. */
+export function DashboardPresetPreview({
+ tiles,
+}: {
+ tiles: readonly DashboardTileLayout[]
+}) {
+ return (
+ <svg
+ viewBox="0 0 56 42"
+ aria-hidden="true"
+ className="size-auto h-6 w-8 shrink-0 text-foreground/80"
+ >
+ {tiles
+ .filter((tile) => tile.enabled)
+ .map((tile) => (
+ <rect
+ key={tile.id}
+ x={tile.x * 14 + 1}
+ y={tile.y * 14 + 1}
+ width={tile.w * 14 - 3}
+ height={tile.h * 14 - 3}
+ rx="2.5"
+ fill="currentColor"
+ fillOpacity={tile.w * tile.h > 1 ? 0.24 : 0.12}
+ stroke="currentColor"
+ strokeOpacity="0.3"
+ />
+ ))}
+ </svg>
+ )
+}
+
+const HINT_KEYS = {
+ 'insufficient-space': 'panel.dashboard.configure.availabilityHints.space',
+ 'out-of-bounds': 'panel.dashboard.configure.availabilityHints.bounds',
+ 'unsupported-span': 'panel.dashboard.configure.availabilityHints.unsupported',
+} as const
+
+export function DashboardLayoutHint({
+ id,
+ reason,
+}: {
+ id: string
+ reason: DashboardLayoutFailureReason
+}) {
+ const { t } = useTranslation()
+ return (
+ <div className="mt-1 flex shrink-0 items-start gap-1.5 border-t border-border/60 px-2 pt-2 pb-1.5 text-muted-foreground">
+ <Info aria-hidden className="mt-0.5 size-3 shrink-0" />
+ <p id={id} className="text-[11px] leading-4">
+ {t(HINT_KEYS[reason])}
+ </p>
+ </div>
+ )
+}
diff --git a/src/renderer/routes/dashboard/components/dashboard-tile-frame.test.tsx b/src/renderer/routes/dashboard/components/dashboard-tile-frame.test.tsx
index 4f53132e..e0d94f1b 100644
--- a/src/renderer/routes/dashboard/components/dashboard-tile-frame.test.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-tile-frame.test.tsx
@@ -1,4 +1,5 @@
import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
import { TooltipProvider } from '@renderer/components/ui/tooltip'
import type { DashboardTileLayout } from '@shared/types/settings'
import { fireEvent, render, screen } from '@testing-library/react'
@@ -23,7 +24,6 @@ const labels: DashboardTileFrameLabels = {
remove: 'Remove tile',
resize: 'Resize tile',
sizeGroup: 'Tile size',
- size: (size) => size,
unavailable: () => 'Not enough space',
}
@@ -138,7 +138,9 @@ describe('DashboardTileFrame', () => {
fireEvent.pointerDown(screen.getByRole('button', { name: 'Drag tile' }))
await user.click(screen.getByRole('button', { name: 'Tile size' }))
- await user.click(await screen.findByRole('menuitemradio', { name: '1x1' }))
+ await user.click(
+ await screen.findByRole('menuitemradio', { name: 'Compact 1 × 1' })
+ )
await user.click(screen.getByRole('button', { name: 'Remove tile' }))
expect(onDragHandlePointerDown).toHaveBeenCalledWith(
@@ -155,19 +157,28 @@ describe('DashboardTileFrame', () => {
await user.click(screen.getByRole('button', { name: 'Tile size' }))
expect(
- await screen.findByRole('menuitemradio', { name: '2x1' })
+ await screen.findByRole('menuitemradio', { name: 'Wide 2 × 1' })
).toHaveAttribute('aria-checked', 'true')
})
it('shows registered but capacity-blocked spans as disabled', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 })
- renderFrame({ editing: true })
+ const onResize = vi.fn()
+ renderFrame({ editing: true, onResize })
await user.click(screen.getByRole('button', { name: 'Tile size' }))
const blocked = await screen.findByRole('menuitemradio', {
- name: /1x2 Not enough space/,
+ name: /Tall 1 × 2 Not enough space/,
})
expect(blocked).toHaveAttribute('aria-disabled', 'true')
- expect(screen.queryByRole('menuitemradio', { name: /3x1/ })).toBeNull()
+ expect(blocked).toHaveAccessibleDescription(
+ 'Shrink or remove another tile.'
+ )
+ expect(blocked).not.toHaveTextContent('Not enough space')
+ expect(screen.queryByRole('menuitemradio', { name: /3 × 1/ })).toBeNull()
+ await user.click(blocked)
+ blocked.focus()
+ await user.keyboard('{Enter}')
+ expect(onResize).not.toHaveBeenCalled()
})
})
diff --git a/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx b/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx
index 5432a44b..df3056d0 100644
--- a/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx
@@ -18,6 +18,7 @@ import type {
DashboardTileSpan,
} from '@shared/types/settings'
import {
+ Check,
GripVertical,
MoveDiagonal2,
PanelTop,
@@ -26,26 +27,29 @@ import {
Trash2,
} from 'lucide-react'
import type React from 'react'
+import { useId, useState } from 'react'
+import { useTranslation } from 'react-i18next'
import type {
DashboardLayoutFailureReason,
DashboardTileSizeOption,
} from '../layout/dashboard-layout'
import {
- type DashboardTilePresentationDefinition,
- type DashboardTileSpanKey,
dashboardTileOrientation,
+ dashboardTileSizeLabel,
dashboardTileSpanKey,
} from '../layout/dashboard-registry'
+import {
+ DASHBOARD_LAYOUT_MENU_CLASS,
+ DASHBOARD_LAYOUT_OPTION_CLASS,
+ DashboardLayoutHint,
+ DashboardLayoutPreview,
+} from './dashboard-layout-menu'
export interface DashboardTileFrameLabels {
drag: string
remove: string
resize?: string
sizeGroup: string
- size: (
- size: DashboardTileSpanKey,
- presentation: DashboardTilePresentationDefinition
- ) => string
unavailable: (reason: DashboardLayoutFailureReason) => string
}
@@ -97,6 +101,13 @@ export function DashboardTileFrame({
onResize,
onRemove,
}: DashboardTileFrameProps) {
+ const { t } = useTranslation()
+ const hintId = useId()
+ const [hintReason, setHintReason] =
+ useState<DashboardLayoutFailureReason | null>(null)
+ const unavailableReason = sizeOptions.find(
+ (option) => !option.available
+ )?.failureReason
const currentSize = dashboardTileSpanKey(tile)
const gridStyle = {
'--dashboard-grid-column': `${tile.x + 1} / span ${tile.w}`,
@@ -162,7 +173,7 @@ export function DashboardTileFrame({
<Trash2 aria-hidden />
</Button>
</ControlTooltip>
- <DropdownMenu>
+ <DropdownMenu onOpenChange={() => setHintReason(null)}>
<DropdownMenuTrigger
render={
<Button
@@ -176,8 +187,17 @@ export function DashboardTileFrame({
>
<SizeIcon span={tile} />
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-40">
+ <DropdownMenuContent
+ align="end"
+ sideOffset={8}
+ className={DASHBOARD_LAYOUT_MENU_CLASS}
+ >
+ <div className="shrink-0 px-2 pt-1 pb-1.5 text-[11px] font-medium">
+ {labels.sizeGroup}
+ </div>
<DropdownMenuRadioGroup
+ aria-label={labels.sizeGroup}
+ className="min-h-0 space-y-0.5 overflow-y-auto overscroll-contain"
value={currentSize}
onValueChange={(value) => {
const option = sizeOptions.find(
@@ -192,31 +212,74 @@ export function DashboardTileFrame({
{sizeOptions.map(
({ presentation, available, failureReason }) => {
const size = dashboardTileSpanKey(presentation.span)
+ const selected = size === currentSize
+ const name = t(
+ `panel.dashboard.configure.sizeLabels.${dashboardTileSizeLabel(presentation)}`
+ )
+ const dimensions = t('panel.dashboard.configure.size', {
+ width: presentation.span.w,
+ height: presentation.span.h,
+ })
+ const accessibleName = `${name} ${dimensions}`
return (
<DropdownMenuRadioItem
key={size}
value={size}
disabled={!available}
+ showIndicator={false}
+ label={name}
aria-label={
!available && failureReason
- ? `${labels.size(size, presentation)} ${labels.unavailable(failureReason)}`
- : labels.size(size, presentation)
+ ? `${accessibleName} ${labels.unavailable(failureReason)}`
+ : accessibleName
}
- className="gap-2"
+ aria-describedby={!available ? hintId : undefined}
+ onMouseEnter={() =>
+ setHintReason(failureReason ?? null)
+ }
+ onFocus={() => setHintReason(failureReason ?? null)}
+ className={cn(
+ DASHBOARD_LAYOUT_OPTION_CLASS,
+ selected && 'bg-accent/70'
+ )}
>
- <SizeIcon span={presentation.span} />
- <span>{labels.size(size, presentation)}</span>
- {!available && failureReason ? (
- <span className="ml-auto text-[10px] text-muted-foreground">
- {' · '}
- {labels.unavailable(failureReason)}
+ <DashboardLayoutPreview
+ span={presentation.span}
+ className={cn(
+ 'text-foreground',
+ !available && 'opacity-35'
+ )}
+ />
+ <span
+ className={cn(
+ 'min-w-0 flex-1',
+ !available && 'opacity-60'
+ )}
+ >
+ <span className="block text-xs leading-4 font-medium">
+ {name}
+ </span>
+ <span className="block text-[10px] leading-3.5 tabular-nums text-muted-foreground">
+ {dimensions}
</span>
+ </span>
+ {selected ? (
+ <Check
+ aria-hidden
+ className="size-3.5 text-foreground"
+ />
) : null}
</DropdownMenuRadioItem>
)
}
)}
</DropdownMenuRadioGroup>
+ {unavailableReason ? (
+ <DashboardLayoutHint
+ id={hintId}
+ reason={hintReason ?? unavailableReason}
+ />
+ ) : null}
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/src/renderer/routes/dashboard/dashboard-page.tsx b/src/renderer/routes/dashboard/dashboard-page.tsx
index 33545b63..1955368a 100644
--- a/src/renderer/routes/dashboard/dashboard-page.tsx
+++ b/src/renderer/routes/dashboard/dashboard-page.tsx
@@ -179,7 +179,8 @@ export function DashboardPage() {
<PanelShell
title={t('panel.dashboard.title')}
actions={dashboardActions}
- headerClassName="px-2"
+ headerClassName="px-2 compact-header:py-1"
+ actionsClassName="compact-header:min-h-[30px]"
contentClassName="pl-2.5 pr-2 pt-4 pb-10"
>
<DashboardGrid
diff --git a/src/renderer/routes/dashboard/layout/dashboard-presets.test.ts b/src/renderer/routes/dashboard/layout/dashboard-presets.test.ts
index 07851bdd..f2c4e046 100644
--- a/src/renderer/routes/dashboard/layout/dashboard-presets.test.ts
+++ b/src/renderer/routes/dashboard/layout/dashboard-presets.test.ts
@@ -42,37 +42,37 @@ const EXPECTED_TILES: Record<DashboardLayoutPresetId, DashboardTileLayout[]> = {
{ id: 'nat', enabled: false, x: 0, y: 0, w: 1, h: 1 },
],
taskFocus: [
- { id: 'tasks', enabled: true, x: 0, y: 0, w: 2, h: 3 },
- { id: 'engine', enabled: true, x: 2, y: 0, w: 1, h: 1 },
- { id: 'speedLimit', enabled: true, x: 3, y: 0, w: 1, h: 1 },
- { id: 'speedUp', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'speedDown', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 2, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 2, w: 1, h: 1 },
+ { id: 'engine', enabled: true, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 1, y: 0, w: 1, h: 1 },
+ { id: 'active', enabled: true, x: 2, y: 0, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 3, y: 0, w: 1, h: 1 },
+ { id: 'speedUp', enabled: true, x: 0, y: 1, w: 1, h: 1 },
+ { id: 'tasks', enabled: true, x: 1, y: 1, w: 3, h: 2 },
+ { id: 'speedDown', enabled: true, x: 0, y: 2, w: 1, h: 1 },
{ id: 'nat', enabled: false, x: 0, y: 0, w: 1, h: 1 },
{ id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
],
speedFocus: [
- { id: 'speedUp', enabled: true, x: 0, y: 0, w: 2, h: 1 },
- { id: 'speedDown', enabled: true, x: 2, y: 0, w: 2, h: 1 },
- { id: 'tasks', enabled: true, x: 0, y: 1, w: 2, h: 2 },
- { id: 'engine', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'speedLimit', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 2, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 2, w: 1, h: 1 },
+ { id: 'speedDown', enabled: true, x: 0, y: 0, w: 2, h: 2 },
+ { id: 'speedUp', enabled: true, x: 2, y: 0, w: 2, h: 2 },
+ { id: 'engine', enabled: true, x: 0, y: 2, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 1, y: 2, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 2, y: 2, w: 2, h: 1 },
+ { id: 'tasks', enabled: false, x: 0, y: 0, w: 2, h: 2 },
+ { id: 'active', enabled: false, x: 0, y: 0, w: 1, h: 1 },
{ id: 'nat', enabled: false, x: 0, y: 0, w: 1, h: 1 },
{ id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
],
compact: [
- { id: 'engine', enabled: true, x: 0, y: 0, w: 2, h: 1 },
- { id: 'speedLimit', enabled: true, x: 2, y: 0, w: 2, h: 1 },
- { id: 'speedUp', enabled: true, x: 0, y: 1, w: 1, h: 1 },
- { id: 'speedDown', enabled: true, x: 1, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'tasks', enabled: true, x: 0, y: 2, w: 2, h: 1 },
- { id: 'nat', enabled: true, x: 2, y: 2, w: 2, h: 1 },
- { id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'engine', enabled: true, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'nat', enabled: true, x: 1, y: 0, w: 1, h: 1 },
+ { id: 'speedUp', enabled: true, x: 2, y: 0, w: 1, h: 1 },
+ { id: 'speedDown', enabled: true, x: 3, y: 0, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 0, y: 1, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 1, y: 1, w: 1, h: 1 },
+ { id: 'tasks', enabled: true, x: 2, y: 1, w: 2, h: 1 },
+ { id: 'active', enabled: true, x: 0, y: 2, w: 2, h: 1 },
+ { id: 'activity', enabled: true, x: 2, y: 2, w: 2, h: 1 },
],
}
diff --git a/src/renderer/routes/dashboard/layout/dashboard-presets.ts b/src/renderer/routes/dashboard/layout/dashboard-presets.ts
index 8d886a27..dfacc1cf 100644
--- a/src/renderer/routes/dashboard/layout/dashboard-presets.ts
+++ b/src/renderer/routes/dashboard/layout/dashboard-presets.ts
@@ -12,7 +12,6 @@ export type DashboardLayoutPresetId =
export interface DashboardLayoutPreset {
id: DashboardLayoutPresetId
titleKey: string
- descriptionKey: string
layout: DashboardLayoutSettings
}
@@ -20,7 +19,6 @@ export const DASHBOARD_LAYOUT_PRESETS: readonly DashboardLayoutPreset[] = [
{
id: 'balanced',
titleKey: 'panel.dashboard.configure.presets.balanced.title',
- descriptionKey: 'panel.dashboard.configure.presets.balanced.description',
layout: {
version: 1,
columns: 4,
@@ -40,18 +38,17 @@ export const DASHBOARD_LAYOUT_PRESETS: readonly DashboardLayoutPreset[] = [
{
id: 'taskFocus',
titleKey: 'panel.dashboard.configure.presets.taskFocus.title',
- descriptionKey: 'panel.dashboard.configure.presets.taskFocus.description',
layout: {
version: 1,
columns: 4,
tiles: [
- { id: 'tasks', enabled: true, x: 0, y: 0, w: 2, h: 3 },
- { id: 'engine', enabled: true, x: 2, y: 0, w: 1, h: 1 },
- { id: 'speedLimit', enabled: true, x: 3, y: 0, w: 1, h: 1 },
- { id: 'speedUp', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'speedDown', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 2, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 2, w: 1, h: 1 },
+ { id: 'engine', enabled: true, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 1, y: 0, w: 1, h: 1 },
+ { id: 'active', enabled: true, x: 2, y: 0, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 3, y: 0, w: 1, h: 1 },
+ { id: 'speedUp', enabled: true, x: 0, y: 1, w: 1, h: 1 },
+ { id: 'tasks', enabled: true, x: 1, y: 1, w: 3, h: 2 },
+ { id: 'speedDown', enabled: true, x: 0, y: 2, w: 1, h: 1 },
{ id: 'nat', enabled: false, x: 0, y: 0, w: 1, h: 1 },
{ id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
],
@@ -60,18 +57,17 @@ export const DASHBOARD_LAYOUT_PRESETS: readonly DashboardLayoutPreset[] = [
{
id: 'speedFocus',
titleKey: 'panel.dashboard.configure.presets.speedFocus.title',
- descriptionKey: 'panel.dashboard.configure.presets.speedFocus.description',
layout: {
version: 1,
columns: 4,
tiles: [
- { id: 'speedUp', enabled: true, x: 0, y: 0, w: 2, h: 1 },
- { id: 'speedDown', enabled: true, x: 2, y: 0, w: 2, h: 1 },
- { id: 'tasks', enabled: true, x: 0, y: 1, w: 2, h: 2 },
- { id: 'engine', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'speedLimit', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 2, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 2, w: 1, h: 1 },
+ { id: 'speedDown', enabled: true, x: 0, y: 0, w: 2, h: 2 },
+ { id: 'speedUp', enabled: true, x: 2, y: 0, w: 2, h: 2 },
+ { id: 'engine', enabled: true, x: 0, y: 2, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 1, y: 2, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 2, y: 2, w: 2, h: 1 },
+ { id: 'tasks', enabled: false, x: 0, y: 0, w: 2, h: 2 },
+ { id: 'active', enabled: false, x: 0, y: 0, w: 1, h: 1 },
{ id: 'nat', enabled: false, x: 0, y: 0, w: 1, h: 1 },
{ id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
],
@@ -80,20 +76,19 @@ export const DASHBOARD_LAYOUT_PRESETS: readonly DashboardLayoutPreset[] = [
{
id: 'compact',
titleKey: 'panel.dashboard.configure.presets.compact.title',
- descriptionKey: 'panel.dashboard.configure.presets.compact.description',
layout: {
version: 1,
columns: 4,
tiles: [
- { id: 'engine', enabled: true, x: 0, y: 0, w: 2, h: 1 },
- { id: 'speedLimit', enabled: true, x: 2, y: 0, w: 2, h: 1 },
- { id: 'speedUp', enabled: true, x: 0, y: 1, w: 1, h: 1 },
- { id: 'speedDown', enabled: true, x: 1, y: 1, w: 1, h: 1 },
- { id: 'active', enabled: true, x: 2, y: 1, w: 1, h: 1 },
- { id: 'transfer', enabled: true, x: 3, y: 1, w: 1, h: 1 },
- { id: 'tasks', enabled: true, x: 0, y: 2, w: 2, h: 1 },
- { id: 'nat', enabled: true, x: 2, y: 2, w: 2, h: 1 },
- { id: 'activity', enabled: false, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'engine', enabled: true, x: 0, y: 0, w: 1, h: 1 },
+ { id: 'nat', enabled: true, x: 1, y: 0, w: 1, h: 1 },
+ { id: 'speedUp', enabled: true, x: 2, y: 0, w: 1, h: 1 },
+ { id: 'speedDown', enabled: true, x: 3, y: 0, w: 1, h: 1 },
+ { id: 'speedLimit', enabled: true, x: 0, y: 1, w: 1, h: 1 },
+ { id: 'transfer', enabled: true, x: 1, y: 1, w: 1, h: 1 },
+ { id: 'tasks', enabled: true, x: 2, y: 1, w: 2, h: 1 },
+ { id: 'active', enabled: true, x: 0, y: 2, w: 2, h: 1 },
+ { id: 'activity', enabled: true, x: 2, y: 2, w: 2, h: 1 },
],
},
},
diff --git a/src/renderer/routes/dashboard/tiles/active-tile.test.tsx b/src/renderer/routes/dashboard/tiles/active-tile.test.tsx
index 214ecfb8..49cc4a62 100644
--- a/src/renderer/routes/dashboard/tiles/active-tile.test.tsx
+++ b/src/renderer/routes/dashboard/tiles/active-tile.test.tsx
@@ -1,7 +1,7 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import { TaskStatus } from '@shared/types/task'
-import { render, screen } from '@testing-library/react'
+import { render, screen, within } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { dashboardTileViewport } from '../layout/dashboard-registry'
@@ -45,10 +45,23 @@ describe('ActiveTile', () => {
)
})
- it('renders only the primary count in compact content', () => {
+ it('adds a concise status breakdown below the primary count in compact content', () => {
render(<ActiveTile activeCount={4} viewport={compactViewport} />)
expect(screen.getByText('4')).toBeInTheDocument()
- expect(screen.queryByText(/Downloading|下载中/i)).not.toBeInTheDocument()
+ const breakdown = screen.getByTestId('active-compact-breakdown')
+ expect(
+ within(breakdown)
+ .getAllByRole('term')
+ .map((term) => term.textContent)
+ ).toEqual(['Downloading', 'Waiting', 'Seeding'])
+ expect(
+ within(breakdown)
+ .getAllByRole('definition')
+ .map((definition) => definition.textContent)
+ ).toEqual(['2', '2', '1'])
+ expect(screen.getByTestId('active-content').lastElementChild).toBe(
+ breakdown
+ )
expect(screen.queryByTestId('active-breakdown')).not.toBeInTheDocument()
})
diff --git a/src/renderer/routes/dashboard/tiles/active-tile.tsx b/src/renderer/routes/dashboard/tiles/active-tile.tsx
index ca4cf807..6339582d 100644
--- a/src/renderer/routes/dashboard/tiles/active-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/active-tile.tsx
@@ -1,7 +1,13 @@
// src/renderer/routes/dashboard/tiles/active-tile.tsx
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@renderer/components/ui/tooltip'
import { useTaskList } from '@renderer/hooks/use-task-list'
import { cn } from '@renderer/lib/utils'
import { TaskStatus } from '@shared/types/task'
+import { ArrowDown, ArrowUp, Clock3, type LucideIcon } from 'lucide-react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { StatusDot } from '../components/status-dot'
@@ -83,7 +89,28 @@ export function ActiveTile({
className="flex min-h-0 flex-1 flex-col justify-between gap-3"
>
<TileTitle value={activeCount} />
- {!compact ? (
+ {compact ? (
+ <dl
+ data-testid="active-compact-breakdown"
+ className="mt-auto flex min-w-0 items-center justify-between gap-2 text-muted-foreground"
+ >
+ <CompactStatus
+ icon={ArrowDown}
+ label={t('panel.dashboard.active.downloading')}
+ count={counts.downloading}
+ />
+ <CompactStatus
+ icon={Clock3}
+ label={t('panel.dashboard.active.waiting')}
+ count={counts.waiting}
+ />
+ <CompactStatus
+ icon={ArrowUp}
+ label={t('panel.dashboard.active.seeding')}
+ count={counts.seeding}
+ />
+ </dl>
+ ) : (
<div
data-testid="active-breakdown"
className={cn(
@@ -109,8 +136,42 @@ export function ActiveTile({
</div>
))}
</div>
- ) : null}
+ )}
</div>
</TileShell>
)
}
+
+function CompactStatus({
+ icon: Icon,
+ label,
+ count,
+}: {
+ icon: LucideIcon
+ label: string
+ count: number
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={<div className="flex min-w-0 items-center gap-1" />}
+ >
+ <dt className="shrink-0">
+ <Icon className="size-3" aria-hidden />
+ <span className="sr-only">{label}</span>
+ </dt>
+ <dd
+ className={cn(
+ 'min-w-0 truncate text-xs leading-4 tabular-nums',
+ count > 0 && 'font-medium text-foreground/80'
+ )}
+ >
+ {count}
+ </dd>
+ </TooltipTrigger>
+ <TooltipContent>
+ {label}: {count}
+ </TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/src/renderer/routes/dashboard/tiles/activity-tile.tsx b/src/renderer/routes/dashboard/tiles/activity-tile.tsx
index f05900f8..d2c89e54 100644
--- a/src/renderer/routes/dashboard/tiles/activity-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/activity-tile.tsx
@@ -80,7 +80,7 @@ export function ActivityTile({
className="flex shrink-0 items-center justify-between gap-2 pt-1 text-[9px] leading-3 text-muted-foreground"
>
<span className="min-w-0 truncate">
- {statusMessages.join(' · ')}
+ {statusMessages.join('; ')}
</span>
{activity.status === 'stale' ? (
<Button
diff --git a/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx b/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx
index 7c3e1588..e1fe076a 100644
--- a/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx
+++ b/src/renderer/routes/dashboard/tiles/nat-tile.test.tsx
@@ -5,6 +5,7 @@ import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import {
NatPortReachability,
+ NatProtocol,
NatState,
type NatStatus,
NatType,
@@ -126,33 +127,29 @@ describe('NatTile', () => {
expect(screen.getByText('NAT')).toBeInTheDocument()
})
- it('shows the Active state label', () => {
+ it('uses a concise compact label and the Engine tile status dot in the footer', () => {
natState.status = makeStatus({ state: NatState.Active })
const { container } = render(<NatTile viewport={COMPACT} />)
- const stateLabel = screen.getByText('Active')
+ const stateLabel = screen.getByText('Mapped')
expect(stateLabel).toBeInTheDocument()
- expect(stateLabel.parentElement).toHaveClass(
- 'h-8',
- 'text-[22px]',
- 'leading-none'
- )
+ expect(stateLabel.parentElement).toHaveClass('text-[22px]', 'h-8')
expect(stateLabel).toHaveClass('leading-[26px]')
- expect(screen.getByTestId('nat-hero')).toContainElement(
+ expect(screen.getByTestId('nat-hero')).not.toContainElement(
container.querySelector('[data-slot="status-dot"]')
)
- expect(
- container.querySelector('[data-slot="status-dot"]')
- ).not.toHaveAttribute('data-pulse')
+ expect(container.querySelector('[data-slot="status-dot"]')).toHaveAttribute(
+ 'data-pulse',
+ 'true'
+ )
})
- it('pulses only while NAT is transitioning', () => {
+ it('pulses while mapping and settles to a neutral dot after retries are exhausted', () => {
natState.status = makeStatus({ state: NatState.Discovering })
const { container, rerender } = render(<NatTile viewport={COMPACT} />)
-
+ expect(screen.getByText('Mapping')).toBeInTheDocument()
const dot = container.querySelector('[data-slot="status-dot"]')
- expect(dot).toHaveAttribute('data-bucket', 'settingUp')
+ expect(dot).toHaveClass('status-dot', 'bg-amber-500')
expect(dot).toHaveAttribute('data-pulse', 'true')
- expect(dot).toHaveClass('bg-blue-500')
natState.status = makeStatus({
state: NatState.Failed,
@@ -160,27 +157,36 @@ describe('NatTile', () => {
maxRetries: 3,
})
rerender(<NatTile viewport={COMPACT} />)
-
- expect(dot).toHaveAttribute('data-bucket', 'failed')
- expect(dot).not.toHaveAttribute('data-pulse')
- expect(dot).toHaveClass('bg-red-500')
+ const settledDot = container.querySelector('[data-slot="status-dot"]')
+ expect(settledDot).not.toHaveAttribute('data-pulse')
+ expect(settledDot).toHaveAttribute('data-bucket', 'failed')
+ expect(settledDot).toHaveClass('bg-muted-foreground/40')
+ expect(screen.getByText('Mapping')).toBeInTheDocument()
+ expect(screen.queryByText('Failed')).not.toBeInTheDocument()
})
it('localizes the state label to Chinese', async () => {
await i18n.changeLanguage('zh-CN')
natState.status = makeStatus({ state: NatState.Active })
render(<NatTile viewport={COMPACT} />)
- expect(screen.getByText('已激活')).toBeInTheDocument()
+ expect(screen.getByText('已映射')).toBeInTheDocument()
})
- it('shows the retry counter while retrying', () => {
+ it('keeps retries in the menu and does not offer another attempt while retrying', async () => {
natState.status = makeStatus({
state: NatState.Failed,
retryAttempt: 2,
maxRetries: 3,
})
render(<NatTile viewport={COMPACT} />)
- expect(screen.getByText('Retrying 2/3')).toBeInTheDocument()
+ expect(screen.getByText('Mapping')).toBeInTheDocument()
+ expect(screen.queryByText(/Automatic retries/)).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ expect(await screen.findByText('Automatic retries (2/3)')).toBeVisible()
+ expect(
+ screen.queryByRole('menuitem', { name: 'Retry' })
+ ).not.toBeInTheDocument()
+ expect(mockInvoke).not.toHaveBeenCalled()
})
it('shows the Off label when NAT status is unavailable', () => {
@@ -214,9 +220,6 @@ describe('NatTile', () => {
expect(summary).toHaveTextContent('Port restricted')
expect(summary).toHaveTextContent('Mappings')
expect(summary).toHaveTextContent('0 active')
- const controls = screen.getByRole('group', { name: 'NAT controls' })
- expect(screen.getByTestId('nat-hero')).toContainElement(controls)
- expect(summary).not.toContainElement(controls)
for (const item of [
...within(summary).getAllByRole('term'),
...within(summary).getAllByRole('definition'),
@@ -272,69 +275,112 @@ describe('NatTile', () => {
expect(within(details).getAllByRole('term')).toHaveLength(5)
expect(within(details).getAllByRole('definition')).toHaveLength(5)
expect(screen.getByTestId('nat-metric-external-ip')).toHaveClass(
- 'col-span-2'
+ 'col-span-full'
)
})
- it('keeps the featured metric and two-column hierarchy when tall', () => {
+ it('stacks diagnostic fields in one column in the narrow tall presentation', () => {
render(<NatTile viewport={TALL_DETAILED} />)
- expect(screen.getByTestId('nat-details')).toHaveClass('grid-cols-2')
+ expect(screen.getByTestId('nat-details')).toHaveClass('grid-cols-1')
expect(screen.getByTestId('nat-details')).toHaveAttribute(
'data-orientation',
'tall'
)
expect(screen.getByTestId('nat-metric-external-ip')).toHaveClass(
- 'col-span-2'
+ 'col-span-full'
)
})
- it('keeps only the toggle in compact and uses concise focus action text', () => {
- const { rerender } = render(<NatTile viewport={COMPACT} />)
+ it.each([SUMMARY, TALL_DETAILED, SQUARE_DETAILED, FOCUS])(
+ 'replaces stale diagnostic fields with a quiet empty state when off in $contentLevel',
+ (viewport) => {
+ natState.status = makeStatus({
+ enabled: false,
+ lastDiagnostic: {
+ runAt: Date.now(),
+ natType: NatType.Open,
+ gatewayInfo: null,
+ portReachability: {
+ btListenPort: NatPortReachability.Reachable,
+ dhtListenPort: NatPortReachability.Reachable,
+ },
+ protocolAvailability: { pcp: true, natpmp: true, upnp: true },
+ healthScore: 'good',
+ recommendations: [],
+ },
+ })
+ render(<NatTile viewport={viewport} />)
- expect(screen.queryByTestId('nat-actions')).not.toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'Disable NAT' })
- ).toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'Run diagnostic' })
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('link', { name: 'NAT settings' })
- ).not.toBeInTheDocument()
+ expect(screen.getByText('Off')).toBeInTheDocument()
+ expect(screen.getByTestId('nat-empty')).toHaveTextContent(
+ 'BT port mapping is off.'
+ )
+ expect(screen.queryByText('Good')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('nat-details')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('nat-summary')).not.toBeInTheDocument()
+ }
+ )
- rerender(<NatTile viewport={FOCUS} />)
+ it('adds protocol and port details only in the full-height presentation', () => {
+ natState.status = makeStatus({
+ activeMappings: [
+ {
+ purpose: 'bt-listen',
+ protocol: 'TCP',
+ method: NatProtocol.Upnp,
+ internalPort: 6881,
+ externalPort: 16881,
+ ttl: 3600,
+ expiresAt: Date.now() + 3600_000,
+ createdAt: Date.now(),
+ lastRenewedAt: Date.now(),
+ },
+ ],
+ })
+ const { rerender } = render(<NatTile viewport={SQUARE_DETAILED} />)
+ expect(screen.queryByTestId('nat-mapping-list')).not.toBeInTheDocument()
- expect(screen.getByTestId('nat-actions').children).toHaveLength(3)
- expect(
- screen.getByRole('group', { name: 'NAT controls' })
- ).toBeInTheDocument()
+ rerender(<NatTile viewport={FOCUS} />)
+ const mappings = screen.getByRole('region', { name: 'Mapped ports' })
+ expect(within(mappings).getByText('BitTorrent')).toBeInTheDocument()
+ expect(within(mappings).getByText('TCP / UPnP')).toBeInTheDocument()
expect(
- screen.getByRole('link', { name: 'NAT settings' })
+ within(mappings).getByText('Internal 6881 to external 16881')
).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'Disable NAT' })
- ).toHaveTextContent(/^Disable$/)
- expect(
- screen.getByRole('button', { name: 'Force remap' })
- ).toHaveTextContent(/^Remap$/)
- expect(
- screen.getByRole('button', { name: 'Run diagnostic' })
- ).toHaveTextContent(/^Diagnose$/)
})
- it('localizes concise focus action text without shortening accessible names', async () => {
- await i18n.changeLanguage('zh-CN')
- render(<NatTile viewport={FOCUS} />)
+ it.each([COMPACT, SUMMARY, TALL_DETAILED, SQUARE_DETAILED, FOCUS])(
+ 'offers the same controls in $contentLevel presentations',
+ async (viewport) => {
+ render(<NatTile viewport={viewport} />)
+ expect(screen.queryByTestId('nat-actions')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ expect(
+ await screen.findByRole('menuitem', { name: 'Network settings' })
+ ).toHaveAttribute('href', '/settings/network')
+ expect(
+ screen.getByRole('menuitem', { name: 'Network guide' })
+ ).toBeVisible()
+ expect(
+ screen.getByRole('menuitem', { name: 'Turn off NAT mapping' })
+ ).toBeVisible()
+ expect(
+ screen.queryByRole('menuitem', { name: 'Retry' })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.getByText(/Helps other BT peers connect to you/)
+ ).toBeVisible()
+ }
+ )
- expect(screen.getByRole('button', { name: '禁用 NAT' })).toHaveTextContent(
- /^禁用$/
- )
- expect(
- screen.getByRole('button', { name: '强制重映射' })
- ).toHaveTextContent(/^重映射$/)
- expect(screen.getByRole('button', { name: '运行诊断' })).toHaveTextContent(
- /^诊断$/
+ it('localizes the shared menu and guide', async () => {
+ await i18n.changeLanguage('zh-CN')
+ render(<NatTile viewport={COMPACT} />)
+ fireEvent.click(screen.getByRole('button', { name: 'NAT 控制' }))
+ fireEvent.click(await screen.findByRole('menuitem', { name: '优化网络' }))
+ expect(openExternalMock).toHaveBeenCalledWith(
+ EXTERNAL_URLS.motrix.manual.natTroubleshooting.zh
)
})
@@ -361,42 +407,73 @@ describe('NatTile', () => {
expect(screen.getByText(ipv6)).toHaveAttribute('title', ipv6)
})
- it('runs a diagnostic when the diagnose action is clicked', () => {
- render(<NatTile viewport={SQUARE_DETAILED} />)
- fireEvent.click(screen.getByRole('button', { name: 'Run diagnostic' }))
- expect(mockInvoke).toHaveBeenCalledWith(Commands.RunNatDiagnostic)
- })
-
- it('forces a remap when the remap action is clicked', () => {
- render(<NatTile viewport={SQUARE_DETAILED} />)
- fireEvent.click(screen.getByRole('button', { name: 'Force remap' }))
- expect(mockInvoke).toHaveBeenCalledWith(Commands.ForceRemapNat)
+ it('disables NAT from the menu when running', async () => {
+ render(<NatTile viewport={COMPACT} />)
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'Turn off NAT mapping' })
+ )
+ expect(mockInvoke).toHaveBeenCalledExactlyOnceWith(Commands.DisableNat)
})
- it('disables NAT via the toggle when running', () => {
- natState.status = makeStatus({ state: NatState.Active })
+ it('enables NAT from the menu when disabled even if the last state was active', async () => {
+ natState.status = makeStatus({ enabled: false })
render(<NatTile viewport={COMPACT} />)
- fireEvent.click(screen.getByRole('button', { name: 'Disable NAT' }))
- expect(mockInvoke).toHaveBeenCalledWith(Commands.DisableNat)
+ expect(screen.getByText('Off')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ expect(
+ screen.queryByRole('menuitem', { name: 'Turn off NAT mapping' })
+ ).not.toBeInTheDocument()
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Enable NAT' }))
+ expect(mockInvoke).toHaveBeenCalledExactlyOnceWith(Commands.EnableNat)
})
- it('enables NAT via the toggle when stopped', () => {
- natState.status = makeStatus({ state: NatState.Stopped })
+ it('waits for the status snapshot before offering an enable action', async () => {
+ natState.status = null
render(<NatTile viewport={COMPACT} />)
- fireEvent.click(screen.getByRole('button', { name: 'Enable NAT' }))
- expect(mockInvoke).toHaveBeenCalledWith(Commands.EnableNat)
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ expect(
+ await screen.findByRole('menuitem', { name: 'Network settings' })
+ ).toBeVisible()
+ expect(
+ screen.queryByRole('menuitem', { name: 'Enable NAT' })
+ ).not.toBeInTheDocument()
})
- it('offers the official troubleshooting guide in the terminal failed state', () => {
+ it.each([
+ ['Retry', Commands.EnableNat],
+ ['Turn off NAT mapping', Commands.DisableNat],
+ ])(
+ 'offers %s after the retry budget is exhausted',
+ async (action, command) => {
+ natState.status = makeStatus({
+ state: NatState.Failed,
+ retryAttempt: 3,
+ maxRetries: 3,
+ })
+ render(<NatTile viewport={COMPACT} />)
+ expect(mockInvoke).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ expect(
+ await screen.findByText('Automatic mapping unavailable')
+ ).toBeVisible()
+ expect(screen.getByText(/link downloads/)).toBeVisible()
+ expect(screen.getByText('Automatic retries (3/3)')).toBeVisible()
+ fireEvent.click(screen.getByRole('menuitem', { name: action }))
+ expect(mockInvoke).toHaveBeenCalledExactlyOnceWith(command)
+ }
+ )
+
+ it('offers the official troubleshooting guide in the terminal failed state', async () => {
natState.status = makeStatus({
state: NatState.Failed,
retryAttempt: 3,
maxRetries: 3,
})
render(<NatTile viewport={SQUARE_DETAILED} />)
-
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
fireEvent.click(
- screen.getByRole('button', { name: 'NAT troubleshooting guide' })
+ await screen.findByRole('menuitem', { name: 'Network guide' })
)
expect(openExternalMock).toHaveBeenCalledWith(
EXTERNAL_URLS.motrix.manual.natTroubleshooting.en
@@ -406,7 +483,10 @@ describe('NatTile', () => {
it('toasts when a command is rate limited', async () => {
mockInvoke.mockResolvedValue({ ok: false, error: ErrorCode.IpcRateLimited })
render(<NatTile viewport={SQUARE_DETAILED} />)
- fireEvent.click(screen.getByRole('button', { name: 'Run diagnostic' }))
+ fireEvent.click(screen.getByRole('button', { name: 'NAT controls' }))
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'Turn off NAT mapping' })
+ )
await waitFor(() =>
expect(toastAddMock).toHaveBeenCalledWith(
expect.objectContaining({
diff --git a/src/renderer/routes/dashboard/tiles/nat-tile.tsx b/src/renderer/routes/dashboard/tiles/nat-tile.tsx
index 4cacc9cd..92c65d9d 100644
--- a/src/renderer/routes/dashboard/tiles/nat-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/nat-tile.tsx
@@ -1,52 +1,23 @@
-// src/renderer/routes/dashboard/tiles/nat-tile.tsx
-
import { Button } from '@renderer/components/ui/button'
-import { toast } from '@renderer/components/ui/toast'
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from '@renderer/components/ui/tooltip'
+import { DropdownMenuTrigger } from '@renderer/components/ui/dropdown-menu'
+import { NatStatusMenu } from '@renderer/features/nat/nat-status-menu'
+import { useMinuteClock } from '@renderer/hooks/use-minute-clock'
import { useNatStatus } from '@renderer/hooks/use-nat-status'
-import {
- isNatRetrying,
- isNatRunning,
- type NatBucket,
- natBucket,
-} from '@renderer/lib/nat-status'
-import { transport } from '@renderer/lib/transport'
+import { NAT_STATUS_TEXT_KEY, natBucket } from '@renderer/lib/nat-status'
+import { formatRelativeTime } from '@renderer/lib/relative-time'
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, BookOpen, Power, RefreshCw, Settings2 } from 'lucide-react'
-import type { ComponentType } from 'react'
-import { useCallback } from 'react'
+import { type NatMapping, NatProtocol } from '@shared/types/nat'
+import { ArrowRight, Ellipsis, Router } from 'lucide-react'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
import { StatusDot } from '../components/status-dot'
import { TileShell } from '../components/tile-shell'
import { TileTitle } from '../components/tile-title'
import type { DashboardTileViewport } from '../layout/dashboard-registry'
-const STATE_TEXT_KEY: Record<NatBucket, string> = {
- active: 'panel.dashboard.nat.state.active',
- settingUp: 'panel.dashboard.nat.state.settingUp',
- failed: 'panel.dashboard.nat.state.failed',
- off: 'panel.dashboard.nat.state.off',
-}
-
-function formatRelative(ms: number, lang: string): string {
- const rtf = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' })
- const deltaMs = ms - Date.now()
- const absSec = Math.abs(deltaMs) / 1000
- if (absSec < 60) return rtf.format(Math.round(deltaMs / 1000), 'seconds')
- if (absSec < 3600) return rtf.format(Math.round(deltaMs / 60_000), 'minutes')
- if (absSec < 86_400)
- return rtf.format(Math.round(deltaMs / 3_600_000), 'hours')
- return rtf.format(Math.round(deltaMs / 86_400_000), 'days')
+const MAPPING_METHOD_LABELS: Record<NatProtocol, string> = {
+ [NatProtocol.Pcp]: 'PCP',
+ [NatProtocol.NatPmp]: 'NAT-PMP',
+ [NatProtocol.Upnp]: 'UPnP',
}
export interface NatTileProps {
@@ -54,14 +25,6 @@ export interface NatTileProps {
className?: string
}
-interface NatAction {
- key: string
- Icon: ComponentType<{ className?: string }>
- label: string
- shortLabel: string
- run: () => void
-}
-
export function NatTile({ viewport, className }: NatTileProps) {
return __MOTRIX_TARGET__ === 'electron' ? (
<ElectronNatTile viewport={viewport} className={className} />
@@ -70,235 +33,208 @@ export function NatTile({ viewport, className }: NatTileProps) {
function ElectronNatTile({ viewport, className }: NatTileProps) {
const { t, i18n } = useTranslation()
- const services = usePlatformServices()
const status = useNatStatus()
+ const now = useMinuteClock()
const compact = viewport.contentLevel === 'compact'
const summary = viewport.contentLevel === 'summary'
- const showDetails =
- viewport.contentLevel === 'detailed' || viewport.contentLevel === 'focus'
+ const narrow = viewport.span.w === 1
const focus = viewport.contentLevel === 'focus'
-
- const { bucket, color } = natBucket(status)
- const failed = bucket === 'failed'
- const stateLabel =
- status && isNatRetrying(status)
- ? t('panel.dashboard.nat.retrying', {
- attempt: status.retryAttempt,
- max: status.maxRetries,
- })
- : t(STATE_TEXT_KEY[bucket])
- const running = isNatRunning(status)
-
- const runCommand = useCallback(
- async (channel: CommandChannel) => {
- const res = (await transport.invoke(channel)) as
- | { ok?: boolean; error?: string }
- | undefined
- if (res && res.ok === false && res.error === ErrorCode.IpcRateLimited) {
- toast.add({
- title: t('panel.dashboard.nat.rateLimited'),
- type: 'error',
- })
- }
- },
- [t]
+ const detailed = !compact && !summary
+ const { bucket } = natBucket(status)
+ const stateLabel = t(
+ narrow
+ ? `panel.dashboard.nat.compact.state.${bucket}`
+ : NAT_STATUS_TEXT_KEY[bucket]
)
-
+ const diagnostic = status?.lastDiagnostic
+ const gateway = status?.gatewayInfo ?? diagnostic?.gatewayInfo
+ const mappings = status?.activeMappings ?? []
+ const hasDetails =
+ bucket !== 'off' &&
+ (bucket === 'active' || gateway || diagnostic || mappings.length > 0)
const none = t('panel.dashboard.nat.none')
- const natType = status?.lastDiagnostic?.natType
- const typeLabel = natType ? t(`panel.dashboard.nat.natType.${natType}`) : none
- const externalIp = status?.gatewayInfo?.externalIp ?? none
- const mappingsCount = status?.activeMappings.length ?? 0
- const health = status?.lastDiagnostic?.healthScore
+ const typeLabel = diagnostic?.natType
+ ? t(`panel.dashboard.nat.natType.${diagnostic.natType}`)
+ : none
const healthLabel = t(
- `panel.dashboard.nat.healthScore.${health ?? 'unknown'}`
+ `panel.dashboard.nat.healthScore.${diagnostic?.healthScore ?? 'unknown'}`
)
- const lastCheck = status?.lastDiagnostic?.runAt
- ? formatRelative(status.lastDiagnostic.runAt, i18n.language)
+ const lastCheck = diagnostic?.runAt
+ ? formatRelativeTime(diagnostic.runAt, now, i18n.language)
: t('panel.dashboard.nat.lastCheckNever')
-
- const toggleLabel = running
- ? t('panel.dashboard.nat.actions.disable')
- : t('panel.dashboard.nat.actions.enable')
- const toggleShortLabel = running
- ? t('panel.dashboard.nat.actions.short.disable')
- : t('panel.dashboard.nat.actions.short.enable')
- const actions: NatAction[] = [
- {
- key: 'toggle',
- Icon: Power,
- label: toggleLabel,
- shortLabel: toggleShortLabel,
- run: () =>
- void runCommand(running ? Commands.DisableNat : Commands.EnableNat),
- },
- {
- key: 'remap',
- Icon: RefreshCw,
- label: t('panel.dashboard.nat.actions.remap'),
- shortLabel: t('panel.dashboard.nat.actions.short.remap'),
- run: () => void runCommand(Commands.ForceRemapNat),
- },
- {
- key: 'diagnose',
- Icon: Activity,
- label: t('panel.dashboard.nat.actions.diagnose'),
- shortLabel: t('panel.dashboard.nat.actions.short.diagnose'),
- 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)
- ),
- })
- }
+ const caption = compact
+ ? t(`panel.dashboard.nat.compact.caption.${status ? bucket : 'waiting'}`, {
+ count: mappings.length,
+ })
+ : status
+ ? bucket === 'active'
+ ? t('panel.dashboard.nat.mappingsValue', { count: mappings.length })
+ : t(`panel.dashboard.nat.caption.${bucket}`)
+ : t('panel.dashboard.nat.caption.waiting')
+ const statusDot = (
+ <StatusDot
+ data-bucket={bucket}
+ pulse={bucket === 'active' || bucket === 'settingUp'}
+ className={cn(
+ bucket === 'active'
+ ? 'bg-emerald-500'
+ : bucket === 'settingUp'
+ ? 'bg-amber-500'
+ : 'bg-muted-foreground/40'
+ )}
+ />
+ )
return (
<TileShell
label={t('panel.dashboard.nat.title')}
className={className}
+ bodyClassName="@container/nat"
action={
- compact ? (
- <Button
- type="button"
- size="icon-xs"
- variant="ghost"
- className="cursor-default"
- aria-label={toggleLabel}
- onClick={actions[0]?.run}
- >
- <Power className="size-3.5" aria-hidden />
- </Button>
- ) : (
- <Button
- size="icon-xs"
- variant="ghost"
- className="cursor-default"
+ <NatStatusMenu status={status}>
+ <DropdownMenuTrigger
render={
- <Link
- to="/settings/network"
- role="link"
- aria-label={t('panel.dashboard.nat.actions.settings')}
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ aria-label={t('panel.dashboard.nat.actions.group')}
/>
}
- nativeButton={false}
>
- <Settings2 className="size-3.5 text-muted-foreground" aria-hidden />
- </Button>
- )
+ <Ellipsis className="size-3.5 text-muted-foreground" aria-hidden />
+ </DropdownMenuTrigger>
+ </NatStatusMenu>
}
>
<div
data-testid="nat-hero"
- className={cn(
- 'flex min-w-0 items-center gap-2.5 pt-0.5',
- compact && 'mt-auto',
- summary && 'justify-between'
- )}
+ className="flex min-h-8 shrink-0 items-center"
>
- <div className="flex min-w-0 flex-1 items-center gap-2.5">
- <StatusDot
- data-bucket={bucket}
- pulse={bucket === 'settingUp'}
- className={cn(color, compact && 'size-3')}
- />
- <div className="min-w-0 flex-1">
- <TileTitle variant="text" title={stateLabel}>
- {stateLabel}
- </TileTitle>
- </div>
- </div>
- {summary ? (
- <NatActions
- actions={actions}
- label={t('panel.dashboard.nat.actions.group')}
- summary
- />
- ) : null}
+ <TileTitle variant="text" title={stateLabel}>
+ {stateLabel}
+ </TileTitle>
</div>
- {summary ? (
- <dl
- data-testid="nat-summary"
- className="mt-auto grid min-w-0 grid-cols-3 pt-3"
- >
- <Metric
- label={t('panel.dashboard.nat.health')}
- value={healthLabel}
- compact
- />
- <Metric
- label={t('panel.dashboard.nat.type')}
- value={typeLabel}
- compact
- divided
- />
- <Metric
- label={t('panel.dashboard.nat.mappings')}
- value={t('panel.dashboard.nat.mappingsValue', {
- count: mappingsCount,
- })}
- compact
- divided
- />
- </dl>
- ) : null}
-
- {showDetails ? (
- <dl
- data-testid="nat-details"
- data-content-level={viewport.contentLevel}
- data-orientation={viewport.orientation}
+ {compact ? (
+ <div className="mt-auto flex items-end justify-between gap-3 pt-2">
+ <p className="text-[11px] leading-snug text-muted-foreground">
+ {caption}
+ </p>
+ {statusDot}
+ </div>
+ ) : !hasDetails ? (
+ <div
+ data-testid="nat-empty"
className={cn(
- 'mt-4 grid min-h-0 flex-1 grid-cols-2 grid-rows-[auto_minmax(0,1fr)_minmax(0,1fr)] gap-x-5 gap-y-3',
- focus && 'gap-x-8 gap-y-4'
+ 'flex min-h-0 flex-1 text-muted-foreground',
+ summary
+ ? 'items-end justify-between gap-3 pt-2'
+ : 'flex-col items-center justify-center gap-3'
)}
>
- <Metric
- testId="nat-metric-external-ip"
- label={t('panel.dashboard.nat.externalIp')}
- value={externalIp}
- featured
- focus={focus}
- />
- <Metric
- label={t('panel.dashboard.nat.health')}
- value={healthLabel}
- focus={focus}
- />
- <Metric
- label={t('panel.dashboard.nat.type')}
- value={typeLabel}
- focus={focus}
- divided
- />
- <Metric
- label={t('panel.dashboard.nat.mappings')}
- value={String(mappingsCount)}
- focus={focus}
- />
- <Metric
- label={t('panel.dashboard.nat.lastCheck')}
- value={lastCheck}
- focus={focus}
- divided
- />
- </dl>
- ) : null}
-
- {showDetails ? (
- <NatActions
- actions={actions}
- label={t('panel.dashboard.nat.actions.group')}
- focus={focus}
- />
+ {detailed ? (
+ <div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-muted/50">
+ <Router className="size-6 stroke-[1.5]" aria-hidden />
+ </div>
+ ) : null}
+ <p
+ className={cn(
+ 'max-w-60 text-xs leading-relaxed',
+ detailed && 'text-center'
+ )}
+ >
+ {caption}
+ </p>
+ {summary ? statusDot : null}
+ </div>
+ ) : summary ? (
+ <div className="mt-auto flex items-end gap-3 pt-2">
+ <dl
+ data-testid="nat-summary"
+ className="grid min-w-0 flex-1 grid-cols-3 gap-3"
+ >
+ <Metric
+ label={t('panel.dashboard.nat.health')}
+ value={healthLabel}
+ dense
+ />
+ <Metric
+ label={t('panel.dashboard.nat.type')}
+ value={typeLabel}
+ dense
+ />
+ <Metric
+ label={t('panel.dashboard.nat.mappings')}
+ value={t('panel.dashboard.nat.mappingsValue', {
+ count: mappings.length,
+ })}
+ dense
+ />
+ </dl>
+ {statusDot}
+ </div>
+ ) : (
+ <div className="mt-3 flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto">
+ <dl
+ data-testid="nat-details"
+ data-content-level={viewport.contentLevel}
+ data-orientation={viewport.orientation}
+ className={cn(
+ 'grid min-w-0',
+ narrow
+ ? 'shrink-0 grid-cols-1 gap-0'
+ : 'grid-cols-2 gap-x-5 gap-y-4',
+ !narrow && (focus ? 'shrink-0' : 'flex-1 content-between')
+ )}
+ >
+ <Metric
+ testId="nat-metric-external-ip"
+ label={t('panel.dashboard.nat.externalIp')}
+ value={gateway?.externalIp ?? none}
+ featured
+ className={cn('col-span-full', narrow && 'mb-3')}
+ />
+ {focus ? (
+ <>
+ <Metric
+ label={t('panel.dashboard.nat.internalIp')}
+ value={gateway?.internalIp ?? none}
+ />
+ <Metric
+ label={t('panel.dashboard.nat.gatewayIp')}
+ value={gateway?.gatewayIp ?? none}
+ />
+ </>
+ ) : null}
+ <Metric
+ label={t('panel.dashboard.nat.health')}
+ value={healthLabel}
+ inline={narrow}
+ />
+ <Metric
+ label={t('panel.dashboard.nat.type')}
+ value={typeLabel}
+ inline={narrow}
+ />
+ <Metric
+ label={t('panel.dashboard.nat.mappings')}
+ value={t('panel.dashboard.nat.mappingsValue', {
+ count: mappings.length,
+ })}
+ inline={narrow}
+ />
+ <Metric
+ label={t('panel.dashboard.nat.lastCheck')}
+ value={lastCheck}
+ inline={narrow}
+ />
+ </dl>
+ {focus ? <MappingList mappings={mappings} /> : null}
+ </div>
+ )}
+ {detailed ? (
+ <div className="flex shrink-0 justify-end pt-3">{statusDot}</div>
) : null}
</TileShell>
)
@@ -308,48 +244,49 @@ function Metric({
label,
value,
testId,
- compact = false,
featured = false,
- focus = false,
- divided = false,
+ inline = false,
+ dense = false,
+ className,
}: {
label: string
value: string
testId?: string
- compact?: boolean
featured?: boolean
- focus?: boolean
- divided?: boolean
+ inline?: boolean
+ dense?: boolean
+ className?: string
}) {
return (
<div
data-testid={testId}
className={cn(
'min-w-0',
- featured
- ? 'col-span-2 rounded-xl bg-muted/40 px-3.5 py-3 ring-1 ring-inset ring-foreground/5'
- : 'flex flex-col justify-center py-2',
- featured && focus && 'px-4 py-4',
- divided && !featured && 'border-l border-border/70 pl-4'
+ featured && 'rounded-xl bg-muted/40 px-3 py-2.5',
+ inline &&
+ 'grid grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)] items-baseline gap-2 border-b border-border/50 py-2.5 last:border-0',
+ className
)}
>
- <dt className="whitespace-nowrap text-[10px] leading-none font-medium tracking-[0.04em] text-muted-foreground uppercase">
+ <dt
+ className={cn(
+ 'text-[10px] font-medium tracking-[0.04em] text-muted-foreground uppercase',
+ dense ? 'leading-3' : 'leading-4'
+ )}
+ >
{label}
</dt>
<dd
title={value}
className={cn(
- 'mt-1.5 block min-w-0 font-medium tracking-[-0.01em] text-foreground',
- featured ? 'break-all' : 'break-words',
- compact
- ? 'text-[14px]'
- : featured
- ? focus
- ? 'text-[22px]'
- : 'text-[18px]'
- : focus
- ? 'text-[17px]'
- : 'text-[15px]'
+ 'min-w-0 font-medium text-foreground',
+ featured
+ ? 'mt-1 break-all font-mono text-[clamp(0.75rem,8cqi,1rem)] leading-5'
+ : inline
+ ? 'break-words text-right text-xs leading-4'
+ : dense
+ ? 'mt-1 break-words text-xs leading-4'
+ : 'mt-1 break-words text-sm leading-5'
)}
>
{value}
@@ -358,60 +295,54 @@ function Metric({
)
}
-function NatActions({
- actions,
- label,
- summary = false,
- focus = false,
-}: {
- actions: NatAction[]
- label: string
- summary?: boolean
- focus?: boolean
-}) {
+function MappingList({ mappings }: { mappings: readonly NatMapping[] }) {
+ const { t } = useTranslation()
return (
- <TooltipProvider delay={300}>
- <fieldset
- data-testid="nat-actions"
- aria-label={label}
- className={cn(
- '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'
- )}
- >
- {actions.map((action, index) => (
- <Tooltip key={action.key}>
- <TooltipTrigger
- render={
- <Button
- type="button"
- size={summary ? 'icon-xs' : focus ? 'sm' : 'icon-sm'}
- variant="ghost"
- aria-label={action.label}
- onClick={action.run}
- className={cn(
- 'min-w-0 cursor-default rounded-md text-muted-foreground transition-[background-color,color,transform] duration-100 ease-out hover:bg-background/80 hover:text-foreground active:scale-[0.97] motion-reduce:transform-none motion-reduce:transition-none dark:hover:bg-background/35',
- summary && 'size-7',
- !summary && 'w-full',
- focus && 'h-9 gap-1.5 px-2',
- index === 0 &&
- 'bg-background/75 text-foreground shadow-xs dark:bg-background/30'
- )}
- />
- }
+ <section
+ data-testid="nat-mapping-list"
+ aria-label={t('panel.dashboard.nat.mappingDetails')}
+ className="min-w-0 border-t border-border/60 pt-3"
+ >
+ <h3 className="text-[10px] font-medium uppercase tracking-[0.04em] text-muted-foreground">
+ {t('panel.dashboard.nat.mappingDetails')}
+ </h3>
+ {mappings.length > 0 ? (
+ <ul className="mt-2 space-y-2">
+ {mappings.map((mapping) => (
+ <li
+ key={`${mapping.purpose}:${mapping.protocol}:${mapping.internalPort}:${mapping.externalPort}`}
+ className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 rounded-lg bg-muted/35 px-3 py-2"
>
- <action.Icon className="size-4" aria-hidden />
- {focus ? (
- <span className="whitespace-nowrap text-xs">
- {action.shortLabel}
+ <div className="min-w-0">
+ <p className="text-xs font-medium">
+ {t(`panel.dashboard.nat.mappingPurpose.${mapping.purpose}`)}
+ </p>
+ <p className="mt-0.5 text-[10px] text-muted-foreground">
+ {mapping.protocol} / {MAPPING_METHOD_LABELS[mapping.method]}
+ </p>
+ </div>
+ <div className="flex items-center gap-1.5 font-mono text-xs tabular-nums">
+ <span className="sr-only">
+ {t('panel.dashboard.nat.portMapping', {
+ internal: mapping.internalPort,
+ external: mapping.externalPort,
+ })}
</span>
- ) : null}
- </TooltipTrigger>
- <TooltipContent>{action.label}</TooltipContent>
- </Tooltip>
- ))}
- </fieldset>
- </TooltipProvider>
+ <span aria-hidden>{mapping.internalPort}</span>
+ <ArrowRight
+ className="size-3 text-muted-foreground"
+ aria-hidden
+ />
+ <span aria-hidden>{mapping.externalPort}</span>
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="mt-2 text-xs text-muted-foreground">
+ {t('panel.dashboard.nat.noMappings')}
+ </p>
+ )}
+ </section>
)
}
diff --git a/src/renderer/routes/downloads/engine-badge.tsx b/src/renderer/routes/downloads/engine-badge.tsx
index 0473163d..b685109b 100644
--- a/src/renderer/routes/downloads/engine-badge.tsx
+++ b/src/renderer/routes/downloads/engine-badge.tsx
@@ -1,4 +1,5 @@
import { Badge } from '@renderer/components/ui/badge'
+import { requestEngineDiagnostics } from '@renderer/features/engine-diagnostics/controller'
import { useEngineDisplayStatus } from '@renderer/hooks/use-engine-display-status'
import { cn } from '@renderer/lib/utils'
import { useTranslation } from 'react-i18next'
@@ -13,6 +14,9 @@ export function EngineBadge() {
? t('panel.downloads.stats.engineStarting')
: t('panel.downloads.stats.engineOffline')
const connectionText = connection ? t(`panel.connection.${connection}`) : null
+ const statusTitle = connectionText
+ ? `${engineText}, ${connectionText}`
+ : engineText
const text =
state === 'failed' || state === 'stopped'
? engineText
@@ -29,12 +33,18 @@ export function EngineBadge() {
: 'bg-gray-500'
return (
<Badge
+ render={<button type="button" />}
variant="secondary"
- title={connectionText ? `${engineText} · ${connectionText}` : engineText}
- role="status"
+ className="app-no-drag cursor-pointer select-none hover:bg-secondary/80 focus-visible:outline-none"
+ aria-haspopup="dialog"
+ title={`${t('panel.dashboard.engine.diagnostics.title')}: ${statusTitle}`}
+ onClick={requestEngineDiagnostics}
>
- <span className={cn('flex size-2 rounded-full mr-2', dot)} />
- {text}
+ <span
+ aria-hidden="true"
+ className={cn('flex size-2 rounded-full mr-2', dot)}
+ />
+ <span role="status">{text}</span>
</Badge>
)
}
diff --git a/src/renderer/routes/downloads/nat-badge.tsx b/src/renderer/routes/downloads/nat-badge.tsx
index 238a01bf..f8dfc92a 100644
--- a/src/renderer/routes/downloads/nat-badge.tsx
+++ b/src/renderer/routes/downloads/nat-badge.tsx
@@ -1,63 +1,27 @@
import { Badge } from '@renderer/components/ui/badge'
+import { DropdownMenuTrigger } from '@renderer/components/ui/dropdown-menu'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from '@renderer/components/ui/dropdown-menu'
-import { Spinner } from '@renderer/components/ui/spinner'
+ NatStatusIndicator,
+ NatStatusMenu,
+} from '@renderer/features/nat/nat-status-menu'
import { useNatStatus } from '@renderer/hooks/use-nat-status'
-import { type NatBucket, natBucket } 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 { NAT_STATUS_TEXT_KEY, natBucket } from '@renderer/lib/nat-status'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
-
-const TEXT_KEY: Record<NatBucket, string> = {
- active: 'panel.downloads.stats.natActive',
- settingUp: 'panel.downloads.stats.natSettingUp',
- failed: 'panel.downloads.stats.natMapping',
- off: 'panel.downloads.stats.natMapping',
-}
export function NatBadge() {
return __MOTRIX_TARGET__ === 'electron' ? <ElectronNatBadge /> : null
}
function ElectronNatBadge() {
- const { t, i18n } = useTranslation()
- const services = usePlatformServices()
+ const { t } = useTranslation()
const status = useNatStatus()
const { bucket } = natBucket(status)
- const color = bucket === 'active' ? 'bg-green-500' : 'bg-muted-foreground'
- const badgeText = t(TEXT_KEY[bucket])
- const detailText =
- bucket === 'failed' ? t('panel.downloads.stats.natUnavailable') : badgeText
-
- const handleEnable = useCallback(() => {
- void transport.invoke(Commands.EnableNat)
- }, [])
- const handleDisable = useCallback(() => {
- void transport.invoke(Commands.DisableNat)
- }, [])
- const troubleshootingUrl = getNatTroubleshootingUrl(
- i18n.resolvedLanguage ?? i18n.language
- )
- const handleHelp = useCallback(() => {
- void services.openExternal(troubleshootingUrl)
- }, [services, troubleshootingUrl])
+ const badgeText = t(NAT_STATUS_TEXT_KEY[bucket])
- if (!status?.enabled || bucket === 'off') return null
+ if (bucket === 'off') return null
return (
- <DropdownMenu>
+ <NatStatusMenu status={status}>
<DropdownMenuTrigger
nativeButton={false}
render={
@@ -68,62 +32,12 @@ function ElectronNatBadge() {
/>
}
>
- {bucket === 'settingUp' ? (
- <Spinner
- aria-hidden="true"
- className="mr-1.5 size-3 text-muted-foreground motion-reduce:animate-none"
- />
- ) : (
- <span
- aria-hidden="true"
- className={cn('size-2 rounded-full mr-2', color)}
- />
- )}
+ <NatStatusIndicator
+ status={status}
+ className={bucket === 'settingUp' ? 'mr-1.5' : 'mr-2'}
+ />
{badgeText}
</DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="w-52 max-w-[calc(100vw-2rem)]"
- >
- <DropdownMenuGroup>
- <DropdownMenuLabel className="space-y-1 whitespace-normal text-xs font-normal">
- <p className="font-medium text-foreground">{detailText}</p>
- {bucket === 'active' || bucket === 'failed' ? (
- <p className="leading-relaxed text-muted-foreground">
- {t(
- bucket === 'active'
- ? 'panel.downloads.stats.natActiveDesc'
- : 'panel.downloads.stats.natUnavailableDesc'
- )}
- </p>
- ) : null}
- {status.retryAttempt > 0 ? (
- <p className="text-muted-foreground">
- {t('panel.downloads.stats.natRetrying', {
- attempt: status.retryAttempt,
- max: status.maxRetries,
- })}
- </p>
- ) : null}
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {bucket === 'failed' ? (
- <DropdownMenuItem onClick={handleEnable}>
- {t('panel.downloads.stats.natRetry')}
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem render={<Link to="/settings/network" />}>
- {t('panel.downloads.stats.natSettings')}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={handleHelp}>
- {t('panel.downloads.stats.natHelp')}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={handleDisable}>
- {t('panel.downloads.stats.natDisable')}
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
+ </NatStatusMenu>
)
}
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 0af03985..b83b11cb 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -148,33 +148,33 @@
"currentStatus": "Current status",
"lastChecked": "Checked at {{time}}",
"checks": {
- "binary": "Bundled aria2",
- "features": "Engine Features",
- "rpc": "Motrix RPC port",
- "process": "Process ownership",
- "communication": "Engine communication"
+ "binary": "Engine",
+ "features": "Features",
+ "rpc": "RPC port",
+ "process": "Process",
+ "communication": "Connection"
},
"binary": {
- "available": "{{name}} {{version}} is available.",
+ "available": "{{name}} {{version}}",
"unavailable": "{{name}} is missing or cannot be started."
},
"features": {
- "none": "aria2 did not report any engine features.",
- "unavailable": "Engine feature information is unavailable."
+ "none": "Not reported",
+ "unavailable": "Unavailable"
},
"rpc": {
- "listening": "Motrix aria2 is listening normally on port {{port}}.",
- "available": "Port {{port}} is free and ready for Motrix aria2.",
- "occupied": "Port {{port}} is already being used."
+ "listening": "{{port}} (Listening)",
+ "available": "{{port}} (Available)",
+ "occupied": "{{port}} (In use)"
},
"process": {
- "none": "No process is blocking the RPC port.",
- "unidentified": "The process using this port could not be identified. Motrix will not terminate it.",
- "current_app": "PID {{pid}} ({{name}}) is managed by this Motrix session.",
- "verified_orphan": "PID {{pid}} ({{name}}) matches Motrix’s bundled binary and private launch parameters, so it is safe to terminate.",
- "external_aria2": "PID {{pid}} ({{name}}) is aria2, but Motrix cannot verify ownership. It will not be terminated automatically.",
- "other": "PID {{pid}} ({{name}}) is not a verified Motrix aria2 process and is protected.",
- "unknown": "PID {{pid}} could not be identified and is protected."
+ "none": "No port conflict",
+ "unidentified": "Unidentified, Will not be stopped",
+ "current_app": "PID {{pid}} ({{name}}), Managed by Motrix",
+ "verified_orphan": "PID {{pid}} ({{name}}), Verified Motrix leftover; safe to stop",
+ "external_aria2": "PID {{pid}} ({{name}}), Unverified ownership; will not be stopped",
+ "other": "PID {{pid}} ({{name}}), Unverified ownership; will not be stopped",
+ "unknown": "PID {{pid}}, Unidentified; will not be stopped"
},
"communication": {
"ready": "Motrix can communicate with aria2."
@@ -220,6 +220,50 @@
"title": "Force stop the leftover aria2 process?",
"description": "PID {{pid}} matches Motrix’s bundled binary, private RPC secret, and data paths. It will be terminated immediately, then aria2 will restart on the Motrix RPC port.",
"action": "Force stop & recover"
+ },
+ "details": "Diagnostic details",
+ "versionUnknown": "Version unavailable",
+ "copy": "Copy diagnostics",
+ "copied": "Copied",
+ "copyFailed": "Could not copy diagnostics. Please try again.",
+ "refreshFailed": "Could not refresh diagnostics. The last successful report is shown below.",
+ "summary": {
+ "ready": "The download engine is running normally",
+ "starting": "The download engine is starting",
+ "restarting": "The download engine is recovering",
+ "stopped": "The download engine is stopped",
+ "port_in_use": "The engine’s control port is occupied",
+ "binary_unavailable": "The download engine is unavailable",
+ "spawn_failed": "The download engine could not start",
+ "rpc_unavailable": "The engine’s control connection is unavailable",
+ "unexpected_exit": "The download engine exited unexpectedly",
+ "health_check_failed": "The download engine stopped responding",
+ "unknown": "The download engine is unavailable"
+ },
+ "impact": {
+ "failed": "Download controls are unavailable. Task status may be out of date.",
+ "connecting": "Download controls will be available when the engine is ready.",
+ "stopped": "Start the engine to begin or manage downloads."
+ },
+ "runtime": {
+ "process": "Process",
+ "running": "Running",
+ "notRunning": "Not running",
+ "connection": "Connection",
+ "connected": "Connected",
+ "connecting": "Connecting…",
+ "disconnected": "Not connected",
+ "unavailable": "Unavailable",
+ "connectionStatus": "{{transport}} ({{status}})"
+ },
+ "port": {
+ "available": "{{port}} (Available)",
+ "listening": "{{port}} (Listening)",
+ "occupied": "{{port}} (In use)"
+ },
+ "motrixEngine": "aria2 Motrix",
+ "transport": {
+ "websocket": "WebSocket"
}
}
},
@@ -345,6 +389,7 @@
"configure": {
"action": "Configure",
"addTile": "Add",
+ "addTitle": "Add a tile",
"apply": "Apply",
"cancel": "Cancel",
"reset": "Reset",
@@ -355,6 +400,11 @@
"size": "{{width}} × {{height}}",
"currentSize": "Current size: {{width}} × {{height}}",
"invalidCapacity": "Not enough space for this size",
+ "availabilityHints": {
+ "space": "Shrink or remove another tile.",
+ "bounds": "Move the tile inward first.",
+ "unsupported": "Choose a supported size."
+ },
"sizeLabels": {
"compact": "Compact",
"wide": "Wide",
@@ -373,20 +423,16 @@
"custom": "Custom",
"undo": "Undo last preset",
"balanced": {
- "title": "Balanced",
- "description": "A balanced overview of status, speed, activity, and tasks."
+ "title": "Balanced"
},
"taskFocus": {
- "title": "Task Focus",
- "description": "Give Tasks the most space while keeping key status visible."
+ "title": "Task Focus"
},
"speedFocus": {
- "title": "Speed Focus",
- "description": "Emphasize upload and download trends alongside active tasks."
+ "title": "Speed Focus"
},
"compact": {
- "title": "Compact",
- "description": "Fit every Dashboard tile into the fixed 4 × 3 canvas."
+ "title": "Compact"
}
},
"saveFailed": "Could not save layout. Try again.",
@@ -421,6 +467,37 @@
},
"nat": {
"title": "NAT",
+ "compact": {
+ "state": {
+ "active": "Mapped",
+ "settingUp": "Mapping",
+ "failed": "Mapping",
+ "off": "Off"
+ },
+ "caption": {
+ "active_one": "{{count}} port",
+ "active_other": "{{count}} ports",
+ "settingUp": "Connecting…",
+ "failed": "Unavailable",
+ "off": "BT / DHT",
+ "waiting": "Loading…"
+ }
+ },
+ "internalIp": "Local IP",
+ "gatewayIp": "Router",
+ "caption": {
+ "off": "BT port mapping is off.",
+ "settingUp": "Connecting to your router…",
+ "failed": "Automatic mapping unavailable.",
+ "waiting": "Waiting for network status…"
+ },
+ "mappingDetails": "Mapped ports",
+ "mappingPurpose": {
+ "bt-listen": "BitTorrent",
+ "dht-listen": "DHT"
+ },
+ "portMapping": "Internal {{internal}} to external {{external}}",
+ "noMappings": "No active port mappings.",
"state": {
"active": "Active",
"settingUp": "Initializing",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index f11b6bed..257f5f95 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -147,33 +147,33 @@
"currentStatus": "当前状态",
"lastChecked": "检查于 {{time}}",
"checks": {
- "binary": "内置 aria2",
- "features": "引擎特性",
- "rpc": "Motrix RPC 端口",
- "process": "进程归属",
- "communication": "引擎通信"
+ "binary": "引擎",
+ "features": "功能",
+ "rpc": "RPC 端口",
+ "process": "进程",
+ "communication": "连接"
},
"binary": {
- "available": "{{name}} {{version}} 可用。",
+ "available": "{{name}} {{version}}",
"unavailable": "{{name}} 缺失或无法启动。"
},
"features": {
- "none": "aria2 未报告任何引擎特性。",
- "unavailable": "无法获取引擎特性信息。"
+ "none": "未报告",
+ "unavailable": "无法获取"
},
"rpc": {
- "listening": "Motrix aria2 正常监听端口 {{port}}。",
- "available": "端口 {{port}} 空闲,可供 Motrix aria2 使用。",
- "occupied": "端口 {{port}} 已被占用。"
+ "listening": "{{port}}(监听中)",
+ "available": "{{port}}(空闲)",
+ "occupied": "{{port}}(已占用)"
},
"process": {
- "none": "没有进程占用 RPC 端口。",
- "unidentified": "无法识别占用该端口的进程,Motrix 不会将其终止。",
- "current_app": "PID {{pid}}({{name}})由本次 Motrix 会话管理。",
- "verified_orphan": "PID {{pid}}({{name}})与 Motrix 内置 binary 及私有启动参数一致,可以安全终止。",
- "external_aria2": "PID {{pid}}({{name}})是 aria2,但 Motrix 无法确认其归属,因此不会自动终止。",
- "other": "PID {{pid}}({{name}})不是已验证的 Motrix aria2 引擎进程,将受到保护。",
- "unknown": "无法识别 PID {{pid}},该进程将受到保护。"
+ "none": "无端口冲突",
+ "unidentified": "无法识别,不会终止",
+ "current_app": "PID {{pid}}({{name}}),Motrix 管理",
+ "verified_orphan": "PID {{pid}}({{name}}),已验证的 Motrix 残留进程,可安全终止",
+ "external_aria2": "PID {{pid}}({{name}}),归属未验证,不会终止",
+ "other": "PID {{pid}}({{name}}),归属未验证,不会终止",
+ "unknown": "PID {{pid}},无法识别,不会终止"
},
"communication": {
"ready": "Motrix 可以正常连接 aria2。"
@@ -219,6 +219,50 @@
"title": "强制终止残留的 aria2 进程?",
"description": "PID {{pid}} 与 Motrix 内置 binary、私有 RPC secret 和数据路径一致。该进程会被立即终止,随后 aria2 将在 Motrix RPC 端口重新启动。",
"action": "强制终止并恢复"
+ },
+ "details": "诊断详情",
+ "versionUnknown": "版本信息不可用",
+ "copy": "复制诊断信息",
+ "copied": "已复制",
+ "copyFailed": "无法复制诊断信息,请重试。",
+ "refreshFailed": "未能刷新诊断信息,以下为上次成功检查的结果。",
+ "summary": {
+ "ready": "下载引擎运行正常",
+ "starting": "下载引擎正在启动",
+ "restarting": "下载引擎正在恢复",
+ "stopped": "下载引擎已停止",
+ "port_in_use": "引擎控制端口被占用",
+ "binary_unavailable": "下载引擎不可用",
+ "spawn_failed": "下载引擎无法启动",
+ "rpc_unavailable": "引擎控制连接不可用",
+ "unexpected_exit": "下载引擎意外退出",
+ "health_check_failed": "下载引擎停止响应",
+ "unknown": "下载引擎不可用"
+ },
+ "impact": {
+ "failed": "暂时无法控制下载,任务状态可能尚未更新。",
+ "connecting": "引擎就绪后,即可开始或管理下载。",
+ "stopped": "启动引擎以开始或管理下载。"
+ },
+ "runtime": {
+ "process": "进程",
+ "running": "运行中",
+ "notRunning": "未运行",
+ "connection": "连接",
+ "connected": "已连接",
+ "connecting": "正在连接…",
+ "disconnected": "未连接",
+ "unavailable": "不可用",
+ "connectionStatus": "{{transport}}({{status}})"
+ },
+ "port": {
+ "available": "{{port}}(空闲)",
+ "listening": "{{port}}(监听中)",
+ "occupied": "{{port}}(已占用)"
+ },
+ "motrixEngine": "aria2 Motrix",
+ "transport": {
+ "websocket": "WebSocket"
}
}
},
@@ -344,6 +388,7 @@
"configure": {
"action": "配置",
"addTile": "添加",
+ "addTitle": "添加卡片",
"apply": "应用",
"cancel": "取消",
"reset": "重置",
@@ -354,6 +399,11 @@
"size": "{{width}} × {{height}}",
"currentSize": "当前尺寸:{{width}} × {{height}}",
"invalidCapacity": "没有足够空间容纳此尺寸",
+ "availabilityHints": {
+ "space": "缩小或移除其他卡片",
+ "bounds": "将卡片移离边缘后重试",
+ "unsupported": "请选择支持的尺寸"
+ },
"sizeLabels": {
"compact": "紧凑",
"wide": "横向",
@@ -372,20 +422,16 @@
"custom": "自定义",
"undo": "撤销上次预设",
"balanced": {
- "title": "均衡",
- "description": "均衡展示状态、速度、活跃任务与任务列表。"
+ "title": "均衡"
},
"taskFocus": {
- "title": "任务优先",
- "description": "为任务列表提供最大空间,同时保留关键状态。"
+ "title": "任务优先"
},
"speedFocus": {
- "title": "速度优先",
- "description": "突出上传、下载趋势与活跃任务。"
+ "title": "速度优先"
},
"compact": {
- "title": "紧凑",
- "description": "在固定 4 × 3 画布中完整展示所有仪表板卡片。"
+ "title": "紧凑"
}
},
"saveFailed": "布局保存失败,请重试。",
@@ -420,6 +466,36 @@
},
"nat": {
"title": "NAT",
+ "compact": {
+ "state": {
+ "active": "已映射",
+ "settingUp": "映射中",
+ "failed": "映射",
+ "off": "未启用"
+ },
+ "caption": {
+ "active_other": "{{count}} 个端口",
+ "settingUp": "连接中…",
+ "failed": "暂不可用",
+ "off": "BT / DHT",
+ "waiting": "加载中…"
+ }
+ },
+ "internalIp": "本机 IP",
+ "gatewayIp": "路由器",
+ "caption": {
+ "off": "BT 端口映射已关闭",
+ "settingUp": "正在连接路由器…",
+ "failed": "自动映射暂不可用",
+ "waiting": "正在获取网络状态…"
+ },
+ "mappingDetails": "端口映射",
+ "mappingPurpose": {
+ "bt-listen": "BitTorrent",
+ "dht-listen": "DHT"
+ },
+ "portMapping": "内部端口 {{internal}} 到外部端口 {{external}}",
+ "noMappings": "暂无端口映射",
"state": {
"active": "已激活",
"settingUp": "初始化中",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 7b8a16ec..2f466c84 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -147,33 +147,33 @@
"currentStatus": "目前狀態",
"lastChecked": "檢查時間:{{time}}",
"checks": {
- "binary": "內建 aria2",
- "features": "引擎功能",
- "rpc": "Motrix RPC 連接埠",
- "process": "處理程序擁有權",
- "communication": "引擎通訊"
+ "binary": "引擎",
+ "features": "功能",
+ "rpc": "RPC 連接埠",
+ "process": "程序",
+ "communication": "連線"
},
"binary": {
- "available": "{{name}} {{version}} 可供使用。",
+ "available": "{{name}} {{version}}",
"unavailable": "缺少 {{name}},或無法啟動。"
},
"features": {
- "none": "aria2 未回報任何引擎功能。",
- "unavailable": "無法取得引擎功能資訊。"
+ "none": "未回報",
+ "unavailable": "無法取得"
},
"rpc": {
- "listening": "Motrix aria2 正常監聽連接埠 {{port}}。",
- "available": "連接埠 {{port}} 未被使用,可供 Motrix aria2 使用。",
- "occupied": "連接埠 {{port}} 已被使用。"
+ "listening": "{{port}}(監聽中)",
+ "available": "{{port}}(閒置)",
+ "occupied": "{{port}}(已占用)"
},
"process": {
- "none": "沒有處理程序阻擋 RPC 連接埠。",
- "unidentified": "無法辨識使用此連接埠的處理程序。Motrix 不會將其終止。",
- "current_app": "PID {{pid}} ({{name}}) 由此 Motrix 工作階段管理。",
- "verified_orphan": "PID {{pid}} ({{name}}) 符合 Motrix 內建執行檔與私有啟動參數,可安全終止。",
- "external_aria2": "PID {{pid}} ({{name}}) 是 aria2,但 Motrix 無法確認擁有權,不會自動終止。",
- "other": "PID {{pid}} ({{name}}) 不是已驗證的 Motrix aria2 處理程序,已受到保護。",
- "unknown": "無法辨識 PID {{pid}},已受到保護。"
+ "none": "無連接埠衝突",
+ "unidentified": "無法辨識,不會終止",
+ "current_app": "PID {{pid}} ({{name}}),Motrix 管理",
+ "verified_orphan": "PID {{pid}} ({{name}}),已驗證的 Motrix 殘留程序,可安全終止",
+ "external_aria2": "PID {{pid}} ({{name}}),擁有權未驗證,不會終止",
+ "other": "PID {{pid}} ({{name}}),擁有權未驗證,不會終止",
+ "unknown": "PID {{pid}},無法辨識,不會終止"
},
"communication": {
"ready": "Motrix 可以與 aria2 通訊。"
@@ -219,6 +219,50 @@
"title": "要強制停止遺留的 aria2 處理程序嗎?",
"description": "PID {{pid}} 符合 Motrix 的內建執行檔、私有 RPC 密鑰與資料路徑。系統會立即將其終止,然後在 Motrix RPC 連接埠重新啟動 aria2。",
"action": "強制停止並復原"
+ },
+ "details": "診斷詳情",
+ "versionUnknown": "無法取得版本資訊",
+ "copy": "複製診斷資訊",
+ "copied": "已複製",
+ "copyFailed": "無法複製診斷資訊,請重試。",
+ "refreshFailed": "無法重新整理診斷資訊,以下為上次成功檢查的結果。",
+ "summary": {
+ "ready": "下載引擎運作正常",
+ "starting": "下載引擎正在啟動",
+ "restarting": "下載引擎正在恢復",
+ "stopped": "下載引擎已停止",
+ "port_in_use": "引擎控制連接埠被占用",
+ "binary_unavailable": "下載引擎無法使用",
+ "spawn_failed": "下載引擎無法啟動",
+ "rpc_unavailable": "引擎控制連線無法使用",
+ "unexpected_exit": "下載引擎意外結束",
+ "health_check_failed": "下載引擎停止回應",
+ "unknown": "下載引擎無法使用"
+ },
+ "impact": {
+ "failed": "暫時無法控制下載,任務狀態可能尚未更新。",
+ "connecting": "引擎就緒後,即可開始或管理下載。",
+ "stopped": "啟動引擎以開始或管理下載。"
+ },
+ "runtime": {
+ "process": "程序",
+ "running": "運作中",
+ "notRunning": "未執行",
+ "connection": "連線",
+ "connected": "已連線",
+ "connecting": "正在連線…",
+ "disconnected": "未連線",
+ "unavailable": "無法使用",
+ "connectionStatus": "{{transport}}({{status}})"
+ },
+ "port": {
+ "available": "{{port}}(閒置)",
+ "listening": "{{port}}(監聽中)",
+ "occupied": "{{port}}(已占用)"
+ },
+ "motrixEngine": "aria2 Motrix",
+ "transport": {
+ "websocket": "WebSocket"
}
}
},
@@ -344,6 +388,7 @@
"configure": {
"action": "設定",
"addTile": "新增",
+ "addTitle": "新增磚塊",
"apply": "套用",
"cancel": "取消",
"reset": "重設",
@@ -354,6 +399,11 @@
"size": "{{width}} × {{height}}",
"currentSize": "目前大小:{{width}} × {{height}}",
"invalidCapacity": "沒有足夠空間容納此大小",
+ "availabilityHints": {
+ "space": "縮小或移除其他磚塊",
+ "bounds": "將磚塊移離邊緣後重試",
+ "unsupported": "請選擇支援的大小"
+ },
"sizeLabels": {
"compact": "精簡",
"wide": "寬",
@@ -372,20 +422,16 @@
"custom": "自訂",
"undo": "復原上次的預設版面",
"balanced": {
- "title": "均衡",
- "description": "均衡呈現狀態、速度、活動與任務。"
+ "title": "均衡"
},
"taskFocus": {
- "title": "著重任務",
- "description": "讓任務使用最多空間,同時保留重要狀態。"
+ "title": "著重任務"
},
"speedFocus": {
- "title": "著重速度",
- "description": "著重上傳與下載趨勢,同時顯示進行中的任務。"
+ "title": "著重速度"
},
"compact": {
- "title": "精簡",
- "description": "將所有儀表板磚塊放入固定的 4 × 3 版面。"
+ "title": "精簡"
}
},
"saveFailed": "無法儲存版面配置。請再試一次。",
@@ -420,6 +466,36 @@
},
"nat": {
"title": "NAT",
+ "compact": {
+ "state": {
+ "active": "已映射",
+ "settingUp": "映射中",
+ "failed": "映射",
+ "off": "未啟用"
+ },
+ "caption": {
+ "active_other": "{{count}} 個連接埠",
+ "settingUp": "連線中…",
+ "failed": "暫不可用",
+ "off": "BT / DHT",
+ "waiting": "載入中…"
+ }
+ },
+ "internalIp": "本機 IP",
+ "gatewayIp": "路由器",
+ "caption": {
+ "off": "BT 連接埠映射已關閉",
+ "settingUp": "正在連線至路由器…",
+ "failed": "自動映射暫不可用",
+ "waiting": "正在取得網路狀態…"
+ },
+ "mappingDetails": "連接埠映射",
+ "mappingPurpose": {
+ "bt-listen": "BitTorrent",
+ "dht-listen": "DHT"
+ },
+ "portMapping": "內部連接埠 {{internal}} 到外部連接埠 {{external}}",
+ "noMappings": "暫無連接埠映射",
"state": {
"active": "啟用中",
"settingUp": "初始化中",
diff --git a/src/shared/schemas/engine-connection.ts b/src/shared/schemas/engine-connection.ts
new file mode 100644
index 00000000..d07f35e1
--- /dev/null
+++ b/src/shared/schemas/engine-connection.ts
@@ -0,0 +1,8 @@
+import { z } from 'zod'
+
+export const EngineConnectionSchema = z.object({
+ transport: z.literal('websocket'),
+ connected: z.boolean(),
+})
+
+export type EngineConnectionSnapshot = z.infer<typeof EngineConnectionSchema>
diff --git a/src/shared/types/engine.ts b/src/shared/types/engine.ts
index a77fb978..5cedfe68 100644
--- a/src/shared/types/engine.ts
+++ b/src/shared/types/engine.ts
@@ -1,3 +1,5 @@
+import type { EngineConnectionSnapshot } from '../schemas/engine-connection'
+
export enum EngineState {
Stopped = 'stopped',
Starting = 'starting',
@@ -111,6 +113,7 @@ export interface EngineDiagnosticReport extends EngineStatusSnapshot {
port: number
available: boolean
expectedListener: boolean
+ connection: EngineConnectionSnapshot
}
process: EngineProcessInfo | null
defaultRpc: {