Skip to content

A full-featured download manager.

feat(downloads): refine task controls and seeding lifecycle (#2143)

Dr_rOota09f0ea39ea2
diff --git a/e2e/add-task.spec.ts b/e2e/add-task.spec.ts
index 93860d2b..cc36e1e4 100644
--- a/e2e/add-task.spec.ts
+++ b/e2e/add-task.spec.ts
@@ -91,7 +91,9 @@ test.describe('add task', () => {
// row that aria2 emitted from a previous failure (a real risk
// we hit during development — see git log around the
// createTaskHandler `.motrix` mkdir guard).
- const row = mainWindow.getByRole('option').filter({ hasText: 'test.bin' })
+ const row = mainWindow
+ .locator('[data-task-id]')
+ .filter({ hasText: 'test.bin' })
await expect(row).toBeVisible({ timeout: 15_000 })
// Sanity-check via IPC that the task isn't in `error` — the row
@@ -170,13 +172,13 @@ test.describe('add task', () => {
.poll(() => mainWindow.url())
.toContain('#/downloads/all?task=')
await expect(
- mainWindow.getByRole('option').filter({ hasText: 'beta.bin' })
+ mainWindow.locator('[data-task-id]').filter({ hasText: 'beta.bin' })
).toBeVisible({ timeout: 15_000 })
await expect(
- mainWindow.getByRole('option').filter({ hasText: 'gamma.bin' })
+ mainWindow.locator('[data-task-id]').filter({ hasText: 'gamma.bin' })
).toBeVisible({ timeout: 15_000 })
await expect(
- mainWindow.getByRole('option').filter({ hasText: 'alpha.bin' })
+ mainWindow.locator('[data-task-id]').filter({ hasText: 'alpha.bin' })
).toHaveCount(0)
} finally {
// These unreachable-tracker one-byte tasks intentionally remain active.
diff --git a/e2e/application-menu.spec.ts b/e2e/application-menu.spec.ts
index 11ffce09..d123288a 100644
--- a/e2e/application-menu.spec.ts
+++ b/e2e/application-menu.spec.ts
@@ -1,6 +1,153 @@
-import { expect, test } from './fixtures/electron-app'
+import { Events } from '@shared/protocol/events'
+import { TaskStatus } from '@shared/types/task'
+import { makeDownloadTask } from '../src/test-utils/task'
+import { expect, test, waitForEngineReady } from './fixtures/electron-app'
test.describe('application menu', () => {
+ test('selects tasks from the Task menu while preserving text editing shortcuts', async ({
+ electronApp,
+ mainWindow,
+ }) => {
+ await waitForEngineReady(mainWindow)
+ await mainWindow
+ .getByRole('link', { name: 'Downloads', exact: true })
+ .click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const tasks = Array.from({ length: 40 }, (_, index) =>
+ makeDownloadTask({
+ id: `menu-selection-${index}`,
+ name: `Menu task ${index}.bin`,
+ status: index < 2 ? TaskStatus.Completed : TaskStatus.Paused,
+ createdAt: index,
+ })
+ )
+ await electronApp.evaluate(
+ ({ BrowserWindow }, payload) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ main?.webContents.send(payload.channel, payload.tasks)
+ },
+ { channel: Events.TaskUpdated, tasks }
+ )
+ const grid = mainWindow.getByRole('grid', { name: 'Downloads' })
+ const rows = grid.locator('[data-task-id]')
+ await expect(rows.first()).toBeVisible()
+ await rows.first().click()
+
+ const clickNativeItem = (id: string) =>
+ electronApp.evaluate(({ Menu, BrowserWindow }, itemId) => {
+ const item = Menu.getApplicationMenu()?.getMenuItemById(itemId)
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ if (!item?.enabled || !main) throw new Error('Menu item is unavailable')
+ main.focus()
+ // Electron normalizes roles to lowercase. AppKit dispatches editing
+ // roles through the responder chain, not MenuItem.click.
+ if (
+ process.platform === 'darwin' &&
+ item.role?.toLowerCase() === 'selectall'
+ ) {
+ Menu.sendActionToFirstResponder('selectAll:')
+ return
+ }
+ item.click({}, main, main.webContents)
+ }, id)
+
+ await clickNativeItem('menubar.task.selectAll')
+ await expect(
+ grid.locator('[data-task-id][aria-selected="false"]')
+ ).toHaveCount(0)
+ await expect(grid).toBeFocused()
+ expect(
+ await mainWindow.evaluate(() => window.getSelection()?.toString())
+ ).toBe('')
+
+ // Virtual rows that were offscreen when the command ran must also be selected.
+ await mainWindow
+ .getByTestId('virtual-list-container')
+ .evaluate((element) => {
+ element.scrollTop = element.scrollHeight
+ })
+ await expect(
+ grid.locator('[data-task-id="menu-selection-0"]')
+ ).toBeVisible()
+ await expect(
+ grid.locator('[data-task-id][aria-selected="false"]')
+ ).toHaveCount(0)
+
+ await mainWindow
+ .getByRole('button', { name: 'All Downloads', exact: true })
+ .click()
+ await mainWindow.getByRole('menuitem', { name: /^Completed/ }).click()
+ await expect(rows).toHaveCount(2)
+ await rows.first().click()
+ await mainWindow.keyboard.press('Escape')
+ await clickNativeItem('menubar.task.selectAll')
+ await expect(
+ grid.locator('[data-task-id][aria-selected="true"]')
+ ).toHaveCount(2)
+
+ const modifier = process.platform === 'darwin' ? 'Meta' : 'Control'
+ await mainWindow.keyboard.press('Escape')
+ await mainWindow.keyboard.press(`${modifier}+a`)
+ await expect(
+ grid.locator('[data-task-id][aria-selected="true"]')
+ ).toHaveCount(2)
+ expect(
+ await mainWindow.evaluate(() => window.getSelection()?.toString())
+ ).toBe('')
+
+ await mainWindow
+ .getByRole('button', { name: 'Search downloads', exact: true })
+ .click()
+ const input = mainWindow.getByPlaceholder('Search downloads', {
+ exact: true,
+ })
+ await input.fill('Menu task')
+ await input.press(`${modifier}+a`)
+ await expect
+ .poll(() =>
+ input.evaluate((element: HTMLInputElement) =>
+ element.value.slice(
+ element.selectionStart ?? 0,
+ element.selectionEnd ?? 0
+ )
+ )
+ )
+ .toBe('Menu task')
+ await expect(
+ grid.locator('[data-task-id][aria-selected="true"]')
+ ).toHaveCount(2)
+ await input.press('ArrowRight')
+ await clickNativeItem('menubar.edit.selectAll')
+ await expect
+ .poll(() =>
+ input.evaluate((element: HTMLInputElement) =>
+ element.value.slice(
+ element.selectionStart ?? 0,
+ element.selectionEnd ?? 0
+ )
+ )
+ )
+ .toBe('Menu task')
+ await mainWindow.keyboard.press('Escape')
+
+ await mainWindow
+ .getByRole('link', { name: 'Settings', exact: true })
+ .click()
+ await expect
+ .poll(() =>
+ electronApp.evaluate(
+ ({ Menu }) =>
+ Menu.getApplicationMenu()?.getMenuItemById('menubar.task.selectAll')
+ ?.enabled
+ )
+ )
+ .toBe(false)
+ })
+
test('uses the native macOS menu without rendering the custom trigger', async ({
electronApp,
mainWindow,
diff --git a/e2e/downloads-seeding.spec.ts b/e2e/downloads-seeding.spec.ts
new file mode 100644
index 00000000..d723d92a
--- /dev/null
+++ b/e2e/downloads-seeding.spec.ts
@@ -0,0 +1,139 @@
+import { createHash } from 'node:crypto'
+import path from 'node:path'
+import type { Page } from '@playwright/test'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { DownloadTask } from '@shared/types/task'
+import type { TaskInspectorActivitySnapshot } from '@shared/types/task-inspector-activity'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+import { startHttpFixture } from './fixtures/http-server'
+
+test('unlimited BT seeding, inspector metrics and re-seeding survive engine restart', async ({
+ electronApp,
+ mainWindow,
+ userDataDir,
+ rpcPort,
+}, testInfo) => {
+ test.setTimeout(120_000)
+ const fixture = await startHttpFixture({ size: 16_384 })
+ let restarted: Awaited<ReturnType<typeof launchMotrix>> | undefined
+ try {
+ const payload = Buffer.from(
+ await (await fetch(fixture.fileUrl)).arrayBuffer()
+ )
+ // Private, local-webseed-only torrent: no tracker or public peer discovery.
+ const torrent = Buffer.concat([
+ Buffer.from(
+ `d4:infod6:lengthi${payload.length}e4:name8:test.bin12:piece lengthi16384e6:pieces20:`
+ ),
+ createHash('sha1').update(payload).digest(),
+ Buffer.from(
+ `7:privatei1ee8:url-list${Buffer.byteLength(fixture.fileUrl)}:${fixture.fileUrl}e`
+ ),
+ ]).toString('base64')
+ await waitForEngineReady(mainWindow)
+ const invoke = (
+ page: Page,
+ channel:
+ | (typeof Commands)[keyof typeof Commands]
+ | (typeof Queries)[keyof typeof Queries],
+ value?: unknown
+ ) =>
+ page.evaluate(
+ ({ channel, value }) => window.motrix.invoke(channel, value),
+ { channel, value }
+ )
+ await invoke(mainWindow, Commands.UpdateSettings, {
+ engine: { seedTime: 1, seedRatio: 1 },
+ })
+ await invoke(mainWindow, Commands.UpdateSettings, {
+ engine: { seedTime: 0, seedRatio: 0 },
+ })
+ await invoke(mainWindow, Commands.CreateTask, {
+ type: 'bt',
+ payload: { kind: 'torrent-base64', base64: torrent },
+ selectedFiles: [0],
+ saveDir: path.join(userDataDir, 'downloads'),
+ })
+ const readTask = async (page = mainWindow) =>
+ ((await invoke(page, Queries.ListTasks)) as DownloadTask[])[0]
+ const readActivity = async (page = mainWindow) => {
+ const result = (await invoke(page, Queries.GetTaskInspectorActivity, {
+ taskId: (await readTask(page)).id,
+ })) as {
+ ok: boolean
+ value?: TaskInspectorActivitySnapshot
+ error?: { message: string }
+ }
+ if (!result.ok || !result.value)
+ throw new Error(result.error?.message ?? 'Inspector query failed')
+ return result.value
+ }
+ const seedingMs = async (page = mainWindow) =>
+ (await readActivity(page)).summary.seeding?.activeMs ?? 0
+ await expect
+ .poll(async () => (await readTask())?.status, { timeout: 25_000 })
+ .toBe('seeding')
+ const first = await readTask()
+ expect(first.progress).toBe(1)
+ expect(await fixture.verifyFile(first.finalPath)).toBe(true)
+ // Inspector Activity publishes durable checkpoints every 30 seconds.
+ await expect.poll(() => seedingMs(), { timeout: 40_000 }).toBeGreaterThan(0)
+ await mainWindow
+ .getByRole('link', { name: 'Downloads', exact: true })
+ .click()
+ await mainWindow.locator(`[data-task-id="${first.id}"]`).dblclick()
+ const inspector = mainWindow.getByTestId('task-inspector-drawer-content')
+ await expect(inspector.getByText('Uploaded', { exact: true })).toBeVisible()
+ await expect(
+ inspector.getByText('Seeding time', { exact: true })
+ ).toBeVisible()
+ await expect(
+ inspector.locator('[data-slot="task-seeding-duration"]')
+ ).not.toHaveText('—')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('seeding-metrics.png'),
+ })
+
+ await invoke(mainWindow, Commands.PauseTask, first.id)
+ await expect.poll(async () => (await readTask()).status).toBe('paused')
+ const pausedMs = await seedingMs()
+ await mainWindow.waitForTimeout(1500)
+ expect(await seedingMs()).toBe(pausedMs)
+ await invoke(mainWindow, Commands.ResumeTask, first.id)
+ await expect.poll(async () => (await readTask()).status).toBe('seeding')
+ await mainWindow.waitForTimeout(2500)
+ await invoke(mainWindow, Commands.StopSeedingTask, first.id)
+ await expect.poll(async () => (await readTask()).status).toBe('completed')
+ const stoppedMs = await seedingMs()
+ expect(stoppedMs).toBeGreaterThan(pausedMs)
+ await invoke(mainWindow, Commands.ReAddTask, first.id)
+ await expect.poll(async () => (await readTask()).status).toBe('seeding')
+ expect((await readTask()).engineTaskId).not.toBe(first.engineTaskId)
+ await mainWindow.waitForTimeout(2500)
+ const beforeRestart = await seedingMs()
+ await electronApp.close()
+ restarted = await launchMotrix({ userDataDir, rpcPort })
+ const nextWindow = await restarted.firstWindow()
+ await waitForEngineReady(nextWindow)
+ await expect
+ .poll(async () => (await readTask(nextWindow))?.status, {
+ timeout: 15_000,
+ })
+ .toBe('seeding')
+ const afterRestart = await seedingMs(nextWindow)
+ expect(afterRestart).toBeGreaterThanOrEqual(beforeRestart)
+ expect(afterRestart).toBeGreaterThan(stoppedMs)
+ await expect
+ .poll(() => seedingMs(nextWindow), { timeout: 40_000 })
+ .toBeGreaterThan(afterRestart)
+ } finally {
+ await restarted?.close()
+ await fixture.close()
+ }
+})
diff --git a/e2e/downloads-speed-limit.spec.ts b/e2e/downloads-speed-limit.spec.ts
new file mode 100644
index 00000000..3fbf0af8
--- /dev/null
+++ b/e2e/downloads-speed-limit.spec.ts
@@ -0,0 +1,179 @@
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { SpeedLimitSettings } from '@shared/types/settings'
+import { expect, test, waitForEngineReady } from './fixtures/electron-app'
+import {
+ setTaskInspectorContentSize,
+ updateTaskInspectorAppearance,
+} from './fixtures/task-inspector-activity'
+
+test('fresh low-speed presets match the unit system and survive unit changes', async ({
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ const binary = process.platform !== 'darwin'
+ const unit = binary ? 'KiB/s' : 'KB/s'
+ const alt = binary
+ ? { upload: 65_536, download: 524_288 }
+ : { upload: 64_000, download: 512_000 }
+ const readSettings = () =>
+ mainWindow.evaluate(async (channel) => {
+ const settings = (await window.motrix.invoke(channel)) as {
+ speedLimit: SpeedLimitSettings
+ }
+ return settings.speedLimit
+ }, Queries.GetSettings)
+ await expect.poll(readSettings).toMatchObject({
+ turtle: 'off',
+ base: { upload: 0, download: 0 },
+ alt,
+ })
+ const badge = mainWindow.locator('[data-slot="downloads-speed-limit"]')
+ await badge.click()
+ await mainWindow
+ .getByRole('menuitemradio', { name: 'Low-speed mode' })
+ .click()
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+ await expect(badge).toHaveAccessibleName('Speed mode: Low speed')
+ await expect(badge).toBeEnabled()
+ await mainWindow
+ .getByRole('heading', { name: 'All Downloads', exact: true })
+ .hover()
+ await badge.hover()
+ const tooltip = mainWindow.getByRole('tooltip')
+ await expect(tooltip).toContainText(`Upload limit: 64 ${unit}`)
+ await expect(tooltip).toContainText(`Download limit: 512 ${unit}`)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('default-speed-limits.png'),
+ })
+ await mainWindow.evaluate(
+ async ({ channel, units }) => {
+ await window.motrix.invoke(channel, { app: { byteUnitSystem: units } })
+ },
+ { channel: Commands.UpdateSettings, units: binary ? 'decimal' : 'binary' }
+ )
+ await expect.poll(readSettings).toMatchObject({ turtle: 'on', alt })
+ await mainWindow.reload({ waitUntil: 'domcontentloaded' })
+ await expect.poll(readSettings).toMatchObject({ turtle: 'on', alt })
+ await expect(badge).toHaveAccessibleName('Speed mode: Low speed')
+})
+
+test('Downloads speed badge changes the existing mode and preserves its limits', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1100, 760)
+ await mainWindow.evaluate(async (channel) => {
+ await window.motrix.invoke(channel, {
+ speedLimit: {
+ turtle: 'off',
+ base: { upload: 1_000_000, download: 2_000_000 },
+ alt: { upload: 80_000, download: 500_000 },
+ auto: {
+ schedule: { enabled: false },
+ adaptive: { enabled: false },
+ videoApp: { enabled: false },
+ },
+ },
+ })
+ }, Commands.UpdateSettings)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const badge = mainWindow.locator('[data-slot="downloads-speed-limit"]')
+ const rates = mainWindow.locator('[data-slot="downloads-transfer-rates"]')
+ await expect(badge).toHaveAccessibleName('Speed mode: Standard')
+ await expect(badge.locator('.lucide-rabbit')).toHaveCount(1)
+ await expect(badge).toHaveCSS('height', '20px')
+ await expect(rates.getByRole('term')).toHaveText([
+ 'Upload speed',
+ 'Download speed',
+ ])
+ const rateBox = (await rates.boundingBox())!
+ const badgeBox = (await badge.boundingBox())!
+ expect(rateBox.x - badgeBox.x - badgeBox.width).toBeCloseTo(8, 0)
+ expect(badgeBox.y).toBeCloseTo(rateBox.y, 0)
+
+ await badge.hover()
+ await expect(mainWindow.getByRole('tooltip')).toContainText(
+ 'Download limit: 2 MB/s'
+ )
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('standard-mode-tooltip.png'),
+ })
+ await badge.click()
+ const menu = mainWindow.getByRole('menu', { name: 'Speed mode' })
+ await expect(menu).toHaveAttribute('data-side', 'top')
+ await expect(mainWindow.getByRole('tooltip')).toHaveCount(0)
+ await expect(
+ menu.getByRole('menuitemradio', { name: 'Standard mode' })
+ ).toHaveAttribute('aria-checked', 'true')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('speed-mode-menu.png'),
+ })
+ await menu.getByRole('menuitemradio', { name: 'Low-speed mode' }).click()
+ await expect(menu).toHaveCount(0)
+ await expect(badge).toHaveAccessibleName('Speed mode: Low speed')
+ await expect(badge.locator('.lucide-turtle')).toHaveCount(1)
+ await expect(badge).toHaveAttribute('data-reduced', 'true')
+ const readSettings = () =>
+ mainWindow.evaluate(async (channel) => {
+ const settings = (await window.motrix.invoke(channel)) as {
+ speedLimit: SpeedLimitSettings
+ }
+ return settings.speedLimit
+ }, Queries.GetSettings)
+ await expect.poll(readSettings).toMatchObject({
+ turtle: 'on',
+ base: { upload: 1_000_000, download: 2_000_000 },
+ alt: { upload: 80_000, download: 500_000 },
+ })
+ await expect
+ .poll(() =>
+ mainWindow.evaluate(
+ (channel) => window.motrix.invoke(channel),
+ Queries.GetSpeedLimitState
+ )
+ )
+ .toMatchObject({
+ turtle: 'on',
+ effective: { upload: 80_000, download: 500_000 },
+ })
+
+ await badge.click()
+ await menu.getByRole('menuitemradio', { name: 'Automatic mode' }).click()
+ await expect(badge).toHaveAccessibleName('Speed mode: Automatic')
+ await expect(badge.locator('.lucide-squirrel')).toHaveCount(1)
+ await expect(badge).toHaveAttribute('data-reduced', 'false')
+ await expect.poll(readSettings).toMatchObject({ turtle: 'auto' })
+
+ // Changes made in other surfaces are reflected without navigating away.
+ await mainWindow.evaluate(async (channel) => {
+ await window.motrix.invoke(channel, { speedLimit: { turtle: 'on' } })
+ }, Commands.UpdateSettings)
+ await expect(badge).toHaveAttribute('data-mode', 'on')
+ await updateTaskInspectorAppearance(mainWindow, 'dark', 'zh-CN')
+ await expect(badge).toHaveAccessibleName('速度模式:低速')
+ await setTaskInspectorContentSize(electronApp, mainWindow, 600, 650)
+ await badge.click()
+ const chineseMenu = mainWindow.getByRole('menu', { name: '速度模式' })
+ await expect(chineseMenu).toBeVisible()
+ const narrowBox = (await badge.boundingBox())!
+ expect(narrowBox.x).toBeGreaterThanOrEqual(0)
+ expect(narrowBox.x + narrowBox.width).toBeLessThanOrEqual(600)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-chinese-speed-menu.png'),
+ })
+ await mainWindow.keyboard.press('Escape')
+ await expect(chineseMenu).toHaveCount(0)
+ await expect(badge).toBeFocused()
+ await badge.press('Enter')
+ await chineseMenu.getByRole('menuitemradio', { name: '常规模式' }).click()
+ await expect(badge).toHaveAccessibleName('速度模式:常规')
+ await expect.poll(readSettings).toMatchObject({
+ turtle: 'off',
+ base: { upload: 1_000_000, download: 2_000_000 },
+ alt: { upload: 80_000, download: 500_000 },
+ })
+})
diff --git a/e2e/downloads-toolbar-glass.spec.ts b/e2e/downloads-toolbar-glass.spec.ts
new file mode 100644
index 00000000..5de09923
--- /dev/null
+++ b/e2e/downloads-toolbar-glass.spec.ts
@@ -0,0 +1,185 @@
+import { writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { Commands } from '@shared/protocol/commands'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+import {
+ setTaskInspectorContentSize,
+ updateTaskInspectorAppearance,
+} from './fixtures/task-inspector-activity'
+
+test('toolbar glass follows the saved switch and preserves search, sizing and focus', async ({
+ userDataDir,
+ rpcPort,
+}, testInfo) => {
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { liquidGlassEffect: true, theme: 'light', language: 'en-US' },
+ tracker: { autoSync: false },
+ onboarding: { disclaimerAccepted: true },
+ })
+ )
+ const app = await launchMotrix({ userDataDir, rpcPort })
+ try {
+ let page = await app.firstWindow()
+ await waitForEngineReady(page)
+ await setTaskInspectorContentSize(app, page, 1280, 900)
+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()
+ const toolbar = page.locator('[data-slot="downloads-toolbar"]')
+ const layers = toolbar.locator('[data-slot="toolbar-glass"]')
+ await expect(layers).toHaveCount(2)
+ for (const layer of await layers.all()) {
+ await expect(layer).toHaveAttribute('data-refraction', 'true')
+ await expect(layer).toHaveCSS('pointer-events', 'none')
+ }
+ await expect(toolbar.getByRole('button')).toHaveCount(4)
+ await page.screenshot({
+ path: testInfo.outputPath('glass-standard-light.png'),
+ })
+ await toolbar
+ .getByRole('button', { name: 'Search downloads', exact: true })
+ .click()
+ const input = toolbar.getByRole('textbox', { name: 'Search downloads' })
+ await input.fill('glass')
+ await expect(input).toBeFocused()
+ const search = page.locator('[data-slot="downloads-search"]')
+ await expect.poll(async () => (await search.boundingBox())!.width).toBe(230)
+ // The map must track the animated search capsule, not stay a circular lens.
+ await expect
+ .poll(() =>
+ search.locator('feImage').evaluate(async (image) => {
+ const decoded = new Image()
+ decoded.src = image.getAttribute('href')!
+ await decoded.decode()
+ return decoded.naturalWidth
+ })
+ )
+ .toBe(228)
+ await page.screenshot({
+ path: testInfo.outputPath('glass-search-light.png'),
+ })
+ // Verify the rendered displacement, not just CSS syntax support. A
+ // temporary striped backdrop exposes the rim while the center stays flat.
+ await input.blur()
+ await search.evaluate((element) => {
+ element.style.backgroundImage =
+ 'repeating-linear-gradient(0deg, white 0px 4px, black 4px 8px)'
+ })
+ const glassSearch = search.locator('[data-slot="toolbar-glass"]')
+ const glassFilter = await glassSearch.evaluate(
+ (element) => element.style.backdropFilter
+ )
+ const refracted = await search.screenshot({
+ path: testInfo.outputPath('rim-refraction.png'),
+ })
+ await glassSearch.evaluate((element) => {
+ element.style.backdropFilter = 'blur(2px) saturate(1.08)'
+ })
+ const frosted = await search.screenshot({
+ path: testInfo.outputPath('rim-frost.png'),
+ })
+ const difference = await page.evaluate(
+ async ([before, after]) => {
+ const read = async (source: string) => {
+ const image = new Image()
+ image.src = `data:image/png;base64,${source}`
+ await image.decode()
+ const canvas = document.createElement('canvas')
+ canvas.width = image.naturalWidth
+ canvas.height = image.naturalHeight
+ const context = canvas.getContext('2d')!
+ context.drawImage(image, 0, 0)
+ return context.getImageData(0, 0, canvas.width, canvas.height)
+ }
+ const a = await read(before)
+ const b = await read(after)
+ let rim = 0
+ let center = 0
+ // Avoid controls and rounded corners; inspect the central 80px span.
+ for (let x = 70; x < 150; x++) {
+ for (let y = 2; y < a.height - 2; y++) {
+ const index = (y * a.width + x) * 4
+ if (Math.abs(a.data[index] - b.data[index]) <= 5) continue
+ if (y < 7 || y >= a.height - 7) rim++
+ else if (y >= 12 && y < a.height - 12) center++
+ }
+ }
+ return { rim, center }
+ },
+ [refracted.toString('base64'), frosted.toString('base64')]
+ )
+ expect(difference.rim).toBeGreaterThan(10)
+ expect(difference.center).toBe(0)
+ await glassSearch.evaluate((element, filter) => {
+ element.style.backdropFilter = filter
+ }, glassFilter)
+ await search.evaluate((element) => {
+ element.style.backgroundImage = ''
+ })
+ await page
+ .getByRole('button', { name: 'Toggle sidebar', exact: true })
+ .click()
+ await expect(toolbar).toHaveAttribute('data-density', 'compact')
+ await expect.poll(async () => (await search.boundingBox())!.height).toBe(30)
+ await input.focus()
+ await page.emulateMedia({ contrast: 'more' })
+ await expect(layers).toHaveCount(0)
+ await expect(input).toBeFocused()
+ await expect(input).toHaveValue('glass')
+ await page.emulateMedia({ contrast: 'no-preference' })
+ await expect(layers).toHaveCount(2)
+ await expect(input).toBeFocused()
+ await page.screenshot({
+ path: testInfo.outputPath('glass-compact-light.png'),
+ })
+ await updateTaskInspectorAppearance(page, 'dark', 'en-US')
+ await expect(page.locator('[data-slot="toolbar-glass"]')).toHaveCount(2)
+ await page.screenshot({
+ path: testInfo.outputPath('glass-compact-dark.png'),
+ })
+
+ // macOS recreates its native window for this setting. Other hosts update
+ // the same renderer through the sanitized preference event.
+ const replacement =
+ process.platform === 'darwin' ? app.waitForEvent('window') : null
+ await page.evaluate(async (command) => {
+ const api = (
+ window as unknown as {
+ motrix: {
+ invoke: (channel: string, ...args: unknown[]) => Promise<unknown>
+ }
+ }
+ ).motrix
+ await api.invoke(command, { app: { liquidGlassEffect: false } })
+ }, Commands.UpdateSettings)
+ if (replacement) {
+ page = await replacement
+ await page.waitForLoadState('domcontentloaded')
+ await waitForEngineReady(page)
+ if (
+ (await page
+ .locator('[data-slot="sidebar-wrapper"]')
+ .getAttribute('data-state')) === 'collapsed'
+ ) {
+ await page
+ .getByRole('button', { name: 'Toggle sidebar', exact: true })
+ .click()
+ }
+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()
+ }
+ await expect(page.locator('[data-slot="downloads-toolbar"]')).toBeVisible()
+ await expect(page.locator('[data-slot="toolbar-glass"]')).toHaveCount(0)
+ await page.reload({ waitUntil: 'domcontentloaded' })
+ await expect(page.locator('[data-slot="downloads-toolbar"]')).toBeVisible()
+ await expect(page.locator('[data-slot="toolbar-glass"]')).toHaveCount(0)
+ } finally {
+ await app.close()
+ }
+})
diff --git a/e2e/downloads-visibility.spec.ts b/e2e/downloads-visibility.spec.ts
index 7c27c310..9fa5bba0 100644
--- a/e2e/downloads-visibility.spec.ts
+++ b/e2e/downloads-visibility.spec.ts
@@ -1,9 +1,21 @@
import type { ElectronApplication, Locator } from '@playwright/test'
+import { DownloadErrorCode } from '@shared/errors'
+import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
-import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import { Queries } from '@shared/protocol/queries'
+import { type DownloadTask, TaskStatus, TaskType } from '@shared/types/task'
import { makeDownloadTask } from '../src/test-utils/task'
-import { expect, test, waitForEngineReady } from './fixtures/electron-app'
-import { setTaskInspectorContentSize } from './fixtures/task-inspector-activity'
+import {
+ expect,
+ findAddTaskWindow,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+import {
+ setTaskInspectorContentSize,
+ updateTaskInspectorAppearance,
+} from './fixtures/task-inspector-activity'
function makeTasks(count: number): DownloadTask[] {
return Array.from({ length: count }, (_, index) => {
@@ -41,10 +53,11 @@ async function expectUsable(row: Locator) {
.poll(() =>
row.evaluate((element) => {
const list = element.closest('[data-testid="virtual-list-container"]')
- if (!list?.firstElementChild) return false
+ const headerRow = list?.querySelector('[role="row"]')
+ if (!list || !headerRow) return false
const rect = element.getBoundingClientRect()
const viewport = list.getBoundingClientRect()
- const header = list.firstElementChild!.getBoundingClientRect()
+ const header = headerRow.getBoundingClientRect()
const hit = document.elementFromPoint(
rect.left + 120,
rect.top + rect.height / 2
@@ -52,13 +65,329 @@ async function expectUsable(row: Locator) {
return (
rect.top >= header.bottom - 1 &&
rect.bottom <= viewport.bottom + 1 &&
- hit?.closest('[role="option"]') === element
+ hit?.closest('[data-task-id]') === element
)
})
)
.toBe(true)
}
+async function expectDrawerSettled(drawer: Locator) {
+ await expect
+ .poll(() =>
+ drawer.evaluate((element) => {
+ const style = getComputedStyle(element)
+ const offset =
+ Number.parseFloat(
+ style.getPropertyValue('--drawer-snap-point-offset')
+ ) || 0
+ return (
+ !element.hasAttribute('data-starting-style') &&
+ !element
+ .getAnimations()
+ .some((animation) => animation.playState === 'running') &&
+ Math.abs(new DOMMatrixReadOnly(style.transform).m42 - offset) < 0.5
+ )
+ })
+ )
+ .toBe(true)
+}
+
+test('download columns sort live tasks without losing selection or filter state', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const tasks = [10, 1, 2].map((index) =>
+ makeDownloadTask({
+ id: `sorting-${index}`,
+ name: `File ${index}.bin`,
+ status: index === 10 ? TaskStatus.Completed : TaskStatus.Downloading,
+ sizeWhenDone: index * 1_000_000,
+ totalBytes: index * 1_000_000,
+ downloadSpeed: index * 1_000,
+ etaSeconds: index * 60,
+ createdAt: Date.parse('2026-09-13T01:00:00Z') + index * 3_600_000,
+ finishedAt: index === 10 ? Date.parse('2026-09-13T12:30:00Z') : null,
+ })
+ )
+ await publish(electronApp, tasks)
+ const list = mainWindow.getByTestId('virtual-list-container')
+ const rows = list.locator('[data-task-id]')
+ await expect(rows).toHaveCount(3)
+ const expectOrder = async (indices: number[]) => {
+ await expect(rows).toHaveText(
+ indices.map((index) => new RegExp(`File ${index}\\.bin`))
+ )
+ }
+ await expectOrder([10, 2, 1])
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(0)
+ await list.getByRole('button', { name: 'Name', exact: true }).hover()
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(0)
+ await list.getByRole('row', { name: /File 2\.bin/ }).click()
+ await list.getByRole('button', { name: 'Name', exact: true }).click()
+ await expectOrder([1, 2, 10])
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(1)
+ await expect(list.getByRole('row', { name: /File 2\.bin/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ await list
+ .getByRole('row', { name: /File 10\.bin/ })
+ .click({ modifiers: ['Shift'] })
+ await expect(list.getByRole('row', { name: /File 1\.bin/ })).toHaveAttribute(
+ 'aria-selected',
+ 'false'
+ )
+ await expect(list.getByRole('row', { name: /File 10\.bin/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+
+ await list.getByRole('button', { name: 'Size', exact: true }).focus()
+ await mainWindow.keyboard.press('Space')
+ await expectOrder([10, 2, 1])
+ await expect(list.getByRole('row', { name: /File 1\.bin/ })).toHaveAttribute(
+ 'aria-selected',
+ 'false'
+ )
+ await mainWindow.keyboard.press('Enter')
+ await expectOrder([1, 2, 10])
+ await mainWindow.keyboard.press('Enter')
+ await expectOrder([10, 2, 1])
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(1)
+ await mainWindow
+ .getByRole('button', { name: 'List View', exact: true })
+ .click()
+ await mainWindow
+ .getByRole('menuitem', { name: 'Restore default order', exact: true })
+ .click()
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(0)
+
+ await list.getByRole('button', { name: 'Date created', exact: true }).click()
+ await expectOrder([10, 2, 1])
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(1)
+ await list
+ .getByRole('button', { name: 'Date created: descending', exact: true })
+ .click()
+ await expectOrder([1, 2, 10])
+ await list
+ .getByRole('button', { name: 'Date completed', exact: true })
+ .click()
+ await expectOrder([10, 1, 2])
+ await expect(rows.locator('time')).toHaveCount(4)
+ await expect(
+ list
+ .getByRole('row', { name: /File 10\.bin/ })
+ .locator('time')
+ .last()
+ ).toHaveAttribute('datetime', '2026-09-13T12:30:00.000Z')
+ await expect(
+ list.getByRole('row', { name: /File 1\.bin/ }).locator('time')
+ ).toHaveCount(1)
+ await expect
+ .poll(() =>
+ mainWindow.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ )
+ )
+ .toBe(true)
+
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1660, 900)
+ await list.evaluate((element) => {
+ element.scrollLeft = 0
+ })
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('sorted-timestamps.png'),
+ animations: 'disabled',
+ })
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+
+ await list
+ .getByRole('button', { name: 'Download speed', exact: true })
+ .click()
+ await expectOrder([2, 1, 10])
+ tasks[1] = { ...tasks[1], downloadSpeed: 50_000 }
+ await publish(electronApp, tasks)
+ await expectOrder([1, 2, 10])
+ await expect(list.getByRole('row', { name: /File 1\.bin/ })).toContainText(
+ '50.0 KB/s'
+ )
+ await mainWindow
+ .getByRole('button', { name: 'List View', exact: true })
+ .click()
+ await mainWindow
+ .getByRole('menuitemcheckbox', { name: 'ETA', exact: true })
+ .click()
+ await mainWindow.keyboard.press('Escape')
+ await list.getByRole('button', { name: 'ETA', exact: true }).click()
+ await expectOrder([1, 2, 10])
+ await list
+ .getByRole('button', { name: 'ETA: ascending', exact: true })
+ .click()
+ await expectOrder([2, 1, 10])
+
+ await mainWindow
+ .getByRole('button', { name: 'All Downloads', exact: true })
+ .click()
+ await mainWindow.getByRole('menuitem', { name: /^Active/ }).click()
+ await expectOrder([2, 1])
+ await expect(
+ list.getByRole('button', { name: 'ETA: descending', exact: true })
+ ).toHaveAttribute('aria-pressed', 'true')
+ await testInfo.attach('sorted-downloads', {
+ body: await mainWindow.screenshot({ animations: 'disabled' }),
+ contentType: 'image/png',
+ })
+})
+
+test('remembers a manual sort across app restarts and clears it when restoring the default', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ let app = await launchMotrix({ userDataDir, rpcPort })
+ const tasks = [
+ makeDownloadTask({ id: 'older', name: 'Alpha.bin', createdAt: 1_000 }),
+ makeDownloadTask({ id: 'newer', name: 'Beta.bin', createdAt: 2_000 }),
+ ]
+ const openDownloads = async () => {
+ const page = await app.firstWindow()
+ await page.waitForLoadState('domcontentloaded')
+ await waitForEngineReady(page)
+ await page.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(page.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(app, tasks)
+ const list = page.getByTestId('virtual-list-container')
+ await expect(list.locator('[data-task-id]')).toHaveCount(tasks.length)
+ return list
+ }
+ try {
+ let list = await openDownloads()
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Beta.bin/,
+ /Alpha.bin/,
+ ])
+ await list.getByRole('button', { name: 'Name', exact: true }).click()
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Alpha.bin/,
+ /Beta.bin/,
+ ])
+ const page = list.page()
+ const nameHeader = list.getByRole('button', {
+ name: 'Name: ascending',
+ exact: true,
+ })
+ await list.getByRole('button', { name: 'Size', exact: true }).hover()
+ const target = await nameHeader.boundingBox()
+ if (!target) throw new Error('Name header is not laid out')
+ await page.mouse.down()
+ await page.mouse.move(
+ target.x + target.width / 2,
+ target.y + target.height / 2,
+ { steps: 12 }
+ )
+ // Chromium's HTML dragover requires a second move at the destination.
+ await page.mouse.move(
+ target.x + target.width / 2 + 1,
+ target.y + target.height / 2
+ )
+ await page.mouse.up()
+ await expect(list.getByRole('columnheader').first()).toContainText('Size')
+ const nameResize = list.getByRole('separator', {
+ name: 'Resize Name column',
+ })
+ await nameResize.focus()
+ await nameResize.press('ArrowRight')
+ await page.getByRole('button', { name: 'List View', exact: true }).click()
+ await page.getByRole('menuitemcheckbox', { name: 'Date completed' }).click()
+ await page.keyboard.press('Escape')
+ await page
+ .getByRole('button', { name: 'Show Inspector', exact: true })
+ .click()
+ await page
+ .getByRole('separator', { name: 'Resize Inspector' })
+ .press('Home')
+ await app.close()
+
+ app = await launchMotrix({ userDataDir, rpcPort })
+ list = await openDownloads()
+ await expect(list.getByRole('columnheader').first()).toContainText('Size')
+ await expect(
+ list.getByRole('separator', { name: 'Resize Name column' })
+ ).toHaveAttribute('aria-valuenow', '256')
+ await expect(
+ list.getByRole('button', { name: 'Date completed', exact: true })
+ ).toHaveCount(0)
+ await expect(
+ list.page().getByRole('dialog', { name: 'Task Inspector' })
+ ).toBeVisible()
+ await expect(
+ list.page().getByRole('separator', { name: 'Resize Inspector' })
+ ).toHaveAttribute('aria-valuenow', '220')
+ await expect(
+ list.getByRole('button', { name: 'Name: ascending', exact: true })
+ ).toHaveAttribute('aria-pressed', 'true')
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Alpha.bin/,
+ /Beta.bin/,
+ ])
+ tasks.push(
+ makeDownloadTask({ id: 'latest', name: 'Gamma.bin', createdAt: 3_000 })
+ )
+ await publish(app, tasks)
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Alpha.bin/,
+ /Beta.bin/,
+ /Gamma.bin/,
+ ])
+ await list
+ .getByRole('button', { name: 'Name: ascending', exact: true })
+ .click()
+ await list
+ .getByRole('button', { name: 'Name: descending', exact: true })
+ .click()
+ await list
+ .page()
+ .getByRole('button', { name: 'List View', exact: true })
+ .click()
+ await list
+ .page()
+ .getByRole('menuitem', { name: 'Restore default order', exact: true })
+ .click()
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(0)
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Gamma.bin/,
+ /Beta.bin/,
+ /Alpha.bin/,
+ ])
+ await app.close()
+
+ app = await launchMotrix({ userDataDir, rpcPort })
+ list = await openDownloads()
+ await expect(list.locator('button[aria-pressed] svg')).toHaveCount(0)
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Gamma.bin/,
+ /Beta.bin/,
+ /Alpha.bin/,
+ ])
+ tasks.push(
+ makeDownloadTask({ id: 'newest', name: 'Delta.bin', createdAt: 4_000 })
+ )
+ await publish(app, tasks)
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Delta.bin/,
+ /Gamma.bin/,
+ /Beta.bin/,
+ /Alpha.bin/,
+ ])
+ } finally {
+ await app.close().catch(() => {})
+ }
+})
+
for (const { count, width, height, zoom } of [
{ count: 26, width: 1280, height: 900, zoom: 1 },
{ count: 200, width: 1000, height: 600, zoom: 1 },
@@ -92,31 +421,34 @@ for (const { count, width, height, zoom } of [
await list.evaluate((element) => {
element.scrollTop = element.scrollHeight
})
- const tail = mainWindow.getByRole('option', {
+ const tail = mainWindow.getByRole('row', {
name: new RegExp(`Active tail ${count - 1}\\.bin`),
})
await expectUsable(tail)
await expect(tail).toContainText('99%')
- await tail.click({ position: { x: 120, y: 24 } })
+ await tail.click({ position: { x: 120, y: 18 } })
+ const listBox = await list.boundingBox()
+ await mainWindow
+ .getByRole('button', { name: 'Show Inspector', exact: true })
+ .click()
const drawer = mainWindow.getByRole('dialog', {
- name: 'Downloads',
+ name: 'Task Inspector',
exact: true,
})
await expect(drawer).toBeVisible()
- await expectUsable(tail)
- await expect
- .poll(async () => {
- const a = await list.boundingBox()
- const b = await drawer.boundingBox()
- return !!a && !!b && a.y + a.height <= b.y
- })
- .toBe(true)
+ await expectDrawerSettled(drawer)
+ expect(await list.boundingBox()).toEqual(listBox)
await testInfo.attach('all-downloads-with-inspector', {
body: await mainWindow.screenshot({ animations: 'disabled' }),
contentType: 'image/png',
})
+ await drawer.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(drawer).toHaveCount(0)
+ await expect(tail).toHaveAttribute('aria-selected', 'true')
+ await expectUsable(tail)
+
// Same task moves from the last row of All to the fourth row of Active.
// Returning must reveal it again even though the list remounts.
await mainWindow
@@ -129,9 +461,27 @@ for (const { count, width, height, zoom } of [
.click()
await mainWindow.getByRole('menuitem', { name: /^All/ }).click()
await expectUsable(tail)
- await mainWindow.keyboard.press('Escape')
- await expect(drawer).toHaveCount(0)
- await expectUsable(tail)
+
+ // A manually scrolled-away focused row stays mounted for ARIA without
+ // forcing the user's viewport back to it.
+ if (count === 200) {
+ // Finish closing the title menu before simulating a manual list scroll.
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+ await list.evaluate((element) => {
+ element.scrollTop = 0
+ })
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBe(0)
+ const grid = mainWindow.locator('[data-downloads-grid]')
+ const activeId = await grid.getAttribute('aria-activedescendant')
+ expect(
+ await mainWindow.evaluate(
+ (id) => !!id && document.getElementById(id) !== null,
+ activeId
+ )
+ ).toBe(true)
+ }
// Data updates must keep every task reachable without a route change.
const added = makeDownloadTask({
@@ -144,7 +494,7 @@ for (const { count, width, height, zoom } of [
element.scrollTop = element.scrollHeight
})
await expectUsable(
- mainWindow.getByRole('option', { name: /New active tail\.bin/ })
+ mainWindow.getByRole('row', { name: /New active tail\.bin/ })
)
await expect
.poll(() =>
@@ -155,3 +505,1506 @@ for (const { count, width, height, zoom } of [
.toBe(true)
})
}
+
+test('clears selection with modifier clicks, Escape and list whitespace', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1000, 672)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(
+ electronApp,
+ [0, 1, 2].map((index) =>
+ makeDownloadTask({
+ id: `deselect-${index}`,
+ name: `Deselect ${index}.bin`,
+ createdAt: 3_000 - index,
+ status: TaskStatus.Paused,
+ })
+ )
+ )
+ const grid = mainWindow.getByRole('grid', { name: 'Downloads' })
+ const rows = grid.locator('[data-task-id]')
+ const selected = grid.locator('[data-task-id][aria-selected="true"]')
+ await expect(rows).toHaveCount(3)
+ const modifier = process.platform === 'darwin' ? 'Meta' : 'Control'
+ await rows.nth(0).click()
+ await rows.nth(0).click()
+ await expect(selected).toHaveCount(1)
+ await rows.nth(0).click({ modifiers: [modifier] })
+ await expect(selected).toHaveCount(0)
+ await rows.nth(0).click()
+ await rows.nth(1).click({ modifiers: [modifier] })
+ await rows.nth(0).click({ modifiers: [modifier] })
+ await expect(selected).toHaveText([/Deselect 1/])
+ const focusedRow = await grid.getAttribute('aria-activedescendant')
+ await mainWindow.keyboard.press('Escape')
+ await expect(selected).toHaveCount(0)
+ await expect(grid).toBeFocused()
+ await expect(grid).toHaveAttribute('aria-activedescendant', focusedRow!)
+ await expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+ await expect(grid).toHaveCSS('outline-style', 'none')
+ await expect(rows.nth(0)).toHaveCSS('outline-style', 'none')
+ await mainWindow.keyboard.press('Escape')
+ await expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('pointer-escape-no-focus-ring.png'),
+ })
+
+ // The grid retains DOM focus so arrow navigation can resume immediately.
+ await mainWindow.keyboard.press('ArrowDown')
+ await expect(grid).toHaveAttribute('data-keyboard-focus', 'true')
+ await expect(grid).toHaveCSS('outline-style', 'solid')
+ await expect(rows.nth(1)).toHaveAttribute('aria-selected', 'true')
+ await expect(rows.nth(1)).toHaveCSS('outline-style', 'solid')
+ await mainWindow.keyboard.press('Escape')
+ await expect(selected).toHaveCount(0)
+ await expect(grid).toHaveCSS('outline-style', 'solid')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('keyboard-escape-preserves-focus-ring.png'),
+ })
+ await rows.nth(0).click()
+ await mainWindow.keyboard.press('Escape')
+ await expect(grid).toHaveCSS('outline-style', 'none')
+
+ await mainWindow.keyboard.press(`${modifier}+a`)
+ await expect(selected).toHaveCount(3)
+ await grid.getByRole('button', { name: 'Name', exact: true }).click()
+ await expect(selected).toHaveCount(3)
+ const last = (await rows.last().boundingBox())!
+ const blank = { x: last.x + 100, y: last.y + last.height + 30 }
+ await mainWindow.keyboard.down(modifier)
+ await mainWindow.mouse.click(blank.x, blank.y)
+ await mainWindow.keyboard.up(modifier)
+ await expect(selected).toHaveCount(3)
+ await mainWindow.mouse.click(blank.x, blank.y)
+ await expect(selected).toHaveCount(0)
+ await expect(grid).toBeFocused()
+ await expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+
+ // Native menu selection must be just as easy to clear without a keyboard.
+ await electronApp.evaluate(({ Menu, BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ const item = Menu.getApplicationMenu()?.getMenuItemById(
+ 'menubar.task.selectAll'
+ )
+ if (!main || !item?.enabled) throw new Error('Task Select All unavailable')
+ item.click({}, main, main.webContents)
+ })
+ await expect(selected).toHaveCount(3)
+ await mainWindow.mouse.click(blank.x, blank.y)
+ await expect(selected).toHaveCount(0)
+})
+
+test('opens details by double click and keeps selection separate from inspector visibility', async ({
+ electronApp,
+ mainWindow,
+}) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(
+ electronApp,
+ [TaskStatus.Paused, TaskStatus.Completed].map((status, index) =>
+ makeDownloadTask({
+ id: `details-${index}`,
+ name: `Details ${index}.bin`,
+ createdAt: 3_000 - index,
+ status,
+ })
+ )
+ )
+ const grid = mainWindow.getByRole('grid', { name: 'Downloads' })
+ const rows = grid.locator('[data-task-id]')
+ const selected = grid.locator('[data-task-id][aria-selected="true"]')
+ const drawer = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ const more = mainWindow.getByRole('button', { name: 'More' })
+ const content = mainWindow.getByTestId('task-inspector-drawer-content')
+ await expect(rows).toHaveCount(2)
+ await expect(more).toBeEnabled()
+ const listBounds = await grid.boundingBox()
+ await rows.nth(0).click()
+ await expect(drawer).toHaveCount(0)
+ await rows.nth(1).click({ modifiers: ['Shift'] })
+ await expect(selected).toHaveCount(2)
+ await expect(drawer).toHaveCount(0)
+ await rows.nth(1).dblclick()
+ await expect(selected).toHaveText([/Details 1/])
+ await expect(
+ content.getByText('Details 1.bin', { exact: true })
+ ).toBeVisible()
+ await expectDrawerSettled(drawer)
+ expect(await grid.boundingBox()).toEqual(listBounds)
+ const handle = drawer.getByRole('separator', { name: 'Resize Inspector' })
+ const viewportHeight = await drawer.evaluate(
+ (element) =>
+ element.closest('[data-slot="drawer-viewport"]')!.getBoundingClientRect()
+ .height
+ )
+ await expect(handle).toHaveAttribute(
+ 'aria-valuenow',
+ String(Math.round(viewportHeight * 0.5))
+ )
+ await handle.press('End')
+ await expectDrawerSettled(drawer)
+ await expect(handle).toHaveAttribute(
+ 'aria-valuenow',
+ String(Math.round(viewportHeight * 0.75))
+ )
+ await rows.nth(0).click()
+ await expect(
+ content.getByText('Details 0.bin', { exact: true })
+ ).toBeVisible()
+ await rows.nth(0).dblclick()
+ await expect(drawer).toBeVisible()
+ await expect(handle).toHaveAttribute(
+ 'aria-valuenow',
+ String(Math.round(viewportHeight * 0.75))
+ )
+ await drawer.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(drawer).toHaveCount(0)
+ await expect(selected).toHaveText([/Details 0/])
+ await rows.nth(1).click()
+ await expect(drawer).toHaveCount(0)
+ await rows.nth(1).dblclick()
+ await expect(handle).toHaveAttribute(
+ 'aria-valuenow',
+ String(Math.round(viewportHeight * 0.75))
+ )
+ await handle.press('Home')
+ await drawer.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(drawer).toHaveCount(0)
+ await more.click()
+ await expect(more).toHaveAttribute('aria-expanded', 'true')
+ await mainWindow.getByRole('menuitem', { name: 'Show Inspector' }).click()
+ await expect(handle).toHaveAttribute('aria-valuenow', '220')
+ await expect(selected).toHaveText([/Details 1/])
+})
+
+test('marquee selection survives row feedback, data updates and blank-space drags', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1000, 672)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const tasks = Array.from({ length: 8 }, (_, index) =>
+ makeDownloadTask({
+ id: `marquee-${index}`,
+ name: `Marquee ${index}.bin`,
+ createdAt: 8_000 - index,
+ status: TaskStatus.Paused,
+ })
+ )
+ await publish(electronApp, tasks)
+ const grid = mainWindow.locator('[data-downloads-grid]')
+ const rows = grid.locator('[data-task-id]')
+ await expect(rows).toHaveCount(8)
+ const first = (await rows.nth(0).boundingBox())!
+ const start = { x: first.x + 100, y: first.y + 18 }
+ await mainWindow.mouse.move(start.x, start.y)
+ await mainWindow.mouse.down()
+ await mainWindow.mouse.move(start.x + 40, start.y + 36, { steps: 4 })
+ await expect(grid.locator('[aria-selected="true"]')).toHaveCount(2)
+ await publish(
+ electronApp,
+ tasks.map((task) => ({ ...task, downloadSpeed: 12_000 }))
+ )
+ await mainWindow.mouse.move(start.x + 100, start.y + 108, { steps: 8 })
+ await expect(grid.locator('[aria-selected="true"]')).toHaveCount(4)
+ await expect(grid.getByTestId('marquee-box')).toHaveCSS('opacity', '1')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('marquee-row-selection.png'),
+ })
+ await mainWindow.mouse.up()
+ await expect(grid.getByTestId('marquee-box')).toHaveCSS('opacity', '0')
+ await expect(grid.locator('[aria-selected="true"]')).toHaveCount(4)
+ await mainWindow.keyboard.press('Escape')
+ const last = (await rows.nth(7).boundingBox())!
+ await mainWindow.mouse.move(start.x + 160, last.y + last.height + 30)
+ await mainWindow.mouse.down()
+ await mainWindow.mouse.move(start.x + 60, start.y + 4 * 36, { steps: 12 })
+ await expect(grid.locator('[aria-selected="true"]')).toHaveCount(4)
+ await mainWindow.mouse.up()
+ await expect(grid.locator('[aria-selected="true"]')).toHaveText([
+ /Marquee 4/,
+ /Marquee 5/,
+ /Marquee 6/,
+ /Marquee 7/,
+ ])
+
+ await mainWindow.keyboard.press('Escape')
+ await publish(
+ electronApp,
+ Array.from({ length: 50 }, (_, index) =>
+ makeDownloadTask({
+ id: `marquee-${index}`,
+ name: `Marquee ${index}.bin`,
+ createdAt: 8_000 - index,
+ status: TaskStatus.Paused,
+ })
+ )
+ )
+ await expect(grid).toHaveAttribute('aria-rowcount', '51')
+ const viewport = grid.getByTestId('virtual-list-container')
+ const viewportBox = (await viewport.boundingBox())!
+ await mainWindow.mouse.move(start.x, start.y + 4 * 36)
+ await mainWindow.mouse.down()
+ await mainWindow.mouse.move(
+ start.x + 140,
+ viewportBox.y + viewportBox.height - 8,
+ { steps: 12 }
+ )
+ await expect
+ .poll(() => viewport.evaluate((element) => element.scrollTop))
+ .toBeGreaterThan(300)
+ await expect(grid.getByTestId('marquee-box')).toHaveCSS('opacity', '1')
+ const rangeEnd = await grid
+ .locator('[data-task-id][aria-selected="true"]')
+ .last()
+ .getAttribute('data-task-id')
+ expect(Number(rangeEnd!.split('-')[1])).toBeGreaterThan(20)
+ await mainWindow.mouse.up()
+ await expect(grid.getByTestId('marquee-box')).toHaveCSS('opacity', '0')
+ const releasedScroll = await viewport.evaluate((element) => element.scrollTop)
+ await mainWindow.evaluate(
+ () =>
+ new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ )
+ )
+ expect(await viewport.evaluate((element) => element.scrollTop)).toBe(
+ releasedScroll
+ )
+
+ await viewport.evaluate((element) => {
+ element.scrollTop = 0
+ })
+ const selectionAtTop = () =>
+ grid
+ .locator('[data-task-id][aria-selected="true"]')
+ .evaluateAll((elements) =>
+ elements.map((element) => element.getAttribute('data-task-id'))
+ )
+ const beforeScrollbar = await selectionAtTop()
+ const thumb = grid.locator(
+ '[data-slot="scroll-area-scrollbar"][data-orientation="vertical"] [data-slot="scroll-area-thumb"]'
+ )
+ await thumb.hover()
+ const thumbBox = (await thumb.boundingBox())!
+ await mainWindow.mouse.move(
+ thumbBox.x + thumbBox.width / 2,
+ thumbBox.y + thumbBox.height / 2
+ )
+ await mainWindow.mouse.down()
+ await mainWindow.mouse.move(
+ thumbBox.x + thumbBox.width / 2,
+ thumbBox.y + thumbBox.height / 2 + 60,
+ { steps: 8 }
+ )
+ await expect(grid.getByTestId('marquee-box')).toHaveCSS('opacity', '0')
+ await mainWindow.mouse.up()
+ await expect
+ .poll(() => viewport.evaluate((element) => element.scrollTop))
+ .toBeGreaterThan(0)
+ await viewport.evaluate((element) => {
+ element.scrollTop = 0
+ })
+ await expect.poll(selectionAtTop).toEqual(beforeScrollbar)
+})
+
+test('inspector content stays fully reachable at every snap and window height', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'inspector-overflow',
+ name: 'Inspector overflow.bin',
+ status: TaskStatus.Completed,
+ finishedAt: Date.parse('2026-09-13T12:30:00Z'),
+ }),
+ ])
+ await mainWindow.getByRole('row', { name: /Inspector overflow.bin/ }).click()
+ await mainWindow
+ .getByRole('button', { name: 'Show Inspector', exact: true })
+ .click()
+ const drawer = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ const handle = drawer.getByRole('separator', { name: 'Resize Inspector' })
+ const content = mainWindow.getByTestId('task-inspector-drawer-content')
+ await expectDrawerSettled(drawer)
+ for (const [width, height] of [
+ [1280, 900],
+ [914, 672],
+ [1000, 600],
+ ]) {
+ await setTaskInspectorContentSize(electronApp, mainWindow, width, height)
+ for (const snapKey of ['Home', 'ArrowUp', 'End']) {
+ await handle.focus()
+ await handle.press(snapKey)
+ await expectDrawerSettled(drawer)
+ const layout = await drawer.evaluate((element) => {
+ const viewport = element
+ .closest('[data-slot="drawer-viewport"]')!
+ .getBoundingClientRect()
+ return {
+ available: viewport.height,
+ visible: viewport.bottom - element.getBoundingClientRect().top,
+ }
+ })
+ const expectedHeight =
+ snapKey === 'Home'
+ ? 220
+ : Math.round(layout.available * (snapKey === 'End' ? 0.75 : 0.5))
+ expect(layout.visible).toBeCloseTo(expectedHeight, 0)
+ await content.evaluate((element) => {
+ element.scrollTop = 0
+ })
+ await content.hover()
+ await mainWindow.mouse.wheel(0, 10_000)
+ await expect
+ .poll(() =>
+ content.evaluate(
+ (element) =>
+ element.scrollTop + element.clientHeight >=
+ element.scrollHeight - 1
+ )
+ )
+ .toBe(true)
+ const geometry = await content.evaluate((element) => {
+ const last = element.querySelector(
+ 'time[datetime="2026-09-13T12:30:00.000Z"]'
+ )!
+ const bounds = element.getBoundingClientRect()
+ const lastBounds = last.getBoundingClientRect()
+ const hit = document.elementFromPoint(
+ lastBounds.left + lastBounds.width / 2,
+ lastBounds.top + lastBounds.height / 2
+ )
+ return {
+ viewportHeight: innerHeight,
+ bottom: bounds.bottom,
+ lastBottom: lastBounds.bottom,
+ lastTop: lastBounds.top,
+ top: bounds.top,
+ reachable: hit === last || last.contains(hit),
+ clientHeight: element.clientHeight,
+ scrollHeight: element.scrollHeight,
+ scrollTop: element.scrollTop,
+ }
+ })
+ await testInfo.attach(`geometry-${width}-${height}-${snapKey}`, {
+ body: JSON.stringify(geometry),
+ contentType: 'application/json',
+ })
+ expect(geometry.bottom).toBeLessThanOrEqual(geometry.viewportHeight)
+ expect(geometry.lastBottom).toBeLessThanOrEqual(geometry.bottom)
+ expect(geometry.lastTop).toBeGreaterThanOrEqual(geometry.top)
+ expect(geometry.reachable).toBe(true)
+ if (width === 914 && snapKey === 'Home') {
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-inspector-scrolled-to-bottom.png'),
+ })
+ }
+ }
+ }
+})
+
+test('native list controls preserve selection through context menus, column changes and drawer snaps', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'alpha',
+ name: 'Alpha.bin',
+ status: TaskStatus.Downloading,
+ }),
+ makeDownloadTask({
+ id: 'beta',
+ name: 'Beta.bin',
+ status: TaskStatus.Paused,
+ }),
+ makeDownloadTask({
+ id: 'gamma',
+ name: 'Gamma.bin',
+ status: TaskStatus.Completed,
+ }),
+ ])
+ const grid = mainWindow.locator('[data-downloads-grid]')
+ const alpha = grid.locator('[data-task-id=alpha]')
+ const beta = grid.locator('[data-task-id=beta]')
+ await alpha.click()
+ await expect(grid).toBeFocused()
+ await expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+ expect(
+ await grid.evaluate((element) => getComputedStyle(element).outlineStyle)
+ ).toBe('none')
+ await expect(
+ mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ ).toHaveCount(0)
+ await grid.locator('[data-task-id=gamma]').click({ button: 'right' })
+ const completedMenu = mainWindow.getByRole('menu')
+ await expect(completedMenu).toBeVisible()
+ await expect(
+ completedMenu.getByRole('menuitem', { name: 'Move Up in Queue' })
+ ).toHaveCount(0)
+ expect(
+ await completedMenu.evaluate((menu) => {
+ const roles = [
+ ...menu.querySelectorAll('[role="menuitem"], [role="separator"]'),
+ ].map((element) => element.getAttribute('role'))
+ return roles.some(
+ (role, index) =>
+ role === 'separator' && roles[index + 1] === 'separator'
+ )
+ })
+ ).toBe(false)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('completed-task-context-menu.png'),
+ })
+ await mainWindow.keyboard.press('Escape')
+ await alpha.click()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('pointer-selection.png'),
+ })
+ await beta.click({ modifiers: ['Meta'] })
+ await beta.click({ button: 'right' })
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'Pause', exact: true })
+ ).toBeVisible()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'Resume', exact: true })
+ ).toBeVisible()
+ await expect(alpha).toHaveAttribute('aria-selected', 'true')
+ await expect(beta).toHaveAttribute('aria-selected', 'true')
+ expect(
+ (await mainWindow.getByRole('menu').boundingBox())!.width
+ ).toBeGreaterThanOrEqual(192)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-context-menu.png'),
+ })
+ await mainWindow.keyboard.press('Escape')
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+ await expect(beta).toHaveAttribute('aria-selected', 'true')
+ await alpha.click({ modifiers: ['Control'] })
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'Resume', exact: true })
+ ).toBeVisible()
+ await expect(beta).toHaveAttribute('aria-selected', 'true')
+ await mainWindow.keyboard.press('Escape')
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+
+ await mainWindow.getByRole('button', { name: 'More', exact: true }).click()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'Resume', exact: true })
+ ).toBeVisible()
+ await mainWindow.keyboard.press('Escape')
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+
+ await grid.getByRole('button', { name: 'Name', exact: true }).focus()
+ await mainWindow.keyboard.press('Shift+Tab')
+ await expect(grid).toBeFocused()
+ await expect(grid).toHaveAttribute('data-keyboard-focus', 'true')
+ expect(
+ await grid.evaluate((element) => getComputedStyle(element).outlineStyle)
+ ).toBe('solid')
+
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('keyboard-focus.png'),
+ })
+ const nameResize = grid.getByRole('separator', { name: 'Resize Name column' })
+ await nameResize.focus()
+ await mainWindow.keyboard.press('ArrowRight')
+ await expect(nameResize).toHaveAttribute('aria-valuenow', '256')
+ const nameHeader = grid.getByRole('button', { name: 'Name', exact: true })
+ await nameHeader.click({ button: 'right' })
+ await mainWindow
+ .getByRole('menuitemcheckbox', { name: 'Date completed' })
+ .click()
+ await mainWindow.keyboard.press('Escape')
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+ await expect(
+ grid.getByRole('button', { name: 'Date completed', exact: true })
+ ).toHaveCount(0)
+ await expect(beta).toHaveAttribute('aria-selected', 'true')
+
+ // A badge occupies its text width, independently of the status column.
+ const badge = beta.getByTestId('task-status-pill')
+ const badgeSize = await badge.boundingBox()
+ const cellSize = await badge.locator('..').boundingBox()
+ expect(badgeSize!.width).toBeLessThan(cellSize!.width - 16)
+
+ await mainWindow
+ .getByRole('button', { name: 'Show Inspector', exact: true })
+ .click()
+ const drawer = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ await expect(drawer).toBeVisible()
+ const handle = drawer.getByRole('separator', { name: 'Resize Inspector' })
+ const header = drawer.locator('[data-slot="drawer-header"]')
+ await expect(
+ header.getByRole('separator', { name: 'Resize Inspector' })
+ ).toBeVisible()
+ await expect
+ .poll(() =>
+ header.evaluate((element) => element.getBoundingClientRect().height)
+ )
+ .toBe(41)
+ await handle.focus()
+ await mainWindow.keyboard.press('Home')
+ await expect(handle).toHaveAttribute('aria-valuenow', '220')
+ await expectDrawerSettled(drawer)
+ // Starting on a header action must not turn a canceled button click into a swipe.
+ const closeBox = (await header
+ .getByRole('button', { name: 'Close', exact: true })
+ .boundingBox())!
+ await mainWindow.mouse.move(
+ closeBox.x + closeBox.width / 2,
+ closeBox.y + closeBox.height / 2
+ )
+ await mainWindow.mouse.down()
+ await mainWindow.mouse.move(closeBox.x - 60, closeBox.y - 30, { steps: 4 })
+ await expect(drawer).not.toHaveAttribute('data-swiping', '')
+ await mainWindow.mouse.up()
+ await expect(drawer).toBeVisible()
+ await expect(handle).toHaveAttribute('aria-valuenow', '220')
+ await handle.click({ trial: true })
+ const box = await handle.boundingBox()
+ await mainWindow.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)
+ await mainWindow.mouse.down()
+ await mainWindow.mouse.move(box!.x + box!.width / 2, box!.y - 12, {
+ steps: 2,
+ })
+ await expect(drawer).toHaveAttribute('data-swiping', '')
+ await mainWindow.mouse.move(box!.x + box!.width / 2, box!.y - 200, {
+ steps: 16,
+ })
+ await mainWindow.mouse.up()
+ await expect.poll(() => handle.getAttribute('aria-valuenow')).not.toBe('220')
+ await expect(alpha).toHaveAttribute('aria-selected', 'true')
+ // A fully expanded overlay deliberately covers these rows. Collapse it
+ // before verifying that the uncovered list stays interactive.
+ await handle.focus()
+ await handle.press('Home')
+ await expectDrawerSettled(drawer)
+ await beta.click()
+ await expect(drawer).toBeVisible()
+ await drawer.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(drawer).toHaveCount(0)
+ await expect(beta).toHaveAttribute('aria-selected', 'true')
+ await alpha.click()
+ await expect(drawer).toHaveCount(0)
+ await mainWindow
+ .getByRole('button', { name: 'Show Inspector', exact: true })
+ .click()
+ await expect(drawer).toContainText('Alpha.bin')
+ await expectDrawerSettled(drawer)
+ await drawer
+ .getByRole('separator', { name: 'Resize Inspector' })
+ .click({ trial: true })
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('native-list-and-snap-drawer.png'),
+ animations: 'disabled',
+ })
+ await testInfo.attach('native-list-and-snap-drawer', {
+ body: await mainWindow.screenshot({ animations: 'disabled' }),
+ contentType: 'image/png',
+ })
+ await mainWindow
+ .getByRole('button', { name: 'Toggle sidebar', exact: true })
+ .click()
+ const toolbarButtons = mainWindow.locator(
+ '[data-slot="panel-shell-actions"] button'
+ )
+ await expect(toolbarButtons).toHaveCount(4)
+ for (const button of await toolbarButtons.all()) {
+ await expect
+ .poll(() =>
+ button.evaluate((element) => {
+ const rect = element.getBoundingClientRect()
+ const icon = element.querySelector('svg')!.getBoundingClientRect()
+ return [rect.width, rect.height, icon.width, icon.height]
+ })
+ )
+ .toEqual([24, 24, 16, 16])
+ }
+ await alpha.click()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('collapsed-sidebar-selection.png'),
+ animations: 'disabled',
+ })
+ await updateTaskInspectorAppearance(mainWindow, 'dark', 'zh-CN')
+ await expect(mainWindow.locator('html')).toHaveClass(/dark/)
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'dark',
+ name: '示例任务.zip',
+ status: TaskStatus.Paused,
+ createdAt: Date.now(),
+ }),
+ ])
+ const darkRow = mainWindow.getByRole('row', { name: '示例任务.zip' })
+ await darkRow.click()
+ await expectDrawerSettled(
+ mainWindow.getByRole('dialog', { name: '任务详情' })
+ )
+ await expect(darkRow.getByTestId('task-status-pill')).toHaveText('已暂停')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('dark-selection.png'),
+ animations: 'disabled',
+ })
+ await darkRow.click({ button: 'right' })
+ await expect(
+ mainWindow.getByRole('menuitem', { name: '调整下载顺序' })
+ ).toBeVisible()
+ expect(
+ (await mainWindow.getByRole('menu').boundingBox())!.width
+ ).toBeGreaterThanOrEqual(192)
+ await mainWindow.getByRole('menuitem', { name: '调整下载顺序' }).hover()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: '在队列中上移' })
+ ).toBeVisible()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: '移至队列最前' })
+ ).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('dark-chinese-context-menu.png'),
+ })
+})
+
+test('compact search filters the table and explains active query and type filters', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const tasks = [
+ makeDownloadTask({ id: 'alpha', name: 'Alpha.iso', type: TaskType.Http }),
+ makeDownloadTask({ id: 'beta', name: 'Beta.iso', type: TaskType.Http }),
+ makeDownloadTask({ id: 'ftp', name: 'Alpha FTP.iso', type: TaskType.Ftp }),
+ ]
+ await publish(electronApp, tasks)
+ const root = mainWindow.locator('[data-slot="downloads-search"]')
+ const search = mainWindow.getByRole('button', {
+ name: 'Search downloads',
+ exact: true,
+ })
+ await expect(
+ mainWindow.getByRole('button', { name: 'More', exact: true })
+ ).toBeEnabled()
+ await search.click()
+ const input = mainWindow.getByRole('textbox', { name: 'Search downloads' })
+ await expect(input).toBeFocused()
+ await expect(root).toHaveAttribute('data-filter-active', 'false')
+ const filter = mainWindow.getByRole('button', { name: /^Filters/ })
+ await expect(filter.locator('svg')).toHaveClass(/lucide-list-filter/)
+ await input.fill('alpha')
+ await expect(mainWindow.locator('[data-task-id]')).toHaveCount(2)
+ await expect(root).toHaveAttribute('data-filter-active', 'true')
+ await expect(filter).toHaveCSS('color', 'rgb(0, 107, 214)')
+ await filter.click()
+ const filterPopup = mainWindow.getByRole('dialog', {
+ name: 'Filters',
+ exact: true,
+ })
+ await expect(filterPopup).toBeVisible()
+ await expect
+ .poll(async () => {
+ const popup = (await filterPopup.boundingBox())!
+ const field = (await root.boundingBox())!
+ return Math.abs(popup.x - field.x) + Math.abs(popup.width - field.width)
+ })
+ .toBeLessThanOrEqual(1)
+ await expect(mainWindow.getByRole('tooltip')).toHaveCount(0)
+ await mainWindow.getByRole('button', { name: /^HTTP/ }).click()
+ await expect(mainWindow.locator('[data-task-id]')).toHaveCount(1)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-filter-popover-light.png'),
+ animations: 'disabled',
+ })
+ await mainWindow.keyboard.press('Escape')
+ await filter.hover()
+ await expect(mainWindow.getByRole('tooltip')).toContainText('Search: alpha')
+ await expect(mainWindow.getByRole('tooltip')).toContainText(
+ 'Type filter: HTTP'
+ )
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-search-light.png'),
+ })
+ await mainWindow
+ .getByRole('button', { name: 'Clear search', exact: true })
+ .click()
+ await expect(input).toHaveValue('')
+ await expect(input).toBeFocused()
+ await expect(root).toHaveAttribute('data-filter-active', 'true')
+ await expect(mainWindow.locator('[data-task-id]')).toHaveCount(2)
+ await filter.click()
+ await mainWindow
+ .getByRole('button', { name: 'Reset filters', exact: true })
+ .click()
+ await mainWindow.keyboard.press('Escape')
+ await expect(root).toHaveAttribute('data-filter-active', 'false')
+ await input.click()
+ await input.press('Escape')
+ await expect(search).toBeFocused()
+ await search.click()
+ await mainWindow.getByRole('heading', { name: 'All Downloads' }).click()
+ await expect(root).toHaveAttribute('data-expanded', 'false')
+ await mainWindow.keyboard.press('Escape')
+
+ await updateTaskInspectorAppearance(mainWindow, 'dark', 'zh-CN')
+ await publish(electronApp, tasks)
+ await mainWindow
+ .getByRole('button', { name: '搜索下载任务', exact: true })
+ .click()
+ const zhInput = mainWindow.getByRole('textbox', { name: '搜索下载任务' })
+ await zhInput.fill('alpha')
+ const zhFilter = mainWindow.getByRole('button', { name: /^筛选/ })
+ await zhFilter.click()
+ await mainWindow.getByRole('button', { name: /^HTTP/ }).click()
+ await mainWindow.getByRole('button', { name: /^FTP/ }).click()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-filter-popover-dark.png'),
+ animations: 'disabled',
+ })
+ await mainWindow.keyboard.press('Escape')
+ await zhFilter.hover()
+ await expect(mainWindow.getByRole('tooltip')).toContainText(
+ '类型筛选:HTTP和FTP'
+ )
+ await expect(zhFilter).toHaveCSS('color', 'rgb(105, 174, 255)')
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('compact-search-dark.png'),
+ })
+ // A stream update can remove every match of an already-selected type.
+ await publish(
+ electronApp,
+ tasks.filter((task) => task.type !== TaskType.Ftp)
+ )
+ await zhFilter.click()
+ const ftp = mainWindow.getByRole('button', { name: /^FTP/ })
+ await expect(ftp).toBeEnabled()
+ await expect(ftp).toHaveAttribute('aria-pressed', 'true')
+ await ftp.click()
+ await expect(ftp).toHaveAttribute('aria-pressed', 'false')
+ await expect(ftp).toBeDisabled()
+})
+
+test('opens new tasks from empty, selected-row and whitespace context menus', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await expect(
+ mainWindow.getByText('No downloads yet', { exact: true })
+ ).toBeVisible()
+ await mainWindow.locator('[data-slot="context-menu-trigger"]').click({
+ button: 'right',
+ position: { x: 20, y: 20 },
+ })
+ const create = mainWindow.getByRole('menuitem', {
+ name: 'New Task…',
+ exact: true,
+ })
+ await expect(create).toBeVisible()
+ await expect(mainWindow.getByRole('menuitem')).toHaveCount(1)
+ await expect(mainWindow.getByRole('menu').getByRole('separator')).toHaveCount(
+ 0
+ )
+ await create.click()
+ const addTask = await findAddTaskWindow(electronApp)
+ await expect(addTask.getByRole('textbox', { name: 'URLs' })).toBeVisible()
+ await addTask.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await publish(electronApp, [
+ makeDownloadTask({ id: 'new-task-context', name: 'Existing.bin' }),
+ ])
+ const row = mainWindow.getByRole('row', { name: 'Existing.bin', exact: true })
+ await row.click()
+ await row.click({ button: 'right' })
+ await expect(create).toBeVisible()
+ await expect(mainWindow.getByRole('menuitem').first()).toHaveAccessibleName(
+ 'Show Inspector'
+ )
+ await expect(create).toHaveAttribute(
+ 'aria-keyshortcuts',
+ process.platform === 'darwin' ? 'Meta+N' : 'Control+N'
+ )
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('new-task-context-menu.png'),
+ animations: 'disabled',
+ })
+ await create.click()
+ const reopened = await findAddTaskWindow(electronApp)
+ await expect(reopened.getByRole('textbox', { name: 'URLs' })).toBeVisible()
+ await reopened.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(row).toHaveAttribute('aria-selected', 'true')
+ const rowBox = (await row.boundingBox())!
+ await mainWindow.mouse.click(rowBox.x + 40, rowBox.y + rowBox.height + 40, {
+ button: 'right',
+ })
+ await expect(create).toBeVisible()
+ // An open context menu hides the background grid from the accessibility tree.
+ await expect(
+ mainWindow.locator('[data-task-id="new-task-context"]')
+ ).toHaveAttribute('aria-selected', 'true')
+ await mainWindow.keyboard.press('Escape')
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+})
+
+for (const compact of [false, true]) {
+ test(`${compact ? 'compact' : 'standard'} toolbar overflows in priority order without losing input, focus or inspector state`, async ({
+ electronApp,
+ mainWindow,
+ }, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow
+ .getByRole('link', { name: 'Downloads', exact: true })
+ .click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await publish(electronApp, [
+ makeDownloadTask({ id: 'alpha', name: 'Alpha.iso' }),
+ makeDownloadTask({ id: 'beta', name: 'Beta.iso' }),
+ ])
+ const toggleSidebar = mainWindow.getByRole('button', {
+ name: 'Toggle sidebar',
+ exact: true,
+ })
+ if (compact) await toggleSidebar.click()
+ const density = compact ? 'compact' : 'standard'
+ const controlSize = compact ? 30 : 36
+ const targetSize = compact ? 24 : 30
+ const iconSize = compact ? 16 : 18
+ const toolbar = mainWindow.locator('[data-slot="downloads-toolbar"]')
+ const group = mainWindow.locator('[data-slot="downloads-action-group"]')
+ const search = mainWindow.locator('[data-slot="downloads-search"]')
+ await expect(toolbar).toHaveAttribute('data-density', density)
+ await expect(toolbar).toHaveAttribute('data-visible-actions', '3')
+ await expect
+ .poll(async () => (await group.boundingBox())!.height)
+ .toBe(controlSize)
+ expect((await group.boundingBox())!.width).toBe(compact ? 86 : 104)
+ await expect
+ .poll(async () => (await search.boundingBox())!.width)
+ .toBe(controlSize)
+ const title = mainWindow.getByRole('heading', { name: 'All Downloads' })
+ await expect(title).toHaveCSS('font-size', compact ? '14px' : '24px')
+ await expect
+ .poll(
+ async () => (await mainWindow.locator('header').boundingBox())!.height
+ )
+ .toBe(compact ? 38 : 80)
+ for (const button of await toolbar.getByRole('button').all()) {
+ await expect
+ .poll(() =>
+ button.evaluate((element) => {
+ const rect = element.getBoundingClientRect()
+ const svg = element.querySelector('svg')!.getBoundingClientRect()
+ return [rect.width, rect.height, svg.width, svg.height]
+ })
+ )
+ .toEqual([targetSize, targetSize, iconSize, iconSize])
+ }
+ await mainWindow.screenshot({
+ path: testInfo.outputPath(`${density}-toolbar-default.png`),
+ animations: 'disabled',
+ })
+ await mainWindow
+ .getByRole('button', { name: 'Search downloads', exact: true })
+ .click()
+ const input = mainWindow.getByRole('textbox', { name: 'Search downloads' })
+ await input.fill('alpha')
+ await expect.poll(async () => (await search.boundingBox())!.width).toBe(230)
+ const heading = await mainWindow
+ .getByRole('heading', { name: 'All Downloads' })
+ .boundingBox()
+ const controls = (await group.boundingBox())!
+ expect(
+ Math.abs(
+ heading!.y + heading!.height / 2 - controls.y - controls.height / 2
+ )
+ ).toBeLessThanOrEqual(1)
+ await mainWindow.getByRole('row', { name: 'Alpha.iso' }).dblclick()
+ const drawer = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ await expectDrawerSettled(drawer)
+ await input.click()
+ const fitToolbar = async (available: number) => {
+ const bounds = (await toolbar.boundingBox())!
+ const viewport = mainWindow.viewportSize()!
+ await setTaskInspectorContentSize(
+ electronApp,
+ mainWindow,
+ Math.round(viewport.width + available - bounds.width),
+ 900
+ )
+ }
+ await fitToolbar(compact ? 308 : 320)
+ await expect(toolbar).toHaveAttribute('data-visible-actions', '2')
+ await expect(input).toBeFocused()
+ await expect(input).toHaveValue('alpha')
+ await expect(drawer).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath(`${density}-toolbar-two-actions.png`),
+ animations: 'disabled',
+ })
+ const info = mainWindow.getByRole('button', {
+ name: 'Hide Inspector',
+ exact: true,
+ })
+ await info.focus()
+ await fitToolbar(280)
+ await expect(toolbar).toHaveAttribute('data-visible-actions', '1')
+ const more = mainWindow.getByRole('button', { name: 'More', exact: true })
+ await expect(more).toBeFocused()
+ await expect(drawer).toBeVisible()
+ expect((await search.boundingBox())!.x).toBeGreaterThanOrEqual(
+ (await group.boundingBox())!.x + (await group.boundingBox())!.width + 7
+ )
+ await more.click()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'List View' })
+ ).toBeVisible()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'Hide Inspector' })
+ ).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath(`${density}-search-overflow.png`),
+ animations: 'disabled',
+ })
+ await mainWindow.keyboard.press('Escape')
+ await fitToolbar(400)
+ await expect(toolbar).toHaveAttribute('data-visible-actions', '3')
+ await expect(info).toBeVisible()
+ await expect(input).toHaveValue('alpha')
+ await expect(drawer).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath(`${density}-search-expanded.png`),
+ animations: 'disabled',
+ })
+ // A density change must preserve the live search, selection and open inspector.
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await toggleSidebar.click()
+ await expect(toolbar).toHaveAttribute(
+ 'data-density',
+ compact ? 'standard' : 'compact'
+ )
+ await expect
+ .poll(async () => (await group.boundingBox())!.height)
+ .toBe(compact ? 36 : 30)
+ await expect(input).toHaveValue('alpha')
+ await expect(
+ mainWindow.getByRole('row', { name: 'Alpha.iso' })
+ ).toHaveAttribute('aria-selected', 'true')
+ await expect(drawer).toBeVisible()
+ expect(
+ await mainWindow.evaluate(
+ () => document.documentElement.scrollHeight > window.innerHeight
+ )
+ ).toBe(false)
+ })
+}
+
+test('context actions open files, select download files, reorder the queue and copy errors', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const channels = {
+ open: Commands.OpenTaskFile,
+ move: Commands.MoveTasks,
+ files: Queries.GetTaskFiles,
+ select: Commands.SetSelectedFiles,
+ }
+ await electronApp.evaluate(({ ipcMain }, channels) => {
+ const calls: Array<{ channel: string; payload: unknown }> = []
+ Object.assign(globalThis, { menuActionCalls: calls })
+ for (const channel of Object.values(channels)) {
+ ipcMain.removeHandler(channel)
+ ipcMain.handle(channel, (_event, payload) => {
+ calls.push({ channel, payload })
+ if (channel === channels.files)
+ return [0, 1, 2].map((index) => ({
+ index,
+ path: `File ${index}.bin`,
+ size: 1000,
+ selected: index === 0,
+ completedBytes: 0,
+ uris: [],
+ }))
+ if (channel === channels.move)
+ return { moved: payload.taskIds, unchanged: [], failed: [] }
+ return undefined
+ })
+ }
+ }, channels)
+ const getCalls = () =>
+ electronApp.evaluate(
+ () =>
+ (
+ globalThis as unknown as {
+ menuActionCalls: Array<{ channel: string; payload: unknown }>
+ }
+ ).menuActionCalls
+ )
+ const tasks = [
+ makeDownloadTask({
+ id: 'menu-completed',
+ name: 'Completed.bin',
+ status: TaskStatus.Completed,
+ fileCount: 1,
+ finalPath: '/downloads/Completed.bin',
+ }),
+ makeDownloadTask({
+ id: 'menu-bt',
+ name: 'Torrent collection',
+ type: TaskType.Bt,
+ status: TaskStatus.Paused,
+ fileCount: 3,
+ bt: {
+ peers: 0,
+ seeds: 0,
+ ratio: 0,
+ trackers: [],
+ selectedFiles: [0],
+ peersInSwarm: 0,
+ seedsInSwarm: 0,
+ announceList: [],
+ comment: null,
+ isPrivate: false,
+ magnetUri: null,
+ sequentialDownload: false,
+ },
+ }),
+ makeDownloadTask({
+ id: 'menu-error',
+ name: 'Failed.bin',
+ status: TaskStatus.Error,
+ errorCode: DownloadErrorCode.DiskFull,
+ errorMessage: 'ENOSPC: fixture disk is full',
+ }),
+ ]
+ await publish(electronApp, tasks)
+ const row = (id: string) => mainWindow.locator(`[data-task-id="${id}"]`)
+ await row('menu-completed').click({ button: 'right' })
+ await mainWindow
+ .getByRole('menuitem', { name: 'Open file', exact: true })
+ .click()
+ await expect.poll(getCalls).toContainEqual({
+ channel: channels.open,
+ payload: { taskId: 'menu-completed' },
+ })
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+
+ await row('menu-bt').click({ button: 'right' })
+ await mainWindow
+ .getByRole('menuitem', { name: 'Download order', exact: true })
+ .hover()
+ await expect(
+ mainWindow.getByRole('menuitem', { name: 'Move to Front', exact: true })
+ ).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('queue-submenu.png'),
+ })
+ await mainWindow
+ .getByRole('menuitem', { name: 'Move to Front', exact: true })
+ .click()
+ await expect.poll(getCalls).toContainEqual({
+ channel: channels.move,
+ payload: { taskIds: ['menu-bt'], direction: 'top' },
+ })
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+ await row('menu-bt').click({ button: 'right' })
+ await mainWindow
+ .getByRole('menuitem', { name: 'Download order', exact: true })
+ .focus()
+ await mainWindow.keyboard.press('ArrowRight')
+ await mainWindow
+ .getByRole('menuitem', { name: 'Move to Back', exact: true })
+ .click()
+ await expect.poll(getCalls).toContainEqual({
+ channel: channels.move,
+ payload: { taskIds: ['menu-bt'], direction: 'bottom' },
+ })
+ await expect(mainWindow.getByRole('menu')).toHaveCount(0)
+
+ await row('menu-bt').click({ button: 'right' })
+ await mainWindow
+ .getByRole('menuitem', { name: 'Choose files…', exact: true })
+ .click()
+ const inspector = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ await expect(inspector).toBeVisible()
+ await expect(
+ inspector.getByRole('tab', { name: 'Files', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await inspector
+ .getByRole('checkbox', { name: 'File 1.bin', exact: true })
+ .click()
+ await inspector.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect.poll(getCalls).toContainEqual({
+ channel: channels.select,
+ payload: { taskId: 'menu-bt', indices: [0, 1] },
+ })
+ await inspector.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(inspector).toHaveCount(0)
+
+ await row('menu-error').click({ button: 'right' })
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('error-context-menu.png'),
+ })
+ await mainWindow
+ .getByRole('menuitem', { name: 'Copy error information', exact: true })
+ .click()
+ await expect
+ .poll(() => electronApp.evaluate(({ clipboard }) => clipboard.readText()))
+ .toContain('ENOSPC: fixture disk is full')
+ await expect
+ .poll(() => electronApp.evaluate(({ clipboard }) => clipboard.readText()))
+ .toContain('Task ID: menu-error')
+})
+
+test('inspector opens a completed file in a compact window', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await electronApp.evaluate(({ ipcMain }, channel) => {
+ const calls: unknown[] = []
+ Object.assign(globalThis, { inspectorOpenFileCalls: calls })
+ ipcMain.removeHandler(channel)
+ ipcMain.handle(channel, (_event, payload) => {
+ calls.push(payload)
+ })
+ }, Commands.OpenTaskFile)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'inspector-completed',
+ name: 'Completed.bin',
+ status: TaskStatus.Completed,
+ fileCount: 1,
+ finalPath: '/downloads/Completed.bin',
+ diskPath: '/downloads/Completed.bin',
+ }),
+ ])
+ await mainWindow.locator('[data-task-id="inspector-completed"]').dblclick()
+ const inspector = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ await expect(inspector).toBeVisible()
+ await expectDrawerSettled(inspector)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 600, 650)
+ await inspector
+ .getByRole('button', { name: 'Open file', exact: true })
+ .click()
+ await expect
+ .poll(() =>
+ electronApp.evaluate(
+ () =>
+ (
+ globalThis as unknown as {
+ inspectorOpenFileCalls: unknown[]
+ }
+ ).inspectorOpenFileCalls
+ )
+ )
+ .toEqual([{ taskId: 'inspector-completed' }])
+ await expect(
+ inspector.getByRole('button', { name: 'Open folder', exact: true })
+ ).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('inspector-open-file-compact.png'),
+ animations: 'disabled',
+ })
+ await inspector.getByRole('button', { name: 'Close', exact: true }).click()
+ await expect(inspector).toHaveCount(0)
+})
+
+for (const [locale, downloads, createdColumn] of [
+ ['en-US', 'Downloads', 'Date created'],
+ ['zh-CN', '下载', '创建时间'],
+ ['zh-TW', '下載', '建立時間'],
+] as const) {
+ test(`task timestamps show localized seconds and full details in ${locale}`, async ({
+ electronApp,
+ mainWindow,
+ }, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1660, 900)
+ await updateTaskInspectorAppearance(mainWindow, 'light', locale)
+ await waitForEngineReady(mainWindow)
+ await mainWindow.getByRole('link', { name: downloads, exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const dates = await mainWindow.evaluate((language) => {
+ const now = new Date(2026, 8, 15, 14, 40).getTime()
+ const first = new Date(2026, 8, 15, 14, 32, 8).getTime()
+ const second = new Date(2026, 8, 15, 14, 32, 59).getTime()
+ const yesterday = new Date(2026, 8, 14, 9, 18, 7).getTime()
+ const historical = new Date(2025, 11, 8, 14, 32, 8).getTime()
+ const full = new Intl.DateTimeFormat(language, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit',
+ })
+ const detailed = new Intl.DateTimeFormat(language, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit',
+ timeZoneName: 'shortOffset',
+ })
+ return {
+ now,
+ first,
+ second,
+ yesterday,
+ historical,
+ todayLabel: new Intl.RelativeTimeFormat(language, {
+ numeric: 'auto',
+ }).format(0, 'day'),
+ yesterdayLabel: new Intl.RelativeTimeFormat(language, {
+ numeric: 'auto',
+ }).format(-1, 'day'),
+ full: full.format(first),
+ detailed: detailed.format(first),
+ historicalLabel: full.format(historical),
+ }
+ }, locale)
+ await mainWindow.clock.setFixedTime(dates.now)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'date-first',
+ name: 'First.bin',
+ createdAt: dates.first,
+ finishedAt: dates.second,
+ status: TaskStatus.Completed,
+ }),
+ makeDownloadTask({
+ id: 'date-second',
+ name: 'Second.bin',
+ createdAt: dates.second,
+ }),
+ makeDownloadTask({
+ id: 'date-yesterday',
+ name: 'Yesterday.bin',
+ createdAt: dates.yesterday,
+ }),
+ makeDownloadTask({
+ id: 'date-history',
+ name: 'History.bin',
+ createdAt: dates.historical,
+ }),
+ ])
+ const list = mainWindow.getByTestId('virtual-list-container')
+ const row = (id: string) => list.locator(`[data-task-id="${id}"]`)
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /Second.bin/,
+ /First.bin/,
+ /Yesterday.bin/,
+ /History.bin/,
+ ])
+ const created = row('date-first').locator('time').first()
+ await expect(created).toContainText(dates.todayLabel)
+ await expect(created).toContainText(':32:08')
+ await expect(row('date-first').locator('time').last()).toContainText(
+ ':32:59'
+ )
+ await expect(row('date-yesterday').locator('time')).toContainText(
+ dates.yesterdayLabel
+ )
+ await expect(row('date-history').locator('time')).toHaveText(
+ dates.historicalLabel
+ )
+ await expect(created).toHaveAttribute('tabindex', '-1')
+ await created.hover()
+ await expect(mainWindow.getByRole('tooltip')).toHaveText(dates.detailed)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('timestamps-tooltip.png'),
+ })
+ // Timestamp text remains part of row selection, not a separate action.
+ await created.click()
+ await expect(row('date-first')).toHaveAttribute('aria-selected', 'true')
+ await expect(mainWindow.getByRole('tooltip')).toHaveCount(0)
+ const createdHeader = list
+ .getByRole('columnheader')
+ .filter({ hasText: createdColumn })
+ // First click exposes the default descending state; the next reverses it.
+ await createdHeader.getByRole('button').click()
+ await createdHeader.getByRole('button').click()
+ await expect(list.locator('[data-task-id]')).toHaveText([
+ /History.bin/,
+ /Yesterday.bin/,
+ /First.bin/,
+ /Second.bin/,
+ ])
+ for (const time of await list.locator('time').all()) {
+ expect(
+ await time.evaluate(
+ (element) => element.scrollWidth <= element.clientWidth
+ )
+ ).toBe(true)
+ }
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('timestamps-list.png'),
+ })
+ await row('date-first').dblclick()
+ const inspector = mainWindow.locator('[data-slot="drawer-content"]')
+ await expect(inspector).toBeVisible()
+ await expectDrawerSettled(inspector)
+ const full = inspector.locator('time').first()
+ await full.scrollIntoViewIfNeeded()
+ await expect(full).toHaveText(dates.full)
+ await full.hover()
+ await expect(mainWindow.getByRole('tooltip')).toHaveText(dates.detailed)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('timestamps-inspector.png'),
+ })
+ })
+}
+
+test('organized context menus expose working scoped shortcuts and keep text editing intact', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ await electronApp.evaluate(({ ipcMain }, channel) => {
+ const calls: unknown[] = []
+ Object.assign(globalThis, { shortcutRemoveCalls: calls })
+ ipcMain.removeHandler(channel)
+ ipcMain.handle(channel, (_event, payload) => {
+ calls.push(payload)
+ return { succeeded: payload.taskIds, failed: [] }
+ })
+ }, Commands.RemoveTasks)
+ await publish(electronApp, [
+ makeDownloadTask({
+ id: 'shortcut-a',
+ name: 'Alpha.bin',
+ status: TaskStatus.Paused,
+ uris: ['https://example.test/alpha.bin'],
+ }),
+ makeDownloadTask({
+ id: 'shortcut-b',
+ name: 'Beta.bin',
+ status: TaskStatus.Paused,
+ uris: ['https://example.test/beta.bin'],
+ }),
+ ])
+ const macOS = process.platform === 'darwin'
+ const primary = macOS ? 'Meta' : 'Control'
+ const grid = mainWindow.locator('[data-downloads-grid]')
+ const row = (id: string) => grid.locator(`[data-task-id="${id}"]`)
+ const clipboard = () =>
+ electronApp.evaluate(({ clipboard }) => clipboard.readText())
+ const removeCalls = () =>
+ electronApp.evaluate(
+ () =>
+ (globalThis as unknown as { shortcutRemoveCalls: unknown[] })
+ .shortcutRemoveCalls
+ )
+ await row('shortcut-a').click()
+ await row('shortcut-b').click({ modifiers: [primary] })
+ await row('shortcut-b').click({ button: 'right' })
+ const menu = mainWindow.getByRole('menu')
+ await expect(menu).toBeVisible()
+ await expect(menu.getByRole('menuitem').first()).toHaveAccessibleName(
+ 'Show Inspector'
+ )
+ await expect(menu.getByRole('menuitem').last()).toHaveAccessibleName('Remove')
+ await expect(
+ menu.getByRole('menuitem', { name: 'Copy URLs', exact: true })
+ ).toHaveAttribute('aria-keyshortcuts', `${primary}+C`)
+ expect((await menu.boundingBox())!.width).toBeGreaterThanOrEqual(192)
+ expect((await menu.boundingBox())!.width).toBeLessThanOrEqual(288)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('organized-multiple-menu.png'),
+ animations: 'disabled',
+ })
+ await mainWindow.keyboard.press(`${primary}+i`)
+ await expect(menu).toHaveCount(0)
+ const inspector = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ await expect(inspector).toBeVisible()
+ await expect(grid).toBeFocused()
+ await mainWindow.keyboard.press(`${primary}+i`)
+ await expect(inspector).toHaveCount(0)
+
+ await mainWindow.keyboard.press(`${primary}+c`)
+ await expect
+ .poll(clipboard)
+ .toBe('https://example.test/alpha.bin\nhttps://example.test/beta.bin')
+ await electronApp.evaluate(({ clipboard }) =>
+ clipboard.writeText('before-menu-copy')
+ )
+ await row('shortcut-b').click({ button: 'right' })
+ await mainWindow.keyboard.press(`${primary}+c`)
+ await expect(menu).toHaveCount(0)
+ await expect
+ .poll(clipboard)
+ .toBe('https://example.test/alpha.bin\nhttps://example.test/beta.bin')
+
+ await mainWindow.keyboard.press(macOS ? 'Meta+Backspace' : 'Delete')
+ const dialog = mainWindow.getByRole('dialog', {
+ name: 'Remove 2 paused tasks?',
+ exact: true,
+ })
+ await expect(dialog).toBeVisible()
+ expect(await removeCalls()).toEqual([])
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(dialog).toHaveCount(0)
+
+ await mainWindow
+ .getByRole('button', { name: 'Search downloads', exact: true })
+ .click()
+ const search = mainWindow.getByRole('textbox', {
+ name: 'Search downloads',
+ exact: true,
+ })
+ await search.fill('alpha')
+ await search.selectText()
+ await mainWindow.keyboard.press(`${primary}+c`)
+ await expect.poll(clipboard).toBe('alpha')
+ await mainWindow.keyboard.press(`${primary}+i`)
+ await expect(inspector).toHaveCount(0)
+ await search.fill('')
+ await search.press('Escape')
+ await row('shortcut-a').click()
+ await row('shortcut-b').click({ modifiers: [primary] })
+ await row('shortcut-b').click({ button: 'right' })
+ await mainWindow.keyboard.press(macOS ? 'Meta+Backspace' : 'Delete')
+ await expect(dialog).toBeVisible()
+ await dialog.getByRole('button', { name: 'Remove', exact: true }).click()
+ await expect
+ .poll(removeCalls)
+ .toEqual([
+ { taskIds: ['shortcut-a', 'shortcut-b'], deleteWithFiles: false },
+ ])
+})
diff --git a/e2e/task-inspector-activity.spec.ts b/e2e/task-inspector-activity.spec.ts
index 12a40925..8ddb5501 100644
--- a/e2e/task-inspector-activity.spec.ts
+++ b/e2e/task-inspector-activity.spec.ts
@@ -224,15 +224,18 @@ async function openActivityForTask(
await expect.poll(() => page.url()).toContain('#/downloads')
}
const openDrawer = page.getByRole('dialog', {
- name: /^(Downloads|下载)$/i,
+ name: /^(Task Inspector|任务详情)$/i,
})
if (await openDrawer.isVisible().catch(() => false)) {
- await page.keyboard.press('Escape')
+ await openDrawer.getByRole('button', { name: /^(Close|关闭)$/ }).click()
await expect(openDrawer).toBeHidden()
}
- const row = page.getByRole('option', { name: new RegExp(taskName, 'i') })
+ const row = page.getByRole('row', { name: new RegExp(taskName, 'i') })
await expect(row).toBeVisible()
await row.click()
+ await page
+ .getByRole('button', { name: /^(Show Inspector|显示详情)$/ })
+ .click()
const tabs = page.getByRole('tab')
await expect(tabs.last()).toBeVisible()
await tabs.last().click()
@@ -257,7 +260,7 @@ async function capture(page: Page, name: string): Promise<void> {
async function expectStatusPillContained(page: Page): Promise<void> {
const drawer = page.getByRole('dialog', {
- name: /^(Downloads|下载)$/i,
+ name: /^(Task Inspector|任务详情)$/i,
})
const statusPill = drawer.getByTestId('task-status-pill')
await expect(statusPill).toBeVisible()
@@ -347,7 +350,7 @@ async function presentActiveReference(
test.describe('Task Inspector Activity', () => {
test.setTimeout(180_000)
- test('keeps Activity and the selected download reachable inside the minimum 914 by 672 window', async ({
+ test('keeps Activity scrollable in an overlay inside the minimum 914 by 672 window', async ({
userDataDir,
}) => {
const { app, page } = await launchSeededApp(userDataDir)
@@ -355,6 +358,11 @@ test.describe('Task Inspector Activity', () => {
const viewport = await setTaskInspectorContentSize(app, page, 914, 672)
expect(viewport).toEqual({ width: 914, height: 672 })
+ await page.getByRole('link', { name: 'Downloads' }).click()
+ await expect(page.getByTestId('downloads-loading')).toHaveCount(0)
+ const list = page.getByTestId('virtual-list-container')
+ const listBox = await list.boundingBox()
+
await openActivityForTask(page, TASK_INSPECTOR_ACTIVITY_NAMES.rich)
const geometry = await page
@@ -389,46 +397,40 @@ test.describe('Task Inspector Activity', () => {
expect(geometry.overflowY).toBe('auto')
expect(geometry.clientHeight).toBeGreaterThan(0)
const drawer = page.getByRole('dialog', {
- name: 'Downloads',
+ name: 'Task Inspector',
exact: true,
})
- const list = page.getByTestId('virtual-list-container')
- const selected = page.getByRole('option', {
- name: new RegExp(TASK_INSPECTOR_ACTIVITY_NAMES.rich),
- })
- await expect
- .poll(() =>
- selected.evaluate((element) => {
- const list = element.closest(
- '[data-testid="virtual-list-container"]'
- )
- if (!list?.firstElementChild) return false
- const rect = element.getBoundingClientRect()
- return (
- rect.top >=
- list.firstElementChild.getBoundingClientRect().bottom - 1 &&
- rect.bottom <= list.getBoundingClientRect().bottom + 1
- )
- })
- )
- .toBe(true)
- const listBox = await list.boundingBox()
- const drawerBox = await drawer.boundingBox()
- expect(listBox!.y + listBox!.height).toBeLessThanOrEqual(drawerBox!.y)
- // The inspector owns overflow when the list needs part of the window.
+ expect(await list.boundingBox()).toEqual(listBox)
+ // Every snap must expose the actual last content pixels, not just
+ // report scrollTop + clientHeight == scrollHeight offscreen.
const content = page.getByTestId('task-inspector-drawer-content')
- await content.evaluate((element) => {
- element.scrollTop = element.scrollHeight
- })
- await expect
- .poll(() =>
- content.evaluate(
- (element) =>
- element.scrollTop + element.clientHeight >=
- element.scrollHeight - 1
+ const handle = drawer.getByRole('separator', { name: 'Resize Inspector' })
+ for (const key of ['Home', 'ArrowUp', 'End']) {
+ await handle.focus()
+ await handle.press(key)
+ await content.hover()
+ await page.mouse.wheel(0, 10_000)
+ await expect
+ .poll(() =>
+ content.evaluate((element) => {
+ const last = element.querySelector(
+ '[data-testid="task-inspector-activity-root"]'
+ )!
+ const bounds = element.getBoundingClientRect()
+ const end = last.getBoundingClientRect()
+ const hit = document.elementFromPoint(
+ end.left + 20,
+ end.bottom - 5
+ )
+ return (
+ bounds.bottom <= innerHeight &&
+ end.bottom <= bounds.bottom &&
+ last.contains(hit)
+ )
+ })
)
- )
- .toBe(true)
+ .toBe(true)
+ }
expect(
await page.evaluate(() => document.documentElement.scrollHeight)
).toBeLessThanOrEqual(viewport.height)
diff --git a/e2e/task-lifecycle.spec.ts b/e2e/task-lifecycle.spec.ts
index c06a93a8..0dd21d5a 100644
--- a/e2e/task-lifecycle.spec.ts
+++ b/e2e/task-lifecycle.spec.ts
@@ -45,7 +45,7 @@ test.describe('task lifecycle', () => {
await mainWindow.getByRole('link', { name: 'Downloads' }).click()
await expect.poll(() => mainWindow.url()).toContain('#/downloads')
- const row = mainWindow.getByRole('option').first()
+ const row = mainWindow.locator('[data-task-id]').first()
await expect(row).toBeVisible({ timeout: 10_000 })
// Reads through window.motrix.invoke so the assertion exercises
diff --git a/extra/aria2.conf b/extra/aria2.conf
index 941416ad..62c9946c 100644
--- a/extra/aria2.conf
+++ b/extra/aria2.conf
@@ -59,6 +59,9 @@ allow-piece-length-change=true
############### BitTorrent — peer behavior ###################################
+# Set seeding time in Motrix's Downloads settings. Motrix applies it per task
+# and excludes global seed-time entries from this configuration at startup.
+
# When a download finishes and starts seeding, stop counting it toward the
# concurrent-downloads quota. Otherwise long-tail seeds permanently block
# new downloads. Highly recommended for desktop UX.
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.ts
index cef47e57..d214c22a 100644
--- a/src/core/engine/aria2/aria2-adapter.test.ts
+++ b/src/core/engine/aria2/aria2-adapter.test.ts
@@ -1571,6 +1571,52 @@ describe('Aria2Adapter', () => {
})
describe('addTorrent', () => {
+ it('reads live seeding defaults and omits zero time without leaking them into HTTP', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addTorrent).mockResolvedValue('gid-new')
+ vi.mocked(rpc.addUri).mockResolvedValue('gid-magnet')
+ let settings = { seedTime: 60, seedRatio: 1 }
+ const adapter = new Aria2Adapter(rpc, undefined, () => settings)
+ const params = { metadata: new Uint8Array([1]), saveDir: '/d' }
+ await adapter.addTorrent(params)
+ expect(vi.mocked(rpc.addTorrent).mock.calls.at(-1)?.[2]).toMatchObject({
+ 'seed-time': '60',
+ 'seed-ratio': '1',
+ })
+ settings = { seedTime: 0, seedRatio: 0 }
+ await adapter.addTorrent(params)
+ expect(
+ vi.mocked(rpc.addTorrent).mock.calls.at(-1)?.[2]
+ ).not.toHaveProperty('seed-time')
+ expect(vi.mocked(rpc.addTorrent).mock.calls.at(-1)?.[2]).toHaveProperty(
+ 'seed-ratio',
+ '0'
+ )
+ settings = { seedTime: 30, seedRatio: 2 }
+ await adapter.createDownload({
+ uris: ['magnet:?xt=urn:btih:abc'],
+ saveDir: '/d',
+ })
+ expect(vi.mocked(rpc.addUri).mock.calls.at(-1)?.[1]).toMatchObject({
+ 'seed-time': '30',
+ 'seed-ratio': '2',
+ })
+ await adapter.addTorrent({ ...params, seedTime: 0, seedRatio: 0 })
+ expect(
+ vi.mocked(rpc.addTorrent).mock.calls.at(-1)?.[2]
+ ).not.toHaveProperty('seed-time')
+ await adapter.createDownload({
+ uris: ['https://example.test/file'],
+ saveDir: '/d',
+ })
+ expect(vi.mocked(rpc.addUri).mock.calls.at(-1)?.[1]).not.toHaveProperty(
+ 'seed-time'
+ )
+ expect(vi.mocked(rpc.addUri).mock.calls.at(-1)?.[1]).not.toHaveProperty(
+ 'seed-ratio'
+ )
+ })
+
it('calls aria2.addTorrent with base64 metadata and options', async () => {
const rpc = createMockRpc()
vi.mocked(rpc.addTorrent).mockResolvedValue('gid-new')
@@ -2077,6 +2123,20 @@ describe('Aria2Adapter', () => {
})
})
+ it('reads the complete waiting queue across pages in engine order', async () => {
+ const rpc = createMockRpc()
+ const first = Array.from({ length: 1000 }, (_, i) => ({
+ gid: `waiting-${i}`,
+ }))
+ vi.mocked(rpc.tellWaiting)
+ .mockResolvedValueOnce(first as Aria2RawStatus[])
+ .mockResolvedValueOnce([{ gid: 'tail' }] as Aria2RawStatus[])
+ const result = await new Aria2Adapter(rpc).listWaitingTaskIds()
+ expect(result).toEqual([...first.map((task) => task.gid), 'tail'])
+ expect(rpc.tellWaiting).toHaveBeenNthCalledWith(2, 1000, 1000, ['gid'])
+ expect(rpc.tellActive).not.toHaveBeenCalled()
+ })
+
describe('listActiveAndWaiting', () => {
it('merges tellActive and tellWaiting, maps entries', async () => {
const rpc = createMockRpc()
diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.ts
index 424a4e0d..b0b43494 100644
--- a/src/core/engine/aria2/aria2-adapter.ts
+++ b/src/core/engine/aria2/aria2-adapter.ts
@@ -20,6 +20,7 @@ import type {
} from '@shared/types/history'
import type { TaskPeer } from '@shared/types/peer'
import type { TaskPiecesResult } from '@shared/types/pieces'
+import type { EngineSettings } from '@shared/types/settings'
import type { GlobalStats } from '@shared/types/stats'
import type { DownloadTask, TaskFile } from '@shared/types/task'
import type { TuningContext } from '@shared/types/tuning'
@@ -156,7 +157,10 @@ export class Aria2Adapter implements EngineAdapter {
constructor(
private rpc: Aria2RpcClient,
- private readonly accessFile: FileAccess = access
+ private readonly accessFile: FileAccess = access,
+ private readonly getSeedingDefaults: () =>
+ | Pick<EngineSettings, 'seedTime' | 'seedRatio'>
+ | undefined = () => undefined
) {
const unsubscribers = [
this.rpc.onBtDownloadComplete((event) => {
@@ -176,6 +180,20 @@ export class Aria2Adapter implements EngineAdapter {
}
}
+ private seedingOptions(
+ overrides: Pick<AddTorrentParams, 'seedTime' | 'seedRatio'> = {}
+ ): Record<string, string> {
+ const defaults = this.getSeedingDefaults()
+ const time = overrides.seedTime ?? defaults?.seedTime
+ const ratio = overrides.seedRatio ?? defaults?.seedRatio
+ // Keep time task-local: aria2 cannot unset an inherited global seed-time
+ // through RPC, and both "0" and "" terminate seeding immediately.
+ return {
+ ...(time !== undefined && time > 0 ? { 'seed-time': String(time) } : {}),
+ ...(ratio !== undefined ? { 'seed-ratio': String(ratio) } : {}),
+ }
+ }
+
async inspectDirectResourceMetadataProfile(): Promise<DirectResourceMetadataProfile | null> {
try {
return await directResourceMetadataProfileFromGlobalOptions(
@@ -375,6 +393,9 @@ export class Aria2Adapter implements EngineAdapter {
)
}
const options: Record<string, string | string[]> = {
+ ...(params.uris.some((uri) => /^magnet:/i.test(uri))
+ ? this.seedingOptions()
+ : {}),
dir: params.saveDir,
}
if (params.filename) options.out = params.filename
@@ -737,12 +758,7 @@ export class Aria2Adapter implements EngineAdapter {
}
)
}
- if (params.seedTime !== undefined) {
- opts['seed-time'] = String(params.seedTime)
- }
- if (params.seedRatio !== undefined) {
- opts['seed-ratio'] = String(params.seedRatio)
- }
+ Object.assign(opts, this.seedingOptions(params))
if (params.btSeedUnverified) {
opts['bt-seed-unverified'] = 'true'
}
@@ -904,6 +920,16 @@ export class Aria2Adapter implements EngineAdapter {
}
}
+ async listWaitingTaskIds(): Promise<string[]> {
+ const ids: string[] = []
+ const pageSize = 1000
+ for (let offset = 0; ; offset += pageSize) {
+ const page = await this.rpc.tellWaiting(offset, pageSize, ['gid'])
+ ids.push(...page.map((task) => task.gid))
+ if (page.length < pageSize) return [...new Set(ids)]
+ }
+ }
+
async listActiveAndWaiting(): Promise<
Array<{ gid: string; infoHash?: string }>
> {
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.ts
index f45511e3..390e8f64 100644
--- a/src/core/engine/aria2/aria2-config-builder.test.ts
+++ b/src/core/engine/aria2/aria2-config-builder.test.ts
@@ -2,29 +2,37 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// ─── Mock node:fs/promises ───────────────────────────────────
-const { mockAccess, mockCopyFile, mockMkdir, mockRename, mockReadFile } =
- vi.hoisted(() => ({
- mockAccess: vi.fn(),
- mockCopyFile: vi.fn(),
- mockMkdir: vi.fn(),
- mockRename: vi.fn(),
- mockReadFile: vi.fn(),
- }))
+const {
+ mockAccess,
+ mockCopyFile,
+ mockMkdir,
+ mockReadFile,
+ mockRename,
+ mockWriteFileAtomic,
+} = vi.hoisted(() => ({
+ mockAccess: vi.fn(),
+ mockCopyFile: vi.fn(),
+ mockMkdir: vi.fn(),
+ mockReadFile: vi.fn(),
+ mockRename: vi.fn(),
+ mockWriteFileAtomic: vi.fn(),
+}))
vi.mock('node:fs/promises', () => ({
default: {
access: mockAccess,
copyFile: mockCopyFile,
mkdir: mockMkdir,
- rename: mockRename,
readFile: mockReadFile,
+ rename: mockRename,
},
access: mockAccess,
copyFile: mockCopyFile,
mkdir: mockMkdir,
- rename: mockRename,
readFile: mockReadFile,
+ rename: mockRename,
}))
+vi.mock('write-file-atomic', () => ({ default: mockWriteFileAtomic }))
import type { Aria2ProxyOptions } from '@core/proxy/serializers'
import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'
@@ -72,7 +80,8 @@ describe('Aria2ConfigBuilder', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockReadFile.mockResolvedValue('')
+ mockReadFile.mockResolvedValue('bt-detach-seed-only=true\n')
+ mockWriteFileAtomic.mockResolvedValue(undefined)
builder = new Aria2ConfigBuilder(
'/app/extra/aria2.conf',
'/home/user/.config/motrix'
@@ -84,6 +93,32 @@ describe('Aria2ConfigBuilder', () => {
})
describe('ensureUserConfig', () => {
+ it('excludes advanced global seeding time while preserving the original config', async () => {
+ mockAccess.mockResolvedValue(undefined)
+ const source =
+ '# seed-time=10\r\nseed-time=0\r\n seed-time = 60\nseed-ratio=2\n'
+ mockReadFile.mockResolvedValue(source)
+ await expect(builder.ensureUserConfig()).resolves.toBe(
+ '/home/user/.config/motrix/aria2.runtime.conf'
+ )
+ expect(mockWriteFileAtomic).toHaveBeenCalledWith(
+ '/home/user/.config/motrix/aria2.runtime.conf',
+ '# seed-time=10\r\nseed-ratio=2\n',
+ { mode: 0o600 }
+ )
+ expect(
+ buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {
+ download: 0,
+ upload: 0,
+ })[0]
+ ).toBe('--conf-path=/home/user/.config/motrix/aria2.runtime.conf')
+ expect(mockCopyFile).not.toHaveBeenCalled()
+ mockReadFile.mockResolvedValue('# seed-time=10\nseed-ratio=2\n')
+ await expect(builder.ensureUserConfig()).resolves.toBe(
+ '/home/user/.config/motrix/aria2.conf'
+ )
+ })
+
it('returns existing user config path when file exists', async () => {
// access resolves → file exists
mockAccess.mockResolvedValue(undefined)
@@ -540,7 +575,7 @@ describe('Aria2ConfigBuilder', () => {
expect(args).toContain(
`--seed-ratio=${DEFAULT_ENGINE_SETTINGS.seedRatio}`
)
- expect(args).toContain(`--seed-time=${DEFAULT_ENGINE_SETTINGS.seedTime}`)
+ expect(args.some((arg) => arg.startsWith('--seed-time='))).toBe(false)
})
it('injects session-save-interval', () => {
@@ -581,7 +616,7 @@ describe('Aria2ConfigBuilder', () => {
expect(args).toContain('--bt-max-peers=256')
expect(args).toContain('--bt-enable-lpd=false')
expect(args).toContain('--seed-ratio=2')
- expect(args).toContain('--seed-time=0')
+ expect(args.some((arg) => arg.startsWith('--seed-time='))).toBe(false)
})
})
diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.ts
index 48a3ec8f..4a23a34e 100644
--- a/src/core/engine/aria2/aria2-config-builder.ts
+++ b/src/core/engine/aria2/aria2-config-builder.ts
@@ -7,6 +7,7 @@ import {
} from '@core/proxy/aria2-proxy-routing'
import type { Aria2ProxyOptions } from '@core/proxy/serializers'
import type { EngineSettings } from '@shared/types/settings'
+import writeFileAtomic from 'write-file-atomic'
import { dnsModeToAsyncDns } from './dns-fallback'
export interface Aria2ConfigBuilderOptions {
@@ -21,6 +22,7 @@ export class Aria2ConfigBuilder {
private readonly dht6FilePath: string
private readonly rpcListenAll: boolean
private configuredInputFile = false
+ private runtimeConfPath: string
constructor(
private templatePath: string,
@@ -28,6 +30,7 @@ export class Aria2ConfigBuilder {
options: Aria2ConfigBuilderOptions = {}
) {
this.userConfPath = path.join(userConfigDir, 'aria2.conf')
+ this.runtimeConfPath = this.userConfPath
this.defaultDbPath = path.join(userConfigDir, 'aria2.db')
this.saveSessionPath = path.join(userConfigDir, 'aria2.session')
this.dhtFilePath = path.join(userConfigDir, 'dht.dat')
@@ -43,12 +46,24 @@ export class Aria2ConfigBuilder {
await mkdir(this.userConfigDir, { recursive: true })
await copyFile(this.templatePath, this.userConfPath)
}
- // aria2.conf remains user-owned. An omitted CLI flag would inherit its
- // input-file, so explicitly clear that value when this startup uses no
- // text input. Ordinary first launches still omit the flag entirely.
- const config = await readFile(this.userConfPath, 'utf8')
- this.configuredInputFile = /^\s*input-file\s*=/m.test(config)
- return this.userConfPath
+ const source = await readFile(this.userConfPath, 'utf8')
+ // Do not inherit a configured text session when this startup disables it.
+ this.configuredInputFile = /^\s*input-file\s*=/m.test(source)
+ // Application seeding time is task-local. A global time inherited from
+ // the advanced config cannot be cleared with a zero/empty RPC option.
+ // Preserve the user's file and all other settings in a runtime copy.
+ const filtered = source.replace(
+ /^[\t ]*seed-time[\t ]*=.*(?:\r?\n|$)/gm,
+ ''
+ )
+ if (filtered === source) {
+ this.runtimeConfPath = this.userConfPath
+ } else {
+ const runtimePath = path.join(this.userConfigDir, 'aria2.runtime.conf')
+ await writeFileAtomic(runtimePath, filtered, { mode: 0o600 })
+ this.runtimeConfPath = runtimePath
+ }
+ return this.runtimeConfPath
}
/**
@@ -158,7 +173,7 @@ export class Aria2ConfigBuilder {
const args: string[] = []
// ── L4 base conf ──
- args.push(`--conf-path=${this.userConfPath}`)
+ args.push(`--conf-path=${this.runtimeConfPath}`)
// ── L2 engine binding ──
args.push(
@@ -219,7 +234,6 @@ export class Aria2ConfigBuilder {
`--bt-max-peers=${settings.btMaxPeers}`,
`--bt-enable-lpd=${settings.btEnableLpd}`,
`--seed-ratio=${settings.seedRatio}`,
- `--seed-time=${settings.seedTime}`,
`--file-allocation=${settings.fileAllocation}`,
`--remote-time=${settings.remoteTime}`,
`--disk-cache=${settings.diskCache}`,
diff --git a/src/core/engine/aria2/seeding-policy.integration.test.ts b/src/core/engine/aria2/seeding-policy.integration.test.ts
new file mode 100644
index 00000000..0eec7c30
--- /dev/null
+++ b/src/core/engine/aria2/seeding-policy.integration.test.ts
@@ -0,0 +1,161 @@
+import { createHash } from 'node:crypto'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import type { EngineSettings } from '@shared/types/settings'
+import { TaskStatus } from '@shared/types/task'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import {
+ type Aria2Handle,
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ connectAdapter,
+ spawnAria2ForTest,
+} from '../../../test-utils/aria2'
+import { Aria2Adapter } from './aria2-adapter'
+import { Aria2ConfigBuilder } from './aria2-config-builder'
+
+type SeedingDefaults = Pick<EngineSettings, 'seedTime' | 'seedRatio'>
+const payload = Buffer.alloc(1024, 42)
+// A single-piece local torrent with no trackers, web seeds or discovery hints.
+const metadata = Buffer.concat([
+ Buffer.from(
+ `d4:infod6:lengthi${payload.length}e4:name11:payload.bin12:piece lengthi16384e6:pieces20:`
+ ),
+ createHash('sha1').update(payload).digest(),
+ Buffer.from('ee'),
+])
+
+describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
+ 'seeding policy with real aria2',
+ () => {
+ let directory: string
+ let handle: Aria2Handle
+ let wired: Awaited<ReturnType<typeof connectAdapter>>
+ let adapter: Aria2Adapter
+ let defaults: SeedingDefaults
+
+ async function start(inputSession = false, configPath?: string) {
+ handle = await spawnAria2ForTest({
+ baseDir: directory,
+ extraArgs: [
+ ...(configPath
+ ? ['--no-conf=false', `--conf-path=${configPath}`]
+ : []),
+ '--enable-dht6=false',
+ '--bt-enable-lpd=false',
+ '--seed-ratio=0',
+ '--force-save=true',
+ `--save-session=${path.join(directory, 'session.txt')}`,
+ ...(inputSession
+ ? [`--input-file=${path.join(directory, 'session.txt')}`]
+ : []),
+ ],
+ })
+ wired = await connectAdapter(handle)
+ adapter = new Aria2Adapter(wired.rpc, undefined, () => defaults)
+ await adapter.connect()
+ }
+ async function stop() {
+ adapter?.dispose()
+ wired?.adapter.dispose()
+ wired?.disconnect()
+ await handle?.kill()
+ }
+ beforeEach(async () => {
+ directory = await mkdtemp(path.join(tmpdir(), 'motrix-seeding-policy-'))
+ defaults = { seedTime: 0, seedRatio: 0 }
+ await writeFile(path.join(directory, 'payload.bin'), payload)
+ await start()
+ })
+ afterEach(async () => {
+ await stop()
+ await rm(directory, { recursive: true, force: true })
+ })
+ async function add(overrides: Partial<SeedingDefaults> = {}) {
+ return adapter.addTorrent({
+ metadata,
+ saveDir: directory,
+ btSeedUnverified: true,
+ ...overrides,
+ })
+ }
+ async function expectStatus(gid: string, status: TaskStatus) {
+ await expect
+ .poll(async () => (await adapter.getTaskStatus(gid))?.status, {
+ timeout: 5000,
+ })
+ .toBe(status)
+ }
+ async function expectKeepsSeeding(gid: string) {
+ await expectStatus(gid, TaskStatus.Seeding)
+ // The broken zero/empty timer retires on the next engine tick.
+ await delay(1500)
+ expect((await adapter.getTaskStatus(gid))?.status).toBe(
+ TaskStatus.Seeding
+ )
+ expect(await adapter.getEngineTaskOptions(gid)).not.toHaveProperty(
+ 'seed-time'
+ )
+ }
+
+ it.each([0, 1])(
+ 'zero time continues seeding with ratio %s',
+ async (seedRatio) => {
+ defaults.seedRatio = seedRatio
+ await expectKeepsSeeding(await add())
+ }
+ )
+ it('positive time ends seeding even when ratio is unlimited', async () => {
+ defaults.seedTime = 0.02
+ await expectStatus(await add(), TaskStatus.Completed)
+ })
+ it('hot defaults apply to the next seeding session without leaving a global timer', async () => {
+ defaults.seedTime = 60
+ const previous = await add()
+ await expectStatus(previous, TaskStatus.Seeding)
+ expect(await adapter.getEngineTaskOptions(previous)).toHaveProperty(
+ 'seed-time',
+ '60'
+ )
+ await adapter.forceRemoveTask(previous)
+ await expectStatus(previous, TaskStatus.Completed)
+ await adapter.removeDownloadResult(previous)
+ defaults.seedTime = 0
+ await expectKeepsSeeding(await add())
+ expect(await wired.rpc.getGlobalOption()).not.toHaveProperty('seed-time')
+ }, 15_000)
+ it('an explicit unlimited task overrides finite application defaults', async () => {
+ defaults.seedTime = 60
+ await expectKeepsSeeding(await add({ seedTime: 0 }))
+ })
+ it('advanced global time cannot override unlimited application settings', async () => {
+ await stop()
+ const configPath = path.join(directory, 'aria2.conf')
+ const source = 'seed-time=0\nseed-ratio=2\n'
+ await writeFile(configPath, source)
+ const builder = new Aria2ConfigBuilder(configPath, directory)
+ const runtimeConfig = await builder.ensureUserConfig()
+ await start(false, runtimeConfig)
+ expect(await readFile(configPath, 'utf8')).toBe(source)
+ expect(await wired.rpc.getGlobalOption()).not.toHaveProperty('seed-time')
+ await expectKeepsSeeding(await add())
+ }, 15_000)
+ it('unlimited seeding survives pause, resume and text-session restart', async () => {
+ const gid = await add()
+ await expectStatus(gid, TaskStatus.Seeding)
+ await adapter.pauseTask(gid)
+ await expectStatus(gid, TaskStatus.Paused)
+ await adapter.resumeTask(gid)
+ await expectStatus(gid, TaskStatus.Seeding)
+ await wired.rpc.saveSession()
+ expect(
+ await readFile(path.join(directory, 'session.txt'), 'utf8')
+ ).not.toContain('seed-time=')
+ await stop()
+ await start(true)
+ await expectKeepsSeeding(gid)
+ }, 15_000)
+ }
+)
diff --git a/src/core/engine/aria2/translate.ts b/src/core/engine/aria2/translate.ts
index 92354633..8d8b6194 100644
--- a/src/core/engine/aria2/translate.ts
+++ b/src/core/engine/aria2/translate.ts
@@ -20,6 +20,7 @@ import {
TaskType,
TransitionPhase,
} from '@shared/types/task'
+import { shareRatio } from '@shared/utils/share-ratio'
import peerid from 'bittorrent-peerid'
import type {
Aria2RawFile,
@@ -211,10 +212,7 @@ export function translateBtExtension(
return {
peers: Number(raw.connections) || 0,
seeds: Number(raw.numSeeders) || 0,
- ratio:
- Number(raw.completedLength) > 0
- ? Number(raw.uploadLength) / Number(raw.completedLength)
- : 0,
+ ratio: shareRatio(Number(raw.uploadLength), Number(raw.totalLength)),
trackers: (raw.bittorrent.announceList ?? []).flat(),
selectedFiles: (raw.files ?? [])
.filter((f) => f.selected === 'true')
diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.ts
index 7c75e2ce..792805d1 100644
--- a/src/core/engine/engine-adapter.ts
+++ b/src/core/engine/engine-adapter.ts
@@ -58,6 +58,7 @@ export interface AddTorrentParams {
outputFilePaths?: OutputFilePath[]
/** Trusted absolute payload root, independent of the engine metadata directory. */
outputRoot?: string
+ /** Seeding minutes; zero disables the time limit. Omitted uses current defaults. */
seedTime?: number
seedRatio?: number
btSeedUnverified?: boolean
@@ -278,6 +279,8 @@ export interface EngineAdapter {
* Used by TaskRecoveryService to match persisted tasks to aria2 state.
*/
listActiveAndWaiting(): Promise<Array<{ gid: string; infoHash?: string }>>
+ /** Engine task IDs in scheduling order, including paused waiting tasks. */
+ listWaitingTaskIds(): Promise<string[]>
/**
* List all stopped (completed/errored/removed) tasks.
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index 67cf681e..f6da8a02 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -1590,6 +1590,21 @@ describe('EngineSupervisor', () => {
})
describe('applyEngineSettings', () => {
+ it('never installs a global seeding timer during hot updates', async () => {
+ await supervisor.start('/usr/bin/aria2c')
+ vi.mocked(rpcClient.changeGlobalOption).mockClear()
+ const previous = settings.getEngine()
+ await supervisor.applyEngineSettings(previous, {
+ ...previous,
+ seedTime: 0,
+ })
+ await supervisor.applyEngineSettings(
+ { ...previous, seedTime: 0 },
+ { ...previous, seedTime: 90 }
+ )
+ expect(rpcClient.changeGlobalOption).not.toHaveBeenCalled()
+ })
+
it('is a no-op unless Ready', async () => {
const previous = settings.getEngine()
await supervisor.applyEngineSettings(previous, {
diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.ts
index ddf3c146..8cbb3c9f 100644
--- a/src/core/engine/engine-supervisor.ts
+++ b/src/core/engine/engine-supervisor.ts
@@ -80,7 +80,6 @@ const HOT_ENGINE_OPTIONS = {
btMaxPeers: 'bt-max-peers',
btEnableLpd: 'bt-enable-lpd',
seedRatio: 'seed-ratio',
- seedTime: 'seed-time',
remoteTime: 'remote-time',
} as const satisfies Partial<Record<keyof EngineSettings, string>>
diff --git a/src/core/inspector-activity/task-inspector-activity-service.test.ts b/src/core/inspector-activity/task-inspector-activity-service.test.ts
index c7860d8e..957d7e0c 100644
--- a/src/core/inspector-activity/task-inspector-activity-service.test.ts
+++ b/src/core/inspector-activity/task-inspector-activity-service.test.ts
@@ -878,3 +878,31 @@ describe('TaskInspectorActivityService', () => {
expect(ctx.store.batches.at(-1)?.[0].samples.length).toBeLessThanOrEqual(64)
})
})
+
+it('counts only observed seeding intervals across pauses and disconnects', () => {
+ const ctx = setup()
+ const sample = (status: TaskStatus) =>
+ ctx.service.recordSamples([ctx.sample({ status })])
+ sample(TaskStatus.Downloading)
+ ctx.advance(1000)
+ sample(TaskStatus.Downloading)
+ sample(TaskStatus.Seeding)
+ ctx.advance(1000)
+ sample(TaskStatus.Seeding)
+ sample(TaskStatus.Paused)
+ ctx.advance(1000)
+ sample(TaskStatus.Paused)
+ sample(TaskStatus.Seeding)
+ ctx.advance(1000)
+ sample(TaskStatus.Seeding)
+ ctx.service.markDisconnected()
+ ctx.advance(60_000)
+ sample(TaskStatus.Seeding)
+ ctx.advance(1000)
+ sample(TaskStatus.Seeding)
+ ctx.service.forceCheckpoint('task-1')
+ const recorded = ctx.store.batches
+ .flat()
+ .reduce((sum, checkpoint) => sum + (checkpoint.seedingMsDelta ?? 0), 0)
+ expect(recorded).toBe(3000)
+})
diff --git a/src/core/inspector-activity/task-inspector-activity-service.ts b/src/core/inspector-activity/task-inspector-activity-service.ts
index dff04225..5aeba82d 100644
--- a/src/core/inspector-activity/task-inspector-activity-service.ts
+++ b/src/core/inspector-activity/task-inspector-activity-service.ts
@@ -100,6 +100,8 @@ interface IntegrationState {
ordinaryCandidate: TaskTransferSample | null
activeMsDelta: number
downloadActiveMsDelta: number
+ seedingMsDelta: number
+ seedingUsRemainder: bigint
activeUsRemainder: bigint
downloadActiveUsRemainder: bigint
downloadBytesDelta: bigint
@@ -563,6 +565,15 @@ export class TaskInspectorActivityService {
)
if (elapsedUs <= 0n) return
+ if (
+ start.status === TaskStatus.Seeding &&
+ end.status === TaskStatus.Seeding
+ ) {
+ const seedingTotal = state.seedingUsRemainder + elapsedUs
+ state.seedingMsDelta += Number(seedingTotal / 1_000n)
+ state.seedingUsRemainder = seedingTotal % 1_000n
+ }
+
if (ACTIVE_STATUSES.has(start.status) && ACTIVE_STATUSES.has(end.status)) {
const activeTotal = state.activeUsRemainder + elapsedUs
state.activeMsDelta += Number(activeTotal / 1_000n)
@@ -852,6 +863,8 @@ export class TaskInspectorActivityService {
ordinaryCandidate: null,
activeMsDelta: 0,
downloadActiveMsDelta: 0,
+ seedingMsDelta: 0,
+ seedingUsRemainder: 0n,
activeUsRemainder: 0n,
downloadActiveUsRemainder: 0n,
downloadBytesDelta: 0n,
@@ -978,6 +991,7 @@ export class TaskInspectorActivityService {
updatedAt: Math.max(state.latestPersistedWall, observedUpdatedAt),
activeMsDelta: state.activeMsDelta,
downloadActiveMsDelta: state.downloadActiveMsDelta,
+ seedingMsDelta: state.seedingMsDelta,
estimatedDownloadBytesDelta: state.downloadBytesDelta,
estimatedUploadBytesDelta: state.uploadBytesDelta,
peakDownloadBps: state.peakDownloadBps,
@@ -1003,6 +1017,7 @@ export class TaskInspectorActivityService {
state.uploadBytesDelta = 0n
state.activeMsDelta = 0
state.downloadActiveMsDelta = 0
+ state.seedingMsDelta = 0
state.rawSampleCountDelta = 0
state.coverageGapAt = null
if (committedCoverageGapCandidate) {
@@ -1038,6 +1053,7 @@ export class TaskInspectorActivityService {
return (
state.activeMsDelta > 0 ||
state.downloadActiveMsDelta > 0 ||
+ state.seedingMsDelta > 0 ||
state.downloadBytesDelta > 0n ||
state.uploadBytesDelta > 0n ||
state.coverageGapAt !== null ||
diff --git a/src/core/inspector-activity/task-inspector-activity-store.test.ts b/src/core/inspector-activity/task-inspector-activity-store.test.ts
index 4247d83e..d3d29052 100644
--- a/src/core/inspector-activity/task-inspector-activity-store.test.ts
+++ b/src/core/inspector-activity/task-inspector-activity-store.test.ts
@@ -434,3 +434,23 @@ describe('TaskInspectorActivityStore', () => {
db.close()
})
})
+
+it('persists seeding time independently and accumulates it after reopening', () => {
+ const db = database()
+ insertParent(db, 'seed')
+ const first = new TaskInspectorActivityStore(db)
+ first.ensureTask('seed', 100)
+ first.checkpointBatch([checkpoint('seed', 2000, { seedingMsDelta: 1500 })])
+ const reopened = new TaskInspectorActivityStore(db)
+ reopened.ensureTask('seed', 2500)
+ reopened.checkpointBatch([checkpoint('seed', 3000, { seedingMsDelta: 500 })])
+ expect(reopened.snapshot('seed')?.summary.seeding).toEqual({
+ activeMs: 2000,
+ trackingStartedAt: 100,
+ })
+ db.prepare('DELETE FROM tasks WHERE motrix_id = ?').run('seed')
+ expect(
+ db.prepare('SELECT COUNT(*) AS n FROM task_seeding_activity').get()
+ ).toEqual({ n: 0 })
+ db.close()
+})
diff --git a/src/core/inspector-activity/task-inspector-activity-store.ts b/src/core/inspector-activity/task-inspector-activity-store.ts
index 4d64b0e2..d032df31 100644
--- a/src/core/inspector-activity/task-inspector-activity-store.ts
+++ b/src/core/inspector-activity/task-inspector-activity-store.ts
@@ -41,6 +41,8 @@ interface SummaryRow {
last_event_ordinal: bigint
active_ms: bigint
download_active_ms: bigint
+ seeding_ms: bigint | null
+ seeding_tracking_started_at: bigint | null
estimated_download_bytes: bigint
estimated_upload_bytes: bigint
peak_download_bps: bigint
@@ -59,6 +61,7 @@ interface Summary {
lastEventOrdinal: number
activeMs: number
downloadActiveMs: number
+ seeding: TaskInspectorActivitySnapshot['summary']['seeding']
estimatedDownloadBytes: bigint
estimatedUploadBytes: bigint
peakDownloadBps: number
@@ -107,6 +110,8 @@ const READ_SUMMARY_SQL = `
last_event_ordinal,
active_ms,
download_active_ms,
+ (SELECT seeding_ms FROM task_seeding_activity WHERE motrix_id = task_inspector_activity.motrix_id) AS seeding_ms,
+ (SELECT tracking_started_at FROM task_seeding_activity WHERE motrix_id = task_inspector_activity.motrix_id) AS seeding_tracking_started_at,
estimated_download_bytes,
estimated_upload_bytes,
peak_download_bps,
@@ -209,6 +214,11 @@ export class TaskInspectorActivityStore {
) VALUES (?, ?, ?)
ON CONFLICT(motrix_id) DO NOTHING`
).run(normalizedTaskId, BigInt(now), BigInt(now))
+ this.prepared(`INSERT INTO task_seeding_activity (motrix_id, tracking_started_at)
+ VALUES (?, ?) ON CONFLICT(motrix_id) DO NOTHING`).run(
+ normalizedTaskId,
+ BigInt(now)
+ )
}
checkpointBatch(
@@ -287,6 +297,7 @@ export class TaskInspectorActivityStore {
lastEventOrdinal: summary.lastEventOrdinal,
activeMs: summary.activeMs,
downloadActiveMs: summary.downloadActiveMs,
+ seeding: summary.seeding,
estimatedDownloadBytes: summary.estimatedDownloadBytes.toString(),
estimatedUploadBytes: summary.estimatedUploadBytes.toString(),
peakDownloadBps: summary.peakDownloadBps,
@@ -337,6 +348,10 @@ export class TaskInspectorActivityStore {
summary.activeMs,
input.activeMsDelta
)
+ const seedingMs = saturatingAddSafeInteger(
+ summary.seeding?.activeMs ?? 0,
+ input.seedingMsDelta ?? 0
+ )
const downloadActiveMs = saturatingAddSafeInteger(
summary.downloadActiveMs,
input.downloadActiveMsDelta
@@ -360,6 +375,7 @@ export class TaskInspectorActivityStore {
const saturated =
activeMs.saturated ||
+ seedingMs.saturated ||
downloadActiveMs.saturated ||
estimatedDownloadBytes.saturated ||
estimatedUploadBytes.saturated ||
@@ -436,6 +452,13 @@ export class TaskInspectorActivityStore {
}
}
+ if (summary.seeding) {
+ const seeded = this.prepared(
+ 'UPDATE task_seeding_activity SET seeding_ms = ? WHERE motrix_id = ?'
+ ).run(BigInt(seedingMs.value), input.taskId)
+ if (seeded.changes !== 1)
+ throw new Error('Task seeding activity disappeared')
+ }
const updated = this.prepared(
`UPDATE task_inspector_activity
SET
@@ -723,6 +746,19 @@ export class TaskInspectorActivityStore {
'last_event_ordinal'
),
activeMs: nonNegativeIntegerFromBigInt(row.active_ms, 'active_ms'),
+ seeding:
+ row.seeding_ms === null || row.seeding_tracking_started_at === null
+ ? null
+ : {
+ activeMs: nonNegativeIntegerFromBigInt(
+ row.seeding_ms,
+ 'seeding_ms'
+ ),
+ trackingStartedAt: safeIntegerFromSql(
+ row.seeding_tracking_started_at,
+ 'seeding_tracking_started_at'
+ ),
+ },
downloadActiveMs: nonNegativeIntegerFromBigInt(
row.download_active_ms,
'download_active_ms'
diff --git a/src/core/inspector-activity/validators.ts b/src/core/inspector-activity/validators.ts
index 815d7fde..322e55b1 100644
--- a/src/core/inspector-activity/validators.ts
+++ b/src/core/inspector-activity/validators.ts
@@ -272,6 +272,8 @@ export function validateCheckpoint(
const taskId = assertTaskId(input.taskId)
assertPositiveSafeInteger(input.updatedAt, 'updatedAt')
assertNonNegativeSafeInteger(input.activeMsDelta, 'activeMsDelta')
+ if (input.seedingMsDelta !== undefined)
+ assertNonNegativeSafeInteger(input.seedingMsDelta, 'seedingMsDelta')
assertNonNegativeSafeInteger(
input.downloadActiveMsDelta,
'downloadActiveMsDelta'
diff --git a/src/core/session/migrations/index.ts b/src/core/session/migrations/index.ts
index cf25da44..7e9bc772 100644
--- a/src/core/session/migrations/index.ts
+++ b/src/core/session/migrations/index.ts
@@ -9,6 +9,7 @@ import { V2_TASK_SCHEMA_OBJECTS, v2 } from './v2'
import { V3_SCHEMA_OBJECTS, v3 } from './v3'
import { V4_SCHEMA_OBJECTS, v4 } from './v4'
import { V5_TASK_SCHEMA_OBJECTS, v5 } from './v5'
+import { V6_SCHEMA_OBJECTS, v6 } from './v6'
interface Migration {
version: number
@@ -23,8 +24,9 @@ interface Migration {
// "Fetching"). v3 adds task-owned Inspector Activity persistence. v4 adds
// durable plugin finalize journals plus post-delivery and quota state. v5
// persists the user-selected save directory independently of engine paths and
-// repairs stale instance statuses beneath terminal tasks.
-const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5]
+// repairs stale instance statuses beneath terminal tasks. v6 adds independent
+// seeding-time counters without inventing pre-upgrade history.
+const MIGRATIONS: Migration[] = [v1, v2, v3, v4, v5, v6]
const HIGHEST_KNOWN_VERSION = MIGRATIONS.reduce(
(max, m) => (m.version > max ? m.version : max),
@@ -279,6 +281,15 @@ function validateCanonicalTaskAndActivitySchema(db: Database.Database): void {
}
function validateCanonicalSchema(db: Database.Database): void {
+ if (
+ !hasExactSchemaObjects(db, V6_SCHEMA_OBJECTS) ||
+ !hasNoExplicitIndexesOrTriggers(db, ['task_seeding_activity'])
+ ) {
+ throw new StaleSchemaError(
+ 'inspector_activity_schema_missing',
+ (db as unknown as { name: string }).name
+ )
+ }
validateCanonicalTaskAndActivitySchema(db)
if (!hasExactSchemaObjects(db, V4_SCHEMA_OBJECTS)) {
throw new StaleSchemaError(
diff --git a/src/core/session/migrations/v1.test.ts b/src/core/session/migrations/v1.test.ts
index 7e707911..29c9e875 100644
--- a/src/core/session/migrations/v1.test.ts
+++ b/src/core/session/migrations/v1.test.ts
@@ -458,7 +458,7 @@ describe('migration v1 (final schema)', () => {
})
describe('migrate() schema guard (Codex finding #7)', () => {
- it('fails fast with SchemaVersionTooNewError when schema_version > 1', async () => {
+ it('fails fast with SchemaVersionTooNewError when schema_version exceeds the supported version', async () => {
const { migrate, SchemaVersionTooNewError } = await import('.')
const db = new Database(':memory:')
db.pragma('foreign_keys = ON')
@@ -468,7 +468,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {
version INTEGER PRIMARY KEY,
applied_at INTEGER NOT NULL
);
- INSERT INTO schema_version (version, applied_at) VALUES (6, 0);
+ INSERT INTO schema_version (version, applied_at) VALUES (7, 0);
CREATE TABLE task_metadata (motrix_id TEXT PRIMARY KEY);
`)
@@ -524,7 +524,7 @@ describe('migrate() schema guard (Codex finding #7)', () => {
const rows = db
.prepare('SELECT version FROM schema_version ORDER BY version')
.all() as Array<{ version: number }>
- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5])
+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6])
db.close()
})
@@ -541,8 +541,9 @@ describe('migrate() schema guard (Codex finding #7)', () => {
.all() as Array<{ version: number }>
// v1 is the Plan A baseline, v2 widens task statuses, v3 adds task-owned
// Inspector Activity persistence, and v4 adds durable Hook delivery and
- // finalize journals. All apply on a fresh DB.
- expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5])
+ // finalize journals. V5 repairs terminal instances and v6 tracks seeding time.
+ // All apply on a fresh DB.
+ expect(rows.map((r) => r.version)).toEqual([1, 2, 3, 4, 5, 6])
const tables = db
.prepare("SELECT name FROM sqlite_master WHERE type='table'")
diff --git a/src/core/session/migrations/v3.test.ts b/src/core/session/migrations/v3.test.ts
index c974adc8..0c1e557c 100644
--- a/src/core/session/migrations/v3.test.ts
+++ b/src/core/session/migrations/v3.test.ts
@@ -110,7 +110,7 @@ describe('migration v3 compatibility', () => {
const db = openMemory()
migrate(db)
- expect(readVersion(db)).toBe(5)
+ expect(readVersion(db)).toBe(6)
const names = db
.prepare(
`SELECT name FROM sqlite_master
@@ -166,7 +166,7 @@ describe('migration v3 compatibility', () => {
const reopened = new Database(dbPath)
reopened.pragma('foreign_keys = ON')
- expect(readVersion(reopened)).toBe(5)
+ expect(readVersion(reopened)).toBe(6)
expect(
reopened
.prepare("SELECT motrix_id FROM tasks WHERE motrix_id = 'survivor'")
@@ -207,7 +207,7 @@ describe('migration v3 compatibility', () => {
})()
expect(() => migrate(db)).not.toThrow()
- expect(readVersion(db)).toBe(5)
+ expect(readVersion(db)).toBe(6)
db.close()
})
diff --git a/src/core/session/migrations/v4.test.ts b/src/core/session/migrations/v4.test.ts
index 64e8f699..68eaf7df 100644
--- a/src/core/session/migrations/v4.test.ts
+++ b/src/core/session/migrations/v4.test.ts
@@ -40,7 +40,7 @@ describe('migration v4', () => {
const db = openMemory()
migrate(db)
- expect(readVersion(db)).toBe(5)
+ expect(readVersion(db)).toBe(6)
const rows = db
.prepare(
`SELECT name FROM sqlite_master
@@ -68,7 +68,7 @@ describe('migration v4', () => {
migrate(db)
- expect(readVersion(db)).toBe(5)
+ expect(readVersion(db)).toBe(6)
expect(
db.prepare("SELECT name FROM tasks WHERE motrix_id = 'survivor'").get()
).toEqual({ name: 'fixture' })
diff --git a/src/core/session/migrations/v5.test.ts b/src/core/session/migrations/v5.test.ts
index b57b419b..714bca52 100644
--- a/src/core/session/migrations/v5.test.ts
+++ b/src/core/session/migrations/v5.test.ts
@@ -111,7 +111,7 @@ describe('task recovery migration v5', () => {
expect(db.prepare('SELECT total_changes() AS count').get()).toEqual(changes)
expect(
db.prepare('SELECT version FROM schema_version ORDER BY version').all()
- ).toEqual([1, 2, 3, 4, 5].map((version) => ({ version })))
+ ).toEqual([1, 2, 3, 4, 5, 6].map((version) => ({ version })))
db.close()
})
})
diff --git a/src/core/session/migrations/v6.test.ts b/src/core/session/migrations/v6.test.ts
new file mode 100644
index 00000000..d42fcca4
--- /dev/null
+++ b/src/core/session/migrations/v6.test.ts
@@ -0,0 +1,46 @@
+import Database from 'better-sqlite3'
+import { describe, expect, it } from 'vitest'
+import { TaskInspectorActivityStore } from '../../inspector-activity/task-inspector-activity-store'
+import { migrate } from '.'
+import { v1 } from './v1'
+import { v2 } from './v2'
+import { v3 } from './v3'
+import { v4 } from './v4'
+import { v5 } from './v5'
+
+describe('seeding activity migration v6', () => {
+ it('preserves old activity without inventing historical seeding time', () => {
+ const db = new Database(':memory:')
+ db.pragma('foreign_keys = ON')
+ db.exec(`CREATE TABLE schema_version (
+ version INTEGER PRIMARY KEY,
+ applied_at INTEGER NOT NULL
+ )`)
+ for (const migration of [v1, v2, v3, v4, v5]) {
+ migration.up(db)
+ db.prepare('INSERT INTO schema_version VALUES (?, 1)').run(
+ migration.version
+ )
+ }
+ db.exec(
+ "INSERT INTO tasks (motrix_id,name,task_type,created_at,updated_at) VALUES ('old','file','bt',1,1)"
+ )
+ db.exec(
+ "INSERT INTO task_inspector_activity (motrix_id,tracking_started_at,updated_at,active_ms) VALUES ('old',1,1000,999)"
+ )
+ migrate(db)
+ const store = new TaskInspectorActivityStore(db)
+ expect(store.snapshot('old')?.summary).toMatchObject({
+ activeMs: 999,
+ seeding: null,
+ })
+ store.ensureTask('old', 2000)
+ expect(store.snapshot('old')?.summary.seeding).toEqual({
+ activeMs: 0,
+ trackingStartedAt: 2000,
+ })
+ expect(() => migrate(db)).not.toThrow()
+ expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([])
+ db.close()
+ })
+})
diff --git a/src/core/session/migrations/v6.ts b/src/core/session/migrations/v6.ts
new file mode 100644
index 00000000..0e908856
--- /dev/null
+++ b/src/core/session/migrations/v6.ts
@@ -0,0 +1,25 @@
+import type Database from 'better-sqlite3'
+import type { SchemaObjectDefinition } from './v1'
+
+export const V6_SCHEMA_OBJECTS: readonly SchemaObjectDefinition[] = [
+ {
+ name: 'task_seeding_activity',
+ sql: `CREATE TABLE task_seeding_activity (
+ motrix_id TEXT NOT NULL PRIMARY KEY
+ CHECK (typeof(motrix_id) = 'text' AND length(motrix_id) > 0),
+ tracking_started_at INTEGER NOT NULL
+ CHECK (typeof(tracking_started_at) = 'integer' AND tracking_started_at BETWEEN 1 AND 9007199254740991),
+ seeding_ms INTEGER NOT NULL DEFAULT 0
+ CHECK (typeof(seeding_ms) = 'integer' AND seeding_ms BETWEEN 0 AND 9007199254740991),
+ FOREIGN KEY (motrix_id) REFERENCES tasks(motrix_id) ON DELETE CASCADE
+ ) WITHOUT ROWID`,
+ },
+]
+
+export const v6 = {
+ version: 6,
+ up(db: Database.Database): void {
+ // No historical backfill: activity before this counter existed is unknown.
+ for (const object of V6_SCHEMA_OBJECTS) db.exec(object.sql)
+ },
+}
diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.ts
index 394adfd0..339050ce 100644
--- a/src/core/settings/settings-manager.test.ts
+++ b/src/core/settings/settings-manager.test.ts
@@ -1,3 +1,4 @@
+import { resolveByteUnitSystem } from '@shared/schemas/byte-unit-system'
import type { AppSettings, DashboardTileLayout } from '@shared/types/settings'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CURRENT_SETTINGS_VERSION } from './migrations'
@@ -8,6 +9,7 @@ import {
DEFAULT_DASHBOARD_LAYOUT,
DEFAULT_ENGINE_SETTINGS,
DEFAULT_ONBOARDING_STATE,
+ DEFAULT_SPEED_LIMIT_SETTINGS,
dashboardLayoutSettingsSchema,
} from './validators'
@@ -66,6 +68,98 @@ describe('SettingsManager', () => {
})
describe('load', () => {
+ it.each([
+ ['darwin', 64_000, 512_000],
+ ['win32', 65_536, 524_288],
+ ['linux', 65_536, 524_288],
+ ])(
+ 'persists first-run speed presets for %s only once',
+ async (platform, upload, download) => {
+ const unitSystem = resolveByteUnitSystem('system', platform as string)
+ manager = new SettingsManager(TEST_PATH, {
+ defaultByteUnitSystem: unitSystem,
+ })
+ mockedFs.readFile.mockRejectedValue(new Error('ENOENT'))
+ mockedFs.writeFile.mockResolvedValue(undefined)
+ await manager.load()
+ expect(manager.get().speedLimit).toMatchObject({
+ turtle: 'off',
+ base: { upload: 0, download: 0 },
+ alt: { upload, download },
+ })
+ const saved = JSON.parse(
+ mockedFs.writeFile.mock.calls.at(-1)![1] as string
+ )
+ expect(saved.speedLimit.alt).toEqual({ upload, download })
+ mockedFs.readFile.mockResolvedValue(JSON.stringify(saved))
+ const reloaded = new SettingsManager(TEST_PATH, {
+ defaultByteUnitSystem:
+ unitSystem === 'decimal' ? 'binary' : 'decimal',
+ })
+ await reloaded.load()
+ expect(reloaded.get().speedLimit.alt).toEqual({ upload, download })
+ await reloaded.update({
+ app: {
+ byteUnitSystem: unitSystem === 'decimal' ? 'binary' : 'decimal',
+ },
+ })
+ expect(reloaded.get().speedLimit.alt).toEqual({ upload, download })
+ }
+ )
+
+ it.each(['decimal', 'binary'] as const)(
+ 'uses an explicit %s preference when the speed profile is missing',
+ async (units) => {
+ manager = new SettingsManager(TEST_PATH, {
+ defaultByteUnitSystem: units === 'decimal' ? 'binary' : 'decimal',
+ })
+ mockedFs.readFile.mockResolvedValue(
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { byteUnitSystem: units, defaultSaveDir: '/tmp/downloads' },
+ engine: { rpcSecret: 'kept' },
+ })
+ )
+ await manager.load()
+ expect(manager.get().speedLimit.alt).toEqual(
+ units === 'decimal'
+ ? { upload: 64_000, download: 512_000 }
+ : { upload: 65_536, download: 524_288 }
+ )
+ expect(mockedFs.writeFile).toHaveBeenCalledOnce()
+ }
+ )
+
+ it.each([
+ { upload: 65_536, download: 524_288 },
+ { upload: 123_456, download: 987_654 },
+ { upload: 0, download: 0 },
+ ])(
+ 'preserves stored limits $upload/$download in decimal mode',
+ async (alt) => {
+ manager = new SettingsManager(TEST_PATH, {
+ defaultByteUnitSystem: 'decimal',
+ })
+ mockedFs.readFile.mockResolvedValue(
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { byteUnitSystem: 'decimal' },
+ speedLimit: {
+ turtle: 'on',
+ base: { upload: 10, download: 20 },
+ alt,
+ },
+ })
+ )
+ await manager.load()
+ expect(manager.get().speedLimit).toMatchObject({
+ turtle: 'on',
+ base: { upload: 10, download: 20 },
+ alt,
+ })
+ }
+ )
+
it('uses defaults when file does not exist', async () => {
mockedFs.readFile.mockRejectedValue(
Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
@@ -129,6 +223,7 @@ describe('SettingsManager', () => {
mockedFs.readFile.mockResolvedValue(
JSON.stringify({
version: CURRENT_SETTINGS_VERSION,
+ speedLimit: DEFAULT_SPEED_LIMIT_SETTINGS,
engine: { ...DEFAULT_ENGINE_SETTINGS, rpcSecret: 'saved-secret' },
app,
plugins: {},
@@ -167,6 +262,7 @@ describe('SettingsManager', () => {
mockedFs.readFile.mockResolvedValue(
JSON.stringify({
version: CURRENT_SETTINGS_VERSION,
+ speedLimit: DEFAULT_SPEED_LIMIT_SETTINGS,
engine: { ...DEFAULT_ENGINE_SETTINGS, rpcSecret: 'saved-secret' },
app: {
...DEFAULT_APP_SETTINGS,
@@ -1109,6 +1205,7 @@ describe('SettingsManager', () => {
it('preserves an explicitly persisted empty rpcSecret after load', async () => {
const fileContent = JSON.stringify({
version: CURRENT_SETTINGS_VERSION,
+ speedLimit: DEFAULT_SPEED_LIMIT_SETTINGS,
engine: { rpcSecret: '' },
app: { defaultSaveDir: '/downloads' },
})
diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.ts
index ea4a2cac..d9f0d1ee 100644
--- a/src/core/settings/settings-manager.ts
+++ b/src/core/settings/settings-manager.ts
@@ -12,10 +12,12 @@ import {
bridgeSettingsSchema,
DEFAULT_BRIDGE_SETTINGS,
} from '@shared/schemas/bridge-settings'
+import type { ByteUnitSystem } from '@shared/schemas/byte-unit-system'
import {
DEFAULT_PROXY_SETTINGS,
proxySettingsSchema,
} from '@shared/schemas/proxy-settings'
+import { createDefaultSpeedLimitSettings } from '@shared/schemas/speed-limit'
import type { GeoIPSettings } from '@shared/types/geoip'
import type {
AppSettings,
@@ -39,7 +41,6 @@ import {
DEFAULT_MEDIA_SETTINGS,
DEFAULT_NAT_SETTINGS,
DEFAULT_ONBOARDING_STATE,
- DEFAULT_SPEED_LIMIT_SETTINGS,
DEFAULT_TRACKER_SETTINGS,
geoIpSettingsSchema,
mediaSettingsSchema,
@@ -107,7 +108,8 @@ function deepMergeSpeedLimit(
}
function createDefaultSettings(
- liquidGlassEffectDefault = DEFAULT_APP_SETTINGS.liquidGlassEffect
+ liquidGlassEffectDefault: boolean,
+ byteUnitSystem: ByteUnitSystem
): AppSettings {
return {
version: CURRENT_SETTINGS_VERSION,
@@ -124,7 +126,7 @@ function createDefaultSettings(
geoip: { ...DEFAULT_GEOIP_SETTINGS },
media: { ...DEFAULT_MEDIA_SETTINGS },
dashboard: validateDashboardLayoutSettings({} as DashboardLayoutSettings),
- speedLimit: { ...DEFAULT_SPEED_LIMIT_SETTINGS },
+ speedLimit: createDefaultSpeedLimitSettings(byteUnitSystem),
// Fresh install: mint a real, durable instance id now rather than
// persisting the '' sentinel. Unlike rpcSecret/defaultSaveDir (seeded
// later by seedSentinels using instance-scoped defaults), the UUID
@@ -145,6 +147,8 @@ export interface SettingsManagerOptions {
defaultSaveDir?: string
isLegacyDefaultSaveDir?: (value: string) => boolean
liquidGlassEffectDefault?: boolean
+ /** Host-selected units used only when seeding a missing speed-limit profile. */
+ defaultByteUnitSystem?: ByteUnitSystem
onChange?: (old: AppSettings, updated: AppSettings) => void
}
@@ -153,6 +157,7 @@ export class SettingsManager {
private readonly defaultSaveDir: string
private readonly isLegacyDefaultSaveDir?: (value: string) => boolean
private readonly liquidGlassEffectDefault: boolean
+ private readonly defaultByteUnitSystem: ByteUnitSystem
private readonly onChange?: (old: AppSettings, updated: AppSettings) => void
// Keep durable writes, in-memory commits, and change notifications in the
// same order across every settings mutation entry point.
@@ -164,7 +169,11 @@ export class SettingsManager {
) {
this.liquidGlassEffectDefault =
opts?.liquidGlassEffectDefault ?? DEFAULT_APP_SETTINGS.liquidGlassEffect
- this.settings = createDefaultSettings(this.liquidGlassEffectDefault)
+ this.defaultByteUnitSystem = opts?.defaultByteUnitSystem ?? 'binary'
+ this.settings = createDefaultSettings(
+ this.liquidGlassEffectDefault,
+ this.defaultByteUnitSystem
+ )
this.defaultSaveDir =
opts?.defaultSaveDir ?? path.join(os.homedir(), 'Downloads')
if (!path.isAbsolute(this.defaultSaveDir)) {
@@ -177,6 +186,7 @@ export class SettingsManager {
async load(): Promise<void> {
let parsed: Record<string, unknown>
let seedMissingRpcSecret = true
+ let seedMissingSpeedLimit = false
try {
const raw = await readFile(this.filePath, 'utf-8')
@@ -190,10 +200,14 @@ export class SettingsManager {
// a missing or invalid field keeps the secure generated first-run
// default. Check presence after migration so legacy shapes participate.
seedMissingRpcSecret = !hasPersistedRpcSecret(migrated)
+ seedMissingSpeedLimit = migrated.speedLimit == null
this.settings = this.buildValidSettings(migrated as Partial<AppSettings>)
} catch {
// File missing, corrupt, or unreadable — use defaults
- this.settings = createDefaultSettings(this.liquidGlassEffectDefault)
+ this.settings = createDefaultSettings(
+ this.liquidGlassEffectDefault,
+ this.defaultByteUnitSystem
+ )
this.seedSentinels(true)
await this.save()
return
@@ -206,7 +220,7 @@ export class SettingsManager {
const seeded = this.seedSentinels(seedMissingRpcSecret)
const versionStale =
!parsed.version || parsed.version !== CURRENT_SETTINGS_VERSION
- if (seeded || versionStale) {
+ if (seeded || seedMissingSpeedLimit || versionStale) {
await this.save()
}
}
@@ -567,10 +581,11 @@ export class SettingsManager {
}
}
+ const app = validateAppSettings(appInput as MotrixAppSettings)
return {
version: CURRENT_SETTINGS_VERSION,
engine: validateEngineSettings((raw.engine ?? {}) as EngineSettings),
- app: validateAppSettings(appInput as MotrixAppSettings),
+ app,
onboarding: onboardingStateSchema.parse(raw.onboarding ?? {}),
nat: validateNatSettings((raw.nat ?? {}) as NatSettings),
proxy: proxySettingsSchema.parse({
@@ -584,9 +599,14 @@ export class SettingsManager {
dashboard: validateDashboardLayoutSettings(
(raw.dashboard ?? {}) as DashboardLayoutSettings
),
- speedLimit: validateSpeedLimitSettings(
- (raw.speedLimit ?? {}) as SpeedLimitSettings
- ),
+ speedLimit:
+ raw.speedLimit == null
+ ? createDefaultSpeedLimitSettings(
+ app.byteUnitSystem === 'system'
+ ? this.defaultByteUnitSystem
+ : app.byteUnitSystem
+ )
+ : validateSpeedLimitSettings(raw.speedLimit),
bridge: bridgeSettingsSchema.parse((raw.bridge ?? {}) as BridgeSettings),
windowState: windowStateSchema.parse(raw.windowState ?? {}),
}
diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.ts
index d9d24ab9..28bd05bb 100644
--- a/src/core/task/actions/finalize-task.test.ts
+++ b/src/core/task/actions/finalize-task.test.ts
@@ -1298,7 +1298,7 @@ describe('finalizeTask BT branch', () => {
expect(task.status).toBe(TaskStatus.Seeding)
})
- it('status=Completed when both seedTime and seedRatio are 0', async () => {
+ it('seeds without either limit when both seedTime and seedRatio are 0', async () => {
const deps = makeDeps()
;(deps.settings.get as ReturnType<typeof vi.fn>).mockReturnValue({
bt: { seedTime: 0, seedRatio: 0 },
@@ -1310,7 +1310,10 @@ describe('finalizeTask BT branch', () => {
await finalizeTask('t1', deps)
- expect(task.status).toBe(TaskStatus.Completed)
+ expect(task.status).toBe(TaskStatus.Seeding)
+ expect(deps.adapter.addTorrent).toHaveBeenCalledWith(
+ expect.objectContaining({ seedTime: 0, seedRatio: 0 })
+ )
})
it('addTorrent failure → status=Completed + soft warning', async () => {
@@ -1400,7 +1403,7 @@ describe('finalizeTask BT branch', () => {
expect(task.engineTaskId).toBe('gid-1')
})
- it('still reseeds when ratio is met but seedTime is requested (passes seedRatio=0 to ignore ratio)', async () => {
+ it('stops when the ratio is met even with a positive time limit', async () => {
const deps = makeDeps()
;(deps.settings.get as ReturnType<typeof vi.fn>).mockReturnValue({
bt: { seedTime: 30, seedRatio: 1 },
@@ -1415,11 +1418,8 @@ describe('finalizeTask BT branch', () => {
await finalizeTask('t1', deps)
- const call = (deps.adapter.addTorrent as ReturnType<typeof vi.fn>).mock
- .calls[0][0]
- expect(call.seedRatio).toBe(0)
- expect(call.seedTime).toBe(30)
- expect(task.status).toBe(TaskStatus.Seeding)
+ expect(deps.adapter.addTorrent).not.toHaveBeenCalled()
+ expect(task.status).toBe(TaskStatus.Completed)
})
it('does not subtract when totalBytes is 0 (degenerate metadata)', async () => {
@@ -1765,13 +1765,14 @@ describe('finalizeTask completion-metrics sync', () => {
expect(task.progress).toBe(0)
})
- it('BT skip-reseed (ratio=0, time=0): progress reaches 1 at Completed', async () => {
+ it('BT skip-reseed (ratio reached): progress reaches 1 at Completed', async () => {
const deps = makeDeps()
;(deps.settings.get as ReturnType<typeof vi.fn>).mockReturnValue({
- bt: { seedTime: 0, seedRatio: 0 },
+ bt: { seedTime: 0, seedRatio: 1 },
})
const task = makeBtTask({
totalBytes: 1_000_000_000,
+ uploadedBytesBaseline: 1_000_000_000,
downloadedBytes: 999_998_976,
progress: 0.999998976,
})
@@ -2280,9 +2281,9 @@ describe('finalizeTask plugin-hook chain (Plan C / T15)', () => {
auditLog: makeAuditLog(),
}
;(deps.settings.get as ReturnType<typeof vi.fn>).mockReturnValue({
- bt: { seedTime: 0, seedRatio: 0 },
+ bt: { seedTime: 0, seedRatio: 1 },
})
- const task = makeBtTask()
+ const task = makeBtTask({ totalBytes: 1000, uploadedBytesBaseline: 1000 })
;(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(
task
)
diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.ts
index 8034b0b4..5bbf288f 100644
--- a/src/core/task/actions/finalize-task.ts
+++ b/src/core/task/actions/finalize-task.ts
@@ -730,13 +730,11 @@ async function finalizeBtAfterRename(
bt.seedRatio > 0 ? Math.max(0, bt.seedRatio - alreadyRatio) : 0
const ratioRequested = bt.seedRatio > 0
const ratioSatisfied = ratioRequested && remainingRatio === 0
- const timeRequested = bt.seedTime > 0
// Nothing left to seed: skip the reseed entirely. The file is already
// on disk at finalPath; we just enter Completed. Avoids spinning up
// a new aria2 row that would be torn down on its first poll.
- const shouldSkipReseed =
- (!ratioRequested && !timeRequested) || (ratioSatisfied && !timeRequested)
+ const shouldSkipReseed = ratioSatisfied
if (shouldSkipReseed) {
setTaskTransitionPhase(task, TransitionPhase.Idle)
const previousStatus = task.status
@@ -757,29 +755,10 @@ async function finalizeBtAfterRename(
return
}
- // When the user requested a ratio but it's already met (and time is
- // still pending), tell aria2 to ignore ratio for this gid so only
- // seed-time governs the stop condition. `seed-ratio=0.0` is aria2's
- // documented "ignore ratio" sentinel.
+ // Either enabled limit ends seeding. A zero ratio imposes no ratio limit;
+ // a zero time is translated by the adapter into an absent time condition.
const seedRatioForNewGid = ratioRequested ? remainingRatio : 0
- // Known issue: aria2 treats `seed-time=0` as "don't seed at all",
- // not "seed forever". If the user has time=0 and is here because of
- // a ratio-only request, the new gid will terminate immediately on
- // aria2's side. Surfacing rather than papering over until the
- // seed-time semantic translation lands (next iteration).
- if (!timeRequested && ratioRequested && !ratioSatisfied) {
- deps.log.warn(
- {
- taskId: task.id,
- seedRatio: bt.seedRatio,
- seedTime: bt.seedTime,
- remainingRatio,
- },
- 'finalize_bt_ratio_only_with_zero_seed_time'
- )
- }
-
const completeWithoutSeeding = async (error: unknown): Promise<void> => {
// Soft degradation: download succeeded; seeding didn't start.
// Mark Completed with a warning rather than Error — the user's
diff --git a/src/core/task/actions/move-tasks.integration.test.ts b/src/core/task/actions/move-tasks.integration.test.ts
new file mode 100644
index 00000000..429b6c11
--- /dev/null
+++ b/src/core/task/actions/move-tasks.integration.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment node
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { TaskStatus } from '@shared/types/task'
+import {
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ connectAdapter,
+ spawnAria2ForTest,
+} from '@test-utils/aria2'
+import { makeDownloadTask } from '@test-utils/task'
+import { describe, expect, it, vi } from 'vitest'
+import { moveTasks } from './move-tasks'
+import type { TaskActionDeps } from './shared'
+
+describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
+ 'moveTasks with real aria2',
+ () => {
+ it('moves paused downloads in the scheduling queue in both directions', async () => {
+ const baseDir = await mkdtemp(path.join(tmpdir(), 'motrix-queue-'))
+ const handle = await spawnAria2ForTest({ baseDir })
+ let disconnect: (() => void) | undefined
+ try {
+ const connection = await connectAdapter(handle)
+ disconnect = connection.disconnect
+ const { rpc, adapter } = connection
+ const tasks = new Map()
+ const gids: string[] = []
+ for (const name of ['a', 'b', 'c', 'd']) {
+ // Paused tasks never make a network request.
+ const gid = await rpc.addUri([`http://127.0.0.1/queue-${name}`], {
+ pause: 'true',
+ })
+ gids.push(gid)
+ tasks.set(
+ name,
+ makeDownloadTask({
+ id: name,
+ engineTaskId: gid,
+ status: TaskStatus.Paused,
+ })
+ )
+ }
+ const deps = {
+ adapter,
+ taskManager: { getById: (id: string) => tasks.get(id) },
+ log: { warn: vi.fn() },
+ } as unknown as TaskActionDeps
+ expect(await adapter.listWaitingTaskIds()).toEqual(gids)
+ expect(
+ (await moveTasks({ taskIds: ['c', 'b'], direction: 'up' }, deps))
+ .moved
+ ).toEqual(['b', 'c'])
+ expect(await adapter.listWaitingTaskIds()).toEqual([
+ gids[1],
+ gids[2],
+ gids[0],
+ gids[3],
+ ])
+ await moveTasks({ taskIds: ['b', 'c'], direction: 'down' }, deps)
+ expect(await adapter.listWaitingTaskIds()).toEqual(gids)
+ expect(
+ (await moveTasks({ taskIds: ['a'], direction: 'up' }, deps)).unchanged
+ ).toEqual(['a'])
+ await moveTasks({ taskIds: ['d', 'b'], direction: 'top' }, deps)
+ expect(await adapter.listWaitingTaskIds()).toEqual([
+ gids[1],
+ gids[3],
+ gids[0],
+ gids[2],
+ ])
+ await moveTasks({ taskIds: ['d', 'b'], direction: 'bottom' }, deps)
+ expect(await adapter.listWaitingTaskIds()).toEqual([
+ gids[0],
+ gids[2],
+ gids[1],
+ gids[3],
+ ])
+ } finally {
+ disconnect?.()
+ await handle.kill()
+ await rm(baseDir, { recursive: true, force: true })
+ }
+ }, 20_000)
+ }
+)
diff --git a/src/core/task/actions/move-tasks.test.ts b/src/core/task/actions/move-tasks.test.ts
new file mode 100644
index 00000000..c4dfbaf3
--- /dev/null
+++ b/src/core/task/actions/move-tasks.test.ts
@@ -0,0 +1,165 @@
+import { TaskKind, TaskStatus } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { describe, expect, it, vi } from 'vitest'
+import { moveTasks } from './move-tasks'
+import type { TaskActionDeps } from './shared'
+
+function setup(order = ['a', 'b', 'c', 'd', 'e']) {
+ const queue = [...order]
+ const tasks = new Map(
+ order.map((id) => [
+ id,
+ makeDownloadTask({
+ id,
+ engineTaskId: id,
+ status: TaskStatus.Paused,
+ }),
+ ])
+ )
+ const changePosition = vi.fn(
+ async (id: string, shift: number, how: string) => {
+ const index = queue.indexOf(id)
+ const destination = Math.max(
+ 0,
+ Math.min(queue.length - 1, how === 'POS_SET' ? shift : index + shift)
+ )
+ queue.splice(index, 1)
+ queue.splice(destination, 0, id)
+ return destination
+ }
+ )
+ const listWaitingTaskIds = vi.fn(async () => [...queue])
+ const deps = {
+ adapter: { changePosition, listWaitingTaskIds },
+ taskManager: { getById: (id: string) => tasks.get(id) },
+ log: { warn: vi.fn() },
+ } as unknown as TaskActionDeps
+ return { deps, tasks, queue, changePosition, listWaitingTaskIds }
+}
+
+describe('moveTasks', () => {
+ it.each(['top', 'bottom'] as const)(
+ 'moves every subset to the %s without changing relative order',
+ async (direction) => {
+ const original = ['a', 'b', 'c', 'd', 'e']
+ for (let mask = 1; mask < 32; mask++) {
+ const selected = original.filter((_, index) => mask & (1 << index))
+ const rest = original.filter((id) => !selected.includes(id))
+ const { deps, queue, changePosition } = setup()
+ const expected =
+ direction === 'top' ? [...selected, ...rest] : [...rest, ...selected]
+ const result = await moveTasks(
+ { taskIds: [...selected].reverse(), direction },
+ deps
+ )
+ expect(queue).toEqual(expected)
+ expect(result.failed).toEqual([])
+ expect(
+ changePosition.mock.calls.every((call) => call[2] === 'POS_SET')
+ ).toBe(true)
+ }
+ }
+ )
+
+ it.each(['top', 'bottom'] as const)(
+ 'does not cross a failed selected task when moving to the %s',
+ async (direction) => {
+ const { deps, queue, changePosition } = setup()
+ changePosition.mockRejectedValueOnce(new Error('engine unavailable'))
+ const result = await moveTasks({ taskIds: ['b', 'd'], direction }, deps)
+ expect(queue).toEqual(
+ direction === 'top'
+ ? ['a', 'b', 'd', 'c', 'e']
+ : ['a', 'c', 'b', 'd', 'e']
+ )
+ expect(result.failed).toHaveLength(1)
+ expect(queue.filter((id) => ['b', 'd'].includes(id))).toEqual(['b', 'd'])
+ }
+ )
+ it.each(['up', 'down'] as const)(
+ 'keeps relative order for every subset moving %s',
+ async (direction) => {
+ const original = ['a', 'b', 'c', 'd', 'e']
+ for (let mask = 1; mask < 32; mask++) {
+ const selected = original.filter((_, index) => mask & (1 << index))
+ const { deps, queue } = setup()
+ const expected = [...original]
+ const scan =
+ direction === 'up' ? [...selected] : [...selected].reverse()
+ for (const id of scan) {
+ const index = expected.indexOf(id)
+ const destination = index + (direction === 'up' ? -1 : 1)
+ if (
+ destination < 0 ||
+ destination >= expected.length ||
+ selected.includes(expected[destination])
+ )
+ continue
+ ;[expected[index], expected[destination]] = [
+ expected[destination],
+ expected[index],
+ ]
+ }
+ // Visible column order / click order must have no influence.
+ const result = await moveTasks(
+ { taskIds: [...selected].reverse(), direction },
+ deps
+ )
+ expect(queue).toEqual(expected)
+ expect(queue.filter((id) => selected.includes(id))).toEqual(selected)
+ expect(result.failed).toEqual([])
+ }
+ }
+ )
+
+ it('deduplicates targets and never moves tasks that are active or managed by a coordinator', async () => {
+ const { deps, tasks, queue, changePosition } = setup()
+ tasks.set('a', { ...tasks.get('a')!, status: TaskStatus.Downloading })
+ tasks.set('b', { ...tasks.get('b')!, kind: TaskKind.Hls })
+ const result = await moveTasks(
+ { taskIds: ['a', 'b', 'c', 'c', 'missing'], direction: 'up' },
+ deps
+ )
+ expect(queue).toEqual(['a', 'c', 'b', 'd', 'e'])
+ expect(changePosition).toHaveBeenCalledTimes(1)
+ expect(result.moved).toEqual(['c'])
+ expect(result.failed.map((entry) => entry.taskId)).toEqual([
+ 'a',
+ 'b',
+ 'missing',
+ ])
+ })
+
+ it('does not cross a selected neighbor whose move failed', async () => {
+ const { deps, queue, changePosition } = setup()
+ changePosition.mockRejectedValueOnce(new Error('engine unavailable'))
+ const result = await moveTasks(
+ { taskIds: ['b', 'c'], direction: 'up' },
+ deps
+ )
+ expect(queue).toEqual(['a', 'b', 'c', 'd', 'e'])
+ expect(result.failed).toEqual([{ taskId: 'b', reason: 'engine-rejected' }])
+ expect(result.unchanged).toEqual(['c'])
+ })
+
+ it('revalidates a task that started after the initial queue read', async () => {
+ const { deps, queue, listWaitingTaskIds, changePosition } = setup()
+ listWaitingTaskIds.mockImplementationOnce(async () => {
+ const before = [...queue]
+ queue.splice(queue.indexOf('b'), 1)
+ return before
+ })
+ const result = await moveTasks({ taskIds: ['b'], direction: 'up' }, deps)
+ expect(result.failed).toEqual([{ taskId: 'b', reason: 'not-waiting' }])
+ expect(changePosition).not.toHaveBeenCalled()
+ })
+
+ it('serializes concurrent batches sharing an engine', async () => {
+ const { deps, queue } = setup()
+ await Promise.all([
+ moveTasks({ taskIds: ['c', 'd'], direction: 'up' }, deps),
+ moveTasks({ taskIds: ['c', 'd'], direction: 'up' }, deps),
+ ])
+ expect(queue).toEqual(['c', 'd', 'a', 'b', 'e'])
+ })
+})
diff --git a/src/core/task/actions/move-tasks.ts b/src/core/task/actions/move-tasks.ts
new file mode 100644
index 00000000..9865637c
--- /dev/null
+++ b/src/core/task/actions/move-tasks.ts
@@ -0,0 +1,119 @@
+import { AppError, ErrorCode } from '@shared/errors'
+import type {
+ MoveTasksPayload,
+ MoveTasksResult,
+} from '@shared/schemas/move-tasks'
+import { canMoveInQueue } from '@shared/types/task-actions'
+import type { EngineAdapter } from '../../engine/engine-adapter'
+import type { TaskActionDeps } from './shared'
+
+// Queue order is shared by all tasks, so even disjoint batches serialize.
+const pendingMoves = new WeakMap<EngineAdapter, Promise<unknown>>()
+
+export async function moveTasks(
+ payload: MoveTasksPayload,
+ deps: TaskActionDeps
+): Promise<MoveTasksResult> {
+ const previous = pendingMoves.get(deps.adapter) ?? Promise.resolve()
+ const operation = previous
+ .catch(() => {})
+ .then(() => moveBatch(payload, deps))
+ pendingMoves.set(deps.adapter, operation)
+ try {
+ return await operation
+ } finally {
+ if (pendingMoves.get(deps.adapter) === operation)
+ pendingMoves.delete(deps.adapter)
+ }
+}
+
+async function moveBatch(
+ { taskIds, direction }: MoveTasksPayload,
+ deps: TaskActionDeps
+): Promise<MoveTasksResult> {
+ const ids = [...new Set(taskIds)]
+ const result: MoveTasksResult = { moved: [], unchanged: [], failed: [] }
+ const tasks = ids
+ .map((id) => {
+ const task = deps.taskManager.getById(id)
+ if (!task || !canMoveInQueue(task)) {
+ result.failed.push({ taskId: id, reason: 'not-waiting' })
+ return null
+ }
+ return task
+ })
+ .filter((task) => task !== null)
+ if (!tasks.length) return result
+ const shift = direction === 'up' || direction === 'top' ? -1 : 1
+ const toEdge = direction === 'top' || direction === 'bottom'
+ const initial = await deps.adapter.listWaitingTaskIds()
+ const positions = new Map(initial.map((id, index) => [id, index]))
+ const selected = new Set(tasks.map((task) => task.engineTaskId))
+ tasks.sort(
+ (a, b) =>
+ ((positions.get(a.engineTaskId) ?? -1) -
+ (positions.get(b.engineTaskId) ?? -1)) *
+ -shift
+ )
+
+ for (const task of tasks) {
+ const move = async () => {
+ const current = deps.taskManager.getById(task.id)
+ if (
+ !current ||
+ !canMoveInQueue(current) ||
+ current.engineTaskId !== task.engineTaskId
+ )
+ throw new AppError(ErrorCode.InvalidSelection, 'not-waiting')
+ // Refresh before each move: downloads may start while the menu is open
+ // or while earlier members of this batch are being moved.
+ const queue = await deps.adapter.listWaitingTaskIds()
+ const index = queue.indexOf(current.engineTaskId)
+ if (index < 0)
+ throw new AppError(ErrorCode.InvalidSelection, 'not-waiting')
+ let destination = index + shift
+ if (toEdge) {
+ destination = index
+ // Stop at the nearest selected task, including one whose move failed.
+ // This preserves the batch's relative order even after partial failure.
+ while (
+ queue[destination + shift] &&
+ !selected.has(queue[destination + shift])
+ )
+ destination += shift
+ }
+ if (
+ destination === index ||
+ !queue[destination] ||
+ selected.has(queue[destination])
+ ) {
+ result.unchanged.push(task.id)
+ return
+ }
+ const position = await deps.adapter.changePosition(
+ current.engineTaskId,
+ toEdge ? destination : shift,
+ toEdge ? 'POS_SET' : 'POS_CUR'
+ )
+ ;(position === index ? result.unchanged : result.moved).push(task.id)
+ }
+ try {
+ await (deps.runTaskMutation
+ ? deps.runTaskMutation([task.id], move)
+ : move())
+ } catch (error) {
+ deps.log.warn(
+ { taskId: task.id, direction, error },
+ 'Waiting queue move failed'
+ )
+ result.failed.push({
+ taskId: task.id,
+ reason:
+ error instanceof AppError && error.code === ErrorCode.InvalidSelection
+ ? 'not-waiting'
+ : 'engine-rejected',
+ })
+ }
+ }
+ return result
+}
diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.ts
index 46939e78..74210b45 100644
--- a/src/core/task/actions/re-add-task.test.ts
+++ b/src/core/task/actions/re-add-task.test.ts
@@ -1184,3 +1184,23 @@ it('retries an interrupted finalize without re-adding its torrent', async () =>
expect(deps.adapter.addTorrent).not.toHaveBeenCalled()
expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()
})
+
+it('settles retired BT upload and re-seeds with current defaults instead of stale engine limits', async () => {
+ const task = makeBtTask({ uploadedBytesBaseline: 100, uploadedBytes: 250 })
+ const deps = makeDeps(task)
+ vi.mocked(deps.adapter.getEngineTaskOptions).mockResolvedValue({
+ 'seed-time': '0',
+ 'seed-ratio': '0.5',
+ })
+ await reAddTask(task.id, deps)
+ expect(deps.adapter.getEngineTaskOptions).not.toHaveBeenCalled()
+ const params = vi.mocked(deps.adapter.addTorrent).mock.calls[0]?.[0]
+ expect(params).not.toHaveProperty('seedTime')
+ expect(params).not.toHaveProperty('seedRatio')
+ expect(deps.taskManager.getById(task.id)).toMatchObject({
+ uploadedBytes: 250,
+ uploadedBytesBaseline: 250,
+ bt: { ratio: 250 / 1024 },
+ })
+ expect(task.uploadedBytesBaseline).toBe(100)
+})
diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.ts
index 7c73b54d..cf23fa55 100644
--- a/src/core/task/actions/re-add-task.ts
+++ b/src/core/task/actions/re-add-task.ts
@@ -3,7 +3,6 @@ import { newEngineTaskId } from '@core/lib/ids'
import type { AppliedDownloadProxyPolicyReader } from '@core/proxy/applied-download-proxy-policy'
import { AppError, ErrorCode } from '@shared/errors'
import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'
-import type { EngineTaskOptions } from '@shared/types/engine-task-options'
import type { DownloadTask } from '@shared/types/task'
import {
TaskInstancePhase,
@@ -34,6 +33,7 @@ import {
shouldPrioritizeBtPreviewPieces,
shouldPrioritizeBtPreviewPiecesFromMetadata,
} from '../bt-storage-layout'
+import { settleBtUpload } from '../bt-upload-settlement'
import {
canMirrorAria2MetadataHeaders,
type DirectResourceProxyOptionsProvider,
@@ -133,7 +133,6 @@ function reAddSaveDir(task: DownloadTask): string {
async function reAddBt(
task: DownloadTask,
- opts: EngineTaskOptions | null,
deps: ReAddTaskDeps,
reservedGid: string,
metadata: Uint8Array
@@ -194,12 +193,8 @@ async function reAddBt(
pause: false,
isPrivate: task.bt?.isPrivate ?? false,
...(prioritizePreviewPieces ? { prioritizePreviewPieces: true } : {}),
- seedTime: opts?.['seed-time']
- ? Number.parseInt(opts['seed-time'], 10)
- : undefined,
- seedRatio: opts?.['seed-ratio']
- ? Number.parseFloat(opts['seed-ratio'])
- : undefined,
+ // Explicit re-seeding starts a new session using the current defaults.
+ // Never replay a retired GID's seed-time=0 or spent ratio allowance.
})
}
@@ -353,6 +348,7 @@ function withReservedGid(
? {
...instance,
gid: engineTaskId,
+ uploadedBytes: 0,
...(status ? { status } : {}),
updatedAt: now,
}
@@ -459,9 +455,8 @@ async function handleFailedEngineAdd(
/**
* Re-add a task to the engine — used for both Retry (Error/Removed)
- * and Re-seed (Completed BT). Pulls live options from aria2 if the
- * stopped-result is still resident (Tier 1) and falls back to
- * task-record fields when not (Tier 2).
+ * and Re-seed (Completed BT). Reconstructs inputs from the durable task
+ * record; torrent sessions use the adapter's current seeding defaults.
*
* No `terminalCause` is threaded through this file's `commitTaskUpdate`
* calls: every candidate this function ever publishes lands in `Seeding` or
@@ -567,22 +562,23 @@ async function reAddTaskUnderMutation(
assertProxyCurrent,
canMirrorAria2MetadataHeaders(deps.adapter.getFeatureReport?.())
)
- let opts: EngineTaskOptions | null = null
- try {
- opts = await deps.adapter.getEngineTaskOptions(task.engineTaskId)
- } catch (err) {
- deps.log.debug(
- { err: String(err), taskId },
- 'reAddTask: getEngineTaskOptions failed; falling back to task fields'
- )
- }
await bestEffortRemove(deps.adapter, task.engineTaskId, deps.log)
+ const retired = structuredClone(task)
+ if (torrentLike) {
+ let upload = 0
+ try {
+ upload = await deps.adapter.getUploadLength(task.engineTaskId)
+ } catch {
+ /* Keep the last observed total. */
+ }
+ settleBtUpload(retired, upload, false)
+ }
const now = Date.now()
const status = torrentLike ? TaskStatus.Seeding : TaskStatus.Downloading
const reservedGid = newEngineTaskId(deps.createEngineTaskId, 'reAddTask')
- const reservedOwner = withReservedGid(task, reservedGid, now)
- const candidate = withReservedGid(task, reservedGid, now, status)
+ const reservedOwner = withReservedGid(retired, reservedGid, now)
+ const candidate = withReservedGid(retired, reservedGid, now, status)
deps.taskManager.reserveEngineTaskId(reservedGid)
try {
@@ -607,7 +603,7 @@ async function reAddTaskUnderMutation(
try {
if (torrentLike && torrentMetadata) {
- await reAddBt(task, opts, deps, reservedGid, torrentMetadata)
+ await reAddBt(task, deps, reservedGid, torrentMetadata)
} else if (directParams) {
assertProxyCurrent?.()
await deps.adapter.createDownload({ ...directParams, gid: reservedGid })
diff --git a/src/core/task/actions/stop-seeding-task.ts b/src/core/task/actions/stop-seeding-task.ts
index dbd7951d..d1e6adaa 100644
--- a/src/core/task/actions/stop-seeding-task.ts
+++ b/src/core/task/actions/stop-seeding-task.ts
@@ -1,6 +1,7 @@
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
import { applyTerminalTransition } from '../apply-terminal-transition'
+import { settleBtUpload } from '../bt-upload-settlement'
import {
commitTaskUpdate,
getTaskOrWarn,
@@ -61,6 +62,13 @@ export async function stopSeedingTask(
await reconcileTask(task, deps, { emitFallback: false })
throw err
}
+ let upload = 0
+ try {
+ upload = await deps.adapter.getUploadLength(task.engineTaskId)
+ } catch {
+ /* Keep the last observed total. */
+ }
+ settleBtUpload(optimistic, upload, false)
// forceRemove success is the authoritative action result. Any immediate
// engine snapshot can be stale Seeding or the short-lived aria2 Removed
// lifecycle state; neither may overwrite the domain outcome Completed.
diff --git a/src/core/task/bt-upload-settlement.ts b/src/core/task/bt-upload-settlement.ts
index 3230cb60..04769fd7 100644
--- a/src/core/task/bt-upload-settlement.ts
+++ b/src/core/task/bt-upload-settlement.ts
@@ -1,4 +1,5 @@
import type { DownloadTask, TaskInstance } from '@shared/types/task'
+import { shareRatio } from '@shared/utils/share-ratio'
import { pickPrimaryInstance } from './task-instance'
const KEY = 'btFinalizeUpload'
@@ -39,11 +40,20 @@ export function settleBtUpload(
): void {
const primary = pickPrimaryInstance(task.instances)
const accounted = accountedUpload(task.instances, task.engineTaskId)
+ upload = Math.max(
+ Number.isFinite(upload) ? upload : 0,
+ task.uploadedBytes - task.uploadedBytesBaseline + (accounted ?? 0)
+ )
// Old interrupted finalizes already saved their baseline without a marker.
// Preserve that total instead of guessing and crediting the same GID twice.
const previous = accounted ?? (recovering && primary ? upload : 0)
task.uploadedBytesBaseline += Math.max(0, upload - previous)
task.uploadedBytes = task.uploadedBytesBaseline
+ if (task.bt)
+ task.bt = {
+ ...task.bt,
+ ratio: shareRatio(task.uploadedBytes, task.totalBytes),
+ }
if (primary) {
primary.payload = {
...primary.payload,
diff --git a/src/core/task/merge-engine-task.test.ts b/src/core/task/merge-engine-task.test.ts
index 14f7cf10..819ed370 100644
--- a/src/core/task/merge-engine-task.test.ts
+++ b/src/core/task/merge-engine-task.test.ts
@@ -1,6 +1,7 @@
import { DownloadErrorCode } from '@shared/errors'
import type { DownloadTask, TaskInstance } from '@shared/types/task'
import {
+ makeDefaultBtExtension,
TaskInstancePhase,
TaskStatus,
TransitionPhase,
@@ -302,3 +303,22 @@ describe('mergeEngineTask', () => {
})
})
})
+
+it('keeps share ratio cumulative when a new GID starts from zero upload', () => {
+ const existing = baseTask({
+ totalBytes: 1000,
+ uploadedBytesBaseline: 1500,
+ bt: makeDefaultBtExtension({ ratio: 1.5 }),
+ })
+ const incoming = baseTask({
+ totalBytes: 1000,
+ uploadedBytes: 200,
+ bt: makeDefaultBtExtension({ ratio: 0.2 }),
+ })
+ expect(mergeEngineTask(existing, incoming)).toMatchObject({
+ uploadedBytes: 1700,
+ bt: { ratio: 1.7 },
+ })
+ expect(existing.bt?.ratio).toBe(1.5)
+ expect(incoming.bt?.ratio).toBe(0.2)
+})
diff --git a/src/core/task/merge-engine-task.ts b/src/core/task/merge-engine-task.ts
index 55234d4f..d589901d 100644
--- a/src/core/task/merge-engine-task.ts
+++ b/src/core/task/merge-engine-task.ts
@@ -1,5 +1,6 @@
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TransitionPhase } from '@shared/types/task'
+import { shareRatio } from '@shared/utils/share-ratio'
import { applyTerminalTransition } from './apply-terminal-transition'
import { unsettledBtUpload } from './bt-upload-settlement'
import { isCompletedDirectOutput } from './completed-direct-task-policy'
@@ -67,6 +68,7 @@ export function mergeEngineTask(
},
now
)
+ const bt = protected_.bt ?? existing.bt
const merged: DownloadTask = {
...existing,
...terminalFields,
@@ -84,7 +86,9 @@ export function mergeEngineTask(
fileCount: protected_.fileCount,
infoHash: protected_.infoHash ?? existing.infoHash,
uris: protected_.uris.length > 0 ? protected_.uris : existing.uris,
- bt: protected_.bt ?? existing.bt,
+ bt: bt
+ ? { ...bt, ratio: shareRatio(uploadedBytes, protected_.totalBytes) }
+ : undefined,
updatedAt: now,
}
if (
diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.ts
index 278adc7e..e54adab5 100644
--- a/src/core/task/task-row-to-download-task.ts
+++ b/src/core/task/task-row-to-download-task.ts
@@ -6,6 +6,7 @@ import {
TransitionPhase,
} from '@shared/types/task'
import { isTorrentLikeType } from '@shared/types/task-actions'
+import { shareRatio } from '@shared/utils/share-ratio'
import { unsettledBtUpload } from './bt-upload-settlement'
import { restoreTaskSaveDirectory } from './task-save-directory'
@@ -35,7 +36,7 @@ export function taskRowToDownloadTask(
)
const bt = isTorrentLikeType(task.taskType)
? makeDefaultBtExtension({
- ratio: task.totalBytes > 0 ? uploadedBytes / task.totalBytes : 0,
+ ratio: shareRatio(uploadedBytes, task.totalBytes),
trackers: task.trackers.flat(),
announceList: task.trackers,
isPrivate: task.isPrivate,
diff --git a/src/main/commands/definitions/task.commands.test.ts b/src/main/commands/definitions/task.commands.test.ts
index e7760d67..eea7ad76 100644
--- a/src/main/commands/definitions/task.commands.test.ts
+++ b/src/main/commands/definitions/task.commands.test.ts
@@ -1,4 +1,5 @@
import { CommandIds } from '@shared/commands-catalog'
+import { Events } from '@shared/protocol/events'
import { describe, expect, it, vi } from 'vitest'
import { CommandRegistry } from '../command-registry'
import { DEFAULT_MENU_CONTEXT } from '../menu-context'
@@ -15,6 +16,38 @@ vi.mock('@core/task/actions', async (importOriginal) => ({
}))
describe('task commands', () => {
+ it('selects tasks only in the main Downloads window', async () => {
+ const registry = new CommandRegistry()
+ const send = vi.fn()
+ const get = vi.fn(() => ({ webContents: { send } }))
+ const deps = { windowManager: { get } } as unknown as CommandDeps
+ registerTaskCommands(registry, deps)
+
+ for (const currentRoute of ['/downloads', '/downloads/completed']) {
+ await registry.execute(CommandIds.TaskSelectAll, undefined, {
+ menuContext: { ...DEFAULT_MENU_CONTEXT, currentRoute },
+ deps,
+ })
+ }
+ expect(get).toHaveBeenCalledWith('main')
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(send).toHaveBeenLastCalledWith(Events.TaskSelectAll)
+
+ for (const currentRoute of ['/settings', '/downloads-other']) {
+ expect(
+ registry.canExecute(CommandIds.TaskSelectAll, {
+ ...DEFAULT_MENU_CONTEXT,
+ currentRoute,
+ })
+ ).toBe(false)
+ await registry.execute(CommandIds.TaskSelectAll, undefined, {
+ menuContext: { ...DEFAULT_MENU_CONTEXT, currentRoute },
+ deps,
+ })
+ }
+ expect(send).toHaveBeenCalledTimes(2)
+ })
+
it('wires Clear Stopped to the shared persistence coordinator', async () => {
const registry = new CommandRegistry()
const taskManager = { marker: 'task-manager' }
diff --git a/src/main/commands/definitions/task.commands.ts b/src/main/commands/definitions/task.commands.ts
index 804380d1..5c3de979 100644
--- a/src/main/commands/definitions/task.commands.ts
+++ b/src/main/commands/definitions/task.commands.ts
@@ -8,6 +8,7 @@ import {
resumeTask,
} from '@core/task/actions'
import { CommandIds } from '@shared/commands-catalog'
+import { Events } from '@shared/protocol/events'
import { TaskStatus } from '@shared/types/task'
import type { CommandRegistry } from '../command-registry'
import type { CommandDeps } from '../types'
@@ -143,6 +144,16 @@ export function registerTaskCommands(
},
})
+ registry.register({
+ id: CommandIds.TaskSelectAll,
+ title: 'menu.task.selectAllTask',
+ precondition: ({ currentRoute }) =>
+ currentRoute === '/downloads' || currentRoute.startsWith('/downloads/'),
+ run: ({ deps }) => {
+ deps.windowManager.get('main')?.webContents.send(Events.TaskSelectAll)
+ },
+ })
+
registry.register({
id: CommandIds.TaskClearStopped,
title: 'menu.task.clearRecentTasks',
diff --git a/src/main/index.ts b/src/main/index.ts
index 9622209e..7b485ec8 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -121,6 +121,10 @@ import type { NatManager } from '@motrix/nat'
import { APP_ID } from '@shared/constants'
import { DEFAULT_LOCALE, type SupportedLocale } from '@shared/constants/locales'
import { Events } from '@shared/protocol/events'
+import {
+ DEFAULT_BYTE_UNIT_PREFERENCE,
+ resolveByteUnitSystem,
+} from '@shared/schemas/byte-unit-system'
import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'
import { EngineState } from '@shared/types/engine'
import type { AppNotification } from '@shared/types/notification'
@@ -324,12 +328,21 @@ const cliToolService = new CliToolService({
!settingsFlatpakEnvironment && settingsSnapEnvironment === null,
})
const settingsManager = new SettingsManager(settingsPath, {
+ defaultByteUnitSystem: resolveByteUnitSystem(
+ DEFAULT_BYTE_UNIT_PREFERENCE,
+ process.platform
+ ),
liquidGlassEffectDefault: shouldEnableLiquidGlassByDefault({
isDev: platform.isDev,
}),
...defaultSaveDirOptions,
onChange: (old, updated) => {
eventBus.emit(Events.SettingsChanged, { old, updated })
+ if (old.app.liquidGlassEffect !== updated.app.liquidGlassEffect) {
+ eventBus.emit(Events.LiquidGlassChanged, {
+ liquidGlassEffect: updated.app.liquidGlassEffect,
+ })
+ }
if (old.app.byteUnitSystem !== updated.app.byteUnitSystem) {
eventBus.emit(Events.ByteUnitSystemChanged, {
byteUnitSystem: updated.app.byteUnitSystem,
@@ -1601,22 +1614,31 @@ async function initializeMainProcess(): Promise<void> {
// preload buffers it until React subscribes).
setupEventForwarding(eventBus, windowManager)
- // Best-effort OS notification bridge (Task 16, spec §6): windowManager and
- // settingsManager are both live at this point, which is all it depends on
- // — it subscribes directly to eventBus and doesn't need the engine or
- // notificationCenter (constructed later, in Phase 2 below — see the F4
- // hoist comment) to exist yet, since it only reacts to NotificationAdded
- // once emitted.
+ // Subscribe before notification-center replay. Resolve task paths on click
+ // so notifications follow any output moves made after download completion.
+ const revealNotificationTask = createRevealInFolderHandler({
+ shell,
+ getTask: (taskId) => taskManager.getById(taskId),
+ })
osNotificationBridge = createOsNotificationBridge({
subscribe: (channel, listener) =>
eventBus.on(channel, (...args: unknown[]) =>
listener(args[0] as AppNotification)
),
getMainWindow: () => windowManager?.get('main') ?? null,
+ showMainWindow: () => windowManager?.show('main'),
getAppSettings: () => settingsManager.getApp(),
translate: i18n.t.bind(i18n),
- navigateToTask: (taskId) =>
- eventBus.emit(Events.NavigateTo, `/downloads/all?task=${taskId}`),
+ navigateToTask: (taskId) => {
+ const win = windowManager?.get('main')
+ if (!win || win.isDestroyed()) return
+ dispatchWhenReady(
+ win,
+ Events.NavigateTo,
+ `/downloads/all?task=${encodeURIComponent(taskId)}`
+ )
+ },
+ revealTaskInFolder: (taskId) => revealNotificationTask({ taskId }),
log,
})
@@ -1685,7 +1707,9 @@ async function initializeMainProcess(): Promise<void> {
// Use that window to set up IPC handlers and core services.
rpcClient = new Aria2RpcClient(transport, protocol, engineSettings.rpcSecret)
- aria2Adapter = new Aria2Adapter(rpcClient)
+ aria2Adapter = new Aria2Adapter(rpcClient, undefined, () =>
+ settingsManager.getEngine()
+ )
const adapter = aria2Adapter
proxyBridge = new ProxyBridgeManager()
supervisor = new EngineSupervisor(
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 55c90f90..d4831f5b 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -395,6 +395,42 @@ describe('buildCommandHandlers', () => {
expect(ctx.sessionManager.runExclusivePersistence).toHaveBeenCalledOnce()
})
+ it('MoveTasks validates the payload and changes the actual engine queue', async () => {
+ const ctx = fakeCtx()
+ const queue = ['first', 'second']
+ vi.mocked(ctx.taskManager.getById).mockReturnValue({
+ id: 'task-second',
+ engineTaskId: 'second',
+ status: TaskStatus.Paused,
+ } as never)
+ Object.assign(ctx.adapter, {
+ listWaitingTaskIds: vi.fn(async () => [...queue]),
+ changePosition: vi.fn(async () => {
+ queue.reverse()
+ return 0
+ }),
+ })
+ const handlers = buildCommandHandlers(
+ ctx as unknown as Parameters<typeof buildCommandHandlers>[0]
+ )
+ await expect(
+ handlers[Commands.MoveTasks]?.({
+ taskIds: ['task-second'],
+ direction: 'up',
+ })
+ ).resolves.toEqual({ moved: ['task-second'], unchanged: [], failed: [] })
+ expect(queue).toEqual(['second', 'first'])
+ await expect(
+ handlers[Commands.MoveTasks]?.({ taskIds: [], direction: 'up' })
+ ).rejects.toThrow()
+ await expect(
+ handlers[Commands.MoveTasks]?.({
+ taskIds: ['task-second'],
+ direction: 'sideways',
+ })
+ ).rejects.toThrow()
+ })
+
it('PauseTasks fans out per id and returns the IPC-safe bulk result', async () => {
const ctx = fakeCtx()
const tasks = new Map([
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 692a7db1..2a46b82e 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -50,6 +50,7 @@ import {
stopSeedingTask,
toBulkTaskCommandResult,
} from '@core/task/actions'
+import { moveTasks } from '@core/task/actions/move-tasks'
import type {
TaskActionDeps,
TaskTransitionRecordInput,
@@ -93,6 +94,7 @@ import {
taskIdsPayloadSchema,
} from '@shared/schemas/bulk-task-command'
import { closeCurrentWindowSchema } from '@shared/schemas/close-current-window'
+import { moveTasksPayloadSchema } from '@shared/schemas/move-tasks'
import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'
import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'
import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'
@@ -133,6 +135,7 @@ import type { createProtocolManager } from '../platform/protocol-manager'
import { resolveWindowsDefaultAppsSettingsUrl } from '../platform/windows-default-apps'
import type { createMainProxyApplier } from '../proxy/wiring'
import type { WindowManager } from '../window/window-manager'
+import { createOpenTaskFileHandler } from './commands/open-task-file'
import { createRevealInFolderHandler } from './commands/reveal-in-folder'
import { createSetSelectedFilesHandler } from './commands/set-selected-files'
import { NatCommandHandlers } from './nat-commands'
@@ -668,6 +671,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
// Plural task commands (option C): one IPC request per multi-select
// action. Per-task outcomes come back IPC-safe; the bulk close inside
// runBulkTaskAction forces one immediate snapshot flush.
+ [Commands.MoveTasks]: async (rawPayload: unknown) =>
+ moveTasks(moveTasksPayloadSchema.parse(rawPayload), pauseResumeDeps),
+
[Commands.PauseTasks]: async (rawPayload: unknown) => {
const taskIds = taskIdsPayloadSchema.parse(rawPayload)
return toBulkTaskCommandResult(
@@ -1294,6 +1300,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
shell,
getTask: (taskId) => taskManager.getById(taskId),
}),
+ [Commands.OpenTaskFile]: createOpenTaskFileHandler({
+ shell,
+ getTask: (taskId) => taskManager.getById(taskId),
+ }),
[Commands.EnableNat]: async () => natHandlers.enable(),
[Commands.DisableNat]: async () => natHandlers.disable(),
diff --git a/src/main/ipc/commands/open-task-file.test.ts b/src/main/ipc/commands/open-task-file.test.ts
new file mode 100644
index 00000000..89119ca9
--- /dev/null
+++ b/src/main/ipc/commands/open-task-file.test.ts
@@ -0,0 +1,130 @@
+// @vitest-environment node
+import { stat } from 'node:fs/promises'
+import { ErrorCode } from '@shared/errors'
+import { TaskStatus } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createOpenTaskFileHandler } from './open-task-file'
+
+vi.mock('node:fs/promises', () => ({ stat: vi.fn() }))
+
+function setup() {
+ const task = makeDownloadTask({
+ id: 'a',
+ status: TaskStatus.Completed,
+ fileCount: 1,
+ finalPath: '/downloads/final.bin',
+ diskPath: '/downloads/partial.bin',
+ })
+ const shell = { openPath: vi.fn(async () => '') }
+ const getTask = vi.fn(() => task)
+ return {
+ task,
+ shell,
+ getTask,
+ handler: createOpenTaskFileHandler({ shell, getTask }),
+ }
+}
+
+beforeEach(() => {
+ vi.mocked(stat)
+ .mockReset()
+ .mockResolvedValue({ isFile: () => true } as Awaited<
+ ReturnType<typeof stat>
+ >)
+})
+
+describe('openTaskFile', () => {
+ it('opens only the published file owned by the task, ignoring supplied paths', async () => {
+ const { handler, shell } = setup()
+ await handler({ taskId: 'a', path: '/some/other/file' })
+ expect(shell.openPath).toHaveBeenCalledExactlyOnceWith(
+ '/downloads/final.bin'
+ )
+ })
+
+ it.each([
+ TaskStatus.Downloading,
+ TaskStatus.Finalizing,
+ TaskStatus.Seeding,
+ TaskStatus.Removed,
+ TaskStatus.Error,
+ ])('rejects %s tasks at execution time', async (status) => {
+ const { handler, task, shell } = setup()
+ task.status = status
+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({
+ code: ErrorCode.InvalidSelection,
+ })
+ expect(shell.openPath).not.toHaveBeenCalled()
+ })
+
+ it('rejects multi-file tasks even when they claim a file path', async () => {
+ const { handler, task, shell } = setup()
+ task.fileCount = 2
+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({
+ code: ErrorCode.InvalidSelection,
+ })
+ expect(shell.openPath).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ 'relative/file',
+ 'https://example.test/file',
+ '//?/C:/file',
+ '/downloads/\0file',
+ ])('rejects an invalid stored path: %s', async (output) => {
+ const { handler, task, shell } = setup()
+ task.finalPath = output
+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({
+ code: ErrorCode.IpcInvalidPayload,
+ })
+ expect(shell.openPath).not.toHaveBeenCalled()
+ })
+
+ it.each(['missing', 'directory', 'denied'])(
+ 'does not open a %s output',
+ async (kind) => {
+ const { handler, shell } = setup()
+ if (kind === 'directory')
+ vi.mocked(stat).mockResolvedValueOnce({
+ isFile: () => false,
+ } as Awaited<ReturnType<typeof stat>>)
+ else vi.mocked(stat).mockRejectedValueOnce(new Error(kind))
+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({
+ code: ErrorCode.TaskOpenFailed,
+ })
+ expect(shell.openPath).not.toHaveBeenCalled()
+ }
+ )
+
+ it('rechecks the task after the filesystem read', async () => {
+ const { handler, task, shell } = setup()
+ vi.mocked(stat).mockImplementationOnce(async () => {
+ task.status = TaskStatus.Removed
+ return { isFile: () => true } as Awaited<ReturnType<typeof stat>>
+ })
+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({
+ code: ErrorCode.TaskOpenFailed,
+ })
+ expect(shell.openPath).not.toHaveBeenCalled()
+ })
+
+ it('reports an operating system open failure', async () => {
+ const { handler, shell } = setup()
+ shell.openPath.mockResolvedValueOnce('No application available')
+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({
+ code: ErrorCode.TaskOpenFailed,
+ })
+ })
+
+ it.each([null, {}, { taskId: '' }, { taskId: 3 }])(
+ 'rejects invalid requests',
+ async (payload) => {
+ const { handler, shell } = setup()
+ await expect(handler(payload)).rejects.toMatchObject({
+ code: ErrorCode.IpcInvalidPayload,
+ })
+ expect(shell.openPath).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/src/main/ipc/commands/open-task-file.ts b/src/main/ipc/commands/open-task-file.ts
new file mode 100644
index 00000000..9d151bec
--- /dev/null
+++ b/src/main/ipc/commands/open-task-file.ts
@@ -0,0 +1,58 @@
+import { stat } from 'node:fs/promises'
+import path from 'node:path'
+import { AppError, ErrorCode } from '@shared/errors'
+import { openTaskFilePayloadSchema } from '@shared/schemas/open-task-file'
+import type { DownloadTask } from '@shared/types/task'
+import { canOpenTaskFile } from '@shared/types/task-actions'
+
+interface OpenTaskFileDeps {
+ shell: { openPath: (path: string) => Promise<string> }
+ getTask: (taskId: string) => DownloadTask | undefined
+}
+
+export function createOpenTaskFileHandler(deps: OpenTaskFileDeps) {
+ return async (payload: unknown): Promise<void> => {
+ const parsed = openTaskFilePayloadSchema.safeParse(payload)
+ if (!parsed.success)
+ throw new AppError(ErrorCode.IpcInvalidPayload, 'Invalid task id')
+ const task = deps.getTask(parsed.data.taskId)
+ if (!task) throw new AppError(ErrorCode.TaskNotFound, 'Task not found')
+ if (!canOpenTaskFile(task))
+ throw new AppError(ErrorCode.InvalidSelection, 'Task output is not ready')
+
+ // Resolve only the task-owned published path, never a renderer-supplied path.
+ const outputPath = task.finalPath || task.diskPath
+ const normalized = outputPath.replaceAll('\\', '/')
+ if (
+ outputPath.includes('\0') ||
+ !path.isAbsolute(outputPath) ||
+ ['//?/', '//./', '/??/', '//??/'].some((prefix) =>
+ normalized.startsWith(prefix)
+ )
+ )
+ throw new AppError(
+ ErrorCode.IpcInvalidPayload,
+ 'Invalid task output path'
+ )
+ try {
+ if (!(await stat(outputPath)).isFile())
+ throw new Error('Task output is not a file')
+ // Check again after the filesystem read in case the task was removed.
+ const current = deps.getTask(task.id)
+ if (
+ !current ||
+ !canOpenTaskFile(current) ||
+ (current.finalPath || current.diskPath) !== outputPath
+ )
+ throw new Error('Task output changed')
+ const error = await deps.shell.openPath(outputPath)
+ if (error) throw new Error(error)
+ } catch (cause) {
+ throw new AppError(
+ ErrorCode.TaskOpenFailed,
+ 'Task output could not be opened',
+ cause
+ )
+ }
+ }
+}
diff --git a/src/main/menu/contributions/shared.ts b/src/main/menu/contributions/shared.ts
index fbd93378..76ff291b 100644
--- a/src/main/menu/contributions/shared.ts
+++ b/src/main/menu/contributions/shared.ts
@@ -103,8 +103,7 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
menuId: MenuIds.MenubarTask,
group: '3_bulk',
order: 30,
- role: 'selectAll',
- titleOverride: 'menu.task.selectAllTask',
+ commandId: CommandIds.TaskSelectAll,
})
menuReg.appendItem({
id: MenuItemIds.TaskClearStopped,
diff --git a/src/main/notifications/os-bridge.test.ts b/src/main/notifications/os-bridge.test.ts
index 5aa49215..2b4823fe 100644
--- a/src/main/notifications/os-bridge.test.ts
+++ b/src/main/notifications/os-bridge.test.ts
@@ -79,29 +79,27 @@ function makeWindow(
return {
isVisible: vi.fn(() => isVisible),
isFocused: vi.fn(() => isFocused),
- show: vi.fn(),
- focus: vi.fn(),
}
}
interface FakeHandle extends OsNotificationHandle {
opts: { title: string; body?: string }
- click(): void
+ click(): Promise<void>
}
function makeNotificationFactory() {
const instances: FakeHandle[] = []
const createNotification = vi.fn(
(opts: { title: string; body?: string }): OsNotificationHandle => {
- const clickListeners: Array<() => void> = []
+ const clickListeners: Array<() => void | Promise<void>> = []
const handle: FakeHandle = {
opts,
show: vi.fn(),
on: vi.fn((event: 'click', listener: () => void) => {
if (event === 'click') clickListeners.push(listener)
}),
- click: () => {
- for (const listener of clickListeners) listener()
+ click: async () => {
+ for (const listener of clickListeners) await listener()
},
}
instances.push(handle)
@@ -146,11 +144,17 @@ function baseDeps(overrides: {
>['createNotification']
isSupported?: () => boolean
log?: ReturnType<typeof makeLog>
+ showMainWindow?: () => void
navigateToTask?: (taskId: string) => void
+ revealTaskInFolder?: (taskId: string) => Promise<void>
translate?: (key: string, params?: Record<string, string>) => string
}) {
const { subscribe, deliver } = makeCapturingSubscribe()
- const navigateToTask = overrides.navigateToTask ?? vi.fn()
+ const navigateToTask = vi.fn(overrides.navigateToTask)
+ const showMainWindow = vi.fn(overrides.showMainWindow)
+ const revealTaskInFolder = vi.fn(
+ overrides.revealTaskInFolder ?? (async () => {})
+ )
const log = overrides.log ?? makeLog()
const translate = overrides.translate ?? ((key: string) => key)
const window = overrides.window ?? null
@@ -160,12 +164,16 @@ function baseDeps(overrides: {
deliver,
log,
navigateToTask,
+ showMainWindow,
+ revealTaskInFolder,
deps: {
subscribe,
getMainWindow: () => window,
+ showMainWindow,
getAppSettings: () => settings,
translate,
navigateToTask,
+ revealTaskInFolder,
isSupported: overrides.isSupported ?? (() => true),
createNotification: overrides.createNotification,
log,
@@ -300,6 +308,8 @@ describe('createOsNotificationBridge — subscription', () => {
getMainWindow: () => null,
getAppSettings: () => makeSettings(),
translate: (key) => key,
+ showMainWindow: vi.fn(),
+ revealTaskInFolder: vi.fn(async () => {}),
navigateToTask: vi.fn(),
isSupported: () => true,
createNotification,
@@ -434,73 +444,208 @@ describe('createOsNotificationBridge — body rendering', () => {
// ---------------------------------------------------------------------------
describe('createOsNotificationBridge — click behavior', () => {
- it('click shows and focuses the main window, then navigates when taskId is set', () => {
+ it.each(['hidden', 'released'])(
+ 'reveals a completed task without showing the %s main window',
+ async (windowState) => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const {
+ deps,
+ deliver,
+ revealTaskInFolder,
+ showMainWindow,
+ navigateToTask,
+ } = baseDeps({
+ window: windowState === 'hidden' ? makeWindow(false, true) : null,
+ settings: makeSettings({ notifyOnComplete: true }),
+ createNotification,
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+ expect(revealTaskInFolder).not.toHaveBeenCalled()
+
+ await instances[0].click()
+
+ expect(revealTaskInFolder).toHaveBeenCalledExactlyOnceWith('t-1')
+ expect(showMainWindow).not.toHaveBeenCalled()
+ expect(navigateToTask).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ NotificationKinds.TaskError,
+ NotificationKinds.EngineFailure,
+ 'unknown-kind',
+ ])('opens the main window before navigating for %s', async (kind) => {
const { createNotification, instances } = makeNotificationFactory()
- const window = makeWindow(false, true)
- const navigateToTask = vi.fn()
- const { deps, deliver } = baseDeps({
- window,
- settings: makeSettings({ notifyOnComplete: true }),
+ const {
+ deps,
+ deliver,
+ showMainWindow,
+ navigateToTask,
+ revealTaskInFolder,
+ } = baseDeps({
+ window: null,
+ settings: makeSettings({ notifyOnError: true }),
createNotification,
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ kind, taskId: 't-1' }))
+
+ await instances[0].click()
+
+ expect(showMainWindow).toHaveBeenCalledOnce()
+ expect(showMainWindow).toHaveBeenCalledBefore(navigateToTask)
+ expect(navigateToTask).toHaveBeenCalledExactlyOnceWith('t-1')
+ expect(revealTaskInFolder).not.toHaveBeenCalled()
+ })
+
+ it('opens the main window without revealing or navigating when taskId is null', async () => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const {
+ deps,
+ deliver,
+ showMainWindow,
navigateToTask,
+ revealTaskInFolder,
+ } = baseDeps({
+ settings: makeSettings({ notifyOnComplete: true }),
+ createNotification,
})
createOsNotificationBridge(deps)
- deliver(
- makeNotification({ kind: NotificationKinds.TaskComplete, taskId: 't-1' })
- )
+ deliver(makeNotification({ taskId: null }))
- instances[0].click()
+ await instances[0].click()
- expect(window.show).toHaveBeenCalledOnce()
- expect(window.focus).toHaveBeenCalledOnce()
- expect(navigateToTask).toHaveBeenCalledWith('t-1')
+ expect(showMainWindow).toHaveBeenCalledOnce()
+ expect(navigateToTask).not.toHaveBeenCalled()
+ expect(revealTaskInFolder).not.toHaveBeenCalled()
})
- it('click shows and focuses but does not navigate when taskId is null', () => {
+ it.each(['rejection', 'synchronous throw'])(
+ 'falls back to the task when revealing fails with a %s',
+ async (failure) => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const err = new Error('output and containing folder unavailable')
+ const revealTaskInFolder = vi.fn(() => {
+ if (failure === 'rejection') return Promise.reject(err)
+ throw err
+ })
+ const { deps, deliver, showMainWindow, navigateToTask, log } = baseDeps({
+ window: null,
+ settings: makeSettings({ notifyOnComplete: true }),
+ createNotification,
+ revealTaskInFolder,
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+
+ await expect(instances[0].click()).resolves.toBeUndefined()
+
+ expect(revealTaskInFolder).toHaveBeenCalledExactlyOnceWith('t-1')
+ expect(showMainWindow).toHaveBeenCalledOnce()
+ expect(showMainWindow).toHaveBeenCalledBefore(navigateToTask)
+ expect(navigateToTask).toHaveBeenCalledExactlyOnceWith('t-1')
+ expect(log.warn).toHaveBeenCalledExactlyOnceWith(
+ { err, taskId: 't-1' },
+ 'os-notification-bridge: reveal failed; opening task'
+ )
+ }
+ )
+
+ it('waits for the reveal result before deciding to open the task', async () => {
const { createNotification, instances } = makeNotificationFactory()
- const window = makeWindow(false, true)
- const navigateToTask = vi.fn()
- const { deps, deliver } = baseDeps({
- window,
+ const reveal = Promise.withResolvers<void>()
+ const { deps, deliver, showMainWindow, navigateToTask } = baseDeps({
settings: makeSettings({ notifyOnComplete: true }),
createNotification,
- navigateToTask,
+ revealTaskInFolder: () => reveal.promise,
})
createOsNotificationBridge(deps)
- deliver(
- makeNotification({ kind: NotificationKinds.TaskComplete, taskId: null })
- )
+ deliver(makeNotification({ taskId: 't-1' }))
+ const click = instances[0].click()
+
+ expect(showMainWindow).not.toHaveBeenCalled()
+ expect(navigateToTask).not.toHaveBeenCalled()
- instances[0].click()
+ reveal.resolve()
+ await click
- expect(window.show).toHaveBeenCalledOnce()
- expect(window.focus).toHaveBeenCalledOnce()
+ expect(showMainWindow).not.toHaveBeenCalled()
expect(navigateToTask).not.toHaveBeenCalled()
})
- it('navigateToTask throwing inside the click callback is caught and logged via log.warn, not thrown', () => {
+ it.each(['showMainWindow', 'navigateToTask'] as const)(
+ 'catches and logs errors from %s during reveal fallback',
+ async (action) => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const err = new Error('window action failed')
+ const { deps, deliver, log } = baseDeps({
+ settings: makeSettings({ notifyOnComplete: true }),
+ createNotification,
+ revealTaskInFolder: vi.fn().mockRejectedValue(new Error('missing')),
+ [action]: () => {
+ throw err
+ },
+ })
+
+ createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+
+ await expect(instances[0].click()).resolves.toBeUndefined()
+ expect(log.warn).toHaveBeenLastCalledWith(
+ { err },
+ 'os-notification-bridge: click handler threw'
+ )
+ }
+ )
+
+ it('ignores clicks after disposal', async () => {
const { createNotification, instances } = makeNotificationFactory()
- const window = makeWindow(false, true)
- const err = new Error('EventBus listener threw')
- const navigateToTask = vi.fn(() => {
- throw err
+ const {
+ deps,
+ deliver,
+ revealTaskInFolder,
+ showMainWindow,
+ navigateToTask,
+ } = baseDeps({
+ settings: makeSettings({ notifyOnComplete: true }),
+ createNotification,
})
- const { deps, deliver, log } = baseDeps({
- window,
+
+ const bridge = createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+ bridge.dispose()
+
+ await instances[0].click()
+
+ expect(revealTaskInFolder).not.toHaveBeenCalled()
+ expect(showMainWindow).not.toHaveBeenCalled()
+ expect(navigateToTask).not.toHaveBeenCalled()
+ })
+
+ it('does not reopen the app if disposed while revealing', async () => {
+ const { createNotification, instances } = makeNotificationFactory()
+ const reveal = Promise.withResolvers<void>()
+ const { deps, deliver, showMainWindow, navigateToTask } = baseDeps({
settings: makeSettings({ notifyOnComplete: true }),
createNotification,
- navigateToTask,
+ revealTaskInFolder: () => reveal.promise,
})
- createOsNotificationBridge(deps)
- deliver(
- makeNotification({ kind: NotificationKinds.TaskComplete, taskId: 't-1' })
- )
+ const bridge = createOsNotificationBridge(deps)
+ deliver(makeNotification({ taskId: 't-1' }))
+ const click = instances[0].click()
+ bridge.dispose()
+ reveal.reject(new Error('folder unavailable'))
+ await click
- expect(() => instances[0].click()).not.toThrow()
- expect(log.warn).toHaveBeenCalledOnce()
+ expect(showMainWindow).not.toHaveBeenCalled()
+ expect(navigateToTask).not.toHaveBeenCalled()
})
})
@@ -590,6 +735,8 @@ describe('createOsNotificationBridge — Electron defaults', () => {
getMainWindow: () => null,
getAppSettings: () => makeSettings({ notifyOnComplete: true }),
translate: (key) => key,
+ showMainWindow: vi.fn(),
+ revealTaskInFolder: vi.fn(async () => {}),
navigateToTask: vi.fn(),
log: { warn: vi.fn() },
})
@@ -612,6 +759,8 @@ describe('createOsNotificationBridge — Electron defaults', () => {
getMainWindow: () => null,
getAppSettings: () => makeSettings({ notifyOnComplete: true }),
translate: (key) => key,
+ showMainWindow: vi.fn(),
+ revealTaskInFolder: vi.fn(async () => {}),
navigateToTask: vi.fn(),
log: { warn: vi.fn() },
})
diff --git a/src/main/notifications/os-bridge.ts b/src/main/notifications/os-bridge.ts
index a3dc89e6..ba534ec5 100644
--- a/src/main/notifications/os-bridge.ts
+++ b/src/main/notifications/os-bridge.ts
@@ -10,8 +10,6 @@ import { Notification } from 'electron'
export interface OsNotificationMainWindow {
isVisible(): boolean
isFocused(): boolean
- show(): void
- focus(): void
}
/** Structural subset of Electron's `Notification` this bridge needs. */
@@ -27,11 +25,15 @@ export interface OsNotificationBridgeDeps {
listener: (payload: AppNotification) => void
) => void
getMainWindow: () => OsNotificationMainWindow | null
+ /** Show the main window, recreating it if it was released in the background. */
+ showMainWindow: () => void
getAppSettings: () => MotrixAppSettings
/** `i18n.t.bind(i18n)` — follows `LocaleCoordinator` language switches. */
translate: (key: string, params?: Record<string, string>) => string
- /** `(taskId) => eventBus.emit(Events.NavigateTo, '/downloads/all?task=' + taskId)` */
+ /** Navigate once the main window's renderer is ready. */
navigateToTask: (taskId: string) => void
+ /** Reveal the task's current output, or its containing directory if missing. */
+ revealTaskInFolder: (taskId: string) => Promise<void>
isSupported?: () => boolean
createNotification?: (opts: {
title: string
@@ -74,6 +76,36 @@ export function createOsNotificationBridge(deps: OsNotificationBridgeDeps): {
let disposed = false
+ async function handleClick(payload: AppNotification): Promise<void> {
+ if (disposed) return
+ // Native clicks fire after handle() returns, so isolate both asynchronous
+ // file-manager failures and errors while showing or navigating the window.
+ try {
+ if (
+ payload.kind === NotificationKinds.TaskComplete &&
+ payload.taskId != null
+ ) {
+ try {
+ await deps.revealTaskInFolder(payload.taskId)
+ return
+ } catch (err) {
+ deps.log.warn(
+ { err, taskId: payload.taskId },
+ 'os-notification-bridge: reveal failed; opening task'
+ )
+ }
+ }
+
+ if (disposed) return
+ deps.showMainWindow()
+ if (payload.taskId != null) {
+ deps.navigateToTask(payload.taskId)
+ }
+ } catch (err) {
+ deps.log.warn({ err }, 'os-notification-bridge: click handler threw')
+ }
+ }
+
function handle(payload: AppNotification): void {
const win = deps.getMainWindow()
const foreground = win == null ? false : win.isVisible() && win.isFocused()
@@ -95,23 +127,7 @@ export function createOsNotificationBridge(deps: OsNotificationBridgeDeps): {
const notification = createNotification(
body === undefined ? { title } : { title, body }
)
- notification.on('click', () => {
- // Runs outside handle()'s own try/catch (it fires later, from
- // Electron's Notification emitter, after handle() has already
- // returned) — navigateToTask fans out through EventBus.emit, which
- // has no per-listener isolation, so a throwing downstream listener
- // must be caught here rather than crash the click callback.
- try {
- const clicked = deps.getMainWindow()
- clicked?.show()
- clicked?.focus()
- if (payload.taskId != null) {
- deps.navigateToTask(payload.taskId)
- }
- } catch (err) {
- deps.log.warn({ err }, 'os-notification-bridge: click handler threw')
- }
- })
+ notification.on('click', () => handleClick(payload))
notification.show()
}
diff --git a/src/renderer/components/desktop-kit/hooks/use-selectable-list.test.tsx b/src/renderer/components/desktop-kit/hooks/use-selectable-list.test.tsx
index 85cc2377..f98d19a2 100644
--- a/src/renderer/components/desktop-kit/hooks/use-selectable-list.test.tsx
+++ b/src/renderer/components/desktop-kit/hooks/use-selectable-list.test.tsx
@@ -14,11 +14,22 @@ const makeItems = (count: number): TestItem[] =>
name: `Item ${i}`,
}))
-function TestHarness({ items }: { items: TestItem[] }) {
+function TestHarness({
+ items,
+ nativeSelection = false,
+ macOS = false,
+}: {
+ items: TestItem[]
+ nativeSelection?: boolean
+ macOS?: boolean
+}) {
const { getRowProps, headerCheckbox, onKeyDown } = useSelectableList({
items,
getId: (t) => t.id,
rowHeight: 40,
+ nativeSelection,
+ macOS,
+ getText: (item) => item.name,
})
return (
@@ -274,3 +285,66 @@ describe('useSelectableList (external store)', () => {
expect(result.current.selection.getState().selectedIds.has('b')).toBe(true)
})
})
+
+describe('native table selection', () => {
+ it('moves selection immediately and contracts a reversed Shift range', () => {
+ render(<TestHarness items={makeItems(5)} nativeSelection macOS />)
+ const wrapper = screen.getByTestId('wrapper')
+ fireEvent.click(screen.getByTestId('row-1'))
+ fireEvent.keyDown(wrapper, { key: 'ArrowDown', shiftKey: true })
+ fireEvent.keyDown(wrapper, { key: 'ArrowDown', shiftKey: true })
+ expect(screen.getByTestId('row-3').dataset.selected).toBe('true')
+ fireEvent.keyDown(wrapper, { key: 'ArrowUp', shiftKey: true })
+ expect(screen.getByTestId('row-3').dataset.selected).toBe('false')
+ expect(screen.getByTestId('row-1').dataset.selected).toBe('true')
+ fireEvent.keyDown(wrapper, { key: 'ArrowDown' })
+ expect(screen.getByTestId('row-1').dataset.selected).toBe('false')
+ expect(screen.getByTestId('row-3').dataset.selected).toBe('true')
+ })
+
+ it('reserves Control-click on macOS and uses Command-click to move the focus anchor', () => {
+ render(<TestHarness items={makeItems(5)} nativeSelection macOS />)
+ fireEvent.click(screen.getByTestId('row-0'))
+ fireEvent.click(screen.getByTestId('row-2'), { ctrlKey: true })
+ expect(screen.getByTestId('row-2').dataset.selected).toBe('false')
+ fireEvent.click(screen.getByTestId('row-2'), { metaKey: true })
+ expect(screen.getByTestId('row-2').dataset.focused).toBe('true')
+ fireEvent.keyDown(screen.getByTestId('wrapper'), { key: 'ArrowDown' })
+ expect(screen.getByTestId('row-3').dataset.selected).toBe('true')
+ expect(screen.getByTestId('row-0').dataset.selected).toBe('false')
+ })
+
+ it('keeps Ctrl-click multi-selection on other platforms', () => {
+ render(<TestHarness items={makeItems(3)} nativeSelection />)
+ fireEvent.click(screen.getByTestId('row-0'))
+ fireEvent.click(screen.getByTestId('row-2'), { ctrlKey: true })
+ expect(screen.getByTestId('row-0').dataset.selected).toBe('true')
+ expect(screen.getByTestId('row-2').dataset.selected).toBe('true')
+ })
+
+ it('supports type-to-select and ignores composition and form controls', () => {
+ render(
+ <TestHarness
+ items={[
+ { id: 'a', name: 'Alpha' },
+ { id: 'b', name: 'Beta' },
+ { id: 'c', name: 'Bravo' },
+ ]}
+ nativeSelection
+ macOS
+ />
+ )
+ const wrapper = screen.getByTestId('wrapper')
+ fireEvent.keyDown(wrapper, { key: 'b' })
+ expect(screen.getByTestId('row-1').dataset.selected).toBe('true')
+ fireEvent.keyDown(wrapper, { key: 'b' })
+ expect(screen.getByTestId('row-2').dataset.selected).toBe('true')
+ fireEvent.keyDown(wrapper, { key: 'a', isComposing: true })
+ fireEvent.keyDown(screen.getByTestId('checkbox-0'), {
+ key: 'a',
+ metaKey: true,
+ })
+ expect(screen.getByTestId('row-0').dataset.selected).toBe('false')
+ expect(screen.getByTestId('row-2').dataset.selected).toBe('true')
+ })
+})
diff --git a/src/renderer/components/desktop-kit/hooks/use-selectable-list.ts b/src/renderer/components/desktop-kit/hooks/use-selectable-list.ts
index 3527c551..9ee47467 100644
--- a/src/renderer/components/desktop-kit/hooks/use-selectable-list.ts
+++ b/src/renderer/components/desktop-kit/hooks/use-selectable-list.ts
@@ -18,6 +18,10 @@ interface UseSelectableListOptions<T> {
headerHeight?: number
marquee?: boolean
store?: SelectionStore<T>
+ /** Opt in without changing the focus-only keyboard model of other lists. */
+ nativeSelection?: boolean
+ macOS?: boolean
+ getText?: (item: T) => string
}
interface RowProps {
@@ -60,7 +64,16 @@ interface UseSelectableListReturn<T> {
export function useSelectableList<T>(
options: UseSelectableListOptions<T>
): UseSelectableListReturn<T> {
- const { items, getId, rowHeight, headerHeight = 0, marquee = true } = options
+ const {
+ items,
+ getId,
+ rowHeight,
+ headerHeight = 0,
+ marquee = true,
+ nativeSelection = false,
+ macOS = false,
+ getText,
+ } = options
const listRef = useRef<VirtualListHandle | null>(null)
const containerRef = useRef<HTMLDivElement | null>(null)
@@ -75,18 +88,31 @@ export function useSelectableList<T>(
const selectedIds = store((s) => s.selectedIds)
const focusedIndex = store((s) => s.focusedIndex)
+ const focusedItemId = store((state) => {
+ const item =
+ state.focusedIndex === null ? undefined : state.items[state.focusedIndex]
+ return item ? getId(item) : null
+ })
+ const previousFocus = useRef<string | null>(null)
+ const typeSelection = useRef({ text: '', at: 0 })
// Also reveal focus after a filtered list remounts. A store subscription
// alone misses the initial setItems reindex before its listener attaches.
useEffect(() => {
- if (focusedIndex !== null) listRef.current?.scrollToIndex(focusedIndex)
- }, [focusedIndex])
+ if (
+ focusedIndex !== null &&
+ (!nativeSelection || previousFocus.current !== focusedItemId)
+ ) {
+ listRef.current?.scrollToIndex(focusedIndex)
+ }
+ previousFocus.current = focusedItemId
+ }, [focusedIndex, focusedItemId, nativeSelection])
const hasItems = items.length > 0
useEffect(() => {
const container = listRef.current?.getContainerRef()
if (!hasItems || !container || typeof ResizeObserver === 'undefined') return
- // Opening the inspector shrinks the scrollport without changing focus.
+ // Window and panel resizing can shrink the scrollport without changing focus.
// Observe after the virtualizer so its viewport measurement is current.
const observer = new ResizeObserver(() => {
const index = store.getState().focusedIndex
@@ -113,10 +139,13 @@ export function useSelectableList<T>(
focused: focusedIndex === index,
onClick: (e: ReactMouseEvent) => {
const state = store.getState()
+ if (nativeSelection && macOS && e.ctrlKey) return
if (e.shiftKey) {
- state.rangeSelect(index)
- } else if (e.ctrlKey || e.metaKey) {
+ if (nativeSelection) state.extendSelection(index)
+ else state.rangeSelect(index)
+ } else if (e.metaKey || (e.ctrlKey && (!nativeSelection || !macOS))) {
state.toggle(id)
+ if (nativeSelection) state.focus(id)
} else {
state.select(id)
}
@@ -126,7 +155,7 @@ export function useSelectableList<T>(
},
}
},
- [items, getId, selectedIds, focusedIndex, store]
+ [items, getId, selectedIds, focusedIndex, store, nativeSelection, macOS]
)
const headerCheckbox = useMemo((): HeaderCheckboxState => {
@@ -147,7 +176,78 @@ export function useSelectableList<T>(
const onKeyDown = useCallback(
(e: ReactKeyboardEvent) => {
+ if (e.defaultPrevented || e.nativeEvent.isComposing) return
+ if (
+ e.target instanceof Element &&
+ e.target.closest(
+ 'input, textarea, select, button, [contenteditable="true"], [role="menu"], [role="separator"]'
+ )
+ )
+ return
const state = store.getState()
+ if (nativeSelection) {
+ if (
+ (e.key === 'ArrowDown' || e.key === 'ArrowUp') &&
+ !e.metaKey &&
+ !e.ctrlKey &&
+ !e.altKey
+ ) {
+ e.preventDefault()
+ state.moveSelection(e.key === 'ArrowDown' ? 1 : -1, e.shiftKey)
+ const index = store.getState().focusedIndex
+ if (index !== null) listRef.current?.scrollToIndex(index)
+ return
+ }
+ if (
+ e.key.toLowerCase() === 'a' &&
+ (e.metaKey || (!macOS && e.ctrlKey))
+ ) {
+ e.preventDefault()
+ if (e.shiftKey) state.clearSelection()
+ else state.selectAll()
+ return
+ }
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ e.stopPropagation()
+ state.clearSelection()
+ return
+ }
+ if (
+ getText &&
+ e.key.length === 1 &&
+ !e.metaKey &&
+ !e.ctrlKey &&
+ !e.altKey
+ ) {
+ e.preventDefault()
+ const now = Date.now()
+ const key = e.key.toLocaleLowerCase()
+ const previous =
+ now - typeSelection.current.at < 700
+ ? typeSelection.current.text
+ : ''
+ const text = previous + key
+ typeSelection.current = { text, at: now }
+ const repeated = [...text].every((letter) => letter === key)
+ const prefix = repeated ? key : text
+ const from =
+ (state.focusedIndex ?? -1) + (previous && !repeated ? 0 : 1)
+ for (let offset = 0; offset < state.items.length; offset++) {
+ const index =
+ (((from + offset) % state.items.length) + state.items.length) %
+ state.items.length
+ if (
+ getText(state.items[index]).toLocaleLowerCase().startsWith(prefix)
+ ) {
+ state.select(getId(state.items[index]))
+ listRef.current?.scrollToIndex(index)
+ break
+ }
+ }
+ }
+ return
+ }
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
@@ -180,7 +280,7 @@ export function useSelectableList<T>(
break
}
},
- [store]
+ [store, nativeSelection, macOS, getText, getId]
)
const marqueeProps = useMemo(
diff --git a/src/renderer/components/desktop-kit/inspector-drawer.tsx b/src/renderer/components/desktop-kit/inspector-drawer.tsx
new file mode 100644
index 00000000..09c41906
--- /dev/null
+++ b/src/renderer/components/desktop-kit/inspector-drawer.tsx
@@ -0,0 +1,196 @@
+import {
+ Drawer,
+ DrawerBody,
+ DrawerHeader,
+ DrawerPopup,
+ DrawerPortal,
+ DrawerTitle,
+ DrawerViewport,
+} from '@renderer/components/ui/drawer'
+import { type ReactNode, useEffect, useRef, useState } from 'react'
+
+export type InspectorSnap = 'compact' | 'medium' | 'expanded'
+const SNAP_NAMES: InspectorSnap[] = ['compact', 'medium', 'expanded']
+
+export function getInspectorSnapHeights(availableHeight: number) {
+ const maximum = Math.max(
+ 1,
+ Math.min(Math.round(availableHeight * 0.75), availableHeight - 64)
+ )
+ // Keep useful detents at least 48px apart in short windows. The semantic
+ // preference survives merging, so resizing the window restores its intent.
+ const compact = maximum - 220 < 48 ? maximum : 220
+ let medium = Math.max(compact, Math.round(availableHeight * 0.5))
+ if (medium - compact < 48) medium = compact
+ if (maximum - medium < 48) medium = maximum
+ return [compact, medium, maximum] as const
+}
+
+export function InspectorDrawer({
+ container,
+ open,
+ snap,
+ onSnapChange,
+ onClose,
+ title,
+ resizeLabel,
+ renderHeader,
+ children,
+}: {
+ container: HTMLElement | null
+ open: boolean
+ snap: InspectorSnap
+ onSnapChange: (snap: InspectorSnap) => void
+ onClose: () => void
+ title: string
+ resizeLabel: string
+ renderHeader: (resizeHandle: ReactNode) => ReactNode
+ children: ReactNode
+}) {
+ const popupRef = useRef<HTMLDivElement>(null)
+ const [availableHeight, setAvailableHeight] = useState(600)
+ useEffect(() => {
+ if (!container) return
+ const measure = () => {
+ const height = container.getBoundingClientRect().height
+ if (height > 0) setAvailableHeight(height)
+ }
+ measure()
+ if (typeof ResizeObserver === 'undefined') return
+ const observer = new ResizeObserver(measure)
+ observer.observe(container)
+ return () => observer.disconnect()
+ }, [container])
+ const heights = getInspectorSnapHeights(availableHeight)
+ const maximum = heights[2]
+ const snapPoints = [...new Set(heights)]
+ const height = heights[SNAP_NAMES.indexOf(snap)]
+ const selectHeight = (point: number) => {
+ if (point === height || !snapPoints.includes(point)) return
+ onSnapChange(
+ point === maximum ? 'expanded' : SNAP_NAMES[heights.indexOf(point)]
+ )
+ }
+ if (!container) return null
+ return (
+ <Drawer
+ open={open}
+ modal={false}
+ disablePointerDismissal
+ swipeDirection="down"
+ snapPoints={snapPoints}
+ snapPoint={height}
+ snapToSequentialPoints
+ onSnapPointChange={(point) => {
+ if (typeof point === 'number') selectHeight(point)
+ }}
+ onOpenChange={(next, details) => {
+ if (next) return
+ if (details.reason === 'escape-key') {
+ const target = details.event.target
+ if (
+ !(target instanceof Node) ||
+ !popupRef.current?.contains(target) ||
+ (target instanceof Element &&
+ target.closest('[data-activity-detail-surface="true"]'))
+ ) {
+ details.cancel()
+ return
+ }
+ }
+ onClose()
+ }}
+ >
+ <DrawerPortal container={container}>
+ <DrawerViewport className="pointer-events-none absolute inset-0 z-30 flex items-end overflow-hidden">
+ <DrawerPopup
+ ref={popupRef}
+ initialFocus={false}
+ finalFocus={() =>
+ container.querySelector<HTMLElement>('[data-downloads-grid]')
+ }
+ aria-label={title}
+ className="downloads-inspector-popup pointer-events-auto w-full shadow-[0_-3px_12px_rgba(15,23,42,0.08)]"
+ style={{
+ height: maximum,
+ // Base UI registers these variables with inherits: false. Read
+ // them on the popup itself, keeping its offscreen portion out
+ // of the content's flex height at every snap and during swipes.
+ paddingBottom:
+ 'max(0px, calc(var(--drawer-snap-point-offset, 0px) + var(--drawer-swipe-movement-y, 0px)))',
+ }}
+ >
+ <div className="flex min-h-0 flex-1 flex-col">
+ <DrawerTitle className="sr-only">{title}</DrawerTitle>
+ <DrawerHeader
+ className="shrink-0 cursor-ns-resize touch-none select-none gap-0 p-0 [&_button]:cursor-default"
+ onPointerDown={(event) => {
+ if (
+ (event.target as Element).closest(
+ 'button, a, input, select, textarea, [role="button"]'
+ )
+ )
+ event.stopPropagation()
+ }}
+ onTouchStart={(event) => {
+ if (
+ (event.target as Element).closest(
+ 'button, a, input, select, textarea, [role="button"]'
+ )
+ )
+ event.stopPropagation()
+ }}
+ >
+ {renderHeader(
+ // biome-ignore lint/a11y/useSemanticElements: The header's empty space is a keyboard-adjustable drawer resize control.
+ <div
+ role="separator"
+ tabIndex={0}
+ aria-orientation="horizontal"
+ aria-label={resizeLabel}
+ aria-valuemin={snapPoints[0]}
+ aria-valuemax={maximum}
+ aria-valuenow={height}
+ className="min-w-6 flex-1 self-stretch outline-none focus-visible:shadow-[inset_0_-1px_0_var(--ring)]"
+ onKeyDown={(event) => {
+ if (
+ !['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(
+ event.key
+ )
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.key === 'Home') onSnapChange('compact')
+ else if (event.key === 'End') onSnapChange('expanded')
+ else {
+ const index = snapPoints.indexOf(height)
+ selectHeight(
+ snapPoints[
+ Math.max(
+ 0,
+ Math.min(
+ snapPoints.length - 1,
+ index + (event.key === 'ArrowUp' ? 1 : -1)
+ )
+ )
+ ]
+ )
+ }
+ }}
+ />
+ )}
+ </DrawerHeader>
+ <DrawerBody
+ data-base-ui-swipe-ignore
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ {children}
+ </DrawerBody>
+ </div>
+ </DrawerPopup>
+ </DrawerViewport>
+ </DrawerPortal>
+ </Drawer>
+ )
+}
diff --git a/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.test.tsx b/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.test.tsx
index a8acd410..17085f4b 100644
--- a/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.test.tsx
+++ b/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.test.tsx
@@ -88,6 +88,39 @@ afterEach(() => {
})
describe('MarqueeOverlay', () => {
+ it('keeps an active drag when selection feedback replaces parent callbacks', () => {
+ const { container } = createMockContainer()
+ const containerRef = { current: container }
+ const firstChange = vi.fn()
+ const nextChange = vi.fn()
+ const firstEnd = vi.fn()
+ const nextEnd = vi.fn()
+ const tree = (
+ onSelectionChange: typeof firstChange,
+ onSelectionEnd: typeof firstEnd
+ ) => (
+ <MarqueeOverlay
+ containerRef={containerRef}
+ rowHeight={40}
+ totalCount={100}
+ onSelectionChange={onSelectionChange}
+ onSelectionEnd={onSelectionEnd}
+ />
+ )
+ const view = render(tree(firstChange, firstEnd))
+ fireEvent.mouseDown(container, { clientX: 100, clientY: 120 })
+ fireEvent.mouseMove(window, { clientX: 140, clientY: 180 })
+ flushAnimationFrames()
+ expect(firstChange).toHaveBeenLastCalledWith(3, 4)
+ view.rerender(tree(nextChange, nextEnd))
+ fireEvent.mouseMove(window, { clientX: 180, clientY: 260 })
+ flushAnimationFrames()
+ expect(nextChange).toHaveBeenLastCalledWith(3, 6)
+ expect(screen.getByTestId('marquee-box').style.opacity).toBe('1')
+ fireEvent.mouseUp(window)
+ expect(firstEnd).not.toHaveBeenCalled()
+ expect(nextEnd).toHaveBeenCalledOnce()
+ })
it('keeps one box node mounted and updates its geometry imperatively', () => {
const { container } = createMockContainer()
renderOverlay(container)
diff --git a/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.tsx b/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.tsx
index 79f332a8..d4a1e4e0 100644
--- a/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.tsx
+++ b/src/renderer/components/desktop-kit/marquee-selection/marquee-overlay.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef } from 'react'
+import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
import type { DragState, MarqueeOverlayProps } from './types'
import { useAutoScroll } from './use-auto-scroll'
@@ -35,6 +35,12 @@ export function MarqueeOverlay(props: MarqueeOverlayProps) {
const boxRef = useRef<SVGRectElement | null>(null)
const dragRef = useRef<DragState | null>(null)
const rafRef = useRef<number | null>(null)
+ // Selection feedback rerenders the parent while the pointer is still down.
+ // Read its latest callbacks without tearing down the active gesture's listeners.
+ const selectionCallbacks = useRef({ onSelectionChange, onSelectionEnd })
+ useLayoutEffect(() => {
+ selectionCallbacks.current = { onSelectionChange, onSelectionEnd }
+ }, [onSelectionChange, onSelectionEnd])
const {
updatePointer: updateAutoScrollPointer,
@@ -93,9 +99,12 @@ export function MarqueeOverlay(props: MarqueeOverlayProps) {
container.scrollTop
)
if (range.startIndex <= range.endIndex) {
- onSelectionChange(range.startIndex, range.endIndex)
+ selectionCallbacks.current.onSelectionChange(
+ range.startIndex,
+ range.endIndex
+ )
}
- }, [computeIndices, containerRef, onSelectionChange])
+ }, [computeIndices, containerRef])
const renderDragFrame = useCallback(
(timestamp: number) => {
@@ -123,6 +132,14 @@ export function MarqueeOverlay(props: MarqueeOverlayProps) {
const onMouseDown = useCallback(
(event: MouseEvent) => {
if (!enabled || event.button !== 0) return
+ if (event.ctrlKey || event.metaKey || event.shiftKey) return
+ if (
+ event.target instanceof Element &&
+ event.target.closest(
+ 'button, input, [role="separator"], [role="columnheader"], [data-slot="scroll-area-scrollbar"]'
+ )
+ )
+ return
const container = containerRef.current
if (!container) return
@@ -195,7 +212,7 @@ export function MarqueeOverlay(props: MarqueeOverlayProps) {
if (drag.active) {
paintDragFrame()
- onSelectionEnd()
+ selectionCallbacks.current.onSelectionEnd()
}
hideBox()
@@ -205,7 +222,7 @@ export function MarqueeOverlay(props: MarqueeOverlayProps) {
cancelAnimationFrame(rafRef.current)
rafRef.current = null
}
- }, [hideBox, onSelectionEnd, paintDragFrame, stopAutoScroll])
+ }, [hideBox, paintDragFrame, stopAutoScroll])
useEffect(() => {
const container = containerRef.current
diff --git a/src/renderer/components/desktop-kit/panel/header-action-button.tsx b/src/renderer/components/desktop-kit/panel/header-action-button.tsx
index 9fcdde7d..817c41b3 100644
--- a/src/renderer/components/desktop-kit/panel/header-action-button.tsx
+++ b/src/renderer/components/desktop-kit/panel/header-action-button.tsx
@@ -52,7 +52,7 @@ export function HeaderActionButton({
variant={variant}
size="sm"
aria-label={label}
- className={compact ? COMPACT_ACTION_CLASS : undefined}
+ className={compact ? COMPACT_ACTION_CLASS : 'h-9'}
onClick={onClick}
disabled={disabled}
>
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
index 272bb613..f6b68c98 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
@@ -41,7 +41,7 @@ describe('PanelShell', () => {
</PanelShell>
)
const input = screen.getByPlaceholderText('Filter…')
- // The 28px compact row: h-8 input shrinks to h-7 and narrows so it
+ // The 28px compact row: h-9 input shrinks to h-7 and narrows so it
// does not crowd the short header next to the window chrome.
expect(input).toHaveClass('compact-header:h-7')
expect(input).toHaveClass('compact-header:w-40')
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
index 65be454f..c60794c4 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
@@ -19,6 +19,7 @@ export interface PanelShellProps {
footer?: React.ReactNode
children: React.ReactNode
headerClassName?: string
+ actionsClassName?: string
contentClassName?: string
}
@@ -30,6 +31,7 @@ export function PanelShell({
footer,
children,
headerClassName,
+ actionsClassName,
contentClassName,
}: PanelShellProps) {
return (
@@ -37,7 +39,9 @@ export function PanelShell({
{/* PanelShell header */}
<header
className={cn(
- 'flex shrink-0 items-start justify-between gap-4 px-6 pt-9 pb-4 transition-[padding] duration-200',
+ // Standard headers retain the 36px clearance below window controls.
+ // A 36px action row and 8px bottom padding make an 80px header.
+ 'flex shrink-0 items-center justify-between gap-4 px-6 pt-9 pb-2 transition-[padding] duration-200 motion-reduce:transition-none',
// Compact rows center on the window-chrome icon line: the overlay
// strip renders its 28px buttons at window y 13..41 (pt-[14px]
// wrapper in AppLayout), i.e. centerline y=27. The inset sits 8px
@@ -59,7 +63,10 @@ export function PanelShell({
data-slot="panel-shell-actions"
// Keep actions above the z-30 WindowChrome drag strip but below the
// z-50 modal layer so dialogs always cover background controls.
- className="app-no-drag relative z-40 flex shrink-0 items-center gap-2"
+ className={cn(
+ 'app-no-drag relative z-40 flex min-h-9 shrink-0 items-center gap-2 compact-header:min-h-7',
+ actionsClassName
+ )}
>
{actionsPosition === 'start' && actions}
{search && (
@@ -67,7 +74,7 @@ export function PanelShell({
value={search.value}
onChange={(e) => search.onChange(e.target.value)}
placeholder={search.placeholder}
- className="h-8 w-56 text-sm placeholder:text-xs compact-header:h-7 compact-header:w-40"
+ className="h-9 w-56 text-sm placeholder:text-xs compact-header:h-7 compact-header:w-40"
/>
)}
{actionsPosition === 'end' && actions}
diff --git a/src/renderer/components/desktop-kit/resize-handle.tsx b/src/renderer/components/desktop-kit/resize-handle.tsx
new file mode 100644
index 00000000..2f99294f
--- /dev/null
+++ b/src/renderer/components/desktop-kit/resize-handle.tsx
@@ -0,0 +1,95 @@
+import { useRef } from 'react'
+
+interface ResizeHandleProps {
+ label: string
+ orientation: 'horizontal' | 'vertical'
+ value: number
+ min: number
+ max: number
+ /** A bottom pane grows upwards; a column grows to the right. */
+ reverse?: boolean
+ className?: string
+ onChange: (value: number) => void
+ onCommit: (value: number) => void
+}
+
+export function ResizeHandle({
+ label,
+ orientation,
+ value,
+ min,
+ max,
+ reverse,
+ className,
+ onChange,
+ onCommit,
+}: ResizeHandleProps) {
+ const drag = useRef<{
+ coordinate: number
+ value: number
+ current: number
+ } | null>(null)
+ const clamp = (next: number) => Math.round(Math.max(min, Math.min(max, next)))
+ return (
+ // biome-ignore lint/a11y/useSemanticElements: Interactive window splitter, not a thematic break.
+ <div
+ role="separator"
+ tabIndex={0}
+ aria-label={label}
+ aria-orientation={orientation}
+ aria-valuemin={min}
+ aria-valuemax={max}
+ aria-valuenow={Math.round(value)}
+ className={className}
+ onClick={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ onPointerDown={(event) => {
+ if (event.button !== 0) return
+ event.preventDefault()
+ event.stopPropagation()
+ event.currentTarget.focus({ preventScroll: true })
+ event.currentTarget.setPointerCapture(event.pointerId)
+ drag.current = {
+ coordinate:
+ orientation === 'vertical' ? event.clientX : event.clientY,
+ value,
+ current: value,
+ }
+ }}
+ onPointerMove={(event) => {
+ const start = drag.current
+ if (!start) return
+ const coordinate =
+ orientation === 'vertical' ? event.clientX : event.clientY
+ start.current = clamp(
+ start.value + (coordinate - start.coordinate) * (reverse ? -1 : 1)
+ )
+ onChange(start.current)
+ }}
+ onPointerUp={(event) => {
+ if (!drag.current) return
+ onCommit(drag.current.current)
+ drag.current = null
+ event.currentTarget.releasePointerCapture(event.pointerId)
+ }}
+ onPointerCancel={() => {
+ if (drag.current) onChange(drag.current.value)
+ drag.current = null
+ }}
+ onKeyDown={(event) => {
+ event.stopPropagation()
+ const decrease = orientation === 'vertical' ? 'ArrowLeft' : 'ArrowDown'
+ const increase = orientation === 'vertical' ? 'ArrowRight' : 'ArrowUp'
+ if (![decrease, increase, 'Home', 'End'].includes(event.key)) return
+ event.preventDefault()
+ onCommit(
+ event.key === 'Home'
+ ? min
+ : event.key === 'End'
+ ? max
+ : clamp(value + (event.key === increase ? 16 : -16))
+ )
+ }}
+ />
+ )
+}
diff --git a/src/renderer/components/desktop-kit/selection/create-selection-store.ts b/src/renderer/components/desktop-kit/selection/create-selection-store.ts
index 928ea5b1..8638a074 100644
--- a/src/renderer/components/desktop-kit/selection/create-selection-store.ts
+++ b/src/renderer/components/desktop-kit/selection/create-selection-store.ts
@@ -257,6 +257,37 @@ export function createSelectionStore<T>(
set({ focusedIndex: next })
},
+ focus(id: string) {
+ const index = indexById.get(id)
+ if (index === undefined) return
+ focusedId = id
+ set({ focusedIndex: index })
+ },
+
+ extendSelection(toIndex: number) {
+ const { items, focusedIndex, lastActionIndex } = get()
+ if (items.length === 0) return
+ const target = clamp(toIndex, 0, items.length - 1)
+ if (lastActionIndex === null) {
+ const anchor = focusedIndex ?? target
+ lastActionId = getId(items[anchor])
+ set({ lastActionIndex: anchor })
+ }
+ get().rangeSelect(target)
+ get().focus(getId(items[target]))
+ },
+
+ moveSelection(delta: number, extend = false) {
+ const { focusedIndex, items } = get()
+ if (items.length === 0) return
+ const next =
+ focusedIndex === null
+ ? 0
+ : clamp(focusedIndex + delta, 0, items.length - 1)
+ if (extend) get().extendSelection(next)
+ else get().select(getId(items[next]))
+ },
+
focusedSelect() {
resetMarqueeRange()
const { focusedIndex, items } = get()
diff --git a/src/renderer/components/desktop-kit/selection/types.ts b/src/renderer/components/desktop-kit/selection/types.ts
index 77df4766..964be371 100644
--- a/src/renderer/components/desktop-kit/selection/types.ts
+++ b/src/renderer/components/desktop-kit/selection/types.ts
@@ -28,6 +28,9 @@ export interface SelectionState<T> {
moveFocus: (delta: number) => void
focusedSelect: () => void
shiftMoveFocus: (delta: number) => void
+ focus: (id: string) => void
+ extendSelection: (toIndex: number) => void
+ moveSelection: (delta: number, extend?: boolean) => void
// Queries
isSelected: (id: string) => boolean
diff --git a/src/renderer/components/desktop-kit/toolbar-glass/displacement-map.test.ts b/src/renderer/components/desktop-kit/toolbar-glass/displacement-map.test.ts
new file mode 100644
index 00000000..6c8ecdf9
--- /dev/null
+++ b/src/renderer/components/desktop-kit/toolbar-glass/displacement-map.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { createDisplacementMap } from './displacement-map'
+
+describe('toolbar glass displacement', () => {
+ it.each([
+ [104, 36],
+ [86, 30],
+ [230, 36],
+ [30, 30],
+ ])(
+ 'keeps the center neutral and bends only the capsule rim at %i × %i',
+ (width, height) => {
+ const map = createDisplacementMap(width, height)
+ const pixel = (x: number, y: number) =>
+ Array.from(map.slice((y * width + x) * 4, (y * width + x) * 4 + 4))
+ expect(pixel(Math.floor(width / 2), Math.floor(height / 2))).toEqual([
+ 128, 128, 128, 255,
+ ])
+ // Outside a rounded corner is neutral, not a diagonal/sheared lens.
+ expect(pixel(0, 0)).toEqual([128, 128, 128, 255])
+ const top = pixel(Math.floor(width / 2), 0)
+ const bottom = pixel(Math.floor(width / 2), height - 1)
+ expect(top[1]).toBeGreaterThan(128)
+ expect(bottom[1]).toBeLessThan(128)
+ expect(top[1] + bottom[1]).toBe(256)
+ const left = pixel(0, Math.floor(height / 2))
+ const right = pixel(width - 1, Math.floor(height / 2))
+ expect(left[0]).toBeGreaterThan(128)
+ expect(right[0]).toBeLessThan(128)
+ expect(left[0] + right[0]).toBe(256)
+ }
+ )
+})
diff --git a/src/renderer/components/desktop-kit/toolbar-glass/displacement-map.ts b/src/renderer/components/desktop-kit/toolbar-glass/displacement-map.ts
new file mode 100644
index 00000000..4ca982ba
--- /dev/null
+++ b/src/renderer/components/desktop-kit/toolbar-glass/displacement-map.ts
@@ -0,0 +1,25 @@
+// A capsule has a flat center and a narrow curved rim. Encode the rim's
+// inward sampling offset in R/G; neutral gray leaves the center undistorted.
+export function createDisplacementMap(width: number, height: number) {
+ const pixels = new Uint8ClampedArray(width * height * 4)
+ const radius = Math.min(width, height) / 2
+ const rim = Math.min(5, radius / 3)
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const px = x + 0.5
+ const py = y + 0.5
+ const dx = px - Math.max(radius, Math.min(width - radius, px))
+ const dy = py - Math.max(radius, Math.min(height - radius, py))
+ const distance = Math.hypot(dx, dy)
+ const depth = radius - distance
+ const bend = depth >= 0 && depth < rim ? (1 - depth / rim) ** 2 : 0
+ const offset = (y * width + x) * 4
+ pixels[offset] = 128 - (dx / (distance || 1)) * bend * 127
+ pixels[offset + 1] = 128 - (dy / (distance || 1)) * bend * 127
+ pixels[offset + 2] = 128
+ pixels[offset + 3] = 255
+ }
+ }
+ return pixels
+}
diff --git a/src/renderer/components/desktop-kit/toolbar-glass/toolbar-glass.css b/src/renderer/components/desktop-kit/toolbar-glass/toolbar-glass.css
new file mode 100644
index 00000000..5520265d
--- /dev/null
+++ b/src/renderer/components/desktop-kit/toolbar-glass/toolbar-glass.css
@@ -0,0 +1,37 @@
+.toolbar-glass-surface {
+ position: relative;
+ isolation: isolate;
+}
+
+.toolbar-glass-surface:has(> .toolbar-glass) {
+ background: transparent;
+}
+
+.toolbar-glass {
+ position: absolute;
+ inset: 0;
+ z-index: -1;
+ pointer-events: none;
+ border-radius: inherit;
+ background: rgb(255 255 255 / 58%);
+ backdrop-filter: blur(8px) saturate(1.08);
+ box-shadow:
+ inset 0 1px 0 rgb(255 255 255 / 80%),
+ inset 0 -1px 0 rgb(90 100 115 / 8%),
+ 0 2px 5px rgb(20 30 45 / 5%);
+}
+
+.dark .toolbar-glass {
+ background: rgb(42 44 48 / 66%);
+ box-shadow:
+ inset 0 1px 0 rgb(255 255 255 / 13%),
+ inset 0 -1px 0 rgb(0 0 0 / 16%),
+ 0 2px 5px rgb(0 0 0 / 12%);
+}
+
+@media (prefers-reduced-transparency: reduce), (prefers-contrast: more),
+ (forced-colors: active) {
+ .toolbar-glass-surface {
+ background: var(--background);
+ }
+}
diff --git a/src/renderer/components/desktop-kit/toolbar-glass/toolbar-glass.tsx b/src/renderer/components/desktop-kit/toolbar-glass/toolbar-glass.tsx
new file mode 100644
index 00000000..9d5b9529
--- /dev/null
+++ b/src/renderer/components/desktop-kit/toolbar-glass/toolbar-glass.tsx
@@ -0,0 +1,137 @@
+import { useEffect, useId, useRef, useState, useSyncExternalStore } from 'react'
+import { createDisplacementMap } from './displacement-map'
+import './toolbar-glass.css'
+
+const SOLID_MATERIAL_QUERY =
+ '(prefers-reduced-transparency: reduce), (prefers-contrast: more), (forced-colors: active)'
+
+function solidMaterialRequested() {
+ return window.matchMedia?.(SOLID_MATERIAL_QUERY).matches === true
+}
+
+function subscribeMaterialPreference(listener: () => void) {
+ const query = window.matchMedia?.(SOLID_MATERIAL_QUERY)
+ query?.addEventListener('change', listener)
+ return () => query?.removeEventListener('change', listener)
+}
+
+/** Decorative background only; the existing controls keep their DOM and focus. */
+export function ToolbarGlass({ enabled }: { enabled: boolean }) {
+ const solid = useSyncExternalStore(
+ subscribeMaterialPreference,
+ solidMaterialRequested,
+ () => true
+ )
+ return enabled && !solid ? <GlassLayer /> : null
+}
+
+function GlassLayer() {
+ const id = `toolbar-glass-${useId().replaceAll(':', '')}`
+ const layerRef = useRef<HTMLSpanElement>(null)
+ const imageRef = useRef<SVGFEImageElement>(null)
+ const [ready, setReady] = useState(false)
+
+ useEffect(() => {
+ const layer = layerRef.current
+ // SVG backdrop filters are supported by Electron/Chromium. Other web
+ // engines retain the CSS frost; syntax acceptance alone is insufficient.
+ const chromium =
+ __MOTRIX_TARGET__ === 'electron' ||
+ /Chrom(e|ium)\//.test(navigator.userAgent)
+ if (
+ !layer ||
+ !chromium ||
+ typeof CSS === 'undefined' ||
+ !CSS.supports('backdrop-filter', `url("#${id}")`)
+ )
+ return
+ const canvas = document.createElement('canvas')
+ const context = canvas.getContext('2d')
+ if (!context) return
+ let frame = 0
+ let lastSize = ''
+
+ const update = () => {
+ frame = 0
+ const bounds = layer.getBoundingClientRect()
+ if (bounds.width < 1 || bounds.height < 1) return
+ // CSS-pixel maps suffice for this small, softly refracted rim. Bound
+ // allocations even if an unexpected layout stretches the surface.
+ const width = Math.min(1024, Math.round(bounds.width))
+ const height = Math.min(128, Math.round(bounds.height))
+ const size = `${width}:${height}`
+ if (lastSize === size) return
+ lastSize = size
+ canvas.width = width
+ canvas.height = height
+ const map = context.createImageData(width, height)
+ map.data.set(createDisplacementMap(width, height))
+ context.putImageData(map, 0, 0)
+ imageRef.current?.setAttribute('href', canvas.toDataURL())
+ setReady(true)
+ }
+ const schedule = () => {
+ if (!frame) frame = requestAnimationFrame(update)
+ }
+ schedule()
+ const observer = new ResizeObserver(schedule)
+ observer.observe(layer)
+ return () => {
+ observer.disconnect()
+ cancelAnimationFrame(frame)
+ canvas.width = 0
+ canvas.height = 0
+ }
+ }, [id])
+
+ return (
+ <span
+ ref={layerRef}
+ data-slot="toolbar-glass"
+ data-refraction={ready}
+ className="toolbar-glass"
+ aria-hidden="true"
+ style={
+ ready
+ ? { backdropFilter: `url("#${id}") blur(2px) saturate(1.08)` }
+ : undefined
+ }
+ >
+ {/* Percentage feImage dimensions need the real surface viewport. A
+ zero-sized SVG makes the map empty and shifts the entire backdrop. */}
+ <svg
+ className="absolute inset-0 size-full"
+ focusable="false"
+ aria-hidden="true"
+ >
+ <defs>
+ <filter
+ id={id}
+ x="0%"
+ y="0%"
+ width="100%"
+ height="100%"
+ colorInterpolationFilters="sRGB"
+ >
+ <feImage
+ ref={imageRef}
+ x="0%"
+ y="0%"
+ width="100%"
+ height="100%"
+ preserveAspectRatio="none"
+ result="rim"
+ />
+ <feDisplacementMap
+ in="SourceGraphic"
+ in2="rim"
+ scale="8"
+ xChannelSelector="R"
+ yChannelSelector="G"
+ />
+ </filter>
+ </defs>
+ </svg>
+ </span>
+ )
+}
diff --git a/src/renderer/components/desktop-kit/virtual-list/types.ts b/src/renderer/components/desktop-kit/virtual-list/types.ts
index 2f75b940..831bc746 100644
--- a/src/renderer/components/desktop-kit/virtual-list/types.ts
+++ b/src/renderer/components/desktop-kit/virtual-list/types.ts
@@ -6,6 +6,10 @@ export interface VirtualListProps<T> {
rowHeight: number
headerHeight?: number
overscan?: number
+ /** Keep an active ARIA descendant mounted without scrolling it into view. */
+ keepMountedIndex?: number
+ /** Opt into the shared cross-platform scrollbar without changing scroll ownership. */
+ scrollbar?: 'native' | 'custom'
scrollRef?: RefObject<HTMLDivElement | null>
renderRow: (props: RowRenderProps<T>) => ReactNode
renderHeader?: () => ReactNode
diff --git a/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx b/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
index 512be6ee..47c29b01 100644
--- a/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
+++ b/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
@@ -1,4 +1,14 @@
-import { useVirtualizer } from '@tanstack/react-virtual'
+import {
+ ScrollArea,
+ ScrollAreaContent,
+ ScrollAreaViewport,
+ ScrollBar,
+} from '@renderer/components/ui/scroll-area'
+import {
+ defaultRangeExtractor,
+ type Range,
+ useVirtualizer,
+} from '@tanstack/react-virtual'
import {
type ForwardedRef,
forwardRef,
@@ -19,6 +29,8 @@ function VirtualListInner<T>(
rowHeight,
headerHeight = 0,
overscan = 5,
+ keepMountedIndex,
+ scrollbar = 'native',
scrollRef,
renderRow,
renderHeader,
@@ -34,6 +46,22 @@ function VirtualListInner<T>(
(index: number) => getId(items[index]),
[getId, items]
)
+ const rangeExtractor = useCallback(
+ (range: Range) => {
+ const indices = defaultRangeExtractor(range)
+ if (
+ keepMountedIndex !== undefined &&
+ keepMountedIndex >= 0 &&
+ keepMountedIndex < items.length &&
+ !indices.includes(keepMountedIndex)
+ ) {
+ indices.push(keepMountedIndex)
+ indices.sort((a, b) => a - b)
+ }
+ return indices
+ },
+ [keepMountedIndex, items.length]
+ )
const virtualizer = useVirtualizer({
count: items.length,
getItemKey,
@@ -42,6 +70,7 @@ function VirtualListInner<T>(
getScrollElement: () => containerRef.current,
estimateSize: () => rowHeight,
overscan,
+ rangeExtractor,
})
useImperativeHandle(ref, () => ({
@@ -56,21 +85,63 @@ function VirtualListInner<T>(
},
}))
- if (items.length === 0 && renderEmpty) {
+ const content = (
+ <>
+ {renderHeader?.()}
+ {items.length === 0 && renderEmpty ? (
+ renderEmpty()
+ ) : (
+ <div
+ style={{
+ height: virtualizer.getTotalSize(),
+ width: '100%',
+ position: 'relative',
+ }}
+ >
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const item = items[virtualRow.index]
+ return (
+ <div
+ key={getId(item)}
+ data-index={virtualRow.index}
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: rowHeight,
+ transform: `translateY(${virtualRow.start - headerHeight}px)`,
+ }}
+ >
+ {renderRow({
+ item,
+ index: virtualRow.index,
+ style: { height: rowHeight },
+ })}
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </>
+ )
+
+ if (scrollbar === 'custom') {
return (
- <div
- ref={containerRef}
- data-testid="virtual-list-container"
- className={className}
- style={{
- overflow: 'auto',
- position: 'relative',
- ...style,
- }}
- >
- {renderHeader?.()}
- {renderEmpty()}
- </div>
+ <ScrollArea className={className} style={style}>
+ <ScrollAreaViewport
+ ref={containerRef}
+ data-testid="virtual-list-container"
+ tabIndex={-1}
+ className="relative"
+ >
+ <ScrollAreaContent style={{ minWidth: '100%' }}>
+ {content}
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar />
+ <ScrollBar orientation="horizontal" />
+ </ScrollArea>
)
}
@@ -79,44 +150,9 @@ function VirtualListInner<T>(
ref={containerRef}
data-testid="virtual-list-container"
className={className}
- style={{
- overflow: 'auto',
- position: 'relative',
- ...style,
- }}
+ style={{ overflow: 'auto', position: 'relative', ...style }}
>
- {renderHeader?.()}
- <div
- style={{
- height: virtualizer.getTotalSize(),
- width: '100%',
- position: 'relative',
- }}
- >
- {virtualizer.getVirtualItems().map((virtualRow) => {
- const item = items[virtualRow.index]
- return (
- <div
- key={getId(item)}
- data-index={virtualRow.index}
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- height: rowHeight,
- transform: `translateY(${virtualRow.start - headerHeight}px)`,
- }}
- >
- {renderRow({
- item,
- index: virtualRow.index,
- style: { height: rowHeight },
- })}
- </div>
- )
- })}
- </div>
+ {content}
</div>
)
}
diff --git a/src/renderer/components/speed-limit-modes.ts b/src/renderer/components/speed-limit-modes.ts
new file mode 100644
index 00000000..235a66c9
--- /dev/null
+++ b/src/renderer/components/speed-limit-modes.ts
@@ -0,0 +1,9 @@
+import type { TurtleState } from '@shared/types/settings'
+import { type LucideIcon, Rabbit, Squirrel, Turtle } from 'lucide-react'
+
+/** Shared mode order and glyphs for the dashboard and Downloads controls. */
+export const SPEED_LIMIT_MODES = [
+ { id: 'off', Icon: Rabbit },
+ { id: 'on', Icon: Turtle },
+ { id: 'auto', Icon: Squirrel },
+] as const satisfies ReadonlyArray<{ id: TurtleState; Icon: LucideIcon }>
diff --git a/src/renderer/components/ui/context-menu.tsx b/src/renderer/components/ui/context-menu.tsx
new file mode 100644
index 00000000..7acff1a4
--- /dev/null
+++ b/src/renderer/components/ui/context-menu.tsx
@@ -0,0 +1,57 @@
+import { ContextMenu as ContextMenuPrimitive } from '@base-ui/react/context-menu'
+import { cn } from '@renderer/lib/utils'
+import type * as React from 'react'
+
+// Base UI context menus share the Menu item primitives. Keep the same shadcn
+// styling and keyboard behavior as the application's dropdown menus.
+export {
+ DropdownMenuCheckboxItem as ContextMenuCheckboxItem,
+ DropdownMenuGroup as ContextMenuGroup,
+ DropdownMenuItem as ContextMenuItem,
+ DropdownMenuLabel as ContextMenuLabel,
+ DropdownMenuRadioGroup as ContextMenuRadioGroup,
+ DropdownMenuRadioItem as ContextMenuRadioItem,
+ DropdownMenuSeparator as ContextMenuSeparator,
+ DropdownMenuShortcut as ContextMenuShortcut,
+ DropdownMenuSub as ContextMenuSub,
+ DropdownMenuSubContent as ContextMenuSubContent,
+ DropdownMenuSubTrigger as ContextMenuSubTrigger,
+} from './dropdown-menu'
+
+export function ContextMenu(
+ props: React.ComponentProps<typeof ContextMenuPrimitive.Root>
+) {
+ return <ContextMenuPrimitive.Root {...props} />
+}
+
+export function ContextMenuTrigger(
+ props: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>
+) {
+ return (
+ <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
+ )
+}
+
+export function ContextMenuContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Popup>) {
+ return (
+ <ContextMenuPrimitive.Portal>
+ <ContextMenuPrimitive.Positioner
+ className="isolate z-50 outline-none"
+ sideOffset={2}
+ >
+ <ContextMenuPrimitive.Popup
+ data-slot="context-menu-content"
+ data-menu-density="compact"
+ className={cn(
+ 'z-50 max-h-(--available-height) min-w-48 overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md outline-none',
+ className
+ )}
+ {...props}
+ />
+ </ContextMenuPrimitive.Positioner>
+ </ContextMenuPrimitive.Portal>
+ )
+}
diff --git a/src/renderer/components/ui/drawer.tsx b/src/renderer/components/ui/drawer.tsx
index 8fa5f46d..5ebd892d 100644
--- a/src/renderer/components/ui/drawer.tsx
+++ b/src/renderer/components/ui/drawer.tsx
@@ -1,88 +1,102 @@
+import { Drawer as DrawerPrimitive } from '@base-ui/react/drawer'
import { cn } from '@renderer/lib/utils'
import type * as React from 'react'
-import { Drawer as DrawerPrimitive } from 'vaul'
-function Drawer({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
- return <DrawerPrimitive.Root data-slot="drawer" {...props} />
+export function Drawer(
+ props: React.ComponentProps<typeof DrawerPrimitive.Root>
+) {
+ return <DrawerPrimitive.Root {...props} />
}
-
-function DrawerTrigger({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
+export function DrawerTrigger(
+ props: React.ComponentProps<typeof DrawerPrimitive.Trigger>
+) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
}
-
-function DrawerPortal({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
+export function DrawerPortal(
+ props: React.ComponentProps<typeof DrawerPrimitive.Portal>
+) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}
-
-function DrawerClose({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
+export function DrawerClose(
+ props: React.ComponentProps<typeof DrawerPrimitive.Close>
+) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}
-
-function DrawerOverlay({
+export function DrawerOverlay({
className,
...props
-}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
+}: React.ComponentProps<typeof DrawerPrimitive.Backdrop>) {
return (
- <DrawerPrimitive.Overlay
+ <DrawerPrimitive.Backdrop
data-slot="drawer-overlay"
+ className={cn('fixed inset-0 z-50 bg-black/50', className)}
+ {...props}
+ />
+ )
+}
+export function DrawerViewport(
+ props: React.ComponentProps<typeof DrawerPrimitive.Viewport>
+) {
+ return <DrawerPrimitive.Viewport data-slot="drawer-viewport" {...props} />
+}
+export function DrawerPopup({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Popup>) {
+ return (
+ <DrawerPrimitive.Popup
+ data-slot="drawer-content"
className={cn(
- 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
+ 'flex flex-col border-t bg-background outline-none',
className
)}
{...props}
/>
)
}
-
-function DrawerContent({
+export function DrawerContent({
className,
children,
...props
-}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
+}: React.ComponentProps<typeof DrawerPrimitive.Popup>) {
return (
- <DrawerPortal data-slot="drawer-portal">
+ <DrawerPortal>
<DrawerOverlay />
- <DrawerPrimitive.Content
- data-slot="drawer-content"
- className={cn(
- 'group/drawer-content fixed z-50 flex h-auto flex-col bg-background',
- 'data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b',
- 'data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t',
- 'data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm',
- 'data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm',
- className
- )}
- {...props}
- >
- <div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
- {children}
- </DrawerPrimitive.Content>
+ <DrawerViewport className="fixed inset-0 z-50 flex items-end">
+ <DrawerPopup
+ className={cn(
+ 'max-h-[calc(100dvh-6rem)] w-full rounded-t-lg',
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </DrawerPopup>
+ </DrawerViewport>
</DrawerPortal>
)
}
-
-function DrawerHeader({ className, ...props }: React.ComponentProps<'div'>) {
+export function DrawerBody(
+ props: React.ComponentProps<typeof DrawerPrimitive.Content>
+) {
+ return <DrawerPrimitive.Content {...props} />
+}
+export function DrawerHeader({
+ className,
+ ...props
+}: React.ComponentProps<'div'>) {
return (
<div
data-slot="drawer-header"
- className={cn(
- 'flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left',
- className
- )}
+ className={cn('flex flex-col gap-1 p-4', className)}
{...props}
/>
)
}
-
-function DrawerFooter({ className, ...props }: React.ComponentProps<'div'>) {
+export function DrawerFooter({
+ className,
+ ...props
+}: React.ComponentProps<'div'>) {
return (
<div
data-slot="drawer-footer"
@@ -91,21 +105,19 @@ function DrawerFooter({ className, ...props }: React.ComponentProps<'div'>) {
/>
)
}
-
-function DrawerTitle({
+export function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
- className={cn('font-semibold text-foreground', className)}
+ className={cn('font-semibold', className)}
{...props}
/>
)
}
-
-function DrawerDescription({
+export function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
@@ -117,16 +129,3 @@ function DrawerDescription({
/>
)
}
-
-export {
- Drawer,
- DrawerClose,
- DrawerContent,
- DrawerDescription,
- DrawerFooter,
- DrawerHeader,
- DrawerOverlay,
- DrawerPortal,
- DrawerTitle,
- DrawerTrigger,
-}
diff --git a/src/renderer/components/ui/dropdown-menu.tsx b/src/renderer/components/ui/dropdown-menu.tsx
index 7532a1d7..50f2db60 100644
--- a/src/renderer/components/ui/dropdown-menu.tsx
+++ b/src/renderer/components/ui/dropdown-menu.tsx
@@ -1,3 +1,4 @@
+import './menu-density.css'
import { Menu as DropdownMenuPrimitive } from '@base-ui/react/menu'
import { cn } from '@renderer/lib/utils'
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'
@@ -51,6 +52,7 @@ function DropdownMenuContent({
>
<DropdownMenuPrimitive.Popup
data-slot="dropdown-menu-content"
+ style={{ outline: 'none' }}
className={cn(
'z-50 max-h-(--available-height) min-w-[8rem] origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
className
@@ -133,22 +135,28 @@ function DropdownMenuRadioGroup({
function DropdownMenuRadioItem({
className,
children,
+ showIndicator = true,
...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
+}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem> & {
+ showIndicator?: boolean
+}) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ !showIndicator && 'pl-2',
className
)}
{...props}
>
- <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
- <DropdownMenuPrimitive.RadioItemIndicator>
- <CircleIcon className="size-2 fill-current" />
- </DropdownMenuPrimitive.RadioItemIndicator>
- </span>
+ {showIndicator && (
+ <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.RadioItemIndicator>
+ <CircleIcon className="size-2 fill-current" />
+ </DropdownMenuPrimitive.RadioItemIndicator>
+ </span>
+ )}
{children}
</DropdownMenuPrimitive.RadioItem>
)
@@ -195,7 +203,7 @@ function DropdownMenuShortcut({
<span
data-slot="dropdown-menu-shortcut"
className={cn(
- 'ml-auto text-xs tracking-widest text-muted-foreground',
+ 'ms-auto shrink-0 whitespace-nowrap text-xs text-muted-foreground',
className
)}
{...props}
@@ -251,6 +259,7 @@ function DropdownMenuSubContent({
>
<DropdownMenuPrimitive.Popup
data-slot="dropdown-menu-sub-content"
+ style={{ outline: 'none' }}
className={cn(
'z-50 min-w-[8rem] origin-(--transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
className
diff --git a/src/renderer/components/ui/menu-density.css b/src/renderer/components/ui/menu-density.css
new file mode 100644
index 00000000..dbfd4fbe
--- /dev/null
+++ b/src/renderer/components/ui/menu-density.css
@@ -0,0 +1,24 @@
+[data-menu-density="compact"] [role^="menuitem"] {
+ min-height: 26px;
+ padding-top: 3px;
+ padding-bottom: 3px;
+ font-size: 12px;
+ line-height: 20px;
+}
+[data-menu-density="compact"] [data-slot="dropdown-menu-label"] {
+ padding-top: 3px;
+ padding-bottom: 3px;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+[data-menu-density="compact"] [role="separator"] {
+ margin-top: 3px;
+ margin-bottom: 3px;
+}
+[data-menu-density="compact"] [data-slot="dropdown-menu-shortcut"] {
+ margin-inline-start: auto;
+ padding-inline-start: 12px;
+ font-size: 11px;
+ line-height: inherit;
+ letter-spacing: normal;
+}
diff --git a/src/renderer/components/ui/popover.tsx b/src/renderer/components/ui/popover.tsx
index f2b643f0..a535fc98 100644
--- a/src/renderer/components/ui/popover.tsx
+++ b/src/renderer/components/ui/popover.tsx
@@ -20,15 +20,17 @@ function PopoverContent({
sideOffset = 4,
alignOffset,
side,
+ anchor,
...props
}: PopoverPrimitive.Popup.Props &
Pick<
PopoverPrimitive.Positioner.Props,
- 'align' | 'alignOffset' | 'side' | 'sideOffset'
+ 'align' | 'alignOffset' | 'side' | 'sideOffset' | 'anchor'
>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Positioner
+ anchor={anchor}
align={align}
alignOffset={alignOffset}
side={side}
diff --git a/src/renderer/components/ui/scroll-area.tsx b/src/renderer/components/ui/scroll-area.tsx
new file mode 100644
index 00000000..d51e313a
--- /dev/null
+++ b/src/renderer/components/ui/scroll-area.tsx
@@ -0,0 +1,67 @@
+import { ScrollArea as ScrollAreaPrimitive } from '@base-ui/react/scroll-area'
+import { cn } from '@renderer/lib/utils'
+import type { ComponentProps } from 'react'
+
+export function ScrollArea({
+ className,
+ ...props
+}: ComponentProps<typeof ScrollAreaPrimitive.Root>) {
+ return (
+ <ScrollAreaPrimitive.Root
+ data-slot="scroll-area"
+ className={cn('relative min-h-0 overflow-hidden', className)}
+ {...props}
+ />
+ )
+}
+
+export function ScrollAreaViewport({
+ className,
+ ...props
+}: ComponentProps<typeof ScrollAreaPrimitive.Viewport>) {
+ return (
+ <ScrollAreaPrimitive.Viewport
+ data-slot="scroll-area-viewport"
+ className={cn(
+ 'size-full rounded-[inherit] outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring',
+ className
+ )}
+ style={{ overflow: 'auto' }}
+ {...props}
+ />
+ )
+}
+
+export function ScrollAreaContent(
+ props: ComponentProps<typeof ScrollAreaPrimitive.Content>
+) {
+ return (
+ <ScrollAreaPrimitive.Content data-slot="scroll-area-content" {...props} />
+ )
+}
+
+export function ScrollBar({
+ className,
+ orientation = 'vertical',
+ ...props
+}: ComponentProps<typeof ScrollAreaPrimitive.Scrollbar>) {
+ return (
+ <ScrollAreaPrimitive.Scrollbar
+ data-slot="scroll-area-scrollbar"
+ orientation={orientation}
+ className={cn(
+ 'absolute z-20 flex touch-none select-none p-0.5 opacity-0 transition-opacity duration-150 data-hovering:opacity-100 data-scrolling:opacity-100 focus-within:opacity-100 motion-reduce:transition-none',
+ orientation === 'vertical'
+ ? 'inset-y-0 right-0 w-2.5 data-has-overflow-x:bottom-2.5'
+ : 'inset-x-0 bottom-0 h-2.5 flex-col data-has-overflow-y:right-2.5',
+ className
+ )}
+ {...props}
+ >
+ <ScrollAreaPrimitive.Thumb
+ data-slot="scroll-area-thumb"
+ className="relative flex-1 rounded-full bg-foreground/25 hover:bg-foreground/40"
+ />
+ </ScrollAreaPrimitive.Scrollbar>
+ )
+}
diff --git a/src/renderer/hooks/use-byte-format.ts b/src/renderer/hooks/use-byte-format.ts
index d45ac61c..b67ca67e 100644
--- a/src/renderer/hooks/use-byte-format.ts
+++ b/src/renderer/hooks/use-byte-format.ts
@@ -8,6 +8,7 @@ import {
type ByteValue,
formatBytes,
formatSpeed,
+ formatSpeedLimit,
} from '@shared/utils/format-bytes'
import { useSyncExternalStore } from 'react'
@@ -16,6 +17,7 @@ function createFormatters(unitSystem: ByteUnitSystem) {
unitSystem,
formatBytes: (bytes: ByteValue) => formatBytes(bytes, { unitSystem }),
formatSpeed: (bytes: ByteValue) => formatSpeed(bytes, unitSystem),
+ formatSpeedLimit: (bytes: ByteValue) => formatSpeedLimit(bytes, unitSystem),
}
}
diff --git a/src/renderer/hooks/use-liquid-glass.test.tsx b/src/renderer/hooks/use-liquid-glass.test.tsx
new file mode 100644
index 00000000..0ac20981
--- /dev/null
+++ b/src/renderer/hooks/use-liquid-glass.test.tsx
@@ -0,0 +1,62 @@
+import { transport } from '@renderer/lib/transport'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { beforeEach, expect, it, vi } from 'vitest'
+import { useLiquidGlass } from './use-liquid-glass'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ invoke: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
+ onConnectionChange: vi.fn(() => () => {}),
+ },
+}))
+
+beforeEach(() => vi.clearAllMocks())
+
+it('reads the saved setting and refreshes after changes and reconnects', async () => {
+ vi.mocked(transport.invoke).mockResolvedValue({
+ app: { liquidGlassEffect: true },
+ })
+ const { result, unmount } = renderHook(useLiquidGlass)
+ await waitFor(() => expect(result.current).toBe(true))
+ expect(transport.invoke).toHaveBeenCalledWith(Queries.GetSettings)
+ const change = vi
+ .mocked(transport.on)
+ .mock.calls.find(([event]) => event === Events.LiquidGlassChanged)![1]
+ vi.mocked(transport.invoke).mockResolvedValue({
+ app: { liquidGlassEffect: false },
+ })
+ await act(async () => change())
+ expect(result.current).toBe(false)
+ vi.mocked(transport.invoke).mockResolvedValue({
+ app: { liquidGlassEffect: true },
+ })
+ await act(async () => {
+ vi.mocked(transport.onConnectionChange!).mock.calls[0][0]({
+ state: 'connected',
+ })
+ })
+ expect(result.current).toBe(true)
+ unmount()
+ expect(transport.off).toHaveBeenCalledWith(Events.LiquidGlassChanged, change)
+})
+
+it('does not overwrite a newer preference with a stale initial snapshot', async () => {
+ let resolveInitial!: (value: unknown) => void
+ vi.mocked(transport.invoke)
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveInitial = resolve
+ })
+ )
+ .mockResolvedValue({ app: { liquidGlassEffect: false } })
+ const { result } = renderHook(useLiquidGlass)
+ const change = vi.mocked(transport.on).mock.calls[0][1]
+ await act(async () => change())
+ await act(async () => resolveInitial({ app: { liquidGlassEffect: true } }))
+ expect(result.current).toBe(false)
+})
diff --git a/src/renderer/hooks/use-liquid-glass.ts b/src/renderer/hooks/use-liquid-glass.ts
new file mode 100644
index 00000000..8e673764
--- /dev/null
+++ b/src/renderer/hooks/use-liquid-glass.ts
@@ -0,0 +1,20 @@
+import { transport } from '@renderer/lib/transport'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import type { AppSettings } from '@shared/types/settings'
+import { useState } from 'react'
+import { useTransportMirror } from './use-transport-mirror'
+
+export function useLiquidGlass(): boolean {
+ const [enabled, setEnabled] = useState(false)
+ useTransportMirror({
+ events: [Events.LiquidGlassChanged],
+ load: async (stale) => {
+ const settings = (await transport.invoke(
+ Queries.GetSettings
+ )) as AppSettings
+ if (!stale()) setEnabled(settings?.app?.liquidGlassEffect === true)
+ },
+ })
+ return enabled
+}
diff --git a/src/renderer/hooks/use-minute-clock.test.ts b/src/renderer/hooks/use-minute-clock.test.ts
index 92688ced..970eebbb 100644
--- a/src/renderer/hooks/use-minute-clock.test.ts
+++ b/src/renderer/hooks/use-minute-clock.test.ts
@@ -37,3 +37,32 @@ describe('useMinuteClock', () => {
expect(first.result.current).toBe(second.result.current)
})
})
+
+describe('minute clock resume', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-09-15T15:59:30Z'))
+ __resetMinuteClockForTests()
+ })
+ afterEach(() => {
+ __resetMinuteClockForTests()
+ vi.useRealTimers()
+ })
+ it.each(['focus', 'visibilitychange'])(
+ 'refreshes immediately on %s after sleep, with one timer',
+ (event) => {
+ const first = renderHook(() => useMinuteClock())
+ const second = renderHook(() => useMinuteClock())
+ vi.setSystemTime(new Date('2026-09-16T02:10:08Z'))
+ act(() =>
+ (event === 'focus' ? window : document).dispatchEvent(new Event(event))
+ )
+ expect(first.result.current).toBe(Date.now())
+ expect(second.result.current).toBe(Date.now())
+ expect(vi.getTimerCount()).toBe(1)
+ first.unmount()
+ second.unmount()
+ expect(vi.getTimerCount()).toBe(0)
+ }
+ )
+})
diff --git a/src/renderer/hooks/use-minute-clock.ts b/src/renderer/hooks/use-minute-clock.ts
index 46db6039..ea1c4e64 100644
--- a/src/renderer/hooks/use-minute-clock.ts
+++ b/src/renderer/hooks/use-minute-clock.ts
@@ -26,19 +26,39 @@ function scheduleNextMinute(): void {
}, delay)
}
+function refresh(): void {
+ if (timer !== null) clearTimeout(timer)
+ timer = null
+ snapshot = Date.now()
+ notify()
+ scheduleNextMinute()
+}
+
+function onVisibilityChange(): void {
+ if (document.visibilityState === 'visible') refresh()
+}
+
+function removeResumeListeners(): void {
+ window.removeEventListener('focus', refresh)
+ document.removeEventListener('visibilitychange', onVisibilityChange)
+}
+
function subscribe(listener: ClockListener): () => void {
const starting = listeners.size === 0
listeners.add(listener)
if (starting) {
snapshot = Date.now()
scheduleNextMinute()
+ window.addEventListener('focus', refresh)
+ document.addEventListener('visibilitychange', onVisibilityChange)
}
return () => {
listeners.delete(listener)
- if (listeners.size === 0 && timer !== null) {
- clearTimeout(timer)
+ if (listeners.size === 0) {
+ if (timer !== null) clearTimeout(timer)
timer = null
+ removeResumeListeners()
}
}
}
@@ -57,6 +77,7 @@ export function useMinuteClock(): number {
/** Internal: tests only. */
export function __resetMinuteClockForTests(): void {
+ removeResumeListeners()
if (timer !== null) clearTimeout(timer)
timer = null
listeners.clear()
diff --git a/src/renderer/hooks/use-speed-limit-state.test.tsx b/src/renderer/hooks/use-speed-limit-state.test.tsx
index a5bb17f2..a3df19b0 100644
--- a/src/renderer/hooks/use-speed-limit-state.test.tsx
+++ b/src/renderer/hooks/use-speed-limit-state.test.tsx
@@ -1,14 +1,19 @@
import { Events } from '@shared/protocol/events'
-import { renderHook, waitFor } from '@testing-library/react'
+import { act, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mockInvoke = vi.fn()
+const removeConnectionListener = vi.fn()
+const onConnectionChange = vi.fn(
+ (..._args: unknown[]) => removeConnectionListener
+)
const listeners = new Map<string, (...a: unknown[]) => 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: (...args: unknown[]) => onConnectionChange(...args),
platform: 'darwin',
},
}))
@@ -27,19 +32,23 @@ const BASE_LIMITED: SpeedLimitStateView = {
describe('useSpeedLimitState', () => {
beforeEach(() => {
mockInvoke.mockReset()
+ onConnectionChange.mockClear()
+ removeConnectionListener.mockClear()
listeners.clear()
})
it('loads initial state and updates on SpeedLimitChanged event', async () => {
mockInvoke.mockResolvedValue(BASE_LIMITED)
const { result } = renderHook(() => useSpeedLimitState())
- await waitFor(() => expect(result.current.turtle).toBe('off'))
+ await waitFor(() => expect(result.current).toEqual(BASE_LIMITED))
- listeners.get(Events.SpeedLimitChanged)?.({
- turtle: 'auto',
- effective: { download: 500_000, upload: 50_000 },
- activeReason: 'schedule',
- })
+ act(() =>
+ listeners.get(Events.SpeedLimitChanged)?.({
+ turtle: 'auto',
+ effective: { download: 500_000, upload: 50_000 },
+ activeReason: 'schedule',
+ })
+ )
await waitFor(() => expect(result.current.turtle).toBe('auto'))
})
@@ -47,7 +56,7 @@ describe('useSpeedLimitState', () => {
// First mount fetches the real state and populates the module cache.
mockInvoke.mockResolvedValue(BASE_LIMITED)
const first = renderHook(() => useSpeedLimitState())
- await waitFor(() => expect(first.result.current.turtle).toBe('off'))
+ await waitFor(() => expect(first.result.current).toEqual(BASE_LIMITED))
first.unmount()
// Simulate a remount where the fetch is still in flight: a cache-less hook
@@ -59,4 +68,49 @@ describe('useSpeedLimitState', () => {
// First render must already reflect the cached real state.
expect(second.result.current).toEqual(BASE_LIMITED)
})
+
+ it('subscribes before reading and rejects snapshots superseded by live changes', async () => {
+ let resolveSnapshot!: (value: SpeedLimitStateView) => void
+ mockInvoke.mockImplementation(() => {
+ expect(listeners.has(Events.SpeedLimitChanged)).toBe(true)
+ return new Promise<SpeedLimitStateView>((resolve) => {
+ resolveSnapshot = resolve
+ })
+ })
+ const { result } = renderHook(useSpeedLimitState)
+ const automatic: SpeedLimitStateView = {
+ turtle: 'auto',
+ activeReason: 'schedule',
+ effective: { upload: 50_000, download: 500_000 },
+ }
+ act(() => listeners.get(Events.SpeedLimitChanged)?.(automatic))
+ await act(async () => resolveSnapshot(BASE_LIMITED))
+ expect(result.current).toEqual(automatic)
+ })
+
+ it('refreshes on reconnect and window focus, and removes listeners on unmount', async () => {
+ mockInvoke.mockResolvedValue(BASE_LIMITED)
+ const { result, unmount } = renderHook(useSpeedLimitState)
+ await waitFor(() => expect(result.current).toEqual(BASE_LIMITED))
+ const automatic: SpeedLimitStateView = {
+ turtle: 'auto',
+ activeReason: 'none',
+ effective: { upload: 0, download: 0 },
+ }
+ mockInvoke.mockResolvedValue(automatic)
+ const reconnect = onConnectionChange.mock.calls[0][0] as (event: {
+ state: string
+ }) => void
+ await act(async () => reconnect({ state: 'connected' }))
+ expect(result.current).toEqual(automatic)
+ mockInvoke.mockResolvedValue(BASE_LIMITED)
+ await act(async () => window.dispatchEvent(new Event('focus')))
+ expect(result.current).toEqual(BASE_LIMITED)
+ unmount()
+ expect(listeners.size).toBe(0)
+ expect(removeConnectionListener).toHaveBeenCalledOnce()
+ const calls = mockInvoke.mock.calls.length
+ window.dispatchEvent(new Event('focus'))
+ expect(mockInvoke).toHaveBeenCalledTimes(calls)
+ })
})
diff --git a/src/renderer/hooks/use-speed-limit-state.ts b/src/renderer/hooks/use-speed-limit-state.ts
index 592c1e24..ef08cc89 100644
--- a/src/renderer/hooks/use-speed-limit-state.ts
+++ b/src/renderer/hooks/use-speed-limit-state.ts
@@ -2,7 +2,7 @@ import { transport } from '@renderer/lib/transport'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import type { SpeedLimitReason, TurtleState } from '@shared/types/settings'
-import { useCallback, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
export interface SpeedLimitStateView {
turtle: TurtleState
@@ -28,30 +28,41 @@ export function useSpeedLimitState(): SpeedLimitStateView {
() => cachedState ?? FALLBACK
)
- const apply = useCallback((next: SpeedLimitStateView) => {
- cachedState = next
- setState(next)
- }, [])
-
- const refresh = useCallback(async () => {
- try {
- const s = await transport.invoke(Queries.GetSpeedLimitState)
- if (s) apply(s as SpeedLimitStateView)
- } catch {
- /* next event will retry */
- }
- }, [apply])
-
useEffect(() => {
- refresh()
+ let disposed = false
+ let generation = 0
+ const apply = (next: SpeedLimitStateView) => {
+ if (disposed) return
+ cachedState = next
+ setState(next)
+ }
+ const refresh = async () => {
+ const current = ++generation
+ try {
+ const next = await transport.invoke(Queries.GetSpeedLimitState)
+ if (next && current === generation) apply(next as SpeedLimitStateView)
+ } catch {
+ /* Refresh again on the next event, focus or reconnect. */
+ }
+ }
const onChange = (...args: unknown[]) => {
+ // A live mode change supersedes any earlier in-flight snapshot.
+ generation++
apply(args[0] as SpeedLimitStateView)
}
transport.on(Events.SpeedLimitChanged, onChange)
+ const removeConnectionListener = transport.onConnectionChange?.((event) => {
+ if (event.state === 'connected') void refresh()
+ })
+ window.addEventListener('focus', refresh)
+ void refresh()
return () => {
+ disposed = true
transport.off(Events.SpeedLimitChanged, onChange)
+ removeConnectionListener?.()
+ window.removeEventListener('focus', refresh)
}
- }, [refresh, apply])
+ }, [])
return state
}
diff --git a/src/renderer/lib/format.test.ts b/src/renderer/lib/format.test.ts
index 335ef80a..7d1182dd 100644
--- a/src/renderer/lib/format.test.ts
+++ b/src/renderer/lib/format.test.ts
@@ -1,5 +1,6 @@
import { SUPPORTED_LOCALE_CODES } from '@shared/constants/locales'
import { resolveByteUnitSystem } from '@shared/schemas/byte-unit-system'
+import { formatSpeedLimit } from '@shared/utils/format-bytes'
import { describe, expect, it } from 'vitest'
import {
formatByteParts,
@@ -10,6 +11,15 @@ import {
} from './format'
describe('formatBytes', () => {
+ it('omits redundant zeroes from static limits without changing live rates', () => {
+ expect(formatSpeedLimit(64_000)).toBe('64 KB/s')
+ expect(formatSpeedLimit(512_000)).toBe('512 KB/s')
+ expect(formatSpeedLimit(65_536, 'binary')).toBe('64 KiB/s')
+ expect(formatSpeedLimit(524_288, 'binary')).toBe('512 KiB/s')
+ expect(formatSpeedLimit(1_500_000)).toBe('1.5 MB/s')
+ expect(formatSpeedLimit(65_536)).toBe('65.5 KB/s')
+ expect(formatSpeed(64_000)).toBe('64.0 KB/s')
+ })
it('uses decimal units and two decimal places for sizes', () => {
expect(formatBytes(0)).toBe('0 B')
expect(formatBytes(Number.NaN)).toBe('0 B')
diff --git a/src/renderer/routes/dashboard/tiles/speed-limit-tile.tsx b/src/renderer/routes/dashboard/tiles/speed-limit-tile.tsx
index 572e4567..fc29ba42 100644
--- a/src/renderer/routes/dashboard/tiles/speed-limit-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/speed-limit-tile.tsx
@@ -1,6 +1,7 @@
import { useByteFormat } from '@renderer/hooks/use-byte-format'
// src/renderer/routes/dashboard/tiles/speed-limit-tile.tsx
+import { SPEED_LIMIT_MODES } from '@renderer/components/speed-limit-modes'
import { Button } from '@renderer/components/ui/button'
import {
Tooltip,
@@ -11,8 +12,8 @@ import {
import type { SpeedLimitStateView } from '@renderer/hooks/use-speed-limit-state'
import { cn } from '@renderer/lib/utils'
-import { Bolt, InfinityIcon, Rabbit, Squirrel, Turtle } from 'lucide-react'
-import type { ComponentType, ReactElement } from 'react'
+import { Bolt, InfinityIcon } from 'lucide-react'
+import type { ReactElement } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
import { TileShell } from '../components/tile-shell'
@@ -20,15 +21,6 @@ import type { DashboardTileViewport } from '../layout/dashboard-registry'
type TurtleState = SpeedLimitStateView['turtle']
-const TURTLES: {
- id: TurtleState
- Icon: ComponentType<{ className?: string }>
-}[] = [
- { id: 'off', Icon: Rabbit },
- { id: 'on', Icon: Turtle },
- { id: 'auto', Icon: Squirrel },
-]
-
export interface SpeedLimitTileProps {
state: SpeedLimitStateView
viewport: DashboardTileViewport
@@ -42,10 +34,10 @@ export function SpeedLimitTile({
onSelectTurtle,
className,
}: SpeedLimitTileProps) {
- const { formatSpeed } = useByteFormat()
+ const { formatSpeedLimit } = useByteFormat()
function fmt(v: number): string | ReactElement {
- return v <= 0 ? <InfinityIcon className="size-4" /> : formatSpeed(v)
+ return v <= 0 ? <InfinityIcon className="size-4" /> : formatSpeedLimit(v)
}
const { t } = useTranslation()
const compact = viewport.contentLevel === 'compact'
@@ -84,7 +76,7 @@ export function SpeedLimitTile({
tall ? 'grid-cols-1' : 'grid-cols-3'
)}
>
- {TURTLES.map(({ id, Icon }) => {
+ {SPEED_LIMIT_MODES.map(({ id, Icon }) => {
const active = state.turtle === id
return (
<Tooltip key={id}>
diff --git a/src/renderer/routes/downloads/columns.ts b/src/renderer/routes/downloads/columns.ts
new file mode 100644
index 00000000..000bf161
--- /dev/null
+++ b/src/renderer/routes/downloads/columns.ts
@@ -0,0 +1,50 @@
+import { TASK_SORT_COLUMNS, type TaskSortColumn } from './sort'
+
+export const TASK_ROW_HEIGHT = 36
+export const TASK_HEADER_HEIGHT = 36
+
+export const TASK_COLUMNS: Record<
+ TaskSortColumn,
+ { width: number; min: number; max: number; numeric?: boolean }
+> = {
+ name: { width: 240, min: 160, max: 900 },
+ size: { width: 84, min: 72, max: 240, numeric: true },
+ progress: { width: 120, min: 100, max: 300, numeric: true },
+ status: { width: 100, min: 80, max: 240 },
+ down: { width: 90, min: 80, max: 240, numeric: true },
+ up: { width: 90, min: 80, max: 240, numeric: true },
+ eta: { width: 80, min: 72, max: 240, numeric: true },
+ connections: { width: 90, min: 72, max: 240, numeric: true },
+ createdAt: { width: 196, min: 140, max: 300 },
+ finishedAt: { width: 196, min: 140, max: 300 },
+}
+
+export function clampColumnWidth(column: TaskSortColumn, width: number) {
+ const definition = TASK_COLUMNS[column]
+ return Number.isFinite(width)
+ ? Math.round(Math.max(definition.min, Math.min(definition.max, width)))
+ : definition.width
+}
+
+export function defaultTaskColumns() {
+ return TASK_SORT_COLUMNS.map((id) => ({
+ id,
+ width: TASK_COLUMNS[id].width,
+ visible: !['up', 'eta', 'connections'].includes(id),
+ }))
+}
+
+export type TaskColumn = ReturnType<typeof defaultTaskColumns>[number]
+
+export function taskGridStyle(columns: readonly TaskColumn[]) {
+ return {
+ gridTemplateColumns: columns
+ .map((column) =>
+ column.id === 'name'
+ ? `minmax(${column.width}px, 1fr)`
+ : `${column.width}px`
+ )
+ .join(' '),
+ minWidth: columns.reduce((sum, column) => sum + column.width, 0) + 24,
+ }
+}
diff --git a/src/renderer/routes/downloads/downloads-list.css b/src/renderer/routes/downloads/downloads-list.css
new file mode 100644
index 00000000..c447a5fc
--- /dev/null
+++ b/src/renderer/routes/downloads/downloads-list.css
@@ -0,0 +1,65 @@
+.downloads-task-grid,
+.downloads-inspector-popup {
+ --ring: #7388a3;
+ --downloads-selection: #e4ebf3;
+}
+.downloads-task-row[data-alternate] {
+ background: color-mix(in srgb, var(--muted) 35%, transparent);
+}
+.downloads-task-grid[data-keyboard-focus="true"]:focus-visible {
+ outline: 1px solid var(--ring);
+ outline-offset: -1px;
+}
+.downloads-task-grid[data-keyboard-focus="true"]:focus-visible
+ .downloads-task-row[data-focused] {
+ outline: 1px solid var(--ring);
+ outline-offset: -1px;
+}
+.downloads-task-row[aria-selected="true"] {
+ background: var(--muted);
+}
+.downloads-task-grid[data-active="true"]
+ .downloads-task-row[aria-selected="true"] {
+ color: var(--foreground);
+ background: var(--downloads-selection);
+}
+.downloads-inspector-popup {
+ transform: translateY(
+ calc(
+ var(--drawer-snap-point-offset, 0px) +
+ var(--drawer-swipe-movement-y, 0px)
+ )
+ );
+ transition:
+ transform 220ms ease-out,
+ padding-bottom 220ms ease-out;
+}
+.downloads-inspector-popup[data-swiping] {
+ transition: none;
+}
+.downloads-inspector-popup[data-starting-style],
+.downloads-inspector-popup[data-ending-style] {
+ transform: translateY(100%);
+}
+.dark .downloads-task-grid,
+.dark .downloads-inspector-popup {
+ --ring: #97aac4;
+ --downloads-selection: #303d50;
+}
+@media (prefers-reduced-motion: reduce) {
+ .downloads-inspector-popup {
+ transition: none;
+ }
+}
+@media (forced-colors: active) {
+ .downloads-task-grid,
+ .downloads-inspector-popup {
+ --ring: Highlight;
+ }
+ .downloads-task-grid[data-active="true"]
+ .downloads-task-row[aria-selected="true"] {
+ color: HighlightText;
+ background: Highlight;
+ forced-color-adjust: none;
+ }
+}
diff --git a/src/renderer/routes/downloads/downloads-page.test.tsx b/src/renderer/routes/downloads/downloads-page.test.tsx
index 0f12b260..aa85944d 100644
--- a/src/renderer/routes/downloads/downloads-page.test.tsx
+++ b/src/renderer/routes/downloads/downloads-page.test.tsx
@@ -4,6 +4,7 @@ import {
type PlatformServices,
PlatformServicesProvider,
} from '@renderer/platform/services'
+import { Queries } from '@shared/protocol/queries'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
@@ -15,6 +16,7 @@ import {
waitFor,
within,
} from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import {
MemoryRouter,
Route,
@@ -25,6 +27,7 @@ import {
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { DownloadsPage } from './downloads-page'
import { useDownloadsSelection } from './store'
+import { useDownloadsView } from './view-preferences'
const taskListMock = vi.hoisted(() => {
const retry = vi.fn<() => Promise<void>>().mockResolvedValue(undefined)
@@ -57,7 +60,15 @@ vi.mock('@renderer/hooks/use-task-speed-history', () => ({
}))
vi.mock('@renderer/lib/transport', () => ({
transport: {
- invoke: vi.fn().mockResolvedValue({ state: 'ready' }),
+ invoke: vi.fn(async (channel: string) =>
+ channel === Queries.GetSpeedLimitState
+ ? {
+ turtle: 'off',
+ effective: { download: 0, upload: 0 },
+ activeReason: 'none',
+ }
+ : { state: 'ready' }
+ ),
on: vi.fn(),
off: vi.fn(),
platform: 'darwin',
@@ -161,6 +172,19 @@ function selectedIds(): string[] {
}
beforeEach(() => {
+ Element.prototype.getAnimations = vi.fn(() => [])
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ )
+ useDownloadsView.setState({
+ inspectorVisible: false,
+ inspectorSnap: 'medium',
+ })
taskListMock.retry.mockClear()
setTaskList({})
useDownloadsSelection.getState().setItems([])
@@ -382,13 +406,14 @@ describe('DownloadsPage', () => {
}
)
- it('closing the Inspector clears selection and removes task', async () => {
+ it('closing the Inspector preserves selection and consumes the task deep link', async () => {
setTaskList({ tasks: [task('a', TaskStatus.Downloading)] })
renderAt('/downloads/active?task=a')
await waitFor(() => expect(selectedIds()).toEqual(['a']))
- fireEvent.keyDown(window, { key: 'Escape' })
- await waitFor(() => expect(selectedIds()).toEqual([]))
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))
+ expect(selectedIds()).toEqual(['a'])
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
await waitFor(() =>
expect(screen.getByTestId('location')).toHaveTextContent(
'/downloads/active'
@@ -429,3 +454,84 @@ describe('DownloadsPage', () => {
expect(selectedIds()).toEqual(['b'])
})
})
+
+describe('Downloads inline search', () => {
+ it('filters the current status view by keyword and type, and clears only the keyword', async () => {
+ setTaskList({
+ tasks: [
+ task('alpha', TaskStatus.Downloading),
+ task('beta', TaskStatus.Paused),
+ task('alpha-done', TaskStatus.Completed),
+ task('alpha-bt', TaskStatus.Downloading, TaskType.Bt),
+ ],
+ })
+ renderAt('/downloads/active?type=http')
+ const user = userEvent.setup()
+ const input = screen.getByRole('textbox', { name: 'Search downloads' })
+ await user.type(input, 'alpha')
+ expect(
+ useDownloadsSelection.getState().items.map((task) => task.id)
+ ).toEqual(['alpha'])
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ await user.click(screen.getByRole('button', { name: 'Clear search' }))
+ expect(input).toHaveValue('')
+ expect(input).toHaveFocus()
+ expect(screen.getByTestId('location')).toHaveTextContent(
+ '/downloads/active?type=http'
+ )
+ expect(
+ screen.getByRole('button', { name: /Filters.*Type filter: HTTP/ })
+ ).toBeInTheDocument()
+ })
+
+ it('keeps selection and inspector open when the selected task still matches a query', async () => {
+ setTaskList({
+ tasks: [
+ task('alpha', TaskStatus.Downloading),
+ task('beta', TaskStatus.Paused),
+ ],
+ })
+ renderAt('/downloads/all?task=alpha')
+ await waitFor(() => expect(selectedIds()).toEqual(['alpha']))
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Search downloads' }))
+ await user.type(
+ screen.getByRole('textbox', { name: 'Search downloads' }),
+ 'alpha'
+ )
+ expect(selectedIds()).toEqual(['alpha'])
+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)
+ expect(
+ screen.queryByRole('row', { name: 'task beta' })
+ ).not.toBeInTheDocument()
+ expect(screen.getByTestId('location')).not.toHaveTextContent('task=')
+ })
+
+ it('clears a conflicting query to reveal an explicit task deep link', async () => {
+ setTaskList({ tasks: [task('alpha', TaskStatus.Paused)] })
+ renderAt('/downloads/all?q=missing&type=bt&task=alpha')
+ await waitFor(() => expect(selectedIds()).toEqual(['alpha']))
+ expect(screen.getByTestId('location')).toHaveTextContent(
+ '/downloads/all?task=alpha'
+ )
+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)
+ })
+
+ it('Escape clears text first, then collapses the empty field and returns focus', async () => {
+ setTaskList({ tasks: [task('alpha', TaskStatus.Downloading)] })
+ renderAt('/downloads/all')
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Search downloads' }))
+ const input = screen.getByRole('textbox', { name: 'Search downloads' })
+ expect(input).toHaveFocus()
+ await user.type(input, 'missing')
+ await user.keyboard('{Escape}')
+ expect(input).toHaveValue('')
+ expect(input).toHaveFocus()
+ await user.keyboard('{Escape}')
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'Search downloads' })
+ ).toHaveFocus()
+ })
+})
diff --git a/src/renderer/routes/downloads/downloads-page.tsx b/src/renderer/routes/downloads/downloads-page.tsx
index db7c1247..e9ac3685 100644
--- a/src/renderer/routes/downloads/downloads-page.tsx
+++ b/src/renderer/routes/downloads/downloads-page.tsx
@@ -2,7 +2,7 @@ import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'
import { Button } from '@renderer/components/ui/button'
import { Skeleton } from '@renderer/components/ui/skeleton'
import { useTaskList } from '@renderer/hooks/use-task-list'
-import type { DownloadTask, TaskType } from '@shared/types/task'
+import type { TaskType } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
import {
useCallback,
@@ -19,6 +19,7 @@ import {
useParams,
useSearchParams,
} from 'react-router'
+import { DownloadsToolbar } from './downloads-toolbar'
import {
applyFilter,
countTasksByTab,
@@ -27,14 +28,15 @@ import {
isValidTab,
parseTypeParam,
serializeTypeParam,
+ taskMatchesQuery,
taskMatchesTab,
} from './filter'
-import { FilterSearchCommand } from './filter-search-command'
import { GlobalStatsBar } from './global-stats-bar'
import { StatusTitleMenu } from './status-title-menu'
import { useDownloadsSelection } from './store'
import { TaskInspectorDrawer } from './task-inspector-drawer'
import { TaskListPanel } from './task-list-panel'
+import { useDownloadsView } from './view-preferences'
interface ActiveDeepLink {
signature: string
@@ -124,22 +126,33 @@ export function DownloadsPage() {
() => parseTypeParam(searchParams.get('type')),
[searchParams]
)
+ const query = searchParams.get('q') ?? ''
const taskParam = searchParams.get('task')?.trim() || null
const deepLinkSignature = `${location.key}:${location.pathname}${location.search}`
const counts = useMemo(() => countTasksByTab(tasks), [tasks])
- const typeCounts = useMemo(() => countTasksByType(tasks), [tasks])
+ const typeCounts = useMemo(
+ () =>
+ countTasksByType(
+ tasks.filter(
+ (task) =>
+ taskMatchesTab(task, filter) && taskMatchesQuery(task, query)
+ )
+ ),
+ [tasks, filter, query]
+ )
const filtered = useMemo(
- () => applyFilter(tasks, filter, types),
- [tasks, filter, types]
+ () => applyFilter(tasks, filter, types, query),
+ [tasks, filter, types, query]
)
const onTabChange = useCallback(
(next: DownloadsTab) => {
- const qs = serializeTypeParam(types)
- navigate(`/downloads/${next}${qs ? `?type=${qs}` : ''}`)
+ const nextParams = new URLSearchParams(searchParams)
+ nextParams.delete('task')
+ navigate(`/downloads/${next}${nextParams.size ? `?${nextParams}` : ''}`)
},
- [navigate, types]
+ [navigate, searchParams]
)
const onTypesChange = useCallback(
@@ -154,6 +167,17 @@ export function DownloadsPage() {
[searchParams, setSearchParams]
)
+ const onQueryChange = useCallback(
+ (next: string) => {
+ const params = new URLSearchParams(searchParams)
+ if (next) params.set('q', next)
+ else params.delete('q')
+ params.delete('task')
+ setSearchParams(params, { replace: true })
+ },
+ [searchParams, setSearchParams]
+ )
+
const select = useDownloadsSelection((s) => s.select)
const clearSelection = useDownloadsSelection((s) => s.clearSelection)
const consumedDeepLinks = useRef(new Set<string>())
@@ -220,11 +244,16 @@ export function DownloadsPage() {
}
const matchesType = types.length === 0 || types.includes(target.type)
- if (!taskMatchesTab(target, filter) || !matchesType) {
+ if (
+ !taskMatchesTab(target, filter) ||
+ !matchesType ||
+ !taskMatchesQuery(target, query)
+ ) {
consumedDeepLinks.current.add(deepLinkSignature)
const next = new URLSearchParams(searchParams)
next.set('task', target.id)
next.delete('type')
+ next.delete('q')
navigate(
{
pathname: '/downloads/all',
@@ -238,10 +267,12 @@ export function DownloadsPage() {
consumedDeepLinks.current.add(deepLinkSignature)
handlingDeepLinkSelection.current = true
select(target.id)
+ useDownloadsView.getState().setInspectorVisible(true)
handlingDeepLinkSelection.current = false
}, [
deepLinkSignature,
filter,
+ query,
hasReadySnapshot,
navigate,
searchParams,
@@ -251,21 +282,6 @@ export function DownloadsPage() {
types,
])
- const onOpenTask = useCallback(
- (task: DownloadTask) => {
- removeTaskQuery()
- if (!taskMatchesTab(task, filter)) {
- const qs = serializeTypeParam(types)
- navigate(`/downloads/all${qs ? `?type=${qs}` : ''}`)
- }
- // select() sets selectedIds immediately so the inspector opens. When we
- // just navigated to /downloads/all, focusedIndex re-resolves on the next
- // list render (setItems) — the drawer only needs selectedIds to be set.
- select(task.id)
- },
- [filter, types, navigate, removeTaskQuery, select]
- )
-
const [container, setContainer] = useState<HTMLElement | null>(null)
const taskList =
status === 'loading' ? (
@@ -279,8 +295,8 @@ export function DownloadsPage() {
hasAnyTasks={counts.all > 0}
selection={useDownloadsSelection}
filter={filter}
- search=""
- onClearSearch={() => onTypesChange([])}
+ search={query}
+ onClearSearch={() => onQueryChange('')}
/>
)
@@ -296,19 +312,25 @@ export function DownloadsPage() {
tab={filter}
onTabChange={onTabChange}
counts={counts}
+ visibleCount={filtered.length}
/>
}
actions={
- <FilterSearchCommand
+ <DownloadsToolbar
tasks={tasks}
+ selection={useDownloadsSelection}
+ query={query}
+ onQueryChange={onQueryChange}
types={types}
onTypesChange={onTypesChange}
typeCounts={typeCounts}
- onOpenTask={onOpenTask}
+ onHideInspector={removeTaskQuery}
/>
}
actionsPosition="end"
- footer={<GlobalStatsBar counts={counts} />}
+ headerClassName="compact-header:py-1"
+ actionsClassName="min-w-0 flex-1"
+ footer={<GlobalStatsBar />}
contentClassName="px-6"
>
{status === 'error' && hasReadySnapshot ? (
diff --git a/src/renderer/routes/downloads/downloads-toolbar-button.tsx b/src/renderer/routes/downloads/downloads-toolbar-button.tsx
new file mode 100644
index 00000000..9e87102e
--- /dev/null
+++ b/src/renderer/routes/downloads/downloads-toolbar-button.tsx
@@ -0,0 +1,21 @@
+import { Button } from '@renderer/components/ui/button'
+import { cn } from '@renderer/lib/utils'
+import type { ComponentProps } from 'react'
+
+/** Both densities reserve 2px padding and a border around each target. */
+export function DownloadsToolbarButton({
+ className,
+ ...props
+}: ComponentProps<typeof Button>) {
+ return (
+ <Button
+ size="icon"
+ variant="ghost"
+ {...props}
+ className={cn(
+ 'app-no-drag relative size-[30px] compact-header:size-6 rounded-full text-foreground bg-transparent transition-colors hover:bg-accent active:bg-accent [&>svg]:size-[18px] compact-header:[&>svg]:size-4 [&>svg]:opacity-65 hover:[&>svg]:opacity-90 focus-visible:[&>svg]:opacity-90 focus-visible:ring-1 focus-visible:ring-[#7388a3] dark:focus-visible:ring-[#97aac4] aria-pressed:bg-accent data-popup-open:bg-accent',
+ className
+ )}
+ />
+ )
+}
diff --git a/src/renderer/routes/downloads/downloads-toolbar.test.ts b/src/renderer/routes/downloads/downloads-toolbar.test.ts
new file mode 100644
index 00000000..af8b124d
--- /dev/null
+++ b/src/renderer/routes/downloads/downloads-toolbar.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest'
+import { toolbarActionCount } from './downloads-toolbar'
+
+describe.each([
+ { density: 'standard', compact: false, full: 342, pair: 308, closed: 148 },
+ { density: 'compact', compact: true, full: 324, pair: 296, closed: 124 },
+])('$density toolbar overflow priority', ({ compact, full, pair, closed }) => {
+ it('reserves readable search space before retaining lower priority buttons', () => {
+ expect(toolbarActionCount(full, true, 3, compact)).toBe(3)
+ expect(toolbarActionCount(full - 1, true, 3, compact)).toBe(2)
+ expect(toolbarActionCount(pair, true, 3, compact)).toBe(2)
+ expect(toolbarActionCount(pair - 1, true, 3, compact)).toBe(1)
+ expect(toolbarActionCount(closed, false, 3, compact)).toBe(3)
+ expect(toolbarActionCount(closed - 1, false, 3, compact)).toBe(2)
+ })
+ it('requires spare space before restoring a hidden button', () => {
+ expect(toolbarActionCount(full + 7, true, 2, compact)).toBe(2)
+ expect(toolbarActionCount(full + 8, true, 2, compact)).toBe(3)
+ expect(toolbarActionCount(pair + 7, true, 1, compact)).toBe(1)
+ expect(toolbarActionCount(pair + 8, true, 1, compact)).toBe(2)
+ })
+})
diff --git a/src/renderer/routes/downloads/downloads-toolbar.tsx b/src/renderer/routes/downloads/downloads-toolbar.tsx
new file mode 100644
index 00000000..10899194
--- /dev/null
+++ b/src/renderer/routes/downloads/downloads-toolbar.tsx
@@ -0,0 +1,137 @@
+import { useCompactHeader } from '@renderer/components/desktop-kit/hooks/use-compact-header'
+import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
+import { ToolbarGlass } from '@renderer/components/desktop-kit/toolbar-glass/toolbar-glass'
+import { useLiquidGlass } from '@renderer/hooks/use-liquid-glass'
+import type { DownloadTask } from '@shared/types/task'
+import { useLayoutEffect, useRef, useState } from 'react'
+import {
+ FilterSearchCommand,
+ type FilterSearchCommandProps,
+} from './filter-search-command'
+import { InspectorToggle, ListViewMenu } from './list-view-menu'
+import { TaskActionsMenu } from './task-actions-menu'
+
+// Match the 30px / 24px targets, 4px gaps and capsule padding in both densities.
+const actionWidth = (count: number, compact: boolean) =>
+ count * (compact ? 24 : 30) + (count - 1) * 4 + 6
+const SEARCH_WIDTH = 230
+const GROUP_GAP = 8
+
+export function toolbarActionCount(
+ width: number,
+ expanded: boolean,
+ previous = 3,
+ compact = false
+): number {
+ const searchWidth = expanded ? SEARCH_WIDTH : actionWidth(1, compact)
+ for (const count of [3, 2]) {
+ // Reserve 8px before restoring an item so resizing near a threshold is stable.
+ const reserve = count > previous ? 8 : 0
+ if (
+ width >=
+ actionWidth(count, compact) + GROUP_GAP + searchWidth + reserve
+ )
+ return count
+ }
+ return 1
+}
+
+export function DownloadsToolbar({
+ tasks,
+ selection,
+ onHideInspector,
+ ...searchProps
+}: Omit<
+ FilterSearchCommandProps,
+ 'expanded' | 'onExpandedChange' | 'width' | 'glassEnabled'
+> & {
+ tasks: readonly DownloadTask[]
+ selection: SelectionStore<DownloadTask>
+ onHideInspector: () => void
+}) {
+ const compact = useCompactHeader()
+ const glassEnabled = useLiquidGlass()
+ const rootRef = useRef<HTMLDivElement>(null)
+ const moreRef = useRef<HTMLButtonElement>(null)
+ const viewRef = useRef<HTMLButtonElement>(null)
+ const inspectorRef = useRef<HTMLButtonElement>(null)
+ const [searchRequested, setSearchRequested] = useState(false)
+ const expanded =
+ searchRequested ||
+ Boolean(searchProps.query.trim()) ||
+ searchProps.types.length > 0
+ const [width, setWidth] = useState(400)
+ const [count, setCount] = useState(3)
+ const [viewMenuOpen, setViewMenuOpen] = useState(false)
+
+ useLayoutEffect(() => {
+ const root = rootRef.current
+ if (!root) return
+ const measure = () => {
+ const available = root.getBoundingClientRect().width
+ if (available > 0) setWidth(available)
+ }
+ measure()
+ const observer = new ResizeObserver(measure)
+ observer.observe(root)
+ return () => observer.disconnect()
+ }, [])
+
+ useLayoutEffect(() => {
+ // Keep an open menu anchored until it closes. The field can shrink while
+ // a user resizes the window with that menu open.
+ if (viewMenuOpen) return
+ const next = toolbarActionCount(width, expanded, count, compact)
+ if (next === count) return
+ const focused = document.activeElement
+ if (
+ (next < 3 && focused === viewRef.current) ||
+ (next < 2 && focused === inspectorRef.current)
+ ) {
+ moreRef.current?.focus({ preventScroll: true })
+ }
+ setCount(next)
+ }, [width, expanded, count, compact, viewMenuOpen])
+
+ return (
+ <div
+ ref={rootRef}
+ data-slot="downloads-toolbar"
+ data-density={compact ? 'compact' : 'standard'}
+ data-visible-actions={count}
+ className="flex min-w-0 flex-1 items-center justify-end gap-2"
+ >
+ <div
+ data-slot="downloads-action-group"
+ className="toolbar-glass-surface flex h-9 shrink-0 items-center gap-1 rounded-full border border-border/70 bg-background/70 p-0.5 compact-header:h-[30px]"
+ >
+ <ToolbarGlass enabled={glassEnabled} />
+ <TaskActionsMenu
+ tasks={tasks}
+ selection={selection}
+ onHideInspector={onHideInspector}
+ triggerRef={moreRef}
+ />
+ {count === 3 && (
+ <ListViewMenu triggerRef={viewRef} onOpenChange={setViewMenuOpen} />
+ )}
+ {count >= 2 && (
+ <InspectorToggle triggerRef={inspectorRef} onHide={onHideInspector} />
+ )}
+ </div>
+ <FilterSearchCommand
+ {...searchProps}
+ glassEnabled={glassEnabled}
+ expanded={expanded}
+ onExpandedChange={setSearchRequested}
+ width={Math.max(
+ 80,
+ Math.min(
+ SEARCH_WIDTH,
+ width - actionWidth(count, compact) - GROUP_GAP
+ )
+ )}
+ />
+ </div>
+ )
+}
diff --git a/src/renderer/routes/downloads/filter-search-command.tsx b/src/renderer/routes/downloads/filter-search-command.tsx
index 76d78055..f0209830 100644
--- a/src/renderer/routes/downloads/filter-search-command.tsx
+++ b/src/renderer/routes/downloads/filter-search-command.tsx
@@ -1,66 +1,269 @@
-import { Button } from '@renderer/components/ui/button'
+import { useCompactHeader } from '@renderer/components/desktop-kit/hooks/use-compact-header'
+import { ToolbarGlass } from '@renderer/components/desktop-kit/toolbar-glass/toolbar-glass'
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@renderer/components/ui/popover'
-import { Search } from 'lucide-react'
-import { useState } from 'react'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@renderer/components/ui/tooltip'
+import { TASK_TYPE_META, TASK_TYPE_ORDER } from '@renderer/lib/task-type-meta'
+import { cn } from '@renderer/lib/utils'
+import { CircleX, ListFilter, Search } from 'lucide-react'
+import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { DownloadsToolbarButton } from './downloads-toolbar-button'
import {
FilterSearchPanel,
type FilterSearchPanelProps,
} from './filter-search-panel'
-export type FilterSearchCommandProps = FilterSearchPanelProps
+export interface FilterSearchCommandProps extends FilterSearchPanelProps {
+ query: string
+ onQueryChange: (query: string) => void
+ expanded: boolean
+ onExpandedChange: (expanded: boolean) => void
+ width: number
+ glassEnabled?: boolean
+}
export function FilterSearchCommand({
- tasks,
+ query,
+ onQueryChange,
types,
onTypesChange,
typeCounts,
- onOpenTask,
+ expanded,
+ onExpandedChange,
+ width,
+ glassEnabled = false,
}: FilterSearchCommandProps) {
- const { t } = useTranslation()
+ const compact = useCompactHeader()
+ const { t, i18n } = useTranslation()
const [open, setOpen] = useState(false)
- const active = types.length > 0
+ const [popupPresent, setPopupPresent] = useState(false)
+ const rootRef = useRef<HTMLDivElement>(null)
+ const popupRef = useRef<HTMLDivElement>(null)
+ const inputRef = useRef<HTMLInputElement>(null)
+ const searchRef = useRef<HTMLButtonElement>(null)
+ const filterRef = useRef<HTMLButtonElement>(null)
+ const returnFocus = useRef(false)
+ const focusOnExpand = useRef(false)
+ const blurFrame = useRef<number | null>(null)
+ const active = Boolean(query.trim()) || types.length > 0
+ const latest = useRef({ active, open })
+ latest.current = { active, open }
+ const inputId = useId()
+ const label = t('panel.downloads.search.placeholder')
+ const descriptions = [
+ query.trim()
+ ? t('panel.downloads.search.activeQuery', { query: query.trim() })
+ : null,
+ types.length > 0
+ ? t('panel.downloads.search.activeTypeFilters', {
+ types: new Intl.ListFormat(i18n.language, {
+ style: 'long',
+ type: 'conjunction',
+ }).format(
+ TASK_TYPE_ORDER.filter((type) => types.includes(type)).map((type) =>
+ t(TASK_TYPE_META[type].labelKey)
+ )
+ ),
+ })
+ : null,
+ ].filter(Boolean)
+ const filterLabel = [
+ t('panel.downloads.search.filters'),
+ ...descriptions,
+ ].join(' · ')
+ const collapseIfIdle = () => {
+ if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current)
+ blurFrame.current = requestAnimationFrame(() => {
+ const focused = document.activeElement
+ if (
+ !latest.current.active &&
+ !latest.current.open &&
+ !rootRef.current?.contains(focused) &&
+ !popupRef.current?.contains(focused)
+ )
+ onExpandedChange(false)
+ })
+ }
+ useEffect(
+ () => () => {
+ if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current)
+ },
+ []
+ )
+ useLayoutEffect(() => {
+ if (expanded && focusOnExpand.current) {
+ inputRef.current?.focus()
+ focusOnExpand.current = false
+ } else if (!expanded && returnFocus.current) {
+ searchRef.current?.focus()
+ returnFocus.current = false
+ }
+ }, [expanded])
return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- render={
- <Button
- variant="ghost"
- size="icon"
- aria-label={t('panel.downloads.search.placeholder')}
- // Match the 28px window-chrome targets so compact panel actions
- // stay on the Toggle Sidebar and Add Task centerline.
- className="panel-action-align-visual-end app-no-drag relative size-7 rounded-full bg-transparent hover:bg-transparent dark:hover:bg-transparent [&>svg]:opacity-50 hover:[&>svg]:opacity-75 focus-visible:[&>svg]:opacity-75"
+ <div
+ ref={rootRef}
+ data-slot="downloads-search"
+ data-expanded={expanded}
+ data-filter-active={active}
+ onBlurCapture={(event) => {
+ // Portal blur events bubble through React too. A closing popup hands
+ // focus back to its trigger after its animation; let it finish.
+ if (!open && rootRef.current?.contains(event.target)) collapseIfIdle()
+ }}
+ className={cn(
+ 'toolbar-glass-surface flex h-9 shrink-0 items-center rounded-full border border-border/70 bg-background/70 p-0.5 transition-[width] duration-150 ease-out motion-reduce:transition-none compact-header:h-[30px]',
+ expanded &&
+ 'has-[input:focus]:border-[#7388a3] dark:has-[input:focus]:border-[#97aac4]'
+ )}
+ style={{ width: expanded ? width : compact ? 30 : 36 }}
+ >
+ <ToolbarGlass enabled={glassEnabled} />
+ {expanded ? (
+ <>
+ <Popover
+ open={open}
+ onOpenChange={(next, details) => {
+ setOpen(next)
+ if (next) {
+ setPopupPresent(true)
+ onExpandedChange(true)
+ }
+ if (
+ !next &&
+ (details.reason === 'outside-press' ||
+ details.reason === 'focus-out')
+ )
+ collapseIfIdle()
+ }}
+ onOpenChangeComplete={(next) => {
+ if (!next) setPopupPresent(false)
+ }}
+ >
+ <Tooltip disabled={open}>
+ <TooltipTrigger
+ delay={400}
+ render={
+ <PopoverTrigger
+ render={
+ <DownloadsToolbarButton
+ ref={filterRef}
+ aria-label={filterLabel}
+ className={
+ active
+ ? 'text-[#006bd6] dark:text-[#69aeff] [&>svg]:opacity-100 hover:text-[#006bd6] dark:hover:text-[#69aeff]'
+ : undefined
+ }
+ />
+ }
+ />
+ }
+ >
+ <ListFilter className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent
+ anchor={rootRef}
+ side="bottom"
+ align="start"
+ sideOffset={8}
+ className={cn(
+ 'block max-w-(--anchor-width) [overflow-wrap:anywhere]',
+ popupPresent && 'invisible'
+ )}
+ >
+ <p>{t('panel.downloads.search.filters')}</p>
+ {descriptions.map((description) => (
+ <p key={description} className="mt-1 opacity-80">
+ {description}
+ </p>
+ ))}
+ </TooltipContent>
+ </Tooltip>
+ <PopoverContent
+ ref={popupRef}
+ anchor={rootRef}
+ aria-label={t('panel.downloads.search.filters')}
+ align="start"
+ sideOffset={8}
+ className="app-no-drag w-(--anchor-width) max-w-[calc(100vw-24px)] p-0"
+ >
+ <FilterSearchPanel
+ types={types}
+ onTypesChange={onTypesChange}
+ typeCounts={typeCounts}
+ />
+ </PopoverContent>
+ </Popover>
+ <input
+ ref={inputRef}
+ id={inputId}
+ type="text"
+ inputMode="search"
+ aria-label={label}
+ placeholder={label}
+ autoComplete="off"
+ spellCheck={false}
+ value={query}
+ onFocus={() => onExpandedChange(true)}
+ onChange={(event) => onQueryChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== 'Escape' || event.nativeEvent.isComposing)
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (query) onQueryChange('')
+ else if (types.length === 0) {
+ returnFocus.current = true
+ onExpandedChange(false)
+ } else filterRef.current?.focus()
+ }}
+ className="h-[30px] w-full min-w-0 border-0 bg-transparent px-1 text-[13px] outline-none placeholder:text-muted-foreground compact-header:h-6 compact-header:text-xs"
/>
- }
- >
- <Search className="size-4" />
- {active && (
- <span className="absolute -right-0.5 -top-0.5 size-2 rounded-full bg-primary ring-2 ring-background" />
- )}
- </PopoverTrigger>
- <PopoverContent
- align="end"
- sideOffset={8}
- className="app-no-drag z-[60] w-[340px] p-0"
- initialFocus={false}
- >
- <FilterSearchPanel
- tasks={tasks}
- types={types}
- onTypesChange={onTypesChange}
- typeCounts={typeCounts}
- onOpenTask={(task) => {
- onOpenTask(task)
- setOpen(false)
- }}
- />
- </PopoverContent>
- </Popover>
+ {query.length > 0 && (
+ <DownloadsToolbarButton
+ aria-label={t('panel.downloads.search.clearQuery')}
+ title={t('panel.downloads.search.clearQuery')}
+ onClick={() => {
+ onQueryChange('')
+ inputRef.current?.focus()
+ }}
+ >
+ <CircleX className="size-3.5" />
+ </DownloadsToolbarButton>
+ )}
+ </>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger
+ delay={400}
+ render={
+ <DownloadsToolbarButton
+ ref={searchRef}
+ aria-label={label}
+ aria-expanded={false}
+ aria-controls={inputId}
+ onClick={() => {
+ focusOnExpand.current = true
+ onExpandedChange(true)
+ }}
+ />
+ }
+ >
+ <Search className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent side="bottom" align="end" sideOffset={8}>
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
)
}
diff --git a/src/renderer/routes/downloads/filter-search-panel.test.tsx b/src/renderer/routes/downloads/filter-search-panel.test.tsx
index c299e4d9..7e83d9af 100644
--- a/src/renderer/routes/downloads/filter-search-panel.test.tsx
+++ b/src/renderer/routes/downloads/filter-search-panel.test.tsx
@@ -1,64 +1,14 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
-import type { DownloadTask } from '@shared/types/task'
-import { TaskStatus, TaskType } from '@shared/types/task'
-import { makeDownloadTask } from '@test-utils/task'
+import { TaskType } from '@shared/types/task'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeAll, describe, expect, it, vi } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import {
FilterSearchPanel,
type FilterSearchPanelProps,
} from './filter-search-panel'
-beforeAll(() => {
- Element.prototype.scrollIntoView = vi.fn()
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- }
- )
-})
-
-function fake(over: Partial<DownloadTask> = {}): DownloadTask {
- return makeDownloadTask({
- id: 't',
- engineTaskId: 'g',
- name: 'demo.iso',
- progress: 0.5,
- totalBytes: 1000,
- downloadedBytes: 500,
- saveDir: '/tmp',
- uris: ['https://example.com/demo.iso'],
- fileCount: 1,
- filename: 'demo.iso',
- sizeWhenDone: 1000,
- diskPath: '/tmp/demo.iso',
- finalPath: '/tmp/demo.iso',
- finalName: 'demo.iso',
- ...over,
- })
-}
-
-const tasks = [
- fake({ id: 'a', name: 'Ubuntu 24.04', type: TaskType.Http }),
- fake({
- id: 'b',
- name: 'Ubuntu server',
- type: TaskType.Magnet,
- status: TaskStatus.Completed,
- }),
- fake({ id: 'c', name: 'Fedora 41', type: TaskType.Bt }),
- fake({
- id: 'd',
- name: 'Ubuntu meta',
- type: TaskType.Http,
- status: TaskStatus.MetadataReady,
- }),
-]
const typeCounts = {
[TaskType.Http]: 2,
[TaskType.Magnet]: 1,
@@ -69,60 +19,45 @@ const typeCounts = {
function setup(props: Partial<FilterSearchPanelProps> = {}) {
const onTypesChange = vi.fn()
- const onOpenTask = vi.fn()
- const user = userEvent.setup()
render(
<FilterSearchPanel
- tasks={tasks}
types={[]}
onTypesChange={onTypesChange}
typeCounts={typeCounts}
- onOpenTask={onOpenTask}
{...props}
/>
)
- return { onTypesChange, onOpenTask, user }
+ return { onTypesChange, user: userEvent.setup() }
}
describe('FilterSearchPanel', () => {
- it('renders only matching tasks as the user types', async () => {
- const { user } = setup()
- await user.type(screen.getByPlaceholderText(/search downloads/i), 'ubuntu')
- expect(screen.getByText('Ubuntu 24.04')).toBeInTheDocument()
- expect(screen.getByText('Ubuntu server')).toBeInTheDocument()
- expect(screen.getByText('Ubuntu meta')).toBeInTheDocument()
- expect(screen.queryByText('Fedora 41')).not.toBeInTheDocument()
- })
-
- it('toggling a type chip calls onTypesChange', async () => {
- const { user, onTypesChange } = setup()
+ it('adds and removes types without replacing the other selected types', async () => {
+ const { user, onTypesChange } = setup({
+ types: [TaskType.Bt, TaskType.Http],
+ })
await user.click(screen.getByRole('button', { name: /HTTP/i }))
- expect(onTypesChange).toHaveBeenCalledWith([TaskType.Http])
+ expect(onTypesChange).toHaveBeenLastCalledWith([TaskType.Bt])
+ await user.click(screen.getByRole('button', { name: /Magnet/i }))
+ expect(onTypesChange).toHaveBeenLastCalledWith([
+ TaskType.Bt,
+ TaskType.Http,
+ TaskType.Magnet,
+ ])
})
-
- it('toggling an active type chip deselects it', async () => {
- const { user, onTypesChange } = setup({ types: [TaskType.Http] })
- await user.click(screen.getByRole('button', { name: /HTTP/i }))
+ it('disables unavailable unselected types but permits clearing a selected zero-count type', async () => {
+ const { user, onTypesChange } = setup({ types: [TaskType.Ftp] })
+ expect(screen.getByRole('button', { name: /Metalink/i })).toBeDisabled()
+ const ftp = screen.getByRole('button', { name: /FTP/i })
+ expect(ftp).toBeEnabled()
+ expect(ftp).toHaveAttribute('aria-pressed', 'true')
+ await user.click(ftp)
expect(onTypesChange).toHaveBeenCalledWith([])
})
-
- it('disables zero-count chips', () => {
- setup()
- expect(screen.getByRole('button', { name: /FTP/i })).toBeDisabled()
- })
-
- it('Enter on the highlighted result calls onOpenTask', async () => {
- const { user, onOpenTask } = setup()
- await user.type(screen.getByPlaceholderText(/search downloads/i), 'fedora')
- await user.keyboard('{Enter}')
- expect(onOpenTask).toHaveBeenCalledWith(
- expect.objectContaining({ id: 'c' })
- )
- })
-
- it('shows the empty state for no matches', async () => {
- const { user } = setup()
- await user.type(screen.getByPlaceholderText(/search downloads/i), 'zzzz')
- expect(screen.getByText(/no matching tasks/i)).toBeInTheDocument()
+ it('resets all type filters', async () => {
+ const { user, onTypesChange } = setup({
+ types: [TaskType.Http, TaskType.Bt],
+ })
+ await user.click(screen.getByRole('button', { name: 'Reset filters' }))
+ expect(onTypesChange).toHaveBeenCalledWith([])
})
})
diff --git a/src/renderer/routes/downloads/filter-search-panel.tsx b/src/renderer/routes/downloads/filter-search-panel.tsx
index f1ce67ee..8743e58c 100644
--- a/src/renderer/routes/downloads/filter-search-panel.tsx
+++ b/src/renderer/routes/downloads/filter-search-panel.tsx
@@ -1,172 +1,68 @@
-import {
- Command,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from '@renderer/components/ui/command'
-import { useByteFormat } from '@renderer/hooks/use-byte-format'
-import { formatProgressPercent } from '@renderer/lib/format'
import { TASK_TYPE_META, TASK_TYPE_ORDER } from '@renderer/lib/task-type-meta'
import { cn } from '@renderer/lib/utils'
-import type { DownloadTask } from '@shared/types/task'
-import { TaskStatus, type TaskType } from '@shared/types/task'
-import { useMemo, useState } from 'react'
+import type { TaskType } from '@shared/types/task'
import { useTranslation } from 'react-i18next'
-import { taskMatchesQuery } from './filter'
export interface FilterSearchPanelProps {
- tasks: readonly DownloadTask[]
types: readonly TaskType[]
onTypesChange: (next: TaskType[]) => void
typeCounts: Record<TaskType, number>
- onOpenTask: (task: DownloadTask) => void
-}
-
-// Finder result buckets, in display order. Keys map to panel.downloads.status.*
-const GROUP_ORDER: readonly TaskStatus[] = [
- TaskStatus.Downloading,
- TaskStatus.Queued,
- TaskStatus.FetchingMetadata,
- TaskStatus.MetadataReady,
- TaskStatus.Finalizing,
- TaskStatus.Seeding,
- TaskStatus.Paused,
- TaskStatus.Completed,
- TaskStatus.Error,
-]
-
-function statusKey(status: TaskStatus): string {
- switch (status) {
- case TaskStatus.FetchingMetadata:
- return 'fetchingMetadata'
- case TaskStatus.MetadataReady:
- return 'metadataReady'
- default:
- return status // 'downloading' | 'paused' | 'completed' | 'error' | ...
- }
}
export function FilterSearchPanel({
- tasks,
types,
onTypesChange,
typeCounts,
- onOpenTask,
}: FilterSearchPanelProps) {
- const { formatBytes } = useByteFormat()
-
const { t } = useTranslation()
- const [query, setQuery] = useState('')
-
- // Finder scope: all non-removed tasks, constrained by the active type chips.
- const scoped = useMemo(
- () =>
- tasks.filter(
- (x) =>
- x.status !== TaskStatus.Removed &&
- (types.length === 0 || types.includes(x.type))
- ),
- [tasks, types]
- )
- const results = useMemo(
- () => scoped.filter((x) => taskMatchesQuery(x, query)),
- [scoped, query]
- )
-
- const toggleType = (ty: TaskType) => {
- onTypesChange(
- types.includes(ty) ? types.filter((x) => x !== ty) : [...types, ty]
- )
- }
-
return (
- <Command shouldFilter={false} className="w-full">
- <CommandInput
- value={query}
- onValueChange={setQuery}
- placeholder={t('panel.downloads.search.placeholder')}
- autoFocus
- />
- <div className="flex flex-wrap items-center gap-1.5 border-b px-3 py-2">
- <span className="mr-1 text-[10px] uppercase tracking-wide text-muted-foreground">
+ <div className="space-y-2 p-3">
+ <div className="flex items-center justify-between gap-3 text-xs">
+ <span className="font-medium">
{t('panel.downloads.search.scopeLabel')}
</span>
- {TASK_TYPE_ORDER.map((ty) => {
- const meta = TASK_TYPE_META[ty]
+ <button
+ type="button"
+ disabled={types.length === 0}
+ onClick={() => onTypesChange([])}
+ className="rounded px-1 text-muted-foreground hover:text-foreground focus-visible:outline focus-visible:outline-1 focus-visible:outline-ring disabled:opacity-40"
+ >
+ {t('panel.downloads.search.resetFilters')}
+ </button>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {TASK_TYPE_ORDER.map((type) => {
+ const meta = TASK_TYPE_META[type]
const Icon = meta.icon
- const on = types.includes(ty)
- const count = typeCounts[ty]
+ const selected = types.includes(type)
+ const count = typeCounts[type]
return (
<button
- key={ty}
+ key={type}
type="button"
- disabled={count === 0}
- onClick={() => toggleType(ty)}
+ aria-pressed={selected}
+ disabled={count === 0 && !selected}
+ onClick={() =>
+ onTypesChange(
+ selected
+ ? types.filter((value) => value !== type)
+ : [...types, type]
+ )
+ }
className={cn(
- 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs',
- on
- ? 'border-primary/40 bg-primary/10 text-primary font-medium'
- : 'border-border text-muted-foreground',
- count === 0 && 'opacity-40'
+ 'inline-flex min-h-6 items-center gap-1 rounded-full border px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-40',
+ selected
+ ? 'border-[#7388a3]/50 bg-[#e4ebf3] text-[#31577d] dark:border-[#97aac4]/50 dark:bg-[#303d50] dark:text-[#b4c9e5]'
+ : 'border-border text-muted-foreground hover:bg-accent'
)}
>
<Icon className="size-3" />
{t(meta.labelKey)}
- <span className="opacity-60">{count}</span>
+ <span className="opacity-60 tabular-nums">{count}</span>
</button>
)
})}
- {types.length > 0 && (
- <button
- type="button"
- onClick={() => onTypesChange([])}
- className="ml-auto text-xs text-primary"
- >
- {t('panel.downloads.search.clear')}
- </button>
- )}
</div>
- <CommandList>
- {results.length === 0 ? (
- <div className="px-3 py-6 text-center">
- <p className="text-sm">{t('panel.downloads.search.empty')}</p>
- <p className="mt-1 text-xs text-muted-foreground">
- {t('panel.downloads.search.emptyHint')}
- </p>
- </div>
- ) : (
- GROUP_ORDER.map((status) => {
- const rows = results.filter((x) => x.status === status)
- if (rows.length === 0) return null
- return (
- <CommandGroup
- key={status}
- heading={t(`panel.downloads.status.${statusKey(status)}`)}
- >
- {rows.map((task) => {
- const Icon = TASK_TYPE_META[task.type].icon
- return (
- <CommandItem
- key={task.id}
- value={task.id}
- onSelect={() => onOpenTask(task)}
- >
- <Icon className="size-4" />
- <span className="flex-1 truncate">{task.name}</span>
- <span className="text-xs text-muted-foreground tabular-nums">
- {task.status === TaskStatus.Downloading
- ? `${formatProgressPercent(task.progress)}%`
- : formatBytes(task.sizeWhenDone)}
- </span>
- </CommandItem>
- )
- })}
- </CommandGroup>
- )
- })
- )}
- </CommandList>
- </Command>
+ </div>
)
}
diff --git a/src/renderer/routes/downloads/filter.ts b/src/renderer/routes/downloads/filter.ts
index 42d78e38..ca37905f 100644
--- a/src/renderer/routes/downloads/filter.ts
+++ b/src/renderer/routes/downloads/filter.ts
@@ -21,14 +21,16 @@ export function taskMatchesTab(task: DownloadTask, tab: DownloadsTab): boolean {
}
}
-/** Main-list filter: tab + protocol type. Search is NOT part of this. */
+/** Search and protocol filters share the current status tab's scope. */
export function applyFilter(
tasks: readonly DownloadTask[],
tab: DownloadsTab,
- types: readonly TaskType[]
+ types: readonly TaskType[],
+ query = ''
): readonly DownloadTask[] {
return tasks.filter((t) => {
if (!taskMatchesTab(t, tab)) return false
+ if (!taskMatchesQuery(t, query)) return false
if (types.length === 0) return true
return types.includes(t.type)
})
@@ -98,7 +100,7 @@ function normalize(s: string): string {
return s.normalize('NFC').toLowerCase()
}
-/** Finder match used by FilterSearchPanel (NOT by applyFilter). */
+/** Match task names, source URLs and categories without case sensitivity. */
export function taskMatchesQuery(task: DownloadTask, needle: string): boolean {
const n = normalize(needle.trim())
if (!n) return true
diff --git a/src/renderer/routes/downloads/format-task-timestamp.test.ts b/src/renderer/routes/downloads/format-task-timestamp.test.ts
new file mode 100644
index 00000000..dc57ddbb
--- /dev/null
+++ b/src/renderer/routes/downloads/format-task-timestamp.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from 'vitest'
+import { formatTaskTimestamp } from './format-task-timestamp'
+
+const now = Date.parse('2026-09-15T06:40:00Z')
+const format = (
+ date: string,
+ locale = 'zh-CN',
+ zone = 'Asia/Shanghai',
+ at = now
+) => formatTaskTimestamp(Date.parse(date), locale, at, zone)!
+
+// Intl may use a non-breaking space before day periods in some ICU releases.
+const spaces = (value: string) => value.replace(/[\u00a0\u202f]/g, ' ')
+
+describe('task timestamps', () => {
+ it('keeps seconds and uses local calendar days for today and yesterday', () => {
+ expect(format('2026-09-15T06:32:08Z').relative).toEqual({
+ date: '今天',
+ time: '14:32:08',
+ })
+ expect(format('2026-09-14T06:32:08Z').relative?.date).toBe('昨天')
+ // Only 15 minutes elapsed, but local midnight changed the calendar date.
+ expect(
+ format(
+ '2026-09-14T15:55:08Z',
+ 'zh-CN',
+ 'Asia/Shanghai',
+ Date.parse('2026-09-14T16:10:00Z')
+ ).relative?.date
+ ).toBe('昨天')
+ })
+
+ it('omits the current year only in the list and includes it for older dates', () => {
+ const recent = format('2026-09-12T06:32:08Z')
+ expect(recent.relative).toBeNull()
+ expect(recent.compact).toBe('9月12日 14:32:08')
+ expect(recent.full).toBe('2026年9月12日 14:32:08')
+ expect(recent.detailed).toContain('GMT+8')
+ expect(format('2025-12-08T06:32:08Z').compact).toBe(
+ '2025年12月8日 14:32:08'
+ )
+ expect(recent.iso).toBe('2026-09-12T06:32:08.000Z')
+ })
+
+ it('handles yesterday across a year boundary before considering year omission', () => {
+ const result = format(
+ '2025-12-31T12:32:08Z',
+ 'en-US',
+ 'UTC',
+ Date.parse('2026-01-01T08:00:00Z')
+ )
+ expect(result.relative?.date).toBe('yesterday')
+ expect(spaces(result.relative!.time)).toBe('12:32:08 PM')
+ expect(result.full).toContain('2025')
+ })
+
+ it.each([
+ ['2026-03-08T05:10:08Z', '2026-03-09T04:05:00Z'],
+ ['2026-11-01T04:10:08Z', '2026-11-02T05:05:00Z'],
+ ])('handles 23-hour and 25-hour local days: %s', (timestamp, at) => {
+ expect(
+ format(timestamp, 'en-US', 'America/New_York', Date.parse(at)).relative
+ ?.date
+ ).toBe('yesterday')
+ })
+
+ it('changes calendar labels and historical offset when the viewing zone changes', () => {
+ const timestamp = '2026-09-14T16:32:08Z'
+ expect(format(timestamp).relative?.date).toBe('今天')
+ expect(format(timestamp, 'zh-CN', 'UTC').relative?.date).toBe('昨天')
+ expect(
+ format('2026-01-15T06:32:08Z', 'en-US', 'America/New_York').detailed
+ ).toContain('GMT-5')
+ expect(
+ format('2026-07-15T06:32:08Z', 'en-US', 'America/New_York').detailed
+ ).toContain('GMT-4')
+ })
+
+ it.each([
+ 'en-US',
+ 'zh-CN',
+ 'zh-TW',
+ 'de-DE',
+ 'fr-FR',
+ 'ja-JP',
+ 'ar-EG',
+ 'th-TH',
+ 'en-US-u-hc-h23',
+ ])(
+ 'delegates date order, digits, calendar and hour cycle to Intl: %s',
+ (locale) => {
+ const timestamp = Date.parse('2026-09-12T06:32:08Z')
+ const result = formatTaskTimestamp(timestamp, locale, now, 'UTC')!
+ const expected = new Intl.DateTimeFormat(locale, {
+ timeZone: 'UTC',
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit',
+ })
+ expect(result.full).toBe(expected.format(timestamp))
+ expect(
+ expected.formatToParts(timestamp).find((part) => part.type === 'second')
+ ).toBeDefined()
+ expect(formatTaskTimestamp(now, locale, now, 'UTC')!.relative!.date).toBe(
+ new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(
+ 0,
+ 'day'
+ )
+ )
+ }
+ )
+
+ it('keeps an explicit calendar year across a non-Gregorian new year', () => {
+ // Rosh Hashanah 2026 falls within a single Gregorian year.
+ const result = format('2026-09-01T06:32:08Z', 'en-US-u-ca-hebrew', 'UTC')
+ expect(result.compact).toBe(result.full)
+ expect(result.full).toContain('5786')
+ })
+
+ it('does not label future dates as today or yesterday', () => {
+ expect(format('2026-09-16T06:32:08Z').relative).toBeNull()
+ })
+
+ it.each([null, 0, -1, Number.NaN, Infinity, 1e20])(
+ 'rejects missing or invalid timestamps: %s',
+ (timestamp) => {
+ expect(formatTaskTimestamp(timestamp, 'en-US', now, 'UTC')).toBeNull()
+ }
+ )
+})
diff --git a/src/renderer/routes/downloads/format-task-timestamp.ts b/src/renderer/routes/downloads/format-task-timestamp.ts
new file mode 100644
index 00000000..59cf2c38
--- /dev/null
+++ b/src/renderer/routes/downloads/format-task-timestamp.ts
@@ -0,0 +1,112 @@
+interface TimestampFormatters {
+ calendarDay: Intl.DateTimeFormat
+ calendarYear: Intl.DateTimeFormat
+ compact: Intl.DateTimeFormat
+ full: Intl.DateTimeFormat
+ detailed: Intl.DateTimeFormat
+ time: Intl.DateTimeFormat
+ relative: Intl.RelativeTimeFormat
+}
+
+const cache = new Map<string, TimestampFormatters>()
+let environment: { now: number; timeZone: string } | undefined
+
+/** Resolve the device zone once per shared clock tick, including after resume. */
+function localTimeZone(now: number): string {
+ if (environment?.now !== now) {
+ environment = {
+ now,
+ timeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
+ }
+ }
+ return environment.timeZone
+}
+
+function getFormatters(locale: string, timeZone: string): TimestampFormatters {
+ const key = JSON.stringify([locale, timeZone])
+ const cached = cache.get(key)
+ if (cached) return cached
+ const dateTime: Intl.DateTimeFormatOptions = {
+ timeZone,
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit',
+ }
+ const formatters = {
+ // ISO day numbers are internal arithmetic; UI always uses the requested locale.
+ calendarDay: new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ calendar: 'iso8601',
+ numberingSystem: 'latn',
+ year: 'numeric',
+ month: 'numeric',
+ day: 'numeric',
+ }),
+ calendarYear: new Intl.DateTimeFormat(locale, {
+ timeZone,
+ year: 'numeric',
+ era: 'short',
+ }),
+ compact: new Intl.DateTimeFormat(locale, dateTime),
+ full: new Intl.DateTimeFormat(locale, { ...dateTime, year: 'numeric' }),
+ detailed: new Intl.DateTimeFormat(locale, {
+ ...dateTime,
+ year: 'numeric',
+ timeZoneName: 'shortOffset',
+ }),
+ time: new Intl.DateTimeFormat(locale, {
+ timeZone,
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit',
+ }),
+ relative: new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }),
+ }
+ // Bound the cache when users change language or device time zone repeatedly.
+ if (cache.size >= 16) cache.clear()
+ cache.set(key, formatters)
+ return formatters
+}
+
+function calendarDay(timestamp: number, formatter: Intl.DateTimeFormat) {
+ const parts = formatter.formatToParts(timestamp)
+ const value = (type: Intl.DateTimeFormatPartTypes) =>
+ Number(parts.find((part) => part.type === type)?.value)
+ // Compare calendar dates, not elapsed 24-hour periods across DST changes.
+ return Date.UTC(value('year'), value('month') - 1, value('day')) / 86_400_000
+}
+
+export function formatTaskTimestamp(
+ timestamp: number | null,
+ locale: string,
+ now: number,
+ timeZone = localTimeZone(now)
+) {
+ if (
+ timestamp === null ||
+ timestamp <= 0 ||
+ !Number.isFinite(new Date(timestamp).getTime())
+ ) {
+ return null
+ }
+ const f = getFormatters(locale, timeZone)
+ const days =
+ calendarDay(timestamp, f.calendarDay) - calendarDay(now, f.calendarDay)
+ const sameYear =
+ f.calendarYear.format(timestamp) === f.calendarYear.format(now)
+ return {
+ iso: new Date(timestamp).toISOString(),
+ compact: (sameYear ? f.compact : f.full).format(timestamp),
+ full: f.full.format(timestamp),
+ detailed: f.detailed.format(timestamp),
+ relative:
+ days === 0 || days === -1
+ ? {
+ date: f.relative.format(days, 'day'),
+ time: f.time.format(timestamp),
+ }
+ : null,
+ }
+}
diff --git a/src/renderer/routes/downloads/global-stats-bar.test.tsx b/src/renderer/routes/downloads/global-stats-bar.test.tsx
index e5fc84fa..be5c6af0 100644
--- a/src/renderer/routes/downloads/global-stats-bar.test.tsx
+++ b/src/renderer/routes/downloads/global-stats-bar.test.tsx
@@ -49,8 +49,6 @@ vi.mock('@renderer/lib/transport', () => ({
import { GlobalStatsBar } from './global-stats-bar'
-const motrixCounts = { all: 7, active: 2, completed: 3, error: 2 }
-
const testPlatformServices: PlatformServices = {
kind: 'electron',
pickSaveDir: vi.fn(async () => null),
@@ -64,24 +62,13 @@ describe('GlobalStatsBar', () => {
it('renders formatted speeds with engine and nat badges', async () => {
render(
<PlatformServicesProvider services={testPlatformServices}>
- <GlobalStatsBar counts={motrixCounts} />
+ <GlobalStatsBar />
</PlatformServicesProvider>
)
- expect(screen.getByText(/16\.5 MB\/s/)).toBeInTheDocument()
+ const [upload, download] = screen.getAllByRole('definition')
+ expect(upload).toHaveTextContent('4.0 MB/s')
+ expect(download).toHaveTextContent('16.5 MB/s')
expect(await screen.findByText(/Engine ready/)).toBeInTheDocument()
expect(await screen.findByText(/NAT mapped/)).toBeInTheDocument()
})
-
- it('uses Motrix task counts instead of aria2 runtime counts', () => {
- render(
- <PlatformServicesProvider services={testPlatformServices}>
- <GlobalStatsBar counts={motrixCounts} />
- </PlatformServicesProvider>
- )
-
- expect(
- screen.getByText('Active 2 · Completed 3 · Error 2')
- ).toBeInTheDocument()
- expect(screen.queryByText(/Completed 42/)).not.toBeInTheDocument()
- })
})
diff --git a/src/renderer/routes/downloads/global-stats-bar.tsx b/src/renderer/routes/downloads/global-stats-bar.tsx
index 5b928da0..c488ba85 100644
--- a/src/renderer/routes/downloads/global-stats-bar.tsx
+++ b/src/renderer/routes/downloads/global-stats-bar.tsx
@@ -1,45 +1,16 @@
-import { useByteFormat } from '@renderer/hooks/use-byte-format'
-import { useGlobalStats } from '@renderer/hooks/use-global-stats'
-
-import { useTranslation } from 'react-i18next'
import { EngineBadge } from './engine-badge'
-import type { DownloadsTab } from './filter'
import { NatBadge } from './nat-badge'
+import { SpeedLimitBadge } from './speed-limit-badge'
+import { TransferSpeedBadge } from './transfer-speed-badge'
-interface GlobalStatsBarProps {
- counts: Record<DownloadsTab, number>
-}
-
-export function GlobalStatsBar({ counts }: GlobalStatsBarProps) {
- const { formatSpeed } = useByteFormat()
-
- const { t } = useTranslation()
- const { stats } = useGlobalStats()
-
+export function GlobalStatsBar() {
return (
<>
- <div className="flex items-center gap-4 text-[11.5px] text-muted-foreground">
- <span className="tabular-nums">
- {t('panel.downloads.stats.downSpeed')}{' '}
- <span className="text-foreground">
- {stats ? formatSpeed(stats.totalDownloadSpeed) : '—'}
- </span>
- </span>
- <span className="tabular-nums">
- {t('panel.downloads.stats.upSpeed')}{' '}
- <span className="text-foreground">
- {stats ? formatSpeed(stats.totalUploadSpeed) : '—'}
- </span>
- </span>
- <span className="tabular-nums">
- {t('panel.downloads.stats.counts', {
- active: counts.active,
- completed: counts.completed,
- error: counts.error,
- })}
- </span>
+ <div className="flex min-w-0 items-center gap-2">
+ <SpeedLimitBadge />
+ <TransferSpeedBadge />
</div>
- <div className="flex items-center gap-3 text-[11.5px]">
+ <div className="flex shrink-0 items-center gap-3 text-[11.5px]">
<NatBadge />
<EngineBadge />
</div>
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
index a0a56780..b841e805 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
@@ -3,7 +3,11 @@ import '@testing-library/jest-dom/vitest'
import { vi } from 'vitest'
vi.mock('@renderer/lib/transport', () => ({
- transport: { invoke: vi.fn().mockResolvedValue({ ok: true }) },
+ transport: {
+ invoke: vi.fn().mockResolvedValue({ ok: true }),
+ on: vi.fn(),
+ off: vi.fn(),
+ },
}))
vi.mock('@renderer/lib/open-add-task-dialog', () => ({
openAddTaskDialog: vi.fn().mockResolvedValue(undefined),
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.tsx b/src/renderer/routes/downloads/inspector/overview-tab.tsx
index 8f2b2791..e53af487 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.tsx
@@ -12,17 +12,16 @@ import {
TooltipTrigger,
} from '@renderer/components/ui/tooltip'
import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import type { TaskInspectorActivitySnapshotCache } from '@renderer/hooks/use-task-inspector-activity'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
-import {
- formatDateTime,
- formatDurationHMS,
- formatProgressPercent,
-} from '@renderer/lib/format'
+import { formatDurationHMS, formatProgressPercent } from '@renderer/lib/format'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
import { canAttemptRetry } from '@shared/types/task-actions'
import { AlertCircleIcon, RotateCcw } from 'lucide-react'
import { useTranslation } from 'react-i18next'
+import { TaskTimestamp } from '../task-timestamp'
+import { SeedingDuration } from './seeding-duration'
import { useTaskActions } from './use-task-actions'
function Card({
@@ -63,32 +62,6 @@ function Row({
)
}
-function TaskTimestamp({
- timestamp,
- locale,
-}: {
- timestamp: number | null
- locale: string
-}) {
- const date = timestamp !== null ? new Date(timestamp) : null
- if (
- timestamp === null ||
- timestamp <= 0 ||
- !date ||
- !Number.isFinite(date.getTime())
- ) {
- return <span>—</span>
- }
- return (
- <time
- className="ml-auto text-right tabular-nums"
- dateTime={date.toISOString()}
- >
- {formatDateTime(timestamp, locale)}
- </time>
- )
-}
-
function ErrorPanel({ task }: { task: DownloadTask }) {
const { t, i18n } = useTranslation()
const { onRetry } = useTaskActions([task])
@@ -136,7 +109,13 @@ function ErrorPanel({ task }: { task: DownloadTask }) {
)
}
-export function OverviewTab({ task }: { task: DownloadTask }) {
+export function OverviewTab({
+ task,
+ snapshotCache,
+}: {
+ task: DownloadTask
+ snapshotCache?: TaskInspectorActivitySnapshotCache
+}) {
const { formatSpeed, formatBytes } = useByteFormat()
const { t, i18n } = useTranslation()
@@ -164,6 +143,23 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
label={t('panel.downloads.inspector.overview.downloaded')}
value={formatBytes(task.downloadedBytes)}
/>
+ {isBt && (
+ <Row
+ label={t('panel.downloads.inspector.overview.uploaded')}
+ value={formatBytes(task.uploadedBytes)}
+ />
+ )}
+ {isBt && (
+ <Row
+ label={t('panel.downloads.inspector.overview.seedingTime')}
+ value={
+ <SeedingDuration
+ taskId={task.id}
+ snapshotCache={snapshotCache}
+ />
+ }
+ />
+ )}
<Row
label={t('panel.downloads.inspector.overview.totalSize')}
value={formatBytes(task.sizeWhenDone)}
@@ -186,7 +182,10 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
/>
<Row
label={t('panel.downloads.inspector.overview.ratio')}
- value={task.bt.ratio.toFixed(2)}
+ value={new Intl.NumberFormat(i18n.language, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }).format(task.bt.ratio)}
/>
</>
) : (
@@ -231,10 +230,7 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
<Row
label={t('panel.downloads.inspector.overview.createdAt')}
value={
- <TaskTimestamp
- timestamp={task.createdAt}
- locale={i18n.language}
- />
+ <TaskTimestamp timestamp={task.createdAt} variant="inspector" />
}
/>
{task.status === TaskStatus.Completed && (
@@ -243,7 +239,7 @@ export function OverviewTab({ task }: { task: DownloadTask }) {
value={
<TaskTimestamp
timestamp={task.finishedAt}
- locale={i18n.language}
+ variant="inspector"
/>
}
/>
diff --git a/src/renderer/routes/downloads/inspector/seeding-duration.test.tsx b/src/renderer/routes/downloads/inspector/seeding-duration.test.tsx
new file mode 100644
index 00000000..c91c9993
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/seeding-duration.test.tsx
@@ -0,0 +1,28 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import type { TaskInspectorActivityState } from '@renderer/hooks/use-task-inspector-activity'
+import { makeTaskInspectorActivitySnapshot } from '@test-utils/task-inspector-activity'
+import { cleanup, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { SeedingDuration } from './seeding-duration'
+
+let activity: TaskInspectorActivityState = { status: 'loading', snapshot: null }
+vi.mock('@renderer/hooks/use-task-inspector-activity', () => ({
+ useTaskInspectorActivity: () => activity,
+}))
+afterEach(cleanup)
+
+describe('SeedingDuration', () => {
+ it('distinguishes missing historical data from a recorded zero', () => {
+ const snapshot = makeTaskInspectorActivitySnapshot()
+ activity = { status: 'ready', snapshot }
+ const { rerender } = render(<SeedingDuration taskId="task-1" />)
+ expect(screen.getByText('—')).toBeInTheDocument()
+ snapshot.summary.seeding = { activeMs: 0, trackingStartedAt: 1000 }
+ rerender(<SeedingDuration taskId="task-1" />)
+ expect(screen.getByText('00:00')).toBeInTheDocument()
+ snapshot.summary.seeding.activeMs = 3_661_000
+ rerender(<SeedingDuration taskId="task-1" />)
+ expect(screen.getByText('1:01:01')).toBeInTheDocument()
+ })
+})
diff --git a/src/renderer/routes/downloads/inspector/seeding-duration.tsx b/src/renderer/routes/downloads/inspector/seeding-duration.tsx
new file mode 100644
index 00000000..741f705d
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/seeding-duration.tsx
@@ -0,0 +1,55 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@renderer/components/ui/tooltip'
+import {
+ type TaskInspectorActivitySnapshotCache,
+ useTaskInspectorActivity,
+} from '@renderer/hooks/use-task-inspector-activity'
+import { formatDurationHMS } from '@renderer/lib/format'
+import { useTranslation } from 'react-i18next'
+import { formatTaskTimestamp } from '../format-task-timestamp'
+
+export function SeedingDuration({
+ taskId,
+ snapshotCache,
+}: {
+ taskId: string
+ snapshotCache?: TaskInspectorActivitySnapshotCache
+}) {
+ const { t, i18n } = useTranslation()
+ const activity = useTaskInspectorActivity(taskId, snapshotCache)
+ const seeding = activity.snapshot?.summary.seeding
+ const value = seeding
+ ? seeding.activeMs === 0
+ ? '00:00'
+ : formatDurationHMS(seeding.activeMs / 1000)
+ : '—'
+ const since = seeding
+ ? formatTaskTimestamp(seeding.trackingStartedAt, i18n.language, Date.now())
+ ?.full
+ : null
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="tabular-nums" data-slot="task-seeding-duration" />
+ }
+ >
+ {value}
+ </TooltipTrigger>
+ <TooltipContent side="top" align="start" className="max-w-64">
+ {since
+ ? t('panel.downloads.inspector.overview.seedingRecordedSince', {
+ date: since,
+ })
+ : t('panel.downloads.inspector.overview.seedingUnavailable')}
+ {(activity.status === 'stale' ||
+ activity.snapshot?.summary.coverageGapAt != null) && (
+ <p>{t('panel.downloads.inspector.activity.coverageGap')}</p>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/src/renderer/routes/downloads/inspector/task-copy-url.ts b/src/renderer/routes/downloads/inspector/task-copy-url.ts
new file mode 100644
index 00000000..64a93bbe
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/task-copy-url.ts
@@ -0,0 +1,28 @@
+import { fetchTaskBtDetail } from '@renderer/hooks/use-task-bt-detail'
+import { infoHashToMagnetUri } from '@renderer/lib/magnet'
+import type { DownloadTask } from '@shared/types/task'
+import { isTorrentLike } from '@shared/types/task-actions'
+
+export async function getTaskCopyUrl(task: DownloadTask): Promise<string> {
+ if (isTorrentLike(task)) {
+ // Broadcasts omit magnet/tracker details. Resolve them at click time;
+ // a failed fetch must never silently copy a tracker-less magnet.
+ const detail = await fetchTaskBtDetail(task.id)
+ if (detail.magnetUri) return detail.magnetUri
+ if (task.infoHash) {
+ return infoHashToMagnetUri(task.infoHash, {
+ name: task.name,
+ trackers: detail.announceList.flat(),
+ })
+ }
+ }
+ return task.uris[0] ?? ''
+}
+
+export async function copyTaskUrls(
+ tasks: readonly DownloadTask[]
+): Promise<void> {
+ const urls = await Promise.all(tasks.map(getTaskCopyUrl))
+ // Resolve the entire selection before replacing the clipboard.
+ await navigator.clipboard.writeText(urls.join('\n'))
+}
diff --git a/src/renderer/routes/downloads/inspector/task-error-report.ts b/src/renderer/routes/downloads/inspector/task-error-report.ts
new file mode 100644
index 00000000..0dbdb2cd
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/task-error-report.ts
@@ -0,0 +1,33 @@
+import {
+ type FailureReasonI18n,
+ resolveFailureReason,
+} from '@renderer/lib/failure-reason'
+import type { DownloadTask } from '@shared/types/task'
+import { TaskStatus } from '@shared/types/task'
+
+export function taskErrorReport(
+ tasks: readonly DownloadTask[],
+ i18n: FailureReasonI18n
+): string {
+ return tasks
+ .filter((task) => task.status === TaskStatus.Error)
+ .map((task) => {
+ const failure = resolveFailureReason(task, i18n)
+ const details = [
+ ...new Set(
+ [
+ task.errorCode,
+ failure.reason,
+ failure.hint,
+ failure.technicalDetail,
+ ].filter(Boolean)
+ ),
+ ].join('\n')
+ return i18n.t('panel.downloads.action.errorReport', {
+ name: task.name,
+ id: task.id,
+ details,
+ })
+ })
+ .join('\n\n')
+}
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 0ee8352c..bdf1536a 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
@@ -44,6 +44,60 @@ function makeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {
}
describe('TaskInspectorActionBar', () => {
+ it('opens a completed file from the inspector and allows retry after failure', async () => {
+ vi.mocked(transport.invoke).mockClear()
+ let reject!: (error: Error) => void
+ vi.mocked(transport.invoke).mockReturnValueOnce(
+ new Promise((_resolve, fail) => {
+ reject = fail
+ })
+ )
+ render(
+ <TaskInspectorActionBar
+ selected={[makeTask({ status: TaskStatus.Completed })]}
+ onClose={vi.fn()}
+ />
+ )
+ const button = screen.getByRole('button', { name: 'Open file' })
+ fireEvent.click(button)
+ fireEvent.click(button)
+ expect(transport.invoke).toHaveBeenCalledTimes(1)
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.OpenTaskFile, {
+ taskId: 't1',
+ })
+ expect(button).toHaveProperty('disabled', true)
+ reject(new Error('File no longer exists'))
+ await waitFor(() =>
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'Could not open file',
+ description: 'File no longer exists',
+ type: 'error',
+ })
+ )
+ )
+ await waitFor(() => expect(button).toHaveProperty('disabled', false))
+ fireEvent.click(button)
+ await waitFor(() => expect(transport.invoke).toHaveBeenCalledTimes(2))
+ })
+
+ it.each(
+ [
+ [makeTask({ status: TaskStatus.Downloading })],
+ [makeTask({ status: TaskStatus.Finalizing })],
+ [makeTask({ status: TaskStatus.Error })],
+ [makeTask({ status: TaskStatus.Completed, fileCount: 2 })],
+ [makeTask({ status: TaskStatus.Completed, finalPath: '', diskPath: '' })],
+ [
+ makeTask({ id: 'a', status: TaskStatus.Completed }),
+ makeTask({ id: 'b', status: TaskStatus.Completed }),
+ ],
+ ].map((selected) => ({ selected }))
+ )('hides Open file for ineligible selections: $selected', ({ selected }) => {
+ render(<TaskInspectorActionBar selected={selected} onClose={vi.fn()} />)
+ expect(screen.queryByRole('button', { name: 'Open file' })).toBeNull()
+ })
+
it('Downloading single: shows Pause + Copy URL + Remove', () => {
render(
<TaskInspectorActionBar
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
index 3471ae51..a2661442 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
@@ -3,17 +3,16 @@ import { MagnetFileSelectionButton } from '@renderer/components/task/magnet-file
import { Button } from '@renderer/components/ui/button'
import { toast } from '@renderer/components/ui/toast'
import { useModifierKeys } from '@renderer/hooks/use-modifier-keys'
-import { fetchTaskBtDetail } from '@renderer/hooks/use-task-bt-detail'
-import { infoHashToMagnetUri } from '@renderer/lib/magnet'
import { rtlMirror } from '@renderer/lib/task-status-ui'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import { Commands } from '@shared/protocol/commands'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
-import { isTorrentLike } from '@shared/types/task-actions'
+import { canOpenTaskFile } from '@shared/types/task-actions'
import {
ChevronDown,
+ File,
FolderOpen,
Pause,
Play,
@@ -23,14 +22,17 @@ import {
Trash2,
} from 'lucide-react'
import type React from 'react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { canRevealTaskFolder } from './can-reveal-task-folder'
import { RemoveTasksDialog } from './remove-tasks-dialog'
+import { copyTaskUrls } from './task-copy-url'
import { useTaskActions } from './use-task-actions'
export interface TaskInspectorActionBarProps {
selected: readonly DownloadTask[]
onClose: () => void
+ resizeHandle?: React.ReactNode
}
/**
@@ -42,30 +44,12 @@ async function copyTaskUrl(
task: DownloadTask,
onFailure: () => void
): Promise<void> {
- let url: string
try {
- url = await getCopyUrl(task)
+ await copyTaskUrls([task])
} catch (error) {
onFailure()
throw error
}
- await navigator.clipboard.writeText(url)
-}
-
-async function getCopyUrl(task: DownloadTask): Promise<string> {
- if (isTorrentLike(task)) {
- // magnetUri/announceList are projected out of the broadcast (option E);
- // fetch the full per-task detail at click time.
- const detail = await fetchTaskBtDetail(task.id)
- if (detail.magnetUri) return detail.magnetUri
- if (task.infoHash) {
- return infoHashToMagnetUri(task.infoHash, {
- name: task.name,
- trackers: detail.announceList.flat(),
- })
- }
- }
- return task.uris[0] ?? ''
}
interface CountedButtonProps {
@@ -112,12 +96,45 @@ function CountedButton({
)
}
+function OpenTaskFileButton({ task }: { task: DownloadTask }) {
+ const { t } = useTranslation()
+ const [opening, setOpening] = useState(false)
+ const open = async () => {
+ if (opening) return
+ setOpening(true)
+ try {
+ await transport.invoke(Commands.OpenTaskFile, { taskId: task.id })
+ } catch (error) {
+ toast.add({
+ title: t('panel.downloads.action.openFileFailed'),
+ description: error instanceof Error ? error.message : String(error),
+ type: 'error',
+ })
+ } finally {
+ setOpening(false)
+ }
+ }
+ return (
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={opening}
+ onClick={() => void open()}
+ >
+ <File />
+ {t('panel.downloads.action.openFile')}
+ </Button>
+ )
+}
+
function FinalizingActionBar({
task,
onClose,
+ resizeHandle,
}: {
task: DownloadTask
onClose: () => void
+ resizeHandle?: React.ReactNode
}) {
const { t } = useTranslation()
const reason = t('panel.downloads.action.finalizingTooltip')
@@ -153,6 +170,7 @@ function FinalizingActionBar({
>
{t('panel.downloads.action.copyUrl')}
</CopyButton>
+ {resizeHandle}
<Button
size="xs"
variant="outline"
@@ -178,6 +196,7 @@ function FinalizingActionBar({
export function TaskInspectorActionBar({
selected,
onClose,
+ resizeHandle,
}: TaskInspectorActionBarProps) {
const { t } = useTranslation()
const { shift, alt } = useModifierKeys()
@@ -185,7 +204,13 @@ export function TaskInspectorActionBar({
const actions = useTaskActions(selected)
if (single && single.status === TaskStatus.Finalizing) {
- return <FinalizingActionBar task={single} onClose={onClose} />
+ return (
+ <FinalizingActionBar
+ task={single}
+ onClose={onClose}
+ resizeHandle={resizeHandle}
+ />
+ )
}
return (
@@ -274,6 +299,9 @@ export function TaskInspectorActionBar({
<MagnetFileSelectionButton task={single} />
)}
+ {single &&
+ __MOTRIX_TARGET__ === 'electron' &&
+ canOpenTaskFile(single) && <OpenTaskFileButton task={single} />}
{single &&
__MOTRIX_TARGET__ === 'electron' &&
canRevealTaskFolder(single) && (
@@ -325,6 +353,7 @@ export function TaskInspectorActionBar({
onClick={(e) => actions.onRemove({ shift: e.shiftKey })}
/>
+ {resizeHandle}
<Button
size="icon-xs"
variant="ghost"
@@ -338,7 +367,7 @@ export function TaskInspectorActionBar({
<RemoveTasksDialog
open={actions.removeDialog.open}
- selected={selected}
+ selected={actions.removeTargets}
preCheckDeleteFiles={actions.removeDialog.preCheckDeleteFiles}
onOpenChange={(open) => {
if (!open) actions.closeRemoveDialog()
diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.ts b/src/renderer/routes/downloads/inspector/use-task-actions.ts
index 1ef5da42..9d6316f3 100644
--- a/src/renderer/routes/downloads/inspector/use-task-actions.ts
+++ b/src/renderer/routes/downloads/inspector/use-task-actions.ts
@@ -3,11 +3,16 @@ import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { transport } from '@renderer/lib/transport'
import { type CommandChannel, Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
+import {
+ type MoveTasksPayload,
+ moveTasksResultSchema,
+} from '@shared/schemas/move-tasks'
import type { EngineTaskOptions } from '@shared/types/engine-task-options'
import type { DownloadTask } from '@shared/types/task'
import type { BulkTaskCommandResult } from '@shared/types/task-actions'
import {
canAttemptRetry,
+ canMoveInQueue,
canPause,
canRemove,
canReseed,
@@ -128,6 +133,9 @@ function buildPrefillFromTask(
}
export interface TaskActionsState {
+ moveCount: number
+ moving: boolean
+ onMove: (direction: MoveTasksPayload['direction']) => Promise<void>
pauseCount: number
resumeCount: number
stopSeedingCount: number
@@ -137,6 +145,7 @@ export interface TaskActionsState {
total: number
removeDialog: RemoveDialogState
+ removeTargets: readonly DownloadTask[]
onPause: () => Promise<void>
onResume: () => Promise<void>
@@ -152,10 +161,14 @@ export function useTaskActions(
selected: readonly DownloadTask[]
): TaskActionsState {
const { t } = useTranslation()
+ const [moving, setMoving] = useState(false)
const [removeDialog, setRemoveDialog] = useState<RemoveDialogState>({
open: false,
preCheckDeleteFiles: false,
})
+ const [removeTargets, setRemoveTargets] = useState<readonly DownloadTask[]>(
+ []
+ )
const counts = useMemo(() => {
let pauseCount = 0
@@ -173,6 +186,7 @@ export function useTaskActions(
if (canRemove(task)) removeCount++
}
return {
+ moveCount: selected.filter(canMoveInQueue).length,
pauseCount,
resumeCount,
stopSeedingCount,
@@ -234,6 +248,55 @@ export function useTaskActions(
[dispatchSubset]
)
+ const onMove = useCallback(
+ async (direction: MoveTasksPayload['direction']) => {
+ const targets = selected.filter(canMoveInQueue)
+ if (moving || !targets.length) return
+ setMoving(true)
+ try {
+ const result = moveTasksResultSchema.parse(
+ await transport.invoke(Commands.MoveTasks, {
+ taskIds: targets.map((task) => task.id),
+ direction,
+ })
+ )
+ if (result.failed.length) {
+ reportPartial(
+ toActionResults(targets, {
+ succeeded: [...result.moved, ...result.unchanged],
+ failed: result.failed.map((entry) => ({
+ ...entry,
+ reason: t(
+ entry.reason === 'not-waiting'
+ ? 'panel.downloads.action.queueTaskStarted'
+ : 'panel.downloads.action.queueMoveFailed'
+ ),
+ })),
+ })
+ )
+ } else {
+ toast.add({
+ title: t(
+ result.moved.length
+ ? 'panel.downloads.action.queueMoved'
+ : 'panel.downloads.action.queueBoundary'
+ ),
+ description: t('panel.downloads.action.queueMoveHint'),
+ type: 'info',
+ })
+ }
+ } catch {
+ toast.add({
+ title: t('panel.downloads.action.queueMoveFailed'),
+ type: 'error',
+ })
+ } finally {
+ setMoving(false)
+ }
+ },
+ [selected, moving, reportPartial, t]
+ )
+
const onStopSeeding = useCallback(
() => dispatchSubset(Commands.StopSeedingTasks, canStopSeeding),
[dispatchSubset]
@@ -287,12 +350,16 @@ export function useTaskActions(
[selected, altReAddSingle, dispatchSubset]
)
- const onRemove = useCallback((modifier?: { shift: boolean }) => {
- setRemoveDialog({
- open: true,
- preCheckDeleteFiles: modifier?.shift ?? false,
- })
- }, [])
+ const onRemove = useCallback(
+ (modifier?: { shift: boolean }) => {
+ setRemoveTargets([...selected])
+ setRemoveDialog({
+ open: true,
+ preCheckDeleteFiles: modifier?.shift ?? false,
+ })
+ },
+ [selected]
+ )
const closeRemoveDialog = useCallback(() => {
setRemoveDialog({ open: false, preCheckDeleteFiles: false })
@@ -300,7 +367,7 @@ export function useTaskActions(
const confirmRemove = useCallback(
async (deleteFiles: boolean) => {
- const targets = selected.filter(canRemove)
+ const targets = removeTargets.filter(canRemove)
if (targets.length > 0) {
const results = await invokeBulk(Commands.RemoveTasks, targets, {
taskIds: targets.map((task) => task.id),
@@ -310,12 +377,15 @@ export function useTaskActions(
}
setRemoveDialog({ open: false, preCheckDeleteFiles: false })
},
- [selected, reportPartial]
+ [removeTargets, reportPartial]
)
return {
...counts,
+ moving,
+ onMove,
removeDialog,
+ removeTargets,
onPause,
onResume,
onStopSeeding,
diff --git a/src/renderer/routes/downloads/list-view-menu.tsx b/src/renderer/routes/downloads/list-view-menu.tsx
new file mode 100644
index 00000000..76317c97
--- /dev/null
+++ b/src/renderer/routes/downloads/list-view-menu.tsx
@@ -0,0 +1,215 @@
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { Columns3, Info } from 'lucide-react'
+import type { Ref } from 'react'
+import { useTranslation } from 'react-i18next'
+import { DownloadsToolbarButton } from './downloads-toolbar-button'
+import {
+ DEFAULT_TASK_SORT,
+ nextTaskSort,
+ TASK_SORT_COLUMNS,
+ type TaskSortColumn,
+} from './sort'
+import { useDownloadsSort } from './store'
+import type { TaskMenuShortcut } from './task-menu-shortcuts'
+import { useDownloadsView } from './view-preferences'
+
+export function ColumnVisibilityItems() {
+ const { t } = useTranslation()
+ const columns = useDownloadsView((state) => state.columns)
+ const setVisible = useDownloadsView((state) => state.setColumnVisible)
+ const reset = useDownloadsView((state) => state.resetColumns)
+ return (
+ <>
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>
+ {t('panel.downloads.view.columns')}
+ </DropdownMenuLabel>
+ {columns.map((column) => (
+ <DropdownMenuCheckboxItem
+ key={column.id}
+ checked={column.visible}
+ disabled={column.id === 'name'}
+ closeOnClick={false}
+ onCheckedChange={(visible) => setVisible(column.id, visible)}
+ >
+ {t(`panel.downloads.column.${column.id}`)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={reset}>
+ {t('panel.downloads.view.resetColumns')}
+ </DropdownMenuItem>
+ </>
+ )
+}
+
+export function ListViewMenuItems() {
+ const { t } = useTranslation()
+ const sort = useDownloadsSort((state) => state.sort)
+ const setSort = useDownloadsSort((state) => state.setSort)
+ const resetSort = useDownloadsSort((state) => state.resetSort)
+ const effective = sort ?? DEFAULT_TASK_SORT
+ return (
+ <>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ {t('panel.downloads.view.sortBy')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent data-menu-density="compact">
+ <DropdownMenuRadioGroup
+ value={effective.column}
+ onValueChange={(column) =>
+ setSort(nextTaskSort(null, column as TaskSortColumn))
+ }
+ >
+ {TASK_SORT_COLUMNS.map((column) => (
+ <DropdownMenuRadioItem key={column} value={column}>
+ {t(`panel.downloads.column.${column}`)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup
+ value={effective.direction}
+ onValueChange={(direction) =>
+ setSort({
+ column: effective.column,
+ direction: direction as 'asc' | 'desc',
+ })
+ }
+ >
+ <DropdownMenuRadioItem value="asc">
+ {t('panel.downloads.view.ascending')}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="desc">
+ {t('panel.downloads.view.descending')}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuItem onClick={resetSort}>
+ {t('panel.downloads.sort.reset')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <ColumnVisibilityItems />
+ </>
+ )
+}
+
+export function ListViewSubmenu() {
+ const { t } = useTranslation()
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ {t('panel.downloads.view.title')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent data-menu-density="compact">
+ <ListViewMenuItems />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )
+}
+
+export function ListViewMenu({
+ onOpenChange,
+ triggerRef,
+}: {
+ onOpenChange?: (open: boolean) => void
+ triggerRef?: Ref<HTMLButtonElement>
+}) {
+ const { t } = useTranslation()
+ return (
+ <DropdownMenu onOpenChange={onOpenChange}>
+ <DropdownMenuTrigger
+ render={
+ <DownloadsToolbarButton
+ ref={triggerRef}
+ aria-label={t('panel.downloads.view.title')}
+ title={t('panel.downloads.view.title')}
+ />
+ }
+ >
+ <Columns3 className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" data-menu-density="compact">
+ <ListViewMenuItems />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+export function InspectorMenuItem({
+ onHide,
+ onShow,
+ shortcut,
+}: {
+ onHide?: () => void
+ onShow?: () => void
+ shortcut?: TaskMenuShortcut
+}) {
+ const { t } = useTranslation()
+ const visible = useDownloadsView((state) => state.inspectorVisible)
+ const setVisible = useDownloadsView((state) => state.setInspectorVisible)
+ return (
+ <DropdownMenuItem
+ aria-keyshortcuts={shortcut?.aria}
+ onClick={() => {
+ if (visible) onHide?.()
+ else onShow?.()
+ setVisible(!visible)
+ }}
+ >
+ {t(`panel.downloads.view.${visible ? 'hideInspector' : 'showInspector'}`)}
+ {shortcut && (
+ <DropdownMenuShortcut aria-hidden="true">
+ {shortcut.label}
+ </DropdownMenuShortcut>
+ )}
+ </DropdownMenuItem>
+ )
+}
+
+export function InspectorToggle({
+ onHide,
+ triggerRef,
+}: {
+ onHide?: () => void
+ triggerRef?: Ref<HTMLButtonElement>
+}) {
+ const { t } = useTranslation()
+ const visible = useDownloadsView((state) => state.inspectorVisible)
+ const setVisible = useDownloadsView((state) => state.setInspectorVisible)
+ const label = t(
+ `panel.downloads.view.${visible ? 'hideInspector' : 'showInspector'}`
+ )
+ return (
+ <DownloadsToolbarButton
+ ref={triggerRef}
+ aria-label={label}
+ title={label}
+ aria-pressed={visible}
+ onClick={() => {
+ if (visible) onHide?.()
+ setVisible(!visible)
+ }}
+ >
+ <Info className="size-4" />
+ </DownloadsToolbarButton>
+ )
+}
diff --git a/src/renderer/routes/downloads/nat-badge.tsx b/src/renderer/routes/downloads/nat-badge.tsx
index e8246bf0..238a01bf 100644
--- a/src/renderer/routes/downloads/nat-badge.tsx
+++ b/src/renderer/routes/downloads/nat-badge.tsx
@@ -83,7 +83,7 @@ function ElectronNatBadge() {
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
- className="w-60 max-w-[calc(100vw-2rem)]"
+ className="w-52 max-w-[calc(100vw-2rem)]"
>
<DropdownMenuGroup>
<DropdownMenuLabel className="space-y-1 whitespace-normal text-xs font-normal">
diff --git a/src/renderer/routes/downloads/sort.test.ts b/src/renderer/routes/downloads/sort.test.ts
new file mode 100644
index 00000000..53d30076
--- /dev/null
+++ b/src/renderer/routes/downloads/sort.test.ts
@@ -0,0 +1,304 @@
+import {
+ makeDefaultBtExtension,
+ TaskStatus,
+ TaskType,
+} from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { describe, expect, it } from 'vitest'
+import {
+ nextTaskSort,
+ sortTasks,
+ TASK_SORT_COLUMNS,
+ type TaskSortColumn,
+} from './sort'
+
+describe('download sorting', () => {
+ it('defaults to newest creation time first, including tasks appended during a session', () => {
+ const tasks = [
+ makeDownloadTask({ id: 'old', createdAt: 1_000 }),
+ makeDownloadTask({ id: 'recent', createdAt: 2_000 }),
+ makeDownloadTask({ id: 'unknown' }),
+ ]
+ expect(sortTasks(tasks, null, 'en-US').map((task) => task.id)).toEqual([
+ 'recent',
+ 'old',
+ 'unknown',
+ ])
+ const added = makeDownloadTask({ id: 'new', createdAt: 3_000 })
+ expect(
+ sortTasks([...tasks, added], null, 'en-US').map((task) => task.id)
+ ).toEqual(['new', 'recent', 'old', 'unknown'])
+ expect(tasks.map((task) => task.id)).toEqual(['old', 'recent', 'unknown'])
+ })
+ it.each(['createdAt', 'finishedAt'] as const)(
+ 'sorts %s by the full timestamp and keeps missing dates last',
+ (column) => {
+ const earlier = Date.parse('2026-09-13T10:00:01Z')
+ const later = Date.parse('2026-09-13T10:00:59Z')
+ const tasks = [
+ makeDownloadTask({ id: 'missing', status: TaskStatus.Completed }),
+ makeDownloadTask({
+ id: 'earlier',
+ status: TaskStatus.Completed,
+ [column]: earlier,
+ }),
+ makeDownloadTask({
+ id: 'invalid',
+ status: TaskStatus.Completed,
+ [column]: 1e20,
+ }),
+ makeDownloadTask({
+ id: 'later',
+ status: TaskStatus.Completed,
+ [column]: later,
+ }),
+ ]
+ expect(nextTaskSort(null, column)).toEqual({ column, direction: 'desc' })
+ expect(
+ sortTasks(tasks, { column, direction: 'desc' }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['later', 'earlier', 'missing', 'invalid'])
+ expect(
+ sortTasks(tasks, { column, direction: 'asc' }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['earlier', 'later', 'missing', 'invalid'])
+ }
+ )
+
+ it('does not rank failure or unfinished timestamps as completed tasks', () => {
+ const tasks = [
+ makeDownloadTask({
+ id: 'error',
+ status: TaskStatus.Error,
+ finishedAt: 30_000,
+ }),
+ makeDownloadTask({ id: 'unfinished', finishedAt: 20_000 }),
+ makeDownloadTask({
+ id: 'completed',
+ status: TaskStatus.Completed,
+ finishedAt: 10_000,
+ }),
+ ]
+ for (const direction of ['asc', 'desc'] as const) {
+ expect(
+ sortTasks(tasks, { column: 'finishedAt', direction }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['completed', 'error', 'unfinished'])
+ }
+ })
+
+ it.each(TASK_SORT_COLUMNS)(
+ 'toggles %s between two directions without clearing the sort',
+ (column) => {
+ const first = nextTaskSort(null, column)!
+ const second = nextTaskSort(first, column)!
+ expect(first.column).toBe(column)
+ expect(second.column).toBe(column)
+ expect(second.direction).not.toBe(first.direction)
+ expect(nextTaskSort(second, column)).toEqual(first)
+ }
+ )
+
+ it('starts each newly selected column in its useful direction', () => {
+ expect(nextTaskSort({ column: 'name', direction: 'desc' }, 'size')).toEqual(
+ { column: 'size', direction: 'desc' }
+ )
+ expect(nextTaskSort({ column: 'size', direction: 'asc' }, 'eta')).toEqual({
+ column: 'eta',
+ direction: 'asc',
+ })
+ })
+
+ it('uses natural names, preserves ties, and leaves the snapshot untouched', () => {
+ const tasks = Object.freeze([
+ makeDownloadTask({ id: 'ten', name: 'File 10.zip' }),
+ makeDownloadTask({ id: 'two', name: 'file 2.zip' }),
+ makeDownloadTask({ id: 'same', name: 'FILE 2.zip' }),
+ ])
+ expect(
+ sortTasks(tasks, { column: 'name', direction: 'asc' }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['two', 'same', 'ten'])
+ expect(
+ sortTasks(tasks, { column: 'name', direction: 'desc' }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['ten', 'two', 'same'])
+ expect(sortTasks(tasks, null, 'en-US')).toEqual(tasks)
+ expect(tasks.map((task) => task.id)).toEqual(['ten', 'two', 'same'])
+ })
+
+ it.each([
+ 'size',
+ 'progress',
+ 'down',
+ 'up',
+ 'eta',
+ 'connections',
+ ] satisfies TaskSortColumn[])(
+ 'sorts %s numerically in both directions using the displayed metric',
+ (column) => {
+ const tasks = [
+ makeDownloadTask({
+ id: 'high',
+ sizeWhenDone: 1_000_000,
+ totalBytes: 1,
+ progress: 0.805,
+ downloadSpeed: 1_000_000,
+ uploadSpeed: 1_000_000,
+ etaSeconds: 100,
+ connections: 10,
+ }),
+ makeDownloadTask({
+ id: 'low',
+ sizeWhenDone: 2_000,
+ totalBytes: 10_000_000,
+ progress: 0.804,
+ downloadSpeed: 2_000,
+ uploadSpeed: 2_000,
+ etaSeconds: 2,
+ connections: 2,
+ }),
+ ]
+ expect(
+ sortTasks(tasks, { column, direction: 'asc' }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['low', 'high'])
+ expect(
+ sortTasks(tasks, { column, direction: 'desc' }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['high', 'low'])
+ }
+ )
+
+ it.each(['asc', 'desc'] as const)(
+ 'keeps hidden and invalid ETAs last in %s order',
+ (direction) => {
+ const missing = [
+ makeDownloadTask({
+ id: 'paused',
+ status: TaskStatus.Paused,
+ etaSeconds: 1,
+ }),
+ makeDownloadTask({
+ id: 'complete',
+ status: TaskStatus.Completed,
+ etaSeconds: 1,
+ }),
+ makeDownloadTask({
+ id: 'finalizing',
+ status: TaskStatus.Finalizing,
+ etaSeconds: 1,
+ }),
+ ...[0, -1, Number.NaN, Number.POSITIVE_INFINITY].map(
+ (etaSeconds, index) =>
+ makeDownloadTask({ id: `unknown-${index}`, etaSeconds })
+ ),
+ ]
+ const tasks = [
+ ...missing,
+ makeDownloadTask({ id: 'slow', etaSeconds: 100 }),
+ makeDownloadTask({ id: 'fast', etaSeconds: 2 }),
+ ]
+ expect(
+ sortTasks(tasks, { column: 'eta', direction }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual([
+ ...(direction === 'asc' ? ['fast', 'slow'] : ['slow', 'fast']),
+ ...missing.map((task) => task.id),
+ ])
+ }
+ )
+
+ it.each(['down', 'up'] as const)(
+ 'keeps hidden %s speeds last in both directions',
+ (column) => {
+ const tasks = [
+ makeDownloadTask({
+ id: 'completed',
+ status: TaskStatus.Completed,
+ downloadSpeed: 100_000,
+ uploadSpeed: 100_000,
+ }),
+ makeDownloadTask({ id: 'zero' }),
+ makeDownloadTask({ id: 'live', downloadSpeed: 100, uploadSpeed: 100 }),
+ ]
+ for (const direction of ['asc', 'desc'] as const) {
+ expect(
+ sortTasks(tasks, { column, direction }, 'en-US').map(
+ (task) => task.id
+ )
+ ).toEqual(['live', 'completed', 'zero'])
+ }
+ }
+ )
+
+ it('compares torrent peers with direct-download connections', () => {
+ const tasks = [
+ makeDownloadTask({
+ id: 'torrent',
+ type: TaskType.Bt,
+ connections: 100,
+ bt: makeDefaultBtExtension({ peers: 2 }),
+ }),
+ makeDownloadTask({ id: 'http', connections: 10 }),
+ makeDownloadTask({
+ id: 'magnet',
+ type: TaskType.Magnet,
+ connections: 100,
+ }),
+ ]
+ expect(
+ sortTasks(
+ tasks,
+ { column: 'connections', direction: 'desc' },
+ 'en-US'
+ ).map((task) => task.id)
+ ).toEqual(['http', 'torrent', 'magnet'])
+ })
+
+ it('groups statuses in lifecycle order', () => {
+ const statuses = [
+ TaskStatus.Completed,
+ TaskStatus.Downloading,
+ TaskStatus.Queued,
+ TaskStatus.Error,
+ TaskStatus.Finalizing,
+ TaskStatus.Seeding,
+ TaskStatus.Paused,
+ TaskStatus.MetadataReady,
+ TaskStatus.FetchingMetadata,
+ ]
+ const tasks = statuses.map((status) =>
+ makeDownloadTask({ id: status, status })
+ )
+ const expected = [
+ TaskStatus.Queued,
+ TaskStatus.FetchingMetadata,
+ TaskStatus.MetadataReady,
+ TaskStatus.Downloading,
+ TaskStatus.Finalizing,
+ TaskStatus.Seeding,
+ TaskStatus.Paused,
+ TaskStatus.Completed,
+ TaskStatus.Error,
+ ]
+ expect(
+ sortTasks(tasks, { column: 'status', direction: 'asc' }, 'zh-CN').map(
+ (task) => task.status
+ )
+ ).toEqual(expected)
+ expect(
+ sortTasks(tasks, { column: 'status', direction: 'desc' }, 'en-US').map(
+ (task) => task.status
+ )
+ ).toEqual([...expected].reverse())
+ })
+})
diff --git a/src/renderer/routes/downloads/sort.ts b/src/renderer/routes/downloads/sort.ts
new file mode 100644
index 00000000..1c5547b6
--- /dev/null
+++ b/src/renderer/routes/downloads/sort.ts
@@ -0,0 +1,128 @@
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import { z } from 'zod'
+import {
+ getTaskConnections,
+ getTaskEta,
+ getTaskSpeed,
+ getTaskTimestamp,
+} from './task-column-values'
+
+export const TASK_SORT_COLUMNS = [
+ 'name',
+ 'size',
+ 'progress',
+ 'status',
+ 'down',
+ 'up',
+ 'eta',
+ 'connections',
+ 'createdAt',
+ 'finishedAt',
+] as const
+
+export type TaskSortColumn = (typeof TASK_SORT_COLUMNS)[number]
+export const TaskSortSchema = z
+ .object({
+ column: z.enum(TASK_SORT_COLUMNS),
+ direction: z.enum(['asc', 'desc']),
+ })
+ .nullable()
+export type TaskSort = z.infer<typeof TaskSortSchema>
+export type TaskSortDirection = NonNullable<TaskSort>['direction']
+
+export const DEFAULT_TASK_SORT: NonNullable<TaskSort> = {
+ column: 'createdAt',
+ direction: 'desc',
+}
+
+const DEFAULT_DIRECTION: Record<TaskSortColumn, TaskSortDirection> = {
+ name: 'asc',
+ size: 'desc',
+ progress: 'desc',
+ status: 'asc',
+ down: 'desc',
+ up: 'desc',
+ eta: 'asc',
+ connections: 'desc',
+ createdAt: 'desc',
+ finishedAt: 'desc',
+}
+
+// Lifecycle order keeps related states together regardless of UI language.
+const STATUS_ORDER: Record<TaskStatus, number> = {
+ [TaskStatus.Queued]: 0,
+ [TaskStatus.FetchingMetadata]: 1,
+ [TaskStatus.MetadataReady]: 2,
+ [TaskStatus.Downloading]: 3,
+ [TaskStatus.Finalizing]: 4,
+ [TaskStatus.Seeding]: 5,
+ [TaskStatus.Paused]: 6,
+ [TaskStatus.Completed]: 7,
+ [TaskStatus.Error]: 8,
+ [TaskStatus.Removed]: 9,
+}
+
+export function nextTaskSort(
+ sort: TaskSort,
+ column: TaskSortColumn
+): NonNullable<TaskSort> {
+ const direction = DEFAULT_DIRECTION[column]
+ if (sort?.column !== column) return { column, direction }
+ return { column, direction: sort.direction === 'asc' ? 'desc' : 'asc' }
+}
+
+function numericValue(
+ task: DownloadTask,
+ column: Exclude<TaskSortColumn, 'name'>
+): number | null {
+ switch (column) {
+ case 'size':
+ return task.sizeWhenDone
+ case 'progress':
+ return Math.max(0, Math.min(1, task.progress))
+ case 'status':
+ return STATUS_ORDER[task.status]
+ case 'down':
+ return getTaskSpeed(task, 'downloadSpeed')
+ case 'up':
+ return getTaskSpeed(task, 'uploadSpeed')
+ case 'eta':
+ return getTaskEta(task)
+ case 'connections':
+ return getTaskConnections(task)
+ case 'createdAt':
+ case 'finishedAt':
+ return getTaskTimestamp(task, column)
+ }
+}
+
+export function sortTasks(
+ tasks: readonly DownloadTask[],
+ sort: TaskSort,
+ locale: string
+): readonly DownloadTask[] {
+ const { column, direction } = sort ?? DEFAULT_TASK_SORT
+ const multiplier = direction === 'asc' ? 1 : -1
+ if (column === 'name') {
+ const collator = new Intl.Collator(locale, {
+ numeric: true,
+ sensitivity: 'base',
+ })
+ return [...tasks].sort(
+ (a, b) => collator.compare(a.name, b.name) * multiplier
+ )
+ }
+
+ // Sort a copy and retain the source order for equal values. The default
+ // ordering also applies to new tasks appended to a live snapshot.
+ return [...tasks].sort((a, b) => {
+ const left = numericValue(a, column)
+ const right = numericValue(b, column)
+ const leftMissing = left === null || !Number.isFinite(left)
+ const rightMissing = right === null || !Number.isFinite(right)
+ // Dashes and unavailable estimates stay last in either direction.
+ if (leftMissing) return rightMissing ? 0 : 1
+ if (rightMissing) return -1
+ return (left - right) * multiplier
+ })
+}
diff --git a/src/renderer/routes/downloads/speed-limit-badge.test.tsx b/src/renderer/routes/downloads/speed-limit-badge.test.tsx
new file mode 100644
index 00000000..1baaebd8
--- /dev/null
+++ b/src/renderer/routes/downloads/speed-limit-badge.test.tsx
@@ -0,0 +1,162 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { toast } from '@renderer/components/ui/toast'
+import type { SpeedLimitStateView } from '@renderer/hooks/use-speed-limit-state'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { MemoryRouter, Route, Routes } from 'react-router'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { SpeedLimitBadge } from './speed-limit-badge'
+
+let state: SpeedLimitStateView
+let user: ReturnType<typeof userEvent.setup>
+vi.mock('@renderer/hooks/use-speed-limit-state', () => ({
+ useSpeedLimitState: () => state,
+}))
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { invoke: vi.fn().mockResolvedValue(undefined) },
+}))
+vi.mock('@renderer/components/ui/toast', () => ({ toast: { add: vi.fn() } }))
+
+function setup() {
+ return render(
+ <MemoryRouter>
+ <Routes>
+ <Route path="/" element={<SpeedLimitBadge />} />
+ <Route
+ path="/settings/downloads"
+ element={<h1>Download settings</h1>}
+ />
+ </Routes>
+ </MemoryRouter>
+ )
+}
+
+beforeEach(() => {
+ user = userEvent.setup()
+ vi.clearAllMocks()
+ vi.mocked(transport.invoke).mockResolvedValue(undefined)
+ state = {
+ turtle: 'off',
+ effective: { upload: 0, download: 800_000 },
+ activeReason: 'base',
+ }
+})
+
+describe('SpeedLimitBadge', () => {
+ it.each([
+ ['off', 'Standard', 'rabbit'],
+ ['on', 'Low speed', 'turtle'],
+ ['auto', 'Automatic', 'squirrel'],
+ ] as const)(
+ 'shows the %s mode with its existing dashboard glyph',
+ async (mode, label, icon) => {
+ state.turtle = mode
+ setup()
+ const button = screen.getByRole('button', {
+ name: `Speed mode: ${label}`,
+ })
+ expect(button.querySelector(`.lucide-${icon}`)).toBeInTheDocument()
+ await user.click(button)
+ const radios = await screen.findAllByRole('menuitemradio')
+ expect(radios).toHaveLength(3)
+ expect(radios[['off', 'on', 'auto'].indexOf(mode)]).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ expect(screen.getByRole('menu')).toHaveAttribute('data-side', 'top')
+ }
+ )
+
+ it('shows effective limits without calling standard mode unlimited', async () => {
+ const user = userEvent.setup()
+ setup()
+ await user.hover(
+ screen.getByRole('button', { name: 'Speed mode: Standard' })
+ )
+ const tooltip = await screen.findByRole('tooltip')
+ expect(tooltip).toHaveTextContent('Speed mode: Standard')
+ expect(tooltip).toHaveTextContent('Upload limit: Unlimited')
+ expect(tooltip).toHaveTextContent('Download limit: 800 KB/s')
+ await user.click(
+ screen.getByRole('button', { name: 'Speed mode: Standard' })
+ )
+ await waitFor(() =>
+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()
+ )
+ })
+
+ it('saves only the chosen mode and prevents another change while saving', async () => {
+ let finish!: () => void
+ vi.mocked(transport.invoke).mockReturnValue(
+ new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ )
+ setup()
+ const button = screen.getByRole('button', { name: 'Speed mode: Standard' })
+ await user.click(button)
+ fireEvent.click(
+ await screen.findByRole('menuitemradio', { name: 'Low-speed mode' })
+ )
+ expect(transport.invoke).toHaveBeenCalledExactlyOnceWith(
+ Commands.UpdateSettings,
+ { speedLimit: { turtle: 'on' } }
+ )
+ expect(button).toBeDisabled()
+ expect(button).toHaveAttribute('aria-busy', 'true')
+ fireEvent.click(button)
+ expect(transport.invoke).toHaveBeenCalledTimes(1)
+ await act(async () => finish())
+ expect(button).not.toBeDisabled()
+ // The confirmed controller state, rather than an optimistic guess, owns the label.
+ expect(button).toHaveTextContent('Standard')
+ })
+
+ it('keeps the confirmed mode on failure and allows retry', async () => {
+ vi.mocked(transport.invoke).mockRejectedValueOnce(new Error('save failed'))
+ setup()
+ const button = screen.getByRole('button', { name: 'Speed mode: Standard' })
+ await user.click(button)
+ await user.click(
+ await screen.findByRole('menuitemradio', { name: 'Automatic mode' })
+ )
+ await waitFor(() =>
+ expect(toast.add).toHaveBeenCalledWith({
+ type: 'error',
+ title: 'Couldn’t change the speed mode. Try again.',
+ })
+ )
+ expect(button).not.toBeDisabled()
+ expect(button).toHaveTextContent('Standard')
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ await user.click(button)
+ await user.click(
+ await screen.findByRole('menuitemradio', { name: 'Automatic mode' })
+ )
+ await waitFor(() => expect(transport.invoke).toHaveBeenCalledTimes(2))
+ })
+
+ it('keeps automatic mode visible when no rule is active and opens existing settings', async () => {
+ state = {
+ turtle: 'auto',
+ activeReason: 'none',
+ effective: { upload: 0, download: 0 },
+ }
+ setup()
+ const button = screen.getByRole('button', { name: 'Speed mode: Automatic' })
+ expect(button).toHaveAttribute('data-reduced', 'false')
+ await user.click(button)
+ await user.click(
+ await screen.findByRole('menuitem', { name: 'Speed limit settings' })
+ )
+ expect(
+ screen.getByRole('heading', { name: 'Download settings' })
+ ).toBeInTheDocument()
+ expect(transport.invoke).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/routes/downloads/speed-limit-badge.tsx b/src/renderer/routes/downloads/speed-limit-badge.tsx
new file mode 100644
index 00000000..c2a1a8e1
--- /dev/null
+++ b/src/renderer/routes/downloads/speed-limit-badge.tsx
@@ -0,0 +1,156 @@
+import { SPEED_LIMIT_MODES } from '@renderer/components/speed-limit-modes'
+import { Badge } from '@renderer/components/ui/badge'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { toast } from '@renderer/components/ui/toast'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@renderer/components/ui/tooltip'
+import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import { useSpeedLimitState } from '@renderer/hooks/use-speed-limit-state'
+import { transport } from '@renderer/lib/transport'
+import { cn } from '@renderer/lib/utils'
+import { Commands } from '@shared/protocol/commands'
+import type { TurtleState } from '@shared/types/settings'
+import { ChevronDown } from 'lucide-react'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+
+export function SpeedLimitBadge() {
+ const { t } = useTranslation()
+ const { formatSpeedLimit } = useByteFormat()
+ const state = useSpeedLimitState()
+ const [open, setOpen] = useState(false)
+ const [pending, setPending] = useState(false)
+ const pendingRef = useRef(false)
+ const { Icon } =
+ SPEED_LIMIT_MODES.find(({ id }) => id === state.turtle) ??
+ SPEED_LIMIT_MODES[0]
+ const mode = t(`settings.downloads.speedLimit.turtle_${state.turtle}`)
+ const description = t('panel.downloads.speedLimit.currentMode', { mode })
+ const reduced =
+ state.turtle === 'on' ||
+ (state.turtle === 'auto' &&
+ ['schedule', 'videoApp', 'adaptive'].includes(state.activeReason))
+ const formatLimit = (value: number) =>
+ value > 0
+ ? formatSpeedLimit(value)
+ : t('settings.downloads.speedLimit.unlimited')
+
+ const selectMode = async (turtle: TurtleState) => {
+ if (pendingRef.current || turtle === state.turtle) return
+ pendingRef.current = true
+ setPending(true)
+ try {
+ await transport.invoke(Commands.UpdateSettings, {
+ speedLimit: { turtle },
+ })
+ } catch {
+ toast.add({
+ type: 'error',
+ title: t('panel.downloads.speedLimit.saveFailed'),
+ })
+ } finally {
+ pendingRef.current = false
+ setPending(false)
+ }
+ }
+
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <Tooltip disabled={open}>
+ <TooltipTrigger
+ delay={400}
+ render={
+ <DropdownMenuTrigger
+ disabled={pending}
+ render={
+ <Badge
+ render={<button type="button" />}
+ variant="secondary"
+ data-slot="downloads-speed-limit"
+ data-mode={state.turtle}
+ data-reduced={reduced}
+ aria-label={description}
+ aria-busy={pending}
+ className={cn(
+ 'app-no-drag gap-1.5 cursor-default select-none transition-colors hover:bg-accent data-popup-open:bg-accent disabled:opacity-50 focus-visible:ring-1 focus-visible:ring-[#7388a3] dark:focus-visible:ring-[#97aac4]',
+ reduced &&
+ 'bg-[#e4ebf3] text-[#435775] hover:bg-[#dce5ef] data-popup-open:bg-[#dce5ef] dark:bg-[#303d50] dark:text-[#bfcede] dark:hover:bg-[#3a485c] dark:data-popup-open:bg-[#3a485c]'
+ )}
+ />
+ }
+ />
+ }
+ >
+ <Icon aria-hidden="true" />
+ {mode}
+ <ChevronDown aria-hidden="true" className="opacity-55" />
+ </TooltipTrigger>
+ <TooltipContent side="top" align="start" sideOffset={8}>
+ <div className="space-y-1">
+ <p className="font-medium">{description}</p>
+ <p>
+ {t('panel.downloads.speedLimit.uploadLimit', {
+ speed: formatLimit(state.effective.upload),
+ })}
+ </p>
+ <p>
+ {t('panel.downloads.speedLimit.downloadLimit', {
+ speed: formatLimit(state.effective.download),
+ })}
+ </p>
+ {state.turtle === 'auto' && state.activeReason !== 'none' && (
+ <p>
+ {t(`panel.dashboard.speedLimit.reason.${state.activeReason}`)}
+ </p>
+ )}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent
+ side="top"
+ align="start"
+ sideOffset={8}
+ aria-label={t('panel.downloads.speedLimit.title')}
+ data-menu-density="compact"
+ className="w-max min-w-36 max-w-[min(16rem,var(--available-width))]"
+ >
+ <DropdownMenuRadioGroup
+ value={state.turtle}
+ onValueChange={(value) => {
+ const mode = SPEED_LIMIT_MODES.find(({ id }) => id === value)
+ if (mode) void selectMode(mode.id)
+ }}
+ >
+ {SPEED_LIMIT_MODES.map(({ id, Icon }) => (
+ <DropdownMenuRadioItem
+ key={id}
+ value={id}
+ disabled={pending}
+ showIndicator={false}
+ closeOnClick
+ >
+ <Icon className="size-3.5 text-muted-foreground" aria-hidden />
+ {t(`panel.dashboard.speedLimit.turtle.${id}`)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem render={<Link to="/settings/downloads" />}>
+ {t('panel.dashboard.speedLimit.settings')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/src/renderer/routes/downloads/status-pill.tsx b/src/renderer/routes/downloads/status-pill.tsx
index 2adc04d7..1bc4037f 100644
--- a/src/renderer/routes/downloads/status-pill.tsx
+++ b/src/renderer/routes/downloads/status-pill.tsx
@@ -16,19 +16,27 @@ const LABEL_KEY: Record<TaskStatus, string> = {
[TaskStatus.Removed]: 'panel.downloads.status.error',
}
-export function StatusPill({ status }: { status: TaskStatus }) {
+export function StatusPill({
+ status,
+ compact = false,
+}: {
+ status: TaskStatus
+ compact?: boolean
+}) {
const { t } = useTranslation()
const tone = getStatusTone(status)
return (
<span
data-testid="task-status-pill"
className={cn(
- 'inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-[11px] font-medium',
+ 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
)}
>
- {t(LABEL_KEY[status])}
+ <span className="truncate">{t(LABEL_KEY[status])}</span>
</span>
)
}
diff --git a/src/renderer/routes/downloads/status-title-menu.tsx b/src/renderer/routes/downloads/status-title-menu.tsx
index af39d5cd..a0c1686a 100644
--- a/src/renderer/routes/downloads/status-title-menu.tsx
+++ b/src/renderer/routes/downloads/status-title-menu.tsx
@@ -15,12 +15,14 @@ export interface StatusTitleMenuProps {
tab: DownloadsTab
onTabChange: (tab: DownloadsTab) => void
counts: Record<DownloadsTab, number>
+ visibleCount?: number
}
export function StatusTitleMenu({
tab,
onTabChange,
counts,
+ visibleCount = counts[tab],
}: StatusTitleMenuProps) {
const { t } = useTranslation()
const statusLabel = t(`panel.downloads.tab.${tab}`)
@@ -33,22 +35,19 @@ export function StatusTitleMenu({
render={
<button
type="button"
- // relative z-[60] lifts the trigger above the z-50 WindowChrome
- // drag strip; without it, in the collapsed (short) header the
- // strip covers the trigger and `no-drag` is overridden by the
- // strip's `drag` region, so clicks become window-drags.
- // h-8 / h-4 pins the trigger to the search button's height per
- // sidebar state (32px expanded, 16px collapsed) so the two
- // controls read as a centered, size-aligned pair (items-center
- // vertically centers the title text).
- className="app-no-drag relative z-[40] flex h-8 items-center gap-1 outline-hidden compact-header:h-7"
+ // Align the title with the compact toolbar above the window drag strip.
+ className="app-no-drag relative z-[40] flex h-9 min-w-0 items-center gap-1 outline-hidden compact-header:h-7"
/>
}
>
- <h1 className={PANEL_TITLE_CLASS}>{title}</h1>
+ <h1 className={cn(PANEL_TITLE_CLASS, 'truncate')}>{title}</h1>
<ChevronDown className="size-4 shrink-0 text-muted-foreground compact-header:size-3" />
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="app-no-drag">
+ <DropdownMenuContent
+ align="start"
+ className="app-no-drag"
+ data-menu-density="compact"
+ >
{DOWNLOADS_TABS.map((key) => (
<DropdownMenuItem
key={key}
@@ -72,7 +71,7 @@ export function StatusTitleMenu({
{/* Inline count on the title line — hidden when collapsed/narrow so the
header stays a single tight row. */}
<div className="shrink-0 whitespace-nowrap text-xs text-muted-foreground tabular-nums compact-header:hidden">
- <Badge variant="outline">{`${counts[tab]}/${counts.all}`}</Badge>
+ <Badge variant="outline">{`${visibleCount}/${counts.all}`}</Badge>
</div>
</div>
)
diff --git a/src/renderer/routes/downloads/store.test.ts b/src/renderer/routes/downloads/store.test.ts
index a910ef2c..77d8de7a 100644
--- a/src/renderer/routes/downloads/store.test.ts
+++ b/src/renderer/routes/downloads/store.test.ts
@@ -1,7 +1,7 @@
import type { DownloadTask } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
-import { beforeEach, describe, expect, it } from 'vitest'
-import { useDownloadsSelection } from './store'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createDownloadsSortStore, useDownloadsSelection } from './store'
function fakeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {
return makeDownloadTask({
@@ -56,3 +56,78 @@ describe('useDownloadsSelection', () => {
)
})
})
+
+describe('Downloads sort persistence', () => {
+ beforeEach(() => localStorage.clear())
+ afterEach(() => {
+ vi.restoreAllMocks()
+ localStorage.clear()
+ })
+
+ it('starts with the implicit default and restores a manual column and direction in a fresh store', () => {
+ const first = createDownloadsSortStore()
+ expect(first.getState().sort).toBeNull()
+ first.getState().toggleSort('size')
+ first.getState().toggleSort('size')
+ const restored = createDownloadsSortStore()
+ expect(restored.getState().sort).toEqual({
+ column: 'size',
+ direction: 'asc',
+ })
+ restored.getState().toggleSort('finishedAt')
+ expect(createDownloadsSortStore().getState().sort).toEqual({
+ column: 'finishedAt',
+ direction: 'desc',
+ })
+ })
+
+ it('removes the saved manual preference when returning to the default', () => {
+ const first = createDownloadsSortStore()
+ first.getState().toggleSort('name')
+ first.getState().toggleSort('name')
+ first.getState().resetSort()
+ expect(first.getState().sort).toBeNull()
+ expect(localStorage.getItem('motrix.downloads.sort')).toBeNull()
+ expect(createDownloadsSortStore().getState().sort).toBeNull()
+ })
+
+ it.each([
+ 'not json',
+ 'null',
+ '[]',
+ '{}',
+ '{"column":"obsolete","direction":"asc"}',
+ '{"column":"name","direction":"sideways"}',
+ ])(
+ 'falls back to the default for an invalid saved preference: %s',
+ (saved) => {
+ localStorage.setItem('motrix.downloads.sort', saved)
+ const store = createDownloadsSortStore()
+ expect(store.getState().sort).toBeNull()
+ store.getState().toggleSort('createdAt')
+ expect(createDownloadsSortStore().getState().sort).toEqual({
+ column: 'createdAt',
+ direction: 'desc',
+ })
+ }
+ )
+
+ it('keeps sorting usable when storage reads or writes are blocked', () => {
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('Blocked storage')
+ })
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('Blocked storage')
+ })
+ vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
+ throw new Error('Blocked storage')
+ })
+ const store = createDownloadsSortStore()
+ expect(store.getState().sort).toBeNull()
+ expect(() => store.getState().toggleSort('name')).not.toThrow()
+ expect(store.getState().sort).toEqual({ column: 'name', direction: 'asc' })
+ store.getState().toggleSort('name')
+ expect(() => store.getState().resetSort()).not.toThrow()
+ expect(store.getState().sort).toBeNull()
+ })
+})
diff --git a/src/renderer/routes/downloads/store.ts b/src/renderer/routes/downloads/store.ts
index 73d8e37e..f3e4bb8a 100644
--- a/src/renderer/routes/downloads/store.ts
+++ b/src/renderer/routes/downloads/store.ts
@@ -1,13 +1,66 @@
import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'
import type { DownloadTask } from '@shared/types/task'
+import { create } from 'zustand'
+import {
+ nextTaskSort,
+ type TaskSort,
+ type TaskSortColumn,
+ TaskSortSchema,
+} from './sort'
/**
* Module-level singleton selection store for the Downloads page.
*
- * Shared between `TaskListPanel` (via `useSelectableList({ store })`,
- * Task 6) and `TaskInspectorDrawer` (which subscribes directly to derive
- * its open / single-vs-multi state from `selectedIds.size`).
+ * Shared by the list, task actions, and inspector. Inspector visibility is
+ * an independent view preference; selection never implicitly opens it.
*/
export const useDownloadsSelection = createSelectionStore<DownloadTask>(
(t) => t.id
)
+
+const DOWNLOADS_SORT_STORAGE_KEY = 'motrix.downloads.sort'
+
+function readSavedSort(): TaskSort {
+ try {
+ const saved = localStorage.getItem(DOWNLOADS_SORT_STORAGE_KEY)
+ return saved === null ? null : TaskSortSchema.parse(JSON.parse(saved))
+ } catch {
+ // Missing storage or an outdated/invalid preference uses the default.
+ return null
+ }
+}
+
+function saveSort(sort: TaskSort): void {
+ try {
+ if (sort === null) localStorage.removeItem(DOWNLOADS_SORT_STORAGE_KEY)
+ else localStorage.setItem(DOWNLOADS_SORT_STORAGE_KEY, JSON.stringify(sort))
+ } catch {
+ // Keep in-memory sorting usable when browser storage is unavailable.
+ }
+}
+
+interface DownloadsSortState {
+ sort: TaskSort
+ toggleSort: (column: TaskSortColumn) => void
+ setSort: (sort: TaskSort) => void
+ resetSort: () => void
+}
+
+export function createDownloadsSortStore() {
+ return create<DownloadsSortState>((set, get) => ({
+ sort: readSavedSort(),
+ toggleSort: (column) => {
+ const sort = nextTaskSort(get().sort, column)
+ get().setSort(sort)
+ },
+ setSort: (sort) => {
+ const validated = TaskSortSchema.parse(sort)
+ saveSort(validated)
+ set({ sort: validated })
+ },
+ resetSort: () => get().setSort(null),
+ }))
+}
+
+// UI-only preference shared by Downloads filters and restored on app startup.
+export const useDownloadsSort = createDownloadsSortStore()
diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsx
new file mode 100644
index 00000000..a8ae0fa3
--- /dev/null
+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx
@@ -0,0 +1,593 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'
+import { toast } from '@renderer/components/ui/toast'
+import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
+import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
+import { transport } from '@renderer/lib/transport'
+import { DownloadErrorCode } from '@shared/errors'
+import { Commands } from '@shared/protocol/commands'
+import type { DownloadTask } from '@shared/types/task'
+import { TaskStatus, TaskType } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { TaskActionsMenu } from './task-actions-menu'
+import { useDownloadsView } from './view-preferences'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ invoke: vi.fn().mockResolvedValue({ failed: [] }),
+ platform: 'darwin',
+ },
+}))
+vi.mock('@renderer/components/ui/toast', () => ({ toast: { add: vi.fn() } }))
+vi.mock('@renderer/lib/open-add-task-dialog', () => ({
+ openAddTaskDialog: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@renderer/lib/open-magnet-file-selection', () => ({
+ openMagnetFileSelection: vi.fn().mockResolvedValue(true),
+}))
+const tasks = ['a', 'b', 'c'].map((id) =>
+ makeDownloadTask({ id, name: id, status: TaskStatus.Paused })
+)
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(transport).platform = 'darwin'
+ useDownloadsView.setState({
+ inspectorVisible: false,
+ inspectorTab: 'overview',
+ })
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: vi.fn().mockResolvedValue(undefined) },
+ })
+})
+
+function setup(context = true, items = tasks) {
+ const selection = createSelectionStore<DownloadTask>((task) => task.id)
+ selection.getState().setItems(items)
+ if (items[0]) selection.getState().select(items[0].id)
+ if (items[1]) selection.getState().toggle(items[1].id)
+ render(
+ <TaskActionsMenu tasks={items} selection={selection}>
+ {context ? (
+ <div data-testid="context-list">
+ {items.map((task) => (
+ <div data-task-id={task.id} key={task.id}>
+ {task.name}
+ </div>
+ ))}
+ </div>
+ ) : undefined}
+ </TaskActionsMenu>
+ )
+ return selection
+}
+
+describe('TaskActionsMenu', () => {
+ it('opens a new task from an empty list without empty task groups', async () => {
+ setup(true, [])
+ fireEvent.contextMenu(screen.getByTestId('context-list'))
+ const item = await screen.findByRole('menuitem', { name: 'New Task…' })
+ expect(screen.getAllByRole('menuitem')).toHaveLength(1)
+ expect(screen.queryByRole('separator')).not.toBeInTheDocument()
+ fireEvent.click(item)
+ await waitFor(() => expect(openAddTaskDialog).toHaveBeenCalledWith())
+ expect(transport.invoke).not.toHaveBeenCalled()
+ })
+
+ it('keeps the selected batch when creating from a row or list whitespace', async () => {
+ const selection = setup()
+ const user = userEvent.setup()
+ for (const target of [
+ screen.getByText('b'),
+ screen.getByTestId('context-list'),
+ ]) {
+ fireEvent.contextMenu(target)
+ const item = await screen.findByRole('menuitem', { name: 'New Task…' })
+ expect(screen.getAllByRole('menuitem').at(-2)).toBe(item)
+ await user.click(item)
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ expect(selection.getState().committedSelectedIds).toEqual(
+ new Set(['a', 'b'])
+ )
+ }
+ expect(openAddTaskDialog).toHaveBeenCalledTimes(2)
+ expect(transport.invoke).not.toHaveBeenCalled()
+ })
+
+ it('reports a failure to open the new task window', async () => {
+ setup(true, [])
+ vi.mocked(openAddTaskDialog).mockRejectedValueOnce(
+ new Error('Window unavailable')
+ )
+ fireEvent.contextMenu(screen.getByTestId('context-list'))
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'New Task…' }))
+ await waitFor(() =>
+ expect(toast.add).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'error',
+ description: 'Window unavailable',
+ })
+ )
+ )
+ })
+
+ it('keeps view controls available without a selection and exposes details by keyboard', async () => {
+ const user = userEvent.setup()
+ const selection = setup(false)
+ act(() => {
+ selection.getState().clearSelection()
+ useDownloadsView.getState().setInspectorVisible(false)
+ })
+ const trigger = screen.getByRole('button', { name: 'More' })
+ expect(trigger).toBeEnabled()
+ await user.click(trigger)
+ expect(
+ await screen.findByRole('menuitem', { name: 'List View' })
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByRole('menuitem', { name: 'Copy URL' })
+ ).not.toBeInTheDocument()
+ await user.keyboard('{Escape}')
+ act(() => selection.getState().select('a'))
+ expect(trigger).toBeEnabled()
+ trigger.focus()
+ await user.keyboard('{Enter}')
+ expect(trigger).toHaveAttribute('aria-expanded', 'true')
+ await user.click(
+ await screen.findByRole('menuitem', { name: 'Show Inspector' })
+ )
+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)
+ expect(selection.getState().selectedIds).toEqual(new Set(['a']))
+ })
+ it.each([TaskStatus.Completed, TaskStatus.Finalizing, TaskStatus.Error])(
+ 'omits empty transfer/queue groups without adjacent separators for %s tasks',
+ async (status) => {
+ setup(true, [
+ makeDownloadTask({ id: 'a', name: 'a', status, type: TaskType.Http }),
+ ])
+ fireEvent.contextMenu(screen.getByText('a'))
+ const menu = await screen.findByRole('menu')
+ expect(
+ screen.queryByRole('menuitem', { name: 'Move Up in Queue' })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('menuitem', { name: 'Move Down in Queue' })
+ ).not.toBeInTheDocument()
+ const roles = [
+ ...menu.querySelectorAll('[role="menuitem"], [role="separator"]'),
+ ].map((element) => element.getAttribute('role'))
+ expect(roles[0]).toBe('menuitem')
+ expect(roles.at(-1)).toBe('menuitem')
+ for (const [index, role] of roles.entries()) {
+ if (role === 'separator') expect(roles[index + 1]).toBe('menuitem')
+ }
+ }
+ )
+ it('copies the captured batch as one clipboard write after selection changes', async () => {
+ const selection = setup(
+ true,
+ tasks.map((task) => ({
+ ...task,
+ uris: [`https://example.test/${task.id}`],
+ }))
+ )
+ fireEvent.contextMenu(screen.getByText('b'))
+ const item = await screen.findByRole('menuitem', { name: 'Copy URLs' })
+ act(() => selection.getState().select('c'))
+ fireEvent.click(item)
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ 'https://example.test/a\nhttps://example.test/b'
+ )
+ )
+ expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(1)
+ })
+ it('copies the final file path and reports clipboard failures', async () => {
+ setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ finalPath: '/downloads/final.bin',
+ diskPath: '/downloads/partial.bin',
+ }),
+ ])
+ vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(
+ new Error('Clipboard denied')
+ )
+ fireEvent.contextMenu(screen.getByText('a'))
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'Copy file path' })
+ )
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ '/downloads/final.bin'
+ )
+ )
+ await waitFor(() =>
+ expect(toast.add).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'error' })
+ )
+ )
+ expect(toast.add).not.toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'success' })
+ )
+ })
+ it('opens file selection for a magnet whose metadata is ready', async () => {
+ setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ type: TaskType.Magnet,
+ status: TaskStatus.MetadataReady,
+ }),
+ ])
+ fireEvent.contextMenu(screen.getByText('a'))
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'Select files' })
+ )
+ await waitFor(() =>
+ expect(openMagnetFileSelection).toHaveBeenCalledWith('a')
+ )
+ })
+ it('preserves multi-selection when right-clicking a selected task and sends one batch', async () => {
+ const selection = setup()
+ fireEvent.contextMenu(screen.getByText('b'))
+ await screen.findByRole('menuitem', { name: 'Resume' })
+ expect([...selection.getState().committedSelectedIds]).toEqual(['a', 'b'])
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Resume' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.ResumeTasks, [
+ 'a',
+ 'b',
+ ])
+ )
+ })
+ it('targets only an unselected context row', async () => {
+ const selection = setup()
+ fireEvent.contextMenu(screen.getByText('c'))
+ await screen.findByRole('menuitem', { name: 'Resume' })
+ expect([...selection.getState().committedSelectedIds]).toEqual(['c'])
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Resume' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.ResumeTasks, ['c'])
+ )
+ })
+ it('keeps the removal confirmation bound to the original batch after selection changes', async () => {
+ const user = userEvent.setup()
+ const selection = setup()
+ fireEvent.contextMenu(screen.getByText('b'))
+ await user.click(await screen.findByRole('menuitem', { name: 'Remove' }))
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
+ act(() => selection.getState().select('c'))
+ await user.click(screen.getByRole('button', { name: 'Remove' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RemoveTasks, {
+ taskIds: ['a', 'b'],
+ deleteWithFiles: false,
+ })
+ )
+ })
+ it.each([
+ ['up', 'Move Up in Queue'],
+ ['down', 'Move Down in Queue'],
+ ['top', 'Move to Front'],
+ ['bottom', 'Move to Back'],
+ ] as const)(
+ 'moves the captured selection %s through the queue submenu',
+ async (direction, label) => {
+ const user = userEvent.setup()
+ setup()
+ vi.mocked(transport.invoke).mockResolvedValueOnce({
+ moved: ['a', 'b'],
+ unchanged: [],
+ failed: [],
+ })
+ fireEvent.contextMenu(screen.getByText('b'))
+ await user.click(
+ await screen.findByRole('menuitem', { name: 'Download order' })
+ )
+ fireEvent.click(await screen.findByRole('menuitem', { name: label }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.MoveTasks, {
+ taskIds: ['a', 'b'],
+ direction,
+ })
+ )
+ }
+ )
+
+ it('opens the captured completed file by task id and reports failures', async () => {
+ setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ status: TaskStatus.Completed,
+ fileCount: 1,
+ finalPath: '/downloads/a.bin',
+ }),
+ ])
+ vi.mocked(transport.invoke).mockRejectedValueOnce(new Error('File missing'))
+ fireEvent.contextMenu(screen.getByText('a'))
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Open file' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.OpenTaskFile, {
+ taskId: 'a',
+ })
+ )
+ await waitFor(() =>
+ expect(toast.add).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'Could not open file', type: 'error' })
+ )
+ )
+ })
+
+ it.each([TaskStatus.Downloading, TaskStatus.Finalizing, TaskStatus.Error])(
+ 'does not offer to open a %s output',
+ async (status) => {
+ setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ status,
+ fileCount: 1,
+ finalPath: '/downloads/a.bin',
+ }),
+ ])
+ fireEvent.contextMenu(screen.getByText('a'))
+ await screen.findByRole('menu')
+ expect(
+ screen.queryByRole('menuitem', { name: 'Open file' })
+ ).not.toBeInTheDocument()
+ }
+ )
+
+ it('opens file selection on the original task after the selection changes', async () => {
+ const selection = setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ type: TaskType.Bt,
+ status: TaskStatus.Paused,
+ fileCount: 3,
+ }),
+ makeDownloadTask({ id: 'b', name: 'b' }),
+ ])
+ act(() => selection.getState().select('a'))
+ fireEvent.contextMenu(screen.getByText('a'))
+ const item = await screen.findByRole('menuitem', { name: 'Choose files…' })
+ act(() => selection.getState().select('b'))
+ fireEvent.click(item)
+ expect(useDownloadsView.getState()).toMatchObject({
+ inspectorVisible: true,
+ inspectorTab: 'files',
+ })
+ expect(selection.getState().committedSelectedIds).toEqual(new Set(['a']))
+ expect(openMagnetFileSelection).not.toHaveBeenCalled()
+ })
+
+ it('copies only captured errors with translated reasons and technical details', async () => {
+ const selection = setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ status: TaskStatus.Error,
+ errorCode: DownloadErrorCode.DiskFull,
+ errorMessage: 'ENOSPC',
+ }),
+ makeDownloadTask({ id: 'b', name: 'b', status: TaskStatus.Completed }),
+ ])
+ fireEvent.contextMenu(screen.getByText('a'))
+ const item = await screen.findByRole('menuitem', {
+ name: 'Copy error information',
+ })
+ act(() => selection.getState().select('b'))
+ fireEvent.click(item)
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(1)
+ )
+ const text = vi.mocked(navigator.clipboard.writeText).mock.calls[0][0]
+ expect(text).toContain('Task ID: a')
+ expect(text).toContain('DL_DISK_FULL')
+ expect(text).toContain('ENOSPC')
+ expect(text).not.toContain('Task ID: b')
+ })
+
+ it('exposes the same actions through the toolbar while the inspector is hidden', async () => {
+ setup(false)
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'More' }))
+ await user.click(await screen.findByRole('menuitem', { name: 'Resume' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.ResumeTasks, [
+ 'a',
+ 'b',
+ ])
+ )
+ })
+})
+
+describe('organized task menu and keyboard actions', () => {
+ it('groups completed-task access, clipboard, creation and removal in that order', async () => {
+ setup(true, [
+ makeDownloadTask({
+ id: 'a',
+ name: 'a',
+ status: TaskStatus.Completed,
+ fileCount: 1,
+ diskPath: '/downloads/a.bin',
+ finalPath: '/downloads/a.bin',
+ }),
+ ])
+ fireEvent.contextMenu(screen.getByText('a'))
+ const menu = await screen.findByRole('menu')
+ const groups = [...menu.querySelectorAll('[role="group"]')].map((group) =>
+ [...group.querySelectorAll('[role="menuitem"]')].map((item) =>
+ [...item.childNodes]
+ .filter((node) => node.nodeType === Node.TEXT_NODE)
+ .map((node) => node.textContent)
+ .join('')
+ )
+ )
+ expect(groups).toEqual([
+ ['Open file', 'Open folder', 'Show Inspector'],
+ ['Copy URL', 'Copy file path'],
+ ['New Task…'],
+ ['Remove'],
+ ])
+ expect(screen.getByRole('menuitem', { name: 'Copy URL' })).toHaveAttribute(
+ 'aria-keyshortcuts',
+ 'Meta+C'
+ )
+ expect(
+ screen.getByRole('menuitem', { name: 'Show Inspector' })
+ ).toHaveAttribute('aria-keyshortcuts', 'Meta+I')
+ expect(
+ menu.querySelector('[data-slot="dropdown-menu-shortcut"]')
+ ).toHaveAttribute('aria-hidden', 'true')
+ expect(
+ screen.getByRole('menuitem', { name: 'Open file' })
+ ).not.toHaveAttribute('aria-keyshortcuts')
+ })
+
+ it.each(['darwin', 'win32', 'linux'] as const)(
+ 'copies the selected batch once with the %s primary modifier',
+ async (platform) => {
+ vi.mocked(transport).platform = platform
+ setup(
+ true,
+ tasks.map((task) => ({
+ ...task,
+ uris: [`https://example.test/${task.id}`],
+ }))
+ )
+ fireEvent.keyDown(screen.getByTestId('context-list'), {
+ key: 'c',
+ metaKey: platform === 'darwin',
+ ctrlKey: platform !== 'darwin',
+ })
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ 'https://example.test/a\nhttps://example.test/b'
+ )
+ )
+ expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ it('restores the captured selection, toggles the inspector and closes the menu with its shortcut', async () => {
+ const selection = setup()
+ fireEvent.contextMenu(screen.getByText('b'))
+ const menu = await screen.findByRole('menu')
+ act(() => selection.getState().select('c'))
+ fireEvent.keyDown(menu, { key: 'i', metaKey: true })
+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)
+ expect(selection.getState().committedSelectedIds).toEqual(
+ new Set(['a', 'b'])
+ )
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ fireEvent.keyDown(screen.getByTestId('context-list'), {
+ key: 'i',
+ metaKey: true,
+ })
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ })
+
+ it.each(['darwin', 'win32'] as const)(
+ 'opens the existing removal confirmation, with files kept by default, on %s',
+ async (platform) => {
+ vi.mocked(transport).platform = platform
+ const selection = setup()
+ fireEvent.keyDown(screen.getByTestId('context-list'), {
+ key: platform === 'darwin' ? 'Backspace' : 'Delete',
+ metaKey: platform === 'darwin',
+ })
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
+ expect(transport.invoke).not.toHaveBeenCalled()
+ act(() => selection.getState().select('c'))
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }))
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.RemoveTasks, {
+ taskIds: ['a', 'b'],
+ deleteWithFiles: false,
+ })
+ )
+ }
+ )
+
+ it('preserves text editing, IME input, extra modifiers and held keys', () => {
+ const selection = setup()
+ const list = screen.getByTestId('context-list')
+ const input = document.createElement('input')
+ const editable = document.createElement('div')
+ editable.setAttribute('contenteditable', 'true')
+ const child = document.createElement('span')
+ editable.append(child)
+ list.append(input, editable)
+ for (const target of [input, child]) {
+ fireEvent.keyDown(target, { key: 'i', metaKey: true })
+ fireEvent.keyDown(target, { key: 'Backspace', metaKey: true })
+ fireEvent.copy(target)
+ }
+ fireEvent.keyDown(list, { key: 'i', metaKey: true, isComposing: true })
+ fireEvent.keyDown(list, { key: 'i', metaKey: true, shiftKey: true })
+ fireEvent.keyDown(list, { key: 'i', metaKey: true, repeat: true })
+ fireEvent.keyDown(list, { key: 'Backspace' })
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(navigator.clipboard.writeText).not.toHaveBeenCalled()
+ expect(selection.getState().committedSelectedIds).toEqual(
+ new Set(['a', 'b'])
+ )
+ })
+
+ it('copies the captured batch through a native copy event while the menu is open', async () => {
+ const selection = setup(
+ true,
+ tasks.map((task) => ({
+ ...task,
+ uris: [`https://example.test/${task.id}`],
+ }))
+ )
+ fireEvent.contextMenu(screen.getByText('b'))
+ const item = await screen.findByRole('menuitem', { name: 'Copy URLs' })
+ act(() => selection.getState().select('c'))
+ fireEvent.copy(item)
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ 'https://example.test/a\nhttps://example.test/b'
+ )
+ )
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ })
+
+ it('supports the same keyboard actions in the More menu', async () => {
+ setup(
+ false,
+ tasks.map((task) => ({
+ ...task,
+ uris: [`https://example.test/${task.id}`],
+ }))
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'More' }))
+ const item = await screen.findByRole('menuitem', { name: 'Copy URLs' })
+ fireEvent.keyDown(item, { key: 'c', metaKey: true })
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ 'https://example.test/a\nhttps://example.test/b'
+ )
+ )
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ })
+})
diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsx
new file mode 100644
index 00000000..e7989e27
--- /dev/null
+++ b/src/renderer/routes/downloads/task-actions-menu.tsx
@@ -0,0 +1,515 @@
+import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuTrigger,
+} from '@renderer/components/ui/context-menu'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { toast } from '@renderer/components/ui/toast'
+import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
+import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import type { DownloadTask } from '@shared/types/task'
+import { TaskStatus } from '@shared/types/task'
+import { canOpenTaskFile, canSelectTaskFiles } from '@shared/types/task-actions'
+import { Ellipsis } from 'lucide-react'
+import {
+ type ClipboardEvent,
+ Fragment,
+ type KeyboardEvent,
+ type ReactElement,
+ type Ref,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+import { DownloadsToolbarButton } from './downloads-toolbar-button'
+import { canRevealTaskFolder } from './inspector/can-reveal-task-folder'
+import { RemoveTasksDialog } from './inspector/remove-tasks-dialog'
+import { copyTaskUrls } from './inspector/task-copy-url'
+import { taskErrorReport } from './inspector/task-error-report'
+import { useTaskActions } from './inspector/use-task-actions'
+import { InspectorMenuItem, ListViewSubmenu } from './list-view-menu'
+import {
+ matchesTaskMenuShortcut,
+ taskMenuShortcuts,
+} from './task-menu-shortcuts'
+import { useDownloadsView } from './view-preferences'
+
+export function TaskActionsMenu({
+ tasks,
+ selection,
+ children,
+ onHideInspector,
+ triggerRef,
+}: {
+ tasks: readonly DownloadTask[]
+ selection: SelectionStore<DownloadTask>
+ /** A context trigger must forward DOM props and its ref. */
+ children?: ReactElement
+ onHideInspector?: () => void
+ triggerRef?: Ref<HTMLButtonElement>
+}) {
+ const { t, i18n } = useTranslation()
+ const selectedIds = selection((state) => state.committedSelectedIds)
+ const [targetIds, setTargetIds] = useState<ReadonlySet<string> | null>(null)
+ const selected = useMemo(
+ () => tasks.filter((task) => (targetIds ?? selectedIds).has(task.id)),
+ [tasks, targetIds, selectedIds]
+ )
+ const [menuOpen, setMenuOpen] = useState(false)
+ const pendingRef = useRef(false)
+ const [pending, setPending] = useState(false)
+ const actions = useTaskActions(selected)
+ const single = selected.length === 1 ? selected[0] : null
+ const canChooseFiles = single && canSelectTaskFiles(single)
+ const hasTransferActions =
+ actions.pauseCount +
+ actions.resumeCount +
+ actions.retryCount +
+ actions.reseedCount +
+ actions.stopSeedingCount >
+ 0 ||
+ single?.status === TaskStatus.MetadataReady ||
+ canChooseFiles ||
+ actions.moveCount > 0
+ const inspectorVisible = useDownloadsView((state) => state.inspectorVisible)
+ const macOS =
+ transport.platform === 'darwin' ||
+ (transport.platform === 'web' && /Mac|iPhone|iPad/.test(navigator.platform))
+ const shortcuts = useMemo(
+ () => taskMenuShortcuts(macOS, __MOTRIX_TARGET__ === 'electron'),
+ [macOS]
+ )
+ const taskPath = single?.finalPath || single?.diskPath
+ const runAction = async (
+ action: () => Promise<unknown>,
+ failureTitle: string
+ ) => {
+ if (pendingRef.current) return
+ pendingRef.current = true
+ setPending(true)
+ try {
+ await action()
+ } catch (error) {
+ toast.add({
+ title: failureTitle,
+ description: error instanceof Error ? error.message : String(error),
+ type: 'error',
+ })
+ } finally {
+ pendingRef.current = false
+ setPending(false)
+ }
+ }
+ const copy = (action: () => Promise<void>) => {
+ void runAction(async () => {
+ await action()
+ toast.add({ title: t('panel.downloads.action.copied'), type: 'success' })
+ }, t('panel.downloads.action.copyFailed'))
+ }
+ const prepare = () =>
+ setTargetIds(new Set(selection.getState().committedSelectedIds))
+ const restoreSelection = () => {
+ const state = selection.getState()
+ if (
+ selected.length === state.committedSelectedIds.size &&
+ selected.every((task) => state.committedSelectedIds.has(task.id))
+ )
+ return
+ if (!selected[0]) return
+ state.select(selected[0].id)
+ for (const task of selected.slice(1)) state.toggle(task.id)
+ }
+ const closeMenu = () => {
+ setMenuOpen(false)
+ setTargetIds(null)
+ }
+ const ignoresShortcut = (target: EventTarget | null) =>
+ target instanceof Element &&
+ Boolean(
+ target.closest(
+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="separator"]'
+ )
+ )
+ const handleShortcut = (event: KeyboardEvent) => {
+ if (
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ ignoresShortcut(event.target)
+ )
+ return
+ const action = matchesTaskMenuShortcut(event, shortcuts.inspector)
+ ? 'inspector'
+ : matchesTaskMenuShortcut(event, shortcuts.copyUrl)
+ ? 'copy'
+ : matchesTaskMenuShortcut(event, shortcuts.remove)
+ ? 'remove'
+ : null
+ if (!action || (action !== 'inspector' && selected.length === 0)) return
+ if (
+ action === 'inspector' &&
+ children &&
+ !selected.length &&
+ !inspectorVisible
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ if (action === 'inspector') {
+ if (inspectorVisible) onHideInspector?.()
+ else restoreSelection()
+ useDownloadsView.getState().setInspectorVisible(!inspectorVisible)
+ } else if (action === 'copy') {
+ copy(() => copyTaskUrls(selected))
+ } else if (actions.removeCount > 0 && !actions.removeDialog.open) {
+ actions.onRemove()
+ }
+ closeMenu()
+ }
+ // Native Edit > Copy can arrive as a copy event instead of a keydown.
+ const handleCopy = (event: ClipboardEvent) => {
+ if (
+ event.defaultPrevented ||
+ ignoresShortcut(event.target) ||
+ !selected.length
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ copy(() => copyTaskUrls(selected))
+ closeMenu()
+ }
+ const groups = [
+ {
+ id: 'access',
+ visible: selected.length > 0 || !children,
+ content: (
+ <>
+ {single &&
+ __MOTRIX_TARGET__ === 'electron' &&
+ canOpenTaskFile(single) && (
+ <DropdownMenuItem
+ disabled={pending}
+ onClick={() =>
+ void runAction(
+ () =>
+ transport.invoke(Commands.OpenTaskFile, {
+ taskId: single.id,
+ }),
+ t('panel.downloads.action.openFileFailed')
+ )
+ }
+ >
+ {t('panel.downloads.action.openFile')}
+ </DropdownMenuItem>
+ )}
+ {single &&
+ __MOTRIX_TARGET__ === 'electron' &&
+ canRevealTaskFolder(single) && (
+ <DropdownMenuItem
+ onClick={() => {
+ void transport
+ .invoke(Commands.RevealInFolder, { taskId: single.id })
+ .catch((error: unknown) =>
+ toast.add({
+ title: t('panel.downloads.action.singleTaskFailed', {
+ name: single.name,
+ reason: String(error),
+ }),
+ type: 'error',
+ })
+ )
+ }}
+ >
+ {t('panel.downloads.action.openFolder')}
+ </DropdownMenuItem>
+ )}
+ <InspectorMenuItem
+ onHide={onHideInspector}
+ onShow={restoreSelection}
+ shortcut={shortcuts.inspector}
+ />
+ {!children && <ListViewSubmenu />}
+ </>
+ ),
+ },
+ {
+ id: 'transfer',
+ visible: hasTransferActions,
+ content: (
+ <>
+ {actions.pauseCount > 0 && (
+ <DropdownMenuItem onClick={() => void actions.onPause()}>
+ {t('panel.downloads.action.pause')}
+ </DropdownMenuItem>
+ )}
+ {actions.resumeCount > 0 && (
+ <DropdownMenuItem onClick={() => void actions.onResume()}>
+ {t('panel.downloads.action.resume')}
+ </DropdownMenuItem>
+ )}
+ {actions.stopSeedingCount > 0 && (
+ <DropdownMenuItem onClick={() => void actions.onStopSeeding()}>
+ {t('panel.downloads.action.stopSeeding')}
+ </DropdownMenuItem>
+ )}
+ {actions.retryCount > 0 && (
+ <DropdownMenuItem onClick={() => void actions.onRetry()}>
+ {t('panel.downloads.action.retry')}
+ </DropdownMenuItem>
+ )}
+ {actions.reseedCount > 0 && (
+ <DropdownMenuItem onClick={() => void actions.onReseed()}>
+ {t('panel.downloads.action.reseed')}
+ </DropdownMenuItem>
+ )}
+ {single?.status === TaskStatus.MetadataReady && (
+ <DropdownMenuItem
+ disabled={pending}
+ onClick={() =>
+ void runAction(
+ () => openMagnetFileSelection(single.id),
+ t('panel.downloads.action.selectFilesFailed')
+ )
+ }
+ >
+ {t('panel.downloads.action.selectFiles')}
+ </DropdownMenuItem>
+ )}
+ {canChooseFiles && (
+ <DropdownMenuItem
+ onClick={() => {
+ selection.getState().select(single.id)
+ useDownloadsView.getState().setInspectorTab('files')
+ useDownloadsView.getState().setInspectorVisible(true)
+ }}
+ >
+ {t('panel.downloads.action.chooseFiles')}
+ </DropdownMenuItem>
+ )}
+ {actions.moveCount > 0 && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger disabled={actions.moving}>
+ {t('panel.downloads.action.queueOrder')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ data-menu-density="compact"
+ className="w-max min-w-44 max-w-[min(18rem,var(--available-width))]"
+ >
+ {(
+ [
+ ['up', 'moveQueueUp'],
+ ['down', 'moveQueueDown'],
+ ['top', 'moveQueueTop'],
+ ['bottom', 'moveQueueBottom'],
+ ] as const
+ ).map(([direction, label]) => (
+ <Fragment key={direction}>
+ {direction === 'top' && <DropdownMenuSeparator />}
+ <DropdownMenuItem
+ disabled={actions.moving}
+ onClick={() => void actions.onMove(direction)}
+ >
+ {t(`panel.downloads.action.${label}`)}
+ </DropdownMenuItem>
+ </Fragment>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ </>
+ ),
+ },
+ {
+ id: 'copy',
+ visible: selected.length > 0,
+ content: (
+ <>
+ <DropdownMenuItem
+ aria-keyshortcuts={shortcuts.copyUrl.aria}
+ disabled={selected.length === 0 || pending}
+ onClick={() => copy(() => copyTaskUrls(selected))}
+ >
+ {t(
+ selected.length > 1
+ ? 'panel.downloads.action.copyUrls'
+ : 'panel.downloads.action.copyUrl'
+ )}
+ <DropdownMenuShortcut aria-hidden="true">
+ {shortcuts.copyUrl.label}
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+ {taskPath && (
+ <DropdownMenuItem
+ disabled={pending}
+ onClick={() =>
+ copy(() => navigator.clipboard.writeText(taskPath))
+ }
+ >
+ {t('panel.downloads.action.copyPath')}
+ </DropdownMenuItem>
+ )}
+ {selected.some((task) => task.status === TaskStatus.Error) && (
+ <DropdownMenuItem
+ disabled={pending}
+ onClick={() =>
+ copy(() =>
+ navigator.clipboard.writeText(
+ taskErrorReport(selected, {
+ t,
+ exists: (key) => i18n.exists(key),
+ })
+ )
+ )
+ }
+ >
+ {t('panel.downloads.action.copyError')}
+ </DropdownMenuItem>
+ )}
+ </>
+ ),
+ },
+ {
+ id: 'create',
+ visible: true,
+ content: (
+ <DropdownMenuItem
+ disabled={pending}
+ aria-keyshortcuts={shortcuts.newTask?.aria}
+ onClick={() =>
+ void runAction(() => openAddTaskDialog(), t('common.error'))
+ }
+ >
+ {t('menu.task.newTask')}
+ {shortcuts.newTask && (
+ <DropdownMenuShortcut aria-hidden="true">
+ {shortcuts.newTask.label}
+ </DropdownMenuShortcut>
+ )}
+ </DropdownMenuItem>
+ ),
+ },
+ {
+ id: 'remove',
+ visible: actions.removeCount > 0,
+ content: (
+ <DropdownMenuItem
+ variant="destructive"
+ aria-keyshortcuts={shortcuts.remove.aria}
+ onClick={() => actions.onRemove()}
+ >
+ {t('panel.downloads.action.remove')}
+ <DropdownMenuShortcut aria-hidden="true">
+ {shortcuts.remove.label}
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+ ),
+ },
+ ].filter((group) => group.visible)
+ const items = groups.map((group, index) => (
+ <Fragment key={group.id}>
+ {index > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuGroup>{group.content}</DropdownMenuGroup>
+ </Fragment>
+ ))
+ const dialog = (
+ <RemoveTasksDialog
+ open={actions.removeDialog.open}
+ selected={actions.removeTargets}
+ preCheckDeleteFiles={actions.removeDialog.preCheckDeleteFiles}
+ onOpenChange={(open) => {
+ if (!open) actions.closeRemoveDialog()
+ }}
+ onConfirm={(deleteFiles) => void actions.confirmRemove(deleteFiles)}
+ />
+ )
+ if (children)
+ return (
+ <>
+ <ContextMenu
+ open={menuOpen}
+ onOpenChange={(open) => {
+ if (open) prepare()
+ else setTargetIds(null)
+ setMenuOpen(open)
+ }}
+ >
+ <ContextMenuTrigger
+ render={children}
+ onKeyDownCapture={handleShortcut}
+ onCopyCapture={handleCopy}
+ onContextMenuCapture={(event) => {
+ const row = (event.target as Element).closest<HTMLElement>(
+ '[data-task-id]'
+ )
+ if (!row?.dataset.taskId) return
+ const state = selection.getState()
+ if (!state.selectedIds.has(row.dataset.taskId))
+ state.select(row.dataset.taskId)
+ state.focus(row.dataset.taskId)
+ prepare()
+ }}
+ />
+ <ContextMenuContent
+ onKeyDownCapture={handleShortcut}
+ onCopyCapture={handleCopy}
+ className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
+ >
+ {items}
+ </ContextMenuContent>
+ </ContextMenu>
+ {dialog}
+ </>
+ )
+ return (
+ <>
+ <DropdownMenu
+ open={menuOpen}
+ onOpenChange={(open) => {
+ if (open) prepare()
+ else setTargetIds(null)
+ setMenuOpen(open)
+ }}
+ >
+ <DropdownMenuTrigger
+ onKeyDownCapture={handleShortcut}
+ onCopyCapture={handleCopy}
+ render={
+ <DownloadsToolbarButton
+ aria-label={t('panel.downloads.view.taskActions')}
+ title={t('panel.downloads.view.taskActions')}
+ ref={triggerRef}
+ />
+ }
+ >
+ <Ellipsis className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ onKeyDownCapture={handleShortcut}
+ onCopyCapture={handleCopy}
+ align="end"
+ data-menu-density="compact"
+ className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
+ >
+ {items}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {dialog}
+ </>
+ )
+}
diff --git a/src/renderer/routes/downloads/task-column-header.test.tsx b/src/renderer/routes/downloads/task-column-header.test.tsx
index 4ceadc58..7a815257 100644
--- a/src/renderer/routes/downloads/task-column-header.test.tsx
+++ b/src/renderer/routes/downloads/task-column-header.test.tsx
@@ -1,48 +1,99 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import { fireEvent, render, screen } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vitest'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { defaultTaskColumns } from './columns'
+import { nextTaskSort, type TaskSort } from './sort'
import { TaskColumnHeader } from './task-column-header'
+import { useDownloadsView } from './view-preferences'
+
+beforeEach(() => useDownloadsView.setState({ columns: defaultTaskColumns() }))
describe('TaskColumnHeader', () => {
- it('renders localized column labels', () => {
- render(
+ it('uses column semantics and only displays the active chevron', async () => {
+ const user = userEvent.setup()
+ const { container, rerender } = render(
+ <TaskColumnHeader sort={null} onSort={() => {}} />
+ )
+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
+ expect(container.querySelector('button svg')).toBeNull()
+ await user.hover(screen.getByRole('button', { name: 'Name' }))
+ expect(container.querySelector('button svg')).toBeNull()
+ rerender(
<TaskColumnHeader
- headerCheckbox={{
- checked: false,
- indeterminate: false,
- onChange: () => {},
- }}
+ sort={{ column: 'createdAt', direction: 'desc' }}
+ onSort={() => {}}
/>
)
- expect(screen.getByText(/name/i)).toBeInTheDocument()
- expect(screen.getByText(/status/i)).toBeInTheDocument()
+ expect(container.querySelectorAll('button svg')).toHaveLength(1)
+ expect(
+ screen.getByRole('columnheader', { name: /Date created/ })
+ ).toHaveAttribute('aria-sort', 'descending')
})
- it('covers the full horizontal scroll width on compact viewports', () => {
- render(
- <TaskColumnHeader
- headerCheckbox={{
- checked: false,
- indeterminate: false,
- onChange: () => {},
- }}
- />
- )
+ it('reverses sorting repeatedly by keyboard without reaching the list handler', async () => {
+ const onKeyDown = vi.fn()
+ const user = userEvent.setup()
+ function Harness() {
+ const [sort, setSort] = useState<TaskSort>(null)
+ return (
+ <div role="listbox" tabIndex={0} onKeyDown={onKeyDown}>
+ <TaskColumnHeader
+ sort={sort}
+ onSort={(column) =>
+ setSort((current) => nextTaskSort(current, column))
+ }
+ />
+ </div>
+ )
+ }
+ render(<Harness />)
+ const button = screen.getByRole('button', { name: 'Name' })
+ button.focus()
+ await user.keyboard(' ')
+ expect(button).toHaveAccessibleName('Name: ascending')
+ await user.keyboard('{Enter}')
+ expect(button).toHaveAccessibleName('Name: descending')
+ await user.keyboard(' ')
+ expect(button).toHaveAccessibleName('Name: ascending')
+ expect(onKeyDown).not.toHaveBeenCalled()
+ })
- expect(screen.getByText(/name/i).parentElement).toHaveStyle({
- minWidth: '960px',
+ it('allows keyboard resizing and reordering without sorting', () => {
+ const onSort = vi.fn()
+ render(<TaskColumnHeader sort={null} onSort={onSort} />)
+ fireEvent.keyDown(
+ screen.getByRole('separator', { name: 'Resize Name column' }),
+ { key: 'ArrowRight' }
+ )
+ expect(useDownloadsView.getState().columns[0].width).toBe(256)
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Name' }), {
+ key: 'ArrowRight',
+ shiftKey: true,
+ altKey: true,
})
+ expect(
+ useDownloadsView
+ .getState()
+ .columns.slice(0, 2)
+ .map((column) => column.id)
+ ).toEqual(['size', 'name'])
+ expect(onSort).not.toHaveBeenCalled()
})
- it('fires onChange when header checkbox clicked', () => {
- const onChange = vi.fn()
- render(
- <TaskColumnHeader
- headerCheckbox={{ checked: false, indeterminate: false, onChange }}
- />
- )
- fireEvent.click(screen.getByRole('checkbox'))
- expect(onChange).toHaveBeenCalled()
+ it('opens the shadcn context menu to choose columns', async () => {
+ render(<TaskColumnHeader sort={null} onSort={() => {}} />)
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'Name' }))
+ expect(
+ await screen.findByRole('menuitemcheckbox', { name: 'Name' })
+ ).toHaveAttribute('aria-disabled', 'true')
+ const eta = screen.getByRole('menuitemcheckbox', { name: 'ETA' })
+ fireEvent.click(eta)
+ expect(
+ useDownloadsView.getState().columns.find((column) => column.id === 'eta')
+ ?.visible
+ ).toBe(true)
})
})
diff --git a/src/renderer/routes/downloads/task-column-header.tsx b/src/renderer/routes/downloads/task-column-header.tsx
index f32f2e50..df248dad 100644
--- a/src/renderer/routes/downloads/task-column-header.tsx
+++ b/src/renderer/routes/downloads/task-column-header.tsx
@@ -1,47 +1,158 @@
-import { Checkbox } from '@renderer/components/ui/checkbox'
+import { ResizeHandle } from '@renderer/components/desktop-kit/resize-handle'
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuTrigger,
+} from '@renderer/components/ui/context-menu'
+import { cn } from '@renderer/lib/utils'
+import { ChevronDown, ChevronUp } from 'lucide-react'
+import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import {
+ defaultTaskColumns,
+ TASK_COLUMNS,
+ type TaskColumn,
+ taskGridStyle,
+} from './columns'
+import { ColumnVisibilityItems } from './list-view-menu'
+import { nextTaskSort, type TaskSort, type TaskSortColumn } from './sort'
+import { useDownloadsView } from './view-preferences'
export interface TaskColumnHeaderProps {
- headerCheckbox: {
- checked: boolean
- indeterminate: boolean
- onChange: () => void
- }
+ sort: TaskSort
+ onSort: (column: TaskSortColumn) => void
+ columns?: TaskColumn[]
}
-export const TASK_GRID_TEMPLATE =
- '28px minmax(180px,2.2fr) 80px 130px 90px 90px 80px 72px 90px'
-
-// Fixed tracks + the name track's minimum + gaps + horizontal padding.
-// Keeping the grid box at least this wide makes its background and borders
-// cover the full horizontal scroll range on compact viewports.
-export const TASK_GRID_MIN_WIDTH = 960
-
-export function TaskColumnHeader({ headerCheckbox }: TaskColumnHeaderProps) {
+export function TaskColumnHeader({
+ sort,
+ onSort,
+ columns = defaultTaskColumns(),
+}: TaskColumnHeaderProps) {
const { t } = useTranslation()
+ const setWidth = useDownloadsView((state) => state.setColumnWidth)
+ const moveColumn = useDownloadsView((state) => state.moveColumn)
+ const dragging = useRef<TaskSortColumn | null>(null)
return (
- <div
- className="sticky top-0 z-10 grid h-9 shrink-0 items-center gap-3 border-b border-border bg-background px-3 py-2 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground"
- style={{
- gridTemplateColumns: TASK_GRID_TEMPLATE,
- minWidth: TASK_GRID_MIN_WIDTH,
- }}
- >
- <Checkbox
- checked={headerCheckbox.checked}
- indeterminate={headerCheckbox.indeterminate}
- onCheckedChange={headerCheckbox.onChange}
- />
- <span>{t('panel.downloads.column.name')}</span>
- <span className="tabular-nums">{t('panel.downloads.column.size')}</span>
- <span>{t('panel.downloads.column.progress')}</span>
- <span>{t('panel.downloads.column.status')}</span>
- <span className="tabular-nums">{t('panel.downloads.column.down')}</span>
- <span className="tabular-nums">{t('panel.downloads.column.up')}</span>
- <span>{t('panel.downloads.column.eta')}</span>
- <span className="tabular-nums">
- {t('panel.downloads.column.connections')}
- </span>
- </div>
+ <ContextMenu>
+ <ContextMenuTrigger
+ render={
+ // biome-ignore lint/a11y/useSemanticElements: Virtualized rows use CSS grids within a scrolling div.
+ <div
+ role="row"
+ tabIndex={-1}
+ aria-rowindex={1}
+ className="sticky top-0 z-10 grid h-9 shrink-0 items-center border-b border-border bg-background px-3 text-xs font-medium text-muted-foreground"
+ style={taskGridStyle(columns)}
+ />
+ }
+ >
+ {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 next = nextTaskSort(sort, id)
+ const SortIcon = sort?.direction === 'asc' ? ChevronUp : ChevronDown
+ return (
+ // biome-ignore lint/a11y/useSemanticElements: Column headers belong to the virtual ARIA grid.
+ <div
+ key={id}
+ tabIndex={-1}
+ role="columnheader"
+ aria-colindex={index + 1}
+ aria-sort={
+ active
+ ? sort.direction === 'asc'
+ ? 'ascending'
+ : 'descending'
+ : undefined
+ }
+ className="relative min-w-0"
+ onDragOver={(event) => {
+ if (dragging.current) event.preventDefault()
+ }}
+ onDrop={(event) => {
+ event.preventDefault()
+ if (dragging.current) moveColumn(dragging.current, id)
+ dragging.current = null
+ }}
+ >
+ <button
+ type="button"
+ draggable
+ aria-pressed={active}
+ aria-label={
+ active
+ ? t(`panel.downloads.sort.${sort.direction}`, {
+ column: accessibleLabel,
+ })
+ : accessibleLabel
+ }
+ title={t(
+ `panel.downloads.sort.${next.direction === 'asc' ? 'sortAscending' : 'sortDescending'}`,
+ { column: accessibleLabel }
+ )}
+ className={cn(
+ 'flex h-7 w-full min-w-0 cursor-default items-center gap-1 rounded-sm px-2 text-left outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring',
+ active && 'text-foreground'
+ )}
+ onClick={() => onSort(id)}
+ onDragStart={(event) => {
+ dragging.current = id
+ event.dataTransfer.effectAllowed = 'move'
+ event.dataTransfer.setData('text/plain', id)
+ }}
+ onDragEnd={() => {
+ dragging.current = null
+ }}
+ onKeyDown={(event) => {
+ event.stopPropagation()
+ if (
+ !event.altKey ||
+ !event.shiftKey ||
+ !['ArrowLeft', 'ArrowRight'].includes(event.key)
+ )
+ return
+ event.preventDefault()
+ const neighbor =
+ columns[index + (event.key === 'ArrowLeft' ? -1 : 1)]
+ if (!neighbor) return
+ if (event.key === 'ArrowLeft') moveColumn(id, neighbor.id)
+ else moveColumn(neighbor.id, id)
+ }}
+ onMouseDownCapture={(event) => event.stopPropagation()}
+ >
+ <span className="truncate">{label}</span>
+ {active && (
+ <SortIcon
+ aria-hidden="true"
+ className="ml-auto size-3 shrink-0"
+ />
+ )}
+ </button>
+ <ResizeHandle
+ label={t('panel.downloads.view.resizeColumn', {
+ column: accessibleLabel,
+ })}
+ orientation="vertical"
+ value={column.width}
+ min={TASK_COLUMNS[id].min}
+ max={TASK_COLUMNS[id].max}
+ className="absolute -right-1 top-0 z-10 h-7 w-2 cursor-col-resize touch-none border-r border-border/50 outline-none focus-visible:bg-ring/30"
+ onChange={(width) => setWidth(id, width, false)}
+ onCommit={(width) => setWidth(id, width)}
+ />
+ </div>
+ )
+ })}
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ColumnVisibilityItems />
+ </ContextMenuContent>
+ </ContextMenu>
)
}
diff --git a/src/renderer/routes/downloads/task-column-values.ts b/src/renderer/routes/downloads/task-column-values.ts
new file mode 100644
index 00000000..ff95b34a
--- /dev/null
+++ b/src/renderer/routes/downloads/task-column-values.ts
@@ -0,0 +1,46 @@
+import { type DownloadTask, TaskStatus, TaskType } from '@shared/types/task'
+
+export function getTaskSpeed(
+ task: DownloadTask,
+ field: 'downloadSpeed' | 'uploadSpeed'
+): number | null {
+ const speed = task[field]
+ return task.status === TaskStatus.Completed ||
+ task.status === TaskStatus.Finalizing ||
+ !Number.isFinite(speed) ||
+ speed <= 0
+ ? null
+ : speed
+}
+
+export function getTaskEta(task: DownloadTask): number | null {
+ return task.status === TaskStatus.Paused ||
+ task.status === TaskStatus.Completed ||
+ task.status === TaskStatus.Finalizing ||
+ !Number.isFinite(task.etaSeconds) ||
+ task.etaSeconds <= 0
+ ? null
+ : task.etaSeconds
+}
+
+export function getTaskConnections(task: DownloadTask): number {
+ return task.type === TaskType.Bt || task.type === TaskType.Magnet
+ ? (task.bt?.peers ?? 0)
+ : task.connections
+}
+
+export function getTaskTimestamp(
+ task: DownloadTask,
+ field: 'createdAt' | 'finishedAt'
+): number | null {
+ // finishedAt also records failures in the domain model. Only successful
+ // completion belongs in the Completed column, matching the inspector.
+ if (field === 'finishedAt' && task.status !== TaskStatus.Completed)
+ return null
+ const timestamp = task[field]
+ return timestamp !== null &&
+ timestamp > 0 &&
+ Number.isFinite(new Date(timestamp).getTime())
+ ? timestamp
+ : null
+}
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx
index 3755cb2a..e5abcf27 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx
@@ -1,5 +1,6 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
+import { getInspectorSnapHeights } from '@renderer/components/desktop-kit/inspector-drawer'
import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'
import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
import { DownloadErrorCode } from '@shared/errors'
@@ -16,6 +17,7 @@ import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TaskInspectorDrawer } from './task-inspector-drawer'
+import { useDownloadsView } from './view-preferences'
const activityHookState = vi.hoisted(() => ({
current: null as unknown,
@@ -155,7 +157,47 @@ function TestHarness({
}
describe('TaskInspectorDrawer', () => {
+ it.each([
+ [900, [220, 450, 675]],
+ [600, [220, 300, 450]],
+ [500, [220, 220, 375]],
+ [400, [220, 220, 300]],
+ [300, [225, 225, 225]],
+ [240, [176, 176, 176]],
+ ] as const)('adapts snap heights to a %ipx container', (height, expected) => {
+ expect(getInspectorSnapHeights(height)).toEqual(expected)
+ })
+
+ it('skips merged detents when resizing with the keyboard in a short window', async () => {
+ const measure = vi
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockReturnValue(new DOMRect(0, 0, 1000, 400))
+ try {
+ const user = userEvent.setup()
+ const selection = createSelectionStore<DownloadTask>((task) => task.id)
+ render(<TestHarness selection={selection} tasks={[]} />)
+ const resize = screen.getByRole('separator', { name: 'Resize Inspector' })
+ expect(resize).toHaveAttribute('aria-valuenow', '220')
+ expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
+ resize.focus()
+ await user.keyboard('{ArrowUp}')
+ expect(resize).toHaveAttribute('aria-valuenow', '300')
+ expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')
+ await user.keyboard('{ArrowDown}')
+ expect(resize).toHaveAttribute('aria-valuenow', '220')
+ await user.keyboard('{ArrowDown}')
+ expect(resize).toHaveAttribute('aria-valuenow', '220')
+ } finally {
+ measure.mockRestore()
+ }
+ })
+
beforeEach(() => {
+ useDownloadsView.setState({
+ inspectorTab: 'overview',
+ inspectorVisible: true,
+ inspectorSnap: 'medium',
+ })
activityHookState.calls.length = 0
activityHookState.current = {
status: 'ready',
@@ -163,7 +205,8 @@ describe('TaskInspectorDrawer', () => {
}
})
- it('does not render drawer content when selection is empty', () => {
+ it('does not render drawer content when hidden', () => {
+ useDownloadsView.setState({ inspectorVisible: false })
const selection = createSelectionStore<DownloadTask>((t) => t.id)
render(<TestHarness selection={selection} tasks={[fake()]} />)
expect(screen.queryByRole('dialog')).toBeNull()
@@ -299,7 +342,7 @@ describe('TaskInspectorDrawer', () => {
expect(screen.getByText(/total size/i)).toBeInTheDocument()
})
- it('clears selection and calls the optional dismissal callback', () => {
+ it('preserves selection when closed and calls the dismissal callback', () => {
const selection = createSelectionStore<DownloadTask>((t) => t.id)
const tasks = [fake({ id: 'a' })]
const onDismiss = vi.fn()
@@ -309,11 +352,9 @@ describe('TaskInspectorDrawer', () => {
<TestHarness selection={selection} tasks={tasks} onDismiss={onDismiss} />
)
- act(() =>
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
- )
+ act(() => screen.getByRole('button', { name: 'Close' }).click())
- expect(selection.getState().committedSelectedIds).toEqual(new Set())
+ expect(selection.getState().committedSelectedIds).toEqual(new Set(['a']))
expect(onDismiss).toHaveBeenCalledOnce()
})
@@ -347,11 +388,11 @@ describe('TaskInspectorDrawer', () => {
expect(screen.queryByRole('dialog', { name: 'Failed details' })).toBeNull()
await user.keyboard('{Escape}')
- expect(selection.getState().committedSelectedIds).toEqual(new Set())
+ expect(selection.getState().committedSelectedIds).toEqual(new Set(['a']))
expect(onDismiss).toHaveBeenCalledOnce()
})
- it('allows Activity to use more drawer height without changing other tabs', async () => {
+ it('keeps the chosen snap point when changing tabs', async () => {
const user = userEvent.setup()
const selection = createSelectionStore<DownloadTask>((t) => t.id)
const tasks = [fake({ id: 'a' })]
@@ -360,12 +401,47 @@ describe('TaskInspectorDrawer', () => {
render(<TestHarness selection={selection} tasks={tasks} />)
const drawer = screen.getByRole('dialog')
- expect(drawer).toHaveClass('max-h-[min(80%,calc(100%-16rem))]')
- expect(drawer).not.toHaveClass('max-h-[min(85%,calc(100%-16rem))]')
+ const height = drawer.style.height
await user.click(screen.getByRole('tab', { name: /activity/i }))
- expect(drawer).toHaveClass('max-h-[min(85%,calc(100%-16rem))]')
- expect(drawer).not.toHaveClass('max-h-[min(80%,calc(100%-16rem))]')
+ expect(drawer.style.height).toBe(height)
+ expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
})
+
+ it.each(['empty', 'single', 'multiple', 'finalizing'] as const)(
+ 'resizes from the %s header without consuming button keys',
+ async (mode) => {
+ const user = userEvent.setup()
+ const selection = createSelectionStore<DownloadTask>((task) => task.id)
+ const tasks = [
+ fake({
+ id: 'a',
+ status:
+ mode === 'finalizing' ? TaskStatus.Finalizing : TaskStatus.Paused,
+ }),
+ fake({ id: 'b' }),
+ ]
+ selection.getState().setItems(tasks)
+ if (mode === 'multiple') selection.getState().selectAll()
+ else if (mode !== 'empty') selection.getState().select('a')
+ render(<TestHarness selection={selection} tasks={tasks} />)
+
+ const resize = screen.getByRole('separator', { name: 'Resize Inspector' })
+ const header = resize.closest('[data-slot="drawer-header"]')
+ const close = screen.getByRole('button', { name: 'Close' })
+ expect(header).toContainElement(close)
+ expect(resize).not.toContainElement(close)
+ close.focus()
+ await user.keyboard('{ArrowUp}')
+ expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
+ resize.focus()
+ await user.keyboard('{Home}')
+ expect(useDownloadsView.getState().inspectorSnap).toBe('compact')
+ await user.keyboard('{ArrowUp}')
+ expect(useDownloadsView.getState().inspectorSnap).toBe('medium')
+ await user.keyboard('{End}')
+ expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')
+ }
+ )
})
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsx
index 57f6d2cc..9a4e3b4d 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx
@@ -1,7 +1,14 @@
import { CopyButton } from '@renderer/components/desktop-kit/copy-button'
+import { InspectorDrawer } from '@renderer/components/desktop-kit/inspector-drawer'
import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
import { Badge } from '@renderer/components/ui/badge'
import { Button } from '@renderer/components/ui/button'
+import {
+ ScrollArea,
+ ScrollAreaContent,
+ ScrollAreaViewport,
+ ScrollBar,
+} from '@renderer/components/ui/scroll-area'
import {
Tabs,
TabsContent,
@@ -10,7 +17,6 @@ import {
} from '@renderer/components/ui/tabs'
import { createTaskInspectorActivitySnapshotCache } from '@renderer/hooks/use-task-inspector-activity'
import { transport } from '@renderer/lib/transport'
-import { cn } from '@renderer/lib/utils'
import { Commands } from '@shared/protocol/commands'
import type { DownloadTask } from '@shared/types/task'
import { TaskType } from '@shared/types/task'
@@ -23,9 +29,9 @@ import {
RadioTower,
SquareActivity,
UsersRound,
+ X,
} from 'lucide-react'
-import { useCallback, useEffect, useMemo, useState } from 'react'
-import { createPortal } from 'react-dom'
+import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { ActivityTab } from './inspector/activity-tab'
import { canRevealTaskFolder } from './inspector/can-reveal-task-folder'
@@ -37,19 +43,12 @@ import { PiecesTab } from './inspector/pieces-tab'
import { TaskInspectorActionBar } from './inspector/task-inspector-action-bar'
import { TrackersTab } from './inspector/trackers-tab'
import { StatusPill } from './status-pill'
-
-type SubTab =
- | 'overview'
- | 'files'
- | 'pieces'
- | 'peers'
- | 'trackers'
- | 'activity'
+import { type InspectorTab, useDownloadsView } from './view-preferences'
export interface TaskInspectorDrawerProps {
selection: SelectionStore<DownloadTask>
tasks: readonly DownloadTask[]
- /** Bounded flex-column portal target. The inspector shares height with the list. */
+ /** Bounded portal target. The inspector overlays the list without resizing it. */
container: HTMLElement | null
onDismiss?: () => void
}
@@ -70,12 +69,14 @@ export function TaskInspectorDrawer({
}: TaskInspectorDrawerProps) {
const { t } = useTranslation()
const selected = useSelectedTasks(selection, tasks)
- const clear = selection((s) => s.clearSelection)
- const open = selected.length > 0
+ const open = useDownloadsView((s) => s.inspectorVisible)
+ const snap = useDownloadsView((s) => s.inspectorSnap)
+ const setSnap = useDownloadsView((s) => s.setInspectorSnap)
const single = selected.length === 1 ? selected[0] : null
const isBt = single?.type === TaskType.Bt || single?.type === TaskType.Magnet
const showPieces = single !== null && canInspectPieces(single)
- const [subtab, setSubtab] = useState<SubTab>('overview')
+ const subtab = useDownloadsView((s) => s.inspectorTab)
+ const setSubtab = useDownloadsView((s) => s.setInspectorTab)
const activitySnapshotCache = useMemo(
createTaskInspectorActivitySnapshotCache,
[]
@@ -83,182 +84,206 @@ export function TaskInspectorDrawer({
const onClose = useCallback(() => {
onDismiss?.()
- clear()
- }, [clear, onDismiss])
+ useDownloadsView.getState().setInspectorVisible(false)
+ }, [onDismiss])
+ const activeSubtab =
+ (subtab === 'pieces' && !showPieces) ||
+ ((subtab === 'peers' || subtab === 'trackers') && !isBt)
+ ? 'overview'
+ : subtab
- useEffect(() => {
- if (!open) return
- const onKey = (e: KeyboardEvent) => {
- if (e.key !== 'Escape' || e.defaultPrevented) return
- if (
- e.target instanceof Element &&
- e.target.closest('[data-activity-detail-surface="true"]')
- ) {
- return
+ return (
+ <InspectorDrawer
+ container={container}
+ open={open}
+ snap={snap}
+ onSnapChange={setSnap}
+ onClose={onClose}
+ title={t('panel.downloads.view.inspector')}
+ resizeLabel={t('panel.downloads.view.resizeInspector')}
+ renderHeader={(resizeHandle) =>
+ selected.length > 0 ? (
+ <TaskInspectorActionBar
+ selected={selected}
+ onClose={onClose}
+ resizeHandle={resizeHandle}
+ />
+ ) : (
+ <div className="flex shrink-0 items-center justify-between border-b border-border/50 px-4 py-2">
+ <span className="text-xs font-medium">
+ {t('panel.downloads.view.inspector')}
+ </span>
+ {resizeHandle}
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ aria-label={t('common.close')}
+ onClick={onClose}
+ >
+ <X />
+ </Button>
+ </div>
+ )
}
- onClose()
- }
- window.addEventListener('keydown', onKey)
- return () => window.removeEventListener('keydown', onKey)
- }, [open, onClose])
-
- const drawer = open ? (
- <div
- role="dialog"
- aria-label={t('panel.downloads.title')}
- className={cn(
- 'drawer-slide-in relative z-30 flex shrink-0 flex-col',
- // Keep room for the panel chrome, column header, and selectable rows.
- subtab === 'activity'
- ? 'max-h-[min(85%,calc(100%-16rem))]'
- : 'max-h-[min(80%,calc(100%-16rem))]',
- 'border-t border-border bg-background',
- 'shadow-[0_-6px_20px_rgba(15,23,42,0.1)]'
- )}
>
- <TaskInspectorActionBar selected={selected} onClose={onClose} />
+ <ScrollArea className="min-h-0 flex-1">
+ <ScrollAreaViewport
+ data-testid="task-inspector-drawer-content"
+ className="overscroll-contain"
+ >
+ <ScrollAreaContent
+ className="px-4 pb-4 pt-3"
+ style={{ minWidth: '100%' }}
+ >
+ {single ? (
+ <>
+ <div className="mb-3 flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1 flex flex-col gap-1">
+ <div className="min-w-0 flex items-center gap-2">
+ <Badge
+ variant="default"
+ className="shrink-0 rounded px-2 py-0 text-[10px]"
+ >
+ {single.type.toUpperCase()}
+ </Badge>
+ <span className="min-w-0 truncate text-sm font-medium">
+ {single.name}
+ </span>
+ </div>
- <div
- data-testid="task-inspector-drawer-content"
- className="min-h-0 flex-1 overflow-auto px-4 pb-4 pt-3"
- >
- {single ? (
- <>
- <div className="mb-3 flex items-start justify-between gap-3">
- <div className="min-w-0 flex-1 flex flex-col gap-1">
- <div className="min-w-0 flex items-center gap-2">
- <Badge
- variant="default"
- className="shrink-0 rounded px-2 py-0 text-[10px]"
- >
- {single.type.toUpperCase()}
- </Badge>
- <span className="min-w-0 truncate text-sm font-medium">
- {single.name}
- </span>
+ {__MOTRIX_TARGET__ === 'electron' &&
+ canRevealTaskFolder(single) && (
+ <div className="min-w-0 flex items-center gap-1 text-xs text-muted-foreground">
+ <Button
+ className="min-w-0 flex-1 justify-start overflow-hidden text-muted-foreground hover:no-underline cursor-pointer"
+ variant="secondary"
+ size="xs"
+ dir="ltr"
+ onClick={() =>
+ transport.invoke(Commands.RevealInFolder, {
+ taskId: single.id,
+ })
+ }
+ >
+ <HardDrive className="mr-1 size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">
+ {single.finalPath || single.diskPath}
+ </span>
+ </Button>
+ <CopyButton
+ variant="ghost"
+ className="ml-1 h-4.5 w-4.5 shrink-0 rounded-md p-0 has-[>svg]:px-0 [&_svg:not([class*='size-'])]:size-3"
+ content={single.finalPath || single.diskPath}
+ />
+ </div>
+ )}
+ </div>
+ <StatusPill status={single.status} />
</div>
-
- {__MOTRIX_TARGET__ === 'electron' &&
- canRevealTaskFolder(single) && (
- <div className="min-w-0 flex items-center gap-1 text-xs text-muted-foreground">
- <Button
- className="min-w-0 flex-1 justify-start overflow-hidden text-muted-foreground hover:no-underline cursor-pointer"
- variant="secondary"
- size="xs"
- dir="ltr"
- onClick={() =>
- transport.invoke(Commands.RevealInFolder, {
- taskId: single.id,
- })
- }
+ <Tabs
+ value={activeSubtab}
+ onValueChange={(v) => setSubtab(v as InspectorTab)}
+ >
+ <TabsList className="mb-1 bg-tab-background">
+ <TabsTrigger
+ value="overview"
+ className="text-xs px-5"
+ aria-label={t('panel.downloads.inspector.tab.overview')}
+ title={t('panel.downloads.inspector.tab.overview')}
+ >
+ <Info className="size-3.5" />
+ </TabsTrigger>
+ <TabsTrigger
+ value="files"
+ className="text-xs px-5"
+ aria-label={t('panel.downloads.inspector.tab.files')}
+ title={t('panel.downloads.inspector.tab.files')}
+ >
+ <Files className="size-3.5" />
+ </TabsTrigger>
+ {showPieces && (
+ <TabsTrigger
+ value="pieces"
+ className="text-xs px-5"
+ aria-label={t('panel.downloads.inspector.tab.pieces')}
+ title={t('panel.downloads.inspector.tab.pieces')}
>
- <HardDrive className="mr-1 size-3.5 shrink-0 text-muted-foreground" />
- <span className="truncate">
- {single.finalPath || single.diskPath}
- </span>
- </Button>
- <CopyButton
- variant="ghost"
- className="ml-1 h-4.5 w-4.5 shrink-0 rounded-md p-0 has-[>svg]:px-0 [&_svg:not([class*='size-'])]:size-3"
- content={single.finalPath || single.diskPath}
- />
- </div>
+ <Grid3x3 className="size-3.5" />
+ </TabsTrigger>
+ )}
+ {isBt && (
+ <TabsTrigger
+ value="peers"
+ className="text-xs px-5"
+ aria-label={t('panel.downloads.inspector.tab.peers')}
+ title={t('panel.downloads.inspector.tab.peers')}
+ >
+ <UsersRound className="size-3.5" />
+ </TabsTrigger>
+ )}
+ {isBt && (
+ <TabsTrigger
+ value="trackers"
+ className="text-xs px-5"
+ aria-label={t('panel.downloads.inspector.tab.trackers')}
+ title={t('panel.downloads.inspector.tab.trackers')}
+ >
+ <RadioTower className="size-3.5" />
+ </TabsTrigger>
+ )}
+ <TabsTrigger
+ value="activity"
+ className="text-xs px-5"
+ aria-label={t('panel.downloads.inspector.tab.activity')}
+ title={t('panel.downloads.inspector.tab.activity')}
+ >
+ <SquareActivity className="size-3.5" />
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="overview" className="min-h-0">
+ <OverviewTab
+ task={single}
+ snapshotCache={activitySnapshotCache}
+ />
+ </TabsContent>
+ <TabsContent value="files" className="min-h-0">
+ <FilesTab key={single.id} task={single} />
+ </TabsContent>
+ {showPieces && (
+ <TabsContent value="pieces" className="min-h-0">
+ <PiecesTab task={single} />
+ </TabsContent>
)}
- </div>
- <StatusPill status={single.status} />
- </div>
- <Tabs value={subtab} onValueChange={(v) => setSubtab(v as SubTab)}>
- <TabsList className="mb-1 bg-tab-background">
- <TabsTrigger
- value="overview"
- className="text-xs px-5"
- aria-label={t('panel.downloads.inspector.tab.overview')}
- title={t('panel.downloads.inspector.tab.overview')}
- >
- <Info className="size-3.5" />
- </TabsTrigger>
- <TabsTrigger
- value="files"
- className="text-xs px-5"
- aria-label={t('panel.downloads.inspector.tab.files')}
- title={t('panel.downloads.inspector.tab.files')}
- >
- <Files className="size-3.5" />
- </TabsTrigger>
- {showPieces && (
- <TabsTrigger
- value="pieces"
- className="text-xs px-5"
- aria-label={t('panel.downloads.inspector.tab.pieces')}
- title={t('panel.downloads.inspector.tab.pieces')}
- >
- <Grid3x3 className="size-3.5" />
- </TabsTrigger>
- )}
- {isBt && (
- <TabsTrigger
- value="peers"
- className="text-xs px-5"
- aria-label={t('panel.downloads.inspector.tab.peers')}
- title={t('panel.downloads.inspector.tab.peers')}
- >
- <UsersRound className="size-3.5" />
- </TabsTrigger>
- )}
- {isBt && (
- <TabsTrigger
- value="trackers"
- className="text-xs px-5"
- aria-label={t('panel.downloads.inspector.tab.trackers')}
- title={t('panel.downloads.inspector.tab.trackers')}
- >
- <RadioTower className="size-3.5" />
- </TabsTrigger>
- )}
- <TabsTrigger
- value="activity"
- className="text-xs px-5"
- aria-label={t('panel.downloads.inspector.tab.activity')}
- title={t('panel.downloads.inspector.tab.activity')}
- >
- <SquareActivity className="size-3.5" />
- </TabsTrigger>
- </TabsList>
- <TabsContent value="overview" className="min-h-0">
- <OverviewTab task={single} />
- </TabsContent>
- <TabsContent value="files" className="min-h-0">
- <FilesTab task={single} />
- </TabsContent>
- {showPieces && (
- <TabsContent value="pieces" className="min-h-0">
- <PiecesTab task={single} />
- </TabsContent>
- )}
- {isBt && (
- <TabsContent value="peers" className="min-h-0">
- <PeersTab task={single} />
- </TabsContent>
- )}
- {isBt && (
- <TabsContent value="trackers" className="min-h-0">
- <TrackersTab task={single} />
- </TabsContent>
- )}
- <TabsContent value="activity" className="min-h-0">
- <ActivityTab
- task={single}
- snapshotCache={activitySnapshotCache}
- />
- </TabsContent>
- </Tabs>
- </>
- ) : (
- <MultiSelectionSummary tasks={selected} />
- )}
- </div>
- </div>
- ) : null
-
- return container && drawer ? createPortal(drawer, container) : null
+ {isBt && (
+ <TabsContent value="peers" className="min-h-0">
+ <PeersTab task={single} />
+ </TabsContent>
+ )}
+ {isBt && (
+ <TabsContent value="trackers" className="min-h-0">
+ <TrackersTab task={single} />
+ </TabsContent>
+ )}
+ <TabsContent value="activity" className="min-h-0">
+ <ActivityTab
+ task={single}
+ snapshotCache={activitySnapshotCache}
+ />
+ </TabsContent>
+ </Tabs>
+ </>
+ ) : selected.length > 0 ? (
+ <MultiSelectionSummary tasks={selected} />
+ ) : (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ {t('panel.downloads.view.selectToInspect')}
+ </p>
+ )}
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar />
+ <ScrollBar orientation="horizontal" />
+ </ScrollArea>
+ </InspectorDrawer>
+ )
}
diff --git a/src/renderer/routes/downloads/task-list-panel.test.tsx b/src/renderer/routes/downloads/task-list-panel.test.tsx
index e6ac99d9..02264666 100644
--- a/src/renderer/routes/downloads/task-list-panel.test.tsx
+++ b/src/renderer/routes/downloads/task-list-panel.test.tsx
@@ -1,12 +1,281 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'
-import type { DownloadTask } from '@shared/types/task'
-import { render, screen } from '@testing-library/react'
-import { describe, expect, it } from 'vitest'
+import type { VirtualListProps } from '@renderer/components/desktop-kit/virtual-list/types'
+import { transport } from '@renderer/lib/transport'
+import { Events } from '@shared/protocol/events'
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { defaultTaskColumns } from './columns'
+import { useDownloadsSort } from './store'
import { TaskListPanel } from './task-list-panel'
+import { useDownloadsView } from './view-preferences'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { platform: 'darwin', on: vi.fn(), off: vi.fn() },
+}))
+
+// Render every row in jsdom, which has no viewport measurements. Keep the real
+// selection hook and TaskRow so reordering exercises their index callbacks.
+vi.mock('@renderer/components/desktop-kit/virtual-list/virtual-list', () => ({
+ VirtualList: ({
+ items,
+ getId,
+ renderRow,
+ renderHeader,
+ scrollRef,
+ }: VirtualListProps<DownloadTask>) => (
+ <div ref={scrollRef} data-testid="virtual-list-container">
+ {renderHeader?.()}
+ {items.map((item, index) => (
+ <div key={getId(item)}>{renderRow({ item, index, style: {} })}</div>
+ ))}
+ </div>
+ ),
+}))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ window.getSelection()?.removeAllRanges()
+ useDownloadsSort.setState({ sort: null })
+ useDownloadsView.setState({
+ inspectorVisible: false,
+ inspectorSnap: 'medium',
+ columns: defaultTaskColumns().map((column) => ({
+ ...column,
+ visible: true,
+ })),
+ })
+})
+
+function renderTasks(tasks: DownloadTask[]) {
+ const selection = createSelectionStore<DownloadTask>((task) => task.id)
+ const tree = (items: DownloadTask[]) => (
+ <TaskListPanel
+ tasks={items}
+ hasAnyTasks
+ filter="all"
+ search=""
+ onClearSearch={() => {}}
+ selection={selection}
+ />
+ )
+ const view = render(tree(tasks))
+ return {
+ ...view,
+ selection,
+ updateTasks: (next: DownloadTask[]) => view.rerender(tree(next)),
+ }
+}
+
+function visibleNames() {
+ return screen
+ .getAllByRole('row')
+ .filter((row) => row.hasAttribute('data-task-id'))
+ .map((row) => row.querySelector('.font-medium')?.textContent)
+}
describe('TaskListPanel', () => {
+ it('clears pointer selection with Escape without revealing keyboard focus', async () => {
+ const user = userEvent.setup()
+ const { selection } = renderTasks([
+ makeDownloadTask({ id: 'a', name: 'Alpha.bin' }),
+ makeDownloadTask({ id: 'b', name: 'Beta.bin' }),
+ ])
+ const grid = screen.getByRole('grid')
+ await user.click(screen.getByRole('row', { name: 'Alpha.bin' }))
+ const focusedRow = grid.getAttribute('aria-activedescendant')
+ expect(grid).toHaveFocus()
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+
+ await user.keyboard('{Escape}{Escape}')
+ expect(selection.getState().selectedIds.size).toBe(0)
+ expect(grid).toHaveFocus()
+ expect(grid).toHaveAttribute('aria-activedescendant', focusedRow)
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+
+ // Cancellation must not make a later programmatic return look like Tab.
+ act(() => screen.getByRole('button', { name: 'Name' }).focus())
+ act(() => grid.focus())
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+ })
+
+ it('shows focus for row navigation and preserves it on Escape until a pointer action', async () => {
+ const user = userEvent.setup()
+ renderTasks([
+ makeDownloadTask({ id: 'a', name: 'Alpha.bin' }),
+ makeDownloadTask({ id: 'b', name: 'Beta.bin' }),
+ ])
+ const grid = screen.getByRole('grid')
+ const alpha = screen.getByRole('row', { name: 'Alpha.bin' })
+ await user.click(alpha)
+ for (const event of [
+ { key: 'Shift' },
+ { key: 'a', metaKey: true },
+ { key: 'ArrowDown', altKey: true },
+ { key: 'a', isComposing: true },
+ { key: 'F8' },
+ ]) {
+ fireEvent.keyDown(grid, event)
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+ }
+ await user.keyboard('{ArrowDown}')
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'true')
+ await user.keyboard('{Escape}')
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'true')
+ await user.click(alpha)
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'false')
+ await user.keyboard('b')
+ expect(grid).toHaveAttribute('data-keyboard-focus', 'true')
+ expect(screen.getByRole('row', { name: 'Beta.bin' })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ })
+
+ it.each([TaskStatus.Paused, TaskStatus.Downloading, TaskStatus.Completed])(
+ 'opens %s task details only on a plain double click, preserving the chosen height',
+ async (status) => {
+ const user = userEvent.setup()
+ const { selection } = renderTasks([
+ makeDownloadTask({ id: 'a', name: 'A.bin', status }),
+ makeDownloadTask({ id: 'b', name: 'B.bin' }),
+ ])
+ const row = screen.getByRole('row', { name: 'A.bin' })
+ act(() => useDownloadsView.getState().setInspectorSnap('expanded'))
+ await user.click(row)
+ expect(selection.getState().selectedIds).toEqual(new Set(['a']))
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ await user.dblClick(row)
+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)
+ expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')
+ await user.dblClick(row)
+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)
+
+ act(() => useDownloadsView.getState().setInspectorVisible(false))
+ await user.click(screen.getByRole('row', { name: 'B.bin' }))
+ expect(selection.getState().selectedIds).toEqual(new Set(['b']))
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ }
+ )
+
+ it('does not open details from modified double clicks, column controls or whitespace', async () => {
+ const user = userEvent.setup()
+ renderTasks([
+ makeDownloadTask({ id: 'a', name: 'A.bin' }),
+ makeDownloadTask({ id: 'b', name: 'B.bin' }),
+ ])
+ const row = screen.getByRole('row', { name: 'A.bin' })
+ for (const modifier of ['Meta', 'Control', 'Shift', 'Alt']) {
+ await user.keyboard(`{${modifier}>}`)
+ await user.dblClick(row)
+ await user.keyboard(`{/${modifier}}`)
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ }
+ await user.dblClick(screen.getByRole('button', { name: 'Name' }))
+ await user.dblClick(screen.getByTestId('virtual-list-container'))
+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)
+ })
+
+ it('clears selection on plain viewport whitespace clicks while preserving header and modified clicks', () => {
+ const { selection } = renderTasks([
+ makeDownloadTask({ id: 'a', name: 'A.bin' }),
+ makeDownloadTask({ id: 'b', name: 'B.bin' }),
+ ])
+ const viewport = screen.getByTestId('virtual-list-container')
+ act(() => selection.getState().selectAll())
+ fireEvent.click(screen.getByRole('button', { name: 'Name' }))
+ fireEvent.click(screen.getAllByRole('columnheader')[0])
+ fireEvent.click(viewport, { metaKey: true })
+ fireEvent.click(viewport, { ctrlKey: true })
+ fireEvent.click(viewport, { shiftKey: true })
+ expect(selection.getState().selectedIds).toEqual(new Set(['a', 'b']))
+
+ fireEvent.click(viewport)
+ expect(selection.getState().selectedIds.size).toBe(0)
+ expect(selection.getState().committedSelectedIds.size).toBe(0)
+ })
+
+ it('selects the current list from the native menu and removes the listener on unmount', () => {
+ const tasks = [1, 2, 3].map((id) =>
+ makeDownloadTask({
+ id: String(id),
+ name: `File ${id}`,
+ })
+ )
+ const { selection, updateTasks, unmount } = renderTasks(tasks)
+ const listener = vi
+ .mocked(transport.on)
+ .mock.calls.find(([channel]) => channel === Events.TaskSelectAll)?.[1]
+ expect(listener).toBeTypeOf('function')
+ const textRange = document.createRange()
+ textRange.selectNodeContents(screen.getByRole('grid'))
+ window.getSelection()?.addRange(textRange)
+ expect(window.getSelection()?.toString()).not.toBe('')
+ act(() => listener?.())
+ expect(selection.getState().selectedIds).toEqual(new Set(['1', '2', '3']))
+ expect(screen.getByRole('grid')).toHaveFocus()
+ expect(window.getSelection()?.toString()).toBe('')
+
+ updateTasks(tasks.slice(1))
+ act(() => selection.getState().clearSelection())
+ act(() => listener?.())
+ expect(selection.getState().selectedIds).toEqual(new Set(['2', '3']))
+ expect(window.getSelection()?.toString()).toBe('')
+ unmount()
+ expect(transport.off).toHaveBeenCalledWith(Events.TaskSelectAll, listener)
+ })
+
+ it('keeps new tasks first by default and restores that order after manual sorting', () => {
+ const tasks = [
+ makeDownloadTask({ id: 'older', name: 'Older', createdAt: 1_000 }),
+ makeDownloadTask({ id: 'newer', name: 'Newer', createdAt: 2_000 }),
+ ]
+ const { updateTasks } = renderTasks(tasks)
+ expect(visibleNames()).toEqual(['Newer', 'Older'])
+ expect(
+ screen.getByRole('button', { name: 'Date created' })
+ ).toHaveAttribute('aria-pressed', 'false')
+ updateTasks([
+ ...tasks,
+ makeDownloadTask({ id: 'latest', name: 'Latest', createdAt: 3_000 }),
+ ])
+ expect(visibleNames()).toEqual(['Latest', 'Newer', 'Older'])
+ fireEvent.click(screen.getByRole('button', { name: 'Name' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Name: ascending' }))
+ expect(visibleNames()).toEqual(['Older', 'Newer', 'Latest'])
+ act(() => useDownloadsSort.getState().resetSort())
+ expect(visibleNames()).toEqual(['Latest', 'Newer', 'Older'])
+ expect(screen.getByRole('button', { name: 'Name' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ )
+ })
+ it('freezes row targets through a pointer gesture while refreshing task data', async () => {
+ const a = makeDownloadTask({ id: 'a', name: 'A.bin', sizeWhenDone: 20 })
+ const b = makeDownloadTask({ id: 'b', name: 'B.bin', sizeWhenDone: 10 })
+ useDownloadsSort.setState({ sort: { column: 'size', direction: 'desc' } })
+ const view = renderTasks([a, b])
+ const row = screen.getByRole('row', { name: 'A.bin' })
+ fireEvent(row, new MouseEvent('pointerdown', { bubbles: true, button: 0 }))
+ view.updateTasks([
+ { ...a, sizeWhenDone: 5 },
+ { ...b, sizeWhenDone: 30 },
+ ])
+ expect(visibleNames()).toEqual(['A.bin', 'B.bin'])
+ fireEvent.click(row)
+ expect([...view.selection.getState().committedSelectedIds]).toEqual(['a'])
+ fireEvent(window, new MouseEvent('pointerup', { bubbles: true, button: 0 }))
+ await waitFor(() => expect(visibleNames()).toEqual(['B.bin', 'A.bin']))
+ expect(screen.getByRole('row', { name: 'A.bin' })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ })
+
it('renders EmptyTasks when filtered task list is empty', () => {
const selection = createSelectionStore<DownloadTask>((t) => t.id)
render(
@@ -21,4 +290,85 @@ describe('TaskListPanel', () => {
)
expect(screen.getByText(/no downloads yet/i)).toBeInTheDocument()
})
+
+ it('reorders rows, preserves selection, and uses the new indices for Shift-click and keyboard selection', () => {
+ const tasks = [3, 1, 2].map((id) =>
+ makeDownloadTask({ id: String(id), name: `File ${id}` })
+ )
+ const { selection } = renderTasks(tasks)
+ fireEvent.click(screen.getByText('File 2'))
+ fireEvent.click(screen.getByRole('button', { name: 'Name' }))
+ expect(visibleNames()).toEqual(['File 1', 'File 2', 'File 3'])
+ expect([...selection.getState().selectedIds]).toEqual(['2'])
+ expect(selection.getState().focusedIndex).toBe(1)
+
+ // File 3 was index 0 before sorting. A memoized stale callback would select
+ // File 1 as well when extending this range.
+ fireEvent.click(screen.getByText('File 3'), { shiftKey: true })
+ expect([...selection.getState().selectedIds]).toEqual(['2', '3'])
+ fireEvent.keyDown(screen.getByRole('grid'), { key: 'ArrowUp' })
+ fireEvent.keyDown(screen.getByRole('grid'), { key: 'Escape' })
+ fireEvent.keyDown(screen.getByRole('grid'), { key: 'ArrowUp' })
+ expect([...selection.getState().selectedIds]).toEqual(['1'])
+
+ fireEvent.click(screen.getByRole('button', { name: 'Name: ascending' }))
+ expect(visibleNames()).toEqual(['File 3', 'File 2', 'File 1'])
+ fireEvent.click(screen.getByRole('button', { name: 'Name: descending' }))
+ expect(visibleNames()).toEqual(['File 1', 'File 2', 'File 3'])
+ })
+
+ it('reorders refreshed values and new tasks while updating visible cells', () => {
+ const tasks = [
+ makeDownloadTask({
+ id: 'a',
+ name: 'Small',
+ sizeWhenDone: 2_000,
+ connections: 1,
+ }),
+ makeDownloadTask({
+ id: 'b',
+ name: 'Large',
+ sizeWhenDone: 10_000,
+ connections: 2,
+ }),
+ ]
+ const { updateTasks } = renderTasks(tasks)
+ fireEvent.click(screen.getByRole('button', { name: 'Size' }))
+ expect(visibleNames()).toEqual(['Large', 'Small'])
+ updateTasks([
+ { ...tasks[0], name: 'Largest', sizeWhenDone: 30_000, connections: 99 },
+ tasks[1],
+ makeDownloadTask({ id: 'c', name: 'New', sizeWhenDone: 20_000 }),
+ ])
+ expect(visibleNames()).toEqual(['Largest', 'New', 'Large'])
+ expect(
+ screen
+ .getAllByRole('row')
+ .filter((row) => row.hasAttribute('data-task-id'))[0]
+ ).toHaveTextContent('30.00 KB')
+ expect(
+ screen
+ .getAllByRole('row')
+ .filter((row) => row.hasAttribute('data-task-id'))[0]
+ ).toHaveTextContent('99')
+ })
+
+ it('retains the sort across list remounts and select-all follows the visible list', () => {
+ const tasks = [2, 1].map((id) =>
+ makeDownloadTask({ id: String(id), name: `File ${id}` })
+ )
+ const first = renderTasks(tasks)
+ fireEvent.click(screen.getByRole('button', { name: 'Name' }))
+ first.unmount()
+ const { selection } = renderTasks(tasks)
+ expect(visibleNames()).toEqual(['File 1', 'File 2'])
+ fireEvent.keyDown(screen.getByRole('grid'), { key: 'a', metaKey: true })
+ expect([...selection.getState().selectedIds]).toEqual(['1', '2'])
+ expect(
+ screen
+ .getAllByRole('row')
+ .filter((row) => row.hasAttribute('data-task-id'))
+ .every((row) => row.getAttribute('aria-selected') === 'true')
+ ).toBe(true)
+ })
})
diff --git a/src/renderer/routes/downloads/task-list-panel.tsx b/src/renderer/routes/downloads/task-list-panel.tsx
index 120cfd60..1b32eadb 100644
--- a/src/renderer/routes/downloads/task-list-panel.tsx
+++ b/src/renderer/routes/downloads/task-list-panel.tsx
@@ -1,16 +1,26 @@
+import './downloads-list.css'
import { useSelectableList } from '@renderer/components/desktop-kit/hooks/use-selectable-list'
import { MarqueeOverlay } from '@renderer/components/desktop-kit/marquee-selection/marquee-overlay'
import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'
import { VirtualList } from '@renderer/components/desktop-kit/virtual-list/virtual-list'
+import { useIpcEvent } from '@renderer/hooks/use-ipc-event'
+import { transport } from '@renderer/lib/transport'
+import { Events } from '@shared/protocol/events'
import type { DownloadTask } from '@shared/types/task'
-import { useCallback } from 'react'
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { TASK_HEADER_HEIGHT, TASK_ROW_HEIGHT } from './columns'
import { EmptyTasks } from './empty-tasks'
import type { DownloadsTab } from './filter'
+import { sortTasks } from './sort'
+import { useDownloadsSort } from './store'
+import { TaskActionsMenu } from './task-actions-menu'
import { TaskColumnHeader } from './task-column-header'
import { TaskRow } from './task-row'
+import { useDownloadsView } from './view-preferences'
-const ROW_HEIGHT = 48
-const HEADER_HEIGHT = 36
+const TASK_LIST_CONTROL_SELECTOR =
+ 'button, input, textarea, select, a, [contenteditable="true"], [role="separator"], [role="columnheader"], [data-slot="scroll-area-scrollbar"]'
export interface TaskListPanelProps {
tasks: readonly DownloadTask[]
@@ -29,53 +39,281 @@ export function TaskListPanel({
search,
onClearSearch,
}: TaskListPanelProps) {
- const getId = useCallback((t: DownloadTask) => t.id, [])
- const {
- listRef,
- listProps,
- marqueeProps,
- getRowProps,
- headerCheckbox,
- onKeyDown,
- } = useSelectableList({
- items: tasks as DownloadTask[],
- getId,
- rowHeight: ROW_HEIGHT,
- headerHeight: HEADER_HEIGHT,
- store: selection,
+ const { t, i18n } = useTranslation()
+ const sort = useDownloadsSort((state) => state.sort)
+ const toggleSort = useDownloadsSort((state) => state.toggleSort)
+ const allColumns = useDownloadsView((state) => state.columns)
+ const columns = useMemo(
+ () => allColumns.filter((column) => column.visible),
+ [allColumns]
+ )
+ const sorted = useMemo(
+ () => sortTasks(tasks, sort, i18n.language),
+ [tasks, sort, i18n.language]
+ )
+ const [frozenIds, setFrozenIds] = useState<string[] | null>(null)
+ const displayed = useMemo(() => {
+ if (!frozenIds) return sorted as DownloadTask[]
+ const latest = new Map(tasks.map((task) => [task.id, task]))
+ return frozenIds.flatMap((id) => {
+ const task = latest.get(id)
+ return task ? [task] : []
+ })
+ }, [tasks, sorted, frozenIds])
+ const gridRef = useRef<HTMLDivElement>(null)
+ const [active, setActive] = useState(false)
+ const pointerFocus = useRef(false)
+ const [keyboardFocus, setKeyboardFocus] = useState(false)
+ const downId = useRef<string | null>(null)
+ const suppressClick = useRef(false)
+ const lastClickedId = useRef<string | null>(null)
+ const prefix = useId()
+ const getId = useCallback((task: DownloadTask) => task.id, [])
+ const getText = useCallback((task: DownloadTask) => task.name, [])
+ const macOS =
+ transport.platform === 'darwin' ||
+ (transport.platform === 'web' && /Mac|iPhone|iPad/.test(navigator.platform))
+ const { listRef, listProps, marqueeProps, getRowProps, onKeyDown } =
+ useSelectableList({
+ items: displayed,
+ getId,
+ getText,
+ rowHeight: TASK_ROW_HEIGHT,
+ headerHeight: TASK_HEADER_HEIGHT,
+ store: selection,
+ nativeSelection: true,
+ macOS,
+ })
+ const focusedId = selection((state) =>
+ state.focusedIndex === null
+ ? undefined
+ : state.items[state.focusedIndex]?.id
+ )
+ useIpcEvent(Events.TaskSelectAll, () => {
+ selection.getState().selectAll()
+ window.getSelection()?.removeAllRanges()
+ pointerFocus.current = true
+ setKeyboardFocus(false)
+ gridRef.current?.focus({ preventScroll: true })
})
+ useEffect(() => {
+ let releaseTimer: ReturnType<typeof setTimeout> | undefined
+ const release = () => {
+ // A click follows pointerup; keep its row mapping until that click commits.
+ releaseTimer = setTimeout(() => {
+ setFrozenIds(null)
+ downId.current = null
+ }, 0)
+ }
+ const blur = () => {
+ setActive(false)
+ setFrozenIds(null)
+ downId.current = null
+ }
+ const focus = () =>
+ setActive(Boolean(gridRef.current?.contains(document.activeElement)))
+ const keyboard = (event: KeyboardEvent) => {
+ // Only Tab changes how focus arrives from outside the list. Escape and
+ // command shortcuts must preserve the preceding pointer interaction.
+ if (event.key === 'Tab' && !event.isComposing)
+ pointerFocus.current = false
+ }
+ window.addEventListener('keydown', keyboard, true)
+ window.addEventListener('pointerup', release)
+ window.addEventListener('pointercancel', release)
+ window.addEventListener('blur', blur)
+ window.addEventListener('focus', focus)
+ return () => {
+ clearTimeout(releaseTimer)
+ window.removeEventListener('pointerup', release)
+ window.removeEventListener('pointercancel', release)
+ window.removeEventListener('blur', blur)
+ window.removeEventListener('focus', focus)
+ window.removeEventListener('keydown', keyboard, true)
+ }
+ }, [])
- if (tasks.length === 0) {
+ if (tasks.length === 0)
return (
- <EmptyTasks
- filter={filter}
- search={search}
- hasAnyTasks={hasAnyTasks}
- onClearSearch={onClearSearch}
- />
+ <TaskActionsMenu tasks={tasks} selection={selection}>
+ <div className="flex min-h-0 flex-1 flex-col outline-none">
+ <EmptyTasks
+ filter={filter}
+ search={search}
+ hasAnyTasks={hasAnyTasks}
+ onClearSearch={onClearSearch}
+ />
+ </div>
+ </TaskActionsMenu>
)
- }
return (
- <div
- role="listbox"
- tabIndex={0}
- onKeyDown={onKeyDown}
- className="relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-border"
- >
- <VirtualList
- ref={listRef}
- {...listProps}
- className="min-h-0 flex-1"
- renderHeader={() => (
- <TaskColumnHeader headerCheckbox={headerCheckbox} />
- )}
- renderRow={({ item, index }) => (
- <TaskRow task={item} rowProps={getRowProps(index)} />
- )}
- renderEmpty={() => null}
- />
- <MarqueeOverlay {...marqueeProps} />
- </div>
+ <TaskActionsMenu tasks={tasks} selection={selection}>
+ {/* biome-ignore lint/a11y/useSemanticElements: A native table cannot contain the virtualizer positioning wrappers. */}
+ <div
+ ref={gridRef}
+ role="grid"
+ aria-label={t('panel.downloads.title')}
+ aria-multiselectable="true"
+ aria-rowcount={displayed.length + 1}
+ aria-colcount={columns.length}
+ aria-activedescendant={
+ focusedId ? `${prefix}-${encodeURIComponent(focusedId)}` : undefined
+ }
+ data-downloads-grid
+ data-active={active}
+ data-keyboard-focus={keyboardFocus}
+ tabIndex={0}
+ onKeyDown={(event) => {
+ // Context menus can leave DOM focus on their trigger. Let Base UI
+ // consume Escape/navigation before the list changes selection.
+ if (event.currentTarget.hasAttribute('data-popup-open')) return
+ if (
+ event.target === event.currentTarget &&
+ !event.defaultPrevented &&
+ !event.nativeEvent.isComposing &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.altKey &&
+ (event.key === 'ArrowUp' ||
+ event.key === 'ArrowDown' ||
+ event.key.length === 1)
+ ) {
+ // Reveal focus for row navigation and typeahead, not cancellation.
+ pointerFocus.current = false
+ setKeyboardFocus(true)
+ }
+ onKeyDown(event)
+ }}
+ onFocusCapture={(event) => {
+ setActive(true)
+ if (event.target === event.currentTarget)
+ setKeyboardFocus(
+ !pointerFocus.current &&
+ event.currentTarget.matches(':focus-visible')
+ )
+ }}
+ onBlurCapture={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget))
+ setActive(false)
+ }}
+ onPointerDownCapture={(event) => {
+ pointerFocus.current = true
+ setKeyboardFocus(false)
+ if (event.button !== 0 || (macOS && event.ctrlKey)) return
+ if ((event.target as Element).closest(TASK_LIST_CONTROL_SELECTOR))
+ return
+ suppressClick.current = false
+ downId.current =
+ (event.target as Element).closest<HTMLElement>('[data-task-id]')
+ ?.dataset.taskId ?? null
+ setFrozenIds(displayed.map(getId))
+ event.currentTarget.focus({ preventScroll: true })
+ }}
+ onMouseDownCapture={(event) => {
+ const target = event.target as Element
+ if (
+ marqueeProps.containerRef.current?.contains(target) &&
+ !target.closest(TASK_LIST_CONTROL_SELECTOR)
+ ) {
+ // The grid owns keyboard focus through aria-activedescendant;
+ // cells and viewport whitespace must not take focus from it.
+ event.preventDefault()
+ }
+ }}
+ onClickCapture={(event) => {
+ lastClickedId.current = null
+ const target = event.target as Element
+ const id =
+ target.closest<HTMLElement>('[data-task-id]')?.dataset.taskId
+ if (
+ suppressClick.current ||
+ (downId.current && id && id !== downId.current)
+ ) {
+ event.preventDefault()
+ event.stopPropagation()
+ suppressClick.current = false
+ return
+ }
+ if (
+ id &&
+ event.button === 0 &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey &&
+ !target.closest(TASK_LIST_CONTROL_SELECTOR)
+ )
+ lastClickedId.current = id
+ if (
+ !id &&
+ event.button === 0 &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ marqueeProps.containerRef.current?.contains(target) &&
+ !target.closest(TASK_LIST_CONTROL_SELECTOR)
+ ) {
+ selection.getState().clearSelection()
+ }
+ }}
+ onDoubleClick={(event) => {
+ const target = event.target as Element
+ const id =
+ target.closest<HTMLElement>('[data-task-id]')?.dataset.taskId
+ if (
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey ||
+ target.closest(TASK_LIST_CONTROL_SELECTOR) ||
+ !id ||
+ id !== lastClickedId.current ||
+ !tasks.some((task) => task.id === id)
+ )
+ return
+ selection.getState().select(id)
+ useDownloadsView.getState().setInspectorVisible(true)
+ }}
+ className="downloads-task-grid relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border outline-none"
+ >
+ <VirtualList
+ ref={listRef}
+ {...listProps}
+ scrollbar="custom"
+ keepMountedIndex={
+ focusedId
+ ? displayed.findIndex((task) => task.id === focusedId)
+ : undefined
+ }
+ className="min-h-0 flex-1"
+ renderHeader={() => (
+ <TaskColumnHeader
+ columns={columns}
+ sort={sort}
+ onSort={toggleSort}
+ />
+ )}
+ renderRow={({ item, index }) => (
+ <TaskRow
+ id={`${prefix}-${encodeURIComponent(item.id)}`}
+ task={item}
+ columns={columns}
+ index={index}
+ rowProps={getRowProps(index)}
+ />
+ )}
+ renderEmpty={() => null}
+ />
+ <MarqueeOverlay
+ {...marqueeProps}
+ onSelectionEnd={() => {
+ suppressClick.current = true
+ marqueeProps.onSelectionEnd()
+ }}
+ />
+ </div>
+ </TaskActionsMenu>
)
}
diff --git a/src/renderer/routes/downloads/task-menu-shortcuts.test.ts b/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
new file mode 100644
index 00000000..689b14e4
--- /dev/null
+++ b/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest'
+import {
+ matchesTaskMenuShortcut,
+ taskMenuShortcuts,
+} from './task-menu-shortcuts'
+
+describe('task menu shortcuts', () => {
+ it('uses macOS symbols and the actual desktop new-task binding', () => {
+ const bindings = taskMenuShortcuts(true, true)
+ expect(bindings.newTask).toMatchObject({ label: '⌘N', aria: 'Meta+N' })
+ expect(bindings.inspector).toMatchObject({ label: '⌘I', aria: 'Meta+I' })
+ expect(bindings.copyUrl).toMatchObject({ label: '⌘C', aria: 'Meta+C' })
+ expect(bindings.remove).toMatchObject({
+ label: '⌘⌫',
+ aria: '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(true, false).newTask).toMatchObject({
+ label: '⌃N',
+ aria: 'Control+N',
+ })
+ })
+ it('matches exact modifiers and never treats bare macOS Backspace as Remove', () => {
+ const event = {
+ key: 'c',
+ metaKey: true,
+ ctrlKey: false,
+ shiftKey: false,
+ altKey: false,
+ }
+ expect(
+ matchesTaskMenuShortcut(event, taskMenuShortcuts(true, true).copyUrl)
+ ).toBe(true)
+ expect(
+ matchesTaskMenuShortcut(
+ { ...event, ctrlKey: true },
+ taskMenuShortcuts(true, true).copyUrl
+ )
+ ).toBe(false)
+ expect(
+ matchesTaskMenuShortcut(
+ { ...event, shiftKey: true },
+ taskMenuShortcuts(true, true).copyUrl
+ )
+ ).toBe(false)
+ expect(
+ matchesTaskMenuShortcut(
+ { ...event, key: 'Backspace', metaKey: false },
+ taskMenuShortcuts(true, true).remove
+ )
+ ).toBe(false)
+ })
+})
diff --git a/src/renderer/routes/downloads/task-menu-shortcuts.ts b/src/renderer/routes/downloads/task-menu-shortcuts.ts
new file mode 100644
index 00000000..bd4b4e57
--- /dev/null
+++ b/src/renderer/routes/downloads/task-menu-shortcuts.ts
@@ -0,0 +1,75 @@
+import { CommandIds } from '@shared/commands-catalog'
+import { DEFAULT_KEYBINDINGS } from '@shared/keybindings-catalog'
+
+export interface TaskMenuShortcut {
+ key: string
+ metaKey: boolean
+ ctrlKey: boolean
+ shiftKey: boolean
+ altKey: boolean
+ label: string
+ aria: string
+}
+
+function shortcut(accelerator: string, macOS: boolean): TaskMenuShortcut {
+ const parts = accelerator.split('+')
+ const key = parts.pop() ?? ''
+ const primary = parts.includes('CommandOrControl')
+ const metaKey = parts.includes('Command') || (primary && macOS)
+ const ctrlKey = parts.includes('Control') || (primary && !macOS)
+ const shiftKey = parts.includes('Shift')
+ const altKey = parts.includes('Alt')
+ const modifiers = [
+ ctrlKey && ['Ctrl', '⌃', 'Control'],
+ altKey && ['Alt', '⌥', 'Alt'],
+ shiftKey && ['Shift', '⇧', 'Shift'],
+ metaKey && ['Meta', '⌘', 'Meta'],
+ ].filter((part): part is string[] => Boolean(part))
+ return {
+ key,
+ metaKey,
+ ctrlKey,
+ shiftKey,
+ altKey,
+ label: [
+ ...modifiers.map((part) => part[macOS ? 1 : 0]),
+ macOS && key === 'Backspace' ? '⌫' : key,
+ ].join(macOS ? '' : '+'),
+ aria: [...modifiers.map((part) => part[2]), key].join('+'),
+ }
+}
+
+export function taskMenuShortcuts(macOS: boolean, desktop: boolean) {
+ const binding = DEFAULT_KEYBINDINGS.find(
+ (entry) => entry.commandId === CommandIds.TaskNew
+ )
+ const newTask =
+ binding &&
+ (desktop
+ ? binding.accelerator
+ : binding.webAccelerator === undefined
+ ? binding.accelerator
+ : binding.webAccelerator)
+ return {
+ newTask: newTask ? shortcut(newTask, macOS) : null,
+ inspector: shortcut('CommandOrControl+I', macOS),
+ copyUrl: shortcut('CommandOrControl+C', macOS),
+ remove: shortcut(macOS ? 'Command+Backspace' : 'Delete', macOS),
+ }
+}
+
+export function matchesTaskMenuShortcut(
+ event: Pick<
+ KeyboardEvent,
+ 'key' | 'metaKey' | 'ctrlKey' | 'shiftKey' | 'altKey'
+ >,
+ binding: TaskMenuShortcut
+): boolean {
+ return (
+ event.key.toLowerCase() === binding.key.toLowerCase() &&
+ event.metaKey === binding.metaKey &&
+ event.ctrlKey === binding.ctrlKey &&
+ event.shiftKey === binding.shiftKey &&
+ event.altKey === binding.altKey
+ )
+}
diff --git a/src/renderer/routes/downloads/task-row.test.tsx b/src/renderer/routes/downloads/task-row.test.tsx
index c88a75ac..b5a79b0e 100644
--- a/src/renderer/routes/downloads/task-row.test.tsx
+++ b/src/renderer/routes/downloads/task-row.test.tsx
@@ -20,6 +20,7 @@ import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
+import { formatTaskTimestamp } from './format-task-timestamp'
import { TaskRow } from './task-row'
function fake(overrides: Partial<DownloadTask> = {}): DownloadTask {
@@ -54,7 +55,7 @@ const rowProps = {
function getEtaCell(container: HTMLElement): Element {
const row = container.firstElementChild
- const etaCell = row?.children.item(row.children.length - 2)
+ const etaCell = row?.children.item(row.children.length - 4)
if (!etaCell) throw new Error('TaskRow ETA cell not found')
return etaCell
}
@@ -78,7 +79,7 @@ describe('TaskRow', () => {
it('renders task name and formatted size', () => {
render(<TaskRow task={fake()} rowProps={rowProps} />)
- expect(screen.getByText('ubuntu.iso')).toBeInTheDocument()
+ expect(screen.getByTitle('ubuntu.iso')).toBeInTheDocument()
expect(screen.getByText(/4\.70 GB/)).toBeInTheDocument()
})
@@ -117,13 +118,71 @@ describe('TaskRow', () => {
const { container } = render(
<TaskRow task={fake()} rowProps={{ ...rowProps, selected: true }} />
)
- expect(container.firstChild).toHaveClass('bg-accent/40')
+ expect(container.firstChild).toHaveAttribute('aria-selected', 'true')
})
it('uses the same minimum width as the scrollable column header', () => {
const { container } = render(<TaskRow task={fake()} rowProps={rowProps} />)
- expect(container.firstChild).toHaveStyle({ minWidth: '960px' })
+ expect(container.firstChild).toHaveStyle({ minWidth: '1310px' })
+ })
+
+ it('renders localized creation and completion timestamps and refreshes on completion', () => {
+ const createdAt = Date.parse('2020-09-13T01:02:08Z')
+ const finishedAt = Date.parse('2020-09-13T03:04:19Z')
+ const task = fake({ createdAt })
+ const { container, rerender } = render(
+ <TaskRow task={task} rowProps={rowProps} />
+ )
+ const row = container.firstElementChild!
+ expect(row.children.item(row.children.length - 2)).toHaveTextContent(
+ formatTaskTimestamp(createdAt, 'en-US', Date.now())!.compact
+ )
+ expect(
+ row.children.item(row.children.length - 2)?.querySelector('time')
+ ).toHaveAttribute('datetime', '2020-09-13T01:02:08.000Z')
+ expect(row.lastElementChild).toHaveTextContent('—')
+ rerender(
+ <TaskRow
+ task={{ ...task, status: TaskStatus.Completed, finishedAt }}
+ rowProps={rowProps}
+ />
+ )
+ expect(row.lastElementChild).toHaveTextContent(
+ formatTaskTimestamp(finishedAt, 'en-US', Date.now())!.compact
+ )
+ expect(row.lastElementChild?.querySelector('time')).toHaveAttribute(
+ 'datetime',
+ '2020-09-13T03:04:19.000Z'
+ )
+ })
+
+ it('does not present failure timestamps as completion or render invalid dates', () => {
+ const { container, rerender } = render(
+ <TaskRow
+ task={fake({
+ status: TaskStatus.Error,
+ createdAt: 0,
+ finishedAt: Date.now(),
+ })}
+ rowProps={rowProps}
+ />
+ )
+ const row = container.firstElementChild!
+ expect(row.children.item(row.children.length - 2)).toHaveTextContent('—')
+ expect(row.lastElementChild).toHaveTextContent('—')
+ rerender(
+ <TaskRow
+ task={fake({
+ status: TaskStatus.Completed,
+ createdAt: Number.NaN,
+ finishedAt: 1e20,
+ })}
+ rowProps={rowProps}
+ />
+ )
+ expect(row.children.item(row.children.length - 2)).toHaveTextContent('—')
+ expect(row.lastElementChild).toHaveTextContent('—')
})
it('renders gracefully for magnet metadata pending (Plan B)', () => {
@@ -161,7 +220,10 @@ describe('TaskRow', () => {
rowProps={rowProps}
/>
)
- expect(screen.getByText('Disk is full')).toBeInTheDocument()
+ expect(container.firstChild).toHaveAttribute(
+ 'aria-description',
+ 'Disk is full'
+ )
expect(container.firstChild).toHaveAttribute(
'title',
'ENOSPC: no space left on device'
diff --git a/src/renderer/routes/downloads/task-row.tsx b/src/renderer/routes/downloads/task-row.tsx
index a28dcbaa..74d12cec 100644
--- a/src/renderer/routes/downloads/task-row.tsx
+++ b/src/renderer/routes/downloads/task-row.tsx
@@ -1,18 +1,33 @@
-import { Checkbox } from '@renderer/components/ui/checkbox'
import { useByteFormat } from '@renderer/hooks/use-byte-format'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
import { formatDurationHMS, formatProgressPercent } from '@renderer/lib/format'
import { getProgressBarTone } from '@renderer/lib/task-status-ui'
import { cn } from '@renderer/lib/utils'
import type { DownloadTask } from '@shared/types/task'
-import { TaskStatus, TaskType } from '@shared/types/task'
-import { memo } from 'react'
+import { TaskStatus } from '@shared/types/task'
+import { memo, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
+import {
+ defaultTaskColumns,
+ TASK_COLUMNS,
+ type TaskColumn,
+ taskGridStyle,
+} from './columns'
+import type { TaskSortColumn } from './sort'
import { StatusPill } from './status-pill'
-import { TASK_GRID_MIN_WIDTH, TASK_GRID_TEMPLATE } from './task-column-header'
+import {
+ getTaskConnections,
+ getTaskEta,
+ getTaskSpeed,
+ getTaskTimestamp,
+} from './task-column-values'
+import { TaskTimestamp } from './task-timestamp'
export interface TaskRowProps {
task: DownloadTask
+ columns?: TaskColumn[]
+ index?: number
+ id?: string
rowProps: {
selected: boolean
focused: boolean
@@ -21,116 +36,114 @@ export interface TaskRowProps {
}
}
-function TaskRowBase({ task, rowProps }: TaskRowProps) {
+function TaskRowBase({
+ task,
+ rowProps,
+ columns = defaultTaskColumns(),
+ index = 0,
+ id,
+}: TaskRowProps) {
const { formatBytes, formatSpeed } = useByteFormat()
-
const { t, i18n } = useTranslation()
const pct = formatProgressPercent(task.progress)
- const showDash = (value: number) =>
- value <= 0 ||
- task.status === TaskStatus.Completed ||
- task.status === TaskStatus.Finalizing
- const hideEta =
- task.status === TaskStatus.Paused ||
- task.status === TaskStatus.Completed ||
- task.status === TaskStatus.Finalizing
- const connections =
- task.type === TaskType.Bt || task.type === TaskType.Magnet
- ? `${task.bt?.peers ?? 0}`
- : task.connections.toString()
-
- const isError = task.status === TaskStatus.Error
- const failure = isError
- ? resolveFailureReason(
- {
- errorCode: task.errorCode,
- errorMessage: task.errorMessage,
- errorDetailKey: task.errorDetailKey,
- errorDetailParams: task.errorDetailParams,
- },
- { t, exists: (key) => i18n.exists(key) }
- )
- : null
+ const downloadSpeed = getTaskSpeed(task, 'downloadSpeed')
+ const uploadSpeed = getTaskSpeed(task, 'uploadSpeed')
+ const eta = getTaskEta(task)
+ const failure =
+ task.status === TaskStatus.Error
+ ? resolveFailureReason(
+ {
+ errorCode: task.errorCode,
+ errorMessage: task.errorMessage,
+ errorDetailKey: task.errorDetailKey,
+ errorDetailParams: task.errorDetailParams,
+ },
+ { t, exists: (key) => i18n.exists(key) }
+ )
+ : null
+ const extensionIndex = task.name.lastIndexOf('.')
+ const extension =
+ extensionIndex > 0 && task.name.length - extensionIndex <= 16
+ ? task.name.slice(extensionIndex)
+ : ''
+ const cells: Record<TaskSortColumn, ReactNode> = {
+ name: (
+ <span
+ className="flex min-w-0 font-medium"
+ title={
+ failure
+ ? `${task.name}\n${failure.reason}\n${failure.technicalDetail ?? ''}`
+ : task.name
+ }
+ >
+ <span className="truncate">
+ {extension ? task.name.slice(0, -extension.length) : task.name}
+ </span>
+ {extension && <span className="shrink-0">{extension}</span>}
+ </span>
+ ),
+ size: formatBytes(task.sizeWhenDone),
+ progress: (
+ <span className="flex items-center gap-2">
+ <span className="h-1 min-w-0 flex-1 overflow-hidden rounded-full bg-muted">
+ <span
+ className={cn('block h-full', getProgressBarTone(task.status))}
+ style={{ width: `${pct}%` }}
+ />
+ </span>
+ <span className="w-10 shrink-0 text-right">{pct}%</span>
+ </span>
+ ),
+ status: <StatusPill status={task.status} compact />,
+ down: downloadSpeed === null ? '—' : formatSpeed(downloadSpeed),
+ up: uploadSpeed === null ? '—' : formatSpeed(uploadSpeed),
+ eta: eta === null ? '—' : formatDurationHMS(eta),
+ connections: getTaskConnections(task),
+ createdAt: (
+ <TaskTimestamp timestamp={getTaskTimestamp(task, 'createdAt')} />
+ ),
+ finishedAt: (
+ <TaskTimestamp
+ timestamp={getTaskTimestamp(task, 'finishedAt')}
+ pending={task.status !== TaskStatus.Completed}
+ />
+ ),
+ }
return (
+ // biome-ignore lint/a11y/useSemanticElements: This row is positioned by the virtual ARIA grid.
<div
- role="option"
+ role="row"
+ id={id}
+ data-task-id={task.id}
+ data-focused={rowProps.focused || undefined}
+ data-alternate={index % 2 === 1 || undefined}
+ aria-label={task.name}
+ aria-rowindex={index + 2}
aria-selected={rowProps.selected}
+ aria-description={failure?.reason}
tabIndex={-1}
onClick={rowProps.onClick}
onKeyDown={() => {}}
title={failure?.technicalDetail ?? undefined}
- className={cn(
- 'grid h-12 cursor-default select-none items-center gap-3 border-b border-border/50 px-3 text-[12.5px]',
- rowProps.selected && 'bg-accent/40',
- !rowProps.selected && rowProps.focused && 'bg-accent/10'
- )}
- style={{
- gridTemplateColumns: TASK_GRID_TEMPLATE,
- minWidth: TASK_GRID_MIN_WIDTH,
- }}
+ className="downloads-task-row grid h-9 cursor-default select-none items-center px-3 text-xs"
+ style={taskGridStyle(columns)}
>
- <Checkbox
- checked={rowProps.selected}
- onCheckedChange={() => rowProps.onCheckboxChange()}
- onClick={(e) => e.stopPropagation()}
- />
- <div className="flex min-w-0 flex-col gap-0.5">
- <span className="truncate font-medium text-foreground">
- {task.name}
- </span>
- <span className="truncate text-[11px] text-muted-foreground">
- {failure
- ? failure.reason
- : `${task.type.toUpperCase()} · ${task.fileCount} files`}
- </span>
- </div>
- <span className="tabular-nums">{formatBytes(task.sizeWhenDone)}</span>
- <div className="flex flex-col gap-1">
- <div className="h-1 overflow-hidden rounded-full bg-muted">
- <div
- className={cn('h-full', getProgressBarTone(task.status))}
- style={{ width: `${pct}%` }}
- />
- </div>
- <div className="flex justify-between text-[10.5px] text-muted-foreground">
- <span>{pct}%</span>
- <span className="tabular-nums">
- {formatBytes(task.downloadedBytes)}
- </span>
+ {columns.map((column, columnIndex) => (
+ // biome-ignore lint/a11y/useSemanticElements: Grid cells belong to virtual rows rather than a native table.
+ <div
+ key={column.id}
+ tabIndex={-1}
+ role="gridcell"
+ aria-colindex={columnIndex + 1}
+ className={cn(
+ 'min-w-0 overflow-hidden px-2 tabular-nums',
+ TASK_COLUMNS[column.id].numeric && 'text-right'
+ )}
+ >
+ {cells[column.id]}
</div>
- </div>
- <StatusPill status={task.status} />
- <span className="tabular-nums">
- {showDash(task.downloadSpeed) ? '—' : formatSpeed(task.downloadSpeed)}
- </span>
- <span className="tabular-nums">
- {showDash(task.uploadSpeed) ? '—' : formatSpeed(task.uploadSpeed)}
- </span>
- <span className="tabular-nums">
- {hideEta ? '—' : formatDurationHMS(task.etaSeconds)}
- </span>
- <span className="tabular-nums text-muted-foreground">{connections}</span>
+ ))}
</div>
)
}
-
-export const TaskRow = memo(TaskRowBase, (prev, next) => {
- const a = prev.task
- const b = next.task
- return (
- prev.rowProps.selected === next.rowProps.selected &&
- prev.rowProps.focused === next.rowProps.focused &&
- a.id === b.id &&
- a.status === b.status &&
- a.progress === b.progress &&
- a.downloadSpeed === b.downloadSpeed &&
- a.uploadSpeed === b.uploadSpeed &&
- a.etaSeconds === b.etaSeconds &&
- a.bt?.peers === b.bt?.peers &&
- a.errorCode === b.errorCode &&
- a.errorMessage === b.errorMessage &&
- a.errorDetailKey === b.errorDetailKey &&
- a.errorDetailParams === b.errorDetailParams &&
- a.diagnosisRevision === b.diagnosisRevision
- )
-})
+export const TaskRow = memo(TaskRowBase)
diff --git a/src/renderer/routes/downloads/task-timestamp.test.tsx b/src/renderer/routes/downloads/task-timestamp.test.tsx
new file mode 100644
index 00000000..37a7e3ee
--- /dev/null
+++ b/src/renderer/routes/downloads/task-timestamp.test.tsx
@@ -0,0 +1,52 @@
+import '@testing-library/jest-dom/vitest'
+import { __resetMinuteClockForTests } from '@renderer/hooks/use-minute-clock'
+import { i18n } from '@renderer/lib/i18n'
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { TaskTimestamp } from './task-timestamp'
+
+describe('TaskTimestamp', () => {
+ beforeEach(async () => {
+ await i18n.changeLanguage('zh-CN')
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date(2026, 8, 15, 23, 59, 30))
+ __resetMinuteClockForTests()
+ })
+ afterEach(async () => {
+ cleanup()
+ __resetMinuteClockForTests()
+ vi.useRealTimers()
+ await i18n.changeLanguage('en-US')
+ })
+
+ it('updates today at local midnight without changing the task or adding tab stops', () => {
+ const timestamp = new Date(2026, 8, 15, 14, 32, 8).getTime()
+ const { container } = render(<TaskTimestamp timestamp={timestamp} />)
+ expect(screen.getByText('今天 14:32:08')).toBeInTheDocument()
+ act(() => vi.advanceTimersByTime(30_000))
+ const time = screen.getByText('昨天 14:32:08')
+ expect(time).toHaveAttribute('datetime', new Date(timestamp).toISOString())
+ expect(time).toHaveAttribute('tabindex', '-1')
+ expect(time).toHaveAccessibleName(/2026年9月15日.*14:32:08/)
+ expect(container.querySelector('button')).toBeNull()
+ })
+
+ it('keeps a full date in the inspector and reacts to language changes', async () => {
+ render(
+ <TaskTimestamp
+ timestamp={new Date(2026, 8, 15, 14, 32, 8).getTime()}
+ variant="inspector"
+ />
+ )
+ expect(screen.getByText('2026年9月15日 14:32:08')).toBeInTheDocument()
+ await act(() => i18n.changeLanguage('en-US'))
+ expect(screen.getByText(/Sep 15, 2026, 2:32:08 PM/)).toBeInTheDocument()
+ })
+
+ it('distinguishes unrecorded history from a task that has not completed', () => {
+ const { rerender } = render(<TaskTimestamp timestamp={null} />)
+ expect(screen.getByText('—')).toHaveAccessibleName('未记录')
+ rerender(<TaskTimestamp timestamp={null} pending />)
+ expect(screen.getByText('—')).toHaveAccessibleName('尚未完成')
+ })
+})
diff --git a/src/renderer/routes/downloads/task-timestamp.tsx b/src/renderer/routes/downloads/task-timestamp.tsx
new file mode 100644
index 00000000..406bdb44
--- /dev/null
+++ b/src/renderer/routes/downloads/task-timestamp.tsx
@@ -0,0 +1,57 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@renderer/components/ui/tooltip'
+import { useMinuteClock } from '@renderer/hooks/use-minute-clock'
+import { cn } from '@renderer/lib/utils'
+import { useTranslation } from 'react-i18next'
+import { formatTaskTimestamp } from './format-task-timestamp'
+
+export function TaskTimestamp({
+ timestamp,
+ variant = 'list',
+ pending = false,
+}: {
+ timestamp: number | null
+ variant?: 'list' | 'inspector'
+ pending?: boolean
+}) {
+ const { t, i18n } = useTranslation()
+ const now = useMinuteClock()
+ const formatted = formatTaskTimestamp(timestamp, i18n.language, now)
+ const detail =
+ formatted?.detailed ??
+ t(
+ pending
+ ? 'panel.downloads.timestamp.notCompleted'
+ : 'panel.downloads.timestamp.notRecorded'
+ )
+ const label = !formatted
+ ? '—'
+ : variant === 'inspector'
+ ? formatted.full
+ : formatted.relative
+ ? t('panel.downloads.timestamp.relativeDateTime', formatted.relative)
+ : formatted.compact
+ const className = cn(
+ 'tabular-nums',
+ variant === 'list' ? 'block truncate' : 'ml-auto text-end'
+ )
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ delay={400}
+ tabIndex={-1}
+ aria-label={detail}
+ className={className}
+ render={formatted ? <time dateTime={formatted.iso} /> : <span />}
+ >
+ {label}
+ </TooltipTrigger>
+ <TooltipContent side="bottom" align="start" sideOffset={8}>
+ {detail}
+ </TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/src/renderer/routes/downloads/transfer-speed-badge.tsx b/src/renderer/routes/downloads/transfer-speed-badge.tsx
new file mode 100644
index 00000000..a6e1a0fd
--- /dev/null
+++ b/src/renderer/routes/downloads/transfer-speed-badge.tsx
@@ -0,0 +1,73 @@
+import { Badge } from '@renderer/components/ui/badge'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@renderer/components/ui/tooltip'
+import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import { useGlobalStats } from '@renderer/hooks/use-global-stats'
+import { cn } from '@renderer/lib/utils'
+import { ArrowDown, ArrowUp } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+export function TransferSpeedBadge() {
+ const { formatSpeed } = useByteFormat()
+ const { t } = useTranslation()
+ const { stats } = useGlobalStats()
+ const rates = [
+ {
+ key: 'upSpeed',
+ icon: ArrowUp,
+ speed: stats?.totalUploadSpeed,
+ },
+ {
+ key: 'downSpeed',
+ icon: ArrowDown,
+ speed: stats?.totalDownloadSpeed,
+ },
+ ] as const
+
+ return (
+ <Badge
+ render={<dl />}
+ variant="secondary"
+ data-slot="downloads-transfer-rates"
+ className="gap-0 px-0"
+ >
+ {rates.map(({ key, icon: Icon, speed }, index) => {
+ const label = t(`panel.downloads.stats.${key}`)
+ return (
+ <Tooltip key={key}>
+ <TooltipTrigger
+ delay={400}
+ render={
+ <div
+ className={cn(
+ 'relative flex items-center gap-1.5 px-2',
+ index > 0 &&
+ 'before:absolute before:inset-y-0.5 before:left-0 before:w-px before:bg-border/70'
+ )}
+ />
+ }
+ >
+ <dt className="flex items-center">
+ <Icon
+ aria-hidden="true"
+ className="size-3 text-muted-foreground"
+ strokeWidth={1.75}
+ />
+ <span className="sr-only">{label}</span>
+ </dt>
+ <dd dir="ltr" className="whitespace-nowrap tabular-nums">
+ {speed == null ? '—' : formatSpeed(speed)}
+ </dd>
+ </TooltipTrigger>
+ <TooltipContent side="top" align="start" sideOffset={8}>
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ )
+ })}
+ </Badge>
+ )
+}
diff --git a/src/renderer/routes/downloads/view-preferences.test.ts b/src/renderer/routes/downloads/view-preferences.test.ts
new file mode 100644
index 00000000..b1e72a99
--- /dev/null
+++ b/src/renderer/routes/downloads/view-preferences.test.ts
@@ -0,0 +1,66 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createDownloadsViewStore } from './view-preferences'
+
+beforeEach(() => localStorage.clear())
+afterEach(() => {
+ vi.restoreAllMocks()
+ localStorage.clear()
+})
+
+describe('Downloads view preferences', () => {
+ it('shares the inspector tab during the session without persisting it', () => {
+ const store = createDownloadsViewStore()
+ store.getState().setInspectorTab('files')
+ store.getState().setInspectorVisible(true)
+ expect(store.getState().inspectorTab).toBe('files')
+ expect(createDownloadsViewStore().getState().inspectorTab).toBe('overview')
+ })
+ it('restores columns, order and inspector independently of selection', () => {
+ const store = createDownloadsViewStore()
+ expect(store.getState().inspectorVisible).toBe(false)
+ store.getState().setColumnWidth('name', 320)
+ store.getState().setColumnVisible('eta', true)
+ store.getState().moveColumn('eta', 'name')
+ store.getState().setInspectorVisible(true)
+ store.getState().setInspectorSnap('compact')
+ const restored = createDownloadsViewStore().getState()
+ expect(restored.columns[0].id).toBe('eta')
+ expect(restored.columns[1].width).toBe(320)
+ expect(restored.inspectorVisible).toBe(true)
+ expect(restored.inspectorSnap).toBe('compact')
+ store.getState().resetColumns()
+ expect(store.getState().inspectorVisible).toBe(true)
+ })
+
+ it('clamps resizing and keeps the name visible without persisting every drag frame', () => {
+ const store = createDownloadsViewStore()
+ const write = vi.spyOn(Storage.prototype, 'setItem')
+ store.getState().setColumnWidth('name', 20000, false)
+ expect(store.getState().columns[0].width).toBe(900)
+ expect(write).not.toHaveBeenCalled()
+ store.getState().persist()
+ expect(write).toHaveBeenCalledOnce()
+ store.getState().setColumnVisible('name', false)
+ expect(store.getState().columns[0].visible).toBe(true)
+ })
+
+ it('falls back on corrupt or duplicated columns and blocked storage', () => {
+ localStorage.setItem('motrix.downloads.view.v1', '{invalid')
+ expect(createDownloadsViewStore().getState().columns[0].id).toBe('name')
+ const store = createDownloadsViewStore()
+ store.getState().persist()
+ const data = JSON.parse(localStorage.getItem('motrix.downloads.view.v1')!)
+ data.columns[1] = data.columns[0]
+ localStorage.setItem('motrix.downloads.view.v1', JSON.stringify(data))
+ expect(createDownloadsViewStore().getState().columns[1].id).toBe('size')
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('blocked')
+ })
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('blocked')
+ })
+ const blocked = createDownloadsViewStore()
+ expect(() => blocked.getState().setInspectorVisible(true)).not.toThrow()
+ expect(blocked.getState().inspectorVisible).toBe(true)
+ })
+})
diff --git a/src/renderer/routes/downloads/view-preferences.ts b/src/renderer/routes/downloads/view-preferences.ts
new file mode 100644
index 00000000..d4646d5b
--- /dev/null
+++ b/src/renderer/routes/downloads/view-preferences.ts
@@ -0,0 +1,149 @@
+import { z } from 'zod'
+import { create } from 'zustand'
+import {
+ clampColumnWidth,
+ defaultTaskColumns,
+ type TaskColumn,
+} from './columns'
+import { TASK_SORT_COLUMNS, type TaskSortColumn } from './sort'
+
+const STORAGE_KEY = 'motrix.downloads.view.v1'
+const ViewPreferencesSchema = z.object({
+ version: z.literal(1),
+ columns: z
+ .array(
+ z.object({
+ id: z.enum(TASK_SORT_COLUMNS),
+ width: z.number().finite().min(40).max(1200),
+ visible: z.boolean(),
+ })
+ )
+ .length(TASK_SORT_COLUMNS.length)
+ .refine(
+ (columns) =>
+ new Set(columns.map((column) => column.id)).size ===
+ TASK_SORT_COLUMNS.length
+ ),
+ inspectorVisible: z.boolean(),
+ inspectorSnap: z.enum(['compact', 'medium', 'expanded']),
+})
+
+function defaults() {
+ return {
+ version: 1 as const,
+ columns: defaultTaskColumns(),
+ inspectorVisible: false,
+ inspectorSnap: 'medium' as const,
+ }
+}
+
+function readPreferences() {
+ try {
+ const saved = ViewPreferencesSchema.parse(
+ JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null')
+ )
+ return {
+ ...saved,
+ columns: saved.columns.map((column) => ({
+ ...column,
+ width: clampColumnWidth(column.id, column.width),
+ visible: column.id === 'name' || column.visible,
+ })),
+ }
+ } catch {
+ return defaults()
+ }
+}
+
+export type InspectorTab =
+ | 'overview'
+ | 'files'
+ | 'pieces'
+ | 'peers'
+ | 'trackers'
+ | 'activity'
+
+interface DownloadsViewState {
+ inspectorTab: InspectorTab
+ setInspectorTab: (tab: InspectorTab) => void
+ columns: TaskColumn[]
+ inspectorVisible: boolean
+ inspectorSnap: 'compact' | 'medium' | 'expanded'
+ setColumnVisible: (id: TaskSortColumn, visible: boolean) => void
+ setColumnWidth: (id: TaskSortColumn, width: number, persist?: boolean) => void
+ moveColumn: (id: TaskSortColumn, before: TaskSortColumn) => void
+ resetColumns: () => void
+ setInspectorVisible: (visible: boolean) => void
+ setInspectorSnap: (snap: 'compact' | 'medium' | 'expanded') => void
+ persist: () => void
+}
+
+export function createDownloadsViewStore() {
+ return create<DownloadsViewState>((set, get) => ({
+ ...readPreferences(),
+ inspectorTab: 'overview',
+ setInspectorTab: (inspectorTab) => set({ inspectorTab }),
+ persist: () => {
+ const { columns, inspectorVisible, inspectorSnap } = get()
+ try {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({
+ version: 1,
+ columns,
+ inspectorVisible,
+ inspectorSnap,
+ })
+ )
+ } catch {
+ // The view remains usable when storage is blocked or full.
+ }
+ },
+ setColumnVisible: (id, visible) => {
+ set({
+ columns: get().columns.map((column) =>
+ column.id === id
+ ? { ...column, visible: id === 'name' || visible }
+ : column
+ ),
+ })
+ get().persist()
+ },
+ setColumnWidth: (id, width, persist = true) => {
+ set({
+ columns: get().columns.map((column) =>
+ column.id === id
+ ? { ...column, width: clampColumnWidth(id, width) }
+ : column
+ ),
+ })
+ if (persist) get().persist()
+ },
+ moveColumn: (id, before) => {
+ if (id === before) return
+ const columns = [...get().columns]
+ const source = columns.findIndex((column) => column.id === id)
+ if (source < 0) return
+ const [column] = columns.splice(source, 1)
+ const target = columns.findIndex((column) => column.id === before)
+ if (target < 0) return
+ columns.splice(target, 0, column)
+ set({ columns })
+ get().persist()
+ },
+ resetColumns: () => {
+ set({ columns: defaultTaskColumns() })
+ get().persist()
+ },
+ setInspectorVisible: (inspectorVisible) => {
+ set({ inspectorVisible })
+ get().persist()
+ },
+ setInspectorSnap: (inspectorSnap) => {
+ set({ inspectorSnap })
+ get().persist()
+ },
+ }))
+}
+
+export const useDownloadsView = createDownloadsViewStore()
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
index f8502c9b..f64e38e3 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
@@ -68,6 +68,37 @@ beforeEach(async () => {
})
describe('<AppearanceDialog>', () => {
+ it.each(['darwin', 'win32', 'linux', 'web'])(
+ 'uses the existing glass switch and saves only that preference on %s',
+ async (platform) => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: platform,
+ })
+ render(
+ <AppearanceDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.appearance.title"
+ descKey="settings.cards.appearance.desc"
+ />
+ )
+ const toggle = await screen.findByRole('switch', {
+ name: 'Enable Liquid Glass effect',
+ })
+ const user = userEvent.setup()
+ await user.click(toggle)
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.UpdateSettings,
+ expect.anything()
+ )
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: { liquidGlassEffect: true },
+ })
+ }
+ )
+
it('renders hydrated select labels instead of raw values', async () => {
render(
<AppearanceDialog
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.tsx b/src/renderer/routes/settings/cards/appearance-dialog.tsx
index 3d5edf02..3c1865d6 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.tsx
@@ -369,30 +369,30 @@ export function AppearanceDialog({
/>
)}
- {isMac && (
- <FormField
- control={form.control}
- name="liquidGlassEffect"
- render={({ field }) => (
- <SettingsFormRow>
- <div className="space-y-1">
- <FormLabel>
- {t('settings.appearance.liquidGlassEffect')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.appearance.liquidGlassEffectDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </SettingsFormRow>
- )}
- />
- )}
+ <FormField
+ control={form.control}
+ name="liquidGlassEffect"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.appearance.liquidGlassEffect')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.appearance.liquidGlassEffectDesc')}
+ {isMac &&
+ ` ${t('settings.appearance.liquidGlassEffectMacDesc')}`}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
{showRunMode && (
<FormField
diff --git a/src/renderer/routes/settings/cards/downloads-dialog.tsx b/src/renderer/routes/settings/cards/downloads-dialog.tsx
index ac3c40bd..cc082452 100644
--- a/src/renderer/routes/settings/cards/downloads-dialog.tsx
+++ b/src/renderer/routes/settings/cards/downloads-dialog.tsx
@@ -16,7 +16,7 @@ import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
-import { DEFAULT_SPEED_LIMIT_SETTINGS } from '@shared/schemas/speed-limit'
+import { createDefaultSpeedLimitSettings } from '@shared/schemas/speed-limit'
import type { AppSettings } from '@shared/types/settings'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
@@ -46,7 +46,10 @@ export function DownloadsDialog({
const { t } = useTranslation()
const { unitSystem } = useByteFormat()
const form = useForm<DownloadsFields>({
- defaultValues: DOWNLOADS_DEFAULTS,
+ defaultValues: {
+ ...DOWNLOADS_DEFAULTS,
+ speedLimit: createDefaultSpeedLimitSettings(unitSystem),
+ },
resolver: zodResolver(downloadsFormSchema, {
error: downloadsValidationError(t, unitSystem === 'binary' ? 1024 : 1000),
}),
@@ -66,8 +69,11 @@ export function DownloadsDialog({
? { ...ENGINE_DEFAULTS, ...all.engine }
: ENGINE_DEFAULTS,
speedLimit: all?.speedLimit
- ? { ...DEFAULT_SPEED_LIMIT_SETTINGS, ...all.speedLimit }
- : DEFAULT_SPEED_LIMIT_SETTINGS,
+ ? {
+ ...createDefaultSpeedLimitSettings(unitSystem),
+ ...all.speedLimit,
+ }
+ : createDefaultSpeedLimitSettings(unitSystem),
})
})
.catch(() => {})
diff --git a/src/renderer/routes/settings/cards/speed-limit-section.tsx b/src/renderer/routes/settings/cards/speed-limit-section.tsx
index 92e5e79f..99b35f73 100644
--- a/src/renderer/routes/settings/cards/speed-limit-section.tsx
+++ b/src/renderer/routes/settings/cards/speed-limit-section.tsx
@@ -231,7 +231,7 @@ export function SpeedLimitSection({
}: {
form: UseFormReturn<DownloadsFields>
}) {
- const { formatSpeed, unitSystem } = useByteFormat()
+ const { formatSpeedLimit, unitSystem } = useByteFormat()
const kiloByte = unitSystem === 'binary' ? 1024 : 1000
const { t } = useTranslation()
@@ -239,7 +239,7 @@ export function SpeedLimitSection({
const turtle = settings.turtle
const scheduleEnabled = settings.auto.schedule.enabled
const adaptiveEnabled = settings.auto.adaptive.enabled
- const summary = effectSummary(settings, t, formatSpeed)
+ const summary = effectSummary(settings, t, formatSpeedLimit)
const kbLimitRow = (
name: KbLimitName,
diff --git a/src/server/index.ts b/src/server/index.ts
index 7ce4dffc..32de2c2d 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -312,6 +312,11 @@ async function main() {
defaultSaveDir: configuredDefaultSaveDir,
onChange: (old, updated) => {
eventBus.emit(Events.SettingsChanged, { old, updated })
+ if (old.app.liquidGlassEffect !== updated.app.liquidGlassEffect) {
+ eventBus.emit(Events.LiquidGlassChanged, {
+ liquidGlassEffect: updated.app.liquidGlassEffect,
+ })
+ }
if (old.app.byteUnitSystem !== updated.app.byteUnitSystem) {
eventBus.emit(Events.ByteUnitSystemChanged, {
byteUnitSystem: updated.app.byteUnitSystem,
@@ -643,7 +648,9 @@ async function main() {
protocol,
engineSettings.rpcSecret
)
- const adapter = new Aria2Adapter(rpcClient)
+ const adapter = new Aria2Adapter(rpcClient, undefined, () =>
+ settingsManager.getEngine()
+ )
shutdownActions.unsubscribeProducers = () => {
let firstError: unknown
for (const unsubscribe of pollingNotificationUnsubscribers.splice(0)) {
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index be6c4c39..e037611a 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -844,6 +844,42 @@ describe('server Commands.CreateTask magnet metadata selection', () => {
})
describe('server plural task commands', () => {
+ it('MoveTasks validates the payload and changes the actual engine queue', async () => {
+ const ctx = makeFakeCtx()
+ const queue = ['first', 'second']
+ vi.mocked(ctx.taskManager.getById).mockReturnValue({
+ id: 'task-second',
+ engineTaskId: 'second',
+ status: TaskStatus.Paused,
+ } as never)
+ Object.assign(ctx.adapter, {
+ listWaitingTaskIds: vi.fn(async () => [...queue]),
+ changePosition: vi.fn(async () => {
+ queue.reverse()
+ return 0
+ }),
+ })
+ const handlers = buildServerCommandHandlers(
+ ctx as Parameters<typeof buildServerCommandHandlers>[0]
+ )
+ await expect(
+ handlers[Commands.MoveTasks]?.({
+ taskIds: ['task-second'],
+ direction: 'up',
+ })
+ ).resolves.toEqual({ moved: ['task-second'], unchanged: [], failed: [] })
+ expect(queue).toEqual(['second', 'first'])
+ await expect(
+ handlers[Commands.MoveTasks]?.({ taskIds: [], direction: 'up' })
+ ).rejects.toThrow()
+ await expect(
+ handlers[Commands.MoveTasks]?.({
+ taskIds: ['task-second'],
+ direction: 'sideways',
+ })
+ ).rejects.toThrow()
+ })
+
it('PauseTasks fans out per id and returns the IPC-safe bulk result', async () => {
const ctx = makeFakeCtx()
const tasks = new Map([
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 33bb5659..c05273ea 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -38,6 +38,7 @@ import {
stopSeedingTask,
toBulkTaskCommandResult,
} from '@core/task/actions'
+import { moveTasks } from '@core/task/actions/move-tasks'
import type {
TaskActionDeps,
TaskTransitionRecordInput,
@@ -72,6 +73,7 @@ import {
taskIdsPayloadSchema,
} from '@shared/schemas/bulk-task-command'
import { supportedLocaleSchema } from '@shared/schemas/locale'
+import { moveTasksPayloadSchema } from '@shared/schemas/move-tasks'
import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'
import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'
import { EngineRecoveryAction } from '@shared/types/engine'
@@ -555,6 +557,9 @@ export function buildServerCommandHandlers(
// Plural task commands (option C): one IPC request per multi-select
// action from the web renderer. Same handlers as desktop.
+ [Commands.MoveTasks]: async (rawPayload: unknown) =>
+ moveTasks(moveTasksPayloadSchema.parse(rawPayload), pauseResumeDeps),
+
[Commands.PauseTasks]: async (rawPayload: unknown) => {
const taskIds = taskIdsPayloadSchema.parse(rawPayload)
return toBulkTaskCommandResult(
diff --git a/src/shared/commands-catalog.ts b/src/shared/commands-catalog.ts
index 6d69e6fc..29f493df 100644
--- a/src/shared/commands-catalog.ts
+++ b/src/shared/commands-catalog.ts
@@ -24,6 +24,7 @@ export const CommandIds = {
TaskMoveDown: 'motrix.task.moveDown',
TaskPauseAll: 'motrix.task.pauseAll',
TaskResumeAll: 'motrix.task.resumeAll',
+ TaskSelectAll: 'motrix.task.selectAll',
TaskClearStopped: 'motrix.task.clearStopped',
// Navigation
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 936d1a57..7dfdcca1 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -7,6 +7,7 @@ export enum ErrorCode {
TaskCreateFailed = 'TASK_CREATE_FAILED',
TaskNotFound = 'TASK_NOT_FOUND',
TaskRevealFailed = 'TASK_REVEAL_FAILED',
+ TaskOpenFailed = 'TASK_OPEN_FAILED',
TaskNotRetryable = 'TASK_NOT_RETRYABLE',
SessionRestoreFailed = 'SESSION_RESTORE_FAILED',
SettingsInvalid = 'SETTINGS_INVALID',
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 2b59fe02..c3af4c1b 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -499,7 +499,23 @@
"up": "↑",
"eta": "ETA",
"connections": "Peers",
- "status": "Status"
+ "status": "Status",
+ "createdAt": "Date created",
+ "finishedAt": "Date completed"
+ },
+ "timestamp": {
+ "notRecorded": "Not recorded",
+ "notCompleted": "Not completed yet",
+ "relativeDateTime": "{{date}}, {{time}}"
+ },
+ "sort": {
+ "down": "Download speed",
+ "up": "Upload speed",
+ "asc": "{{column}}: ascending",
+ "desc": "{{column}}: descending",
+ "sortAscending": "Sort {{column}} ascending",
+ "sortDescending": "Sort {{column}} descending",
+ "reset": "Restore default order"
},
"empty": {
"noTasks": "No downloads yet",
@@ -524,9 +540,8 @@
}
},
"stats": {
- "downSpeed": "↓",
- "upSpeed": "↑",
- "counts": "Active {{active}} · Completed {{completed}} · Error {{error}}",
+ "downSpeed": "Download speed",
+ "upSpeed": "Upload speed",
"engineOk": "Engine ready",
"engineStarting": "Engine starting",
"engineOffline": "Engine offline",
@@ -568,7 +583,11 @@
"type": "Type",
"infoHash": "Info hash",
"private": "Private",
- "connections": "Connections"
+ "connections": "Connections",
+ "uploaded": "Uploaded",
+ "seedingTime": "Seeding time",
+ "seedingRecordedSince": "Recorded since {{date}}. Paused and offline time is excluded; earlier seeding history is unavailable.",
+ "seedingUnavailable": "Seeding time has not been recorded for this task."
},
"activity": {
"transferTitle": {
@@ -731,10 +750,22 @@
},
"action": {
"pause": "Pause",
+ "queueMoveFailed": "Could not update the waiting queue.",
+ "queueTaskStarted": "The task is no longer in the waiting queue.",
+ "queueMoveHint": "Queue position determines which waiting download starts next. Column sorting is saved separately.",
+ "queueBoundary": "Selection is already at the queue boundary",
+ "queueMoved": "Waiting queue updated",
+ "moveQueueDown": "Move Down in Queue",
+ "moveQueueUp": "Move Up in Queue",
"resume": "Resume",
"retry": "Retry",
"openFolder": "Open folder",
"copyUrl": "Copy URL",
+ "copyUrls": "Copy URLs",
+ "copyPath": "Copy file path",
+ "copied": "Copied to clipboard",
+ "copyFailed": "Could not copy to clipboard. Try again.",
+ "selectFilesFailed": "Could not open file selection.",
"copyUrlFailed": "Copy failed: could not load the task’s link details. Try again.",
"selectFiles": "Select files",
"remove": "Remove",
@@ -760,7 +791,15 @@
"removeAll_completed_Title": "Remove {{count}} completed tasks?",
"removeAll_error_Title": "Remove {{count}} failed tasks?",
"removeAll_downloading_Title": "Remove {{count}} active tasks?",
- "removeMixedTitle": "Remove {{count}} tasks?"
+ "removeMixedTitle": "Remove {{count}} tasks?",
+ "openFile": "Open file",
+ "openFileFailed": "Could not open file",
+ "chooseFiles": "Choose files…",
+ "queueOrder": "Download order",
+ "moveQueueTop": "Move to Front",
+ "moveQueueBottom": "Move to Back",
+ "copyError": "Copy error information",
+ "errorReport": "{{name}}\nTask ID: {{id}}\n{{details}}"
},
"titleCount": "{{shown}} shown · {{total}} total",
"type": {
@@ -772,6 +811,11 @@
},
"search": {
"placeholder": "Search downloads",
+ "activeTypeFilters": "Type filter: {{types}}",
+ "filters": "Filters",
+ "resetFilters": "Reset filters",
+ "clearQuery": "Clear search",
+ "activeQuery": "Search: {{query}}",
"scopeLabel": "Type",
"clear": "Clear",
"empty": "No matching tasks",
@@ -779,6 +823,28 @@
},
"stale": {
"banner": "Task list may be out of date — reconnecting…"
+ },
+ "view": {
+ "title": "List View",
+ "columns": "Columns",
+ "resetColumns": "Restore Default Columns",
+ "sortBy": "Sort By",
+ "ascending": "Ascending",
+ "descending": "Descending",
+ "showInspector": "Show Inspector",
+ "hideInspector": "Hide Inspector",
+ "inspector": "Task Inspector",
+ "resizeInspector": "Resize Inspector",
+ "selectToInspect": "Select a task to view its details.",
+ "resizeColumn": "Resize {{column}} column",
+ "taskActions": "More"
+ },
+ "speedLimit": {
+ "title": "Speed mode",
+ "currentMode": "Speed mode: {{mode}}",
+ "uploadLimit": "Upload limit: {{speed}}",
+ "downloadLimit": "Download limit: {{speed}}",
+ "saveFailed": "Couldn’t change the speed mode. Try again."
}
}
},
@@ -997,7 +1063,8 @@
"reduceMotion": "Reduce motion",
"reduceMotionDesc": "Reduce interface animations, including the glass motion effects on the Downloads page.",
"liquidGlassEffect": "Enable Liquid Glass effect",
- "liquidGlassEffectDesc": "macOS 26 App only — recreates the main window when changed.",
+ "liquidGlassEffectDesc": "Use translucent glass for the Downloads toolbar.",
+ "liquidGlassEffectMacDesc": "Also uses native window glass on macOS 26+. Changing this recreates the main window.",
"runMode": "Show app in",
"runModeStandard": "Dock & Menu Bar",
"runModeTray": "Menu Bar Only",
@@ -1171,7 +1238,7 @@
"seedRatio": "Seed ratio limit",
"seedRatioDesc": "Stop seeding above this ratio. 0 = unlimited.",
"seedTime": "Seed time limit (minutes)",
- "seedTimeDesc": "Stop seeding after this many minutes. 0 = unlimited."
+ "seedTimeDesc": "Stop seeding after this many minutes. 0 = unlimited. Applies to new and re-seeded tasks."
}
},
"downloads": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 0e89e0a2..52d78784 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -497,7 +497,23 @@
"up": "↑",
"eta": "剩余",
"connections": "连接",
- "status": "状态"
+ "status": "状态",
+ "createdAt": "创建时间",
+ "finishedAt": "完成时间"
+ },
+ "timestamp": {
+ "notRecorded": "未记录",
+ "notCompleted": "尚未完成",
+ "relativeDateTime": "{{date}} {{time}}"
+ },
+ "sort": {
+ "down": "下载速度",
+ "up": "上传速度",
+ "asc": "{{column}}:升序",
+ "desc": "{{column}}:降序",
+ "sortAscending": "按{{column}}升序排列",
+ "sortDescending": "按{{column}}降序排列",
+ "reset": "恢复默认顺序"
},
"empty": {
"noTasks": "暂无下载任务",
@@ -522,9 +538,8 @@
}
},
"stats": {
- "downSpeed": "↓",
- "upSpeed": "↑",
- "counts": "活动 {{active}} · 已完成 {{completed}} · 错误 {{error}}",
+ "downSpeed": "下载速度",
+ "upSpeed": "上传速度",
"engineOk": "引擎就绪",
"engineStarting": "引擎启动中",
"engineOffline": "引擎离线",
@@ -566,7 +581,11 @@
"type": "类型",
"infoHash": "InfoHash",
"private": "Private",
- "connections": "连接"
+ "connections": "连接",
+ "uploaded": "累计上传",
+ "seedingTime": "做种时长",
+ "seedingRecordedSince": "自 {{date}} 起记录。不计暂停和离线时间;此前的做种记录不可用。",
+ "seedingUnavailable": "此任务尚无做种时长记录。"
},
"activity": {
"transferTitle": {
@@ -720,10 +739,22 @@
},
"action": {
"pause": "暂停",
+ "queueMoveFailed": "无法调整等待队列。",
+ "queueTaskStarted": "任务已不在等待队列中。",
+ "queueMoveHint": "队列位置决定等待任务的启动顺序,列排序单独保存。",
+ "queueBoundary": "所选任务已到达队列边界",
+ "queueMoved": "已调整等待队列",
+ "moveQueueDown": "在队列中下移",
+ "moveQueueUp": "在队列中上移",
"resume": "继续",
"retry": "重试",
"openFolder": "打开文件夹",
"copyUrl": "复制链接",
+ "copyUrls": "复制多个链接",
+ "copyPath": "复制文件路径",
+ "copied": "已复制到剪贴板",
+ "copyFailed": "无法复制到剪贴板,请重试。",
+ "selectFilesFailed": "无法打开文件选择。",
"copyUrlFailed": "复制失败:无法加载任务链接详情,请重试。",
"selectFiles": "选择文件",
"remove": "移除…",
@@ -749,7 +780,15 @@
"removeAll_completed_Title": "移除 {{count}} 个已完成任务?",
"removeAll_error_Title": "移除 {{count}} 个失败任务?",
"removeAll_downloading_Title": "移除 {{count}} 个进行中任务?",
- "removeMixedTitle": "移除 {{count}} 个任务?"
+ "removeMixedTitle": "移除 {{count}} 个任务?",
+ "openFile": "打开文件",
+ "openFileFailed": "无法打开文件",
+ "chooseFiles": "选择下载文件…",
+ "queueOrder": "调整下载顺序",
+ "moveQueueTop": "移至队列最前",
+ "moveQueueBottom": "移至队列最后",
+ "copyError": "复制错误信息",
+ "errorReport": "{{name}}\n任务 ID:{{id}}\n{{details}}"
},
"titleCount": "{{shown}} 项 · 共 {{total}}",
"type": {
@@ -761,6 +800,11 @@
},
"search": {
"placeholder": "搜索下载任务",
+ "activeTypeFilters": "类型筛选:{{types}}",
+ "filters": "筛选",
+ "resetFilters": "重置筛选",
+ "clearQuery": "清除搜索",
+ "activeQuery": "搜索:{{query}}",
"scopeLabel": "类型",
"clear": "清除",
"empty": "无匹配任务",
@@ -768,6 +812,28 @@
},
"stale": {
"banner": "任务列表可能已过期,正在重新连接…"
+ },
+ "view": {
+ "title": "列表显示",
+ "columns": "显示列",
+ "resetColumns": "恢复默认列布局",
+ "sortBy": "排序方式",
+ "ascending": "升序",
+ "descending": "降序",
+ "showInspector": "显示详情",
+ "hideInspector": "隐藏详情",
+ "inspector": "任务详情",
+ "resizeInspector": "调整详情高度",
+ "selectToInspect": "选择任务以查看详情。",
+ "resizeColumn": "调整{{column}}列宽",
+ "taskActions": "更多"
+ },
+ "speedLimit": {
+ "title": "速度模式",
+ "currentMode": "速度模式:{{mode}}",
+ "uploadLimit": "上传上限:{{speed}}",
+ "downloadLimit": "下载上限:{{speed}}",
+ "saveFailed": "无法切换速度模式,请重试。"
}
}
},
@@ -984,7 +1050,8 @@
"reduceMotion": "减少动画",
"reduceMotionDesc": "减少界面动画,包括下载页的玻璃动态效果。",
"liquidGlassEffect": "启用液态玻璃效果",
- "liquidGlassEffectDesc": "仅 macOS 26 App — 更改后会重建主窗口。",
+ "liquidGlassEffectDesc": "为下载页工具栏使用半透明玻璃效果。",
+ "liquidGlassEffectMacDesc": "macOS 26 及以上同时使用原生窗口玻璃,更改后会重建主窗口。",
"runMode": "显示位置",
"runModeStandard": "程序坞与菜单栏",
"runModeTray": "仅菜单栏",
@@ -1158,7 +1225,7 @@
"seedRatio": "做种比率上限",
"seedRatioDesc": "超过此比率停止做种。0 = 无限制。",
"seedTime": "做种时间上限(分钟)",
- "seedTimeDesc": "做种超过该分钟数后停止。0 = 无限制。"
+ "seedTimeDesc": "做种达到该分钟数后停止。0 = 无限制。应用于新建或重新做种的任务。"
}
},
"downloads": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index c75d2017..ffdfc09d 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -497,7 +497,23 @@
"up": "↑",
"eta": "預估剩餘時間",
"connections": "對等節點",
- "status": "狀態"
+ "status": "狀態",
+ "createdAt": "建立時間",
+ "finishedAt": "完成時間"
+ },
+ "timestamp": {
+ "notRecorded": "未記錄",
+ "notCompleted": "尚未完成",
+ "relativeDateTime": "{{date}} {{time}}"
+ },
+ "sort": {
+ "down": "下載速度",
+ "up": "上傳速度",
+ "asc": "{{column}}:遞增",
+ "desc": "{{column}}:遞減",
+ "sortAscending": "依{{column}}遞增排序",
+ "sortDescending": "依{{column}}遞減排序",
+ "reset": "恢復預設順序"
},
"empty": {
"noTasks": "尚無下載任務",
@@ -522,9 +538,8 @@
}
},
"stats": {
- "downSpeed": "↓",
- "upSpeed": "↑",
- "counts": "進行中 {{active}} · 已完成 {{completed}} · 錯誤 {{error}}",
+ "downSpeed": "下載速度",
+ "upSpeed": "上傳速度",
"engineOk": "引擎已就緒",
"engineStarting": "引擎啟動中",
"engineOffline": "引擎離線",
@@ -566,7 +581,11 @@
"type": "類型",
"infoHash": "資訊雜湊",
"private": "私人",
- "connections": "連線數"
+ "connections": "連線數",
+ "uploaded": "累計上傳",
+ "seedingTime": "做種時長",
+ "seedingRecordedSince": "自 {{date}} 起記錄。不計暫停及離線時間;此前的做種記錄無法取得。",
+ "seedingUnavailable": "此任務尚無做種時長記錄。"
},
"activity": {
"transferTitle": {
@@ -720,10 +739,22 @@
},
"action": {
"pause": "暫停",
+ "queueMoveFailed": "無法調整等待佇列。",
+ "queueTaskStarted": "任務已不在等待佇列中。",
+ "queueMoveHint": "佇列位置決定等待任務的啟動順序,欄位排序另行儲存。",
+ "queueBoundary": "所選任務已到達佇列邊界",
+ "queueMoved": "已調整等待佇列",
+ "moveQueueDown": "在佇列中下移",
+ "moveQueueUp": "在佇列中上移",
"resume": "繼續",
"retry": "重試",
"openFolder": "開啟資料夾",
"copyUrl": "複製 URL",
+ "copyUrls": "複製多個連結",
+ "copyPath": "複製檔案路徑",
+ "copied": "已複製到剪貼簿",
+ "copyFailed": "無法複製到剪貼簿,請重試。",
+ "selectFilesFailed": "無法開啟檔案選擇。",
"copyUrlFailed": "複製失敗:無法載入任務的連結詳細資料。請再試一次。",
"selectFiles": "選擇檔案",
"remove": "移除",
@@ -749,7 +780,15 @@
"removeAll_completed_Title": "要移除 {{count}} 個已完成的任務嗎?",
"removeAll_error_Title": "要移除 {{count}} 個失敗的任務嗎?",
"removeAll_downloading_Title": "要移除 {{count}} 個進行中的任務嗎?",
- "removeMixedTitle": "要移除 {{count}} 個任務嗎?"
+ "removeMixedTitle": "要移除 {{count}} 個任務嗎?",
+ "openFile": "開啟檔案",
+ "openFileFailed": "無法開啟檔案",
+ "chooseFiles": "選擇下載檔案…",
+ "queueOrder": "調整下載順序",
+ "moveQueueTop": "移至佇列最前",
+ "moveQueueBottom": "移至佇列最後",
+ "copyError": "複製錯誤資訊",
+ "errorReport": "{{name}}\n任務 ID:{{id}}\n{{details}}"
},
"titleCount": "顯示 {{shown}} 項 · 共 {{total}} 項",
"type": {
@@ -761,6 +800,11 @@
},
"search": {
"placeholder": "搜尋下載項目",
+ "activeTypeFilters": "類型篩選:{{types}}",
+ "filters": "篩選",
+ "resetFilters": "重設篩選",
+ "clearQuery": "清除搜尋",
+ "activeQuery": "搜尋:{{query}}",
"scopeLabel": "類型",
"clear": "清除",
"empty": "沒有符合的任務",
@@ -768,6 +812,28 @@
},
"stale": {
"banner": "任務清單可能不是最新的,正在重新連線…"
+ },
+ "view": {
+ "title": "列表顯示",
+ "columns": "顯示欄",
+ "resetColumns": "回復預設欄配置",
+ "sortBy": "排序方式",
+ "ascending": "升冪",
+ "descending": "降冪",
+ "showInspector": "顯示詳細資訊",
+ "hideInspector": "隱藏詳細資訊",
+ "inspector": "任務詳細資訊",
+ "resizeInspector": "調整詳細資訊高度",
+ "selectToInspect": "選擇任務以查看詳細資訊。",
+ "resizeColumn": "調整{{column}}欄寬",
+ "taskActions": "更多"
+ },
+ "speedLimit": {
+ "title": "速度模式",
+ "currentMode": "速度模式:{{mode}}",
+ "uploadLimit": "上傳上限:{{speed}}",
+ "downloadLimit": "下載上限:{{speed}}",
+ "saveFailed": "無法切換速度模式,請重試。"
}
}
},
@@ -984,7 +1050,8 @@
"reduceMotion": "減少動畫",
"reduceMotionDesc": "減少介面動畫,包括下載頁的玻璃動態效果。",
"liquidGlassEffect": "啟用液態玻璃效果",
- "liquidGlassEffectDesc": "僅限 macOS 26 App,變更後會重新建立主視窗。",
+ "liquidGlassEffectDesc": "為下載頁工具列使用半透明玻璃效果。",
+ "liquidGlassEffectMacDesc": "macOS 26 及以上同時使用原生視窗玻璃,變更後會重新建立主視窗。",
"runMode": "顯示位置",
"runModeStandard": "Dock 與選單列",
"runModeTray": "僅選單列",
@@ -1158,7 +1225,7 @@
"seedRatio": "分享率上限",
"seedRatioDesc": "分享率超過此值後停止做種。0 = 無限制。",
"seedTime": "做種時間上限 (分鐘)",
- "seedTimeDesc": "做種達此分鐘數後停止。0 = 無限制。"
+ "seedTimeDesc": "做種達到此分鐘數後停止。0 = 無限制。套用於新建或重新做種的任務。"
}
},
"downloads": {
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 49c2caa2..cd94b609 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -10,6 +10,7 @@ export const Commands = {
// CLI keep driving the singular task/* wire methods.
PauseTasks: 'command:pauseTasks',
ResumeTasks: 'command:resumeTasks',
+ MoveTasks: 'command:moveTasks',
RemoveTasks: 'command:removeTasks',
ReAddTasks: 'command:reAddTasks',
// Generic user Retry. Shell handlers route sidecar-backed torrents to
@@ -88,6 +89,7 @@ export const Commands = {
ConfigureAppImageNativeHost: 'command:configureAppImageNativeHost',
RemoveAppImageIntegration: 'command:removeAppImageIntegration',
RevealInFolder: 'command:revealInFolder',
+ OpenTaskFile: 'command:openTaskFile',
// Menu
UpdateMenuContext: 'command:updateMenuContext',
ExecuteApplicationMenuItem: 'command:executeApplicationMenuItem',
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index 70abaaac..1dae1385 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -37,6 +37,8 @@ export const Events = {
SettingsChanged: 'event:settingsChanged',
// Payload: { reduceMotion: boolean }. Full settings remain host-internal.
ReducedMotionChanged: 'event:reducedMotionChanged',
+ // Payload: { liquidGlassEffect: boolean }.
+ LiquidGlassChanged: 'event:liquidGlassChanged',
// Payload: { byteUnitSystem: ByteUnitPreference }.
ByteUnitSystemChanged: 'event:byteUnitSystemChanged',
LocaleChanged: 'event:localeChanged',
@@ -112,6 +114,9 @@ export const Events = {
// resulting durable NotificationAdded event is what reaches renderers.
EngineCompatibilityWarning: 'event:engineCompatibilityWarning',
ApplicationMenuChanged: 'event:applicationMenuChanged',
+ // No payload; only the main window's current Downloads list handles this.
+ // Sent directly by the desktop shell, never through the core event bus.
+ TaskSelectAll: 'event:taskSelectAll',
// Renderer-local shell state. Electron sends this directly to the owning
// BrowserWindow instead of broadcasting it through the core event bus.
WindowMaximizedChanged: 'event:windowMaximizedChanged',
diff --git a/src/shared/protocol/forwardable-events.test.ts b/src/shared/protocol/forwardable-events.test.ts
index a28c0bbe..13fed243 100644
--- a/src/shared/protocol/forwardable-events.test.ts
+++ b/src/shared/protocol/forwardable-events.test.ts
@@ -6,6 +6,7 @@ import { ForwardableEvents } from './forwardable-events'
describe('ForwardableEvents', () => {
it('forwards the motion preference without exposing the full settings event', () => {
expect(ForwardableEvents).toContain(Events.ReducedMotionChanged)
+ expect(ForwardableEvents).toContain(Events.LiquidGlassChanged)
expect(ForwardableEvents).toContain(Events.ByteUnitSystemChanged)
expect(ForwardableEvents).not.toContain(Events.SettingsChanged)
})
@@ -23,7 +24,7 @@ describe('ForwardableEvents', () => {
})
it('has the expected number of forwardable events', () => {
- expect(ForwardableEvents).toHaveLength(54)
+ expect(ForwardableEvents).toHaveLength(55)
})
it('includes the bridge approval events (web-shell pairing)', () => {
diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.ts
index 3766a3ca..b5f24669 100644
--- a/src/shared/protocol/forwardable-events.ts
+++ b/src/shared/protocol/forwardable-events.ts
@@ -42,6 +42,7 @@ export const ForwardableEvents = [
Events.GeoIPStatusChanged,
Events.LocaleChanged,
Events.ReducedMotionChanged,
+ Events.LiquidGlassChanged,
Events.ByteUnitSystemChanged,
Events.PluginConfigChanged,
Events.PluginGrantsChanged,
diff --git a/src/shared/schemas/move-tasks.ts b/src/shared/schemas/move-tasks.ts
new file mode 100644
index 00000000..5ccd20ab
--- /dev/null
+++ b/src/shared/schemas/move-tasks.ts
@@ -0,0 +1,14 @@
+import { z } from 'zod'
+
+export const moveTasksPayloadSchema = z.object({
+ taskIds: z.array(z.string().min(1)).min(1).max(1000),
+ direction: z.enum(['up', 'down', 'top', 'bottom']),
+})
+export type MoveTasksPayload = z.infer<typeof moveTasksPayloadSchema>
+
+export const moveTasksResultSchema = z.object({
+ moved: z.array(z.string()),
+ unchanged: z.array(z.string()),
+ failed: z.array(z.object({ taskId: z.string(), reason: z.string() })),
+})
+export type MoveTasksResult = z.infer<typeof moveTasksResultSchema>
diff --git a/src/shared/schemas/open-task-file.ts b/src/shared/schemas/open-task-file.ts
new file mode 100644
index 00000000..7aa8a23d
--- /dev/null
+++ b/src/shared/schemas/open-task-file.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod'
+
+export const openTaskFilePayloadSchema = z.object({
+ taskId: z.string().trim().min(1),
+})
diff --git a/src/shared/schemas/speed-limit.test.ts b/src/shared/schemas/speed-limit.test.ts
index 90880251..7b632739 100644
--- a/src/shared/schemas/speed-limit.test.ts
+++ b/src/shared/schemas/speed-limit.test.ts
@@ -1,10 +1,31 @@
import { describe, expect, it } from 'vitest'
import {
+ createDefaultSpeedLimitSettings,
DEFAULT_SPEED_LIMIT_SETTINGS,
speedLimitSettingsSchema,
} from './speed-limit'
describe('speedLimitSettingsSchema', () => {
+ it.each([
+ ['decimal', 64_000, 512_000],
+ ['binary', 65_536, 524_288],
+ ] as const)(
+ 'creates integer presets in %s display units',
+ (units, upload, download) => {
+ const settings = createDefaultSpeedLimitSettings(units)
+ expect(settings.alt).toEqual({ upload, download })
+ expect(settings.base).toEqual({ upload: 0, download: 0 })
+ expect(settings.turtle).toBe('off')
+ expect(settings.auto.schedule.enabled).toBe(false)
+ expect(settings.auto.adaptive.enabled).toBe(false)
+ settings.auto.schedule.days.push(1)
+ expect(createDefaultSpeedLimitSettings(units).auto.schedule.days).toEqual(
+ []
+ )
+ expect(DEFAULT_SPEED_LIMIT_SETTINGS.auto.schedule.days).toEqual([])
+ }
+ )
+
it('DEFAULT_SPEED_LIMIT_SETTINGS has correct baseline values', () => {
expect(DEFAULT_SPEED_LIMIT_SETTINGS.turtle).toBe('off')
expect(DEFAULT_SPEED_LIMIT_SETTINGS.base).toEqual({
diff --git a/src/shared/schemas/speed-limit.ts b/src/shared/schemas/speed-limit.ts
index 3c1690a1..cd8a6f28 100644
--- a/src/shared/schemas/speed-limit.ts
+++ b/src/shared/schemas/speed-limit.ts
@@ -3,6 +3,7 @@ import type {
SpeedTestProvider,
} from '@shared/types/settings'
import { z } from 'zod'
+import type { ByteUnitSystem } from './byte-unit-system'
import { settingsInputObject } from './settings-input'
const byteRateSchema = z.number().min(0).max(Number.MAX_SAFE_INTEGER)
@@ -102,3 +103,15 @@ export const speedLimitSettingsInputSchema = settingsInputObject(
export const DEFAULT_SPEED_LIMIT_SETTINGS: SpeedLimitSettings =
speedLimitSettingsSchema.parse({})
+
+/** First-run presets follow display units; persisted values retain their bytes. */
+export function createDefaultSpeedLimitSettings(
+ unitSystem: ByteUnitSystem
+): SpeedLimitSettings {
+ const kiloByte = unitSystem === 'binary' ? 1024 : 1000
+ return structuredClone(
+ speedLimitSettingsSchema.parse({
+ alt: { upload: 64 * kiloByte, download: 512 * kiloByte },
+ })
+ )
+}
diff --git a/src/shared/schemas/task-inspector-activity.test.ts b/src/shared/schemas/task-inspector-activity.test.ts
index 4b8213ba..980c9f69 100644
--- a/src/shared/schemas/task-inspector-activity.test.ts
+++ b/src/shared/schemas/task-inspector-activity.test.ts
@@ -252,3 +252,16 @@ describe('task inspector activity wire validation', () => {
).toBeNull()
})
})
+
+it('accepts additive seeding statistics and rejects invalid counters', () => {
+ const value = snapshot()
+ expect(parseTaskInspectorActivitySnapshot(value, 'task-1')).not.toBeNull()
+ value.summary.seeding = { activeMs: 1000, trackingStartedAt: 1 }
+ expect(
+ parseTaskInspectorActivitySnapshot(value, 'task-1')?.summary.seeding
+ ).toEqual(value.summary.seeding)
+ for (const activeMs of [-1, Number.NaN, Number.POSITIVE_INFINITY, 0.5]) {
+ value.summary.seeding.activeMs = activeMs
+ expect(parseTaskInspectorActivitySnapshot(value, 'task-1')).toBeNull()
+ }
+})
diff --git a/src/shared/schemas/task-inspector-activity.ts b/src/shared/schemas/task-inspector-activity.ts
index 8ff238b0..07e1045d 100644
--- a/src/shared/schemas/task-inspector-activity.ts
+++ b/src/shared/schemas/task-inspector-activity.ts
@@ -210,6 +210,14 @@ const taskInspectorActivitySnapshotSchema = z
lastEventOrdinal: nonNegativeSafeIntegerSchema,
activeMs: nonNegativeSafeIntegerSchema,
downloadActiveMs: nonNegativeSafeIntegerSchema,
+ seeding: z
+ .object({
+ activeMs: nonNegativeSafeIntegerSchema,
+ trackingStartedAt: positiveSafeIntegerSchema,
+ })
+ .strict()
+ .nullable()
+ .optional(),
estimatedDownloadBytes: serializedByteCountSchema,
estimatedUploadBytes: serializedByteCountSchema,
peakDownloadBps: nonNegativeSafeIntegerSchema,
diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.ts
index c2644e29..e65abf6b 100644
--- a/src/shared/types/task-actions.ts
+++ b/src/shared/types/task-actions.ts
@@ -74,6 +74,37 @@ export function canResume(t: DownloadTask): boolean {
return t.status === TaskStatus.Paused
}
+/** A completed task whose published output is a single file. */
+export function canOpenTaskFile(t: DownloadTask): boolean {
+ return (
+ t.status === TaskStatus.Completed &&
+ t.fileCount === 1 &&
+ Boolean(t.finalPath || t.diskPath)
+ )
+}
+
+/** Live multi-file downloads that accept a changed file selection. */
+export function canSelectTaskFiles(t: DownloadTask): boolean {
+ return (
+ Boolean(t.engineTaskId) &&
+ t.fileCount > 1 &&
+ (isTorrentLike(t) || t.type === TaskType.Metalink) &&
+ (t.status === TaskStatus.Queued ||
+ t.status === TaskStatus.Downloading ||
+ t.status === TaskStatus.Paused ||
+ t.status === TaskStatus.Seeding)
+ )
+}
+
+/** Waiting queue only; coordinator-managed tasks have no single queue slot. */
+export function canMoveInQueue(t: DownloadTask): boolean {
+ return (
+ Boolean(t.engineTaskId) &&
+ !isMediaKind(t.kind) &&
+ (t.status === TaskStatus.Queued || t.status === TaskStatus.Paused)
+ )
+}
+
export function canStopSeeding(t: DownloadTask): boolean {
return t.status === TaskStatus.Seeding
}
diff --git a/src/shared/types/task-inspector-activity.ts b/src/shared/types/task-inspector-activity.ts
index 9b780aca..5c7e8bfa 100644
--- a/src/shared/types/task-inspector-activity.ts
+++ b/src/shared/types/task-inspector-activity.ts
@@ -70,6 +70,8 @@ export interface TaskInspectorActivitySummary {
lastEventOrdinal: number
activeMs: number
downloadActiveMs: number
+ /** Absent on older hosts, null when historical seeding was never observed. */
+ seeding?: { activeMs: number; trackingStartedAt: number } | null
estimatedDownloadBytes: SerializedByteCount
estimatedUploadBytes: SerializedByteCount
peakDownloadBps: number
@@ -117,6 +119,7 @@ export interface TaskActivityCheckpoint {
updatedAt: number
activeMsDelta: number
downloadActiveMsDelta: number
+ seedingMsDelta?: number
estimatedDownloadBytesDelta: bigint
estimatedUploadBytesDelta: bigint
peakDownloadBps: number
diff --git a/src/shared/utils/format-bytes.ts b/src/shared/utils/format-bytes.ts
index ad910696..ade34d83 100644
--- a/src/shared/utils/format-bytes.ts
+++ b/src/shared/utils/format-bytes.ts
@@ -75,3 +75,12 @@ export function formatSpeed(
): string {
return `${formatBytes(bytes, { unitSystem, decimals: 1 })}/s`
}
+
+/** Static caps omit trailing zeroes while live speeds retain a stable precision. */
+export function formatSpeedLimit(
+ bytes: ByteValue,
+ unitSystem = DEFAULT_BYTE_UNIT_SYSTEM
+): string {
+ const { number, unit } = formatByteParts(bytes, { unitSystem, decimals: 1 })
+ return `${number.replace(/\.0$/, '')} ${unit}/s`
+}
diff --git a/src/shared/utils/share-ratio.ts b/src/shared/utils/share-ratio.ts
new file mode 100644
index 00000000..d0df0929
--- /dev/null
+++ b/src/shared/utils/share-ratio.ts
@@ -0,0 +1,8 @@
+/** Share ratio against the task payload size, including upload from retired sessions. */
+export function shareRatio(uploadedBytes: number, totalBytes: number): number {
+ return totalBytes > 0 &&
+ Number.isFinite(totalBytes) &&
+ Number.isFinite(uploadedBytes)
+ ? Math.max(0, uploadedBytes) / totalBytes
+ : 0
+}