Skip to content

A full-featured download manager.

feat(ui): refine dashboard charts and download task controls (#2176)

Dr_rOot19ededab54a5
diff --git a/e2e/downloads-visibility.spec.ts b/e2e/downloads-visibility.spec.ts
index ba108385..9575a19d 100644
--- a/e2e/downloads-visibility.spec.ts
+++ b/e2e/downloads-visibility.spec.ts
@@ -279,6 +279,75 @@ test('media file list shows every segment through virtual scrolling and stays re
})
})
+test('default columns keep the download speed fully visible at minimum window size', async ({
+ electronApp,
+ mainWindow,
+}) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 914, 672)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'minimum-window-speed',
+ name: 'A reasonably descriptive download filename.zip',
+ status: TaskStatus.Downloading,
+ downloadSpeed: 999_900_000,
+ progress: 0.425,
+ }),
+ ])
+ const list = mainWindow.getByTestId('virtual-list-container')
+ const header = list.getByRole('columnheader').nth(4)
+ const speed = list.locator('[data-task-id]').getByRole('gridcell').nth(4)
+ await expect(speed).toHaveText('999.9 MB/s')
+ await header.getByRole('button').click()
+ await expect(header).toHaveAttribute('aria-sort', 'descending')
+
+ const expectSpeedFits = async () => {
+ await expect
+ .poll(() =>
+ speed.evaluate((cell) => {
+ const viewport = cell.closest(
+ '[data-testid="virtual-list-container"]'
+ )!
+ const bounds = viewport.getBoundingClientRect()
+ const rect = cell.getBoundingClientRect()
+ const range = document.createRange()
+ range.selectNodeContents(cell)
+ const text = range.getBoundingClientRect()
+ return (
+ rect.left >= bounds.left &&
+ rect.right <= bounds.right - 8 &&
+ text.left >= rect.left + 8 &&
+ text.right <= rect.right - 8 &&
+ viewport.scrollLeft === 0
+ )
+ })
+ )
+ .toBe(true)
+ const label = header.locator('button span')
+ expect(
+ await label.evaluate(
+ (element) => element.scrollWidth <= element.clientWidth
+ )
+ ).toBe(true)
+ expect(
+ await mainWindow.evaluate(
+ () => document.documentElement.scrollWidth === window.innerWidth
+ )
+ ).toBe(true)
+ }
+ await expectSpeedFits()
+ const toggleSidebar = mainWindow.getByRole('button', {
+ name: 'Toggle sidebar',
+ exact: true,
+ })
+ await toggleSidebar.click()
+ await expectSpeedFits()
+ await toggleSidebar.click()
+ await expectSpeedFits()
+})
+
test('download columns sort live tasks without losing selection or filter state', async ({
electronApp,
mainWindow,
@@ -507,7 +576,7 @@ test('remembers a manual sort across app restarts and clears it when restoring t
await expect(list.getByRole('columnheader').first()).toContainText('Size')
await expect(
list.getByRole('separator', { name: 'Resize Name column' })
- ).toHaveAttribute('aria-valuenow', '256')
+ ).toHaveAttribute('aria-valuenow', '216')
await expect(
list.getByRole('button', { name: 'Date completed', exact: true })
).toHaveCount(0)
@@ -1268,7 +1337,7 @@ test('native list controls preserve selection through context menus, column chan
const nameResize = grid.getByRole('separator', { name: 'Resize Name column' })
await nameResize.focus()
await mainWindow.keyboard.press('ArrowRight')
- await expect(nameResize).toHaveAttribute('aria-valuenow', '256')
+ await expect(nameResize).toHaveAttribute('aria-valuenow', '216')
const nameHeader = grid.getByRole('button', { name: 'Name', exact: true })
await nameHeader.click({ button: 'right' })
await mainWindow
@@ -1397,7 +1466,7 @@ test('native list controls preserve selection through context menus, column chan
}),
])
const darkRow = mainWindow.getByRole('row', { name: '示例任务.zip' })
- await darkRow.click()
+ await darkRow.dblclick()
await expectDrawerSettled(
mainWindow.getByRole('dialog', { name: '任务详情' })
)
@@ -2216,6 +2285,36 @@ test('organized context menus expose working scoped shortcuts and keep text edit
exact: true,
})
await expect(dialog).toBeVisible()
+ await expect(dialog.getByRole('checkbox')).not.toBeChecked()
+ expect(await removeCalls()).toEqual([])
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(dialog).toHaveCount(0)
+
+ for (const entry of ['context', 'more'] as const) {
+ for (const shift of [true, false]) {
+ if (entry === 'context')
+ await row('shortcut-b').click({ button: 'right' })
+ else
+ await mainWindow
+ .getByRole('button', { name: 'More', exact: true })
+ .click()
+ await menu.getByRole('menuitem', { name: 'Remove', exact: true }).click({
+ modifiers: shift ? ['Shift'] : [],
+ })
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByRole('checkbox')).toBeChecked({ checked: shift })
+ expect(await removeCalls()).toEqual([])
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(dialog).toHaveCount(0)
+ }
+ }
+
+ await grid.focus()
+ await mainWindow.keyboard.press(
+ macOS ? 'Meta+Shift+Backspace' : 'Shift+Delete'
+ )
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByRole('checkbox')).toBeChecked()
expect(await removeCalls()).toEqual([])
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
await expect(dialog).toHaveCount(0)
diff --git a/e2e/settings-persistence.spec.ts b/e2e/settings-persistence.spec.ts
index bf3c0ee5..80e929a6 100644
--- a/e2e/settings-persistence.spec.ts
+++ b/e2e/settings-persistence.spec.ts
@@ -25,6 +25,57 @@ async function openMain(app: ElectronApplication): Promise<Page> {
}
test.describe('settings persistence', () => {
+ test('task file deletion defaults to trash and persists an explicit permanent choice', async ({
+ userDataDir,
+ rpcPort,
+ }, testInfo) => {
+ let app = await launchMotrix({ userDataDir, rpcPort })
+ const openDownloadsSettings = async () => {
+ const main = await openMain(app)
+ await waitForEngineReady(main)
+ await main.getByRole('link', { name: 'Settings', exact: true }).click()
+ await main
+ .getByRole('button', {
+ name: /Concurrency, bandwidth limits, network reliability/,
+ })
+ .click()
+ return main
+ }
+ try {
+ let main = await openDownloadsSettings()
+ const deletion = main.getByRole('combobox', {
+ name: 'When deleting task files',
+ })
+ await expect(deletion).toHaveText('Move to trash')
+ await deletion.click()
+ await main.getByRole('option', { name: 'Delete permanently' }).click()
+ await expect(
+ main.getByText(
+ 'Files are deleted directly and cannot be restored from the trash.'
+ )
+ ).toBeVisible()
+ await main.screenshot({
+ path: testInfo.outputPath('file-deletion-settings.png'),
+ })
+ await main.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(deletion).toBeHidden()
+ await app.close()
+
+ app = await launchMotrix({ userDataDir, rpcPort })
+ main = await openDownloadsSettings()
+ const restored = main.getByRole('combobox', {
+ name: 'When deleting task files',
+ })
+ await expect(restored).toHaveText('Delete permanently')
+ await restored.click()
+ await main.getByRole('option', { name: 'Move to trash' }).click()
+ await main.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(restored).toBeHidden()
+ } finally {
+ await app.close().catch(() => {})
+ }
+ })
+
test('magnet selection timeout is opt-in and persists its waiting time', async ({
userDataDir,
rpcPort,
diff --git a/src/core/task/actions/remove-task.test.ts b/src/core/task/actions/remove-task.test.ts
index 006b2c47..7ef53406 100644
--- a/src/core/task/actions/remove-task.test.ts
+++ b/src/core/task/actions/remove-task.test.ts
@@ -106,6 +106,26 @@ function mediaTaskWithMetadata() {
}
describe('removeTask', () => {
+ it('retains the task and torrent metadata when file cleanup fails', async () => {
+ const deps = makeDeps()
+ const task = makeDownloadTask({
+ status: TaskStatus.Completed,
+ type: TaskType.Bt,
+ diskPath: '/downloads/torrent',
+ saveDir: '/downloads',
+ torrentMetaPath: '/metadata/source.torrent',
+ })
+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)
+ const error = new Error('Trash unavailable')
+ vi.mocked(deps.fileCleanupService.cleanup).mockRejectedValue(error)
+
+ await expect(
+ removeTask(task.id, { deleteWithFiles: true }, deps)
+ ).rejects.toBe(error)
+ expect(deps.torrentMetaStore.remove).not.toHaveBeenCalled()
+ expect(deps.db.deleteTask).not.toHaveBeenCalled()
+ expect(deps.taskManager.remove).not.toHaveBeenCalled()
+ })
it.each([false, true])(
'removes associated media metadata when deleteWithFiles=%s',
async (deleteWithFiles) => {
diff --git a/src/core/task/actions/remove-task.ts b/src/core/task/actions/remove-task.ts
index 495ce739..58187548 100644
--- a/src/core/task/actions/remove-task.ts
+++ b/src/core/task/actions/remove-task.ts
@@ -264,15 +264,14 @@ async function removeTaskUnderMutation(
if (shouldDeleteFiles) {
await cleanupReservedOutputs(task, deps)
- await Promise.all([
- getBtDirectStorageLayout(task)?.multiFile === false &&
- !isClaimedByOtherTask(`${task.diskPath}.aria2`, task.id, deps)
- ? deps.fileCleanupService.cleanup(task.diskPath, task.type, true)
- : deps.fileCleanupService.cleanup(task.diskPath, task.type),
- task.torrentMetaPath
- ? deps.torrentMetaStore.remove(task.torrentMetaPath)
- : Promise.resolve(),
- ])
+ await (getBtDirectStorageLayout(task)?.multiFile === false &&
+ !isClaimedByOtherTask(`${task.diskPath}.aria2`, task.id, deps)
+ ? deps.fileCleanupService.cleanup(task.diskPath, task.type, true)
+ : deps.fileCleanupService.cleanup(task.diskPath, task.type))
+ // Keep metadata with a retryable task if file cleanup (including trash)
+ // fails. Removing both concurrently can orphan the retained BT task.
+ if (task.torrentMetaPath)
+ await deps.torrentMetaStore.remove(task.torrentMetaPath)
} else if (!options.deleteWithFiles) {
deps.eventBus.emit(Events.ToastShow, {
key: 'task.remove.orphanToast',
diff --git a/src/main/index.ts b/src/main/index.ts
index 05037b0b..6fa88e56 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -195,6 +195,7 @@ import { setupNativeThemeSync } from './platform/native-theme-sync'
import { setupPowerManager } from './platform/power-manager'
import { createProtocolManager } from './platform/protocol-manager'
import { createElectronPlatformServices } from './platform/services'
+import { removeTaskPath } from './platform/task-file-remover'
import { setupTray } from './platform/tray'
import { createElectronCapabilityHost } from './plugin/capability-host'
import { startDevWatcher } from './plugin/dev-watcher'
@@ -451,7 +452,8 @@ const mediaMetaStore = new MediaMetaStoreImpl(
path.join(platform.userDataDir, 'media')
)
const fileCleanupService = new FileCleanupServiceImpl({
- removePathRecursive,
+ removePathRecursive: (absPath) =>
+ removeTaskPath(absPath, settingsManager.getApp().fileDeletionMode),
})
// ─── Late-Initialized (assigned in app.on('ready')) ─────
diff --git a/src/main/platform/task-file-remover.test.ts b/src/main/platform/task-file-remover.test.ts
new file mode 100644
index 00000000..8565457d
--- /dev/null
+++ b/src/main/platform/task-file-remover.test.ts
@@ -0,0 +1,106 @@
+import fs from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { TaskType } from '@shared/types/task'
+import { shell } from 'electron'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { FileCleanupServiceImpl } from '../../core/task/file-cleanup-service'
+import { removeTaskPath } from './task-file-remover'
+
+vi.mock('electron', () => ({ shell: { trashItem: vi.fn() } }))
+
+describe('desktop task file deletion', () => {
+ let root: string
+
+ beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(tmpdir(), 'motrix-task-delete-'))
+ vi.mocked(shell.trashItem).mockReset()
+ await fs.mkdir(path.join(root, 'trash'))
+ vi.mocked(shell.trashItem).mockImplementation(async (target) => {
+ await fs.rename(target, path.join(root, 'trash', path.basename(target)))
+ })
+ })
+
+ afterEach(async () => {
+ vi.restoreAllMocks()
+ await fs.rm(root, { recursive: true, force: true })
+ })
+
+ it('trashes a partial HTTP download and its control file', async () => {
+ const target = path.join(root, 'file.motrix')
+ await fs.writeFile(target, 'download')
+ await fs.writeFile(`${target}.aria2`, 'control')
+ const cleanup = new FileCleanupServiceImpl({
+ removePathRecursive: (file) => removeTaskPath(file, 'trash'),
+ })
+
+ await cleanup.cleanup(target, TaskType.Http)
+
+ expect(vi.mocked(shell.trashItem).mock.calls).toEqual([
+ [target],
+ [`${target}.aria2`],
+ ])
+ expect(
+ await fs.readFile(path.join(root, 'trash/file.motrix'), 'utf8')
+ ).toBe('download')
+ expect(
+ await fs.readFile(path.join(root, 'trash/file.motrix.aria2'), 'utf8')
+ ).toBe('control')
+ })
+
+ it('trashes a BT directory with its contents', async () => {
+ const target = path.join(root, 'torrent')
+ await fs.mkdir(target)
+ await fs.writeFile(path.join(target, 'file'), 'download')
+ await removeTaskPath(target, 'trash')
+ expect(
+ await fs.readFile(path.join(root, 'trash/torrent/file'), 'utf8')
+ ).toBe('download')
+ })
+
+ it('keeps files when the OS cannot move them to trash', async () => {
+ const target = path.join(root, 'file')
+ await fs.writeFile(target, 'download')
+ const error = new Error('Trash unavailable')
+ vi.mocked(shell.trashItem).mockRejectedValue(error)
+
+ await expect(removeTaskPath(target, 'trash')).rejects.toBe(error)
+ expect(await fs.readFile(target, 'utf8')).toBe('download')
+ })
+
+ it('ignores absent files and does not hide filesystem access errors', async () => {
+ const target = path.join(root, 'missing')
+ await expect(removeTaskPath(target, 'trash')).resolves.toBeUndefined()
+ expect(shell.trashItem).not.toHaveBeenCalled()
+
+ const error = Object.assign(new Error('Permission denied'), {
+ code: 'EACCES',
+ })
+ vi.spyOn(fs, 'lstat').mockRejectedValue(error)
+ await expect(removeTaskPath(target, 'trash')).rejects.toBe(error)
+ expect(shell.trashItem).not.toHaveBeenCalled()
+ })
+
+ it.skipIf(process.platform === 'win32')(
+ 'trashes broken symlinks',
+ async () => {
+ const target = path.join(root, 'link')
+ await fs.symlink(path.join(root, 'missing'), target)
+ await removeTaskPath(target, 'trash')
+ expect(shell.trashItem).toHaveBeenCalledWith(target)
+ expect(
+ (await fs.lstat(path.join(root, 'trash/link'))).isSymbolicLink()
+ ).toBe(true)
+ }
+ )
+
+ it('deletes directly only when permanent deletion is selected', async () => {
+ const target = path.join(root, 'torrent')
+ await fs.mkdir(target)
+ await fs.writeFile(path.join(target, 'file'), 'download')
+ await removeTaskPath(target, 'permanent')
+ await expect(fs.lstat(target)).rejects.toMatchObject({ code: 'ENOENT' })
+ await expect(removeTaskPath(target, 'permanent')).resolves.toBeUndefined()
+ expect(shell.trashItem).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/platform/task-file-remover.ts b/src/main/platform/task-file-remover.ts
new file mode 100644
index 00000000..6bbe3efe
--- /dev/null
+++ b/src/main/platform/task-file-remover.ts
@@ -0,0 +1,28 @@
+import fs from 'node:fs/promises'
+import path from 'node:path'
+import type { FileDeletionMode } from '@shared/schemas/app-settings'
+import { shell } from 'electron'
+import { removePathRecursive } from './fs-helpers'
+
+/** User-requested task cleanup. Internal temporary-file cleanup stays direct. */
+export async function removeTaskPath(
+ absPath: string,
+ mode: FileDeletionMode
+): Promise<void> {
+ if (mode === 'permanent') {
+ await removePathRecursive(absPath)
+ return
+ }
+
+ const target = path.resolve(absPath)
+ try {
+ // lstat also finds broken symlinks, so trashing a link never follows it.
+ await fs.lstat(target)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
+ throw error
+ }
+
+ // A failed trash operation must never fall back to permanent deletion.
+ await shell.trashItem(target)
+}
diff --git a/src/renderer/hooks/use-global-speed-history.test.tsx b/src/renderer/hooks/use-global-speed-history.test.tsx
index 9916580c..db11b650 100644
--- a/src/renderer/hooks/use-global-speed-history.test.tsx
+++ b/src/renderer/hooks/use-global-speed-history.test.tsx
@@ -7,11 +7,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mockInvoke = vi.fn()
const listeners = new Map<string, (...a: unknown[]) => void>()
+const connectionListeners = new Set<(event: { state: string }) => void>()
vi.mock('@renderer/lib/transport', () => ({
transport: {
invoke: (...a: unknown[]) => mockInvoke(...a),
on: (ch: string, cb: (...a: unknown[]) => void) => listeners.set(ch, cb),
off: (ch: string) => listeners.delete(ch),
+ onConnectionChange: (cb: (event: { state: string }) => void) => {
+ connectionListeners.add(cb)
+ return () => connectionListeners.delete(cb)
+ },
platform: 'darwin',
},
}))
@@ -22,7 +27,7 @@ const { useGlobalSpeedHistory, __resetGlobalSpeedHistoryStoreForTests } =
const stats = (down: number, up: number) => ({
totalDownloadSpeed: down,
totalUploadSpeed: up,
- activeTasks: 0,
+ activeTasks: down > 0 || up > 0 ? 1 : 0,
waitingTasks: 0,
stoppedTasks: 0,
})
@@ -35,6 +40,8 @@ describe('useGlobalSpeedHistory', () => {
})
afterEach(() => {
__resetGlobalSpeedHistoryStoreForTests()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
})
it('hydrates from GetSpeedHistory on first mount and merges later events', async () => {
@@ -91,4 +98,140 @@ describe('useGlobalSpeedHistory', () => {
expect(a.result.current).toBe(b.result.current) // same reference
expect(mockInvoke).toHaveBeenCalledTimes(1)
})
+
+ describe('idle display clock', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(100_000)
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ mockInvoke.mockResolvedValue([{ t: 99_000, down: 500, up: 100 }])
+ })
+
+ async function mount() {
+ const hook = renderHook(() => useGlobalSpeedHistory())
+ await act(async () => {
+ await Promise.resolve()
+ })
+ return hook
+ }
+
+ const emit = (down = 0, up = 0, activeTasks = 0) => {
+ act(() =>
+ listeners.get(Events.StatsUpdated)?.({
+ ...stats(down, up),
+ activeTasks,
+ })
+ )
+ }
+
+ const advance = async (ms: number) => {
+ await act(async () => vi.advanceTimersByTimeAsync(ms))
+ }
+
+ it('scrolls a completed transfer out with one zero sample per second between 10s engine polls', async () => {
+ const { result } = await mount()
+ emit()
+ for (let second = 1; second <= 30; second++) {
+ await advance(1_000)
+ if (second % 10 === 0) emit()
+ expect(result.current).toHaveLength(second + 2)
+ expect(result.current.at(-1)).toEqual({
+ t: 100_000 + second * 1_000,
+ down: 0,
+ up: 0,
+ })
+ }
+ expect(
+ result.current
+ .slice(-24)
+ .every((point) => point.down === 0 && point.up === 0)
+ ).toBe(true)
+ expect(mockInvoke).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not insert zero samples during active work or after a transfer resumes', async () => {
+ const { result } = await mount()
+ emit(0, 0, 1)
+ const active = result.current
+ await advance(5_000)
+ expect(result.current).toBe(active)
+ emit()
+ await advance(2_000)
+ emit(800, 50, 1)
+ const resumed = result.current
+ await advance(5_000)
+ expect(result.current).toBe(resumed)
+ expect(result.current.at(-1)).toMatchObject({ down: 800, up: 50 })
+ })
+
+ it('clears a stale non-zero engine rate as soon as the final active task stops', async () => {
+ const { result } = await mount()
+ emit(500, 100, 0)
+ expect(result.current.at(-1)).toEqual({ t: 100_000, down: 0, up: 0 })
+ await advance(3_000)
+ expect(result.current.at(-1)).toEqual({ t: 103_000, down: 0, up: 0 })
+ expect(result.current).toHaveLength(5)
+ })
+
+ it('stops extending idle data if engine confirmation becomes stale', async () => {
+ const { result } = await mount()
+ emit()
+ await advance(15_000)
+ const stale = result.current
+ await advance(30_000)
+ expect(result.current).toBe(stale)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('cancels the idle clock immediately on transport disconnect', async () => {
+ const { result } = await mount()
+ emit()
+ await advance(2_000)
+ act(() => {
+ for (const listener of connectionListeners)
+ listener({ state: 'disconnected' })
+ })
+ const disconnected = result.current
+ await advance(10_000)
+ expect(result.current).toBe(disconnected)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('pauses while hidden and cancels the timer when the last subscriber leaves', async () => {
+ const { result, unmount } = await mount()
+ emit()
+ await advance(2_000)
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
+ act(() => document.dispatchEvent(new Event('visibilitychange')))
+ const hidden = result.current
+ await advance(3_000)
+ expect(result.current).toBe(hidden)
+ expect(vi.getTimerCount()).toBe(0)
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ act(() => document.dispatchEvent(new Event('visibilitychange')))
+ await advance(0)
+ expect(result.current.at(-1)?.t).toBe(Date.now())
+ unmount()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('starts the idle clock after an in-flight seed resolves without losing the idle event', async () => {
+ let resolveSeed!: (points: SpeedPoint[]) => void
+ mockInvoke.mockReturnValue(
+ new Promise<SpeedPoint[]>((resolve) => {
+ resolveSeed = resolve
+ })
+ )
+ const { result } = renderHook(() => useGlobalSpeedHistory())
+ emit()
+ expect(vi.getTimerCount()).toBe(0)
+ await act(async () => resolveSeed([{ t: 99_000, down: 500, up: 100 }]))
+ await advance(1_000)
+ expect(result.current).toEqual([
+ { t: 99_000, down: 500, up: 100 },
+ { t: 100_000, down: 0, up: 0 },
+ { t: 101_000, down: 0, up: 0 },
+ ])
+ })
+ })
})
diff --git a/src/renderer/hooks/use-global-speed-history.ts b/src/renderer/hooks/use-global-speed-history.ts
index 0b645246..6a2e4c4a 100644
--- a/src/renderer/hooks/use-global-speed-history.ts
+++ b/src/renderer/hooks/use-global-speed-history.ts
@@ -8,6 +8,9 @@ import { useSyncExternalStore } from 'react'
const MAX_POINTS = 200
const MOCK_STEP_MS = 1000
+const IDLE_SAMPLE_STEP_MS = 1_000
+// Idle engine polls arrive every 10s. Stop holding zero if confirmation is stale.
+const IDLE_CONFIRMATION_MAX_AGE_MS = 15_000
const MOCK_DOWNLOAD_MBPS = [
0, 0, 0, 0, 5, 52, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 3, 8, 15, 38, 63,
@@ -24,6 +27,44 @@ let sessionEpoch = 0
let initialized = false
let initializing = false
let pendingTail: SpeedPoint[] = []
+let idleConfirmedAt: number | null = null
+let idleTimer: ReturnType<typeof setTimeout> | null = null
+let stopConnectionListener: (() => void) | undefined
+
+function stopIdleClock() {
+ if (idleTimer !== null) clearTimeout(idleTimer)
+ idleTimer = null
+}
+
+function scheduleIdleClock() {
+ stopIdleClock()
+ if (
+ idleConfirmedAt === null ||
+ Date.now() - idleConfirmedAt >= IDLE_CONFIRMATION_MAX_AGE_MS ||
+ listeners.size === 0 ||
+ document.hidden ||
+ initializing
+ ) {
+ return
+ }
+
+ const nextSampleAt = (store.at(-1)?.t ?? Date.now()) + IDLE_SAMPLE_STEP_MS
+ idleTimer = setTimeout(
+ () => {
+ idleTimer = null
+ if (
+ idleConfirmedAt === null ||
+ Date.now() - idleConfirmedAt >= IDLE_CONFIRMATION_MAX_AGE_MS
+ ) {
+ return
+ }
+ // Display-only zero tail between confirmed idle polls; no extra engine RPC.
+ appendPoint({ t: Date.now(), down: 0, up: 0 })
+ scheduleIdleClock()
+ },
+ Math.max(0, nextSampleAt - Date.now())
+ )
+}
function notify() {
for (const cb of listeners) cb()
@@ -50,15 +91,32 @@ function createMockSpeedHistory(): SpeedPoint[] {
function onStatsEvent(...args: unknown[]) {
const stats = args[0] as GlobalStats
+ // Engines can retain their last measured rate after the final task stops.
+ const idle = stats.activeTasks === 0
const point: SpeedPoint = {
t: Date.now(),
- down: stats.totalDownloadSpeed,
- up: stats.totalUploadSpeed,
+ down: idle ? 0 : stats.totalDownloadSpeed,
+ up: idle ? 0 : stats.totalUploadSpeed,
}
+ idleConfirmedAt = idle ? point.t : null
+ stopIdleClock()
if (initializing) {
pendingTail.push(point)
} else {
- appendPoint(point)
+ const tail = store.at(-1)
+ // A real idle poll can land just after the display clock. Confirm it
+ // without adding a second zero vertex or restarting an in-flight slide.
+ if (
+ idleConfirmedAt === null ||
+ !tail ||
+ tail.down !== 0 ||
+ tail.up !== 0 ||
+ point.t < tail.t ||
+ point.t - tail.t >= IDLE_SAMPLE_STEP_MS
+ ) {
+ appendPoint(point)
+ }
+ scheduleIdleClock()
}
}
@@ -67,6 +125,11 @@ function initialize() {
initializing = true
const epoch = sessionEpoch
transport.on(Events.StatsUpdated, onStatsEvent)
+ stopConnectionListener = transport.onConnectionChange?.(({ state }) => {
+ if (state === 'connected') return
+ idleConfirmedAt = null
+ stopIdleClock()
+ })
void transport
.invoke(Queries.GetSpeedHistory, { limit: MAX_POINTS })
.then((data) => {
@@ -82,6 +145,7 @@ function initialize() {
initialized = true
initializing = false
notify()
+ scheduleIdleClock()
})
.catch(() => {
if (epoch !== sessionEpoch) return
@@ -95,6 +159,8 @@ function initialize() {
}
// reset so a later subscriber can retry without leaking the listener
transport.off(Events.StatsUpdated, onStatsEvent)
+ stopConnectionListener?.()
+ stopConnectionListener = undefined
initializing = false
pendingTail = []
})
@@ -102,8 +168,18 @@ function initialize() {
function subscribe(cb: () => void): () => void {
listeners.add(cb)
+ if (listeners.size === 1) {
+ document.addEventListener('visibilitychange', scheduleIdleClock)
+ scheduleIdleClock()
+ }
if (!initialized && !initializing) initialize()
- return () => listeners.delete(cb)
+ return () => {
+ listeners.delete(cb)
+ if (listeners.size === 0) {
+ stopIdleClock()
+ document.removeEventListener('visibilitychange', scheduleIdleClock)
+ }
+ }
}
export function useGlobalSpeedHistory(): readonly SpeedPoint[] {
@@ -116,6 +192,11 @@ export function useGlobalSpeedHistory(): readonly SpeedPoint[] {
/** Internal: tests only. Resets the module-level singleton. */
export function __resetGlobalSpeedHistoryStoreForTests(): void {
+ stopIdleClock()
+ idleConfirmedAt = null
+ stopConnectionListener?.()
+ stopConnectionListener = undefined
+ document.removeEventListener('visibilitychange', scheduleIdleClock)
transport.off(Events.StatsUpdated, onStatsEvent)
store = []
listeners.clear()
@@ -126,6 +207,10 @@ export function __resetGlobalSpeedHistoryStoreForTests(): void {
onOperatorSessionLost(() => {
sessionEpoch++
+ stopIdleClock()
+ idleConfirmedAt = null
+ stopConnectionListener?.()
+ stopConnectionListener = undefined
transport.off(Events.StatsUpdated, onStatsEvent)
store = []
pendingTail = []
diff --git a/src/renderer/routes/dashboard/components/speed-sparkline.test.tsx b/src/renderer/routes/dashboard/components/speed-sparkline.test.tsx
new file mode 100644
index 00000000..5731ed60
--- /dev/null
+++ b/src/renderer/routes/dashboard/components/speed-sparkline.test.tsx
@@ -0,0 +1,231 @@
+import '@testing-library/jest-dom/vitest'
+import { setAppReduceMotion } from '@renderer/lib/reduced-motion'
+import type { SpeedPoint } from '@shared/types/stats'
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { SpeedSparkline } from './speed-sparkline'
+
+const STEP = 1_000 / 23
+const history = Array.from({ length: 200 }, (_, index) => ({
+ t: index * 1_000,
+ up: 20 + (index % 5) * 10,
+ down: 40 + (index % 7) * 20,
+}))
+
+function append(points: readonly SpeedPoint[], speed = 100, elapsed = 1_000) {
+ return [
+ ...points.slice(1),
+ { t: (points.at(-1)?.t ?? 0) + elapsed, up: speed, down: speed },
+ ]
+}
+
+function chart(points: readonly SpeedPoint[], ceiling = 200, pointCount = 24) {
+ return (
+ <SpeedSparkline
+ history={points}
+ kind="down"
+ ceiling={ceiling}
+ pointCount={pointCount}
+ />
+ )
+}
+
+function offset(container: HTMLElement) {
+ return Number(
+ container
+ .querySelector('[data-slot="speed-motion"]')
+ ?.getAttribute('transform')
+ ?.match(/^translate\(([^ ]+)/)?.[1]
+ )
+}
+
+function scale(container: HTMLElement) {
+ return Number(
+ container
+ .querySelector('[data-slot="speed-motion"]')
+ ?.getAttribute('transform')
+ ?.match(/scale\(1 ([^)]+)/)?.[1]
+ )
+}
+
+function path(container: HTMLElement) {
+ return (
+ container.querySelector('[data-slot="speed-curve"]')?.getAttribute('d') ??
+ ''
+ )
+}
+
+describe('SpeedSparkline streaming', () => {
+ let now = 0
+ let nextFrame = 0
+ let frames: Map<number, FrameRequestCallback>
+
+ const advance = (ms: number) => {
+ now += ms
+ act(() => {
+ const callbacks = [...frames.values()]
+ frames.clear()
+ for (const callback of callbacks) callback(now)
+ })
+ }
+
+ beforeEach(() => {
+ now = 0
+ nextFrame = 0
+ frames = new Map()
+ setAppReduceMotion(false)
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.set(++nextFrame, callback)
+ return nextFrame
+ })
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id))
+ })
+
+ afterEach(() => {
+ cleanup()
+ setAppReduceMotion(false)
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ it('shows the initial snapshot immediately without an entrance animation', () => {
+ const { container } = render(chart(history))
+ expect(offset(container)).toBe(0)
+ expect(path(container).split('L')).toHaveLength(24)
+ expect(frames.size).toBe(0)
+ })
+
+ it('moves existing vertices left at a constant speed while revealing the new sample', () => {
+ const { container, rerender } = render(chart(history))
+ const oldVertices = path(container)
+ .slice(1)
+ .split('L')
+ .map((point) => point.split(',').map(Number))
+ advance(1_000)
+ rerender(chart(append(history)))
+ const newPath = path(container)
+ const newVertices = newPath
+ .slice(1)
+ .split('L')
+ .map((point) => point.split(',').map(Number))
+
+ expect(offset(container)).toBeCloseTo(STEP)
+ for (let index = 0; index < oldVertices.length; index++) {
+ expect(newVertices[index][0] + offset(container)).toBeCloseTo(
+ oldVertices[index][0]
+ )
+ expect(newVertices[index][1]).toBe(oldVertices[index][1])
+ }
+ advance(250)
+ expect(offset(container)).toBeCloseTo(STEP * 0.75)
+ advance(250)
+ expect(offset(container)).toBeCloseTo(STEP * 0.5)
+ expect(path(container)).toBe(newPath)
+ advance(500)
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ })
+
+ it('continues from the displayed position when another sample arrives mid-slide', () => {
+ const { container, rerender } = render(chart(history))
+ const next = append(history)
+ rerender(chart(next))
+ advance(400)
+ const before = offset(container)
+ rerender(chart(append(next, 80)))
+ expect(offset(container) - STEP).toBeCloseTo(before)
+ expect(frames.size).toBe(1)
+ })
+
+ it('keeps early histories at a fixed spacing as the window fills', () => {
+ const short = history.slice(-3)
+ const { container, rerender } = render(chart(short))
+ rerender(chart([...short, { t: 200_000, up: 100, down: 100 }]))
+ expect(offset(container)).toBeCloseTo(STEP)
+ expect(path(container).split('L')).toHaveLength(25)
+ })
+
+ it('preserves the displayed scale when a peak changes, then settles without overshoot', () => {
+ const { container, rerender } = render(chart(history))
+ const next = append(history, 800)
+ rerender(chart(next, 1_000))
+ expect(scale(container)).toBe(5)
+ advance(150)
+ expect(scale(container)).toBeGreaterThan(1)
+ expect(scale(container)).toBeLessThan(5)
+ advance(150)
+ expect(scale(container)).toBe(1)
+ })
+
+ it('snaps replacement histories, long suspensions, and resized windows to their current state', () => {
+ const { container, rerender } = render(chart(history))
+ rerender(chart(append(history)))
+ advance(200)
+ rerender(chart(append(history, 100, 60_000)))
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ rerender(chart(history.slice(0, 10)))
+ expect(offset(container)).toBe(0)
+ rerender(chart(history, 200, 48))
+ expect(offset(container)).toBe(0)
+ expect(path(container).split('L')).toHaveLength(48)
+ })
+
+ it('renders idle history without scheduling invisible animation frames', () => {
+ const idle = history.map((point) => ({ ...point, up: 0, down: 0 }))
+ const { container, rerender } = render(chart(idle, 1))
+ rerender(chart(append(idle, 0), 1))
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ })
+
+ it('keeps moving after the speed reaches zero until the last activity leaves the window', () => {
+ const { container, rerender } = render(chart(history))
+ let samples = history
+ for (let second = 1; second <= 24; second++) {
+ samples = append(samples, 0)
+ rerender(chart(samples))
+ expect(offset(container)).toBeCloseTo(STEP)
+ advance(500)
+ expect(offset(container)).toBeCloseTo(STEP / 2)
+ advance(500)
+ expect(offset(container)).toBe(0)
+ }
+ samples = append(samples, 0)
+ rerender(chart(samples))
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ })
+
+ it('stops immediately when reduced motion is enabled and still accepts new data', () => {
+ const { container, rerender } = render(chart(history))
+ const next = append(history)
+ rerender(chart(next))
+ advance(200)
+ act(() => setAppReduceMotion(true))
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ const before = path(container)
+ rerender(chart(append(next, 150)))
+ expect(path(container)).not.toBe(before)
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ })
+
+ it('finishes when hidden and cancels pending work when unmounted', () => {
+ const { container, rerender, unmount } = render(chart(history))
+ const next = append(history)
+ rerender(chart(next))
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
+ act(() => document.dispatchEvent(new Event('visibilitychange')))
+ expect(offset(container)).toBe(0)
+ expect(frames.size).toBe(0)
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ rerender(chart(append(next)))
+ expect(frames.size).toBe(1)
+ unmount()
+ expect(frames.size).toBe(0)
+ })
+})
diff --git a/src/renderer/routes/dashboard/components/speed-sparkline.tsx b/src/renderer/routes/dashboard/components/speed-sparkline.tsx
new file mode 100644
index 00000000..089c2bc6
--- /dev/null
+++ b/src/renderer/routes/dashboard/components/speed-sparkline.tsx
@@ -0,0 +1,180 @@
+import { useReducedMotion } from '@renderer/lib/reduced-motion'
+import { normalizeSpeedHistory } from '@renderer/lib/speed-chart'
+import type { SpeedPoint } from '@shared/types/stats'
+import { useLayoutEffect, useRef } from 'react'
+
+const WIDTH = 1_000
+const HEIGHT = 1_000
+const BASELINE = 875
+const SCALE_DURATION = 300
+
+interface SpeedSparklineProps {
+ history: readonly SpeedPoint[]
+ kind: 'up' | 'down'
+ ceiling: number
+ pointCount: number
+}
+
+interface AnimationState extends SpeedSparklineProps {
+ startedAt: number
+ duration: number
+ offset: number
+ fromCeiling: number
+}
+
+function sampleAnimation(state: AnimationState, now: number) {
+ const elapsed = Math.max(0, now - state.startedAt)
+ const progress = Math.min(1, elapsed / state.duration)
+ const scaleProgress = 1 - (1 - Math.min(1, elapsed / SCALE_DURATION)) ** 3
+ return {
+ offset: state.offset * (1 - progress),
+ ceiling:
+ state.fromCeiling + (state.ceiling - state.fromCeiling) * scaleProgress,
+ done: progress === 1 && scaleProgress === 1,
+ }
+}
+
+/** A rolling window with stable vertices; only the drawing moves per frame. */
+export function SpeedSparkline({
+ history,
+ kind,
+ ceiling,
+ pointCount,
+}: SpeedSparklineProps) {
+ const reducedMotion = useReducedMotion()
+ const groupRef = useRef<SVGGElement>(null)
+ const lineRef = useRef<SVGPathElement>(null)
+ const fillRef = useRef<SVGPathElement>(null)
+ const stateRef = useRef<AnimationState | null>(null)
+
+ useLayoutEffect(() => {
+ const group = groupRef.current
+ const line = lineRef.current
+ const fill = fillRef.current
+ if (!group || !line || !fill) return
+
+ const now = performance.now()
+ const previous = stateRef.current
+ const previousTail = previous?.history.at(-1)
+ const tail = history.at(-1)
+ const previousIndex = previousTail
+ ? history.findLastIndex(
+ (point) =>
+ point.t === previousTail.t && point[kind] === previousTail[kind]
+ )
+ : -1
+ const added = previousIndex < 0 ? 0 : history.length - previousIndex - 1
+ const elapsed = tail && previousTail ? tail.t - previousTail.t : 0
+ const canContinue =
+ previous &&
+ previous.kind === kind &&
+ previous.pointCount === pointCount &&
+ previousIndex >= 0 &&
+ added < pointCount &&
+ elapsed >= 0 &&
+ elapsed <= 5_000 &&
+ !reducedMotion &&
+ !document.hidden
+ const current = previous ? sampleAnimation(previous, now) : null
+ const offset = canContinue ? added + (current?.offset ?? 0) : 0
+ // Keep the outgoing vertices until they have crossed the left clip edge.
+ const points = normalizeSpeedHistory(
+ history.slice(-pointCount - Math.ceil(offset)),
+ pointCount + Math.ceil(offset)
+ )
+ const step = WIDTH / (pointCount - 1)
+ const coordinates = points.map((point, index) => {
+ const x = WIDTH - (points.length - index - 1) * step
+ const y = BASELINE - (point[kind] / ceiling) * BASELINE
+ return `${x},${y}`
+ })
+ const path = `M${coordinates.join('L')}`
+ const firstX = WIDTH - (points.length - 1) * step
+ line.setAttribute('d', path)
+ fill.setAttribute(
+ 'd',
+ `${path}L${WIDTH},${BASELINE}L${firstX},${BASELINE}Z`
+ )
+
+ const hasActivity = points.some((point) => point[kind] > 0)
+ const state: AnimationState = {
+ history,
+ kind,
+ ceiling,
+ pointCount,
+ startedAt: now,
+ // Match the sampling cadence, with no easing or pause between samples.
+ duration: Math.max(
+ 250,
+ Math.min(1_500, added > 0 ? elapsed / added : 1_000)
+ ),
+ offset: hasActivity ? offset : 0,
+ fromCeiling:
+ canContinue && hasActivity ? (current?.ceiling ?? ceiling) : ceiling,
+ }
+ stateRef.current = state
+ let frame = 0
+
+ const draw = (timestamp: number) => {
+ const sample = sampleAnimation(state, timestamp)
+ const scale = ceiling / sample.ceiling
+ group.setAttribute(
+ 'transform',
+ `translate(${sample.offset * step} ${BASELINE}) scale(1 ${scale}) translate(0 ${-BASELINE})`
+ )
+ if (!sample.done && (state.offset > 0 || state.fromCeiling !== ceiling)) {
+ frame = requestAnimationFrame(draw)
+ }
+ }
+ const finish = () => {
+ cancelAnimationFrame(frame)
+ state.offset = 0
+ state.fromCeiling = ceiling
+ draw(now + Math.max(state.duration, SCALE_DURATION))
+ }
+ const onVisibilityChange = () => {
+ if (document.hidden) finish()
+ }
+
+ draw(now)
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ return () => {
+ cancelAnimationFrame(frame)
+ document.removeEventListener('visibilitychange', onVisibilityChange)
+ }
+ }, [history, kind, ceiling, pointCount, reducedMotion])
+
+ const color = `hsl(var(--chart-${kind === 'up' ? 2 : 1}))`
+
+ return (
+ <svg
+ data-slot="speed-sparkline"
+ aria-hidden="true"
+ className="h-full w-full overflow-hidden"
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ preserveAspectRatio="none"
+ >
+ <rect
+ x="0"
+ y={BASELINE}
+ width={WIDTH}
+ height={HEIGHT - BASELINE}
+ fill={color}
+ fillOpacity={0.12}
+ />
+ <g ref={groupRef} data-slot="speed-motion">
+ <path ref={fillRef} fill={color} fillOpacity={0.12} />
+ <path
+ ref={lineRef}
+ data-slot="speed-curve"
+ fill="none"
+ stroke={color}
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </g>
+ </svg>
+ )
+}
diff --git a/src/renderer/routes/dashboard/tiles/speed-tile.test.tsx b/src/renderer/routes/dashboard/tiles/speed-tile.test.tsx
index f85e38ce..3bdd838e 100644
--- a/src/renderer/routes/dashboard/tiles/speed-tile.test.tsx
+++ b/src/renderer/routes/dashboard/tiles/speed-tile.test.tsx
@@ -46,7 +46,10 @@ describe('SpeedTile', () => {
it('keeps samples distributed across the chart after a long sampling gap', () => {
const now = Date.now()
const history = Array.from({ length: 200 }, (_, index) => ({
- t: index === 0 ? now - 86_400_000 : now - (199 - index) * 1_000,
+ t:
+ index < 180
+ ? now - 86_400_000 + index * 1_000
+ : now - (199 - index) * 1_000,
up: 100 + (index % 7) * 10,
down: 200 + (index % 11) * 10,
}))
@@ -54,12 +57,12 @@ describe('SpeedTile', () => {
<SpeedTile kind="up" history={history} viewport={COMPACT} />
)
const path = container
- .querySelector('.recharts-area-curve')
+ .querySelector('[data-slot="speed-curve"]')
?.getAttribute('d')
expect(path).toBeDefined()
expect(Number(path?.match(/^M([\d.-]+)/)?.[1])).toBeCloseTo(0)
- const firstSegment = path?.match(/C([^C]+)/)?.[1].match(/[\d.-]+/g)
- expect(Number(firstSegment?.[4])).toBeLessThan(60)
+ const firstSegment = path?.match(/L([\d.-]+)/)
+ expect(Number(firstSegment?.[1])).toBeCloseTo(1_000 / 23)
})
it('renders the UPLOAD label and current up speed', () => {
@@ -75,14 +78,16 @@ describe('SpeedTile', () => {
expect(screen.getAllByText(/150/).length).toBeGreaterThanOrEqual(1)
})
- it('renders a lighter smooth stroke for non-zero speeds', () => {
+ it('renders a light, rounded streaming stroke for non-zero speeds', () => {
const { container } = render(
<SpeedTile kind="down" history={points} viewport={SUMMARY} />
)
- const line = container.querySelector('.recharts-area-curve')
+ const line = container.querySelector('[data-slot="speed-curve"]')
expect(line).not.toBeNull()
expect(line).toHaveAttribute('stroke-width', '1.5')
- expect(line?.getAttribute('d')).toContain('C')
+ expect(line).toHaveAttribute('stroke-linejoin', 'round')
+ expect(line).toHaveAttribute('vector-effect', 'non-scaling-stroke')
+ expect(line?.getAttribute('d')).toContain('L')
})
it('renders only the KPI and minimal chart treatment when compact', () => {
@@ -122,12 +127,12 @@ describe('SpeedTile', () => {
const { container, rerender } = render(
<SpeedTile kind="up" history={points} viewport={SUMMARY} />
)
- const chart = container.querySelector('.recharts-wrapper')
+ const chart = container.querySelector('[data-slot="speed-sparkline"]')
rerender(<SpeedTile kind="up" history={points} viewport={FOCUS} />)
expect(screen.getByTestId('speed-scale').children).toHaveLength(3)
- expect(container.querySelector('.recharts-wrapper')).toBe(chart)
+ expect(container.querySelector('[data-slot="speed-sparkline"]')).toBe(chart)
})
it('renders a flat zero state with no history', () => {
diff --git a/src/renderer/routes/dashboard/tiles/speed-tile.tsx b/src/renderer/routes/dashboard/tiles/speed-tile.tsx
index fb81fe30..fb81816b 100644
--- a/src/renderer/routes/dashboard/tiles/speed-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/speed-tile.tsx
@@ -1,15 +1,10 @@
// src/renderer/routes/dashboard/tiles/speed-tile.tsx
-import { type ChartConfig, ChartContainer } from '@renderer/components/ui/chart'
import { useByteFormat } from '@renderer/hooks/use-byte-format'
-import {
- chartCeiling,
- normalizeSpeedHistory,
- sampleSpeedHistory,
-} from '@renderer/lib/speed-chart'
+import { chartCeiling, SPEED_CHART_MIN_POINTS } from '@renderer/lib/speed-chart'
import { cn } from '@renderer/lib/utils'
import type { SpeedPoint } from '@shared/types/stats'
import { useTranslation } from 'react-i18next'
-import { Area, AreaChart, XAxis, YAxis } from 'recharts'
+import { SpeedSparkline } from '../components/speed-sparkline'
import { TileShell } from '../components/tile-shell'
import { TileTitle } from '../components/tile-title'
import type { DashboardTileViewport } from '../layout/dashboard-registry'
@@ -21,11 +16,6 @@ export interface SpeedTileProps {
className?: string
}
-const CHART_CONFIG: ChartConfig = {
- up: { label: 'Up', color: 'hsl(var(--chart-2))' },
- down: { label: 'Down', color: 'hsl(var(--chart-1))' },
-}
-
export function SpeedTile({
kind,
history,
@@ -42,19 +32,9 @@ export function SpeedTile({
const showPeak =
viewport.contentLevel === 'detailed' || viewport.contentLevel === 'focus'
const focus = viewport.contentLevel === 'focus'
- const normalizedHistory = normalizeSpeedHistory(history)
- // Preserve sample spacing: clock gaps must not compress recent activity.
- const chartData = sampleSpeedHistory(
- normalizedHistory,
- viewport.span.w * 16,
- dataKey
- ).map((point) => ({
- ...point,
- position: normalizedHistory.indexOf(point),
- }))
+ // Keep the scale anchored to retained history while recent samples roll by.
const visibleMax = Math.max(peak, current)
const chartMax = chartCeiling(visibleMax)
- const chartMin = -chartMax / 7
const scaleMax = visibleMax > 0 ? chartMax : 0
const scaleValues = focus
? [
@@ -112,37 +92,12 @@ export function SpeedTile({
: '-top-10'
)}
>
- <ChartContainer
- config={CHART_CONFIG}
- className="aspect-auto h-full w-full"
- initialDimension={{ width: 240, height: 112 }}
- >
- <AreaChart
- data={chartData}
- margin={{ top: 0, right: 0, left: 0, bottom: 0 }}
- >
- <XAxis
- dataKey="position"
- type="number"
- domain={['dataMin', 'dataMax']}
- hide
- />
- <YAxis dataKey={dataKey} domain={[chartMin, chartMax]} hide />
- <Area
- type="monotoneX"
- dataKey={dataKey}
- stroke={`var(--color-${kind})`}
- strokeWidth={1.5}
- strokeLinecap="round"
- strokeLinejoin="round"
- baseValue={chartMin}
- fill={`var(--color-${kind})`}
- fillOpacity={0.12}
- isAnimationActive={false}
- dot={false}
- />
- </AreaChart>
- </ChartContainer>
+ <SpeedSparkline
+ history={history}
+ kind={kind}
+ ceiling={chartMax}
+ pointCount={Math.max(SPEED_CHART_MIN_POINTS, viewport.span.w * 16)}
+ />
</div>
</TileShell>
)
diff --git a/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx b/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx
index 96d0a309..219fb501 100644
--- a/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx
+++ b/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx
@@ -2,6 +2,7 @@ import { makeMediaProgress } from '@test-utils/media-progress'
import '@testing-library/jest-dom/vitest'
import { i18n } from '@renderer/lib/i18n'
import { DownloadErrorCode } from '@shared/errors'
+import { Commands } from '@shared/protocol/commands'
import {
type BtExtension,
type DownloadTask,
@@ -18,6 +19,8 @@ import type { DashboardTileViewport } from '../layout/dashboard-registry'
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
+ invoke: vi.fn(),
+ toast: vi.fn(),
openAddTaskDialog: vi.fn(),
retry: vi.fn(async () => {}),
now: { current: Date.UTC(2026, 6, 27, 8, 0, 0) },
@@ -42,7 +45,15 @@ vi.mock('react-router', async () => {
return { ...actual, useNavigate: () => mocks.navigate }
})
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { platform: 'darwin', invoke: mocks.invoke },
+}))
+vi.mock('@renderer/components/ui/toast', () => ({
+ toast: { add: mocks.toast },
+}))
+
vi.mock('@renderer/hooks/use-task-list', () => ({
+ getTaskListSnapshot: () => mocks.taskList.current,
useTaskList: () => ({
...mocks.taskList.current,
retry: mocks.retry,
@@ -197,6 +208,8 @@ function renderTile({
describe('TasksTile', () => {
beforeEach(async () => {
await i18n.changeLanguage('en-US')
+ mocks.invoke.mockReset().mockResolvedValue({ succeeded: [], failed: [] })
+ mocks.toast.mockReset()
mocks.navigate.mockReset()
mocks.openAddTaskDialog.mockReset()
mocks.retry.mockClear()
@@ -248,7 +261,7 @@ describe('TasksTile', () => {
).toHaveAttribute('aria-checked', 'true')
})
- it('renders every Active status with honest metrics and one real progress bar', () => {
+ it('renders every Active status with concise metrics and meaningful progress', () => {
setSource([
task('ready', TaskStatus.MetadataReady, { priority: 7 }),
task('downloading', TaskStatus.Downloading, { priority: 6 }),
@@ -268,20 +281,33 @@ describe('TasksTile', () => {
renderTile({ viewport: VIEWPORTS['2x3'] })
expect(screen.getAllByTestId('tasks-row')).toHaveLength(7)
- expect(screen.getByText('Fetching')).toBeInTheDocument()
- expect(screen.getByText('Ready')).toBeInTheDocument()
- expect(screen.getByText('Finalizing')).toBeInTheDocument()
- expect(screen.getByText('Queued')).toBeInTheDocument()
- expect(screen.getByText('Paused')).toBeInTheDocument()
- expect(screen.getByText('68% saved')).toBeInTheDocument()
- expect(screen.getByText('Seeding · Ratio 1.25')).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'metadata.iso, Fetching' })
+ ).toHaveAccessibleDescription('Fetching')
+ expect(
+ screen.getByRole('button', { name: 'ready.iso, Awaiting file selection' })
+ ).toHaveAccessibleDescription('Awaiting file selection')
+ expect(
+ screen.getByRole('button', { name: 'finalizing.iso, Finalizing' })
+ ).toHaveAccessibleDescription('Finalizing')
+ expect(
+ screen.getByRole('button', { name: 'queued.iso, Queued' })
+ ).toHaveAccessibleDescription('Queued')
+ expect(
+ screen.getByRole('button', { name: 'paused.iso, Paused' })
+ ).toHaveAccessibleDescription('Paused 68%')
+ expect(
+ screen.getByRole('button', { name: 'seeding.iso, Seeding' })
+ ).toHaveAccessibleDescription('Seeding. 1.0 KB/s')
expect(screen.queryByText('37%')).toBeNull()
- expect(screen.getAllByRole('progressbar')).toHaveLength(1)
+ expect(screen.getAllByRole('progressbar')).toHaveLength(2)
const progress = screen.getByRole('progressbar', {
name: 'downloading.iso progress',
})
expect(progress).toHaveAttribute('aria-valuenow', '50')
- expect(progress).toHaveClass('left-[26px]', 'right-1', 'w-auto')
+ expect(
+ screen.getByRole('progressbar', { name: 'paused.iso progress' })
+ ).toHaveAttribute('aria-valuenow', '68')
})
it('keeps ordering stable when only speed and progress change', () => {
@@ -320,11 +346,11 @@ describe('TasksTile', () => {
['2x1', 3],
['2x2', 4],
['2x3', 7],
- ['3x2', 5],
- ['3x3', 8],
- ['4x2', 6],
+ ['3x2', 4],
+ ['3x3', 7],
+ ['4x2', 4],
] as const)(
- 'reserves the final %s slot for overflow',
+ 'fits the %s rows with an overflow footer',
(viewportKey, limit) => {
setSource(
Array.from({ length: 10 }, (_, index) =>
@@ -335,13 +361,113 @@ describe('TasksTile', () => {
)
renderTile({ viewport: VIEWPORTS[viewportKey] })
- expect(screen.getAllByTestId('tasks-row')).toHaveLength(limit - 1)
+ const visible = viewportKey === '2x1' ? limit - 1 : limit
+ expect(screen.getAllByTestId('tasks-row')).toHaveLength(visible)
expect(screen.getByTestId('tasks-more')).toHaveTextContent(
- `${10 - (limit - 1)} more`
+ `${10 - visible} more`
)
}
)
+ it('keeps every detailed row free of icons and secondary transfer details', () => {
+ setSource([
+ task('download'),
+ task('seed', TaskStatus.Seeding, { bt: bt(1.27) }),
+ ])
+ renderTile()
+ expect(screen.getByTestId('tasks-list').querySelector('svg')).toBeNull()
+ const status = screen.getAllByTestId('task-status-pill')[0]
+ expect(status).toHaveTextContent('Downloading')
+ expect(status).not.toHaveTextContent('50%')
+ expect(screen.getByText('50%')).toBeVisible()
+ expect(screen.queryByText(/ETA|Ratio/)).toBeNull()
+ })
+
+ it('pauses and resumes inline without opening the task', async () => {
+ const user = userEvent.setup()
+ setSource([task('download'), task('paused', TaskStatus.Paused)])
+ renderTile()
+ await user.click(
+ screen.getByRole('button', { name: 'Pause: download.iso' })
+ )
+ expect(mocks.invoke).toHaveBeenCalledWith(Commands.PauseTasks, ['download'])
+ await user.click(screen.getByRole('button', { name: 'Resume: paused.iso' }))
+ expect(mocks.invoke).toHaveBeenCalledWith(Commands.ResumeTasks, ['paused'])
+ expect(mocks.navigate).not.toHaveBeenCalled()
+ })
+
+ it('blocks duplicate actions until the pending command settles and reports failure', async () => {
+ const user = userEvent.setup()
+ let finish!: (value: unknown) => void
+ mocks.invoke.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve
+ })
+ )
+ setSource([task('download')])
+ renderTile()
+ const pause = screen.getByRole('button', { name: 'Pause: download.iso' })
+ await user.click(pause)
+ expect(pause).toBeDisabled()
+ expect(pause).toHaveAttribute('aria-busy', 'true')
+ await user.click(pause)
+ expect(mocks.invoke).toHaveBeenCalledOnce()
+ await act(async () =>
+ finish({
+ succeeded: [],
+ failed: [{ taskId: 'download', reason: 'Engine unavailable' }],
+ })
+ )
+ expect(pause).toBeEnabled()
+ expect(mocks.toast).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'error' })
+ )
+ })
+
+ it('disables inline actions for stale snapshots and development fixtures', () => {
+ setSource([task('cached')], 'error', true)
+ const rendered = renderTile()
+ expect(
+ screen.getByRole('button', { name: 'Pause: cached.iso' })
+ ).toBeDisabled()
+ rendered.unmount()
+ renderTile({ initialEntry: '/?dashboardTasksFixture=active-all' })
+ expect(
+ screen.getByRole('button', { name: 'Pause: Design Resources 2026.zip' })
+ ).toBeDisabled()
+ })
+
+ it('retries an eligible failed task inline', async () => {
+ const user = userEvent.setup()
+ setSource([
+ task('retry', TaskStatus.Error, {
+ type: TaskType.Bt,
+ kind: TaskKind.Bt,
+ torrentMetaPath: '/sidecar/retry.torrent',
+ }),
+ ])
+ renderTile()
+ await user.click(screen.getByRole('radio', { name: 'Failed' }))
+ await user.click(screen.getByRole('button', { name: 'Retry: retry.iso' }))
+ expect(mocks.invoke).toHaveBeenCalledWith(Commands.RetryTasks, ['retry'])
+ expect(mocks.navigate).not.toHaveBeenCalled()
+ })
+
+ it('returns focus to the selected view when a focused action disappears with its row', () => {
+ const active = task('focused')
+ setSource([active])
+ const rendered = renderTile()
+ screen.getByRole('button', { name: 'Pause: focused.iso' }).focus()
+ setSource([{ ...active, status: TaskStatus.Completed }])
+ rendered.rerender(
+ <MemoryRouter>
+ <TasksTile engineOnline viewport={VIEWPORTS['2x2']} />
+ </MemoryRouter>
+ )
+ expect(screen.getByRole('radio', { name: 'Active' })).toHaveFocus()
+ })
+
it('uses summary rows without glyphs, secondary copy, or progress', () => {
setSource([task('summary')])
renderTile({ viewport: VIEWPORTS['2x1'] })
@@ -374,21 +500,19 @@ describe('TasksTile', () => {
await user.click(screen.getByRole('radio', { name: 'Failed' }))
expect(screen.getAllByTestId('tasks-row')).toHaveLength(2)
- expect(
- screen.getByText('Failed: Network connection failed')
- ).toBeInTheDocument()
- expect(screen.getByText('Failed: Download failed')).toBeInTheDocument()
+ expect(screen.getByText('Network connection failed')).toBeInTheDocument()
+ expect(screen.getByText('Download failed')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'failed.iso, Error' })
).toHaveAccessibleDescription(
- '5 min. ago. Failed: Network connection failed. Technical detail: Connection refused'
+ 'Network connection failed. 5 min. ago. Technical detail: Connection refused'
)
expect(screen.queryByRole('progressbar')).toBeNull()
await user.click(screen.getByRole('radio', { name: 'Recent' }))
expect(screen.getAllByTestId('tasks-row')).toHaveLength(1)
expect(screen.getByText('2.05 KB')).toBeInTheDocument()
- expect(screen.getAllByText(/Completed/)).toHaveLength(2)
+ expect(screen.getByText('15 min. ago')).toBeVisible()
expect(screen.queryByText('Connection refused')).toBeNull()
})
@@ -396,10 +520,12 @@ describe('TasksTile', () => {
setSource([task('offline', TaskStatus.Downloading)])
renderTile({ engineOnline: false })
- expect(screen.getByText('—')).toBeInTheDocument()
expect(
- screen.getByText('Offline · last known progress')
- ).toBeInTheDocument()
+ screen.getByRole('button', { name: 'Pause: offline.iso' })
+ ).toBeDisabled()
+ expect(screen.getByTestId('tasks-row')).toHaveAccessibleDescription(
+ 'Offline (last known progress)'
+ )
expect(screen.queryByText(/KB\/s/)).toBeNull()
expect(screen.queryByText(/ETA/)).toBeNull()
expect(screen.getByRole('progressbar')).toBeInTheDocument()
@@ -445,7 +571,7 @@ describe('TasksTile', () => {
expect(screen.getByText('No active tasks')).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveTextContent('No active tasks')
- await user.click(screen.getByRole('button', { name: '+ New task' }))
+ await user.click(screen.getByRole('button', { name: 'New task' }))
expect(mocks.openAddTaskDialog).toHaveBeenCalledOnce()
await user.click(screen.getByRole('radio', { name: 'Failed' }))
@@ -499,9 +625,7 @@ describe('TasksTile', () => {
expect(button).toHaveAccessibleName(
'A very long accessible task name, Downloading'
)
- expect(button).toHaveAccessibleDescription(
- '10.0 KB/s. Downloading · ETA 2m'
- )
+ expect(button).toHaveAccessibleDescription('Downloading 50%. 10.0 KB/s')
expect(button.getAttribute('aria-label')).not.toMatch(/B\/s|9999/)
expect(button.closest('li')).not.toBeNull()
})
@@ -622,11 +746,11 @@ describe('TasksTile', () => {
expect(screen.getByText('20 min. ago')).toBeInTheDocument()
expect(
screen.getByText(
- 'Failed: Cannot recover this task: it is missing the identifying information needed to resume.'
+ 'Cannot recover this task: it is missing the identifying information needed to resume.'
)
).toBeInTheDocument()
expect(screen.getByTestId('tasks-row')).toHaveAccessibleDescription(
- '20 min. ago. Failed: Cannot recover this task: it is missing the identifying information needed to resume.'
+ 'Cannot recover this task: it is missing the identifying information needed to resume.. 20 min. ago'
)
})
@@ -646,7 +770,7 @@ describe('TasksTile', () => {
const row = screen.getByTestId('tasks-row')
expect(row).toHaveAttribute('title', `${longName}\n${longReason.trim()}`)
expect(row).toHaveAccessibleDescription(
- `5 min. ago. Failed: Download failed. Technical detail: ${longReason.trim()}`
+ `Download failed. 5 min. ago. Technical detail: ${longReason.trim()}`
)
})
@@ -664,16 +788,18 @@ describe('TasksTile', () => {
expect(screen.getByText('任务')).toBeInTheDocument()
expect(screen.getByRole('radio', { name: '活跃' })).toBeInTheDocument()
- expect(screen.getByText('已保存 26%')).toBeInTheDocument()
+ expect(screen.getByTestId('tasks-row')).toHaveAccessibleDescription(
+ '已暂停 26%'
+ )
expect(screen.getByTestId('tasks-row')).toHaveAccessibleName(
'cn.iso, 已暂停'
)
await user.click(screen.getByRole('radio', { name: '失败' }))
const failedRow = screen.getByTestId('tasks-row')
- expect(screen.getByText('失败:网络连接失败')).toBeInTheDocument()
+ expect(screen.getByText('网络连接失败')).toBeInTheDocument()
expect(failedRow).toHaveAccessibleDescription(
- '5分钟前. 失败:网络连接失败. 技术详情:Connection refused'
+ '网络连接失败. 5分钟前. 技术详情:Connection refused'
)
expect(
failedRow
diff --git a/src/renderer/routes/dashboard/tiles/tasks-tile.tsx b/src/renderer/routes/dashboard/tiles/tasks-tile.tsx
index defd34db..e91019e2 100644
--- a/src/renderer/routes/dashboard/tiles/tasks-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/tasks-tile.tsx
@@ -7,11 +7,17 @@ import { useTaskList } from '@renderer/hooks/use-task-list'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { formatRelativeTime } from '@renderer/lib/relative-time'
-import { TASK_TYPE_META } from '@renderer/lib/task-type-meta'
import { projectTaskWindow, type TaskView } from '@renderer/lib/task-views'
import { cn } from '@renderer/lib/utils'
+import { useTaskActions } from '@renderer/routes/downloads/inspector/use-task-actions'
+import { StatusPill } from '@renderer/routes/downloads/status-pill'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
+import {
+ canAttemptRetry,
+ canPause,
+ canResume,
+} from '@shared/types/task-actions'
import {
getDownloadProgress,
getMediaPhaseLabel,
@@ -39,9 +45,9 @@ const ROW_LIMITS: Readonly<Record<string, number>> = {
'2x1': 3,
'2x2': 4,
'2x3': 7,
- '3x2': 5,
- '3x3': 8,
- '4x2': 6,
+ '3x2': 4,
+ '3x3': 7,
+ '4x2': 4,
}
const STATUS_KEY: Readonly<Record<TaskStatus, string>> = {
@@ -79,32 +85,7 @@ function rowLimit(viewport: DashboardTileViewport): number {
}
function rowHeightClass(viewport: DashboardTileViewport): string {
- switch (spanKey(viewport)) {
- case '2x1':
- return 'h-6'
- case '3x2':
- case '4x2':
- return 'h-8'
- case '3x3':
- return 'h-9'
- default:
- return 'h-10'
- }
-}
-
-function rowVerticalPaddingClass(viewport: DashboardTileViewport): string {
- switch (spanKey(viewport)) {
- case '2x2':
- case '2x3':
- return 'py-1'
- default:
- return 'py-0.5'
- }
-}
-
-function bodyTopPaddingClass(viewport: DashboardTileViewport): string {
- if (viewport.contentLevel === 'summary') return ''
- return spanKey(viewport) === '4x2' ? 'pt-1' : 'pt-2'
+ return viewport.contentLevel === 'summary' ? 'h-6' : 'h-11'
}
function clampProgress(progress: number): number {
@@ -112,29 +93,6 @@ function clampProgress(progress: number): number {
return Math.min(100, Math.max(0, progress * 100))
}
-function formatEta(seconds: number, locale: string): string {
- if (!Number.isFinite(seconds) || seconds <= 0) return '—'
-
- let value: number
- let unit: 'second' | 'minute' | 'hour'
- if (seconds < 60) {
- value = Math.ceil(seconds)
- unit = 'second'
- } else if (seconds < 3600) {
- value = Math.ceil(seconds / 60)
- unit = 'minute'
- } else {
- value = Math.ceil(seconds / 3600)
- unit = 'hour'
- }
-
- return new Intl.NumberFormat(locale, {
- style: 'unit',
- unit,
- unitDisplay: 'narrow',
- }).format(value)
-}
-
function validTimestamp(value: number | null): value is number {
return typeof value === 'number' && Number.isFinite(value) && value > 0
}
@@ -151,14 +109,64 @@ function taskStatusLabel(
return translate(`panel.downloads.status.${STATUS_KEY[status]}`)
}
+function TaskQuickAction({
+ task,
+ enabled,
+}: {
+ task: DownloadTask
+ enabled: boolean
+}) {
+ const { t } = useTranslation()
+ const selected = useMemo(() => [task], [task])
+ const actions = useTaskActions(selected)
+ const [pending, setPending] = useState(false)
+ const pendingRef = useRef(false)
+ const action = actions.pauseCount
+ ? { label: t('panel.downloads.action.pause'), run: actions.onPause }
+ : actions.resumeCount
+ ? { label: t('panel.downloads.action.resume'), run: actions.onResume }
+ : actions.retryCount
+ ? { label: t('panel.downloads.action.retry'), run: actions.onRetry }
+ : null
+
+ if (!action) return null
+
+ async function run() {
+ if (!enabled || pendingRef.current || !action) return
+ pendingRef.current = true
+ setPending(true)
+ try {
+ await action.run()
+ } finally {
+ pendingRef.current = false
+ setPending(false)
+ }
+ }
+
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={!enabled || pending}
+ aria-label={`${action.label}: ${task.name}`}
+ aria-busy={pending || undefined}
+ onClick={() => void run()}
+ className="relative z-20 col-start-2 row-start-1 me-1 h-7 min-w-11 px-1.5 text-[11px] font-medium text-muted-foreground hover:text-foreground motion-reduce:transition-none"
+ >
+ {action.label}
+ </Button>
+ )
+}
+
function TaskRow({
task,
view,
summary,
engineOnline,
+ actionsEnabled,
now,
heightClass,
- verticalPaddingClass,
onOpen,
onFocusedRowRemoved,
}: {
@@ -166,17 +174,16 @@ function TaskRow({
view: TaskView
summary: boolean
engineOnline: boolean
+ actionsEnabled: boolean
now: number
heightClass: string
- verticalPaddingClass: string
onOpen(task: DownloadTask): void
onFocusedRowRemoved(): void
}) {
const { formatBytes, formatSpeed } = useByteFormat()
-
const { t, i18n } = useTranslation()
const descriptionId = useId()
- const buttonRef = useRef<HTMLButtonElement | null>(null)
+ const groupRef = useRef<HTMLDivElement | null>(null)
const phase = getMediaPhaseLabel(task)
const statusLabel = phase ? t(phase) : taskStatusLabel(task.status, t)
let technicalDetail: string | null = null
@@ -199,9 +206,7 @@ function TaskRow({
now,
i18n.language
),
- secondary: t('panel.dashboard.tasks.secondary.failed', {
- reason: failure.reason,
- }),
+ secondary: failure.reason,
progress: null,
}
} else if (view === 'recent') {
@@ -212,9 +217,11 @@ function TaskRow({
: task.totalBytes
presentation = {
primary: finalSize === null ? '—' : formatBytes(finalSize),
- secondary: t('panel.dashboard.tasks.secondary.completed', {
- time: formatRelativeTime(terminalDisplayTime(task), now, i18n.language),
- }),
+ secondary: formatRelativeTime(
+ terminalDisplayTime(task),
+ now,
+ i18n.language
+ ),
progress: null,
}
} else if (
@@ -228,29 +235,11 @@ function TaskRow({
const downloading = task.mediaProgress?.phase === 'downloading'
presentation = {
primary:
- downloading && engineOnline
- ? formatSpeed(transfer.speedBps)
- : statusLabel,
- secondary: !engineOnline
- ? t('panel.dashboard.tasks.secondary.offline')
- : [
- progress === null
- ? statusLabel
- : `${statusLabel} ${mediaProgressPercent(progress)}%`,
- task.mediaProgress
- ? t('panel.downloads.media.partsFormat', {
- completed: task.mediaProgress.download.completedParts,
- total: task.mediaProgress.download.totalParts,
- })
- : null,
- downloading && transfer.etaSec !== null
- ? t('panel.dashboard.tasks.secondary.eta', {
- time: formatEta(transfer.etaSec, i18n.language),
- })
- : null,
- ]
- .filter(Boolean)
- .join(' · '),
+ downloading && engineOnline ? formatSpeed(transfer.speedBps) : '',
+ secondary:
+ progress === null
+ ? statusLabel
+ : `${statusLabel} ${mediaProgressPercent(progress)}%`,
progress: progress === null ? null : mediaProgressPercent(progress),
indeterminate: progress === null,
}
@@ -258,123 +247,107 @@ function TaskRow({
switch (task.status) {
case TaskStatus.Downloading:
presentation = {
- primary: engineOnline ? formatSpeed(task.downloadSpeed) : '—',
- secondary: engineOnline
- ? `${statusLabel} · ${t('panel.dashboard.tasks.secondary.eta', {
- time: formatEta(task.etaSeconds, i18n.language),
- })}`
- : t('panel.dashboard.tasks.secondary.offline'),
+ primary: engineOnline ? formatSpeed(task.downloadSpeed) : '',
+ secondary: `${statusLabel} ${Math.round(clampProgress(task.progress))}%`,
progress: clampProgress(task.progress),
}
break
- case TaskStatus.FetchingMetadata:
- presentation = {
- primary: t('panel.dashboard.tasks.metric.fetching'),
- secondary: engineOnline
- ? t('panel.dashboard.tasks.secondary.metadata')
- : t('panel.dashboard.tasks.secondary.offline'),
- progress: null,
- }
- break
- case TaskStatus.MetadataReady:
- presentation = {
- primary: t('panel.dashboard.tasks.metric.ready'),
- secondary: engineOnline
- ? t('panel.dashboard.tasks.secondary.chooseFiles')
- : t('panel.dashboard.tasks.secondary.offline'),
- progress: null,
- }
- break
- case TaskStatus.Finalizing:
+ case TaskStatus.Paused: {
+ const progress = getDownloadProgress(task)
+ const percent =
+ progress === null
+ ? null
+ : isMediaTask(task)
+ ? mediaProgressPercent(progress)
+ : clampProgress(task.progress)
presentation = {
- primary: t('panel.dashboard.tasks.metric.finalizing'),
- secondary: engineOnline
- ? t('panel.dashboard.tasks.secondary.finalizing')
- : t('panel.dashboard.tasks.secondary.offline'),
- progress: null,
+ primary: '',
+ secondary:
+ percent === null
+ ? statusLabel
+ : `${statusLabel} ${Math.round(percent)}%`,
+ progress: percent,
}
break
+ }
case TaskStatus.Seeding:
presentation = {
- primary: engineOnline ? formatSpeed(task.uploadSpeed) : '—',
- secondary: engineOnline
- ? task.bt
- ? `${statusLabel} · ${t('panel.dashboard.tasks.secondary.ratio', {
- ratio: task.bt.ratio.toFixed(2),
- })}`
- : statusLabel
- : t('panel.dashboard.tasks.secondary.offline'),
- progress: null,
- }
- break
- case TaskStatus.Queued:
- presentation = {
- primary: t('panel.dashboard.tasks.metric.queued'),
- secondary: engineOnline
- ? t('panel.dashboard.tasks.secondary.waiting')
- : t('panel.dashboard.tasks.secondary.offline'),
- progress: null,
- }
- break
- case TaskStatus.Paused:
- presentation = {
- primary: t('panel.dashboard.tasks.metric.paused'),
- secondary: engineOnline
- ? t('panel.dashboard.tasks.secondary.saved', {
- percent:
- getDownloadProgress(task) === null
- ? '—'
- : isMediaTask(task)
- ? mediaProgressPercent(getDownloadProgress(task) ?? 0)
- : Math.round(clampProgress(task.progress)),
- })
- : t('panel.dashboard.tasks.secondary.offline'),
+ primary: engineOnline ? formatSpeed(task.uploadSpeed) : '',
+ secondary: statusLabel,
progress: null,
}
break
default:
- presentation = {
- primary: statusLabel,
- secondary: statusLabel,
- progress: null,
- }
+ presentation = { primary: '', secondary: statusLabel, progress: null }
}
}
- const setButtonRef = useCallback(
- (element: HTMLButtonElement | null) => {
- const previous = buttonRef.current
+ if (view === 'active' && !engineOnline) {
+ presentation.primary = ''
+ presentation.secondary = t('panel.dashboard.tasks.secondary.offline')
+ presentation.indeterminate = false
+ }
+
+ const setGroupRef = useCallback(
+ (element: HTMLDivElement | null) => {
if (
element === null &&
- previous !== null &&
- document.activeElement === previous
+ groupRef.current?.contains(document.activeElement)
) {
onFocusedRowRemoved()
}
- buttonRef.current = element
+ groupRef.current = element
},
[onFocusedRowRemoved]
)
- const Icon = TASK_TYPE_META[task.type].icon
const accessibleName = `${task.name}, ${statusLabel}`
- const accessibleDescription = technicalDetail
- ? `${presentation.primary}. ${presentation.secondary}. ${t(
- 'panel.dashboard.tasks.secondary.technicalDetail',
- { detail: technicalDetail }
- )}`
- : `${presentation.primary}. ${presentation.secondary}`
+ const accessibleDescription = [
+ presentation.secondary,
+ presentation.primary,
+ technicalDetail
+ ? t('panel.dashboard.tasks.secondary.technicalDetail', {
+ detail: technicalDetail,
+ })
+ : null,
+ ]
+ .filter(Boolean)
+ .join('. ')
const title = technicalDetail ? `${task.name}\n${technicalDetail}` : task.name
+ const hasQuickAction =
+ !summary &&
+ view !== 'recent' &&
+ (canPause(task) || canResume(task) || canAttemptRetry(task))
+ const hasProgress =
+ presentation.progress !== null || presentation.indeterminate
+ const progressPercent =
+ presentation.progress === null
+ ? null
+ : isMediaTask(task)
+ ? presentation.progress
+ : Math.round(presentation.progress)
+ const showStatusBadge = view === 'active' && engineOnline
return (
- <li className={cn('min-w-0 shrink-0 px-1', heightClass)}>
- {/* biome-ignore lint/a11y/useSemanticElements: The spec requires a named row group around one full-row interactive button and its sibling progress indicator. */}
+ <li
+ className={cn(
+ 'min-w-0 shrink-0',
+ !summary && 'border-b border-border/40 last:border-b-0',
+ heightClass
+ )}
+ >
+ {/* biome-ignore lint/a11y/useSemanticElements: A named group keeps navigation, the task action, and progress as accessible siblings. */}
<div
+ ref={setGroupRef}
role="group"
aria-label={task.name}
- className="relative h-full min-w-0"
+ className={cn(
+ 'relative grid h-full min-w-0 items-center',
+ hasQuickAction
+ ? 'grid-cols-[minmax(0,1fr)_auto] gap-x-2'
+ : 'grid-cols-1'
+ )}
>
<button
- ref={setButtonRef}
type="button"
data-testid="tasks-row"
data-task-id={task.id}
@@ -384,57 +357,86 @@ function TaskRow({
onClick={() => onOpen(task)}
className="absolute inset-0 z-0 rounded-md outline-none transition-colors hover:bg-accent/45 focus-visible:bg-accent/45 focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none"
/>
-
{summary ? (
<div
aria-hidden
- className="pointer-events-none relative z-10 flex h-full min-w-0 items-center gap-2 px-1 text-[12px] leading-none"
+ className="pointer-events-none relative z-10 flex h-full min-w-0 items-center gap-2 px-1 text-xs leading-none"
>
- <span className="min-w-0 flex-1 truncate font-medium">
- {task.name}
- </span>
- <span className="shrink-0 text-muted-foreground">
- {presentation.primary}
- </span>
+ <span className="min-w-0 truncate font-medium">{task.name}</span>
+ {showStatusBadge ? (
+ <StatusPill
+ status={task.status}
+ task={task}
+ compact
+ className="h-4 max-w-[55%] shrink-0 px-1 py-0 text-[10px] leading-4"
+ />
+ ) : (
+ <span className="max-w-[45%] shrink-0 truncate text-[11px] text-muted-foreground tabular-nums">
+ {presentation.primary || presentation.secondary}
+ </span>
+ )}
</div>
) : (
<div
aria-hidden
className={cn(
- 'pointer-events-none relative z-10 grid h-full min-w-0 grid-cols-[14px_minmax(0,1fr)_auto] grid-rows-2 items-center gap-x-2 px-1',
- verticalPaddingClass,
- (presentation.progress !== null || presentation.indeterminate) &&
- 'pb-1.5'
+ 'pointer-events-none relative z-10 col-start-1 row-start-1 flex h-full min-w-0 flex-col justify-center gap-0.5 px-1',
+ hasProgress && 'pb-1.5'
)}
>
- <Icon className="row-span-2 size-3.5 text-muted-foreground" />
- <span className="min-w-0 truncate text-[12px] font-medium leading-[13px]">
+ <span className="min-w-0 truncate text-[13px] font-medium leading-4">
{task.name}
</span>
- <span className="shrink-0 text-[11px] leading-[13px] text-muted-foreground">
- {presentation.primary}
- </span>
- <span className="col-span-2 min-w-0 truncate text-[10px] leading-[11px] text-muted-foreground">
- {presentation.secondary}
+ <span className="flex min-w-0 items-center gap-2 text-[11px] leading-3.5 text-muted-foreground tabular-nums">
+ {showStatusBadge ? (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <StatusPill
+ status={task.status}
+ task={task}
+ compact
+ className="h-4 min-w-0 px-1 py-0 text-[10px] leading-4"
+ />
+ {progressPercent !== null ? (
+ <span className="shrink-0">{progressPercent}%</span>
+ ) : null}
+ </span>
+ ) : (
+ <span
+ className={cn(
+ 'min-w-0 truncate',
+ view === 'failed' && 'text-destructive'
+ )}
+ >
+ {presentation.secondary}
+ </span>
+ )}
+ {presentation.primary ? (
+ <span className="shrink-0">{presentation.primary}</span>
+ ) : null}
</span>
</div>
)}
-
<span id={descriptionId} className="sr-only">
{accessibleDescription}
</span>
-
- {!summary &&
- (presentation.progress !== null || presentation.indeterminate) ? (
+ {!summary && hasProgress ? (
<Progress
value={presentation.progress ?? undefined}
aria-label={
t('panel.dashboard.tasks.progressLabel', { name: task.name }) +
(phase ? `: ${statusLabel}` : '')
}
- className="pointer-events-none absolute right-1 bottom-0.5 left-[26px] z-10 h-0.5 w-auto rounded-full"
+ className="pointer-events-none relative z-10 col-start-1 row-start-1 mx-1 mb-1 h-0.5 w-auto self-end rounded-full"
+ indicatorClassName={
+ task.status === TaskStatus.Paused || !engineOnline
+ ? 'bg-muted-foreground/50'
+ : undefined
+ }
/>
) : null}
+ {hasQuickAction ? (
+ <TaskQuickAction task={task} enabled={actionsEnabled} />
+ ) : null}
</div>
</li>
)
@@ -467,7 +469,6 @@ function LoadingRows({
const { t } = useTranslation()
const summary = viewport.contentLevel === 'summary'
const heightClass = rowHeightClass(viewport)
- const verticalPaddingClass = rowVerticalPaddingClass(viewport)
return (
<>
@@ -477,7 +478,7 @@ function LoadingRows({
<ul
aria-busy="true"
aria-label={t('panel.dashboard.tasks.loading')}
- className={cn('flex min-h-0 flex-1 flex-col', !summary && 'gap-1')}
+ className="flex min-h-0 flex-1 flex-col"
>
{Array.from({ length: count }, (_, index) => (
<li
@@ -490,13 +491,7 @@ function LoadingRows({
<Skeleton className="h-3 w-full" />
</div>
) : (
- <div
- className={cn(
- 'grid w-full grid-cols-[14px_1fr_auto] items-center gap-x-2 px-1',
- verticalPaddingClass
- )}
- >
- <Skeleton className="size-3.5 rounded-sm" />
+ <div className="grid w-full grid-cols-[1fr_auto] items-center gap-x-4 px-1">
<div className="grid gap-1">
<Skeleton className="h-2.5 w-3/4" />
<Skeleton className="h-2 w-1/2" />
@@ -536,16 +531,15 @@ export function TasksTile({
const limit = rowLimit(viewport)
const summary = viewport.contentLevel === 'summary'
const heightClass = rowHeightClass(viewport)
- const verticalPaddingClass = rowVerticalPaddingClass(viewport)
- const topPaddingClass = bodyTopPaddingClass(viewport)
const projection = useMemo(
() => projectTaskWindow(source.tasks, view, limit),
[source.tasks, view, limit]
)
const hasOverflow = projection.total > limit
- const visibleRows = hasOverflow
- ? projection.rows.slice(0, limit - 1)
- : projection.rows
+ const visibleRows =
+ hasOverflow && summary
+ ? projection.rows.slice(0, limit - 1)
+ : projection.rows
const overflowCount = projection.total - visibleRows.length
const viewOptions = [
{
@@ -616,7 +610,7 @@ export function TasksTile({
variant="outline"
onClick={() => void openAddTaskDialog()}
>
- + {t('panel.dashboard.tasks.newTask')}
+ {t('panel.dashboard.tasks.newTask')}
</Button>
) : undefined
}
@@ -638,7 +632,7 @@ export function TasksTile({
data-testid="tasks-list"
data-view={view}
data-presentation={spanKey(viewport)}
- className={cn('flex min-h-0 flex-1 flex-col', !summary && 'gap-1')}
+ className="flex min-h-0 flex-1 flex-col"
>
{visibleRows.map((task) => (
<TaskRow
@@ -647,23 +641,20 @@ export function TasksTile({
view={view}
summary={summary}
engineOnline={online}
+ actionsEnabled={online && source.status === 'ready' && !fixture}
now={displayNow}
heightClass={heightClass}
- verticalPaddingClass={verticalPaddingClass}
onOpen={openTask}
onFocusedRowRemoved={focusSelectedSegment}
/>
))}
{hasOverflow ? (
- <li className={cn('min-w-0 shrink-0 px-1', heightClass)}>
+ <li className="mt-auto min-w-0 shrink-0 pt-1">
<button
type="button"
data-testid="tasks-more"
onClick={() => navigate(routeForView)}
- className={cn(
- 'flex h-full w-full items-center rounded-md pr-1 text-left text-[11px] leading-none font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/45 hover:text-foreground focus-visible:bg-accent/45 focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none',
- summary ? 'pl-1' : 'pl-[26px]'
- )}
+ className="flex h-6 w-full items-center rounded-md px-1 text-left text-[11px] leading-none font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/45 hover:text-foreground focus-visible:bg-accent/45 focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none"
>
{t('panel.dashboard.tasks.more', { count: overflowCount })}
</button>
@@ -686,7 +677,7 @@ export function TasksTile({
/>
}
className={className}
- bodyClassName={cn('min-h-0', topPaddingClass)}
+ bodyClassName={cn('min-h-0', !summary && 'pt-2')}
>
{content}
</TileShell>
diff --git a/src/renderer/routes/downloads/columns.ts b/src/renderer/routes/downloads/columns.ts
index e6dce6cd..ab666138 100644
--- a/src/renderer/routes/downloads/columns.ts
+++ b/src/renderer/routes/downloads/columns.ts
@@ -7,12 +7,12 @@ export const TASK_COLUMNS: Record<
TaskSortColumn,
{ width: number; min: number; max: number; numeric?: boolean }
> = {
- name: { width: 240, min: 160, max: 900 },
+ name: { width: 200, min: 160, max: 900 },
size: { width: 84, min: 72, max: 240, numeric: true },
- progress: { width: 120, min: 100, max: 300, numeric: true },
+ progress: { width: 104, min: 100, max: 300, numeric: true },
status: { width: 100, min: 80, max: 240 },
- down: { width: 140, min: 140, max: 240, numeric: true },
- up: { width: 140, min: 140, max: 240, numeric: true },
+ down: { width: 128, min: 128, max: 240, numeric: true },
+ up: { width: 128, min: 128, max: 240, numeric: true },
eta: { width: 112, min: 112, max: 240, numeric: true },
connections: { width: 90, min: 72, max: 240, numeric: true },
createdAt: { width: 196, min: 140, max: 300 },
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.tsx b/src/renderer/routes/downloads/inspector/overview-tab.tsx
index 788b31fc..2736db2c 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.tsx
@@ -284,7 +284,7 @@ export function OverviewTab({
<div className="flex items-center gap-2">
<Tooltip>
<TooltipTrigger render={<span className="tabular-nums" />}>
- {`${task.infoHash.slice(0, 4)}…${task.infoHash.slice(-4)}`}
+ {`${task.infoHash.slice(0, 6)}...${task.infoHash.slice(-6)}`}
</TooltipTrigger>
<TooltipContent side="left">{task.infoHash}</TooltipContent>
</Tooltip>
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
index c5ef4182..8cb82115 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
@@ -335,16 +335,24 @@ describe('TaskInspectorActionBar', () => {
expect(screen.queryByText('(1)')).toBeNull()
})
- it('clicking Remove opens the confirmation dialog', () => {
- render(
- <TaskInspectorActionBar
- selected={[makeTask({ status: TaskStatus.Downloading })]}
- onClose={vi.fn()}
- />
- )
- fireEvent.click(screen.getByRole('button', { name: /Remove/ }))
- expect(screen.getByText(/Remove “sample”\?/)).toBeDefined()
- })
+ it.each([false, true])(
+ 'clicking Remove preserves Shift=%s in the confirmation dialog',
+ (shift) => {
+ render(
+ <TaskInspectorActionBar
+ selected={[makeTask({ status: TaskStatus.Downloading })]}
+ onClose={vi.fn()}
+ />
+ )
+ fireEvent.click(screen.getByRole('button', { name: /Remove/ }), {
+ shiftKey: shift,
+ })
+ expect(screen.getByText(/Remove “sample”\?/)).toBeDefined()
+ expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe(
+ String(shift)
+ )
+ }
+ )
describe('Copy URL', () => {
beforeEach(() => {
diff --git a/src/renderer/routes/downloads/status-pill.tsx b/src/renderer/routes/downloads/status-pill.tsx
index 5ec555a9..4c4cef28 100644
--- a/src/renderer/routes/downloads/status-pill.tsx
+++ b/src/renderer/routes/downloads/status-pill.tsx
@@ -24,10 +24,12 @@ export function StatusPill({
status,
compact = false,
task,
+ className,
}: {
status: TaskStatus
task?: DownloadTask
compact?: boolean
+ className?: string
}) {
const { t } = useTranslation()
const tone = getStatusTone(
@@ -37,12 +39,14 @@ export function StatusPill({
return (
<span
data-testid="task-status-pill"
+ title={t(label)}
className={cn(
compact
? 'inline-flex w-fit max-w-full items-center rounded px-1.5 py-0.5 text-[11px] leading-4'
: 'inline-flex w-fit max-w-full shrink-0 items-center rounded-full px-2 py-0.5 text-[11px] font-medium',
tone.bg,
- tone.text
+ tone.text,
+ className
)}
>
<span className="truncate">{t(label)}</span>
diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsx
index 300146ac..7c393f0d 100644
--- a/src/renderer/routes/downloads/task-actions-menu.test.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx
@@ -525,6 +525,65 @@ describe('TaskActionsMenu', () => {
})
describe('organized task menu and keyboard actions', () => {
+ it.each([
+ [true, false],
+ [true, true],
+ [false, false],
+ [false, true],
+ ])(
+ 'preserves Shift on Remove (context menu: %s, shift: %s)',
+ async (context, shift) => {
+ setup(context)
+ if (context) fireEvent.contextMenu(screen.getByText('b'))
+ else await userEvent.click(screen.getByRole('button', { name: 'More' }))
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove' }), {
+ shiftKey: shift,
+ })
+ const checkbox = await screen.findByRole('checkbox')
+ expect(checkbox).toHaveAttribute('aria-checked', String(shift))
+ expect(transport.invoke).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledExactlyOnceWith(
+ Commands.RemoveTasks,
+ {
+ taskIds: ['a', 'b'],
+ deleteWithFiles: shift,
+ }
+ )
+ )
+ }
+ )
+
+ it.each(['darwin', 'win32', 'linux'] as const)(
+ 'prechecks files for the shifted removal shortcut on %s without deleting immediately',
+ async (platform) => {
+ vi.mocked(transport).platform = platform
+ setup()
+ const list = screen.getByTestId('context-list')
+ const shortcut = {
+ key: platform === 'darwin' ? 'Backspace' : 'Delete',
+ metaKey: platform === 'darwin',
+ }
+ fireEvent.keyDown(list, { ...shortcut, shiftKey: true })
+ expect(await screen.findByRole('checkbox')).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ expect(transport.invoke).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ )
+ fireEvent.keyDown(list, shortcut)
+ expect(await screen.findByRole('checkbox')).toHaveAttribute(
+ 'aria-checked',
+ 'false'
+ )
+ expect(transport.invoke).not.toHaveBeenCalled()
+ }
+ )
+
it('groups completed-task access, clipboard, creation and removal in that order', async () => {
setup(true, [
makeDownloadTask({
@@ -652,6 +711,12 @@ describe('organized task menu and keyboard actions', () => {
fireEvent.keyDown(list, { key: 'i', metaKey: true, shiftKey: true })
fireEvent.keyDown(list, { key: 'i', metaKey: true, repeat: true })
fireEvent.keyDown(list, { key: 'Backspace' })
+ fireEvent.keyDown(list, {
+ key: 'Backspace',
+ metaKey: true,
+ shiftKey: true,
+ altKey: true,
+ })
expect(useDownloadsView.getState().inspectorVisible).toBe(false)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(navigator.clipboard.writeText).not.toHaveBeenCalled()
diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsx
index e7e5f267..b28b224b 100644
--- a/src/renderer/routes/downloads/task-actions-menu.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.tsx
@@ -216,7 +216,8 @@ export function TaskActionsMenu({
? 'inspector'
: matchesTaskMenuShortcut(event, shortcuts.copyUrl)
? 'copy'
- : matchesTaskMenuShortcut(event, shortcuts.remove)
+ : matchesTaskMenuShortcut(event, shortcuts.remove) ||
+ matchesTaskMenuShortcut(event, shortcuts.removeWithFiles)
? 'remove'
: null
if (!action || (action !== 'inspector' && selected.length === 0)) return
@@ -231,7 +232,7 @@ export function TaskActionsMenu({
} else if (action === 'copy') {
copy(() => copyTaskUrls(selected))
} else if (actions.removeCount > 0 && !actions.removeDialog.open) {
- actions.onRemove()
+ actions.onRemove({ shift: event.shiftKey })
}
closeMenu()
}
@@ -472,7 +473,7 @@ export function TaskActionsMenu({
<DropdownMenuItem
variant="destructive"
aria-keyshortcuts={shortcuts.remove.aria}
- onClick={() => actions.onRemove()}
+ onClick={(event) => actions.onRemove({ shift: event.shiftKey })}
>
{t('panel.downloads.action.remove')}
<DropdownMenuShortcut aria-hidden="true">
diff --git a/src/renderer/routes/downloads/task-column-header.test.tsx b/src/renderer/routes/downloads/task-column-header.test.tsx
index 9bef7e1c..b3fd41df 100644
--- a/src/renderer/routes/downloads/task-column-header.test.tsx
+++ b/src/renderer/routes/downloads/task-column-header.test.tsx
@@ -19,6 +19,9 @@ describe('TaskColumnHeader', () => {
)
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
expect(container.querySelector('button svg')).toBeNull()
+ const download = screen.getByRole('button', { name: 'Download speed' })
+ expect(download).toHaveTextContent(/^Download$/)
+ expect(download).toHaveAttribute('title', 'Sort Download speed descending')
await user.hover(screen.getByRole('button', { name: 'Name' }))
expect(container.querySelector('button svg')).toBeNull()
rerender(
@@ -68,7 +71,7 @@ describe('TaskColumnHeader', () => {
screen.getByRole('separator', { name: 'Resize Name column' }),
{ key: 'ArrowRight' }
)
- expect(useDownloadsView.getState().columns[0].width).toBe(256)
+ expect(useDownloadsView.getState().columns[0].width).toBe(216)
fireEvent.keyDown(screen.getByRole('button', { name: 'Name' }), {
key: 'ArrowRight',
shiftKey: true,
diff --git a/src/renderer/routes/downloads/task-column-header.tsx b/src/renderer/routes/downloads/task-column-header.tsx
index 600e317b..ac261dae 100644
--- a/src/renderer/routes/downloads/task-column-header.tsx
+++ b/src/renderer/routes/downloads/task-column-header.tsx
@@ -50,11 +50,15 @@ export function TaskColumnHeader({
{columns.map((column, index) => {
const id = column.id
const active = sort?.column === id
- const label = t(`panel.downloads.column.${id}`)
- const accessibleLabel =
- id === 'down' || id === 'up'
- ? t(`panel.downloads.sort.${id}`)
- : label
+ const speedColumn = id === 'down' || id === 'up'
+ const label = t(
+ speedColumn
+ ? `panel.downloads.columnHeader.${id}`
+ : `panel.downloads.column.${id}`
+ )
+ const accessibleLabel = speedColumn
+ ? t(`panel.downloads.sort.${id}`)
+ : label
const next = nextTaskSort(sort, id)
const SortIcon = sort?.direction === 'asc' ? ChevronUp : ChevronDown
return (
diff --git a/src/renderer/routes/downloads/task-menu-shortcuts.test.ts b/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
index 594f11c6..6fd56a3c 100644
--- a/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
+++ b/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
@@ -14,10 +14,17 @@ describe('task menu shortcuts', () => {
label: '⌘⌫',
aria: 'Meta+Backspace',
})
+ expect(bindings.removeWithFiles).toMatchObject({
+ label: '⇧⌘⌫',
+ aria: 'Shift+Meta+Backspace',
+ })
})
it('uses Ctrl and Delete on Windows/Linux, and the web new-task override on Mac', () => {
expect(taskMenuShortcuts(false, true).copyUrl.label).toBe('Ctrl+C')
expect(taskMenuShortcuts(false, true).remove.label).toBe('Delete')
+ expect(taskMenuShortcuts(false, true).removeWithFiles.label).toBe(
+ 'Shift+Delete'
+ )
expect(taskMenuShortcuts(true, false).newTask).toBeNull()
})
it('matches exact modifiers and never treats bare macOS Backspace as Remove', () => {
diff --git a/src/renderer/routes/downloads/task-menu-shortcuts.ts b/src/renderer/routes/downloads/task-menu-shortcuts.ts
index bd4b4e57..f5f0bac7 100644
--- a/src/renderer/routes/downloads/task-menu-shortcuts.ts
+++ b/src/renderer/routes/downloads/task-menu-shortcuts.ts
@@ -55,6 +55,10 @@ export function taskMenuShortcuts(macOS: boolean, desktop: boolean) {
inspector: shortcut('CommandOrControl+I', macOS),
copyUrl: shortcut('CommandOrControl+C', macOS),
remove: shortcut(macOS ? 'Command+Backspace' : 'Delete', macOS),
+ removeWithFiles: shortcut(
+ macOS ? 'Command+Shift+Backspace' : 'Shift+Delete',
+ macOS
+ ),
}
}
diff --git a/src/renderer/routes/downloads/task-row.test.tsx b/src/renderer/routes/downloads/task-row.test.tsx
index 8af3d8ca..90680bb7 100644
--- a/src/renderer/routes/downloads/task-row.test.tsx
+++ b/src/renderer/routes/downloads/task-row.test.tsx
@@ -178,7 +178,7 @@ describe('TaskRow', () => {
it('uses the same minimum width as the scrollable column header', () => {
const { container } = render(<TaskRow task={fake()} rowProps={rowProps} />)
- expect(container.firstChild).toHaveStyle({ minWidth: '1310px' })
+ expect(container.firstChild).toHaveStyle({ minWidth: '1362px' })
})
it('renders localized creation and completion timestamps and refreshes on completion', () => {
diff --git a/src/renderer/routes/downloads/view-preferences.test.ts b/src/renderer/routes/downloads/view-preferences.test.ts
index e4da8526..b3574e40 100644
--- a/src/renderer/routes/downloads/view-preferences.test.ts
+++ b/src/renderer/routes/downloads/view-preferences.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { defaultTaskColumns } from './columns'
import { createDownloadsViewStore } from './view-preferences'
beforeEach(() => localStorage.clear())
@@ -8,6 +9,40 @@ afterEach(() => {
})
describe('Downloads view preferences', () => {
+ it('updates the previous default layout without changing inspector preferences', () => {
+ const columns = defaultTaskColumns().map((column) => ({
+ ...column,
+ width:
+ column.id === 'name'
+ ? 240
+ : column.id === 'progress'
+ ? 120
+ : column.id === 'down' || column.id === 'up'
+ ? 140
+ : column.width,
+ }))
+ const saved = {
+ version: 1,
+ columns,
+ inspectorVisible: true,
+ inspectorSnap: 'expanded',
+ }
+ localStorage.setItem('motrix.downloads.view.v1', JSON.stringify(saved))
+ const restored = createDownloadsViewStore().getState()
+ expect(restored.columns).toEqual(defaultTaskColumns())
+ expect(restored.inspectorVisible).toBe(true)
+ expect(restored.inspectorSnap).toBe('expanded')
+ restored.persist()
+ expect(createDownloadsViewStore().getState().columns).toEqual(
+ defaultTaskColumns()
+ )
+
+ // A customized layout must retain its other widths as well.
+ columns[0].width = 320
+ localStorage.setItem('motrix.downloads.view.v1', JSON.stringify(saved))
+ expect(createDownloadsViewStore().getState().columns).toEqual(columns)
+ })
+
it('shares the inspector tab during the session without persisting it', () => {
const store = createDownloadsViewStore()
store.getState().setInspectorTab('files')
diff --git a/src/renderer/routes/downloads/view-preferences.ts b/src/renderer/routes/downloads/view-preferences.ts
index d4646d5b..db960080 100644
--- a/src/renderer/routes/downloads/view-preferences.ts
+++ b/src/renderer/routes/downloads/view-preferences.ts
@@ -8,8 +8,14 @@ import {
import { TASK_SORT_COLUMNS, type TaskSortColumn } from './sort'
const STORAGE_KEY = 'motrix.downloads.view.v1'
+const PREVIOUS_DEFAULT_WIDTHS: Partial<Record<TaskSortColumn, number>> = {
+ name: 240,
+ progress: 120,
+ down: 140,
+ up: 140,
+}
const ViewPreferencesSchema = z.object({
- version: z.literal(1),
+ version: z.union([z.literal(1), z.literal(2)]),
columns: z
.array(
z.object({
@@ -30,7 +36,7 @@ const ViewPreferencesSchema = z.object({
function defaults() {
return {
- version: 1 as const,
+ version: 2 as const,
columns: defaultTaskColumns(),
inspectorVisible: false,
inspectorSnap: 'medium' as const,
@@ -42,13 +48,28 @@ function readPreferences() {
const saved = ViewPreferencesSchema.parse(
JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null')
)
+ const columns = saved.columns.map((column) => ({
+ ...column,
+ width: clampColumnWidth(column.id, column.width),
+ visible: column.id === 'name' || column.visible,
+ }))
+ const defaultColumns = defaultTaskColumns()
+ // Only migrate the untouched old layout; preserve custom widths and order.
+ const oldDefaults =
+ saved.version === 1 &&
+ columns.every((column, index) => {
+ const current = defaultColumns[index]
+ const oldWidth = PREVIOUS_DEFAULT_WIDTHS[column.id] ?? current.width
+ return (
+ column.id === current.id &&
+ column.visible &&
+ column.width === oldWidth
+ )
+ })
return {
...saved,
- columns: saved.columns.map((column) => ({
- ...column,
- width: clampColumnWidth(column.id, column.width),
- visible: column.id === 'name' || column.visible,
- })),
+ version: 2 as const,
+ columns: oldDefaults ? defaultColumns : columns,
}
} catch {
return defaults()
@@ -89,7 +110,7 @@ export function createDownloadsViewStore() {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
- version: 1,
+ version: 2,
columns,
inspectorVisible,
inspectorSnap,
diff --git a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
index 086d08e7..8a92a092 100644
--- a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
@@ -22,10 +22,18 @@ import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { DownloadsDialog } from './downloads-dialog'
-const { toastAddMock } = vi.hoisted(() => ({ toastAddMock: vi.fn() }))
+const { toastAddMock, runtime } = vi.hoisted(() => ({
+ toastAddMock: vi.fn(),
+ runtime: { platform: 'darwin' },
+}))
vi.mock('@renderer/lib/transport', () => ({
- transport: { invoke: vi.fn() },
+ transport: {
+ invoke: vi.fn(),
+ get platform() {
+ return runtime.platform
+ },
+ },
}))
vi.mock('@renderer/components/ui/toast', () => ({
@@ -85,6 +93,7 @@ afterEach(() => {
describe('<DownloadsDialog>', () => {
beforeEach(async () => {
+ runtime.platform = 'darwin'
await i18n.changeLanguage('en-US')
vi.mocked(transport.invoke).mockReset()
toastAddMock.mockReset()
@@ -94,6 +103,87 @@ describe('<DownloadsDialog>', () => {
})
})
+ it('defaults desktop deletion to trash and saves only the chosen mode with a warning', async () => {
+ render(
+ <DownloadsDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )
+ const deletion = await screen.findByRole('combobox', {
+ name: 'When deleting task files',
+ })
+ await waitFor(() =>
+ expect(screen.getByLabelText(/magnet resolve timeout/i)).toHaveValue(120)
+ )
+ expect(deletion).toHaveTextContent('Move to trash')
+ const user = userEvent.setup()
+ await user.click(deletion)
+ await user.click(
+ await screen.findByRole('option', { name: 'Delete permanently' })
+ )
+ expect(
+ screen.getByText(
+ 'Files are deleted directly and cannot be restored from the trash.'
+ )
+ ).toBeVisible()
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: { fileDeletionMode: 'permanent' },
+ })
+ })
+
+ it('hydrates a saved deletion mode and can switch back to trash', async () => {
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetSettings)
+ return { ...FIXTURE, app: { fileDeletionMode: 'permanent' } }
+ return { saved: true, requiresRestart: false, changedRestartKeys: [] }
+ })
+ render(
+ <DownloadsDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )
+ const deletion = await screen.findByRole('combobox', {
+ name: 'When deleting task files',
+ })
+ await waitFor(() =>
+ expect(deletion).toHaveTextContent('Delete permanently')
+ )
+ const user = userEvent.setup()
+ await user.click(deletion)
+ await user.click(
+ await screen.findByRole('option', { name: 'Move to trash' })
+ )
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: { fileDeletionMode: 'trash' },
+ })
+ })
+
+ it('hides the desktop deletion preference in the web client', async () => {
+ runtime.platform = 'web'
+ render(
+ <DownloadsDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )
+ await waitFor(() =>
+ expect(screen.getByLabelText(/magnet resolve timeout/i)).toHaveValue(120)
+ )
+ expect(
+ screen.queryByRole('combobox', { name: 'When deleting task files' })
+ ).not.toBeInTheDocument()
+ })
+
it('hydrates and submits dirty fields without restart confirm for non-RESTART change', async () => {
const onClose = vi.fn()
render(
diff --git a/src/renderer/routes/settings/cards/downloads-dialog.tsx b/src/renderer/routes/settings/cards/downloads-dialog.tsx
index 3f4d0a74..57d29390 100644
--- a/src/renderer/routes/settings/cards/downloads-dialog.tsx
+++ b/src/renderer/routes/settings/cards/downloads-dialog.tsx
@@ -71,6 +71,11 @@ export function DownloadsDialog({
if (cancelled) return
const all = data as AppSettings
form.reset({
+ app: {
+ fileDeletionMode:
+ all?.app?.fileDeletionMode ??
+ DOWNLOADS_DEFAULTS.app.fileDeletionMode,
+ },
engine: all?.engine
? { ...ENGINE_DEFAULTS, ...all.engine }
: ENGINE_DEFAULTS,
@@ -91,10 +96,8 @@ export function DownloadsDialog({
const onSubmit = useSettingsSubmit(form, async (values) => {
// pickDirty recurses the dirty-fields tree: if speedLimit.base.download
// is dirty, it returns { speedLimit: { base: { download: <new> } } }.
- // We then spread the engine dirty patch back into { engine: ... } and pass
- // the whole thing to UpdateSettings. SettingsManager deep-merges each
- // top-level namespace, so partial patches for both engine and speedLimit
- // are safe.
+ // SettingsManager deep-merges each top-level namespace, so partial
+ // patches for app, engine, and speedLimit are safe.
// biome-ignore lint/suspicious/noExplicitAny: dirtyFields shape doesn't fit DirtyTree; cast is safe
const dirty = pickDirty(values, form.formState.dirtyFields as any)
if (!dirty) {
diff --git a/src/renderer/routes/settings/cards/downloads-form.ts b/src/renderer/routes/settings/cards/downloads-form.ts
index 55f3a0f8..3ef36326 100644
--- a/src/renderer/routes/settings/cards/downloads-form.ts
+++ b/src/renderer/routes/settings/cards/downloads-form.ts
@@ -1,5 +1,9 @@
import { settingsValidationError } from '@renderer/lib/settings-validation'
import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas'
+import {
+ appSettingsInputSchema,
+ DEFAULT_APP_SETTINGS,
+} from '@shared/schemas/app-settings'
import { engineSettingsInputSchema } from '@shared/schemas/engine-settings'
import {
DEFAULT_SPEED_LIMIT_SETTINGS,
@@ -9,13 +13,11 @@ import type { TFunction } from 'i18next'
import { z } from 'zod'
// ─── Form shape ────────────────────────────────────────────────────────────────
-// The form combines the engine settings subset with the full speedLimit
-// namespace. On submit, pickDirty recurses the dirty-fields tree and returns
-// only changed keys at every level, so { engine: {...}, speedLimit: {...} } is
-// built correctly. UpdateSettings deep-merges each top-level namespace, so a
-// partial speedLimit patch (only the changed sub-fields) is safe.
+// On submit, pickDirty returns only changed keys across app, engine, and
+// speedLimit. UpdateSettings deep-merges each top-level namespace.
export const downloadsFormSchema = z.object({
+ app: appSettingsInputSchema.pick({ fileDeletionMode: true }),
engine: engineSettingsInputSchema.pick({
performanceProfile: true,
maxConcurrentDownloads: true,
@@ -72,6 +74,7 @@ export const ENGINE_DEFAULTS: EngineFields = {
}
export const DOWNLOADS_DEFAULTS: DownloadsFields = {
+ app: { fileDeletionMode: DEFAULT_APP_SETTINGS.fileDeletionMode },
engine: ENGINE_DEFAULTS,
// Source of truth: src/shared/schemas/speed-limit.ts (DEFAULT_SPEED_LIMIT_SETTINGS).
speedLimit: DEFAULT_SPEED_LIMIT_SETTINGS,
diff --git a/src/renderer/routes/settings/cards/engine-tuning-section.tsx b/src/renderer/routes/settings/cards/engine-tuning-section.tsx
index dc34ae89..bed15aac 100644
--- a/src/renderer/routes/settings/cards/engine-tuning-section.tsx
+++ b/src/renderer/routes/settings/cards/engine-tuning-section.tsx
@@ -18,6 +18,7 @@ import {
SelectValue,
} from '@renderer/components/ui/select'
import { Separator } from '@renderer/components/ui/separator'
+import { transport } from '@renderer/lib/transport'
import { BUILTIN_USER_AGENTS } from '@shared/constants/user-agents'
import type { UseFormReturn } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
@@ -32,6 +33,13 @@ export function EngineTuningSection({
form: UseFormReturn<DownloadsFields>
}) {
const { t } = useTranslation()
+ const fileDeletionOptions = [
+ { value: 'trash', label: t('settings.downloads.disk.fileDeletionTrash') },
+ {
+ value: 'permanent',
+ label: t('settings.downloads.disk.fileDeletionPermanent'),
+ },
+ ] as const
const fileAllocationOptions = [
{
value: 'none',
@@ -152,6 +160,50 @@ export function EngineTuningSection({
<h3 className="text-sm font-semibold text-foreground">
{t('settings.downloads.disk.title')}
</h3>
+ {transport.platform !== 'web' && (
+ <FormField
+ control={form.control}
+ name="app.fileDeletionMode"
+ render={({ field }) => (
+ <SettingsFormRow className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
+ <div className="min-w-0 flex-1 space-y-1">
+ <FormLabel>
+ {t('settings.downloads.disk.fileDeletionMode')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t(
+ field.value === 'permanent'
+ ? 'settings.downloads.disk.fileDeletionPermanentDesc'
+ : 'settings.downloads.disk.fileDeletionTrashDesc'
+ )}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Select
+ items={fileDeletionOptions}
+ value={field.value}
+ onValueChange={(value) => {
+ if (value !== null) field.onChange(value)
+ }}
+ >
+ <SettingsSelectTrigger>
+ <SelectValue />
+ </SettingsSelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {fileDeletionOptions.map(({ label, value }) => (
+ <SelectItem key={value} value={value}>
+ {label}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ )}
<FormField
control={form.control}
name="engine.fileAllocation"
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 3a0c0e2f..33cbb9d0 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -373,13 +373,13 @@
},
"secondary": {
"metadata": "Fetching metadata",
- "chooseFiles": "Choose files",
+ "chooseFiles": "Awaiting file selection",
"finalizing": "Finishing download",
"waiting": "Waiting to start",
"eta": "ETA {{time}}",
"ratio": "Ratio {{ratio}}",
"saved": "{{percent}}% saved",
- "offline": "Offline · last known progress",
+ "offline": "Offline (last known progress)",
"completed": "Completed {{time}}",
"failed": "Failed: {{reason}}",
"technicalDetail": "Technical detail: {{detail}}"
@@ -567,7 +567,7 @@
"status": {
"queued": "Queued",
"fetchingMetadata": "Fetching",
- "metadataReady": "Ready",
+ "metadataReady": "Awaiting file selection",
"downloading": "Downloading",
"finalizing": "Finalizing",
"seeding": "Seeding",
@@ -587,6 +587,10 @@
"createdAt": "Date created",
"finishedAt": "Date completed"
},
+ "columnHeader": {
+ "down": "Download",
+ "up": "Upload"
+ },
"timestamp": {
"notRecorded": "Not recorded",
"notCompleted": "Not completed yet",
@@ -655,8 +659,8 @@
"general": "General",
"createdAt": "Created",
"finishedAt": "Completed",
- "downSpeed": "↓ speed",
- "upSpeed": "↑ speed",
+ "downSpeed": "Download speed",
+ "upSpeed": "Upload speed",
"eta": "ETA",
"downloaded": "Downloaded",
"totalSize": "Total size",
@@ -1441,6 +1445,11 @@
},
"disk": {
"title": "Disk and session",
+ "fileDeletionMode": "When deleting task files",
+ "fileDeletionTrash": "Move to trash",
+ "fileDeletionPermanent": "Delete permanently",
+ "fileDeletionTrashDesc": "Applies when removing tasks with their files. Files stay in the trash until it is emptied.",
+ "fileDeletionPermanentDesc": "Files are deleted directly and cannot be restored from the trash.",
"fileAllocation": "File allocation",
"fileAllocationDesc": "How aria2 reserves disk space for new files.",
"fileAllocationNone": "None",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index df0a3956..367f70cf 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -372,13 +372,13 @@
},
"secondary": {
"metadata": "正在获取元数据",
- "chooseFiles": "选择文件",
+ "chooseFiles": "等待选择文件",
"finalizing": "正在完成下载",
"waiting": "等待开始",
"eta": "预计 {{time}}",
"ratio": "分享率 {{ratio}}",
"saved": "已保存 {{percent}}%",
- "offline": "离线 · 显示上次进度",
+ "offline": "离线(显示上次进度)",
"completed": "完成于 {{time}}",
"failed": "失败:{{reason}}",
"technicalDetail": "技术详情:{{detail}}"
@@ -564,7 +564,7 @@
"status": {
"queued": "排队中",
"fetchingMetadata": "获取信息中",
- "metadataReady": "待选文件",
+ "metadataReady": "等待选择文件",
"downloading": "下载中",
"finalizing": "收尾中",
"seeding": "做种中",
@@ -584,6 +584,10 @@
"createdAt": "创建时间",
"finishedAt": "完成时间"
},
+ "columnHeader": {
+ "down": "下载速度",
+ "up": "上传速度"
+ },
"timestamp": {
"notRecorded": "未记录",
"notCompleted": "尚未完成",
@@ -652,8 +656,8 @@
"general": "常规",
"createdAt": "创建时间",
"finishedAt": "完成时间",
- "downSpeed": "↓ 速度",
- "upSpeed": "↑ 速度",
+ "downSpeed": "下载速度",
+ "upSpeed": "上传速度",
"eta": "ETA",
"downloaded": "已下载",
"totalSize": "大小",
@@ -1426,6 +1430,11 @@
"lowestSpeedLimitDesc": "速度低于此值时断开。0 表示关闭。"
},
"disk": {
+ "fileDeletionMode": "删除任务文件时",
+ "fileDeletionTrash": "移到回收站",
+ "fileDeletionPermanent": "直接删除",
+ "fileDeletionTrashDesc": "适用于移除任务时同时删除文件。清空回收站后才会释放磁盘空间。",
+ "fileDeletionPermanentDesc": "文件将直接删除,无法从回收站恢复。",
"title": "磁盘与会话",
"fileAllocation": "文件预分配",
"fileAllocationDesc": "aria2 如何为新文件预留磁盘空间。",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index d4f1fb80..b68b1d81 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -372,13 +372,13 @@
},
"secondary": {
"metadata": "正在取得中繼資料",
- "chooseFiles": "選擇檔案",
+ "chooseFiles": "等待選擇檔案",
"finalizing": "正在完成下載",
"waiting": "等待開始",
"eta": "預估剩餘 {{time}}",
"ratio": "分享率 {{ratio}}",
"saved": "已儲存 {{percent}}%",
- "offline": "離線 · 上次已知的進度",
+ "offline": "離線(顯示上次進度)",
"completed": "完成於 {{time}}",
"failed": "失敗:{{reason}}",
"technicalDetail": "技術詳細資料:{{detail}}"
@@ -564,7 +564,7 @@
"status": {
"queued": "排隊中",
"fetchingMetadata": "取得中",
- "metadataReady": "就緒",
+ "metadataReady": "等待選擇檔案",
"downloading": "下載中",
"finalizing": "完成中",
"seeding": "做種中",
@@ -584,6 +584,10 @@
"createdAt": "建立時間",
"finishedAt": "完成時間"
},
+ "columnHeader": {
+ "down": "下載速度",
+ "up": "上傳速度"
+ },
"timestamp": {
"notRecorded": "未記錄",
"notCompleted": "尚未完成",
@@ -652,8 +656,8 @@
"general": "一般",
"createdAt": "建立時間",
"finishedAt": "完成時間",
- "downSpeed": "↓ 速度",
- "upSpeed": "↑ 速度",
+ "downSpeed": "下載速度",
+ "upSpeed": "上傳速度",
"eta": "預估剩餘時間",
"downloaded": "已下載",
"totalSize": "總大小",
@@ -1426,6 +1430,11 @@
"lowestSpeedLimitDesc": "低於此速度時中斷連線。0 = 停用。"
},
"disk": {
+ "fileDeletionMode": "刪除任務檔案時",
+ "fileDeletionTrash": "移至資源回收筒",
+ "fileDeletionPermanent": "直接刪除",
+ "fileDeletionTrashDesc": "適用於移除任務時一併刪除檔案。清空資源回收筒後才會釋放磁碟空間。",
+ "fileDeletionPermanentDesc": "檔案將直接刪除,無法從資源回收筒還原。",
"title": "磁碟與工作階段",
"fileAllocation": "檔案配置",
"fileAllocationDesc": "aria2 為新檔案保留磁碟空間的方式。",
diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.ts
index d1c512d0..3b6a9693 100644
--- a/src/shared/schemas/app-settings.test.ts
+++ b/src/shared/schemas/app-settings.test.ts
@@ -6,6 +6,23 @@ import {
} from './app-settings'
describe('appSettingsSchema', () => {
+ it('defaults existing and invalid file deletion preferences to trash', () => {
+ expect(DEFAULT_APP_SETTINGS.fileDeletionMode).toBe('trash')
+ for (const fileDeletionMode of [undefined, null, 'delete', false]) {
+ expect(
+ appSettingsSchema.parse({ fileDeletionMode }).fileDeletionMode
+ ).toBe('trash')
+ }
+ for (const fileDeletionMode of ['trash', 'permanent']) {
+ expect(
+ appSettingsSchema.parse({ fileDeletionMode }).fileDeletionMode
+ ).toBe(fileDeletionMode)
+ }
+ expect(
+ appSettingsInputSchema.partial().safeParse({ fileDeletionMode: 'delete' })
+ .success
+ ).toBe(false)
+ })
it('defaults old or invalid tray colors to auto without resetting valid preferences', () => {
expect(DEFAULT_APP_SETTINGS.trayIconColor).toBe('auto')
for (const trayIconColor of [undefined, null, 'white', true]) {
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index 34a3c762..fbf2382e 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -12,6 +12,8 @@ import { settingsInputObject } from './settings-input'
import { DEFAULT_TRAY_ICON_COLOR, trayIconColorSchema } from './tray-icon-color'
export const appUpdateChannelSchema = z.enum(['stable', 'beta'])
+export const fileDeletionModeSchema = z.enum(['trash', 'permanent'])
+export type FileDeletionMode = z.infer<typeof fileDeletionModeSchema>
export const MAGNET_FILE_SELECTION_TIMEOUT_MIN_SECONDS = 10
export const MAGNET_FILE_SELECTION_TIMEOUT_MAX_SECONDS = 3600
@@ -32,6 +34,7 @@ export const appSettingsSchema = z.object({
// absolute platform download directory on first load. The renderer never
// observes '' because settings are loaded before the UI mounts.
defaultSaveDir: z.string().catch(''),
+ fileDeletionMode: fileDeletionModeSchema.catch('trash'),
directoryPreferences: DirectoryPreferencesSchema.catch({
favorites: [],
recent: [],
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index 1c5b92b8..6145bb9c 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -1,3 +1,4 @@
+import type { FileDeletionMode } from '@shared/schemas/app-settings'
import type { ByteUnitPreference } from '@shared/schemas/byte-unit-system'
import type { TrayIconColor } from '@shared/schemas/tray-icon-color'
import type { RunMode } from '../constants'
@@ -224,6 +225,8 @@ export interface MotrixAppSettings {
language: SupportedLocale
directoryPreferences: DirectoryPreferences
defaultSaveDir: string
+ /** Desktop task file deletion only; the server always deletes directly. */
+ fileDeletionMode: FileDeletionMode
notifyOnComplete: boolean
notifyOnError: boolean
/** When true, opening the New Task dialog reads the clipboard once and